# Technical Documentation: CGAL/cgal

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/CGAL/cgal)

### Overview (README.md)

The Computational Geometry Algorithms Library (CGAL) is a C++ library that
aims to provide easy access to efficient and reliable algorithms in
computational geometry.

CGAL Releases
=============
The primary vector of distribution of CGAL are source tarballs, released
twice a year, announced on [the web site of CGAL](https://www.cgal.org/).

Getting Started with CGAL
=========================

**Since version 5.0, CGAL is a header-only library, meaning that
it is no longer needed to build CGAL libraries before it can be used.**

Head over to the [CGAL manual](https://doc.cgal.org/latest/Manual/general_intro.html)
for usage guides and tutorials that will get you started smoothly.

License
=======
See the file [LICENSE.md](LICENSE.md).

CGAL Git Repository Layout
==========================

The Git repository of CGAL has a different layout from release tarballs. It
contains a `CMakeLists.txt` file that serves as anchor for configuring and building programs,
and a set of subfolders, so called *packages*. Most packages
implement a data structure or an algorithm for CGAL (e.g., `Convex_hull_2`,
or `Triangulation_3`); however some packages serve special needs:

* `Installation` - meta-files and CMake-support
* `Maintenance` - infrastructural support
* `Core`, `CGALimageIO`, `Qt_widget`, `GraphicsView` - component libraries
* `Scripts` - scripts to simplify developer's and user's work
* `Testsuite` - infrastructure for testsuite
* `Documentation` - infrastructure for CGAL's manual
* `STL_Extension` - extensions to the standard template library

More Information
================
* [The CGAL web site](https://www.cgal.org/)
* [Documentation of the latest CGAL release](https://doc.cgal.org/)
* [Documentation of the CGAL `main` branch (updated weekly)](https://cgal.geometryfactory.com/CGAL/doc/master/)
* [CGAL daily testsuite results](https://cgal.geometryfactory.com/CGAL/testsuite/)
* [Guidelines for CGAL developers](https://github.com/CGAL/cgal/wiki/Guidelines) and [Information for new developers](https://github.com/CGAL/cgal/wiki/Information-for-New-Developers)

---

### Documentation Doc CMakeLists (`Documentation/doc/CMakeLists.txt`)

cmake_minimum_required(VERSION 3.12...3.31)
project(Documentation NONE)

# Check whether this cmake script is the top level one
if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR})
  # decide if this is a branch build
  if(NOT EXISTS "${CMAKE_SOURCE_DIR}/../VERSION")
    set(CGAL_BRANCH_BUILD
        ON
        CACHE INTERNAL "CGAL Branch build")
  endif()

  if(CGAL_BRANCH_BUILD)
    set(CGAL_ROOT "${CMAKE_SOURCE_DIR}/../..")
  else()
    set(CGAL_ROOT "${CMAKE_SOURCE_DIR}/..")
  endif()
  get_filename_component(CGAL_ROOT ${CGAL_ROOT} REALPATH)
else()
  option(BUILD_DOC "Build the doxygen documentation" OFF)
  if(NOT BUILD_DOC)
    return()
  endif()
  set(CGAL_ROOT "${CMAKE_SOURCE_DIR}")
endif()

cmake_minimum_required(VERSION 3.18...3.31) # for list(SORT ... COMPARE NATURAL)

find_package(Doxygen REQUIRED)
find_package(Python3 REQUIRED COMPONENTS Interpreter)

if (NOT Python3_EXECUTABLE)
  message(FATAL_ERROR "Cannot build the documentation without Python3!")
  return()
endif()

message(VERBOSE "Using Python version ${Python3_VERSION}: ${Python3_EXECUTABLE}")

if(NOT DOXYGEN_FOUND)
  message(WARNING "Cannot build the documentation without Doxygen!")
  return()
endif()

#starting from cmake 3.9 the usage of DOXYGEN_EXECUTABLE is deprecated
if(TARGET Doxygen::doxygen)
  get_property(
    DOXYGEN_EXECUTABLE
    TARGET Doxygen::doxygen
    PROPERTY IMPORTED_LOCATION)
endif()

macro(subdirlist result curdir)
  file(
    GLOB children
    RELATIVE ${curdir}
    ${curdir}/*)
  set(dirlist "")
  foreach(child ${children})
    if(IS_DIRECTORY ${curdir}/${child})
      set(dirlist ${dirlist} ${child})
    endif()
  endforeach()
  set(${result} ${dirlist})
endmacro()

function(configure_doxygen_package CGAL_PACKAGE_NAME)
  if(CGAL_BRANCH_BUILD)
    set(CGAL_PACKAGE_DIR ${CGAL_ROOT}/${CGAL_PACKAGE_NAME})
  else()
    set(CGAL_PACKAGE_DIR ${CGAL_ROOT})
  endif()

  set(CGAL_PACKAGE_DOC_DIR ${CGAL_PACKAGE_DIR}/doc/${CGAL_PACKAGE_NAME})
  set(CGAL_PACKAGE_INCLUDE_DIR ${CGAL_PACKAGE_DIR}/include/)

  if(NOT EXISTS ${CGAL_PACKAGE_DOC_DIR}/Doxyfile.in)
    return()
  endif()
  set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${CGAL_PACKAGE_DOC_DIR}/Doxyfile.in)

  set(CGAL_DOC_PACKAGE_DEFAULTS
      ${CGAL_DOC_DXY_DIR}/${CGAL_PACKAGE_NAME}_defaults.dxy)
  file(REMOVE ${CGAL_DOC_PACKAGE_DEFAULTS})
  file(APPEND ${CGAL_DOC_PACKAGE_DEFAULTS}
       "@INCLUDE = ${CGAL_DOC_DOXY_DEFAULT}\n")
  file(APPEND ${CGAL_DOC_PACKAGE_DEFAULTS}
       "OUTPUT_DIRECTORY = ${CGAL_DOC_OUTPUT_DIR}/${CGAL_PACKAGE_NAME}\n")
  file(APPEND ${CGAL_DOC_PACKAGE_DEFAULTS} "HTML_OUTPUT = .\n")

  if(CGAL_DOC_CREATE_LOGS)
    file(APPEND ${CGAL_DOC_PACKAGE_DEFAULTS}
         "WARN_LOGFILE = ${CGAL_DOC_LOG_DIR}/${CGAL_PACKAGE_NAME}.log\n")
  endif()

  if(CGAL_DOC_RELEASE)
    file(APPEND ${CGAL_DOC_PACKAGE_DEFAULTS} "GENERATE_TODOLIST = NO\n")
    file(APPEND ${CGAL_DOC_PACKAGE_DEFAULTS} "GENERATE_BUGLIST = NO\n")
  endif()

  if(EXISTS "${CGAL_PACKAGE_DIR}/examples")
    file(APPEND ${CGAL_DOC_PACKAGE_DEFAULTS}
         "EXAMPLE_PATH = ${CGAL_PACKAGE_DIR}/examples\n")
  endif()
  if(CGAL_GENERATE_XML)
    file(APPEND ${CGAL_DOC_PACKAGE_DEFAULTS} "GENERATE_XML = YES\n")
  endif()

  file(APPEND ${CGAL_DOC_PACKAGE_DEFAULTS}
       "GENERATE_TAGFILE = ${CGAL_DOC_TAG_GEN_DIR}/${CGAL_PACKAGE_NAME}.tag\n")
  file(APPEND ${CGAL_DOC_PACKAGE_DEFAULTS}
       "STRIP_FROM_PATH = ${CGAL_PACKAGE_DOC_DIR}/\n")
  file(APPEND ${CGAL_DOC_PACKAGE_DEFAULTS}
       "STRIP_FROM_PATH += ${CGAL_PACKAGE_DIR}/include/\n")
  file(APPEND ${CGAL_DOC_PACKAGE_DEFAULTS}
       "STRIP_FROM_INC_PATH = ${CGAL_PACKAGE_DOC_DIR}/\n")
  file(APPEND ${CGAL_DOC_PACKAGE_DEFAULTS}
       "STRIP_FROM_INC_PATH += ${CGAL_PACKAGE_DIR}/include/\n")
  file(APPEND ${CGAL_DOC_PACKAGE_DEFAULTS}
       "ALIASES += \"cgalPkgDescriptionBegin{2}=\\details \"\n")
  file(
    APPEND ${CGAL_DOC_PACKAGE_DEFAULTS}
    "ALIASES += \"cgalPkgManuals{2}=<div class=\\\"PkgManuals\\\"></div>\"\n")
  file(APPEND ${CGAL_DOC_PACKAGE_DEFAULTS} "INPUT = ${CGAL_PACKAGE_DOC_DIR}\n")

  #special cases for Stream_support and Documentation package: stream support also needs include/CGAL while Documentation
  if((NOT EXISTS "${CGAL_PACKAGE_DOC_DIR}/CGAL" AND (NOT ${CGAL_PACKAGE_NAME} STREQUAL "Documentation")) OR ${CGAL_PACKAGE_NAME} STREQUAL "Stream_support")
    # This package has in-source documentation.
    if(CGAL_BRANCH_BUILD) # use the entire include subdir
      file(APPEND ${CGAL_DOC_PACKAGE_DEFAULTS}
           "INPUT += ${CGAL_PACKAGE_DIR}/include/\n")
    else() # use the filelist
      if(EXISTS "${CGAL_PACKAGE_DOC_DIR}/filelist.txt")
        file(STRINGS "${CGAL_PACKAGE_DOC_DIR}/filelist.txt" CGAL_PKG_FILES)
        foreach(pkg_file ${CGAL_PKG_FILES})
          file(APPEND ${CGAL_DOC_PACKAGE_DEFAULTS}
               "INPUT += ${CGAL_PACKAGE_DIR}/include/${pkg_file}\n")
        endforeach()
      endif()
    endif()
  endif()
  if(EXISTS "${CGAL_PACKAGE_DIR}/include/CGAL/${CGAL_PACKAGE_NAME}/internal")
    file(APPEND ${CGAL_DOC_PACKAGE_DEFAULTS}
        "EXCLUDE += ${CGAL_PACKAGE_DIR}/include/CGAL/${CGAL_PACKAGE_NAME}/internal\n")
  endif()

  # IMAGE_PATH is set by default. For Documentation, we generate the extra path using packages.txt
  set(IMAGE_PATHS "${CGAL_PACKAGE_DOC_DIR}/fig")
  set(DEPENDENCIES "")
  # figure out the dependencies, using the file `dependencies` or `packages.txt` for Documentation
  if(${CGAL_PACKAGE_NAME} STREQUAL "Documentation")
    set(PackageFile ${CGAL_PACKAGE_DOC_DIR}/packages.txt)
    file(STRINGS ${PackageFile} EntriesAsList REGEX "^\\\\package_listing{.+}$")
    foreach(Line ${EntriesAsList})
      string(REGEX REPLACE "^\\\\package_listing{(.+)}$" "\\1" PKG "${Line}")
      list(APPEND DEPENDENCIES ${PKG})

      if(CGAL_BRANCH_BUILD)
        set(IMG_DIR "${CGAL_ROOT}/${PKG}/doc/${PKG}/fig")
      else()
        set(IMG_DIR "${CGAL_ROOT}/doc/${PKG}/fig")
      endif()

      if(EXISTS ${IMG_DIR})
        list(APPEND IMAGE_PATHS ${IMG_DIR})
      endif()
    endforeach()
  else()
    if(EXISTS ${CGAL_PACKAGE_DOC_DIR}/dependencies)
      set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${CGAL_PACKAGE_DOC_DIR}/dependencies)
      file(STRINGS ${CGAL_PACKAGE_DOC_DIR}/dependencies DEPENDENCIES)
    endif()
  endif()

  foreach(depend ${DEPENDENCIES})
    file(APPEND ${CGAL_DOC_PACKAGE_DEFAULTS}
         "TAGFILES += ${CGAL_DOC_TAG_DIR}/${depend}.tag=../${depend}\n")
  endforeach()

  foreach(image_path ${IMAGE_PATHS})
    file(APPEND ${CGAL_DOC_PACKAGE_DEFAULTS} "IMAGE_PATH += ${image_path}\n")
  endforeach()

  configure_file(${CGAL_PACKAGE_DOC_DIR}/Doxyfile.in
                 ${CGAL_DOC_DXY_DIR}/${CGAL_PACKAGE_NAME}.dxy)

  # TODO we also want to run html_post_process per package as a custom_command with POST_BUILD
  # target that build the doc and put the tag file in the generation directory CGAL_DOC_TAG_GEN_DIR
  add_custom_target(
    ${CGAL_PACKAGE_NAME}_internal_doxygen_run
    ${DOXYGEN_EXECUTABLE} ${CGAL_DOC_DXY_DIR}/${CGAL_PACKAGE_NAME}.dxy)

  set_target_properties(${CGAL_PACKAGE_NAME}_internal_doxygen_run
                        PROPERTIES FOLDER Documentation/Packages)

  #target moving the tag file into the read directory CGAL_DOC_TAG_DIR
  if("${CGAL_PACKAGE_NAME}" STREQUAL "Documentation")
    set(CGAL_PACKAGE_TAGFILE "Manual.tag")
  else()
    set(CGAL_PACKAGE_TAGFILE "${CGAL_PACKAGE_NAME}.tag")
  endif()
  add_custom_target(
    ${CGAL_PACKAGE_NAME}_copy_doc_tags
    ${CMAKE_COMMAND} -E copy "${CGAL_DOC_TAG_GEN_DIR}/${CGAL_PACKAGE_TAGFILE}"
    "${CGAL_DOC_TAG_DIR}/${CGAL_PACKAGE_TAGFILE}")

  #add the doc target doing both the doc generation and then the tag file copy
  add_custom_target(
    ${CGAL_PACKAGE_NAME}_doc
    ${DOXYGEN_EXECUTABLE} ${CGAL_DOC_DXY_DIR}/${CGAL_PACKAGE_NAME}.dxy
    COMMAND
      ${CMAKE_COMMAND} -E copy
      "${CGAL_DOC_TAG_GEN_DIR}/${CGAL_PACKAGE_TAGFILE}"
      "${CGAL_DOC_TAG_DIR}/${CGAL_PACKAGE_TAGFILE}")

  #     ${depend}_doc)
  # don't do this for now
  # foreach(depend ${DEPENDENCIES})
  #   add_dependencies(${CGAL_PACKAGE_NAME}_doc
  #     ${depend}_doc)
  # endforeach()
endfunction()

# set up the directories and variables
if(CGAL_DOC_MATHJAX_LOCATION)
  set(CGAL_DOC_MATHJAX_LOCATION_FULL_OPTION_LINE
      "MATHJAX_RELPATH = ${CGAL_DOC_MATHJAX_LOCATION}")
else()
  set(CGAL_DOC_MATHJAX_LOCATION
      "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2")
endif()

set(CGAL_DOC_OUTPUT_DIR "${CMAKE_BINARY_DIR}/doc_output")
file(MAKE_DIRECTORY "${CGAL_DOC_OUTPUT_DIR}")

option(
  CGAL_DOC_CREATE_LOGS
  "Write log files or print warnings and errors to cerr when building the doc."
  OFF)

if(CGAL_DOC_CREATE_LOGS)
  set(CGAL_DOC_LOG_DIR "${CMAKE_BINARY_DIR}/doc_log")
  file(MAKE_DIRECTORY "${CGAL_DOC_LOG_DIR}")
endif()

option(CGAL_EXTRACT_ALL_NO_DETAILED_IF_EMPTY
       "Use CGAL special doxygen setting EXTRACT_ALL_NO_DETAILED_IF_EMPTY." ON)
if(CGAL_EXTRACT_ALL_NO_DETAILED_IF_EMPTY)
  set(CGAL_OPT_EXTRACT_ALL_NO_DETAILED_IF_EMPTY
      "EXTRACT_ALL_NO_DETAILED_IF_EMPTY = YES")
else()
  # The default is NO, so we could leave it out, but it is better to have a commented out placeholder
  # this will work for versions with and without the setting.
  set(CGAL_OPT_EXTRACT_ALL_NO_DETAILED_IF_EMPTY
      "#EXTRACT_ALL_NO_DETAILED_IF_EMPTY = NO")
endif()

option(CGAL_NO_ADDITIONAL_DETAILS
       "Use CGAL special doxygen setting NO_ADDITIONAL_DETAILS." ON)
if(CGAL_NO_ADDITIONAL_DETAILS)
  set(CGAL_OPT_NO_ADDITIONAL_DETAILS
      "NO_ADDITIONAL_DETAILS = YES")
else()
  # The default is NO, so we could leave it out, but it is better to have a commented out placeholder
  # this will work for versions with and without the setting.
  set(CGAL_OPT_NO_ADDITIONAL_DETAILS
      "#NO_ADDITIONAL_DETAILS = NO")
endif()

#we use two directories for the generation/reading of tag files to prevent issues
#if the targets are built in parallel
set(CGAL_DOC_TAG_GEN_DIR "${CMAKE_BINARY_DIR}/doc_gen_tags")
file(MAKE_DIRECTORY "${CGAL_DOC_TAG_GEN_DIR}")
set(CGAL_DOC_TAG_DIR "${CMAKE_BINARY_DIR}/doc_tags")
file(MAKE_DIRECTORY "${CGAL_DOC_TAG_DIR}")
set(CGAL_DOC_DXY_DIR "${CMAKE_BINARY_DIR}/doc_dxy")
file(MAKE_DIRECTORY "${CGAL_DOC_DXY_DIR}")

#Setting the resource directory depending on the version of doxygen
set(CGAL_DOC_RESOURCE_PREFIX_DIR "${CMAKE_CURRENT_LIST_DIR}/resources")

#  first look if resources for the specific doxygen version is available, fallback
#  on the default otherwise

#select only the version number (not the commit hash)
string(REPLACE " " ";" DOXYGEN_VERSION ${DOXYGEN_VERSION})
list(GET DOXYGEN_VERSION 0 DOXYGEN_VERSION)
message(VERBOSE "Doxygen version ${DOXYGEN_VERSION}: ${DOXYGEN_EXECUTABLE}")

# The Doxygen version is search in that sorted list (to find the index for which the version is less or equal)
set(CGAL_DOXYGEN_RESOURCES_VERSIONS 1.9.6 1.14.0)
list(SORT CGAL_DOXYGEN_RESOURCES_VERSIONS COMPARE NATURAL)

# The GLOB is here to check that the list in CGAL_DOXYGEN_RESOURCES_VERSIONS is correct.
# CGAL_DOXYGEN_RESOURCES_DIRS is also used below.
file(GLOB CGAL_DOXYGEN_RESOURCES_DIRS
    RELATIVE "${CGAL_DOC_RESOURCE_PREFIX_DIR}"
    "${CGAL_DOC_RESOURCE_PREFIX_DIR}/*")
list(SORT CGAL_DOXYGEN_RESOURCES_DIRS COMPARE NATURAL)

if(NOT CGAL_DOXYGEN_RESOURCES_DIRS STREQUAL CGAL_DOXYGEN_RESOURCES_VERSIONS)
  message(WARNING "The directories in ${CGAL_DOC_RESOURCE_PREFIX_DIR} do not match the expected versions:\n"
                  "    [${CGAL_DOXYGEN_RESOURCES_DIRS}] vs [${CGAL_DOXYGEN_RESOURCES_VERSIONS}]")
endif()

function(CGAL_insert_in_sorted_list list_name value)
  set(list ${${list_name}})
  if(NOT value IN_LIST list)
    list(APPEND list "${value}")
    list(SORT list COMPARE NATURAL)
  endif()
  set(${list_name} ${list} PARENT_SCOPE)
endfunction()

if(DOXYGEN_VERSION IN_LIST CGAL_DOXYGEN_RESOURCES_DIRS)
  list(FIND CGAL_DOXYGEN_RESOURCES_DIRS "${DOXYGEN_VERSION}" DOXYGEN_VERSION_INDEX)
else()
  CGAL_insert_in_sorted_list(CGAL_DOXYGEN_RESOURCES_DIRS ${DOXYGEN_VERSION})
  list(FIND CGAL_DOXYGEN_RESOURCES_DIRS ${DOXYGEN_VERSION} DOXYGEN_VERSION_INDEX)
  math(EXPR DOXYGEN_VERSION_INDEX "${DOXYGEN_VERSION_INDEX} - 1")
endif()
list(GET CGAL_DOXYGEN_RESOURCES_DIRS "${DOXYGEN_VERSION_INDEX}" CGAL_DOC_RESOURCE_DIR)

set(CGAL_DOC_RESOURCE_DIR "${CGAL_DOC_RESOURCE_PREFIX_DIR}/${CGAL_DOC_RESOURCE_DIR}")
if(NOT EXISTS "${CGAL_DOC_RESOURCE_DIR}")
  message(FATAL_ERROR "Doxygen resources for version ${DOXYGEN_VERSION} not found")
else()
  message(VERBOSE "Using Doxygen resources from ${CGAL_DOC_RESOURCE_DIR}")
endif()

set(CGAL_DOC_BIBLIO_DIR "${CMAKE_CURRENT_LIST_DIR}/biblio")
set(CGAL_DOC_SCRIPT_DIR "${CMAKE_CURRENT_LIST_DIR}/scripts")

set(CGAL_DOC_HEADER ${CGAL_DOC_DXY_DIR}/header.html)
configure_file(${CGAL_DOC_RESOURCE_DIR}/header.html ${CGAL_DOC_HEADER} @ONLY)
set(CGAL_DOC_HEADER_PACKAGE ${CGAL_DOC_DXY_DIR}/header_package.html)
configure_file(${CGAL_DOC_RESOURCE_DIR}/header_package.html
               ${CGAL_DOC_HEADER_PACKAGE} @ONLY)

#Generate the bibtex file
#this is needed also for BaseDoxyfile.in
string(TIMESTAMP CGAL_BUILD_YEAR4 "%Y")
string(TIMESTAMP CGAL_BUILD_YEAR2 "%y")
string(TIMESTAMP CGAL_BUILD_MONTH "%m")

if(${CGAL_BUILD_MONTH} GREATER 6)
  set(CGAL_RELEASE_YEAR_ID "${CGAL_BUILD_YEAR2}b")
else()
  set(CGAL_RELEASE_YEAR_ID "${CGAL_BUILD_YEAR2}a")
endif()

if(NOT CGAL_CREATED_VERSION_NUM)
  if(CGAL_BRANCH_BUILD)
    include(${CGAL_ROOT}/CGALConfigVersion.cmake)

    # Prefer the public release version (e.g. "6.0-beta1") which includes
    # pre-release suffixes; fall back to computing from components when it
    # is not available (issue #8322).
    if(CGAL_VERSION_PUBLIC_RELEASE_VERSION)
      set(CGAL_CREATED_VERSION_NUM "${CGAL_VERSION_PUBLIC_RELEASE_VERSION}")
    elseif(CGAL_BUGFIX_VERSION AND CGAL_BUGFIX_VERSION GREATER 0)
      set(CGAL_CREATED_VERSION_NUM
          "${CGAL_MAJOR_VERSION}.${CGAL_MINOR_VERSION}.${CGAL_BUGFIX_VERSION}")
    else()
      set(CGAL_CREATED_VERSION_NUM
          "${CGAL_MAJOR_VERSION}.${CGAL_MINOR_VERSION}")
    endif()
  else()
    if(EXISTS "${CGAL_ROOT}/doc/public_release_name")
      file(STRINGS "${CGAL_ROOT}/doc/public_release_name" CGAL_VERSION_LINE)
      string(REGEX REPLACE "CGAL-" "" CGAL_CREATED_VERSION_NUM
                           "${CGAL_VERSION_LINE}")
    else()
      #read version.h and get the line with CGAL_VERSION
      file(STRINGS "${CGAL_ROOT}/include/CGAL/version.h" CGAL_VERSION_LINE
           REGEX "CGAL_VERSION ")
      #extract release id, including any pre-release suffix like -beta1, -dev,
      #or multi-segment ids such as -Ic-33
      string(REGEX MATCH "[0-9]+\\.[0-9]+(\\.[0-9]+)?(-[a-zA-Z0-9]+)*" CGAL_CREATED_VERSION_NUM
                   "${CGAL_VERSION_LINE}")
    endif()
  endif()
endif()

# Introduce our own version variable. This way we avoid tying this too
# closely to the convoluted versioning code and can adapt without a
# huge diff.
set(CGAL_DOC_VERSION ${CGAL_CREATED_VERSION_NUM})

## generate how_to_cite files
execute_process(
  COMMAND ${Python3_EXECUTABLE} ${CGAL_DOC_SCRIPT_DIR}/generate_how_to_cite.py
          ${CGAL_ROOT} ${CMAKE_BINARY_DIR} "${CGAL_BRANCH_BUILD}"
  RESULT_VARIABLE GENERATE_HOW_TO_CITE_RESULT)
if(NOT GENERATE_HOW_TO_CITE_RESULT EQUAL "0")
  message(FATAL_ERROR "generate_how_to_cite did not exit correctly")
endif()

configure_file(${CMAKE_BINARY_DIR}/how_to_cite_cgal.bib.in
               ${CMAKE_BINARY_DIR}/how_to_cite_cgal.bib)
configure_file(${CMAKE_BINARY_DIR}/how_to_cite_cgal.txt.in
               ${CMAKE_BINARY_DIR}/how_to_cite_cgal.txt)
configure_file(${CMAKE_BINARY_DIR}/how_to_cite.html.in
               ${CMAKE_BINARY_DIR}/how_to_cite.html)

#
configure_file(${CGAL_DOC_RESOURCE_DIR}/BaseDoxyfile.in
               ${CGAL_DOC_DXY_DIR}/BaseDoxyfile)

set(CGAL_DOC_DOXY_DEFAULT "${CGAL_DOC_DXY_DIR}/BaseDoxyfile")

if (BE_QUIET)
  file(APPEND ${CGAL_DOC_DOXY_DEFAULT} "WARN_LOGFILE=doxygen.log\n")
endif()

# pkglist_filter gets the path to the pkglist_filter of this source
# directory.
if(WIN32)
  configure_file(${CGAL_DOC_SCRIPT_DIR}/pkglist_filter.bat
                 ${CMAKE_BINARY_DIR}/pkglist_filter.bat)
endif()
configure_file(${CGAL_DOC_SCRIPT_DIR}/pkglist_filter
               ${CMAKE_BINARY_DIR}/pkglist_filter)
configure_file(${CGAL_DOC_SCRIPT_DIR}/pkglist_filter.py
               ${CMAKE_BINARY_DIR}/pkglist_filter.py)

set(CGAL_DOC_PACKAGES "")
if(CGAL_BRANCH_BUILD)
  file(
    GLOB CGAL_ALL_PACKAGES
    RELATIVE ${CGAL_ROOT}
    "${CGAL_ROOT}/*")
  foreach(pkg ${CGAL_ALL_PACKAGES})
    #detect packages with documentation to process
    if(IS_DIRECTORY ${CGAL_ROOT}/${pkg})
      if(EXISTS "${CGAL_ROOT}/${pkg}/doc/${pkg}/PackageDescription.txt")
        list(APPEND CGAL_DOC_PACKAGES ${pkg})
      endif()
    endif()
    #set up directories of packages
    if(IS_DIRECTORY ${CGAL_ROOT}/${pkg}/examples)
      set(CGAL_${pkg}_EXAMPLE_DIR "${CGAL_ROOT}/${pkg}/examples")
    endif()
    if(IS_DIRECTORY ${CGAL_ROOT}/${pkg}/include)
      set(CGAL_${pkg}_INCLUDE_DIR "${CGAL_ROOT}/${pkg}/include")
    endif()
    if(IS_DIRECTORY ${CGAL_ROOT}/${pkg}/demo)
      set(CGAL_${pkg}_DEMO_DIR "${CGAL_ROOT}/${pkg}/demo")
    endif()
  endforeach()
else()
  subdirlist(CGAL_DOC_PACKAGES_TMP ${CGAL_ROOT}/doc)
  set(CGAL_DOC_PACKAGES)
  foreach(package ${CGAL_DOC_PACKAGES_TMP})
    if(EXISTS "${CGAL_ROOT}/doc/${package}/PackageDescription.txt")
      list(APPEND CGAL_DOC_PACKAGES "${package}")
    endif()
  endforeach()

  subdirlist(CGAL_EXAMPLE_PACKAGES ${CGAL_ROOT}/examples)
  subdirlist(CGAL_DEMO_PACKAGES ${CGAL_ROOT}/demo)
  list(APPEND CGAL_EXAMPLE_PACKAGES "BGL"
  )# manually add BGL to the list of packages
  foreach(pkg ${CGAL_EXAMPLE_PACKAGES})
    set(CGAL_${pkg}_EXAMPLE_DIR "${CGAL_ROOT}/examples")
    # This might not be entirely correct, but there is no reliable,
    # easy way to get a list of all package names when not in a
    # branch build.
    set(CGAL_${pkg}_INCLUDE_DIR "${CGAL_ROOT}/include")
  endforeach()
  foreach(pkg ${CGAL_DEMO_PACKAGES})
    set(CGAL_${pkg}_DEMO_DIR "${CGAL_ROOT}/demo")
  endforeach()
endif()

#special cases
if(NOT CGAL_BRANCH_BUILD)
  foreach(pkg "Mesher_level" "Surface_mesh_decomposition")
    set(CGAL_${pkg}_INCLUDE_DIR "${CGAL_ROOT}/include")
  endforeach()
endif()

option(CGAL_BUILD_THREE_DOC "Build the documentation of the Three package" OFF)

if(NOT CGAL_BUILD_THREE_DOC)
  list(REMOVE_ITEM CGAL_DOC_PACKAGES "Three")
endif()

foreach(package ${CGAL_DOC_PACKAGES})
  configure_doxygen_package(${package})
endforeach()

# Add a custom target "doc"
add_custom_target(doc)
add_custom_target(doc_pre)
add_custom_target(doc_post)

# do the main package manually, it isn't part of ${CGAL_CONFIGURED_PACKAGES_NAMES}
configure_doxygen_package("Documentation")
set_target_properties(Documentation_doc PROPERTIES FOLDER Documentation)

# hard-code that doc depends on all packages
foreach(depend ${CGAL_DOC_PACKAGES})
  add_dependencies(doc_pre ${depend}_internal_doxygen_run)
  add_dependencies(doc_post ${depend}_copy_doc_tags)
  add_dependencies(${depend}_copy_doc_tags doc_pre)
endforeach()
add_dependencies(doc_pre Documentation_internal_doxygen_run)
add_dependencies(doc_post Documentation_copy_doc_tags)
add_dependencies(Documentation_copy_doc_tags doc_pre)

#total level doc dependencies
add_dependencies(doc doc_post)


set(CGAL_DOC_TESTSUITE_SCRIPT "${CGAL_DOC_SCRIPT_DIR}/testsuite.py")

add_custom_target(
  doc_with_postprocessing
  ${Python3_EXECUTABLE} ${CGAL_DOC_SCRIPT_DIR}/html_output_post_processing.py
  --output ${CGAL_DOC_OUTPUT_DIR} --resources ${CGAL_DOC_RESOURCE_DIR})
add_dependencies(doc_with_postprocessing doc)

if(CGAL_DOC_CREATE_LOGS)
  add_custom_target(
    Documentation_test
    ${Python3_EXECUTABLE} ${CGAL_DOC_TESTSUITE_SCRIPT} --output-dir
    ${CGAL_DOC_OUTPUT_DIR} --doc-log-dir ${CGAL_DOC_LOG_DIR})
  add_dependencies(Documentation_test doc)

  add_custom_target(
    Documentation_test_publish
    ${Python3_EXECUTABLE}
    ${CGAL_DOC_TESTSUITE_SCRIPT}
    --output-dir
    ${CGAL_DOC_OUTPUT_DIR}
    --doc-log-dir
    ${CGAL_DOC_LOG_DIR}
    --publish
    ${CGAL_DOC_PUBLISH_DIR}
    --do-copy-results)
  add_dependencies(Documentation_test_publish doc)

  add_custom_target(
    doc_and_publish_testsuite
    ${Python3_EXECUTABLE}
    ${CGAL_DOC_TESTSUITE_SCRIPT}
    --output-dir
    ${CGAL_DOC_OUTPUT_DIR}
    --doc-log-dir
    ${CGAL_DOC_LOG_DIR}
    --publish
    ${CGAL_DOC_PUBLISH_DIR}
    --do-copy-results
    --cgal-version
    "${CGAL_FULL_VERSION}"
    --version-to-keep
    10)
  add_dependencies(doc_and_publish_testsuite doc_with_postprocessing)

endif()

---

### AABB Tree Doc AABB Tree PackageDescription (`AABB_tree/doc/AABB_tree/PackageDescription.txt`)

/// \defgroup PkgAABBTreeRef Reference Manual

/// \defgroup PkgAABBTreeConcepts Concepts
/// \ingroup PkgAABBTreeRef

/*!
\addtogroup PkgAABBTreeRef
\cgalPkgDescriptionBegin{2D and 3D Fast Intersection and Distance Computation,PkgAABBTree}
\cgalPkgPicture{aabb-teaser-thumb.png}
\cgalPkgSummaryBegin
\cgalPkgAuthors{Pierre Alliez, Stéphane Tayeb, and Camille Wormser}
\cgalPkgDesc{The AABB (axis-aligned bounding box) tree component offers a static data structure and algorithms to perform efficient intersection and distance queries on sets of finite 2D and 3D geometric objects.}
\cgalPkgManuals{Chapter_Fast_Intersection_and_Distance_Computation,PkgAABBTreeRef}
\cgalPkgSummaryEnd
\cgalPkgShortInfoBegin
\cgalPkgSince{3.5}
\cgalPkgBib{cgal:atw-aabb}
\cgalPkgLicense{\ref licensesGPL "GPL"}
\cgalPkgDemo{AABB Tree,AABB_demo.zip}
\cgalPkgShortInfoEnd
\cgalPkgDescriptionEnd

\cgalClassifedRefPages

\cgalCRPSection{Concepts}
- `AABBPrimitive`
- `AABBPrimitiveWithSharedData`
- `AABBGeomTraits_2`
- `AABBGeomTraits_3`
- `AABBTraits`
- `AABBRayIntersectionGeomTraits_2`
- `AABBRayIntersectionGeomTraits_3`
- `AABBRayIntersectionTraits`

\cgalCRPSection{Classes}
- `CGAL::AABB_traits<GeomTraits,Primitive>` (deprecated, use `CGAL::AABB_traits_3<GeomTraits,Primitive>`)
- `CGAL::AABB_traits_2<GeomTraits,Primitive>`
- `CGAL::AABB_traits_3<GeomTraits,Primitive>`
- `CGAL::AABB_tree<AT>`

\cgalCRPSection{Primitives}
- `CGAL::AABB_triangle_primitive_2<GeomTraits, Iterator, CacheDatum>`
- `CGAL::AABB_indexed_triangle_primitive_2<GeomTraits, IndexIterator, PointRange, CacheDatum, PointMap>`
- `CGAL::AABB_segment_primitive_2<GeomTraits, Iterator, CacheDatum>`
- `CGAL::AABB_polyline_segment_primitive_2<GeomTraits, Iterator, PointRange, CacheDatum, PointMap>`
- `CGAL::AABB_triangle_primitive<GeomTraits, Iterator, CacheDatum>` (deprecated, use `CGAL::AABB_triangle_primitive_3<GeomTraits, Iterator, CacheDatum>`)
- `CGAL::AABB_triangle_primitive_3<GeomTraits, Iterator, CacheDatum>`
- `CGAL::AABB_segment_primitive<GeomTraits, Iterator, CacheDatum>` (deprecated, use `CGAL::AABB_segment_primitive_3<GeomTraits, Iterator, CacheDatum>`)
- `CGAL::AABB_segment_primitive_3<GeomTraits, Iterator, CacheDatum>`
- `CGAL::AABB_primitive<Id,ObjectPropertyMap,PointPropertyMap,ExternalPropertyMaps,CacheDatum>`
- `CGAL::AABB_halfedge_graph_segment_primitive<HalfedgeGraph,Vpm,OneHalfedgeGraphPerTree,CacheDatum>`
- `CGAL::AABB_face_graph_triangle_primitive<FaceGraph,Vpm,OneFaceGraphPerTree,CacheDatum>`

\cgalCRPSection{Functions}
- `CGAL::AABB_trees::do_intersect()`
- `CGAL::AABB_trees::all_pairs_of_intersecting_primitives()`
*/

---

### AABB Tree Doc AABB Tree Aabb Tree (`AABB_tree/doc/AABB_tree/aabb_tree.txt`)

namespace CGAL {

/*!

\mainpage User Manual
\anchor Chapter_Fast_Intersection_and_Distance_Computation
\cgalAutoToc

\authors Pierre Alliez, Stephane Tayeb, and Camille Wormser

\section aabb_tree_introduction Introduction

The AABB tree component offers a static data structure and algorithms
to perform efficient intersection and distance queries against sets of
finite 2D or 3D geometric objects. The set of geometric objects stored in
the data structure can be queried for intersection detection,
intersection computation and distance. The intersection queries can be
of any type, provided that the corresponding intersection predicates
and constructors are implemented in the traits class. The distance
queries are limited to point queries. Examples of intersection queries
include line objects (rays, lines, segments) against sets of
triangles, or plane objects (planes, triangles) against sets of
segments. An example of a distance query consists of finding the
closest point from a point query to a set of triangles.

Similarly to the package \ref PkgBoxIntersectionD,
this component might also be used for finding all intersecting pairs of objects,
and can even achieve a better performance when running on several threads.

The AABB tree data structure takes as input an iterator range of
geometric data, which is then converted into primitives. From these
primitives a hierarchy of axis-aligned bounding boxes (AABBs) is
constructed and used to speed up intersection and distance queries.
Each primitive gives access to both one input geometric object
(so-called datum) and one reference id to this object. A typical
example primitive wraps a 3D triangle as datum and a face handle of a
polyhedral surface as id. Each intersection query can return the
intersection objects (e.g., 3D points or segments for ray queries) as
well as the id (here the face handle) of the intersected
primitives. Similarly, each distance query can return the closest
point from the point query as well as the id of the closest primitive.

\cgalFigureBegin{aabbtree_meca,anchor.png}
Left: surface triangle mesh of a mechanical part. Right: AABB tree constructed.
\cgalFigureEnd

\section aabb_tree_interface Interface

The main entry point to the component is the class `AABB_tree`
which represents a static AABB tree constructed from an iterator range
of geometric data. Once instantiated an AABB tree can be queried for
intersection and distance queries.

\b Intersections. Assume for example that the tree contains triangle
primitives. The tree can be queried for intersection against line
objects (rays, segments or line) in various ways. We distinguish
intersection *tests* which do not construct any intersection
objects, from *intersections* which construct the intersection
objects.

Tests:

- Function `AABB_tree::do_intersect()` tests if the input primitives are
intersected by the query. This function is fast as it involves only
predicates and stops after the first encountered intersection.
- Function `AABB_tree::number_of_intersected_primitives()` counts all
intersected primitives.
- Function `AABB_tree::all_intersected_primitives()` enumerates all intersected
primitives ids without constructing the corresponding intersection
objects.
- Function `AABB_tree::any_intersected_primitive()` returns the first
encountered intersecting primitive id (if any) without constructing
the corresponding intersection object, and stops after the first
encountered intersection. Note that the traversal order of the tree is
such that first herein does not refer to any particular ordering of
the intersections with respect to the query.
- Function `AABB_tree::first_intersected_primitive()` returns
the intersecting primitive id (if any) of the corresponding
intersection object that is closest to the source of the ray.

Constructions:

- Function  `AABB_tree::all_intersections()` detects and constructs all
intersection objects with the input primitives.
- Function  `AABB_tree::any_intersection()` detects and constructs the first
encountered intersection and constructs the corresponding object. This
function is fast as it stops after the first encountered intersection.
- Function `AABB_tree::first_intersection()` detects and constructs
the intersection object that is closest to the source of the ray.


\b Distance. An AABB tree computes the closest point from a
given point query to the input primitives through the function
`AABB_tree::closest_point()`. In addition, it can compute the id of the
closest primitive from a given point query through the function
`AABB_tree::closest_point_and_primitive()`, i.e., the id of the
primitive which realizes the minimum distance from the point
query. The AABB tree uses a secondary search structure to speed up the
distance queries. The construction of this secondary structure should
be requested by the user by a call to
`AABB_tree::accelerate_distance_queries()` before the first the distance
computation. This data structure is not generated by default because
it is used only for distance computations.

\warning Having degenerate primitives in the AABB-tree is not recommended as the underlying
predicates and constructions of the traits class might not be able to handle them.
For example if one is using `CGAL::AABB_traits` with a Kernel from \cgal,
having degenerate triangles or segments in the AABB-tree will result in an undefined
behavior or a crash.

\section two_aabb_tree_interface Operations between Two AABB Trees

Given two AABB trees, the function `CGAL::AABB_trees::do_intersect()` determines whether any
primitive of the first tree intersects a primitive of the second tree.
To enumerate all intersecting pairs of primitives, use `CGAL::AABB_trees::all_pairs_of_intersecting_primitives()`.

These functions provide an alternative to `CGAL::box_intersection_d()`. In practice, `CGAL::AABB_trees::all_pairs_of_intersecting_primitives()` generally provides better performance,
particularly when using a parallel execution tag (see \ref aabb_tree_perf).

Note that compared to `CGAL::box_intersection_d()`, the tree of primitives is actually constructed. It becomes even more interesting in term of runtime
if several calls to the aforementioned intersection functions are done with the same tree.

\section aabb_tree_examples Examples

\subsection aabb_tree_examples_1 Tree of Triangles, for Intersection and Distance Queries

In the following example a set of 3D triangles is stored in a
list. The AABB primitive wraps a triangle as `datum` and an
iterator in the list as `id`. We compute the number of input
triangles intersected by a ray query, as well as the closest point and
the squared distance from a point query.

\cgalExample{AABB_tree/AABB_triangle_3_example.cpp}

\subsection aabb_tree_examples_2 Tree of Polyhedron Triangle Facets for Intersection Queries

In the following example the AABB primitive wraps a facet handle of a
triangle polyhedral surface as `id` and the corresponding 3D
triangle as geometric object. From a segment query we test the
intersections, then compute the number of intersections, compute the
first encountered intersection (generally a point), compute all
intersections (where each intersection is a pair of one \cgal object
and one primitive id - here a face handle) and compute all intersected
primitives. The latter involves only tests and no predicates and is
hence faster than computing all intersections. We also compute the
first encountered intersection with a plane query, which is generally
a segment.  We finally compute the first intersection along a ray.

\cgalExample{AABB_tree/AABB_polyhedron_facet_intersection_example.cpp}


\subsection aabb_ray_shooting Ray Shooting

In the following example we load a closed polyhedral surface and perform a
ray shooting query from the centroid of each face, orthogonally to the face
towards the interior.  As the centroid is computed with floating point
arithmetic the first face hit by the ray may be the face of the centroid.
The skip functor takes care of ignoring the face.

\cgalExample{AABB_tree/AABB_ray_shooting_example.cpp}



\subsection aabb_tree_examples_3 Tree of Polyhedron Triangle Facets for Distance Queries

In the following example the AABB primitive wraps a facet handle of a
triangle polyhedral surface as `id` and the corresponding 3D
triangle as geometric object. From a point query we compute the
squared distance, the closest point as well as the closest point and
primitive id. The latter returns a pair composed of a point and a face
handle.

\cgalExample{AABB_tree/AABB_polyhedron_facet_distance_example.cpp}

\subsection aabb_tree_examples_4 Tree of Segments for Intersection and Distance Queries

In the following example the segments are stored into a list, and the
AABB primitive wraps a segment as `datum` and an iterator in the
list as `id`. We compute the number of intersections with plane
and triangles queries, and the closest point from a point query.
\cgalExample{AABB_tree/AABB_segment_3_example.cpp}

\subsection aabb_tree_examples_8 Tree of Polyline and Polygon Segments for Intersection and Distance Queries

The following example uses segments given by a polyline and a polygon. The difference is that the polygon is closed. The `id` in this case is the iterator pointing to a `Point_2` in the polyline or the polygon. The datum, a `Segment_2`, is created on the fly from the points using the `id` as the source and the following `Point_2` as the target. We count the intersections with a `Segment_2` and the closest point and id from a point query.
\cgalExample{AABB_tree/AABB_polyline_segment_2_example.cpp}

\subsection aabb_tree_examples_5 Tree of Polyhedron Edge Segments for Intersection and Distance Queries

In the following example the AABB primitive wraps a halfedge handle as
`id` and generates a 3D segment on the fly, each time its method
`datum` is called. We compute the number of intersections with a
triangle query and the closest point from a point query.
\cgalExample{AABB_tree/AABB_polyhedron_edge_example.cpp}

\subsection aabb_tree_examples_6 Incremental Insertion of Primitives

The AABB tree is a static data structure, but it allows to insert
primitives, and will internally rebuild triggered by the first query,
or because the user calls the `AABB_tree::build()` method.  The following
example illustrates this for two polyhedral surfaces.

\cgalExample{AABB_tree/AABB_insertion_example.cpp}

\subsection aabb_tree_examples_7 Trees of Custom Primitives

The AABB tree example folder contains three examples of trees
constructed with custom primitives. In \ref AABB_tree/AABB_custom_example.cpp "AABB_custom_example.cpp"
the primitive contains triangles which are defined by three pointers
to custom points. In \ref AABB_tree/AABB_custom_triangle_soup_example.cpp "AABB_custom_triangle_soup_example.cpp" all input
triangles are stored into a single array as to form a triangle
soup. The primitive internally uses a `boost::iterator_adaptor`
as to provide the three functions `AABBPrimitive::id()`, `AABBPrimitive::datum()`,
and `AABBPrimitive::reference_point()` required by the primitive concept. In
\ref AABB_tree/AABB_custom_indexed_triangle_set_example.cpp "AABB_custom_indexed_triangle_set_example.cpp" the input is an indexed
triangle set stored through two arrays: one array of points and one
array of indices which refer to the point array. Here also the
primitive internally uses a `boost::iterator_adaptor`.

\subsection aabb_tree_examples_9 Intersection of Two Trees

In the following example, we compute all the intersections between two triangle soups both representing a tetrahedron. The triangle soups
are stored as a vector of `Triangle_3`. We first compute if the tetrahedra do intersect and then we
compute the indices of the intersecting triangles.

\cgalExample{AABB_tree/AABB_intersection_example.cpp}

\section aabb_tree_perf Performances

We provide some performance numbers for the case where the AABB tree
contains a set of polyhedron triangle facets. We measure the tree
construction time, the memory occupancy and the number of queries per
second for a variety of intersection and distance queries. The machine
used is a PC running Linux Mint with an Intel CPU Core Ultra 7 155H with 16 cores and 32GB of RAM.
By default, the kernel used is `Simple_cartesian<double>` (the fastest in our experiments). The
program has been compiled with the compiler gcc 13.3 2023 with the `O3`
option which maximizes speed.

\subsection aabb_tree_perf_cons Construction

The surface triangle mesh chosen for benchmarking the tree
construction is the knot model (14,400 triangles) depicted by
\cgalFigureRef{figAABB-tree-bench}. We measure the tree construction time (both
AABB tree alone and AABB tree with internal KD-tree) for four denser versions of the knot model.


|  Number of triangles | Construction (in ms) (Parallel) | (Sequential) | Construction with internal KD-tree (in ms) (Parallel) | (Sequential) |
| ----: | ----: | ----: | ----: | ----: |
  230,400 | 20 | 36 | 48 | 66 |
  921,600 | 72 | 187 | 155 | 306 |
  3,686,400 | 292 | 816 | 729 | 1426 |
  14,745,600 | 1,425 | 4,196 | 3,028 | 7,016 |

\subsection aabb_tree_perf_mem Memory

When using the polyhedron triangle facet primitive (defined in
`CGAL/AABB_face_graph_triangle_primitive.h`) the AABB tree occupies
approximately 61 bytes per primitive (without constructing the
internal KD-tree). It increases to approximately 150 bytes per
primitive when constructing the internal KD-tree with one reference
point per primitive (the default mode when calling the function
`AABB_tree::accelerate_distance_queries()`). Note that the polyhedron
facet primitive stores only one facet handle as primitive id
and computes on the fly a 3D triangle from the facet handle stored
internally. When explicitly storing a 3D triangle in the primitive the
tree occupies approximately 140 bytes per primitive instead of 60
(without constructing the internal KD-tree).

The following table provides orders of memory occupancy in MBytes for
an increasing number of triangles. As the internal KD-tree used to
accelerate the distance queries dominates the memory occupancy, we
recommend to specify for large models a lower number of reference
point (evenly distributed) to construct the internal KD-tree through
the function `AABB_tree::accelerate_distance_queries()` which
takes an iterator range as input.

|  Number of triangles | AABB tree (in MBytes) | AABB tree with internal KD-tree (in MBytes)|
| ----: | ----: | ----: |
   18,400 |   1.10 |    2.76 |
  102,400 |   6.33 |   14.73 |
1,022,400 |  59.56 |  151.31 |
1,822,400 | 108.34 |  291.84 |


\subsection aabb_tree_perf_inter Intersections

The following table measures the number of intersection queries per
second on one core on the 14,400 triangle version of the knot mesh model for ray,
line, segment and plane queries. Each ray query is generated by
choosing a random source point within the mesh bounding box and a
random vector. A line or segment query is generated by choosing two
random points inside the bounding box. A plane query is generated by
picking a random point inside the bounding box and a random normal
vector. Note that a plane query generally intersects many triangles of
the input surface mesh. This explains the low performance numbers for
the intersection functions which enumerate all intersections.


|  Function                              | Segment |     Ray |    Line |   Plane |
| :---- | ----: | ----: | -: | -: |
|   AABB_tree::do_intersect()                       | 513,505 | 788,246 | 773,947 | 1,863,721  |
|   AABB_tree::any_intersected_primitive()         | 521,651 | 852,929 | 831,919 | 2,125,582 |
|   AABB_tree::any_intersection()                   | 504,836 | 835,164 | 821,369 | 1,730,017 |
|   AABB_tree::number_of_intersected_primitives() |  186,102 |  397,069 |  210,052 |   49,941 |
|   AABB_tree::all_intersected_primitives()        |  178,769 |  397,458 |  192,482 |   49,324 |
|   AABB_tree::all_intersections()                  |  178,536 |  352,541 |  193,700 |   21,745 |

Curve of \cgalFigureRef{figAABB-tree-bench} plots the number of queries per second
(here the `AABB_tree::all_intersections()` function with random segment
queries) against the number of input triangles for the knot triangle
surface mesh.

\cgalFigureBegin{figAABB-tree-bench,bench.png, knot.png}
Number of queries per second against number of triangles for the knot model with 14K (shown) to 15M triangles. We call the `all_intersections()` function with segment queries randomly chosen within the bounding box.
\cgalFigureEnd

The following table measures the number of `AABB_tree::all_intersections()`
queries per second against several kernels. We use the 14,400 triangle
version of the knot mesh model for random segment queries.

|  Kernel | Queries/s (all_intersections() with segment queries)|
| :---- | ----: |
|`Simple_cartesian<double>`               | 201,618 |
|`Simple_cartesian<float>`                | 193,414 |
|`Cartesian<double>`                      | 164,784 |
|`Cartesian<float>`                       | 159,686 |
|`Exact_predicates_inexact_constructions_kernel` | 119,590 |

\subsection aabb_tree_perf_dist Distances

The surface triangle mesh chosen for benchmarking distances is again
the knot model in six increasing resolutions. In the following table we first measure the tree
construction time (which includes the construction of the internal
KD-tree data structure used to accelerate the distance queries by up
to one order of magnitude in our experiments). We then measure the
number of queries per second for the three types distance queries
(`AABB_tree::closest_point()`, `AABB_tree::squared_distance()` and
`AABB_tree::closest_point_and_primitive()`) from point queries randomly chosen
inside the bounding box.

|  Nb triangles | Closest_point() | Squared_distance() | Closest_point_and_primitive() |
| ----:    | ----: | ----: | -: |
|   14,400 | 196,043 | 196,356 | 196,708 |
|   57,600 | 123,388 | 123,844 | 123,567 |
|  230,400 | 54,480 | 53,235 | 54,329 |
|  921,600 | 25,761 | 26,890 | 25,386 |
|  3,686,400 | 13,696 | 13,389 | 13,440 |
|  14,745,600 | 7,158 | 6,913| 7,010 |

\subsection aabb_two_trees_perf Intersection of Two AABB Trees

We test the intersection of two AABB trees using 3 models: two common models of mesh processing (Iphigenia and Nefertiti), and twisted knot to maximize the number of intersection. For each model,
we test their intersection with a translated version of themselves (Note: We do not exploit the fact that it is the same model, the tree is built twice).
We compare here `CGAL::AABB_trees::all_pairs_of_intersecting_primitives()` and `CGAL::box_intersection_d()`.



\cgalFigureBegin{figAABB-tree-model,iphigenia.png, nefertiti.png, twisted_knot.png}
The three input models used to illustrate AABB trees intersection performance. Iphigenia (left), Nefertiti (center), Twisted knot (right).
\cgalFigureEnd

| Models | Nb Triangles | Nb Intersections | **AABB** | Tree (ms) | | | **Box** d || **AABB** | Tree Seq. | (ms) | | **Box** d Seq. |
| ----: | ----: | ----: | ----: | ----: | ----: | ----: | ----: || ----: | ----: | ----: | ----: | ----: |
|  |  |  | Build |  Do intersect | All pairs | All pairs + Build |  || Build | Do intersect | All pairs | All pairs + Build |  |
| Iphigenia × Iphigenia Tr. | 703,512 × 703,512 | 47,677 | 91 | <0.1 | 37 | 128 | 424 || 318 | <0.1 | 169 | 488 | 868 |
| Nefertiti × Nefertiti Tr. | 2,018,232 × 2,018,232 | 14,246 | 261 | <0.1 | 10 | 271 | 1,006 ||1,087 | <0.1 | 46 | 1,134 | 2,348 |
| Twisted knot × Twisted knot Rot. | 600,000 × 600,000 | 240,144 | 154 | <0.1 | 57 | 211 | 850 || 541 | <0.1 | 440 | 981 | 2,993 |

\subsection aabb_tree_perf_summary Summary

The experiments described above are neither exhaustive nor conclusive
as we have chosen one specific case where the input primitives are the
facets of a triangle surface polyhedron. Nevertheless, we now provide
some general observations and advises about how to put the AABB tree
to use with satisfactory performances. While the tree construction
times and memory occupancy do not fluctuate much in our experiments
depending on the input surface triangle mesh, the performance
expressed in number of queries varies greatly depending on a complex
combination of criteria: type of kernel, number of input primitives,
distribution of primitives in space, type of function queried, type of
query and location of query in space.

- %Kernel: The type of \cgal kernel turns out to dominate the final
  execution times, the maximum performances being obtained with the
  `Simple_cartesian` kernel parameterized with the double precision
  number type. In applications where the intersection and distance
  execution times are crucial it is possible to use this kernel for
  the AABB tree in combination with a more robust kernel for the main
  data structure.

- Primitives: Although the number of input primitives plays an obvious
  role in the final performance, their distribution in space is at
  least equally important in order to obtain a well-balanced AABB
  tree. Ideally the primitives must be evenly distributed in space and
  the long primitives spanning the bounding box of the tree root node
  must be avoided as much as possible. It is often beneficial to split
  these long primitives into smaller ones before constructing the
  tree, e.g., through recursive longest edge bisection for triangle
  surface meshes.

- Function: The type of function queried plays another important
  role. Obviously the *exhaustive* functions, which list all
  intersections, are slower than the ones stopping after the first
  intersection. Within each of these functions the ones which call
  only intersection tests (`AABB_tree::do_intersect()`,
  `AABB_tree::number_of_intersected_primitives()`,
  `AABB_tree::any_intersected_primitive()`, `AABB_tree::all_intersected_primitives()`) are
  faster than the ones which explicitly construct the intersections
  (`AABB_tree::any_intersection()` and `AABB_tree::all_intersections()`).

- Query: The type of query (e.g., line, ray, segment or plane used
  above) plays another role, strongly correlated with the type of
  function (exhaustive or not, and whether or not it constructs the
  intersections). When all intersection constructions are needed, the
  final execution times highly depend on the complexity of the general
  intersection object. For example a plane query generally intersects
  a surface triangle mesh into many segments while a segment query
  generally intersects a surface triangle mesh into few
  points. Finally, the location of the query in space also plays an
  obvious role in the performances, especially for the distance
  queries. Assuming the internal KD-tree constructed through the
  function `AABB_tree::accelerate_distance_queries()`, it is preferable
  to specify a query point already close to the surface triangle mesh
  so that the query traverses only few AABBs of the tree. For a large
  number of primitive data (greater than 2M faces in our experiments)
  however we noticed that it is not necessary (and sometimes even
  slower) to use all reference points when constructing the
  KD-tree. In these cases we recommend to specify through the function
  ` AABB_tree::accelerate_distance_queries()` fewer reference
  points (typically not more than 100K) evenly distributed over the
  input primitives.

\section aabb_tree_impl Implementation Details

The AABB tree construction is initialized by computing the AABB of the
whole set of input primitives. All primitives are then sorted along
the longest coordinate axis of this box, and the primitives are
separated into two equal size sets. This procedure is applied
recursively until an AABB contains a single primitive. The tree is
leafless as presented in `OPCODE` \cgalCite{cgal:t-ocdl-05}\. An
intersection query traverses the tree by computing intersection tests
only with respect to the AABBs during traversal, and with respect to
the input primitives at the end of traversal (in the leafs of the
tree).

The reference id is not used internally but simply used by the AABB
tree to refer to the primitive in the results provided to the user. It
follows that, while in most cases each reference id corresponds to a
unique primitive, this is not a requirement of the component. This way
a user may use these reference ids as labels, each of them being
shared by several geometric objects.

A distance query between a query point `q` and the input primitives is
turned into a *ball* query centered at `q`. The ball traverses the
tree while recursively querying intersections with the AABBs, and
computes the closest point `p` from the query point to the input
primitives at the leafs of the tree. The ball radius is then shrunk to
the distance between `p` and `q` for all remaining recursive
traversals of the tree. Efficiency is achieved through setting the
initial ball radius to a small value still guaranteed to intersect the
input primitives. This is achieved by constructing an internal secondary data
structure which provides a good hint to the algorithm at the beginning
of the traversal (done by default).
Calling `AABB_tree::do_not_accelerate_distance_queries()` will disable
the construction and the usage of this internal secondary data structure.

\section aabb_tree_history Design and Implementation History

Camille Wormser and Pierre Alliez started working on a data structure
for efficient collision detection in 2007. The generic design for
implementing both intersection and distance queries, and for generic
queries and primitives was developed by Camille Wormser. In 2009,
Pierre Alliez, Stéphane Tayeb and Camille Wormser made the
implementation CGAL-compliant, with the help of Laurent Rineau for
optimizing the tree construction. Additionally, Andreas
Fabri, Jane Tournois, Mariette Yvinec and Sylvain Lefèbvre are
given thanks for helpful comments and discussions during that period.
Later, Sébastien Loriot contributed several improvements:
thread-safe queries, introduction of shared data stored in the traits
for lighter primitive types, ...
In 2024, the package was made compatible with 2D and 3D primitives by
Andreas Fabri, Sébastien Loriot, and Sven Oesau.
In 2026, the package was extended to support the intersection of two AABB trees.
This work also introduced performance optimizations and parallelization, contributed by Leo Valque.

*/

}

---

### AABB Tree Doc AABB Tree Examples (`AABB_tree/doc/AABB_tree/examples.txt`)

/*!
\example AABB_tree/AABB_custom_example.cpp
\example AABB_tree/AABB_custom_indexed_triangle_set_array_example.cpp
\example AABB_tree/AABB_custom_indexed_triangle_set_example.cpp
\example AABB_tree/AABB_custom_triangle_soup_example.cpp
\example AABB_tree/AABB_insertion_example.cpp
\example AABB_tree/AABB_polyhedron_edge_example.cpp
\example AABB_tree/AABB_polyhedron_facet_distance_example.cpp
\example AABB_tree/AABB_polyhedron_facet_intersection_example.cpp
\example AABB_tree/AABB_polyline_segment_2_example.cpp
\example AABB_tree/AABB_segment_3_example.cpp
\example AABB_tree/AABB_segment_2_example.cpp
\example AABB_tree/AABB_ray_shooting_example.cpp
\example AABB_tree/AABB_indexed_triangle_2_example.cpp
\example AABB_tree/AABB_triangle_2_example.cpp
\example AABB_tree/AABB_triangle_3_example.cpp
\example AABB_tree/AABB_halfedge_graph_edge_example.cpp
\example AABB_tree/AABB_face_graph_triangle_example.cpp
\example AABB_tree/AABB_intersection_example.cpp
*/

---

### Advancing Front Surface Reconstruction Doc Advancing Front Surface Reconstruction Advancing Front Surface Reconstruction (`Advancing_front_surface_reconstruction/doc/Advancing_front_surface_reconstruction/Advancing_front_surface_reconstruction.txt`)

namespace CGAL {
/*!

\mainpage User Manual
\anchor Chapter_Advancing_Front_Surface_Reconstruction
\anchor I1ChapterAdvancingFrontSurfaceReconstruction
\cgalAutoToc
\author Tran Kai Frank Da and David Cohen-Steiner

Surface reconstruction from an unstructured point cloud amounts to
generate a plausible surface that approximates well the input
points. This problem is ill-posed as many surfaces can be generated. A
wide range of approaches have been proposed to tackle this
problem. Among them are variational methods
\cgalCite{s-lsm-96}\cgalCite{zomk-insru-00}, tensor voting
\cgalCite{cgal:ml-cfsg-00}, implicit surface
\cgalCite{hddhjmss-pssr-94}\cgalCite{bc-ssrnn-00}, and Delaunay
triangulations.

For Delaunay based algorithms the output surface is commonly generated
as the union of some triangles selected in the 3D Delaunay
triangulation of the input points. Such algorithms are either
volume-based by generating as output the boundary of selected
tetrahedra \cgalCite{abe-cbscc-97}\cgalCite{ack-pcubm-01},
or surface-based by selecting a set of triangles.


In most surface based Delaunay algorithms the triangles are
selected independently, that is in parallel \cgalCite{agj-lcsr-00}\cgalCite{ab-srvf-98}.

This chapter presents a surface-based Delaunay surface
reconstruction algorithm that sequentially selects the triangles, that
is it uses previously selected triangles to select a new triangle for
advancing the front. At each advancing step the most plausible
triangle is selected, and such that the triangles selected
generates an orientable manifold triangulated surface.

Two other examples of this greedy approach are the ball pivoting
algorithm and Boyer-Petitjean's algorithm \cgalCite{bmrst-bpasr-99}\cgalCite{pb-rnrps-01}. In both algorithms
a triangulated surface is incrementally grown starting from a seed
triangle. Ball pivoting is fast, but the quality of the reconstruction
depends on user defined parameters corresponding to the sampling
density. The Boyer-Petitjean approach can handle non-uniform sampling,
but fails when near co-circular points are encountered, and it does
not provide any guarantee on the topology of the surface.

We describe next the algorithm and provide examples.

\note A \ref tuto_reconstruction "detailed tutorial on surface reconstruction"
is provided with a guide to choose the most appropriate method along
with pre- and postprocessing.

\section AFSR_Definitions Definitions and the Algorithm

A detailed description of the algorithm and the underlying theory are provided
in \cgalCite{cgal:csd-gdbsra-04}.

The first step of the algorithm is the construction of a 3D Delaunay
triangulation of the point set.
The radius of a triangle \f$ t \f$ is the radius of the smallest sphere
passing through the vertices of \f$ t\f$ and enclosing no sample
point. In other words, the radius \f$ r_t\f$ is the distance from any
vertex of \f$ t\f$ to the Voronoi edge dual to \f$ t\f$. This triangle with
three boundary edges is the initial triangulated surface, and its
boundary is the advancing front.
The Delaunay triangle with the smallest radius is the starting point
for the greedy algorithm.

The algorithm maintains a priority queue of candidate triangles, that
is of valid triangles incident to the boundary edges of the current
surface. The priority is the plausibility. While the priority queue is
not empty, the algorithm pops from the queue the most plausible
candidate triangle and adds it to the surface. New candidate triangles
are pushed to the priority queue when new boundary edges appear on the
advancing front. As the algorithm creates a two-manifold surface some
candidate triangles can not be selected due to topological constraints
which are explained next.


\subsection AFSR_Topology Topological Constraints

Any triangle \f$t\f$ considered as the next potential candidate shares an
edge \f$e\f$ with the front of the current reconstruction. Let \f$b\f$
be the vertex of \f$t\f$ opposite to \f$e\f$. There are four
configurations where \f$t\f$ is added to the surface.

- extension,  if \f$b\f$ is not yet on the surface.
- hole filling, if \f$b\f$ is on the front and both neighbors of \f$b\f$ on the front are on edge \f$e\f$.
- ear filling, if \f$b\f$ is on the front and one neighbor of \f$b\f$ on the front is on edge \f$e\f$.
- glueing, if \f$b\f$ is on the front and no neighbor of \f$b\f$ on the front is on edge \f$e\f$.

\cgalFigureBegin{figAFSRvalid,valid.png}
Valid candidates.
\cgalFigureEnd

While the first three operations never induce a non-manifold edge or vertex,
we only can perform gluing, if triangle \f$t\f$ has a *twin* facet, that is a
triangle with an edge on the front and incident to \f$b\f$, and the
third vertex on edge \f$e\f$.

A triangle is said  *valid* when the above operations can be applied.

\subsection AFSR_Selection Plausibility of a Candidate Triangle

Valid triangles for an edge on the front are compared through their
radius. While the radius is a good criterion in the case of 2D smooth
curve reconstruction \cgalCite{b-cccda-94}, we need another criterion
for 3D surface reconstruction, namely the dihedral angle between
triangles on the surface, that is the angle between the normals of the
triangles. There are three bounds namely \f$ \alpha_\mathrm{sliver} \f$,
\f$ \beta \f$, and \f$ \delta \f$.

The *candidate* triangle of an edge \f$ e \f$ is the triangle
with the smallest radius:
- that is valid for \f$ e \f$, and
- that has \f$ \beta_t < \alpha_\mathrm{sliver} \f$, and
- that has its internal angles with \f$ e \f$ smaller than \f$ \delta \f$.

There may be no such triangle. In the implementation
of the algorithm \f$ \alpha_\mathrm{sliver} \f$ and \f$ \delta\f$ are equal
to \f$ 5\pi/6 \f$.


We denote by \f$ \beta_t\f$ the angle between the normal of a triangle
\f$ t\f$ incident on a boundary edge \f$ e \f$ and the normal of the
triangle on the surface incident to \f$ e \f$.


We define the *plausibility* grade \f$ p(t) \f$ as \f$ 1/r_t \f$, if
\f$ \beta_t < \beta \f$, and \f$ -\beta_t \f$ else.  The parameter \f$
\beta \f$ can be specified by the user and is set by default to \f$ \pi/6\f$.

Let's have a look at the figure below.
\cgalFigureBegin{figAFSRplausible,wedges.png}
Plausibility. Triangle ``t'`` and incident triangles sharing edge `e` seen from the side.
\cgalFigureEnd

 \f$ \alpha_\mathrm{sliver}\f$ corresponds to the red wedge. The algorithm will never select triangle `t1`
even if it is the only candidate triangle.

\f$\beta\f$ corresponds to the green wedge. If there is a candidate triangle in this zone,
the one with the smallest radius is the most plausible.

If there is no candidate triangle in the green wedge, the triangle with the smallest
angle between its normal and the normal of ``t'`` is chosen.  In the figure above
this would be triangle `t4`.

\subsection AFSR_Boundaries Dealing with Multiple Components, Boundaries and Sharp Edges

By construction the output of the algorithm is a connected orientable
manifold with or without boundary. To cope with multiple components we
merely look for a new seed facet among facets disjoint from the
surface. In case of noisy data or outliers, the user must filter out
small surface components.

It is impossible to handle all kinds of boundaries and non uniform sampling
at the same time, as a void can either be an undersampled area of the surface,
or a hole.

As we do not want the algorithm to rely on a uniformity condition on
the sampling it will fill holes cut off from "flat" regions of the
surface. However, in many cases a boundary component cannot be closed
by adding a spanning disk such that the resulting disk is well
sampled. Typically, closing a boundary component due to a transversal
clipping of the operation, would yield large dihedral angles at
boundary edges. Moreover, if the boundary is sufficiently well
sampled, the radii of the two triangles incident on a boundary edge
would be very different.  These heuristic facts can be used for
boundary detection.

More specifically, we discard any candidate triangle \f$ t \f$, for an edge \f$ e \f$
such that \f$ p(t) < 0\f$, and \f$ r_t > \mathrm{radius\_ratio\_bound} \times r_{t'}\f$ where \f$ t'\f$ is
the triangle on the surface incident on \f$ e \f$. The parameter \f$\mathrm{radius\_ratio\_bound}\f$
is specified by the user and is set by default to 5.

For the example given in  \cgalFigureRef{figAFSRplausible}, we said that if there
was no triangle `t3` in the green wedge, triangle `t4` would be chosen as it has
the smallest angle between its normal and the normal of triangle ``t'``.
However, in case its radius was \f$\mathrm{radius\_ratio\_bound}\f$ times larger than the radius of triangle ``t'``,
triangle `t2` would be chosen, assuming that its radius is not  \f$\mathrm{radius\_ratio\_bound}\f$ times larger.


Note that this heuristic implies that
where the sampling is too sparse with respect to curvature, it must
be sufficiently uniform for our algorithm to work.


\section AFSR_Examples Examples

The first of the following three examples presents a free function for doing surface
reconstruction. For a sequence of points the function produces a sequence
of triplets of indices describing the triangles of the surface.
The second example presents a class that enables to traverse the
surface represented in a 2D triangulation data structure where
the faces are connected with the facets of underlying 3D Delaunay triangulation.
The third example shows how to get outliers and the boundaries of
the surface. The last example shows how to combine this algorithm with
two \cgal algorithms in order to reconstruct surfaces with sharp
features.

\subsection AFSR_Example_function Examples for Global Function

The global function `advancing_front_surface_reconstruction()`
takes an iterator range of points as input and writes for each face of the
reconstructed surface a triplet of point indices into an output iterator.
The following example writes the output triangulated surface to `std::cout`
in accordance to the OFF format.

The function has an overload with an additional argument that allows
to choose how to prioritize facets. It can be written in a way to
avoid the generation of triangles with a perimeter larger than a given
bound.

\cgalExample{Advancing_front_surface_reconstruction/reconstruction_fct.cpp}


While the first example just writes index triples, the second example
uses as output iterator a wrapper around a reference to a `Surface_mesh`
and calls the function `add_face()`.

\cgalExample{Advancing_front_surface_reconstruction/reconstruction_surface_mesh.cpp}


\subsection AFSR_Example_class Example for the Reconstruction Class

The class `Advancing_front_surface_reconstruction` provides
access to a 2D triangulation data structure describing the output surface.
The latter can be explored by hopping from a face to its neighboring faces,
and by hopping from faces of the 2D triangulation data structure to
corresponding facets of the underlying 3D Delaunay triangulation.

The type of the 2D triangulation data structure describing the
reconstructed surface is the nested type
\link Advancing_front_surface_reconstruction::Triangulation_data_structure_2 `Advancing_front_surface_reconstruction::Triangulation_data_structure_2`\endlink.

The type `Advancing_front_surface_reconstruction::Triangulation_data_structure_2::Vertex` is model of the
concept `TriangulationDataStructure_2::Vertex` and has additionally
the method `vertex_3()` that returns an `Advancing_front_surface_reconstruction::Vertex_handle` to the
associated 3D vertex.

 The type `Advancing_front_surface_reconstruction::Triangulation_data_structure_2::Face` is model of the concept
`TriangulationDataStructure_2::Face` and has additionally the method
`facet()` that returns the associated `Advancing_front_surface_reconstruction::Facet`,
and a method `is_on_surface()` for testing if a face is part of the reconstructed
surface.

In case the surface
has boundaries, the 2D surface has one vertex which is associated to
the infinite vertex of the 3D triangulation.


The underlying 3D Delaunay triangulation can be accessed as well,
using the API of the class `Delaunay_triangulation_3`.

The following example writes the surface to `std::cout` in accordance
to the STL (Stereo Lithography) format.

\cgalExample{Advancing_front_surface_reconstruction/reconstruction_class.cpp}


\subsection AFSR_Example_boundaries Example for Outliers and Boundaries

Input points which are not on
a surface are outliers. The member function \link Advancing_front_surface_reconstruction::outliers() `outliers()`\endlink
returns an iterator range of those points.

Boundary edges can be traversed with the member function \link Advancing_front_surface_reconstruction::boundaries() `boundaries()`\endlink
It returns an iterator range type \link Advancing_front_surface_reconstruction::Boundary_range `Boundary_range`\endlink whose iterators have the value type
\link Advancing_front_surface_reconstruction::Vertex_on_boundary_range `Vertex_on_boundary_range`\endlink.  This is again an iterator range whose iterators have the value type
\link Advancing_front_surface_reconstruction::Vertex_handle `Vertex_handle`\endlink.

\cgalExample{Advancing_front_surface_reconstruction/boundaries.cpp}

\subsection AFSR_Example_sharp_features Example for Sharp Features

The priority queue used by the advancing front surface reconstruction
algorithm can be modified to achieve robustness to sharp edges and
provide piecewise-planar or hybrid reconstruction as described in
\cgalCite{cgal:la-srpss-13}. Two other algorithms available in \cgal
must be applied first as a preprocessing to the point set:

- \ref Chapter_Shape_Detection "Shape detection": detect planar sections of the input.

- \ref Point_set_processing_3Structuring "Point set structuring":
resample the planar sections and edges and corners detected among
them.

\cgalFigureBegin{figAFSRstruct,structured_example.png}
Comparison of advancing front output.

- Top: input point set and raw advancing front reconstruction

- Bottom: structured point set and advancing front reconstruction with
structure-dependent priority functor

\cgalFigureEnd

The quality of the reconstruction can be significantly improved thanks
to point set structuring when dealing with shapes with sharp features,
as shown on the previous figure. The following example shows how to
define a priority functor that favors structurally coherent facets and
makes the advancing front algorithm robust to sharp features.


\cgalExample{Advancing_front_surface_reconstruction/reconstruction_structured.cpp}





*/
} /* namespace CGAL */

---

### Advancing Front Surface Reconstruction Doc Advancing Front Surface Reconstruction PackageDescription (`Advancing_front_surface_reconstruction/doc/Advancing_front_surface_reconstruction/PackageDescription.txt`)

/// \defgroup PkgAdvancingFrontSurfaceReconstructionRef Reference Manual

/// \defgroup PkgAdvancingFrontSurfaceReconstructionRefConcepts Concepts
/// \ingroup PkgAdvancingFrontSurfaceReconstructionRef

/*!
\addtogroup PkgAdvancingFrontSurfaceReconstructionRef

\cgalPkgDescriptionBegin{Advancing Front Surface Reconstruction,PkgAdvancingFrontSurfaceReconstruction}
\cgalPkgPicture{afsr-detail.png}
\cgalPkgSummaryBegin
\cgalPkgAuthors{Tran Kai Frank Da and David Cohen-Steiner}
\cgalPkgDesc{This package provides a greedy algorithm for surface reconstruction from an
unorganized point set. Starting from a seed facet, a piecewise linear
surface is grown by adding Delaunay triangles one by one. The most
plausible triangles are added first, in a way that avoids the appearance
of topological singularities. }
\cgalPkgManuals{Chapter_Advancing_Front_Surface_Reconstruction,PkgAdvancingFrontSurfaceReconstructionRef}
\cgalPkgSummaryEnd
\cgalPkgShortInfoBegin
\cgalPkgSince{4.7}
\cgalPkgDependsOn{\ref PkgTriangulation3}
\cgalPkgBib{cgal:dc-afsr}
\cgalPkgLicense{\ref licensesGPL  "GPL"}
\cgalPkgShortInfoEnd
\cgalPkgDescriptionEnd


\cgalClassifedRefPages

\cgalCRPSection{Concepts}

- `AdvancingFrontSurfaceReconstructionTraits_3`

\cgalCRPSection{Classes}

- `CGAL::Advancing_front_surface_reconstruction`
- `CGAL::Advancing_front_surface_reconstruction_vertex_base_3`
- `CGAL::Advancing_front_surface_reconstruction_cell_base_3`

\cgalCRPSection{Functions}

- `CGAL::advancing_front_surface_reconstruction()`

*/

---

### Advancing Front Surface Reconstruction Doc Advancing Front Surface Reconstruction Examples (`Advancing_front_surface_reconstruction/doc/Advancing_front_surface_reconstruction/examples.txt`)

/*!
\example Advancing_front_surface_reconstruction/reconstruction_fct.cpp
\example Advancing_front_surface_reconstruction/reconstruction_class.cpp
\example Advancing_front_surface_reconstruction/reconstruction_surface_mesh.cpp
\example Advancing_front_surface_reconstruction/boundaries.cpp
\example Advancing_front_surface_reconstruction/reconstruction_structured.cpp
*/

---

### Algebraic Foundations Doc Algebraic Foundations Algebraic Foundations (`Algebraic_foundations/doc/Algebraic_foundations/Algebraic_foundations.txt`)

namespace CGAL {
/*!

\mainpage User Manual
\anchor Chapter_Algebraic_Foundations

\cgalAutoToc
\author Michael Hemmer

\section Algebraic_foundationsIntroduction Introduction

\cgal is targeting towards exact computation with non-linear objects,
in particular objects defined on algebraic curves and surfaces.
As a consequence types representing polynomials, algebraic extensions and
finite fields play a more important role in related implementations.
This package has been introduced to stay abreast of these changes.
Since in particular polynomials must be supported by the introduced framework
the package avoids the term <I>number type</I>. Instead, the package distinguishes
between the <I>algebraic structure</I> of a type and whether a type is embeddable on
the real axis, or <I>real embeddable</I> for short.
Moreover, the package introduces the notion of <I>interoperable</I> types which
allows an explicit handling of mixed operations.

\section Algebraic_foundationsAlgebraic Algebraic Structures

The algebraic structure concepts introduced within this section are
motivated by their well-known counterparts in traditional algebra,
but we also had to pay tribute to existing types and their restrictions.
To keep the interface minimal,
it was not desirable to cover all known algebraic structures,
e.g., we did not introduce concepts for such basic structures as <I>groups</I> or
exceptional structures as <I>skew fields</I>.

\cgalFigureBegin{figConceptHierarchyOfAlgebraicStructures,AlgebraicConceptHierarchy.png}
Concept Hierarchy of Algebraic Structures
\cgalFigureEnd

\cgalFigureRef{figConceptHierarchyOfAlgebraicStructures} shows the refinement
relationship of the algebraic structure concepts.
`IntegralDomain`, `UniqueFactorizationDomain`, `EuclideanRing` and
`Field` correspond to the algebraic structures with the
same name. `FieldWithSqrt`, `FieldWithKthRoot` and
`FieldWithRootOf` are fields that in addition are closed under
the operations 'sqrt', 'k-th root' and 'real root of a polynomial',
respectively. The concept `IntegralDomainWithoutDivision` also
corresponds to integral domains in the algebraic sense, the
distinction results from the fact that some implementations of
integral domains lack the (algebraically always well-defined) integral
division.
Note that `Field` refines `IntegralDomain`. This is because
most ring-theoretic notions like greatest common divisors become trivial for
`Field`s. Hence, we see `Field` as a refinement of
`IntegralDomain` and not as a
refinement of one of the more advanced ring concepts.
If an algorithm wants to rely on gcd or remainder computation, it is trying
to do things it should not do with a `Field` in the first place.

The main properties of an algebraic structure are collected in the class
`Algebraic_structure_traits`.
In particular the (most refined) concept each concrete model `AS`
fulfills is encoded in the tag
\link AlgebraicStructureTraits::Algebraic_category `Algebraic_structure_traits<AS>::Algebraic_category` \endlink .
An algebraic structure is at least `Assignable`,
`CopyConstructible`, `DefaultConstructible` and
`EqualityComparable`. Moreover, we require that it is
constructible from `int`.
For ease of use and since their semantic is sufficiently standard to presume
their existence, the usual arithmetic and comparison operators are required
to be realized via \cpp operator overloading.
The division operator is reserved for division in fields.
All other unary (e.g., sqrt) and binary functions
(e.g., gcd, div) must be models of the well-known \stl-concepts
`AdaptableUnaryFunction` or `AdaptableBinaryFunction`
concept and local to the traits class
(e.g., \link AlgebraicStructureTraits::Sqrt `Algebraic_structure_traits<AS>::Sqrt()(x)` \endlink).
This design allows us to profit from all parts in the
\stl and its programming style and avoids the name-lookup and
two-pass template compilation problems experienced with the old design
using overloaded functions. However, for ease of use and backward
compatibility all functionality is also
accessible through global functions defined within namespace `CGAL`,
e.g., \link sqrt `CGAL::sqrt(x)` \endlink. This is realized via function templates using
the according functor of the traits class. For an overview see the section "Global Functions" in the
\ref PkgAlgebraicFoundationsRef.

\subsection Algebraic_foundationsTagsinAlgebraicStructure Tags in Algebraic Structure Traits

\subsubsection Algebraic_foundationsAlgebraicCategory Algebraic Category

For a type `AS`, `Algebraic_structure_traits<AS>`
provides several tags. The most important tag is the `Algebraic_category`
tag, which indicates the most refined algebraic concept the type `AS`
fulfills. The tag is one of;
`Integral_domain_without_division_tag`, `Integral_domain_tag`,
`Field_tag`, `Field_with_sqrt_tag`, `Field_with_kth_root_tag`,
`Field_with_root_of_tag`, `Unique_factorization_domain_tag`,
`Euclidean_ring_tag`, or even `Null_tag`
in case the type is not a model of an algebraic structure concept.
The tags are derived from each other such that they reflect the
hierarchy of the algebraic structure concept, e.g.,
`Field_with_sqrt_tag` is derived from `Field_tag`.

\subsubsection Algebraic_foundationsExactandNumericalSensitive Exact and Numerical Sensitive

Moreover, `Algebraic_structure_traits<AS>` provides the tags `Is_exact`
and `Is_numerical_sensitive`, which are both `Boolean_tag`s.

An algebraic structure is considered <I>exact</I>,
if all operations required by its concept are computed such that a comparison
of two algebraic expressions is always correct.

An algebraic structure is considered as <I>numerically sensitive</I>,
if the performance of the type is sensitive to the condition number of an
algorithm.
Note that there is really a difference among these two notions,
e.g., the fundamental type `int` is not numerical sensitive but
considered inexact due to overflow.
Conversely, types as `leda_real` or `CORE::Expr` are exact but sensitive
to numerical issues due to the internal use of multi precision floating point
arithmetic. We expect that `Is_numerical_sensitive` is used for dispatching
of algorithms, while `Is_exact` is useful to enable assertions that can be
checked for exact types only.

Tags are very useful to dispatch between alternative implementations.
The following example illustrates a dispatch for `Field`s using overloaded
functions. The example only needs two overloads since the algebraic
category tags reflect the algebraic structure hierarchy.

\cgalExample{Algebraic_foundations/algebraic_structure_dispatch.cpp}

\section Algebraic_foundationsRealE Real Embeddable

\anchor secRealEmbeddable

Most number types represent some subset of the real numbers. From those types
we expect functionality to compute the sign, absolute value or double
approximations. In particular, we can expect an order on such a type that
reflects the order along the real axis.
All these properties are gathered in the concept `::RealEmbeddable`.
The concept is orthogonal to the algebraic structure concepts,
i.e., it is possible
that a type is a model of `RealEmbeddable` only,
since the type may just represent values on the real axis
but does not provide any arithmetic operations.

As for algebraic structures this concept is also traits class oriented.
The main functionality related to `RealEmbeddable` is gathered in
the class `Real_embeddable_traits`. In particular, it provides the boolean
tag `Is_real_embeddable` indicating whether a type is a model of
`RealEmbeddable`. The comparison operators are required to be realized via
\cpp operator overloading.
All unary functions (e.g. <I>sign</I>, <I>to_double</I>) and
binary functions (e.g. <I>compare</I> ) are models of the \stl-concepts
`AdaptableUnaryFunction` and `AdaptableBinaryFunction` and are local
to `Real_embeddable_traits`.

In case a type is a model of `IntegralDomainWithoutDivision` and
`RealEmbeddable` the number represented by an object of this type is
the same for arithmetic and comparison.
It follows that the ring represented by this type is a superset of the integers
and a subset of the real numbers and hence has characteristic zero.

In case the type is a model of `Field` and `RealEmbeddable` it is a
superset of the rational numbers.

\section Algebraic_foundationsRealN Real Number Types

Every \cgal `Kernel` comes with two <I>real number types</I>
(number types embeddable into the real numbers). One of them is a
`FieldNumberType`, and the other a `RingNumberType`. The
coordinates of the basic kernel objects (points, vectors, etc.) come
from one of these types (the `FieldNumberType` in case of %Cartesian
kernels, and the `RingNumberType` for %Homogeneous kernels).

The concept `FieldNumberType` combines the requirements of the
concepts `Field` and `RealEmbeddable`, while
`RingNumberType` combines `IntegralDomainWithoutDivision` and
`RealEmbeddable`. Algebraically, the real number types do not form
distinct structures and are therefore not listed in the concept
hierarchy of \cgalFigureRef{figConceptHierarchyOfAlgebraicStructures}.

\section Algebraic_foundationsInteroperability Interoperability

This section introduces two concepts for interoperability of types,
namely `ImplicitInteroperable` and `ExplicitInteroperable`. While
`ExplicitInteroperable` is the base concept, we start with
`ImplicitInteroperable` since it is the more intuitive one.

In general mixed operations are provided by overloaded operators and
functions or just via implicit constructor calls.
This level of interoperability is reflected by the concept
`ImplicitInteroperable`. However, within template code the result type,
or so-called coercion type, of a mixed arithmetic operation may be unclear.
Therefore, the package introduces `Coercion_traits`
giving access to the coercion type via \link Coercion_traits::Type `Coercion_traits<A,B>::Type` \endlink
for two interoperable types `A` and `B`.

Some trivial examples are `int` and `double` with coercion type double
or `Gmpz` and `Gmpq` with coercion type `Gmpq`.
However, the coercion type is not necessarily one of the input types,
e.g. the coercion type of a polynomial
with integer coefficients that is multiplied by a rational type
is supposed to be a polynomial with rational coefficients.

`Coercion_traits` is also
required to provide a functor \link Coercion_traits::Cast `Coercion_traits<A,B>::Cast()` \endlink, that
converts from an input type into the coercion type. This is in fact the core
of the more basic concept `ExplicitInteroperable`.
`ExplicitInteroperable` has been introduced to cover more complex cases
for which it is hard or impossible to guarantee implicit interoperability.
Note that this functor can be useful for `ImplicitInteroperable` types
as well, since it can be used to void redundant type conversions.

In case two types `A` and `B` are `ExplicitInteroperable` with
coercion type `C` they are valid argument types for all binary functors
provided by `Algebraic_structure_traits` and `Real_embeddable_traits` of
`C`. This is also true for the according global functions.

\subsection Algebraic_foundationsExamples Examples

The following example illustrates how two write code for
`ExplicitInteroperable` types.

\cgalExample{Algebraic_foundations/interoperable.cpp}

The following example illustrates a dispatch for `ImplicitInteroperable` and
`ExplicitInteroperable` types.
The binary function (that just multiplies its two arguments) is supposed to
take two `ExplicitInteroperable` arguments. For `ImplicitInteroperable`
types a variant that avoids the explicit cast is selected.

\cgalExample{Algebraic_foundations/implicit_interoperable_dispatch.cpp}

\section Algebraic_foundationsFractions Fractions

Beyond the need for performing algebraic operations on objects as a
whole, there are also number types which one would like to decompose into
numerator and denominator. This does not only hold for rational numbers
as `Quotient`, `Gmpq`, `mpq_class` or `leda_rational`, but
also for compound objects as `Sqrt_extension` or `Polynomial`
which may decompose into a (scalar)
denominator and a compound numerator with a simpler coefficient type
(e.g. integer instead of rational). Often operations can be performed faster on
these denominator-free multiples. In case a type is a `Fraction`
the relevant functionality as well as the numerator and denominator
type are provided by `Fraction_traits`. In particular
`Fraction_traits` provides a tag \link FractionTraits::Is_fraction `Is_fraction` \endlink that can be
used for dispatching.

A related class is `Rational_traits` which has been kept for backward
compatibility reasons. However, we recommend to use `Fraction_traits` since
it is more general and offers dispatching functionality.

\subsection Algebraic_foundationsExamples_1 Examples

The following example show a simple use of `Fraction_traits`:
\cgalExample{Algebraic_foundations/fraction_traits.cpp}

The following example illustrates the integralization of a vector,
i.e., the coefficient vector of a polynomial. Note that for minimizing
coefficient growth \link FractionTraits::Common_factor `Fraction_traits<Type>::Common_factor` \endlink is used to
compute the <i>least</i> common multiple of the denominators.

\cgalExample{Algebraic_foundations/integralize.cpp}

\section Algebraic_foundationsDesign Design and Implementation History

The package is part of \cgal since release 3.3. Of course the package is based
on the former Number type support of CGAL. This goes back to Stefan Schirra and Andreas Fabri. But on the other hand the package is to a large extend influenced
by the experience with the number type support in \exacus \cgalCite{beh-eeeafcs-05},
which in the main goes back to
Lutz Kettner, Susan Hert, Arno Eigenwillig, and Michael Hemmer.
However, the package abstracts from the pure support for
number types that are embedded on the real axis which allows the support of
polynomials, finite fields, and algebraic extensions as well. See also related
subsequent chapters.

*/
} /* namespace CGAL */

---

### Algebraic Foundations Doc Algebraic Foundations PackageDescription (`Algebraic_foundations/doc/Algebraic_foundations/PackageDescription.txt`)

/// \defgroup PkgAlgebraicFoundationsRef Reference Manual

/// \defgroup PkgAlgebraicFoundationsAlgebraicStructuresConcepts Concepts
/// \ingroup PkgAlgebraicFoundationsRef

/*!
\addtogroup PkgAlgebraicFoundationsRef

\cgalPkgDescriptionBegin{Algebraic Foundations,PkgAlgebraicFoundations}
\cgalPkgPicture{Algebraic_foundations2.png}
\cgalPkgSummaryBegin
\cgalPkgAuthor{Michael Hemmer}
\cgalPkgDesc{This package defines what algebra means for \cgal, in terms of concepts, classes and functions. The main features are: (i) explicit concepts for interoperability of types  (ii) separation between algebraic types (not necessarily embeddable into the reals), and number types (embeddable into the reals).}
\cgalPkgManuals{Chapter_Algebraic_Foundations,PkgAlgebraicFoundationsRef}
\cgalPkgSummaryEnd
\cgalPkgShortInfoBegin
\cgalPkgSince{3.3}
\cgalPkgBib{cgal:h-af}
\cgalPkgLicense{\ref licensesLGPL "LGPL"}
\cgalPkgShortInfoEnd
\cgalPkgDescriptionEnd

\cgalClassifedRefPages

\cgalCRPSection{Algebraic Structures}

\cgalCRPSubsection{Concepts}

- `IntegralDomainWithoutDivision`
- `IntegralDomain`
- `UniqueFactorizationDomain`
- `EuclideanRing`
- `Field`
- `FieldWithSqrt`
- `FieldWithKthRoot`
- `FieldWithRootOf`

- `AlgebraicStructureTraits`
- `AlgebraicStructureTraits_::IsZero`
- `AlgebraicStructureTraits_::IsOne`
- `AlgebraicStructureTraits_::Square`
- `AlgebraicStructureTraits_::Simplify`
- `AlgebraicStructureTraits_::UnitPart`
- `AlgebraicStructureTraits_::IntegralDivision`
- `AlgebraicStructureTraits_::Divides`
- `AlgebraicStructureTraits_::Gcd`
- `AlgebraicStructureTraits_::DivMod`
- `AlgebraicStructureTraits_::Div`
- `AlgebraicStructureTraits_::Mod`
- `AlgebraicStructureTraits_::Inverse`
- `AlgebraicStructureTraits_::Sqrt`
- `AlgebraicStructureTraits_::IsSquare`
- `AlgebraicStructureTraits_::KthRoot`
- `AlgebraicStructureTraits_::RootOf`

\cgalCRPSubsection{Classes}

- `CGAL::Algebraic_structure_traits<T>`
- `CGAL::Integral_domain_without_division_tag`
- `CGAL::Integral_domain_tag`
- `CGAL::Field_tag`
- `CGAL::Field_with_sqrt_tag`
- `CGAL::Unique_factorization_domain_tag`
- `CGAL::Euclidean_ring_tag`

\cgalCRPSubsection{Global Functions}

- `CGAL::is_zero()`
- `CGAL::is_one()`
- `CGAL::square()`
- `CGAL::simplify()`
- `CGAL::unit_part()`
- `CGAL::integral_division()`
- `CGAL::is_square()`
- `CGAL::gcd()`
- `CGAL::div_mod()`
- `CGAL::div()`
- `CGAL::mod()`
- `CGAL::inverse()`
- `CGAL::sqrt()`
- `CGAL::kth_root()`
- `CGAL::root_of()`

\cgalCRPSection{Real Embeddable}

\cgalCRPSubsection{Concepts}

- `RealEmbeddable`

- `RealEmbeddableTraits`
- `RealEmbeddableTraits_::IsZero`
- `RealEmbeddableTraits_::Abs`
- `RealEmbeddableTraits_::Sgn`
- `RealEmbeddableTraits_::IsPositive`
- `RealEmbeddableTraits_::IsNegative`
- `RealEmbeddableTraits_::Compare`
- `RealEmbeddableTraits_::ToDouble`
- `RealEmbeddableTraits_::ToInterval`

\cgalCRPSubsection{Classes}

- `CGAL::Real_embeddable_traits<T>`

\cgalCRPSubsection{Global Functions}

- `CGAL::is_zero()`
- `CGAL::abs()`
- `CGAL::sign()`
- `CGAL::is_positive()`
- `CGAL::is_negative()`
- `CGAL::compare()`
- `CGAL::to_double()`
- `CGAL::to_interval()`

\cgalCRPSection{Real Number Types}

\cgalCRPSubsection{Concepts}

- `RingNumberType`
- `FieldNumberType`

\cgalCRPSection{Interoperability}

\cgalCRPSubsection{Concepts}

- `ExplicitInteroperable`
- `ImplicitInteroperable`

\cgalCRPSubsection{Classes}

- `CGAL::Coercion_traits<A,B>`

\cgalCRPSection{Fractions}

\cgalCRPSubsection{Concepts}

- `Fraction`
- `FractionTraits`
- `FractionTraits_::Decompose`
- `FractionTraits_::Compose`
- `FractionTraits_::CommonFactor`

\cgalCRPSubsection{Classes}

- `CGAL::Fraction_traits<T>`

\cgalCRPSection{Miscellaneous}

\cgalCRPSubsection{Concepts}
- `FromIntConstructible`
- `FromDoubleConstructible`

*/

---

### Algebraic Foundations Doc Algebraic Foundations Examples (`Algebraic_foundations/doc/Algebraic_foundations/examples.txt`)

/*!
\example Algebraic_foundations/algebraic_structure_dispatch.cpp
\example Algebraic_foundations/fraction_traits.cpp
\example Algebraic_foundations/implicit_interoperable_dispatch.cpp
\example Algebraic_foundations/integralize.cpp
\example Algebraic_foundations/interoperable.cpp
*/

---

### Algebraic Kernel D Doc Algebraic Kernel D Algebraic Kernel D (`Algebraic_kernel_d/doc/Algebraic_kernel_d/Algebraic_kernel_d.txt`)

namespace CGAL {
/*!

\mainpage User Manual
\anchor Chapter_Algebraic_Kernel
\anchor chapteralgebraickerneld
\cgalAutoToc
\authors Eric Berberich, Michael Hemmer, Michael Kerber, Sylvain Lazard, Luis Pe&ntilde;aranda, and Monique Teillaud

\section Algebraic_kernel_dIntroduction Introduction

Real solving of polynomials is a fundamental problem with a wide application range.
This package provides black-box implementations of
algorithms to determine, compare, and approximate real roots of univariate polynomials
and bivariate polynomial systems. Such a black-box is called an *Algebraic Kernel*.
Since this package is aimed at providing more than one implementation, the interface of
the algebraic kernels is expressed in concepts. The main concepts provided by this package are the
`AlgebraicKernel_d_1` for univariate polynomial systems and `AlgebraicKernel_d_2`
for bivariate polynomial systems, the latter being a refinement of the first.

\section Algebraic_kernel_dAlgebraic Algebraic Kernel Concepts

\subsection Algebraic_kernel_dUnivariateAlgebraicKernel Univariate Algebraic Kernel

\subsection Algebraic_kernel_dMajorTypes Major Types

First of all, the univariate algebraic kernel provides construction, comparison and
approximation of real roots of univariate polynomials.
Thus, the major public types the `AlgebraicKernel_d_1` provides are:

`AlgebraicKernel_d_1::Polynomial_1` - the type representing univariate polynomials,

`AlgebraicKernel_d_1::Coefficient` - the coefficient type of these polynomials,

`AlgebraicKernel_d_1::Algebraic_real_1` - the type representing real roots,

`AlgebraicKernel_d_1::Bound` - the type which is used to approximate these algebraic reals,
in particular, it is used to represent the boundaries of isolating intervals.

\subsection Algebraic_kernel_dConstructionofAlgebraic Construction of Algebraic Real Numbers

The kernel provides two different function objects to construct an
`AlgebraicKernel_d_1::Algebraic_real_1`. The most general way
is to use `AlgebraicKernel_d_1::Isolate_1`; The function object
takes a univariate polynomial and writes all real roots into a given
output iterator. It is also possible to retrieve the multiplicity of
each root. The second option is to construct one particular algebraic
real using `AlgebraicKernel_d_1::Construct_algebraic_real_1`.
This function object provides construction from the native int type, the
coefficient type as well as the bound type. Moreover, it is possible
to construct an algebraic real by giving a polynomial and either an
isolating interval or the index of the root. A related function object
is `AlgebraicKernel_d_1::Number_of_solutions_1` computing the number
of real roots of a polynomial.

\subsection Algebraic_kernel_dComparisonandApproximation Comparison and Approximation of Algebraic Real Numbers

An `AlgebraicKernel_d_1::Algebraic_real_1` is model of
`RealEmbeddable`, for instance, it is possible to compare two
algebraic reals, to determine the sign of an algebraic real or to ask
for its double approximation, see also section \ref secRealEmbeddable.
Moreover, `AlgebraicKernel_d_1::Compare_1` provides
comparison with int, the coefficient type and the bound type.

There are several ways to approximate an `AlgebraicKernel_d_1::Algebraic_real_1`:

`AlgebraicKernel_d_1::Approximate_absolute_1` - provides an approximation that is
better than the passed absolute error bound,

`AlgebraicKernel_d_1::Approximate_relative_1` - provides an approximation that is
better than the passed relative error bound,

`AlgebraicKernel_d_1::Isolate_1` - returns an isolating interval with respect to
a given univariate polynomial,

A related function object is `AlgebraicKernel_d_1::Bound_between_1`, which computes
a number that isolates two algebraic real numbers.

\subsection Algebraic_kernel_dInterplaywithPolynomials Interplay with Polynomials

It is also possible to retrieve a representing polynomial from an
algebraic real using `AlgebraicKernel_d_1::Compute_polynomial_1`,
which guarantees that the algebraic real is a root of the returned
polynomial. As the name already indicates, this operation may be very
costly since the polynomial may not be computed yet. Moreover, it is
not guaranteed that the returned polynomial is the minimal polynomial
of the number. Together with `AlgebraicKernel_d_1::Isolate_1`, it
is possible to retrieve the traditional representation of an algebraic
real as a square free polynomial and an isolating interval.

Though the `AlgebraicKernel_d_1` does not provide arithmetic
operations on `AlgebraicKernel_d_1::Algebraic_real_1`, it is
possible to compute the sign of a polynomial at a given algebraic
real using `AlgebraicKernel_d_1::Sign_at_1`. Or alternatively,
just compute whether the polynomial is zero at an algebraic real number
using `AlgebraicKernel_d_1::Is_zero_at_1`. Note that this operation
can be significantly less expensive, in particular if the polynomial
is not zero at the given algebraic real.

\subsection Algebraic_kernel_dAuxiliaryFunctionality Auxiliary Functionality for Polynomials

First of all the type `AlgebraicKernel_d_1::Polynomial_1` is required
to be a model of the concept `Polynomial_1`, which is defined
in the Polynomial package (see chapter \ref Chapter_Polynomial).
This implies that all essential functionality is provided via
`Polynomial_traits_d`. However, the algebraic kernel also
provides several function objects to handle polynomials:

`AlgebraicKernel_d_1::Is_square_free_1` - determines whether a polynomial is square free,

`AlgebraicKernel_d_1::Make_square_free_1` - computes the square free part of a polynomial,

`AlgebraicKernel_d_1::Square_free_factorize_1` - computes a square free factorization of a polynomial,

`AlgebraicKernel_d_1::Is_coprime_1` - computes whether a pair of polynomials is square free,

`AlgebraicKernel_d_1::Make_coprime_1` - decomposes two polynomials into the coprime factors and their common factor.

Though the polynomial package provides similar functionality we suggest to use
the function objects provided by the kernel, since the design of the algebraic kernel
allows for instance internal caching by the kernel.

Also note that `AlgebraicKernel_d_1::Square_free_factorize_1` only computes the square free
factorization up to a constant factor. This is a slight modification with respect to its
counterpart in `Polynomial_traits_d`. In this way it was possible that the concepts just require
the coefficient type to be a model of `IntegralDomain`, instead of `Field` or `UniqueFactorizationDomain`.
For more details see also:

- \ref PolynomialTraits_d::SquareFreeFactorize
- \ref PolynomialTraits_d::SquareFreeFactorizeUpToConstantFactor

\subsection Algebraic_kernel_dDesignRationale Design Rationale

Most implementations of an `AlgebraicKernel_d_1` will represent
an algebraic real number by the root of a square free polynomial and
an isolating interval, that is, the number is defined as the only
root of the polynomial within the interval. Usually, one will refrain
from computing the minimal polynomial since the computation of the
minimal polynomial is much more expensive and does not pay of. However,
besides the representation by a polynomial and an isolating interval
one can also imagine the representation by a polynomial and the index
of the root, e.g., as the \f$ i\f$th real root when enumerated from minus
to plus infinity. Moreover, it may very well be that the kernel just
computes an approximation of the number, whereas the representing
polynomial is not computed yet.
This is in particular relevant in relation to the `AlgebraicKernel_d_2`,
where `AlgebraicKernel_d_1::Algebraic_real_1` is used to represent coordinates of solutions of bivariate systems.
Hence, the design does
not allow direct access to any, seemingly obvious, members of an
`AlgebraicKernel_d_1::Algebraic_real_1`. Instead, there is, e.g.,
`AlgebraicKernel_d_1::Compute_polynomial_1` which emphasizes
that the requested polynomial may not be computed yet. Similarly,
there is no way to directly ask for the refinement of the current
isolating interval since this would impose a state to every object of
an `AlgebraicKernel_d_1::Algebraic_real_1`.

\subsection Algebraic_kernel_dBivariateAlgebraicKernel Bivariate Algebraic Kernel

The concept `AlgebraicKernel_d_2` is a refinement of `AlgebraicKernel_d_1`,
that is, a model of `AlgebraicKernel_d_2` is also a model of `AlgebraicKernel_d_1`.
Hence, the `AlgebraicKernel_d_2` concept is designed such that occurring
names and functionalities are as similar as possible to those in the
`AlgebraicKernel_d_1` concept.
The following are a direct generalization of their univariate counterparts:

`AlgebraicKernel_d_2::Polynomial_2`,

`AlgebraicKernel_d_2::Algebraic_real_2`,

`AlgebraicKernel_d_2::Construct_algebraic_real_2`,

`AlgebraicKernel_d_2::Isolate_2`,

`AlgebraicKernel_d_2::Is_square_free_2`,

`AlgebraicKernel_d_2::Make_square_free_2`,

`AlgebraicKernel_d_2::Square_free_factorize_2`,

`AlgebraicKernel_d_2::Is_coprime_2`,

`AlgebraicKernel_d_2::Make_coprime_2`,

`AlgebraicKernel_d_2::Solve_2`,

`AlgebraicKernel_d_2::Number_of_solutions_2`,

`AlgebraicKernel_d_2::Compare_xy_2`,

`AlgebraicKernel_d_2::Sign_at_2`,

`AlgebraicKernel_d_2::Is_zero_at_2`.

For instance, `AlgebraicKernel_d_2::Solve_2`
provides the solution for a bivariate polynomial system.
However, it is also possible to obtain the coordinates of these
solutions with the additional functors:

`AlgebraicKernel_d_2::Compute_x_2`,

`AlgebraicKernel_d_2::Compute_y_2`.

In principal this would be sufficient generalization,
since functions such as isolating, approximating algebraic real numbers
could be implemented using these access functions ant
the corresponding functionalities in the univariate algebraic kernel.
However, one should be aware that an `AlgebraicKernel_d_2::Algebraic_real_2`
is not necessarily represented as a pair of univariate solutions, that is,
using `AlgebraicKernel_d_2::Compute_y_2` may entail considerable
computations. Therefore, the concept also requires the following
additional functors that may allow a model to bypass this issue:

`AlgebraicKernel_d_2::Compute_polynomial_x_2`,

`AlgebraicKernel_d_2::Compute_polynomial_y_2`,

`AlgebraicKernel_d_2::Isolate_x_2`,

`AlgebraicKernel_d_2::Isolate_y_2`,

`AlgebraicKernel_d_2::Compare_x_2`,

`AlgebraicKernel_d_2::Compare_y_2`,

`AlgebraicKernel_d_2::Approximate_absolute_x_2`,

`AlgebraicKernel_d_2::Approximate_relative_x_2`,

`AlgebraicKernel_d_2::Approximate_absolute_y_2`,

`AlgebraicKernel_d_2::Approximate_relative_y_2`,

`AlgebraicKernel_d_2::Bound_between_x_2`,

`AlgebraicKernel_d_2::Bound_between_y_2`.

\section Algebraic_kernel_dModels Models

\subsection Algebraic_kernel_dGenericAlgebraicKernels Generic Algebraic Kernels

The package provides generic models of the univariate and bivariate algebraic
kernel, namely `Algebraic_kernel_d_1<Coeff>` and `Algebraic_kernel_d_2<Coeff>`,
respectively. Both kernels support a large set of number types as their
template argument, which defines the supported coefficient type. The supported
types are, for instance, `Gmpz` and `Gmpq` as well as the corresponding types
of LEDA and CORE.

The `Algebraic_kernel_d_1<Coeff>` represents an algebraic real root by a square
free polynomial and an isolating interval that uniquely defines the root.
The current method to isolate roots is the Bitstream Descartes
method \cgalCite{eigenwillig-phd-08}.
The used method to refine the approximation of an algebraic real root is a
slightly modified (filtered) version of the one presented in \cgalCite{abbott-qir-06}.
The method has quadratic convergence.

`Algebraic_kernel_d_2<Coeff>` is based on an algorithm computing a
geometric-topological analysis of a single curve \cgalCite{ekw-fast-07} and of a
pair of curves \cgalCite{ek-exact-08}.
The main idea behind both analyses is to compute the critical
x-coordinates of curves and curve pairs by projection (resultants), and compute
additional information about the critical fibers using subresultants
and Sturm-Habicht sequences \cgalCite{grlr-sturm-habicht-98}.
With that information, the fiber at
critical x-coordinates is computed by a variant of the Bitstream
Descartes method.
See also \cgalCite{kerber-phd-09} for a comprehensive description of
these techniques.
Almost all functors in the class that take a `Polynomial_2`
object as argument trigger such an analysis as a main computation
step. For efficiency, these analyses (of single curves and curve
pairs) are therefore cached internally for efficiency. For instance,
computing the pairwise solutions of 10 `Polynomial_2` objects
requires 10 curve analyses and 45 curve pair analyses to be computed
internally.

A point \f$ p\f$ of type `Algebraic_real_2` is represented
by its \f$ x\f$-coordinate \f$ x_0\f$ (as described in the `Algebraic_kernel_d_1`
paragraph above), an algebraic curve where \f$ p\f$ lies on, and an
integer \f$ i\f$, denoting that \f$ p\f$ is the \f$ i\f$th point in the fiber at \f$ x_0\f$,
counted from the bottom (ignoring a possible vertical line at \f$ x_0\f$).
Note that this determines the point uniquely, but the \f$ y\f$-coordinate
is not stored internally in terms of an `Algebraic_real_1` object.
Querying such a representation by calling `Compute_y_2` is a
time-consuming step, and should be avoided for efficiency reasons if possible.


\section Algebraic_kernel_dExamples Examples

\subsection CGALAK1ConstructionExamples Construction of Algebraic Real Numbers

The following example illustrates the construction of `AlgebraicKernel_d_1::Algebraic_real_1`
using `AlgebraicKernel_d_1::Construct_algebraic_real_1`:
\cgalExample{Algebraic_kernel_d/Construct_algebraic_real_1.cpp}

\subsection CGALAK1Solving Solving Univariate Polynomials

The following example illustrates the construction of `AlgebraicKernel_d_1::Algebraic_real_1`
using `AlgebraicKernel_d_1::Solve_1`: \cgalExample{Algebraic_kernel_d/Solve_1.cpp}

\subsection CGALAK1EGCompare_1 Comparison and Approximation of Algebraic Real Numbers

The following example illustrates the comparison of `AlgebraicKernel_d_1::Algebraic_real_1` numbers:
\cgalExample{Algebraic_kernel_d/Compare_1.cpp}

\subsection CGALAK1EGIsolate_1 Isolation of Algebraic Real Numbers with respect to roots of other polynomials

The following example illustrates the isolation of `AlgebraicKernel_d_1::Algebraic_real_1` numbers:
\cgalExample{Algebraic_kernel_d/Isolate_1.cpp}

\subsection CGALAK1EGSign_at_1 Interplay with Polynomials

The following example illustrates the sign evaluation of `AlgebraicKernel_d_1::Algebraic_real_1` numbers in polynomials:
\cgalExample{Algebraic_kernel_d/Sign_at_1.cpp}

\section Algebraic_kernel_dDesign Design and Implementation History

This package is clearly split into a univariate and bivariate
kernel. However, with respect to its history the package splits into
a design part and an implementation part.

The concepts, which make up the design part,
were written by Eric Berberich, Michael Hemmer, and
Monique Teillaud.
The design history of the package is fairly old and several
ideas that influenced this package can already be found
in \cgalCite{cgal:bhkt-risak-07}. Since then, the initial design underwent
considerable changes. For instance, it was decided that the algebraic
numbers should be under the control of the algebraic kernel. On the other
hand the initial support for polynomials was extended to a separate
and independent package that is not restricted to a certain number of
variables. Thus, the authors want to thank for all the useful feedback and
ideas that was brought to them throughout the last years. In particular,
they want to thank Menelaos Karavelas and Elias Tsigaridas for their
initial contributions.

The two generic models where initially developed as part of the \exacus \cgalCite{beh-eeeafcs-05} project.
However, the models are now fully integrated into the \cgal library,
since also the relevant layers of \exacus are now part of \cgal.
The main authors for `Algebraic_kernel_d_1<Coeff>` and `Algebraic_kernel_d_2<Coeff>` are
Michael Hemmer and Michael Kerber, respectively. Notwithstanding, the authors also want to emphasize the
contribution of all authors of the \exacus project,
particularly the contribution of Arno Eigenwillig, Sebastian Limbach and Pavel Emeliyanenko.

In 2010, two univariate kernels that interface the library RS \cgalCite{cgal:r-rs} were
written by Luis Peñaranda and Sylvain Lazard \cgalCite{cgal:2009-ESA}.
Both models interface the library RS \cgalCite{cgal:r-rs} by Fabrice Rouillier.
The authors want to thank Fabrice Rouillier and Elias Tsigaridas for
strong support and many useful discussions that lead to the integration of RS.
Due to lack of maintenance, these kernels have been removed in 2024.


*/
} /* namespace CGAL */

---

### Algebraic Kernel D Doc Algebraic Kernel D PackageDescription (`Algebraic_kernel_d/doc/Algebraic_kernel_d/PackageDescription.txt`)

/// \defgroup PkgAlgebraicKernelDRef Reference Manual

/// \defgroup PkgAlgebraicKernelDConcepts Concepts
/// \ingroup PkgAlgebraicKernelDRef

/// \defgroup PkgAlgebraicKernelDConceptsUni Univariate Algebraic Kernel
/// \ingroup PkgAlgebraicKernelDConcepts

/// \defgroup PkgAlgebraicKernelDConceptsBi Bivariate Algebraic Kernel
/// \ingroup PkgAlgebraicKernelDConcepts


/// \defgroup PkgAlgebraicKernelDModels Models
/// \ingroup PkgAlgebraicKernelDRef


/*!
\addtogroup PkgAlgebraicKernelDRef
\cgalPkgDescriptionBegin{Algebraic Kernel,PkgAlgebraicKernelD}
\cgalPkgPicture{Algebraic_kernel_d.png}
\cgalPkgSummaryBegin
\cgalPkgAuthors{Eric Berberich, Michael Hemmer, Michael Kerber, Sylvain Lazard, Luis Peñaranda, and Monique Teillaud}
\cgalPkgDesc{Real solving of polynomials is a fundamental problem with a wide application range.  This package is targeted to provide black-box implementation  algorithms to determine, compare and approximate real roots of univariate polynomials and bivariate polynomial systems. Such a black-box is called an *Algebraic %Kernel*.  So far the package only provides models for the univariate kernel. Nevertheless,  it already defines concepts for the bivariate kernel, since this settles the interface for upcoming implementations.}
\cgalPkgManuals{Chapter_Algebraic_Kernel,PkgAlgebraicKernelDRef}
\cgalPkgSummaryEnd
\cgalPkgShortInfoBegin
\cgalPkgSince{3.6}
\cgalPkgBib{cgal:bht-ak}
\cgalPkgLicense{\ref licensesLGPL "LGPL"}
\cgalPkgShortInfoEnd
\cgalPkgDescriptionEnd

\cgalClassifedRefPages

\cgalCRPSection{Concepts}

\cgalCRPSubsection{Univariate Algebraic %Kernel}

- `AlgebraicKernel_d_1`

- `AlgebraicKernel_d_1::ConstructAlgebraicReal_1`
- `AlgebraicKernel_d_1::ComputePolynomial_1`
- `AlgebraicKernel_d_1::Isolate_1`
- `AlgebraicKernel_d_1::IsSquareFree_1`
- `AlgebraicKernel_d_1::MakeSquareFree_1`
- `AlgebraicKernel_d_1::SquareFreeFactorize_1`
- `AlgebraicKernel_d_1::IsCoprime_1`
- `AlgebraicKernel_d_1::MakeCoprime_1`

- `AlgebraicKernel_d_1::Solve_1`
- `AlgebraicKernel_d_1::NumberOfSolutions_1`
- `AlgebraicKernel_d_1::SignAt_1`
- `AlgebraicKernel_d_1::IsZeroAt_1`
- `AlgebraicKernel_d_1::Compare_1`
- `AlgebraicKernel_d_1::BoundBetween_1`
- `AlgebraicKernel_d_1::ApproximateAbsolute_1`
- `AlgebraicKernel_d_1::ApproximateRelative_1`

\cgalCRPSubsection{Bivariate Algebraic %Kernel}

- `AlgebraicKernel_d_2`

- `AlgebraicKernel_d_2::ConstructAlgebraicReal_2`
- `AlgebraicKernel_d_2::ComputePolynomialX_2`
- `AlgebraicKernel_d_2::ComputePolynomialY_2`
- `AlgebraicKernel_d_2::Isolate_2`
- `AlgebraicKernel_d_2::IsolateX_2`
- `AlgebraicKernel_d_2::IsolateY_2`
- `AlgebraicKernel_d_2::IsSquareFree_2`
- `AlgebraicKernel_d_2::MakeSquareFree_2`
- `AlgebraicKernel_d_2::SquareFreeFactorize_2`
- `AlgebraicKernel_d_2::IsCoprime_2`
- `AlgebraicKernel_d_2::MakeCoprime_2`

- `AlgebraicKernel_d_2::Solve_2`
- `AlgebraicKernel_d_2::NumberOfSolutions_2`

- `AlgebraicKernel_d_2::SignAt_2`
- `AlgebraicKernel_d_2::IsZeroAt_2`

- `AlgebraicKernel_d_2::ComputeX_2`
- `AlgebraicKernel_d_2::ComputeY_2`

- `AlgebraicKernel_d_2::CompareX_2`
- `AlgebraicKernel_d_2::CompareY_2`
- `AlgebraicKernel_d_2::CompareXY_2`

- `AlgebraicKernel_d_2::ApproximateAbsoluteX_2`
- `AlgebraicKernel_d_2::ApproximateRelativeX_2`
- `AlgebraicKernel_d_2::ApproximateAbsoluteY_2`
- `AlgebraicKernel_d_2::ApproximateRelativeY_2`

- `AlgebraicKernel_d_2::BoundBetweenX_2`
- `AlgebraicKernel_d_2::BoundBetweenY_2`

\cgalCRPSection{Models}

- `CGAL::Algebraic_kernel_d_1<Coeff>`
- `CGAL::Algebraic_kernel_d_2<Coeff>`

*/

---

### Algebraic Kernel D Doc Algebraic Kernel D Examples (`Algebraic_kernel_d/doc/Algebraic_kernel_d/examples.txt`)

/*!
\example Algebraic_kernel_d/Construct_algebraic_real_1.cpp
\example Algebraic_kernel_d/Solve_1.cpp
\example Algebraic_kernel_d/Compare_1.cpp
\example Algebraic_kernel_d/Isolate_1.cpp
\example Algebraic_kernel_d/Sign_at_1.cpp
*/

---

### Alpha Shapes 2 Doc Alpha Shapes 2 Alpha Shapes 2 (`Alpha_shapes_2/doc/Alpha_shapes_2/Alpha_shapes_2.txt`)

namespace CGAL {
/*!

\mainpage User Manual
\anchor Chapter_2D_Alpha_Shapes
\anchor I1ChapterAlphashapes2D
\cgalAutoToc
\author Tran Kai Frank Da

\image html alphashape.png
\image latex alphashape.png

Assume we are given a set \f$ S\f$ of points in 2D or 3D and we would like to
have something like "the shape formed by these points". This is
quite a vague notion, and there are probably many possible
interpretations, the \f$ \alpha\f$-shape being one of them. Alpha shapes
can be used for shape reconstruction from a dense unorganized set of
data points. Indeed, an \f$ \alpha\f$-shape is demarcated by a frontier,
which is a linear approximation of the original shape \cgalCite{bb-srmua-97t}.

As mentioned in Edelsbrunner's and M&uuml;cke's paper \cgalCite{em-tdas-94},
one can intuitively think of an \f$ \alpha\f$-shape as the
following. Imagine a huge mass of ice-cream making up the space \f$ \mathbb{R}^3\f$
and containing the points as "hard" chocolate pieces. Using one of
these sphere-formed ice-cream spoons, we carve out all parts of the
ice-cream block we can reach without bumping into chocolate pieces,
thereby even carving out holes in the inside (e.g. parts not reachable
by simply moving the spoon from the outside). We will eventually end
up with a (not necessarily convex) object bounded by caps, arcs, and
points. If we now straighten all "round" faces to triangles and line
segments, we have an intuitive description of what is called the
\f$ \alpha\f$-shape of \f$ S\f$. The drawing above provides an example
of this process in 2D (where our ice-cream spoon is simply a circle).

Alpha shapes depend on a parameter \f$ \alpha\f$ after which they are named.
In the ice-cream analogy above, \f$ \alpha\f$ is the squared radius of the
carving spoon. A very small value will allow us to eat up all the
ice-cream except the chocolate points themselves. Thus, we already see
that the \f$ \alpha\f$-shape degenerates to the point-set \f$ S\f$ for
\f$ \alpha \rightarrow 0\f$. On the other hand, a huge value of \f$ \alpha\f$
will prevent us even from moving the spoon between two points since
it is too large. So we will never spoon up the ice-cream lying in the
inside of the convex hull of \f$ S\f$. Hence, the alpha shape becomes
the convex hull of \f$ S\f$ as \f$ \alpha \rightarrow \infty\f$.

\cgal offers 2D and 3D alpha shapes. The GUDHI library offers a
<a href="https://gudhi.inria.fr/doc/latest/group__alpha__complex.html"> dD Alpha complex</a>.

\section Alpha_shapes_2Definitions Definitions

We distinguish two versions of alpha shapes. <I>Basic alpha shapes</I>
are based on the Delaunay triangulation. <I>Weighted alpha shapes</I>
are based on its generalization, the regular triangulation
(cf. Section \ref Section_2D_Triangulations_Regular "Regular Triangulations"),
replacing the Euclidean distance by the power to weighted points.

There is a close connection between alpha shapes and the underlying
triangulations. More precisely, the \f$ \alpha\f$-complex of \f$ S\f$ is a
subcomplex of this triangulation of \f$ S\f$, containing the \f$ \alpha\f$-exposed
\f$ k\f$-simplices, \f$ 0 \leq k \leq d\f$. A simplex is said to be \f$ \alpha\f$-exposed, if there is an
open disk (resp. ball) of radius \f$ \sqrt{\alpha}\f$ through the vertices of the
simplex that does not contain any other point of \f$ S\f$, for the metric used in
the computation of the underlying triangulation. The corresponding
\f$ \alpha\f$-shape is defined as the underlying interior space of the
\f$ \alpha\f$-complex (see \cgalCite{em-tdas-94}).

In general, an \f$ \alpha\f$-complex is a non-connected and non-pure polytope,
meaning that one \f$ k\f$-simplex, with \f$ 0 \leq k \leq d-1\f$, is not necessarily
adjacent to a \f$ (k+1)\f$-simplex.

The \f$ \alpha\f$-shapes of \f$ S\f$ form a discrete family, even though they
are defined for all real numbers \f$ \alpha\f$ with \f$ 0 \leq \alpha
\leq \infty\f$. Thus, we can represent the entire family of \f$ \alpha\f$-shapes
of \f$ S\f$ by the underlying triangulation of \f$ S\f$. In this representation
each \f$ k\f$-simplex of the underlying triangulation is associated with an
interval that specifies for which values of \f$ \alpha\f$ the \f$ k\f$-simplex
belongs to the \f$ \alpha\f$-shape. Relying on this fact, the family of
\f$ \alpha\f$-shapes can be computed efficiently and relatively
easily. Furthermore, we can select an appropriate \f$ \alpha\f$-shape from a
finite number of different \f$ \alpha\f$-shapes and corresponding
\f$ \alpha\f$-values.

\section I1_SectAlpha_Shape_2 Functionality

The class `Alpha_shape_2<Dt>` represents the family of
\f$ \alpha\f$-shapes of points in a plane for <I>all</I> positive
\f$ \alpha\f$. It maintains the underlying triangulation `Dt` which
represents connectivity and order among squared radius of its faces. Each
\f$ k\f$-dimensional face of the `Dt` is associated with an interval
that specifies for which values of \f$ \alpha\f$ the face belongs to the
\f$ \alpha\f$-shape. There are links between the intervals and the
\f$ k\f$-dimensional faces of the triangulation.

The class `Alpha_shape_2<Dt>` provides functions to set and
get the current \f$ \alpha\f$-value, as well as an iterator that enumerates
the \f$ \alpha\f$-values where the \f$ \alpha\f$-shape changes.

It provides iterators to enumerate the vertices and edges that are in
the \f$ \alpha\f$-shape, and functions that allow to classify vertices,
edges, and faces with respect to the \f$ \alpha\f$-shape. They can be in
the interior of a face that belongs or does not belong to the \f$ \alpha\f$-shape.
They can be singular/regular, that is, they can be on the boundary of the \f$ \alpha\f$-shape,
but not incident/incident to a triangle of the \f$ \alpha\f$-complex.

Finally, it provides a function to determine the \f$ \alpha\f$-value
such that the \f$ \alpha\f$-shape satisfies the following two properties,
or at least the second one if there is no such \f$ \alpha\f$ that both
are satisfied: <br>
<ol>
<li> the number of components equals a number of your choice, and
<li> all data points are either on the boundary or in the interior of the regularized version of
the \f$ \alpha\f$-shape (no singular edges).
</ol>

The current implementation is static, that is after its construction
points cannot be inserted or removed.

\section I1_SectDtClass2D Concepts and Models

We currently do not specify concepts for the underlying triangulation
type. Models that work for a basic alpha shape are the classes
`Delaunay_triangulation_2`, `Periodic_2_Delaunay_triangulation_2`, and
`Triangulation_hierarchy_2` templated with a Delaunay
triangulation. A model that works for a weighted alpha shape is
the class `Regular_triangulation_2`.

\subsection AlphaShape2D_ConceptAndModelsAlphaShapes Alpha Shapes

The triangulation needs a geometric traits class as argument.
The requirements of this class are described in the concepts `AlphaShapeTraits_2`
in the non-weighted case and `WeightedAlphaShapeTraits_2` in the weighted case.
All \cgal kernels are models of both concepts.

The triangulation data structure of the triangulation
has to be a model of the concept `TriangulationDataStructure_2`,
whose vertex and face classes are models of the concepts
`AlphaShapeVertex_2` and `AlphaShapeFace_2`, respectively.
The classes `Alpha_shape_vertex_base_2<Gt, Vb>` and `Alpha_shape_face_base_2<Gt, Fb>`
are models of these concepts and can be used for all type of alpha shapes,
provided that the template parameters `Vb` and `Fb` are appropriately chosen,
as we shall see in the following section.

\subsection AlphaShape2D_ConceptAndModelsTDS Triangulation data structure

Additional requirements are put when using weighted or
periodic triangulations as underlying triangulation:
<ul>
<li> When using a weighted triangulation (`Regular_triangulation_2`), the vertex
and face classes must respectively be models to both `AlphaShapeVertex_2` and
`RegularTriangulationVertexBase_2`, and to both
`AlphaShapeFace_2` and `RegularTriangulationFaceBase_2`
(see example: \ref I1_SectWeightedAS2D).
<li> When using a periodic triangulation (`Periodic_2_Delaunay_triangulation_2`),
the vertex and face classes must respectively be models to both `AlphaShapeVertex_2`
and `Periodic_2TriangulationVertexBase_2`,
and to both `AlphaShapeFace_2` and `Periodic_2TriangulationFaceBase_2`
(see example: \ref AlphaShape_2DExampleForPeriodicAlphaShapes).
</ul>

\section Alpha_shapes_2Examples Examples

\subsection I1_SectClassicAS2D Example for Basic Alpha Shapes

The basic alpha shape requires a Delaunay triangulation as
underlying triangulation `Dt`. The Delaunay triangulation class is
parameterized with a geometric and a triangulation data structure traits.

For the geometric traits class we can use a \cgal kernel.

For the triangulation data structure traits, we have to
choose the vertex and face classes needed for alpha shapes,
namely `Alpha_shape_vertex_base_2<Gt, Vb>` and `Alpha_shape_face_base_2<Gt,Fb>`.
The parameter `Vb` and `Fb` must be filled by classes that are models of the
`TriangulationVertexBase_2` and `TriangulationFaceBase_2` concepts. The classes
`Triangulation_vertex_base_2<Gt>` and `Triangulation_face_base_2<Gt>` fit these
requirements.

The example below illustrates how to construct a basic alpha shape.
Note that `Triangulation_vertex_base_2<Gt>` and `Triangulation_face_base_2<Gt>`
are the default parameters for `Vb` and `Fb` in the classes
`Alpha_shape_vertex_base_2<Gt, Vb>` and `Alpha_shape_face_base_2<Gt,Fb>`. They
are thus omitted in the code below.
\cgalExample{Alpha_shapes_2/ex_alpha_shapes_2.cpp}

\subsection I1_SectWeightedAS2D Example for Weighted Alpha Shapes

A weighted alpha shape requires a regular triangulation as
underlying triangulation `Dt`.
Here again, we can use the vertex and face `Alpha_shape_vertex_base_2<Gt, Vb>`
and `Alpha_shape_face_base_2<Gt,Fb>`, but for weighted alpha shapes, `Vb` and `Fb`
must be models of the concepts `RegularTriangulationVertexBase_2` and
`RegularTriangulationFaceBase_2`. The classes `Regular_triangulation_vertex_base_2<Gt>`
`Regular_triangulation_face_base_2<Gt>` fit these requirements.

Note that there is no special weighted alpha shape class.

The example below illustrates how to construct a weighted alpha shape.
\cgalExample{Alpha_shapes_2/ex_weighted_alpha_shapes_2.cpp}

\subsection AlphaShape_2DExampleForPeriodicAlphaShapes Example for Periodic Alpha Shapes
The following example shows how to use a periodic Delaunay
triangulation as underlying triangulation for the alpha shape computation.

In order to define the original domain and to benefit from the
built-in heuristic optimizations of the periodic triangulation computation,
it is recommended to first construct the triangulation and
then construct the alpha shape from it. The alpha
shape constructor that takes a point range can be used as well but in
this case the original domain cannot be specified and the default unit
cube will be chosen and no optimizations will be used.

It is also recommended to switch the triangulation to 1-sheeted
covering if possible. Note that a periodic triangulation in 9-sheeted
covering space is degenerate. In this case, an exact constructions
kernel needs to be used to compute the alpha shapes. Otherwise, the
results will suffer from round-off problems.

\cgalExample{Alpha_shapes_2/ex_periodic_alpha_shapes_2.cpp}

*/
} /* namespace CGAL */

---

### Alpha Shapes 2 Doc Alpha Shapes 2 PackageDescription (`Alpha_shapes_2/doc/Alpha_shapes_2/PackageDescription.txt`)

/// \defgroup PkgAlphaShapes2Ref Reference Manual
/// \defgroup PkgAlphaShapes2Concepts Concepts
/// \ingroup PkgAlphaShapes2Ref

/*!
\addtogroup PkgAlphaShapes2Ref

\cgalPkgDescriptionBegin{2D Alpha Shapes,PkgAlphaShapes2}
\cgalPkgPicture{alpha-detail.png}
\cgalPkgSummaryBegin
\cgalPkgAuthor{Tran Kai Frank Da}
\cgalPkgDesc{This package offers  a data structure encoding the whole family of alpha-complexes related to a given 2D Delaunay or regular triangulation. In particular, the data structure allows to retrieve   the alpha-complex for any alpha value, the whole spectrum of critical alpha values and a filtration on the triangulation faces (this filtration is based on the first  alpha value for which each face is included on the alpha-complex).}
\cgalPkgManuals{Chapter_2D_Alpha_Shapes,PkgAlphaShapes2Ref}
\cgalPkgSummaryEnd
\cgalPkgShortInfoBegin
\cgalPkgSince{2.1}
\cgalPkgDependsOn{\ref PkgTriangulation2}
\cgalPkgBib{cgal:d-as2}
\cgalPkgLicense{\ref licensesGPL  "GPL"}
\cgalPkgDemo{2D Alpha Shapes,alpha_shapes_2.zip}
\cgalPkgShortInfoEnd
\cgalPkgDescriptionEnd

This chapter presents a framework for alpha shapes. The description is based on
the articles \cgalCite{em-tdas-94}, \cgalCite{e-was-92}. Alpha shapes are
the generalization of the convex hull of a point set. Let \f$ S\f$ be a finite set of
points in \f$ \mathbb{R}^d\f$, \f$ d = 2,3\f$ and \f$ \alpha\f$ a parameter with \f$ 0 \leq \alpha \leq
\infty\f$. For \f$ \alpha = \infty\f$, the \f$ \alpha\f$-shape is the convex hull of \f$ S\f$. As
\f$ \alpha\f$ decreases, the \f$ \alpha\f$-shape shrinks and develops cavities, as soon as
a sphere of radius \f$ \sqrt{\alpha}\f$ can be put inside.
Finally, for \f$ \alpha = 0\f$, the \f$ \alpha\f$-shape is the set \f$ S\f$ itself.

We distinguish two versions of alpha shapes, one is based on the Delaunay
triangulation and the other on its generalization, the regular triangulation,
replacing the natural distance by the power to weighted points. The metric used
determines an underlying triangulation of the alpha shape and thus, the version
computed.
The <I>basic alpha shape</I> (cf.  \ref I1_SectClassicAS2D) is associated with the Delaunay triangulation
(cf. Section \ref Section_2D_Triangulations_Delaunay "Delaunay Triangulations").
The <I>weighted alpha shape</I> (cf.  \ref I1_SectWeightedAS2D ) is associated with the regular triangulation
(cf. Section \ref Section_2D_Triangulations_Regular "Regular Triangulations").

There is a close connection between alpha shapes and the underlying
triangulations. More precisely, the \f$ \alpha\f$-complex of \f$ S\f$ is a
subcomplex of this triangulation of \f$ S\f$, containing the \f$ \alpha\f$-exposed
\f$ k\f$-simplices, \f$ 0 \leq k \leq d\f$. A simplex is \f$ \alpha\f$-exposed, if there is an
open disk (resp. ball) of radius \f$ \sqrt{\alpha}\f$ through the vertices of the
simplex that does not contain any other point of \f$ S\f$, for the metric used in
the computation of the underlying triangulation.  The corresponding
\f$ \alpha\f$-shape is defined as the underlying interior space of the
\f$ \alpha\f$-complex.

In general, an \f$ \alpha\f$-complex is a non-connected and non-pure polytope,
meaning that a \f$ k\f$-simplex, with \f$ 0 \leq k \leq d-1\f$, is not necessarily
adjacent to a \f$ (k+1)\f$-simplex.

The \f$ \alpha\f$-shapes of \f$ S\f$ form a discrete family, even though they
are defined for all real numbers \f$ \alpha\f$ with \f$ 0 \leq \alpha
\leq \infty\f$. Thus, we can represent the entire family of \f$ \alpha\f$-shapes
of \f$ S\f$ by the underlying triangulation of \f$ S\f$. In this representation
each \f$ k\f$-simplex of the underlying triangulation is associated with an
interval that specifies for which values of \f$ \alpha\f$ the \f$ k\f$-simplex
belongs to the \f$ \alpha\f$-shape. Relying on this result, the family of
\f$ \alpha\f$-shapes can be computed efficiently and relatively
easily. Furthermore, we can select an appropriate \f$ \alpha\f$-shape from a
finite number of different \f$ \alpha\f$-shapes and corresponding
\f$ \alpha\f$-values.

\cgalClassifedRefPages

\cgalCRPSection{Concepts}
- `AlphaShapeTraits_2`
- `WeightedAlphaShapeTraits_2`
- `AlphaShapeFace_2`
- `AlphaShapeVertex_2`

\cgalCRPSection{Classes}
- `CGAL::Alpha_shape_2<Dt>`
- `CGAL::Alpha_shape_vertex_base_2<AlphaShapeTraits_2>`
- `CGAL::Alpha_shape_face_base_2<AlphaShapeTraits_2, TriangulationFaceBase_2>`

*/

---

### Alpha Shapes 2 Doc Alpha Shapes 2 Examples (`Alpha_shapes_2/doc/Alpha_shapes_2/examples.txt`)

/*!
\example Alpha_shapes_2/ex_alpha_shapes_2.cpp
\example Alpha_shapes_2/ex_periodic_alpha_shapes_2.cpp
\example Alpha_shapes_2/ex_weighted_alpha_shapes_2.cpp
\example Alpha_shapes_2/ex_alpha_projection_traits.cpp
*/

---

### Alpha Shapes 3 Doc Alpha Shapes 3 Alpha Shapes 3 (`Alpha_shapes_3/doc/Alpha_shapes_3/Alpha_shapes_3.txt`)

namespace CGAL {
/*!

\mainpage User Manual
\anchor Chapter_3D_Alpha_Shapes
\cgalAutoToc
\authors Tran Kai Frank Da, S&eacute;bastien Loriot, and Mariette Yvinec

\image html alphashape.png
\image latex alphashape.png

Assume we are given a set \f$ S\f$ of points in 2D or 3D and we would like to
have something like "the shape formed by these points". This is
quite a vague notion and there are probably many possible
interpretations, the alpha shape being one of them. Alpha shapes
can be used for shape reconstruction from a dense unorganized set of
data points. Indeed, an alpha shape is demarcated by a frontier,
which is a linear approximation of the original shape \cgalCite{bb-srmua-97t}.

As mentioned in Edelsbrunner's and M&uuml;cke's paper \cgalCite{em-tdas-94},
one can intuitively think of an alpha shape as the
following. Imagine a huge mass of ice-cream making up the space \f$ \mathbb{R}^3\f$
and containing the points as "hard" chocolate pieces. Using one of
those sphere-formed ice-cream spoons, we carve out all parts of the
ice-cream block we can reach without bumping into chocolate pieces,
thereby even carving out holes in the inside (e.g. parts not reachable
by simply moving the spoon from the outside). We will eventually end
up with a (not necessarily convex) object bounded by caps, arcs and
points. If we now straighten all "round" faces to triangles and line
segments, we have an intuitive description of what is called the
alpha shape of \f$ S\f$. The drawing above provides an example
of this process in 2D (where our ice-cream spoon is simply a circle).

Alpha shapes depend on a parameter \f$ \alpha\f$ after which they are named.
In the ice-cream analogy above, \f$ \alpha\f$ is the squared radius of the
carving spoon. A very small value will allow us to eat up all the
ice-cream except the chocolate points themselves. Thus, we already see
that the alpha shape degenerates to the point-set \f$ S\f$ for
\f$ \alpha \rightarrow 0\f$. On the other hand, a huge value of \f$ \alpha\f$
will prevent us even from moving the spoon between two points since
it is too large and we will never spoon up the ice-cream lying in the
inside of the convex hull of \f$ S\f$. Hence, the alpha shape becomes
the convex hull of \f$ S\f$ as \f$ \alpha \rightarrow \infty\f$.

\cgal offers 2D and 3D alpha shapes. The GUDHI library offers a
<a href="https://gudhi.inria.fr/doc/latest/group__alpha__complex.html"> dD Alpha complex</a>.


\section Alpha_shapes_3Definitions Definitions

We distinguish two versions of alpha shapes. <I>Basic alpha shapes</I>
are based on the Delaunay triangulation. <I>Weighted alpha shapes</I>
are based on its generalization, the regular triangulation
(cf. Section \ref Triangulation3secclassRegulartriangulation "Regular Triangulations"),
replacing the Euclidean distance by the power to weighted points.

Let us consider the basic case with a Delaunay triangulation.
We first define the alpha complex of the set of points \f$ S\f$.
The alpha complex is a subcomplex
of the Delaunay triangulation.
For a given value of \f$ \alpha\f$, the alpha complex includes
all the simplices in the Delaunay triangulation which have
an empty circumscribing sphere with squared radius equal or smaller than \f$ \alpha\f$.
Here "empty" means that the open sphere does not include any points of \f$ S\f$.
The alpha shape is then simply the domain covered by the simplices
of the alpha complex (see \cgalCite{em-tdas-94}).

In general, an alpha complex is a disconnected and non-pure complex,
meaning in particular that the alpha complex may have
singular faces. For \f$ 0 \leq k \leq d-1\f$,
a \f$ k\f$-simplex of the alpha complex is said to be
singular if it is not a facet of a \f$ (k+1)\f$-simplex of the complex.
\cgal provides two versions of alpha shapes. In the general mode,
the alpha shapes correspond strictly to the above definition.
The regularized mode provides a regularized version of the alpha shapes.
It corresponds to the domain covered by a regularized version
of the alpha complex where singular faces are removed
(See \cgalFigureRef{figgenregex} for an example).

\cgalFigureBegin{figgenregex,gen-reg-ex.png}
Comparison of general and regularized alpha-shape. <B>Left:</B> Some points are taken on the surface of a torus, three points being taken relatively far from the surface of the torus; <B>Middle:</B> The general alpha-shape (for a large enough alpha value) contains the singular triangle facet of the three isolated points; <B>Right:</B> The regularized version (for the same value of alpha) does not contain any singular facet.
\cgalFigureEnd

The alpha shapes of a set of points
\f$ S\f$ form a discrete family, even though they
are defined for all real numbers \f$ \alpha\f$.
The entire family of alpha shapes can be represented
through the underlying triangulation of \f$ S\f$. In this representation
each \f$ k\f$-simplex of the underlying triangulation is associated with an
interval that specifies for which values of \f$ \alpha\f$ the \f$ k\f$-simplex
belongs to the alpha complex. Relying on this fact, the family of
alpha shapes can be computed efficiently and relatively
easily. Furthermore, we can select the optimal value
of \f$ \alpha\f$ to get an alpha shape including all data points
and having less than a given number of connected components.
Also, the alpha-values allows to define a filtration on the
faces of the triangulation of a set of points.
In this filtration, the faces of the triangulation are output
in increasing order of the alpha value
for which they appear
in the alpha complex. In case of equal alpha values,
lower dimensional faces are output first.

The definition is analog in the case of weighted alpha shapes.
The input set is now a set of weighted points (which can be regarded
as spheres) and the underlying triangulation
is the regular triangulation of this set.
Two spheres, or two weighted points, with centers \f$ C_1, C_2\f$
and radii \f$ r_1, r_2 \f$ are said to be orthogonal iff
\f$ C_1C_2 ^2 = r_1^2 + r_2^2\f$ and suborthogonal
iff \f$ C_1C_2 ^2 < r_1^2 + r_2^2\f$.
For a given value of \f$ \alpha\f$,
the weighted alpha complex is formed with the simplices of the
regular triangulation such that there is a sphere
orthogonal to the weighted points associated
with the vertices of the simplex and suborthogonal to all the other
input weighted points. Once again the alpha shape is then defined as
the domain covered by the alpha complex and comes in general and
regularized versions.

\section Alpha_Shape_3Functionality Functionality

\subsection AlphaShape_3DFamilyOfAlphaShapes Family of Alpha Shapes

The class `Alpha_shape_3<Dt,ExactAlphaComparisonTag>` represents the whole
family of alpha shapes for a given set of points.
The class includes the underlying triangulation `Dt`
of the set, and associates to each \f$ k\f$-face of this triangulation
an interval specifying
for which values of \f$ \alpha\f$ the face belongs to the
alpha complex.
The second template parameter, `ExactAlphaComparisonTag`, is a tag that,
when set to CGAL::Tag_true, triggers exact comparisons between alpha values.

The class provides functions to set and
get the current \f$ \alpha\f$-value, as well as an iterator that enumerates
the \f$ \alpha\f$ values where the alpha shape changes.

Additionally, the class has a filtration member function that, given
an output iterator with `Object`
as value type, outputs the faces of the triangulation
according to the
order of apparition in the alpha complex when alpha increases.

Finally, it provides a function to determine
the smallest value \f$ \alpha\f$
such that the alpha shape satisfies the following two properties: <br>
<ol>
<li> All data points are either on the boundary or in the interior
of the regularized version of the alpha shape (no singular faces).
<li> The number of components is equal or less than a given number.
</ol>

The current implementation is static, that is after its construction
points cannot be inserted or removed.

\subsection AlphaShape_3DAlphaShapeForAFixedAlpha Alpha Shape for a Fixed Alpha

Given a value of alpha, the class `Fixed_alpha_shape_3<Dt>` represents one
alpha shape for a given set of points.
The class includes the underlying triangulation `Dt`
of the set, and associates to each \f$ k\f$-face of this triangulation
a classification type. This class is dynamic, that is after its construction
points can be inserted or removed.

\subsection AlphaShape_3DClassificationAndIterators Classification and Iterators

Both classes provide member functions to classify for a (given) value
of \f$ \alpha\f$ the different faces of the triangulation as
`EXTERIOR`, `SINGULAR`, `REGULAR` or
`INTERIOR` with respect
to the alpha shape. A \f$ k\f$-face on the boundary of the alpha complex
is said to be: `REGULAR` if it is a subface of the alpha-complex which
is a subface of a \f$ (k+1)\f$-face of the alpha complex, and `SINGULAR` otherwise.
A \f$ k\f$-face of the alpha complex which is not on the boundary of the alpha complex
is said to be `INTERIOR`. See \cgalFigureRef{figclassif} for a 2D illustration.

\cgalFigureBegin{figclassif,classif.png} Classification of simplices, a 2D example. <B>Left:</B> The 2D
Delaunay triangulation of a set of points; <B>Right:</B>
Classification of simplices for a given alpha (the squared radius of
the red circle). `INTERIOR`, `REGULAR` and `SINGULAR` simplices are
depicted in black, green and blue respectively. `EXTERIOR` simplices
are not depicted. The vertex `s` and the edge `tu` are `SINGULAR`
since all higher dimension simplices they are incident to are
`EXTERIOR`. The facet `pqr` is `EXTERIOR` because the squared radius
of its circumscribed circle is larger than alpha.
\cgalFigureEnd

The classes provide also output iterators to get for a given `alpha` value
the vertices, edges, facets and cells of the different types
(`EXTERIOR`, `SINGULAR`, `REGULAR` or
`INTERIOR`).

\subsection AlphaShape3DIO Input/Output
It is possible to export a 3D alpha shape to a `std::ostream`
using the `operator<<`, see the documentation of the class `Alpha_shape_3` for more information.

\section AlphaShape3D_ConceptAndModels Concepts and Models

We currently do not specify concepts for the underlying triangulation
type. Models that work for a family of alpha-shapes are the instantiations
of the classes `Delaunay_triangulation_3` and
`Periodic_3_Delaunay_triangulation_3` (see
example \ref AlphaShape_3DExampleForPeriodicAlphaShapes).
A model that works for a fixed alpha-shape are the instantiations
of the class `Delaunay_triangulation_3`.
Models that work for a weighted alpha-shape are the instantiations
of the classes `Regular_triangulation_3` and
`Periodic_3_regular_triangulation_3`.
The triangulation needs a geometric traits class
and a triangulation data structure as template parameters.

\subsection AlphaShape3D_ConceptAndModelsAlphaShapes Alpha Shapes

For the class `Alpha_shape_3<Dt,ExactAlphaComparisonTag>`, the requirements of
the traits class are described in the concepts `AlphaShapeTraits_3`
in the non-weighted case and `WeightedAlphaShapeTraits_3` in the weighted case.
All \cgal kernels are models of both concepts.

The triangulation data structure of the triangulation
has to be a model of the concept `TriangulationDataStructure_3`
whose vertex and cell classes are model of the concepts
`AlphaShapeVertex_3` and `AlphaShapeCell_3`.
The classes `Alpha_shape_vertex_base_3<Gt>` and `Alpha_shape_cell_base_3<Gt>`
are models of these concepts and can be used for all type of alpha shapes,
provided that the template parameters `Vb` and `Fb` are appropriately chosen,
as we shall see in the following section.

\subsection AlphaShape3D_ConceptAndModelsFixedAlphaShapes Fixed Alpha Shapes

For the class `Fixed_alpha_shape_3<Dt>`, the requirements of
the traits class are described in the concepts `FixedAlphaShapeTraits_3`
in the non-weighted case and `FixedWeightedAlphaShapeTraits_3` in the weighted case.
All \cgal kernels are models of both concepts.
The triangulation data structure of the triangulation
has to be a model of the concept `TriangulationDataStructure_3`
whose vertex and cell classes are model of the concepts
`FixedAlphaShapeVertex_3` and `FixedAlphaShapeCell_3`.
The package provides models `Fixed_alpha_shape_vertex_base_3<Gt>`
and `Fixed_alpha_shape_cell_base_3<Gt>`, respectively.

\subsection AlphaShape3D_ConceptAndModelsTDS Triangulation data structure

Additional requirements are put when using weighted or
periodic triangulations as underlying triangulation:
<ul>
<li> When using a weighted triangulation (`Regular_triangulation_3` or
`Periodic_3_regular_triangulation_3`), the vertex
and cell classes must respectively be models to both `AlphaShapeVertex_3` and
`RegularTriangulationVertexBase_3`, and to both
`AlphaShapeCell_3` and `RegularTriangulationCellBase_3`
(see example: \ref AlphaShape_3DExampleforWeightedAlphaShapes).
<li> When using a periodic triangulation (`Periodic_3_Delaunay_triangulation_3`
or `Periodic_3_regular_triangulation_3`), the vertex and cell classes must
respectively be models to both `AlphaShapeVertex_3` and `Periodic_3TriangulationDSVertexBase_3`,
and to both `AlphaShapeCell_3` and `Periodic_3TriangulationDSCellBase_3`
(see example: \ref  AlphaShape_3DExampleForPeriodicAlphaShapes).
</ul>

\section Alpha_shapes_3AlphaShape3OrFixedAlphaShape3 Alpha_shape_3 vs. Fixed_alpha_shape_3

The class `Alpha_shape_3<Dt,ExactAlphaComparisonTag>` represents the whole family
of alpha shapes for a given set of points while the class `Fixed_alpha_shape_3<Dt>`
represents only one alpha shape (for a fixed alpha). When using the same kernel,
`Fixed_alpha_shape_3<Dt>` is a lighter version. It is thus naturally much more efficient
when the alpha-shape is needed for a single given value of alpha.
In addition, note that the class `Alpha_shape_3<Dt,ExactAlphaComparisonTag>`
requires constructions (squared radius of simplices) while the
class `Fixed_alpha_shape_3<Dt>` uses only predicates.
This implies that a certified construction of one (several)
alpha-shape, using the `Alpha_shape_3<Dt,ExactAlphaComparisonTag>` requires a kernel
with exact predicates and exact constructions (or setting `ExactAlphaComparisonTag` to `Tag_true`)
while using a kernel with exact predicates is sufficient for the class `Fixed_alpha_shape_3<Dt>`.
This makes the class `Fixed_alpha_shape_3<Dt>` even more efficient in this setting.
In addition, note that the `Fixed` version is the only one of the
two that supports incremental insertion and removal of points.

We give the time spent while computing the alpha shape of a protein (considered
as a set of weighted points) featuring 4251 atoms (using `gcc 4.3` under Linux with `-O3`
and `-DNDEBUG` flags, on a 2.27GHz Intel(R) Xeon(R) E5520 CPU):
Using `Exact_predicates_inexact_constructions_kernel`, building
the regular triangulation requires 0.09s, then the class `Fixed_alpha_shape_3<Dt>`
required 0.05s while the class `Alpha_shape_3<Dt,ExactAlphaComparisonTag>` requires 0.35s
if `ExactAlphaComparisonTag` is `Tag_false` (and 0.70s with `Tag_true`).
Using `Exact_predicates_exact_constructions_kernel`, building
the regular triangulation requires 0.19s and then the class `Alpha_shape_3<Dt,ExactAlphaComparisonTag>`
requires 0.90s.

\section Alpha_shapes_3Examples Examples

\subsection AlphaShape_3DExampleForBasicAlphaShapes Example for Basic Alpha-Shapes

This example builds a basic alpha shape using a Delaunay triangulation
as underlying triangulation.

\cgalExample{Alpha_shapes_3/ex_alpha_shapes_3.cpp}

\subsection AlphaShape_3DBuildingBasicAlphaShapesForManyPoints Building Basic Alpha Shapes for Many Points

When many points are input in the alpha shape, say more than 10 000,
it may pay off to use a Delaunay triangulation with the `Fast_location`
policy as underlying triangulation in order to speed up point location
queries (cf. Section \ref Triangulation3seclocpol "The Location Policy Parameter").

\cgalExample{Alpha_shapes_3/ex_alpha_shapes_with_fast_location_3.cpp}

\subsection AlphaShape_3DExampleforWeightedAlphaShapes Example for Weighted Alpha-Shapes

The following examples build a weighted alpha shape requiring a
regular triangulation as underlying triangulation.
The alpha shape is built in `GENERAL` mode.

\cgalExample{Alpha_shapes_3/ex_weighted_alpha_shapes_3.cpp}

\subsection AlphaShape_3DExampleForFixedWeightedAlphaShapes Example for Fixed Weighted Alpha-Shapes

Same example as previous but using a fixed value of alpha.

\cgalExample{Alpha_shapes_3/ex_fixed_weighted_alpha_shapes_3.cpp}

\subsection AlphaShape_3DBuildingAnAlphaShapesWithExactComparisonsOfAlphaValues Building an Alpha Shapes with Exact Comparisons of Alpha Values

On some platforms, the alpha shapes of the set of points of this example
cannot be computed when using a traits with inexact constructions. To be able to compute
them with a traits with inexact constructions, the tag
`ExactAlphaComparisonTag` is set to `Tag_true`.
\cgalExample{Alpha_shapes_3/ex_alpha_shapes_exact_alpha.cpp}

\subsection AlphaShape_3DExampleForPeriodicAlphaShapes Example for Periodic Alpha Shapes

The following example shows how to use a periodic Delaunay
triangulation (Chapter \ref Chapter_3D_Periodic_Triangulations "3D Periodic Triangulations") as underlying
triangulation for the alpha shape computation. Usage of a weighted Delaunay periodic
triangulation is presented in the example: \ref Alpha_shapes_3/ex_weighted_periodic_alpha_shapes_3.cpp "ex_weighted_periodic_alpha_shapes_3.cpp".

In order to define the original domain and to benefit from the
built-in heuristic optimizations of the periodic triangulation computation,
it is recommended to first construct the triangulation and
then construct the alpha shape from it. The alpha
shape constructor that takes a point range can be used as well but in
this case the original domain cannot be specified and the default unit
cube will be chosen and no optimizations will be used.

It is also recommended to switch the triangulation to 1-sheeted
covering if possible. Note that a periodic triangulation in 27-sheeted
covering space is degenerate. In this case, an exact constructions
kernel needs to be used to compute the alpha shapes. Otherwise, the
results will suffer from round-off problems.

\cgalExample{Alpha_shapes_3/ex_periodic_alpha_shapes_3.cpp}

*/
} /* namespace CGAL */

---

### Alpha Shapes 3 Doc Alpha Shapes 3 PackageDescription (`Alpha_shapes_3/doc/Alpha_shapes_3/PackageDescription.txt`)

/// \defgroup PkgAlphaShapes3Ref Reference Manual
/// \defgroup PkgAlphaShapes3Concepts Concepts
/// \ingroup PkgAlphaShapes3Ref
/*!
\addtogroup PkgAlphaShapes3Ref
\cgalPkgDescriptionBegin{3D Alpha Shapes,PkgAlphaShapes3}
\cgalPkgPicture{alpha_shapes_3_small.png}
\cgalPkgSummaryBegin
\cgalPkgAuthors{Tran Kai Frank Da, Sébastien Loriot, and Mariette Yvinec}
\cgalPkgDesc{This package offers a data structure encoding either one alpha-complex or the whole family of alpha-complexes related to a given 3D Delaunay or regular triangulation. In the latter case, the data structure allows to retrieve   the alpha-complex for any alpha value, the whole spectrum of critical alpha values and a filtration on the triangulation faces (this filtration is based on the first  alpha value for which each face is included on the alpha-complex). }
\cgalPkgManuals{Chapter_3D_Alpha_Shapes,PkgAlphaShapes3Ref}
\cgalPkgSummaryEnd
\cgalPkgShortInfoBegin
\cgalPkgSince{2.3}
\cgalPkgDependsOn{\ref PkgTriangulation3}
\cgalPkgBib{cgal:dy-as3}
\cgalPkgLicense{\ref licensesGPL  "GPL"}
\cgalPkgDemo{3D Alpha Shapes,alpha_shape_3.zip}
\cgalPkgShortInfoEnd
\cgalPkgDescriptionEnd

Alpha shapes definition is based on an underlying
triangulation that may be a Delaunay triangulation
in case of basic alpha shapes or a regular triangulation
(cf. Section \ref Triangulation3secclassRegulartriangulation "3D Regular Triangulation")
in case of weighted alpha shapes.

Let us consider the basic case with a Delaunay triangulation.
We first define the alpha complex  of the set of points \f$ S\f$.
The  alpha complex is a subcomplex
of the Delaunay triangulation.
For a given value of \f$ \alpha\f$, the alpha complex includes
all the simplices in the Delaunay triangulation which have
an empty  circumscribing sphere with squared radius equal or smaller than \f$ \alpha\f$.
Here "empty" means  that the open sphere
do not include  any points of \f$ S\f$.
The alpha shape is then simply the domain covered by the simplices
of the alpha complex (see \cgalCite{em-tdas-94}).

In general, an alpha complex is a non-connected and non-pure complex.
This means in particular that the alpha complex may have
singular faces.  For \f$ 0 \leq k \leq d-1\f$,
a \f$ k\f$-simplex of the alpha complex  is said to be
singular if it is not a facet of a \f$ (k+1)\f$-simplex of the complex

The alpha shapes of a  set of points
\f$ S\f$ form a discrete family, even though they
are defined for all real numbers \f$ \alpha\f$.
The entire family of alpha shapes can be represented
through  the underlying triangulation of \f$ S\f$. In this representation,
each \f$ k\f$-simplex of the underlying triangulation is associated with an
interval that specifies for which values of \f$ \alpha\f$ the \f$ k\f$-simplex
belongs to the alpha complex. Relying on this fact, the family of
 alpha shapes can be computed efficiently and relatively
easily. Furthermore, we can select the optimal value
of  \f$ \alpha\f$ to get an alpha shape including all data points
and having   less than a given number of connected components.

The definition is analog in the case of weighted alpha shapes.
The input set is now a set of weighted points (which can be regarded
as spheres) and the underlying triangulation
is the regular triangulation of this set.
Two spheres, or two weighted points, with centers \f$ C_1, C_2\f$
and  radii \f$ r_1, r_2 \f$ are said to be orthogonal iff
\f$  C_1C_2 ^2 = r_1^2 + r_2^2\f$ and suborthogonal
iff  \f$  C_1C_2 ^2 < r_1^2 + r_2^2\f$.
For a given value of \f$ \alpha\f$
the weighted alpha complex is formed with the simplices of the
regular triangulation triangulation
such that there is a sphere orthogonal to the weighted points associated
with the vertices of the simplex  and suborthogonal to all the other
input weighted points. Once again the alpha shape is then defined as
the domain covered by a the alpha complex.

CGAL provides two versions to compute alpha shapes.
The first one gives access to an explicit classification of all the simplices for a fixed alpha value.
The second one gives access to the entire family of alpha shapes of a set of points.
This latter version comes with two modes. In the general mode,
the alpha shapes correspond strictly to the definition previously made.
The regularized mode provides a regularized version of the alpha shapes
corresponding to the domain covered by a regularized version
of the alpha complex where singular faces are removed.

\cgalClassifedRefPages

\cgalCRPSection{Concepts}
- `AlphaShapeTraits_3`
- `WeightedAlphaShapeTraits_3`
- `AlphaShapeCell_3`
- `AlphaShapeVertex_3`
- `FixedAlphaShapeTraits_3`
- `FixedWeightedAlphaShapeTraits_3`
- `FixedAlphaShapeCell_3`
- `FixedAlphaShapeVertex_3`

\cgalCRPSection{Classes}
- `CGAL::Alpha_status<NT>`
- `CGAL::Alpha_shape_3<Dt,ExactAlphaComparisonTag>`
- `CGAL::Alpha_shape_vertex_base_3<Traits,Vb>`
- `CGAL::Alpha_shape_cell_base_3<Traits,Fb>`

- `CGAL::Fixed_alpha_shape_3<Dt>`
- `CGAL::Fixed_alpha_shape_vertex_base_3<Traits,Vb>`
- `CGAL::Fixed_alpha_shape_cell_base_3<Traits,Fb>`

*/

---

### Alpha Shapes 3 Doc Alpha Shapes 3 Examples (`Alpha_shapes_3/doc/Alpha_shapes_3/examples.txt`)

/*!
\example Alpha_shapes_3/ex_alpha_shapes_3.cpp
\example Alpha_shapes_3/ex_alpha_shapes_exact_alpha.cpp
\example Alpha_shapes_3/ex_alpha_shapes_with_fast_location_3.cpp
\example Alpha_shapes_3/ex_fixed_weighted_alpha_shapes_3.cpp
\example Alpha_shapes_3/ex_periodic_alpha_shapes_3.cpp
\example Alpha_shapes_3/ex_weighted_alpha_shapes_3.cpp
\example Alpha_shapes_3/ex_weighted_periodic_alpha_shapes_3.cpp
\example Alpha_shapes_2/ex_alpha_projection_traits.cpp
*/

---

### Alpha Wrap 2 Doc Alpha Wrap 2 PackageDescription (`Alpha_wrap_2/doc/Alpha_wrap_2/PackageDescription.txt`)

/// \defgroup PkgAlphaWrap2Ref Reference Manual

/// \defgroup PkgAlphaWrap2Concepts Concepts
/// \ingroup PkgAlphaWrap2Ref

/// \defgroup AW2_free_functions_grp Free Functions
/// Functions to create a wrap from point clouds, segment soups, and polygons with holes.
/// \ingroup PkgAlphaWrap2Ref

/*!
\addtogroup PkgAlphaWrap2Ref
\cgalPkgDescriptionBegin{2D Alpha Wrapping,PkgAlphaWrap2}
\cgalPkgPicture{alpha_wrap_2.png}
\cgalPkgSummaryBegin
\cgalPkgAuthors{Pierre Alliez, David Cohen-Steiner, Michael Hemmer, Cédric Portaneri, and Mael Rouxel-Labbé}
\cgalPkgDesc{This component takes a polygon soup, a 2D segment soup, and/or a 2D point set as input,
             and generates a valid (watertight, intersection-free and 1-manifold) multi-polygon that
             strictly encloses the input. The algorithm proceeds by shrink-wrapping
             and refining a 2D Delaunay triangulation starting from a loose bounding box of the input.
             Two user-defined parameters, alpha and offset, offer control over the maximum size
             of cavities where the shrink-wrapping process can enter, and the tightness
             of the final polygon(s) to the input, respectively. Once combined, these parameters
             provide a means to trade fidelity to the input for complexity of the output.}
\cgalPkgManuals{Chapter_2D_Alpha_wrapping,PkgAlphaWrap2Ref}
\cgalPkgSummaryEnd
\cgalPkgShortInfoBegin
\cgalPkgSince{6.2}
\cgalPkgDependsOn{\ref PkgTriangulation2 and \ref PkgPolygonRepair}
\cgalPkgBib{cgal:achpr-aw2}
\cgalPkgLicense{\ref licensesGPL "GPL"}
\cgalPkgDemo{2D Alpha wrap demo,alpha_wrap_2.zip}
\cgalPkgShortInfoEnd
\cgalPkgDescriptionEnd

\cgalClassifedRefPages

\cgalCRPSection{Concepts}
- `AlphaWrapTraits_2`

\cgalCRPSection{Functions}
- \link AW2_free_functions_grp `CGAL::alpha_wrap_2()` \endlink
*/

---

### Alpha Wrap 2 Doc Alpha Wrap 2 Alpha Wrap 2 (`Alpha_wrap_2/doc/Alpha_wrap_2/alpha_wrap_2.txt`)

namespace CGAL {

/*!

\mainpage User Manual
\anchor Chapter_2D_Alpha_wrapping
\cgalAutoToc

\authors Pierre Alliez, David Cohen-Steiner, Michael Hemmer, Cédric Portaneri, Mael Rouxel-Labbé

<center>
<img src="aw2_banner.png" style="max-width:70%;"/>
</center>

\section aw2_introduction Introduction

Various tasks in geometric modeling and processing require 2D objects represented as valid polygons,
where "valid" refers to polygons that are closed, intersection-free (simple), orientable, and 1-manifold.
Such representations offer well-defined notions of interior/exterior and geodesic neighborhoods.

2D data are usually acquired through measurements, possibly followed by reconstruction,
designed by humans, or generated through imperfect automated processes.
As a result, they can exhibit a wide variety of defects including gaps, missing data,
self-intersections, degeneracies such as zero-area structures, and non-manifold features.

Given the large repertoire of possible defects, many methods and data structures have been proposed
to repair specific defects (see for example the package \ref PkgPolygonRepair), usually with the goal
of guaranteeing specific properties in the repaired 2D model.
Reliably repairing all types of defects is an ill-posed problem as many valid solutions exist
for a given 2D model with defects.
In addition, the input model can be overly complex with unnecessary geometric details,
spurious topological structures, nonessential inner components, or excessively fine discretizations.
For applications such as collision avoidance, path planning, or simulation,
getting an approximation (i.e., a silhouette) of the input can be more relevant than repairing it.
Approximation herein refers to an approach capable of filtering out inner structures,
fine details and cavities, as well as wrapping the input within a user-defined offset margin.

Given an input 2D geometry, we address the problem of computing a conservative approximation,
where conservative means that the output is guaranteed to strictly enclose the input.
We seek unconditional robustness in the sense that the output polygon should be valid (oriented,
1-manifold, and without self-intersections), even for raw input with many defects
and degeneracies.
The default input is a soup of 2D segments, but the generic interface leaves the door open
to other types of finite 2D primitives such as point sets.

\cgalFigureAnchor{aw2_inputs_fig}
<center>
<img src="aw2_segment_soup.png" style="max-width:70%;"/>
</center>
\cgalFigureCaptionBegin{aw2_inputs_fig}
(Left) Shrink-wrapping output from a segment soup with many intersections and gaps.
(Center & Right) Possible input degeneracies: non-manifold vertices and zero-area structures.
The algorithm handles these cases by wrapping an offset of the input.
\cgalFigureCaptionEnd

\section aw2_definition Approach

Many approaches have been devised to enclose a 2D model within a polygon, featuring different balances
between the runtime and quality (i.e., tightness) of the approximation.
Within the simplest cases, an axis-aligned or oriented bounding box clearly satisfies some desired properties;
however, the approximation error is uncontrollable and often very large.
Computing the convex hull of the input also matches some of the desired properties
and improves the quality of the result, albeit at the price of increasing the runtime.
However, the approximation remains crude, especially in the case of several components.

The convex hull is, in fact, a special case of alpha shapes (\ref PkgAlphaShapes2).
Mathematically, the alpha shape is a subcomplex of the Delaunay triangulation, with simplicies
being part of the complex depending on the size of their minimal (empty) Delaunay ball.
Intuitively, constructing 2D alpha shapes can be thought of as carving 2D space with an empty ball
of user-defined radius alpha.
Alpha shapes yield provable, good piecewise-linear approximations of a shape \cgalCite{bb-srmua-97t},
but are defined on point sets, whereas we wish to deal with more general input data, such as segment soups.
Even after sampling the segment soup, alpha shapes do not guarantee to be conservative for any alpha.
Finally, inner structures are also carved within the interior, instead of being filtered out.

Inspired by alpha shapes, we replace the above notion of carving by <em>shrink-wrapping</em>:
we iteratively construct a subcomplex of a 2D Delaunay triangulation by starting from
a simple 2D Delaunay triangulation enclosing the input, and then iteratively removing eligible triangles
that lie on the boundary of the complex.
In addition, the underlying triangulation---and thus the complex incidentally---is refined
as shrinking proceeds.
Thus, instead of carving from the convex hull of the input data as in alpha shapes, we construct
an entirely new polygon through a Delaunay refinement-like algorithm. The refinement algorithm inserts Steiner points
on the boundary of an offset surface, defined as a level set of the unsigned distance field to the input.

This process both prevents the creation of inner structures within the output and avoids superfluous computations.
In addition, detaching our wrap construction from the geometry and discretization of the input has several advantages:
(1) the underlying data is not restricted to a specific format (polygon soups, segment soups, point sets, etc.)
as all that is required is answering three basic geometric queries: (a) the distance between a point
and the input, (b) the projection of a query point onto the input, (c) an intersection test
between a triangle and the input, and (2) The user has more freedom to trade tightness
to the input for final polygon complexity, as constructing a conservative approximation on a large offset
of the input requires fewer polygon edges.

\subsection aw2_algorithm Algorithm

<b>Initialization</b>. The algorithm is initialized by inserting the four corner vertices
of a loose bounding box into a 2D Delaunay triangulation.
In the 2D Delaunay triangulation of \cgal, all edges are adjacent to two triangle faces.
Each edge of the boundary of the Delaunay triangulation, which coincides with one edge
of the convex hull of the triangulation vertices, is adjacent to a so-called <em>infinite</em> triangle face,
an abstract face connected to the so-called <em>infinite vertex</em> to ensure the aforementioned double-edge adjacency.
Initially, all infinite faces are tagged as outside, and all finite triangle faces are tagged as inside.

<b>Shrink-wrapping</b>. The shrink-wrapping algorithm proceeds by traversing the faces
of the Delaunay triangulation from outside to inside, flood-filling from one face to its adjacent face,
and tagging the adjacent face as outside whenever possible (the term "possible" is specified later).
Flood filling is implemented via a priority queue of Delaunay triangle edges representing
the traversal between the two adjacent faces of the edge, from outside to inside.
These edges are referred to as <em>gates</em> in the following.

Given an outside face and its adjacent inside face, the common edge (i.e., a gate) is said
to be <em>alpha-traversable</em> if its circumradius is larger than the user-defined parameter alpha,
where circumradius refers to the radius of the relating segment's Delaunay ball.
Intuitively, cavities smaller than alpha are not accessible as their gates are not alpha-traversable.

Initialized by the alpha-traversable gates on the convex hull, the priority queue contains only
alpha-traversable gates and is sorted by decreasing order of the circumradius of the gate.
Traversal can be seen as a continuous process that advances along dual Voronoi edges of the gates,
with a pencil of empty balls circumscribing the gate.

\cgalFigureAnchor{aw2_pencil_fig}
<center>
<img src="aw2_pencil.png" style="max-width:30%;"/>
</center>
\cgalFigureCaptionBegin{aw2_pencil_fig}
(Left) Pencil of empty circles (blue) circumscribing a Delaunay edge (green) in a 2D Delaunay triangulation (black).
From the top triangle circumcenter <em>c1</em> to the bottom triangle circumcenter <em>c2</em>, the dual Voronoi edge denoted by <em>e</em> (doted red) is the trace of centers of the largest circles that are empty of Delaunay vertex.
(Right) The graph corresponding to the left example. The x-axis corresponds to the position of empty circle centers located on the Voronoi edge <em>e</em>, from <em>c1</em> to <em>c2</em>. The y-axis is the radius value of the corresponding empty circles. In this case, the minimum radius of this pencil of empty circle is located at the midpoint of the green Delaunay edge.
In our algorithm, a gate (green Delaunay edge) is said to be not alpha-traversable when the minimum radius of the pencil of empty circle is smaller than alpha.
\cgalFigureCaptionEnd

When traversing from an outside face \f$ f_o \f$ to an inside face \f$ f_i \f$ through an alpha-traversable edge \f$ e \f$,
two criteria are tested to prevent the wrapping process from colliding with the input:

(1) We check for an intersection between the dual Voronoi edge of \f$ e \f$, i.e., the segment between
the circumcenters of the two incident faces, and the <em>offset surface</em>, defined as the level set
of unsigned distance field to the input.
If one or several intersections exists, the first intersection point, along the dual Voronoi edge
oriented from outside to inside is inserted into the triangulation as a Steiner point.

(2) If the dual Voronoi edge does not intersect the offset surface but the neighboring face \f$ f_i \f$
intersects the input, we compute the projection of the circumcenter of \f$ f_i \f$
onto the offset surface, and insert it into the triangulation as a Steiner point (which destroys \f$ f_i \f$).

After each of the above Steiner point insertions, all new incident faces are tagged as inside,
and the newly alpha-traversable gates are pushed into the priority queue.

If none of the above two criteria are met, the neighboring face \f$ f_i \f$ is traversed and tagged as outside.
Alpha-Traversable edges of \f$ f_i \f$ that are separating inside from outside faces are pushed as new gates into the priority queue.

Once the queue empties---a process that is guaranteed as edges (and their circumradii) become smaller
due to the insertion of new Steiner points---the construction phase terminates.
The output (multi)polygon is extracted from the Delaunay triangulation as the set of edges
separating inside from outside faces.

The figure below depicts the steps of the algorithm.

\cgalFigureAnchor{aw2_steps_fig}
<center>
<img src="aw2_steps.jpg" style="max-width:95%;"/>
</center>
\cgalFigureCaptionBegin{aw2_steps_fig}
Steps of the shrink-wrapping algorithm in 2D.
The algorithm is initialized by inserting the corners of the loose bounding box of the input (red)
into a Delaunay triangulation, and all finite triangles are tagged inside (grey).
The current gate (green edge) popped out from the queue is alpha-traversable. The triangle adjacent
to the gate is tagged outside when it does not intersect the input, and new alpha-traversable gates
are pushed to the queue. When the adjacent triangle intersects the input, a new Steiner point (large green disc)
is computed and inserted into the triangulation, all neighboring triangles are tagged inside,
new alpha-traversable gates are pushed to the queue, and traversal is resumed.
Grey edges depict the Delaunay triangulation. Blue edges depict the Voronoi diagram.
Pink circles depict the empty circle of radius alpha. The output edges (dark blue) separate inside from outside triangles.
\cgalFigureCaptionEnd

\subsection aw2_guarantees Guarantees

The algorithm is proven to terminate and to produce a set of 1-manifold, simple polygons
that strictly enclose the input data.
The key element to the proof is that we wrap from outside to inside and never allow a face
that intersects the input to be flagged outside.
Furthermore, both criteria that lead to refinement of the triangulation insert Steiner points
that are guaranteed to break the faces in need of refinement and reduce the neighbor edges' circumradii.

Because the main refinement criterion is the insertion of an intersection between a dual Voronoi edge
and an offset of the input, or the projection of a Voronoi vertex onto the offset of the input,
the algorithm has similarities to popular meshing algorithms based on Delaunay filtering
and refinement (see \ref PkgMesh3).

\section aw2_interface Interface

Our algorithm takes as input a set of segments in 2D, provided either as a segment soup or
as a set of polygons, and two user-defined scalar parameters: the <em>alpha</em> and the <em>offset</em> values.
It proceeds by shrink-wrapping and refining a 2D Delaunay triangulation starting from a loose bounding box of the input.
The parameter <em>alpha</em> refers to the size of cavities or holes that cannot be traversed during wrapping,
and hence to the final level of detail, as alpha acts like a sizing field in a common Delaunay
refinement algorithm (\ref PkgMesh3).
The parameter <em>offset</em> refers to the distance between the vertices of the refined triangulation
and the input, so that a large offset translates into a loose enclosing of the input.
This second parameter offers a means to control the trade-off between tightness and complexity.

The main entry point of the component is the global function `CGAL::alpha_wrap_2()` that generates the alpha wrap;
this function takes as input a point set, a polyline soup, or a polygon soup.
There is no prerequisite on the input connectivity so that it can take inputs
with islands, self-intersections, or overlaps, as well as combinatorial or geometrical degeneracies.

The underlying traits class must be a model of the `AlphaWrapTraits_2` concept. It should use
a floating point number type as inexactness is inherent to the algorithm since there is no closed
form description of new vertices on the offset surface.

The output is a multi polygon, i.e., a set of polygons, whose type is chosen by the user,
under the constraint that it must be a model of the `MultipolygonWithHoles_2` concept.

A three-dimensional version of this package is also available: \ref PkgAlphaWrap3.

\section aw2_parameters Choosing Parameters

The two parameters of the algorithm impact both the level of detail and complexity of the output wrap.

\subsection aw2_alpha Alpha

The main parameter, alpha, controls whether a Delaunay edge is traversable during shrink-wrapping.
Alpha's main purpose is to control the size
of the empty balls used during wrapping, and thus to determine which features will appear in the output:
indeed, an edge is alpha-traversable if its circumradius is larger than alpha; hence, the algorithm
can only shrink-wrap through straits or holes with diameters larger than alpha.
A second, less direct consequence is that as long as an edge has a circumradius larger than alpha,
the incident inside face will be visited and possibly refined.
Therefore, when the algorithm terminates, all edges have a circumradius smaller than alpha.
This parameter thus also behaves like a sizing criterion on the edges of the output.

\cgalFigureAnchor{aw2_alpha_param_fig}
<center>
<img src="aw2_alpha_croc.png" style="max-width:90%;"/>
</center>
\cgalFigureCaptionBegin{aw2_alpha_param_fig}
Impact of the alpha parameter on the output.
(Left) The input segment soup, generated from an SVG file. The input
has many self-intersections, non-manifold vertices, superfluous geometric details
and spurious topological structures.
(Middle & Right) This component approximates the input conservatively and produces valid polygons
with different complexity and fidelity to the input, depending on the alpha parameter.
The smaller the alpha, the deeper the shrink-wrapping process will enter cavities.
The alpha parameter is decreasing from left to right, to respectively 1/20, 1/100, and 1/500 of the longest diagonal of the input bounding box.
A large alpha will produce an output less complex but less faithful to the input.
\cgalFigureCaptionEnd

\subsection aw2_offset Offset

The second parameter, the offset distance, controls the distance from the input and thus the definition
of the offset isosurface onto which the vertices of the output polygon are located.
This parameter controls the tightness of the result, which has, in turn, a few consequences.
Firstly, locating vertices away from the input enables the algorithm to generate
a less complex result, especially in convex areas. A trivial example of this behavior would be a very dense
circle-shaped polygon, for which an as-tight-as-possible envelope would also need to be very dense.
Secondly, the farther the isosurface is from the input, the more new points are inserted
through the first criterion (i.e., through intersection with dual Voronoi edge, see Section \ref aw2_algorithm);
thus, the quality of the output improves in terms of angles of the triangle elements.
Finally, and depending on the value of the alpha parameter, a large offset can also offer defeaturing capabilities.
However, using a small offset parameter will tend to better preserve sharp features as projection
Steiner points tend to project onto convex sharp features.

\cgalFigureAnchor{aw2_steiner_fig}
<center>
<img src="aw2_steiner.jpg" style="max-width:90%;"/>
</center>
\cgalFigureCaptionBegin{aw2_steiner_fig}
Steiner points.
The projection Steiner points (green) are computed by projecting the triangle circumcenter onto the offset.
The intersection Steiner points (blue) are computed as the first intersection point between the Voronoi edge and the offset.
(Left) When the offset parameter is small, the algorithm produces more projection Steiner points,
which tends to improve the preservation of convex sharp features.
(Right) When the offset parameter is large, the algorithm produces more intersection Steiner points.
\cgalFigureCaptionEnd

By default, we recommend to set the offset parameter to a small fraction of alpha, such that alpha
becomes the main parameter that controls the final level of detail.

The image below illustrates the impact of both parameters.

\cgalFigureAnchor{aw2_param_grid_fig}
<center>
<img src="aw2_alpha_offset_bike.jpg" style="max-width:80%;"/>
</center>
\cgalFigureCaptionBegin{aw2_param_grid_fig}
Different alpha and offset values on the bike model.
The x-axis represents the offset value equal to 1/5000, 1/500, 1/50, and 1/5 of the longest diagonal of the input bounding box, from left to right.
The y-axis represents the alpha value equal to 1/500, 1/50, and 1/5 of the longest diagonal of the input bounding box, from bottom to top.
Depending on the alpha value, an offset too small or too large will produce outputs with higher complexity.
For each alpha, the models with lower complexity can be used as a scale-space representations for collision detection, from near to far distances.
\cgalFigureCaptionEnd

\subsection aw2_two_side A Note on "Two-Sided" Wraps

The offset parameter is crucial to our approach because it guarantees that the output is a
set of 1-manifold, simple polygons.
Indeed, and even when the input is a zero-area structure such as a single segment,
the output wrap is a thin domain enclosing the said segment, see \cgalFigureRef{aw2_inputs_fig}.

Users should keep in mind that the wrapping algorithm performs using an unsigned distance field,
and has no means of determining whether it is acting on both sides of a same input segment.
It will thus produce two-sided wraps in the case of holes in the input and
values of alpha smaller than the size of the holes.

\cgalFigureAnchor{aw2_double_sided_fig}
<center>
<img src="aw2_double_sided.jpg" style="max-width:40%;"/>
</center>
\cgalFigureCaptionBegin{aw2_double_sided_fig}
Wrapping a Bunny in 2D, with decreasing values for alpha.
When alpha is small enough with respect the diameter of the holes, the algorithm generates a two-sided wrap.
\cgalFigureCaptionEnd

\section aw2_examples Examples

\subsection aw2_examples_polylines Wrapping a Set of Polylines

The following example illustrates how to construct the wrap of a soup of 2D segments.
Alpha is set to 1/20 of the bounding box's longest diagonal edge length,
and offset set to 1/30 of alpha (i.e., 1/600 of the bounding box diagonal edge length).

\cgalExample{Alpha_wrap_2/polyline_wrap_2.cpp}

\subsection aw2_examples_polygons Wrapping a Multipolygon

For polygons, we use multipolygons to represent input sets of polygons (possibly with holes).
The following example uses the \link IOStreamWKT WKT file format\endlink to read such input
and wrap it. Note the possible usage of the \ref PkgPolygonRepair package if a pre-emptive
repair of the polygons is desired.

\cgalExample{Alpha_wrap_2/polygon_wrap_2.cpp}

\subsection aw2_examples_points Wrapping a Point Cloud

Finally, the following example demonstrates how to wrap a 2D point set constructed from the projection
of an input 3D point cloud.

\cgalExample{Alpha_wrap_2/point_set_wrap_2.cpp}

*/

}

---

### Alpha Wrap 2 Doc Alpha Wrap 2 Examples (`Alpha_wrap_2/doc/Alpha_wrap_2/examples.txt`)

/*!
\example Alpha_wrap_2/polygon_wrap_2.cpp
\example Alpha_wrap_2/polyline_wrap_2.cpp
\example Alpha_wrap_2/triangle_soup_wrap_2.cpp
\example Alpha_wrap_2/point_set_wrap_2.cpp
*/

---

### Alpha Wrap 3 Doc Alpha Wrap 3 PackageDescription (`Alpha_wrap_3/doc/Alpha_wrap_3/PackageDescription.txt`)

/// \defgroup PkgAlphaWrap3Ref Reference Manual

/// \defgroup AW3_free_functions_grp Free Functions
/// Functions to create a wrap from point clouds, triangle soups, and triangle meshes.
/// \ingroup PkgAlphaWrap3Ref

/*!
\addtogroup PkgAlphaWrap3Ref
\cgalPkgDescriptionBegin{3D Alpha Wrapping,PkgAlphaWrap3}
\cgalPkgPicture{alpha_wrap_3.jpg}
\cgalPkgSummaryBegin
\cgalPkgAuthors{Pierre Alliez, David Cohen-Steiner, Michael Hemmer, Cédric Portaneri, and Mael Rouxel-Labbé}
\cgalPkgDesc{This component takes a 3D triangle mesh, a triangle soup, or a point set as input, and generates
             a valid triangulated surface mesh that strictly contains the input (watertight, intersection-free
             and 2-manifold). The algorithm proceeds by shrink-wrapping
             and refining a 3D Delaunay triangulation starting from a loose bounding box of the input.
             Two user-defined parameters, alpha and offset, offer control over the maximum size
             of cavities where the shrink-wrapping process can enter, and the tightness
             of the final surface mesh to the input, respectively. Once combined, these parameters
             provide a means to trade fidelity to the input for complexity of the output.}
\cgalPkgManuals{Chapter_3D_Alpha_wrapping,PkgAlphaWrap3Ref}
\cgalPkgSummaryEnd
\cgalPkgShortInfoBegin
\cgalPkgSince{5.5}
\cgalPkgDependsOn{\ref PkgTriangulation3 and \ref PkgPolygonMeshProcessing}
\cgalPkgBib{cgal:achpr-aw3}
\cgalPkgLicense{\ref licensesGPL "GPL"}
\cgalPkgShortInfoEnd
\cgalPkgDescriptionEnd

\cgalClassifedRefPages

\cgalCRPSection{Functions}
- \link AW3_free_functions_grp `CGAL::alpha_wrap_3()` \endlink
*/

---

### Alpha Wrap 3 Doc Alpha Wrap 3 Alpha Wrap 3 (`Alpha_wrap_3/doc/Alpha_wrap_3/alpha_wrap_3.txt`)

namespace CGAL {

/*!

\mainpage User Manual
\anchor Chapter_3D_Alpha_wrapping
\cgalAutoToc

\authors Pierre Alliez, David Cohen-Steiner, Michael Hemmer, Cédric Portaneri, Mael Rouxel-Labbé

<center>
<img src="aw3_bike_lod.jpg" style="max-width:70%;"/>
</center>

Note: a two-dimensional version of this package is also available: \ref PkgAlphaWrap2.

\section aw3_introduction Introduction

Various tasks in geometric modeling and processing require 3D objects represented as valid surface meshes,
where "valid" refers to meshes that are watertight, intersection-free, orientable, and 2-manifold.
Such representations offer well-defined notions of interior/exterior and geodesic neighborhoods.

3D data are usually acquired through measurements followed by reconstruction, designed by humans,
or generated through imperfect automated processes.
As a result, they can exhibit a wide variety of defects including gaps, missing data,
self-intersections, degeneracies such as zero-volume structures, and non-manifold features.

Given the large repertoire of possible defects, many methods and data structures have been proposed
to repair specific defects, usually with the goal of guaranteeing specific properties in the repaired 3D model.
Reliably repairing all types of defects is notoriously difficult and is often an ill-posed problem
as many valid solutions exist for a given 3D model with defects.
In addition, the input model can be overly complex with unnecessary geometric details,
spurious topological structures, nonessential inner components, or excessively fine discretizations.
For applications such as collision avoidance, path planning, or simulation,
getting an approximation of the input can be more relevant than repairing it.
Approximation herein refers to an approach capable of filtering out inner structures,
fine details and cavities, as well as wrapping the input within a user-defined offset margin.

Given an input 3D geometry, we address the problem of computing a conservative approximation,
where conservative means that the output is guaranteed to strictly enclose the input.
We seek unconditional robustness in the sense that the output mesh should be valid (oriented,
2-manifold, and without self-intersections), even for raw input with many defects
and degeneracies.
The default input is a soup of 3D triangles, but the generic interface leaves the door open
to other types of finite 3D primitives such as triangle soups and point sets.

\cgalFigureAnchor{aw3_input_1_fig}
<center>
<img src="aw3_triangle_soup.jpg" style="max-width:70%;"/>
</center>
\cgalFigureCaptionBegin{aw3_input_1_fig}
Shrink-wrapping output from a triangle soup, with many intersections and gaps.
From left to right, input model, output wrap, and superposition.
\cgalFigureCaptionEnd

\cgalFigureAnchor{aw3_input_2_fig}
<center>
<img src="aw3_non_manifold_cases.jpg" style="max-width:75%;"/>
</center>
\cgalFigureCaptionBegin{aw3_input_2_fig}
Dealing with non-manifold features and degeneracies.
From left to right, a non-manifold vertex, self-intersecting faces and two adjacent triangles
representing a zero-volume structure.
The algorithm handles these cases by wrapping an offset of the input.
\cgalFigureCaptionEnd

\section aw3_definition Approach

Many approaches have been devised to enclose a 3D model within a volume, featuring different balances
between the runtime and quality (i.e., tightness) of the approximation.
Within the simplest cases, an axis-aligned or oriented bounding box clearly satisfies some desired properties;
however, the approximation error is uncontrollable and often very large.
Computing the convex hull of the input also matches some of the desired properties
and improves the quality of the result, albeit at the price of increasing the runtime.
However, the approximation remains crude, especially in the case of several components.

The convex hull is, in fact, a special case of alpha shapes (\ref Chapter_3D_Alpha_Shapes).
Mathematically, the alpha shape is a subcomplex of the Delaunay triangulation, with simplicies
being part of the complex depending on the size of their minimal (empty) Delaunay ball.
Intuitively, constructing 3D alpha shapes can be thought of as carving 3D space with an empty ball
of user-defined radius alpha.
Alpha shapes yield provable, good piecewise-linear approximations of a shape \cgalCite{bb-srmua-97t},
but are defined on point sets, whereas we wish to deal with more general input data, such as triangle soups.
Even after sampling the triangle soup, alpha shapes do not guarantee to be conservative for any alpha.
Finally, inner structures are also carved within the volumes, instead of being filtered out.

Inspired by alpha shapes, we replace the above notion of carving by <em>shrink-wrapping</em>:
we iteratively construct a subcomplex of a 3D Delaunay triangulation by starting from
a simple 3D Delaunay triangulation enclosing the input, and then iteratively removing eligible tetrahedra
that lie on the boundary of the complex.
In addition, the underlying triangulation---and thus the complex incidentally---is refined
as shrinking proceeds.
Thus, instead of carving from the convex hull of the input data as in alpha shapes, we construct
an entirely new mesh through a Delaunay refinement-like algorithm. The refinement algorithm inserts Steiner points
on the boundary of an offset volume, defined as a level set of the unsigned distance field to the input.

This process both prevents the creation of inner structures within the output and avoids superfluous computations.
In addition, detaching our mesh construction from the geometry and discretization of the input has several advantages:
(1) the underlying data is not restricted to a specific format (triangle soups, polygon soups, point clouds, etc.)
as all that is required is answering three basic geometric queries: (a) the distance between a point
and the input, (b) the projection of a query point onto the input, (c) an intersection test
between a tetrahedron and the input, and (2) The user has more freedom to trade tightness
to the input for final mesh complexity, as constructing a conservative approximation on a large offset
of the input requires fewer mesh elements.

\subsection aw3_algorithm Algorithm

<b>Initialization</b>. The algorithm is initialized by inserting the eight corner vertices
of a loose bounding box into a 3D Delaunay triangulation.
In the 3D Delaunay triangulation of \cgal, all triangle facets are adjacent to two tetrahedron cells.
Each facet of the boundary of the Delaunay triangulation, which coincides with one facet
of the convex hull of the triangulation vertices, is adjacent to a so-called <em>infinite</em> tetrahedron cell,
an abstract cell connected to the so-called <em>infinite vertex</em> to ensure the aforementioned double-facet adjacency.
Initially, all infinite cells are tagged as outside, and all finite tetrahedron cells are tagged as inside.

<b>Shrink-wrapping</b>. The shrink-wrapping algorithm proceeds by traversing the cells
of the Delaunay triangulation from outside to inside, flood-filling from one cell to its adjacent cell,
and tagging the adjacent cell as outside whenever possible (the term possible is specified later).
Flood filling is implemented via a priority queue of Delaunay triangle facets representing
the traversal between the two adjacent cells of the facet, from outside to inside.
These triangle facets are referred to as <em>gates</em> in the following.

Given an outside cell and its adjacent inside cell, the common facet (i.e., a gate) is said
to be <em>alpha-traversable</em> if its circumradius is larger than the user-defined parameter alpha,
where circumradius refers to the radius of the relating triangle's Delaunay ball.
Intuitively, cavities smaller than alpha are not accessible as their gates are not alpha-traversable.

Initialized by the alpha-traversable gates on the convex hull, the priority queue contains only
alpha-traversable gates and is sorted by decreasing order
of the circumradius of the gate.
Traversal can be seen as a continuous process that advances along dual Voronoi edges of the gates,
with a pencil of empty balls circumscribing the gate.

\cgalFigureAnchor{aw3_pencil_fig}
<center>
<img src="aw3_pencil.png" style="max-width:40%;"/>
</center>
\cgalFigureCaptionBegin{aw3_pencil_fig}
(Left) Pencil of empty circles (blue) circumscribing a Delaunay edge (green) in a 2D Delaunay triangulation (black).
From the top triangle circumcenter <em>c1</em> to the bottom triangle circumcenter <em>c2</em>, the dual Voronoi edge denoted by <em>e</em> (doted red) is the trace of centers of the largest circles that are empty of Delaunay vertex.
(Right) The graph corresponding to the left example. The x-axis corresponds to the position of empty circle centers located on the Voronoi edge <em>e</em>, from <em>c1</em> to <em>c2</em>. The y-axis is the radius value of the corresponding empty circles. In this case, the minimum radius of this pencil of empty circle is located at the midpoint of the green Delaunay edge.
In our algorithm, a gate (green Delaunay edge) is said to be not alpha-traversable when the minimum radius of the pencil of empty circle is smaller than alpha.
\cgalFigureCaptionEnd

When traversing from an outside cell \f$ c_o \f$ to an inside cell \f$ c_i \f$ through an alpha-traversable facet \f$ f \f$,
two criteria are tested to prevent the wrapping process from colliding with the input:

(1) We check for an intersection between the dual Voronoi edge of \f$ f \f$, i.e. the segment between
the circumcenters of the two incident cells, and the <em>offset surface</em>, defined as the level set
of unsigned isosurface to the input.
If one or several intersections exists, the first intersection point, along the dual Voronoi edge
oriented from outside to inside is inserted into the triangulation as a Steiner point.

(2) If the dual Voronoi edge does not intersect the offset surface but the neighboring cell \f$ c_i \f$
intersects the input, we compute the projection of the circumcenter of \f$ c_i \f$
onto the offset surface, and insert it into the triangulation as a Steiner point (which destroys \f$ c_i \f$).

After each of the above Steiner point insertions, all new incident cells are tagged as inside,
and the newly alpha-traversable gates are pushed into the priority queue.

If none of the above two criteria are met, the neighboring cell \f$ c_i \f$ is traversed and tagged as outside.
Alpha-Traversable facets of \f$ c_i \f$ that are separating inside from outside cells are pushed as new gates into the priority queue.

Once the queue empties---a process that is guaranteed as facets (and their circumradii) become smaller
due to the insertion of new Steiner points---the construction phase terminates.
The output triangle surface mesh is extracted from the Delaunay triangulation as the set of facets
separating inside from outside cells.

The figure below depicts the steps of the algorithm in 2D.

\cgalFigureAnchor{aw3_steps_fig}
<center>
<img src="aw3_steps.jpg" style="max-width:95%;"/>
</center>
\cgalFigureCaptionBegin{aw3_steps_fig}
Steps of the shrink-wrapping algorithm in 2D.
The algorithm is initialized by inserting the corners of the loose bounding box of the input (red)
into a Delaunay triangulation, and all finite triangles are tagged inside (grey).
The current gate (green edge) popped out from the queue is alpha-traversable. The triangle adjacent
to the gate is tagged outside when it does not intersect the input, and new alpha-traversable gates
are pushed to the queue. When the adjacent triangle intersects the input, a new Steiner point (large green disc)
is computed and inserted into the triangulation, all neighboring triangles are tagged inside,
new alpha-traversable gates are pushed to the queue, and traversal is resumed.
Grey edges depict the Delaunay triangulation. Blue edges depict the Voronoi diagram.
Pink circles depict the empty circle of radius alpha. The output edges (dark blue) separate inside from outside triangles.
\cgalFigureCaptionEnd

\subsection aw3_guarantees Guarantees

The algorithm is proven to terminate and to produce a 2-manifold triangulated surface mesh
that strictly encloses the input data.
The key element to the proof is that we wrap from outside to inside and never allow a cell
that intersects the input to be flagged outside.
Furthermore, both criteria that lead to refinement of the triangulation insert Steiner points
that are guaranteed to break the cells in need of refinement and reduce the neighbor facets circumradii.

Because the main refinement criterion is the insertion of an intersection between a dual Voronoi edge
and an offset of the input, or the projection of a Voronoi vertex onto the offset of the input,
the algorithm has similarities to popular meshing algorithms based on Delaunay filtering
and refinement (see \ref Chapter_3D_Mesh_Generation).

\section aw3_interface Interface

Our algorithm takes as input a set of triangles in 3D, provided either as a triangle soup or
as a triangle surface mesh, and two user-defined scalar parameters: the <em>alpha</em> and the <em>offset</em> values.
It proceeds by shrink-wrapping and refining a 3D Delaunay triangulation starting from a loose bounding box of the input.
The parameter <em>alpha</em> refers to the size of cavities or holes that cannot be traversed during wrapping,
and hence to the final level of detail, as alpha acts like a sizing field in a common Delaunay
refinement algorithm (\ref Chapter_3D_Mesh_Generation).
The parameter <em>offset</em> refers to the distance between the vertices of the refined triangulation
and the input, so that a large offset translates into a loose enclosing of the input.
This second parameter offers a means to control the trade-off between tightness and complexity.

The main entry point of the component is the global function `CGAL::alpha_wrap_3()` that generates the alpha wrap;
this function takes as input a polygon soup or a polygon mesh.
There is no prerequisite on the input connectivity so that it can take an arbitrary triangle soup,
with islands, self-intersections, or overlaps, as well as combinatorial or geometrical degeneracies.

The underlying traits class must be a model of the `Kernel` concept. It should use
a floating point number type as inexactness is inherent to the algorithm since there is no closed
form description of new vertices on the offset surface.

The output is a triangle surface mesh whose type is chosen by the user, under the constraint
that it must be a model of the `MutableFaceGraph` concept.

\section aw3_parameters Choosing Parameters

The two parameters of the algorithm impact both the level of detail and complexity of the output mesh.

\subsection aw3_alpha Alpha

The main parameter, alpha, controls whether a Delaunay facet is traversable during shrink-wrapping.
Alpha's main purpose is to control the size
of the empty balls used during wrapping, and thus to determine which features will appear in the output:
indeed, a facet is alpha-traversable if its circumradius is larger than alpha; hence, the algorithm
can only shrink-wrap through straits or holes with diameters larger than alpha.
A second, less direct consequence is that as long as a facet has a circumradius larger than alpha,
the incident inside cell will be visited and possibly refined.
Therefore, when the algorithm terminates, all facets have a circumradius smaller than alpha.
This parameter thus also behaves like a sizing criterion on the triangle facets of the output.

\cgalFigureAnchor{aw3_alpha_param_fig}
<center>
<img src="aw3_church_lod.jpg" style="max-width:90%;"/>
</center>
\cgalFigureCaptionBegin{aw3_alpha_param_fig}
Impact of the alpha parameter on the output.
(Left) The input triangle mesh, generated by surface reconstruction from a raw point cloud,
has many non-manifold edges and vertices, superfluous geometric details and spurious topological structures.
(Right) This component approximates the input conservatively and produces valid meshes with different
complexity and fidelity to the input, depending on the alpha parameter.
The smaller the alpha, the deeper the shrink-wrapping process will enter cavities.
The alpha parameter is decreasing from left to right, to respectively 1/50, 1/100 and 1/300 of the longest diagonal of the input bounding box.
A large alpha will produce an output less complex but less faithful to the input.
\cgalFigureCaptionEnd

\subsection aw3_offset Offset

The second parameter, the offset distance, controls the distance from the input and thus the definition
of the offset isosurface onto which the vertices of the output mesh are located.
This parameter controls the tightness of the result, which has, in turn, a few consequences.
Firstly, locating vertices away from the input enables the algorithm to generate
a less complex mesh, especially in convex areas. A trivial example of this behavior would be a very dense mesh
of a sphere, for which an as-tight-as-possible envelope would also be very dense.
Secondly, the farther the isosurface is from the input, the more new points are inserted
through the first criterion (i.e., through intersection with dual Voronoi edge, see Section \ref aw3_algorithm);
thus, the quality of the output improves in terms of angles of the triangle elements.
Finally, and depending on the value of the alpha parameter, a large offset can also offer defeaturing capabilities.
However, using a small offset parameter will tend to better preserve sharp features as projection
Steiner points tend to project onto convex sharp features.

\cgalFigureAnchor{aw3_offset_param_fig}
<center>
<img src="aw3_sharp_feature.jpg" style="max-width:90%;"/>
</center>
\cgalFigureCaptionBegin{aw3_offset_param_fig}
Impact of the offset parameter on the output.
(Left) Input mesh generated by meshing a NURBS CAD model in parameter space.
(Right) The smaller the offset, the closest sample points are to the input.
The offset parameter is decreasing from left to right, to respectively 1/50, 1/200 and 1/1000 of the longest diagonal of the input bounding box.
The alpha parameter is equal to 1/50 of the longest diagonal of the input bounding box for all level of details.
A larger offset will produce an output less complex with better triangle quality.
However, the sharp features (red edges) are well-preserved when the offset parameter is small.
\cgalFigureCaptionEnd

\cgalFigureAnchor{aw3_steiner_fig}
<center>
<img src="aw3_steiner.jpg" style="max-width:90%;"/>
</center>
\cgalFigureCaptionBegin{aw3_steiner_fig}
Steiner points.
The projection Steiner points (green) are computed by projecting the triangle circumcenter onto the offset.
The intersection Steiner points (blue) are computed as the first intersection point between the Voronoi edge and the offset.
(Left) When the offset parameter is small, the algorithm produces more projection Steiner points,
which tends to improve the preservation of convex sharp features.
(Right) When the offset parameter is large, the algorithm produces more intersection Steiner points,
which tends to generate triangles with better quality in terms of angles, in 3D.
\cgalFigureCaptionEnd

By default, we recommend to set the offset parameter to a small fraction of alpha, such that alpha
becomes the main parameter that controls the final level of detail.

The image below illustrates the impact of both parameters.

\cgalFigureAnchor{aw3_param_grid_fig}
<center>
<img src="aw3_alpha_offset_bike.jpg" style="max-width:80%;"/>
</center>
\cgalFigureCaptionBegin{aw3_param_grid_fig}
Different alpha and offset values on the bike model (533,000 triangles).
The x-axis represents the offset value equal to 1/5000, 1/2000, 1/500, 1/200, 1/50, 1/20 and 1/5 of the longest diagonal of the input bounding box, from left to right.
The y-axis represents the alpha value equal to 1/300, 1/100, 1/50, 1/20 and 1/5 of the longest diagonal of the input bounding box, from bottom to top.
The numbers below each level of detail represents their number of triangles.
Depending on the alpha value, an offset too small or too large will produce output mesh with higher complexity.
For each alpha, the models with lower complexity can be used as a scale-space representations for collision detection, from near to far distances.
\cgalFigureCaptionEnd

\subsection aw3_two_side A Note on "Two-Sided" Wraps

The offset parameter is crucial to our approach because it guarantees that the output is a closed,
2-manifold surface mesh.
Indeed, and even when the input is a zero-volume structure such as a single 3D triangle,
the output wrap is a thin volume enclosing the said triangle \cgalFigureRef{aw3_input_2_fig}.

Users should keep in mind that the wrapping algorithm has no means of determining whether it is acting on the inside or the outside
of the unsigned distance field, and will thus produce two-sided wraps in the case of holes in the input
and values of alpha smaller than the size of the holes.

\cgalFigureAnchor{aw3_double_sided_fig}
<center>
<img src="aw3_double_sided.jpg" style="max-width:80%;"/>
</center>
\cgalFigureCaptionBegin{aw3_double_sided_fig}
Two-sided wrap.
(Left) Wrapping a Bunny in 2D, with decreasing values for alpha.
(Right) Wrapping a defect-laden Bunny in 3D. The rightmost column depicts a clipped visualization
of the inside. When alpha is small enough with respect the diameter of the holes, the algorithm generates a two-sided wrap.
\cgalFigureCaptionEnd

\section aw3_performance Performance

The charts below plots the computation times of the wrapping algorithm on the Thingi10k dataset, as well as the complexity of the output triangle mesh.

\cgalFigureAnchor{aw3_bench_fig}
<center>
<img src="aw3_thingi10k_benchmark.jpg" style="max-width:80%;"/>
</center>
\cgalFigureCaptionBegin{aw3_bench_fig}
Execution times and output complexity for different values of alpha on the Thingi10k data set.
Alpha increases from 1/20 to 1/200 of the length of bounding box diagonal.
The x-axis represents the complexity of the output wrap mesh in number of triangle facets.
The y-axis represents the total computation time, in seconds.
The color and diameter of the dots represent the number of faces in the input triangle soup,
ranging from 10 (green) to 3154000 (blue).
\cgalFigureCaptionEnd

\section aw3_examples Examples

Here is an example with an input triangle mesh, with alpha set to 1/20 of the bounding box's longest diagonal edge length,
and offset set to 1/30 of alpha (i.e., 1/600 of the bounding box diagonal edge length).

\cgalExample{Alpha_wrap_3/triangle_mesh_wrap.cpp}

Some triangle soups might not be representable as a mesh due to non-manifoldness or incompatible orientations.
Such triangle soup is nevertheless a valid input for the wrapping algorithm, as illustrated
in the following example.

\cgalExample{Alpha_wrap_3/triangle_soup_wrap.cpp}

Here is an example with a point cloud.

\cgalExample{Alpha_wrap_3/point_set_wrap.cpp}

*/

}

---

### Alpha Wrap 3 Doc Alpha Wrap 3 Examples (`Alpha_wrap_3/doc/Alpha_wrap_3/examples.txt`)

/*!
\example Alpha_wrap_3/triangle_mesh_wrap.cpp
\example Alpha_wrap_3/triangle_soup_wrap.cpp
\example Alpha_wrap_3/point_set_wrap.cpp
*/

---

### Apollonius Graph 2 Doc Apollonius Graph 2 Apollonius Graph 2 (`Apollonius_graph_2/doc/Apollonius_graph_2/Apollonius_graph_2.txt`)

namespace CGAL {
/*!

\mainpage User Manual
\anchor Chapter_2D_Apollonius_Graphs
\anchor chapterapollonius2
\cgalAutoToc
\authors Menelaos Karavelas and Mariette Yvinec

This chapter describes the two-dimensional Apollonius graph
of \cgal. We start with a few definitions in
Section \ref secapollonius2definitions.
The software design of the 2D Apollonius graph package is described
in Section \ref secapollonius2design.
In Section \ref secapollonius2traits we discuss the geometric
traits of the 2D Apollonius graph package and in Section
\ref secapollonius2hierarchy the Apollonius graph hierarchy, a data
structure suitable for fast nearest neighbor queries, is briefly
described.

\section secapollonius2definitions Definitions

\cgalFigureBegin{figapollonius,apollonius_diagram.png,apollonius_graph.png}
The Apollonius diagram (left) and its dual the Apollonius graph (right).
\cgalFigureEnd

The 2D Apollonius graph class of \cgal is designed to compute the
dual of the <I>Apollonius diagram</I> or, as it is also known, the
<I>Additively weighted Voronoi diagram</I>. The algorithm that has been
implemented is dynamic, which means that we can perform insertions and
deletions online. The corresponding \cgal class is called
`Apollonius_graph_2<ApolloniusGraphTraits_2,ApolloniusGraphDataStructure_2>`
and will be discussed in more detail in the sequel. The interested
reader may want to refer to the paper by Karavelas and Yvinec
\cgalCite{cgal:ky-dawvd-02} for the general idea as well as the details of the
algorithm implemented.

Before describing the details of the implementation we make a brief
introduction to the theory of Apollonius diagrams.
The Apollonius diagram is defined over a set of sites
\f$ P_i=(c_i,w_i)\f$, \f$ i=1,\ldots,n\f$, where \f$ c_i\f$ is the point and \f$ w_i\f$
the weight of \f$ P_i\f$. It is a subdivision of the plane into connected
regions, called <I>cells</I>, associated with the sites (see
\cgalFigureRef{figapollonius} (left)). The cell of a
site \f$ P_i\f$ is the locus of points on the plane that are
closer to \f$ P_i\f$ than any other site \f$ P_j\f$, \f$ j\neq i\f$.
The distance \f$ \delta(x, P_i)\f$ of a point \f$ x\f$ in the plane to a
site \f$ P_i\f$ is defined as:
\f[ \delta(x,P_i)=\|x-c_i\|-w_i, \f]
where \f$ \|\cdot\|\f$ denotes the Euclidean norm.
It can easily be seen that it is a generalization of the Voronoi
diagram for points, which can actually be obtained if all the weights
\f$ w_i\f$ are equal. Unlike the case of points, however, it is
possible that a site \f$ P_i\f$ might have an empty cell. This
can also happen in the case of the power diagram, whose dual is the
regular triangulation (see Section
\ref Section_2D_Triangulations_Regular ). If this is
the case we call the site <I>hidden</I> (these are the black
circles in \cgalFigureRef{figapollonius} ). A site which is not
hidden will be referred to as <I>visible</I>.

If all weights \f$ w_i\f$ are non-negative, the Apollonius
diagram can be viewed as the Voronoi diagram of the set of circles
\f$ \{P_1,\ldots, P_n\}\f$, where \f$ c_i\f$ is the center of the circle \f$ P_i\f$
and \f$ w_i\f$ its radius. If the weights are allowed to be negative,
we need to go to 3D in order to explain what the Apollonius diagram
means geometrically. We identify the 2D Euclidean plane with the
\f$ xy\f$-plane in 3D. Then the Voronoi diagram of a set of points can be
seen as the vertical projection on the \f$ xy\f$-plane of the lower
envelope of a set of 3D cones defined as follows: for each point \f$ p\f$
in the set of 2D points we have a cone \f$ C_p\f$ whose apex is the point
\f$ p\f$. The axis of
\f$ C_p\f$ is a line parallel to the \f$ z\f$-axis passing through \f$ p\f$, the
angle of \f$ C_p\f$ is \f$ 45^\circ\f$ and, finally \f$ C_p\f$ is facing in the
positive \f$ z\f$-direction (that is, \f$ C_p\f$ is contained in the positive
\f$ z\f$-halfspace).
The Apollonius diagram corresponds to shifting the
apexes of these cones in the \f$ z\f$-direction by a quantity equal to the
weight. Sites with negative weight will give rise to
cones whose apex is in the negative \f$ z\f$-halfspace and sites
with positive weight will give rise to cones whose apex is in the
positive \f$ z\f$-halfspace. In a manner analogous to the case of points,
the Apollonius diagram can then be defined as the vertical projection
on the \f$ xy\f$-plane of the lower envelope of the set of shifted cones.
Notice that when all apexes are translated along the \f$ z\f$-direction by
the same amount, the projection of the lower envelope of the set of
cones does not change. In particular, we can translate all cones by a
large enough amount so that all apexes are in the positive
\f$ z\f$-halfspace. Algebraically, this means that the Apollonius diagram
does not change if we add to all weights the same quantity, which in
particular, implies that we can assume without loss of generality that
all weights are positive. Given the observations above and in order to
simplify our discussion of Apollonius diagrams, we will, from now on,
assume that all weights are positive, and we will refer to the
sites as circles.

The Apollonius diagram is a planar graph, and so is its dual, the
Apollonius graph. There are many ways to embed it on the plane and one
such way is shown in \cgalFigureRef{figapollonius} (right).
The Apollonius graph is uniquely defined once we have
the Apollonius diagram. If the circles are in <I>general position</I>
(see precise definition below), then the Apollonius graph is a graph
with triangular faces away from
the convex hull of the set of circles (by triangular we mean that
every face has exactly three edges). Near the convex hull we may
have some spikes (i.e., vertices of degree 1). To unify our approach
and handling of the Apollonius graph we add to the set of (finite)
circles a fictitious circle at infinity, which we call the
<I>site at infinity</I>. We can then connect all vertices of the outer
face of the Apollonius graph to the site at infinity which gives us
a graph with the property that all of its faces are now
triangular. However, the Apollonius graph is not a triangulation for
two main reasons: we cannot always embed it on the plane with straight
line segments that yield a triangulation and, moreover, we may have two
faces of the graph that have two edges in common, which is not allowed
in a triangulation. Both of these particularities appear when we
consider the Apollonius graph of the set of circles in
\cgalFigureRef{figapollonius}.

We would like to finish our brief introduction to the theory of
Apollonius graphs by discussing the concept of general position. We say
that a set of circles is in general position if no two triplets of
circles have the same tritangent circle. This statement is rather
technical and it is best understood in the context of points. The
equivalent statement for points is that we have no two triplets of
points that define the same circumcircle, or equivalently that no
four points are co-circular. The statement about general position made
above is a direct generalization of the (much simpler to understand)
statement about points. On the contrary, when we have circles in
degenerate position, the Apollonius graph has faces with more than
three edges on their boundary. We can get a triangulated version of
the graph by simply <I>triangulating</I> the corresponding faces in an
arbitrary way. In fact the algorithm that has been implemented in
\cgal has the property that it always returns a valid
<I>triangulated</I> version of the Apollonius graph. By valid we mean
that it contains the actual Apollonius graph (i.e., the actual dual of
the Apollonius diagram) and whenever there are faces with more than
three faces then they are triangulated. The way that they are
triangulated depends on the order of insertion and deletion of the
circles in the diagram.

One final point has to be made about hidden circles. First of all we
would like to be more precise about our definition of hidden circles:
we say that a circle is hidden if its cell has empty interior. This
definition allows us to guarantee that all visible circles have
cells that are two-dimensional regions.
Geometrically the fact that a circle is hidden means that it is
contained in the closure of the disk of another circle (see again
\cgalFigureRef{figapollonius} ). Note that a circle contained in the union
of several disks, but not in the closure of any one of them, is not
hidden.

Hidden circles pose an additional
difficulty to our algorithm and software design. Since we allow
circles to be inserted and deleted at will, it is possible that a
circle that was hidden at some point in time, may become visible at
a later point in time; for example this can happen if we delete the
circle that hides it. For this purpose we store hidden circles and
have them reappear when they become visible. We will discuss this
issue in detail below. For the time being it suffices to say that the
user has the ability to control this behavior. More specifically it is
possible to discard the circles that become hidden. This choice is
totally natural when for example we expect to do only insertions,
since in this case a circle that becomes hidden will never
reappear. On the other hand if deletions are expected as well, then we
lose the ability to have the hidden circles reappear.

<b>Degenerate Dimensions.</b>

The dimension of the Apollonius graph is in general 2. The exceptions
to this rule are as follows:
<UL>
<LI>The dimension is \f$ -1\f$ if the Apollonius graph contains no circles.
<LI>The dimension is \f$ 0\f$ if the Apollonius graph contains exactly
one visible circle.
<LI>The dimension is \f$ 1\f$ is the Apollonius graph contains exactly
two visible circles.
</UL>

\section secapollonius2design Software Design

The 2D Apollonius graph class
`Apollonius_graph_2<ApolloniusGraphTraits_2,ApolloniusGraphDataStructure_2>`
follows the design of the triangulation packages of \cgal. It is
parametrized by two arguments:
<UL>
<LI>the <B>geometric traits</B> class. It provides the basic
geometric objects involved in the algorithm, such as sites, points
etc. It also provides the geometric predicates for the computation
of the Apollonius graph, as well as some basic constructions that
can be used, for example, to visualize the Apollonius graph or the
Apollonius diagram. The geometric traits for the Apollonius graph
will be discussed in more detail in the next section.
<LI>the <B>Apollonius graph data structure</B>. This is essentially
the same as the triangulation data structure (discussed in Chapter
\ref Chapter_2D_Triangulation_Data_Structure ), augmented with some
additional operations that are specific to Apollonius graphs. The
corresponding concept is that of
`ApolloniusGraphDataStructure_2`, which in fact is a refinement
of the `TriangulationDataStructure_2` concept. The class
`Triangulation_data_structure_2<Vb,Fb>` is a model of
the concept `ApolloniusGraphDataStructure_2`. A default value
for the corresponding template parameter is provided, so the user
does not need to specify it.
</UL>

<b>Storing Hidden Sites.</b>

As we have already mentioned a circle is hidden if it is contained
inside some visible circle. This creates a parent-child relationship
between visible and hidden circles: the parent of a hidden circle is the
visible circle that contains it. If more than one visible circles
contain a hidden circle then the hidden circle can be assigned to any of
the visible circles arbitrarily.

To store hidden circles we assign to every visible circle a list. This
list comprises the hidden circles that are contained in the
visible circle. The user can access the hidden circles associated with
a visible circle through an iterator called
`Hidden_sites_iterator`. This iterator is defined in the
`ApolloniusGraphVertexBase_2` concept and is implemented by its
model, the `Apollonius_graph_vertex_base_2<Gt,StoreHidden>`
class. It is also possible to iterate through the entire set of hidden
sites using a homonymous iterator defined by the
`Apollonius_graph_2<Gt,Agds>` class.

Since storing hidden sites may not be of interest in some cases (e.g.,
for example this is the case if we only perform insertions in the
Apollonius graph), the user has the possibility of controlling this
behavior. More precisely, the class
`Apollonius_graph_vertex_base_2<Gt,StoreHidden>` has two template
parameters, the second of which is a Boolean value. This value is by
default `true` and it indicates that hidden sites should be
stored. The user can indicate that hidden sites may be discarded
by setting this value to `false`.

\section secapollonius2traits The Geometric Traits

The predicates required for the computation of the Apollonius graph
are rather complicated. It is not the purpose of this document to
discuss them in detail. The interested reader may refer to the papers
by Karavelas and Emiris for the details
\cgalCite{cgal:ke-ppawv-02}, \cgalCite{cgal:ke-rctac-03}. However, we would like to give a brief
overview of what they
compute. There are several predicates needed by this algorithm. We
will discuss the most important/complicated ones. It turns out that
it is much easier to describe them in terms of the Apollonius diagram,
rather than the Apollonius graph. Whenever it is applicable we will also
describe their meaning in terms of the Apollonius graph.

The first two geometric predicates are called
`Is_hidden_2` and `Oriented_side_of_bisector_2`. The first one
involves two circles, say \f$ P_1\f$ and \f$ P_2\f$. It determines if \f$ P_1\f$ is
hidden with respect to \f$ P_2\f$; more precisely it checks whether the
circle \f$ P_1\f$ is contained in the closure of the disk defined by the
circle \f$ P_2\f$. As its name indicates, it determines if a circle is
hidden or not. The second predicate involves two circles \f$ P_1\f$ and
\f$ P_2\f$ and a point \f$ q\f$. It answers the question whether \f$ q\f$ is closer
to \f$ P_1\f$ or \f$ P_2\f$. Its name stems from the fact that answering the
aforementioned question is equivalent to determining the oriented
side of the bisector of \f$ P_1\f$ and \f$ P_2\f$ that contains the query point
\f$ q\f$. This predicate is used by the algorithm for closest neighbor
queries for points.

The next geometric predicate is called `Vertex_conflict_2` and it
involves four circles \f$ P_1\f$, \f$ P_2\f$, \f$ P_3\f$, and \f$ P_4\f$ (see
\cgalFigureRef{figag2vc} ). The first three (red circles in
\cgalFigureRef{figag2vc} ) define a tritangent circle (yellow
circle in \cgalFigureRef{figag2vc} ). What we want to determine is
the sign of the distance of the green circle from the yellow
circle. The distance between two circles \f$ K_1=(c_1,r_1)\f$ and
\f$ K_2=(c_2, r_2)\f$ is defined as the distance of their centers minus
their radii:
\f[ \delta(K_1, K_2) = \|c_1-c_2\|-r_1-r_2. \f]
This predicate determines if a vertex in the Apollonius diagram
(the center of the yellow circle) is destroyed when a new circle is
inserted in the diagram (the green circle). In the Apollonius graph
it tells us if a triangular face of the diagram is to be destroyed or
not.

\cgalFigureBegin{figag2vc,apollonius-vertex_conflict-false.png,apollonius-vertex_conflict-true.png}
The `Vertex_conflict_2` predicate. The left-most, bottom-most and top-most circles define the tritangent circle in the middle. We want to determine the sign of the distance of the left-most circle from the one in the middle. The almost horizontal curve is the bisector of the top-most and bottom-most circles. Left: the predicate returns `NEGATIVE`. Right: the predicate returns `POSITIVE`.
\cgalFigureEnd

What we essentially want to compute when we construct incrementally a
Voronoi diagram, is whether the object to be inserted destroys an edge
of the Voronoi diagram or not. In the case of points this is really
easy and it amounts to the well-known <I>incircle</I> test.
In the case
of circles the situation is more complicated. We can have six possible
outcomes as to what portion of an edge of the Apollonius diagram the
new circle destroys (see \cgalFigureRef{figag2edgeconflict} ). The first
two can be answered directly by the `Vertex_conflict_2` predicate
evaluated for the two endpoints of the Apollonius diagram edge. This
is due to the fact that the value of the `Vertex_conflict_2`
predicate is different for the two endpoints. If the two values are
the same then we need an additional test which determines if the interior
of the Apollonius diagram edge is destroyed by the new circle. This is
what the `Finite_edge_interior_conflict_2` and
`Infinite_edge_interior_conflict_2` predicates do. In essence, it
is the same predicate (same idea) applied to two different types of
edges in the Apollonius diagram: a finite or an infinite edge. An edge
is infinite if its dual edge in the Apollonius graph connects the
site at infinity with the vertex corresponding to a (finite) circle;
otherwise it is a finite edge.

\cgalFigureAnchor{figag2edgeconflict}
<CENTER>
<TABLE BORDER>
<TR>
<TD>
\image html ./apollonius-left_vertex.png
\image latex ./apollonius-left_vertex.png
</TD>
<TD>
\image html ./apollonius-right_vertex.png
\image latex ./apollonius-right_vertex.png
</TD>
</TR>
<TR>
<TD>
\image html ./apollonius-no_conflict.png
\image latex ./apollonius-no_conflict.png
</TD>
<TD>
\image html ./apollonius-entire_edge.png
\image latex ./apollonius-entire_edge.png
</TD>
</TR>
<TR>
<TD>
\image html ./apollonius-interior.png
\image latex ./apollonius-interior.png
</TD>
<TD>
\image html ./apollonius-both_vertices.png
\image latex ./apollonius-both_vertices.png
</TD>
</TR>
</TABLE>
</CENTER>
\cgalFigureCaptionBegin{figag2edgeconflict}
The 6 possible outcomes of the
`Finite_edge_interior_conflict_2` predicate. Top left: only a
neighborhood around the left-most endpoint of the edge will be
destroyed. Top right: only a neighborhood around the right-most
endpoint of the edge will be destroyed. Middle left: no portion of the
edge is destroyed. Middle right: the entire edge will be
destroyed. Bottom left: a neighborhood in the interior of the edge
will be destroyed; the regions near the endpoints remain
unaffected. Bottom right: The neighborhood around the two endpoints
will be destroyed, but an interval in the interior of the edge will
remain in the new diagram.
\cgalFigureCaptionEnd

The last predicate that we want to discuss is called
`Is_degenerate_edge_2`. It tells us whether an edge in the
Apollonius diagram is degenerate, that is if its two endpoints
coincide. In the Apollonius graph such an edge corresponds to one of
the additional edges that we use to triangulate the non-triangular
faces.

The aforementioned predicates are part of the
`ApolloniusGraphTraits_2` concept of \cgal. \cgal also provides
a model for this concept, the
`Apollonius_graph_traits_2<K,Method_tag>` class. The first
template parameter of this class must be a model of the `Kernel`
concept. The second template parameter is a tag that indicates what
operations are allowed in the computations that take place within the
traits class.
The two possible values of the `Method_tag` parameter are
`Integral_domain_without_division_tag` and `Field_with_sqrt_tag`. When
`Integral_domain_without_division_tag` is used, only ring operations are used during the
evaluation of the predicates, whereas if `Field_with_sqrt_tag` is
chosen, all four field operations, as well as square roots, are used
during the predicate evaluation.

The `Apollonius_graph_traits_2<K,Method_tag>` class provides exact
predicates if the number type in the kernel `K` is an exact number
type. This is to be associated with the type of operations allowed for
the predicate evaluation. For example `MP_Float` as number
type, with `Integral_domain_without_division_tag` as tag will give exact predicates,
whereas `MP_Float` with `Field_with_sqrt_tag` will give
inexact predicates.

Although exact number types provide exact predicates and constructions,
their use often results in unacceptably large runtimes.
The class `Apollonius_graph_filtered_traits_2<CK,CM,EK,EM,FK,FM>`
aims to paliate this shortcoming. Similar to a filtered kernel, it takes a
constructions kernel `CK`, a filtering kernel `FK` and an
exact kernel `EK`, as well as the corresponding tags
(`CM`, `FM` and `EM`, respectively).
Predicates are evaluated by first using the filtering kernel, and
if this fails the evaluation is performed using the exact kernel,
thus yielding exact predicates at a generally much cheaper cost
than directly using an exact number type. The constructions
are done using the kernel `CK`, which means that
they are not necessarily exact. All template parameters except
`CK` have default values, which are explained in the reference
manual.

\section secapollonius2hierarchy The Apollonius Graph Hierarchy

The `Apollonius_graph_hierarchy_2<ApolloniusGraphTraits_2,ApolloniusGraphDataStructure_2>` class is nothing but the equivalent of the `Triangulation_hierarchy_2`
class, applied to the Apollonius graph. It consists of a series of
Apollonius graphs constructed in a manner analogous to the Delaunay
hierarchy by Devillers \cgalCite{d-iirdt-98}. The class
`Apollonius_graph_hierarchy_2<ApolloniusGraphTraits_2,ApolloniusGraphDataStructure_2>`
has exactly the same interface and functionality as the
`Apollonius_graph_2<ApolloniusGraphTraits_2,ApolloniusGraphDataStructure_2>`
class. Using the Apollonius graph hierarchy involves an additional
cost in space and time for maintaining the hierarchy. Our experiments
have shown that it usually pays off to use the hierarchy for inputs
consisting of more than 1,000 circles. This threshold holds for both
the construction of the Apollonius diagram itself, as well as for
nearest neighbor queries.

\section secapollonius2examples Examples

\subsection Apollonius_graph_2FirstExample First Example

\cgalExample{Apollonius_graph_2/ag2_exact_traits.cpp}

\subsection Apollonius_graph_2SecondExample Second Example

\cgalExample{Apollonius_graph_2/ag2_exact_traits_sqrt.cpp}

\subsection Apollonius_graph_2ThirdExample Third Example

\cgalExample{Apollonius_graph_2/ag2_filtered_traits_no_hidden.cpp}

\subsection Apollonius_graph_2FourthExample Fourth Example

\cgalExample{Apollonius_graph_2/ag2_hierarchy.cpp}

*/
} /* namespace CGAL */

---

### Apollonius Graph 2 Doc Apollonius Graph 2 PackageDescription (`Apollonius_graph_2/doc/Apollonius_graph_2/PackageDescription.txt`)

/// \defgroup PkgApolloniusGraph2Ref Reference Manual
/// \defgroup PkgApolloniusGraph2Concepts Concepts
/// \ingroup PkgApolloniusGraph2Ref
/*!
\addtogroup PkgApolloniusGraph2Ref
\cgalPkgDescriptionBegin{2D Apollonius Graphs (Delaunay Graphs of Disks),PkgApolloniusGraph2}
\cgalPkgPicture{CircleVoronoi.png}
\cgalPkgSummaryBegin
\cgalPkgAuthors{Menelaos Karavelas and Mariette Yvinec}
\cgalPkgDesc{Algorithms for computing the Apollonius graph in two dimensions. The Apollonius graph is the dual of the Apollonius diagram, also known as the <I>additively weighted Voronoi diagram</I>. The latter can be thought of as the Voronoi diagram of a set of disks under the Euclidean metric, and it is a generalization of the standard Voronoi diagram for points. The algorithms provided are dynamic.}
\cgalPkgManuals{Chapter_2D_Apollonius_Graphs,PkgApolloniusGraph2Ref}
\cgalPkgSummaryEnd
\cgalPkgShortInfoBegin
\cgalPkgSince{3.0}
\cgalPkgDependsOn{\ref PkgTDS2}
\cgalPkgBib{cgal:ky-ag2}
\cgalPkgLicense{\ref licensesGPL  "GPL"}
\cgalPkgDemo{2D Apollonius Graph,apollonius_graph_2.zip}
\cgalPkgShortInfoEnd
\cgalPkgDescriptionEnd

An Apollonius graph is the dual of the Apollonius diagram, also known
as the <I>additively weighted Voronoi diagram</I>. It is essentially the
Voronoi diagram of a set of disks, where the distance of a
point of the plane from a disk is defined as the Euclidean
distance of the point and the center of the circle, minus the radius
of the disk.

\cgal provides the class `CGAL::Apollonius_graph_2<Gt,Agds>` for
computing the 2D Apollonius graph. The two template parameters must be
models of the `ApolloniusGraphTraits_2` and
`ApolloniusGraphDataStructure_2` concepts. The first concept is
related to the geometric objects and predicates associated with
Apollonius graphs, whereas the second concept refers to the data
structure used to represent the Apollonius graph. The classes
`Apollonius_graph_traits_2<K,Method_tag>` and
`Triangulation_data_structure_2<Vb,Fb>` are models of the
aforementioned concepts.

\cgalClassifedRefPages

\cgalCRPSection{Concepts}

- `ApolloniusSite_2`
- `ApolloniusGraphTraits_2`
- `ApolloniusGraphDataStructure_2`
- `ApolloniusGraphVertexBase_2`
- `ApolloniusGraphHierarchyVertexBase_2`

\cgalCRPSection{Classes}

- `CGAL::Apollonius_graph_2<Gt,Agds>`
- `CGAL::Apollonius_site_2<K>`
- `CGAL::Apollonius_graph_traits_2<K,Method_tag>`
- `CGAL::Apollonius_graph_filtered_traits_2<CK,CM,EK,EM,FK,FM>`
- `CGAL::Apollonius_graph_vertex_base_2<Gt,StoreHidden>`
- `CGAL::Apollonius_graph_hierarchy_2<Gt,Agds>`
- `CGAL::Apollonius_graph_hierarchy_vertex_base_2<Agvb>`


*/

---

### Apollonius Graph 2 Doc Apollonius Graph 2 Examples (`Apollonius_graph_2/doc/Apollonius_graph_2/examples.txt`)

/*!
\example Apollonius_graph_2/ag2_exact_traits.cpp
\example Apollonius_graph_2/ag2_exact_traits_sqrt.cpp
\example Apollonius_graph_2/ag2_filtered_traits_no_hidden.cpp
\example Apollonius_graph_2/ag2_hierarchy.cpp
*/

---

### Arrangement On Surface 2 Doc Arrangement On Surface 2 Arrangement On Surface 2 (`Arrangement_on_surface_2/doc/Arrangement_on_surface_2/Arrangement_on_surface_2.txt`)

namespace CGAL {
/*!

\mainpage User Manual
\anchor Chapter_2D_Arrangements
\anchor chapterArrangement_on_surface_2
\cgalAutoToc

\authors Ron Wein, Eric Berberich, Efi Fogel, Dan Halperin,
Michael Hemmer, Oren Salzman, and Baruch Zukerman


\section aos_sec-intro Introduction


Geometric arrangements, or arrangements for short, are subdivisions of
some space induced by geometric objects.
\cgalFigureRef{aos_fig-simple_arr} shows an arrangement of two curves
\f$c_1\f$ and \f$c_2\f$ in the plane. It has three faces&mdash;two
bounded faces \f$f_1\f$ and \f$f_2\f$ (filled with diagonal-stripe
patterns) and an unbounded face. The arrangement has seven
vertices&mdash;four represent the endpoints of \f$c_1\f$ and \f$c_2\f$
(drawn as small discs), and three represent the intersection points of
the two curves (drawn as small rings). The arrangement also has eight
edges, each of which is a maximal portion of one curve not
intersecting the other.

\cgalFigureBegin{aos_fig-simple_arr,simple_arr.png}
\cgalFigureEnd

Arrangements are not restricted to curves in the plane. There are
useful arrangements in three and higher dimensions (these are not so
easy to visualize) and they can be induced by geometric objects of any
type, such as spheres, simplices, polytopes, or B&eacute;zier
surfaces. This package provides a data structure that represents a
two-dimensional arrangement of curves embedded in an orientable
parametric surface in three dimensional space, such as a plane, a
cylinder, a sphere, a torus, or a surface homeomorphic to them. This
package also provides operations that construct and manipulate such
arrangements.  Arrangements are ubiquitous in the
computational-geometry literature and have many applications; see,
e.g., \cgalCite{as-aa-00}, \cgalCite{cgal:bfhks-apsca-10},
\cgalCite{cgal:bfhmw-apsgf-10}, and \cgalCite{cgal:h-a-04}.


\subsection aos_ssec-intro-sep Separation of Topology and Geometry


The use of the generic programming paradigm enables a convenient
separation of the topology and the geometry of data
structures.\cgalFootnote{In this context, we sometimes say
<em>combinatorics</em> instead of topology, and say <em>algebra</em> or
<em>numerics</em> instead of geometry. We always mean the same
thing---the separation of the abstract, graph-like structure (the
topology) from the actual embedding in the plane (the geometry).}
This is a key aspect in the design of geometric software, and is put
into practice, for example, in the design of \cgal polyhedra, \cgal
triangulations, and our \cgal arrangements. This separation allows the
convenient abstraction of algorithms and data structures in
combinatorial and topological terms, regardless of the specific
geometry of the objects at hand. This abstraction is realized through
class and function templates that represent specific data structures
and algorithmic frameworks, respectively. Consider the class template

\code{.cpp}
template <typename GeometryTraits, typename Dcel>
class Arrangement_2 { ... };
\endcode

An instance of this template represents an arrangement embedded in the
plane. When the template is instantiated, the `GeometryTraits`
parameter must be substituted by a type that defines a set of
geometric-object types, such as point and curve, and a set of
operations on objects of these types (see Section \ref
aos_sec-geom_traits); the `Dcel` parameter must be substituted by a
type that represents a doubly-connected edge list (\dcel) data
structure. It defines types of topological objects, such as vertices,
edges, and faces, and the operations required to maintain the
incidence relations among objects of these types (see Section \ref
aos_ssec-basic-dcel).

The class template `Arrangement_2` derives from the following class
template:

\code{.cpp}
template <typename GeometryTraits, typename TopologyTraits>
class Arrangement_on_surface_2 { ... };
\endcode

An instance of this template represents a two-dimensional arrangement
embedded in a surface in three dimensional space. When the template is
instantiated, the `GeometryTraits` parameter must be substituted as
described above; the `TopologyTraits` parameter must be substituted
by a type that deals with the topology of the surface (see Section
\ref aos_sec-topol_traits). In particular, it maintains a
representation of the arrangement graph embedded in the surface using
a doubly-connected edge list (\dcel) data-structure suitable for
the particular topology.

Several member functions and nested types defined in the
`Arrangement_2` derived class-template inherit their definitions from
the base class-template `Arrangement_on_surface_2`; their semantics is
equivalent in both class templates. The names of these member
functions and nested types typically appear in the manual without any
scope, as each of these class templates can serve as their scope. (As
a matter of fact, the package provides additional class templates that
represent two-dimensional arrangements, such as the
`Arrangement_with_history_2` class template, which derives from the
class template `Arrangement_2`; these additional class templates also
contain inherited definitions of the aforementioned member functions
and nested types.)

An immediate advantage of the separation of the topology and the
geometry of data structures is that users with limited expertise in
computational geometry can employ the data structure with their own
special type of objects. They must, however, supply the relevant
traits class, which mainly involves algebraic computations. A traits
class also encapsulates the number types used to represent coordinates
of geometric objects and to carry out algebraic operations on them. It
encapsulates the type of coordinate system used (e.g., %Cartesian and
homogeneous), and the geometric or algebraic computation methods
themselves. The precise minimal sets of requirements the actual traits
classes must conform to are organized as a hierarchy of concepts; see
Section \ref aos_sec-geom_traits.


\subsection aos_ssec-intro-well_behaved Well-Behaved Curves


What constitutes valid curves that can be handled by the \ref
PkgArrangementOnSurface2 package is discussed in detail in Section
\ref aos_sec-geom_traits, where the models of the traits classes are
described. However, when we cite combinatorial complexity bounds or
bounds on the resources (i.e., running time and storage space)
required by algorithms, we often postulate stricter assumptions on the
input curves. The prevalent term in use is that the curves are
<em>well behaved</em>, which may have different interpretations in
different settings. If we are concerned with combinatorial complexity
bounds for curves embedded in a two-dimensional surface, then the
standard assumptions are that (i) each curve is non-self-intersecting
(a so-called Jordan arc) and (ii) every pair of curves intersects in
at most some constant number of points. For algorithmic purposes we
need to require more since we assume that any operation on a small
constant number of curves takes unit time. In this sense arcs of
algebraic curves of degree bounded by a constant (namely the zero set
of bivariate polynomials of constant maximum total degree) are well
behaved. Naturally, what are typically considered well-behaved
surfaces in \f$\mathbb{R}^3\f$ is even more complicated to state.

Remarks
<ol>

<li> From the complexity-bound perspective, most of the arrangements
  that we can deal with can be regarded as defined by well-behaved
  curves. Even though the package allows for self-intersecting curves,
  for most types each curve can be decomposed into a constant number
  of well-behaved curves, thus having no effect on the asymptotic
  bounds that we state.
</li>

<li> One type of curves that we deal with is special in this sense:
  <em>polylines</em>, namely concatenations of an unlimited number of
  line segments; see Section \ref arr_sssectr_polylines. A polyline is
  not well behaved, as it cannot be decomposed into a constant number
  of constant-descriptive complexity subcurves. Informative bounds for
  arrangements of polylines are expressed by other parameters in
  addition to the number of polylines, for example, the total number
  of segments in all the polylines together. The same holds for the
  more general type <em>polycurve</em>, which are piecewise curves
  that are not necessarily linear; see Section \ref
  arr_sssectr_polycurves.
</li>

</ol>


\subsection aos_ssec-intro-outline Outline


In Section \ref aos_sec-basic we provide the minimum material you need
to know in order to use \cgal 2D arrangements in the plane. In Section
\ref aos_sec-curved_surfaces we provide additional material you need
to know in order use \cgal 2D arrangements embedded in curved
surfaces.  Most of the succeeding material is oblivious to the type of
the embedding surface. In Section \ref arr_secqueries we show how
queries on an arrangement can be issued. In Section \ref
arr_secgl_funcs we review some useful free (global) functions that
operate on arrangements, the most important ones being the free
insertion-functions.  In Section \ref aos_sec-unbounded we explain how
to construct and manipulate arrangements of unbounded curves.  Section
\ref aos_sec-geom_traits contains detailed descriptions of the
geometric traits concept hierarchy and the various geometric traits
classes included in the \ref PkgArrangementOnSurface2 package. The
different traits classes enables the construction and manipulation of
arrangements of different families of curves. Naturally, here, the
embedding surface plays a significant role. In Section \ref
arr_ssecnotif we review the notification mechanism that allows
external classes to keep track of the changes that an arrangement
instance goes through. Section \ref arr_ssecex_dcel explains how to
extend the \dcel records, to store extra data with them, and to
efficiently update this data.  In Section \ref arr_ssecoverlay we
introduce the fundamental operation of overlaying two arrangements.
Section \ref arr_ssecarr_with_hist describes a class-template that
extends the arrangement by storing additional history records with its
curves. In Section \ref aos_sec-io we review the arrangement
input/output functions. In Section \ref aos_sec-bgl we describes how
to apply the graph algorithms implemented in the Boost Graph Library
to arrangement types. Finally, in Section \ref aos_sec-tips we provide
some tips that can be applied to expedite computation.


\section aos_sec-basic Basic Arrangements


We start with a formal definition of two-dimensional arrangements, and
proceed with an introduction to the data structure used to represent
the incidence relations among features of two-dimensional
arrangements, namely, the <em>doubly-connected edge list</em>, or
\dcel for short. In Section \ref aos_ssec-basic-arr_class we
describe a central component in the \ref PkgArrangementOnSurface2
package, namely, the `Arrangement_2` class-template, which can be used
to represent arrangements in the plane.


\subsection aos_ssec-basic-dcel Representation of Arrangements: The Dcel


Given a set \f$\mathcal{C}\f$ of curves embedded in a two-dimensional
surface, the <em>arrangement</em> \f$\mathcal{A}(\mathcal{C})\f$ is
the subdivision of the surface into zero-dimensional, one-dimensional
and two-dimensional cells,\cgalFootnote{We use the term <em>cell</em>
to describe the various dimensional entities in the induced
subdivision. Sometimes, the term <em>face</em> is used for this
purpose in the literature. However, we use the term <em>face</em> to
describe a <em>two-dimensional</em> cell.}  called <em>vertices</em>,
<em>edges</em> and <em>faces</em>, respectively, induced by the curves
in \f$\mathcal{C}\f$.

In our implementation we use a definition that slightly deviates from
the standard definition above for practical reasons. The curves in
\f$\mathcal{C}\f$ can intersect each other (a single curve may also be
self-intersecting or may comprise several disconnected branches) and
are not necessarily \f$x\f$-monotone.\cgalFootnote{A continuous planar
curve \f$c\f$ is <em>\f$x\f$-monotone</em> if every vertical line
intersects it at most once. For example, a non-vertical line segment
is always \f$x\f$-monotone and so is the graph of any continuous
function \f$y = f(x)\f$. For convenience, we treat vertical line
segments as <em>weakly \f$x\f$-monotone</em>, as there exists a single
vertical line that overlaps them. A circle of radius \f$r\f$ centered
at \f$(x_0, y_0)\f$ is not \f$x\f$-monotone, as the vertical line \f$x
= x_0\f$ intersects it at \f$(x_0, y_0 - r)\f$ and at \f$(x_0, y_0 +
r)\f$.}  We construct a collection \f$\mathcal{C}''\f$ of
\f$x\f$-monotone subcurves that are pairwise disjoint in their
interiors in two steps as follows. First, we decompose each curve in
\f$\mathcal{C}\f$ into maximal \f$x\f$-monotone subcurves and possibly
isolated points, obtaining the collection \f$\mathcal{C}'\f$. Note
that an \f$x\f$-monotone curve cannot be self-intersecting. Then, we
decompose each curve in \f$\mathcal{C}'\f$ into maximal connected
subcurves not intersecting any other curve (or point) in
\f$\mathcal{C}'\f$ in its interior. The collection \f$\mathcal{C}''\f$
contains isolated points, if the collection \f$\mathcal{C}'\f$
contains such points. The arrangement induced by the collection
\f$\mathcal{C}''\f$ can be conveniently embedded as a planar graph,
the vertices of which are associated with curve endpoints or with
isolated points, and the edges of which are associated with
subcurves. It is easy to see that the faces of
\f$\mathcal{A}(\mathcal{C})\f$ are the same as the faces of
\f$\mathcal{A}(\mathcal{C}'')\f$. There are possibly more vertices in
\f$\mathcal{A}(\mathcal{C}'')\f$ than in
\f$\mathcal{A}(\mathcal{C})\f$---the vertices where curves were cut
into \f$x\f$-monotone (non-intersecting) pieces; accordingly there may
also be more edges in \f$\mathcal{A}(\mathcal{C}'')\f$. This graph can
be represented using a <em>doubly-connected edge list</em>
data-structure (\dcel), which consists of containers of vertices,
edges and faces and maintains the incidence relations among these
cells. It is one of a family of combinatorial data structures called
<em>halfedge data structures</em> (<span class="textsc">Hds</span>),
which are edge-centered data structures capable of maintaining
incidence relations among cells of, for example, planar subdivisions,
polyhedra, or other orientable, two-dimensional surfaces embedded in a
space of arbitrary dimension. Geometric interpretation is added by
classes built on top of the halfedge data structure.

\cgalAdvancedBegin

The \f$x\f$-monotone curves of an arrangement are embedded in a
rectangular two-dimensional area called the parameter space. The
parameter space is defined as \f$X \times Y\f$, where \f$X\f$ and
\f$Y\f$ are open, half-open, or closed intervals with endpoints in the
compactified real line \f$\mathbb{R} \cup \{-\infty,+\infty\}\f$. Let
\f$x_{\rm min}\f$, \f$x_{\rm max}\f$, \f$y_{\rm min}\f$, and
\f$y_{\rm max}\f$ denote the endpoints of \f$X\f$ and \f$Y\f$,
respectively. We typically refer to these values as the left, right,
bottom, and top sides of the boundary of the parameter space. If the
parameter space is, for example, the entire compactified plane, as in
the case of arrangements in the plane,
\f$x_{\rm min} = y_{\rm min} = -\infty\f$ and
\f$x_{\rm max} = y_{\rm max} = +\infty\f$; see Section \ref
aos_sec-curved_surfaces for more details.

\cgalAdvancedEnd

The \dcel data-structure represents each edge using a pair of
directed <em>halfedges</em>, one going from the
\f$xy\f$-lexicographically smaller (left) endpoint of the curve
towards the \f$xy\f$-lexicographically larger (right) endpoint, and
the other, known as its <em>twin</em> halfedge, going in the opposite
direction. As each halfedge is directed, it has a <em>source</em>
vertex and a <em>target</em> vertex. Halfedges are used to separate
faces, and to connect vertices, with the exception of <em>isolated
vertices</em> (representing isolated points), which are disconnected.
If a vertex \f$v\f$ is the target of a halfedge \f$e\f$, we say that
\f$v\f$ and \f$e\f$ are <em>incident</em> to each other. The halfedges
incident to a vertex \f$v\f$ form a circular list sorted in a
clockwise order around this vertex. (An isolated vertex has no
incident halfedges.)

An <em>edge</em> of an arrangement is a maximal portion of a curve
between two vertices of the arrangement. Each edge is represented in
the \dcel by a pair of twin halfedges. Each halfedge \f$e\f$
stores a pointer to its <em>incident face</em>, which is the face lying
to its left. Moreover, every halfedge is followed by another halfedge
sharing the same incident face, such that the target vertex of the
halfedge is the same as the source vertex of the next halfedge. The
halfedges around faces form circular chains, such that all halfedges
of a chain are incident to the same face and wind along its boundary.
We call such a chain a <em>connected component of the boundary</em>, or
<em>CCB</em> for short.

The unique CCB of halfedges winding in a counterclockwise orientation
along a face boundary is referred to as the <em>outer CCB</em> of the
face. For the time being let us consider only (i) arrangements of
bounded curves, such that exactly one unbounded face exists in every
arrangement, and (ii) arrangements embedded in the plane, such that
every face has at most one outer CCB. The unbounded face does not have
an outer boundary. Any other connected component of the boundary of
the face is called a <em>hole</em>, or <em>inner CCB</em>, and can be
represented as a circular chain of halfedges winding in a clockwise
orientation around it. Note that a hole does not necessarily
correspond to a face at all, as it may have no area, or alternatively
it may contain several faces. Every face can have several inner CCBs
in its interior, or may not contain inner CCBs at all. In addition,
every face may contain isolated vertices in its interior. We
distinguish between isolated vertices and holes even though,
theoretically, the former are degenerate holes. See
\cgalFigureRef{aos_fig-arr_segs} for an illustration of the various
\dcel features. For more details on the \dcel data structure see
\cgalCite{bkos-cgaa-00} Chapter 2.


\cgalFigureBegin{aos_fig-arr_segs,arr_segs.png}
An arrangement of interior-disjoint line segments with some of the
\dcel records that represent it. The unbounded face \f$f_0\f$ has
a single connected component that forms a hole inside it, and this
hole comprises of several faces. The halfedge \f$e\f$ is directed
from its source vertex \f$v_1\f$ to its target vertex \f$v_2\f$.
This edge, together with its twin \f$e'\f$, correspond to a
line segment that connects the points associated with \f$v_1\f$ and
\f$v_2\f$ and separates the face \f$f_1\f$ from \f$f_2\f$. The
predecessor \f$e_{\rm prev}\f$ and successor \f$e_{\rm next}\f$ of
\f$e\f$ are part of the chain that form the outer boundary of the
face \f$f_2\f$. The face \f$f_1\f$ has a more complicated structure
as it contains two holes in its interior: One hole consists of two
adjacent faces \f$f_3\f$ and \f$f_4\f$, while the other hole
comprises of two edges. \f$f_1\f$ also contains two isolated vertices
\f$u_1\f$ and \f$u_2\f$ in its interior.
\cgalFigureEnd



\subsection aos_ssec-basic-arr_class The Arrangement Class Template


One of the main components of the \ref PkgArrangementOnSurface2
package is the `Arrangement_2<Traits,Dcel>` class template. An
instance of this template is used to represent an arrangement embedded
in the plane. The class template provides the interface needed to
construct such arrangements, traverse them, and maintain them.

The design of the \ref PkgArrangementOnSurface2 package is guided by
two aspects of modularity as follows:
<UL>
<LI>the separation of the representation of the arrangements and the
  various geometric algorithms that operate on them, and</LI>
<LI>the separation of the topological and geometric aspects of the
  two-dimensional subdivision.
</UL>

The latter separation is exhibited by the two template parameters of
the `Arrangement_2` class template; their description follows.

<UL>

<LI>The `Traits` template-parameter should be substituted by a
  model of the `AosBasicTraits_2` concept and optionally
  additional geometry traits concepts. A model of the
  `AosBasicTraits_2` concept defines the types of
  \f$x\f$-monotone curves and two-dimensional points, namely
  `AosBasicTraits_2::X_monotone_curve_2` and
  `AosBasicTraits_2::Point_2`, respectively, and supports
  basic geometric predicates on them. The instantiated traits class
  determines the family of planar curves that induce the arrangement.

  In this section we always use `Arr_non_caching_segment_traits_2` as
  our traits-class model in order to construct arrangements of line
  segments. In succeeding sections we also use `Arr_segment_traits_2`
  as our traits-class model. These two traits trade computation time
  and storage space. The latter stores the underlying line of every
  segment of the arrangement to expedite certain operations on the
  arrangement segments. In Section \ref aos_sec-unbounded we use
  `Arr_linear_traits_2` to construct arrangements of linear curves
  (i.e., lines, rays, and line segments). The \ref
  PkgArrangementOnSurface2 package contains several other traits
  classes that can handle other types of curves, such as polylines
  (continuous piecewise-linear curves), conic arcs, and arcs of
  rational functions. We exemplify the usage of these traits classes
  in Section \ref aos_sec-geom_traits.

<LI>The `Dcel` template-parameter should be substituted by a class
  that models the `AosDcel` concept, which is used to represent
  the topological layout of the arrangement. This parameter is
  substituted by `Arr_default_dcel<Traits>` by default, and
  we use this default value in this and in the following three
  sections. However, in many applications it is necessary to extend the
  \dcel features. This is done by substituting the `Dcel` parameter with
  a different type (typically, a different instance of the
  `Arr_dcel<>` class template); see Section \ref arr_ssecex_dcel
  for further explanations and examples.
</UL>

The function template `print_arrangement_size()` listed below, and
defined in the header file `Arr_print.h`, prints out quantitative
measures of a given arrangement. While in what follows it is used only
by examples, it demonstrates well the use of the member functions
\link Arrangement_on_surface_2::number_of_vertices()
`number_of_vertices()`\endlink, \link
Arrangement_on_surface_2::number_of_edges()
`number_of_edges()`\endlink, and \link
Arrangement_on_surface_2::number_of_faces()
`number_of_faces()`\endlink, which return the number of vertices,
edges, and faces of an arrangement, respectively.

\anchor lst_paz
\code{.cpp}
template <typename Arrangement>
void print_arrangement_size(const Arrangement& arr) {
  std::cout << "The arrangement size:\n"
            << "   |V| = " << arr.number_of_vertices()
            << ",  |E| = " << arr.number_of_edges()
            << ",  |F| = " << arr.number_of_faces() << std::endl;
}
\endcode

You can also obtain the number of halfedges of an arrangement using
the member function \link Arrangement_on_surface_2::number_of_halfedges()
`number_of_halfedges()`\endlink. Recall that the number of halfedges is
always twice the number of edges.

\image html triangle.png
\image latex triangle.png

The simple program listed below constructs an arrangement of three
connected line segments forming a triangle. It uses the
<em>Cartesian</em> kernel with an integral-number type to instantiate
the `Arr_non_caching_segment_traits_2<Kernel>` class template. The
resulting arrangement consists of two faces, a bounded triangular face
and the unbounded face.  Constructing and maintaining arrangements
using limited-precision numbers, such as `int`, works properly only
under severe restrictions, which in many cases render the program not
very useful. In this example, however, the points are far apart, and
constructions of new geometric objects do not occur. Thus, it is safe
to use `int` after all. The program constructs an arrangement induced
by three line segments that are pairwise disjoint in their interior,
prints out the number of faces, and ends. It uses the
\link insert(Arrangement_2<Traits, Dcel>&, InputIterator, InputIterator) `insert()`\endlink
free-function, which inserts the segments into the
arrangement; see Section \ref arr_secgl_funcs. It uses the member
function \link Arrangement_on_surface_2::number_of_faces
`number_of_faces()`\endlink to obtain the number of faces (two in this
case). We give more elaborate examples in the rest of this
chapter. The programs in those examples rely on computing with numbers
of arbitrary precision, which guarantees robust execution and correct
results.

\code{.cpp}
#include <CGAL/Cartesian.h>
#include <CGAL/Arr_non_caching_segment_traits_2.h>
#include <CGAL/Arrangement_2.h>

using Number_type = int;
using Kernel = CGAL::Cartesian<Number_type>;
using Traits = CGAL::Arr_non_caching_segment_traits_2<Kernel>;
using Point = Traits_2::Point_2;
using Segment = Traits_2::X_monotone_curve_2;
using Arrangement = CGAL::Arrangement_2<Traits_2>;

int main() {
  Arrangement arr;
  Point p1(1, 1), p2(1, 2), p3(2, 1);
  Segment cv[] = {Segment(p1, p2), Segment(p2, p3), Segment(p3, p1)};
  CGAL::insert(arr, &cv[0], &cv[sizeof(cv)/sizeof(Segment)]);
  return 0;
}
\endcode


\subsection arr_ssectraverse Traversing the Arrangement


The simplest and most fundamental arrangement operations are the
various traversal methods, which allow users to systematically go over
the relevant features of the arrangement at hand.

As mentioned above, the arrangement is represented as a \dcel,
which stores three containers of vertices, halfedges and faces; thus,
the `Arrangement_2` class template supplies iterator types for these
containers, respectively. For example, if `arr` is an `Arrangement_2`
object, the calls \link Arrangement_on_surface_2::vertices_begin()
`arr.vertices_begin()`\endlink and \link
Arrangement_on_surface_2::vertices_end `arr.vertices_end()`\endlink
return iterators of the nested \link
Arrangement_on_surface_2::Vertex_iterator `Vertex_iterator`\endlink
type that define the valid range of vertices of the arrangement
`arr`. The value type of this iterator is \link
Arrangement_on_surface_2::Vertex `Vertex`\endlink. Moreover, the
vertex-iterator type is convertible to \link
Arrangement_on_surface_2::Vertex_handle `Vertex_handle`\endlink, which
serves as a pointer to a vertex. As we show next, all functions
related to arrangement features accept handle types as input
parameters and return handle types as their output.
See Chapter \ref Chapter_Handles_Ranges_and_Circulators
"Handles and Circulators" for more information on \cgal handles.

In addition to the iterators for arrangement vertices, halfedges, and
faces, the arrangement class also provides an iterator for edges,
namely \link Arrangement_on_surface_2::Edge_iterator
`Edge_iterator`\endlink.  The value type of this iterator is \link
Arrangement_on_surface_2::Halfedge `Halfedge`\endlink, which is the
same as the value type of \link
Arrangement_on_surface_2::Halfedge_iterator
`Halfedge_iterator`\endlink. The calls \link
Arrangement_on_surface_2::edges_begin() `arr.edges_begin()`\endlink
and \link Arrangement_on_surface_2::edges_end()
`arr.edges_end()`\endlink return iterators that define the valid range
of arrangement edges. This range consists of half the number of
halfedges of the arrangement, as every twin halfedges has one
representative in this range.

All iterator, circulator\cgalFootnote{A <em>circulator</em> is used to
traverse a circular list, such as the list of halfedges incident to a
vertex.} and handle types also have non-mutable (<em>const</em>)
counterparts. These non-mutable iterator types are useful for
traversing an arrangement with the promise to keep it unchanged. For
example, the arrangement has a non-constant member function called
`Arrangement_on_surface_2::vertices_begin()` that returns a \link
Arrangement_on_surface_2::Vertex_iterator `Vertex_iterator`\endlink
object and another const member function that returns a \link
Arrangement_on_surface_2::Vertex_const_iterator
`Vertex_const_iterator`\endlink object. In fact, all methods listed in
this section that return an iterator, a circulator, or a handle have
non-mutable counterparts. It should be noted that, for example, \link
Arrangement_on_surface_2::Vertex_handle `Vertex_handle`\endlink can be
readily converted into a \link
Arrangement_on_surface_2::Vertex_const_handle
`Vertex_const_handle`\endlink, but not the other way around.

Conversions of non-mutable handles to the corresponding mutable
handles are nevertheless possible. They can be performed using the
overloaded member function \link
Arrangement_on_surface_2::non_const_handle()
`non_const_handle()`\endlink.  There are three variants that accept a
non-mutable handle to a vertex, a halfedge, or a face, respectively.
The call \link Arrangement_on_surface_2::non_const_handle()
`non_const_handle()`\endlink can be issued only if the arrangement
object `arr` is mutable; see, e.g., Section \ref arr_ssecpl.


\subsubsection arr_sssectr_vertex Traversal Methods for an Arrangement Vertex


A vertex \f$v\f$ of an arrangement induced by bounded curves is always
associated with a geometric entity, namely with an \link
Arrangement_on_surface_2::Point_2 `Point_2`\endlink object, which can
be obtained by \link Arrangement_on_surface_2::Vertex::point()
`v->point()`\endlink, where `v` identifies a handle to \f$v\f$.

The call \link Arrangement_on_surface_2::Vertex::is_isolated()
`v->is_isolated()`\endlink determines whether the vertex \f$v\f$ is
isolated or not. Recall that the halfedges incident to a non-isolated
vertex, namely, the halfedges that share a common target vertex, form
a circular list around this vertex. The call \link
Arrangement_on_surface_2::Vertex::incident_halfedges()
`v->incident_halfedges()`\endlink returns a circulator of the nested
type \link Arrangement_on_surface_2::Halfedge_around_vertex_circulator
`Halfedge_around_vertex_circulator`\endlink that enables the traversal
of this circular list around a given vertex \f$v\f$ in a clockwise
order. The value type of this circulator is \link
Arrangement_on_surface_2::Halfedge `Halfedge`\endlink. By convention,
the target of the halfedge is \f$v\f$. The call \link
Arrangement_on_surface_2::Vertex::degree() `v->degree()`\endlink
evaluates to the number of the halfedges incident to \f$v\f$.

The function below prints all the halfedges incident to a given
arrangement vertex (assuming that objects of the \link
Arrangement_on_surface_2::Point_2 `Point_2`\endlink type can be
inserted into the standard output using the `<<` operator). The
arrangement type is the same as in the simple example above.

\code
template <typename Arrangement>
void print_incident_halfedges(typename Arrangement::Vertex_const_handle v) {
  if (v->is_isolated()) {
    std::cout << "The vertex (" << v->point() << ") is isolated\n";
    return;
  }
  typename Arrangement::Halfedge_around_vertex_const_circulator first, curr;
  first = curr = v->incident_halfedges();
  std::cout << "The neighbors of the vertex (" << v->point() << ") are:";
  do std::cout << " (" << curr->source()->point() << ")";
  while (++curr != first);
  std::cout << std::endl;
}
\endcode

If \f$v\f$ is an isolated vertex, the call \link
Arrangement_on_surface_2::Vertex::face() `v->face()`\endlink can be used to
obtain the face that contains \f$v\f$.


\subsubsection arr_sssectr_halfedge Traversal Methods for an Arrangement Halfedge


A halfedge \f$e\f$ of an arrangement induced by bounded curves is
associated with an \link Arrangement_on_surface_2::X_monotone_curve_2
`X_monotone_curve_2`\endlink object, which can be obtained by
\link Arrangement_on_surface_2::Halfedge::curve()
`e->curve()`\endlink, where `e` identifies a handle to \f$e\f$.

The calls \link Arrangement_on_surface_2::Halfedge::source()
`e->source()`\endlink and \link
Arrangement_on_surface_2::Halfedge::target() `e->target()`\endlink
return handles to the halfedge's source-vertex and target-vertex,
respectively. You can obtain a handle to the twin halfedge using \link
Arrangement_on_surface_2::Halfedge::twin() `e->twin()`\endlink. Note
that from the definition of halfedges in the `Dcel` structure, the
following invariants always hold:
<UL>
<LI>\link Arrangement_on_surface_2::Halfedge::curve()
`e->curve()`\endlink is equivalent to \link
Arrangement_on_surface_2::Halfedge::curve()
`e->twin()->curve()`\endlink,
<LI>\link Arrangement_on_surface_2::Halfedge::source()
`e->source()`\endlink is equivalent to \link
Arrangement_on_surface_2::Halfedge::target()
`e->twin()->target()`\endlink, and
<LI>\link Arrangement_on_surface_2::Halfedge::target()
`e->target()`\endlink is equivalent to \link
Arrangement_on_surface_2::Halfedge::source()
`e->twin()->source()`\endlink.
</UL>

Every halfedge has an incident face that lies to its left, which can
be obtained by \link Arrangement_on_surface_2::Halfedge::face()
`e->face()`\endlink. Recall that a halfedge is always one link in a
connected chain (CCB) of halfedges that share the same incident
face. The \link Arrangement_on_surface_2::Halfedge::prev()
`e->prev()`\endlink and \link
Arrangement_on_surface_2::Halfedge::next() `e->next()`\endlink calls
return handles to the previous and next halfedges in the CCB,
respectively.

As the CCB is a circular list of halfedges, it is only natural to
traverse it using a circulator. Indeed \link
Arrangement_on_surface_2::Halfedge::ccb() `e->ccb()`\endlink returns
an \link Arrangement_on_surface_2::Ccb_halfedge_circulator
`Ccb_halfedge_circulator`\endlink object for traversing all halfedges
along the connected component of \f$e\f$. The value type of this
circulator is \link Arrangement_on_surface_2::Halfedge
`Halfedge`\endlink.

The function template `print_ccb()` listed below prints all
\f$x\f$-monotone curves along a given CCB (assuming that objects of
the \link Arrangement_on_surface_2::Point_2 `Point_2`\endlink and the
\link Arrangement_on_surface_2::X_monotone_curve_2
`X_monotone_curve_2`\endlink types can be inserted into the standard
output using the `<<` operator).

\code
template <typename Arrangement>
void print_ccb(typename Arrangement::Ccb_halfedge_const_circulator circ) {
  Ccb_halfedge_const_circulator curr = circ;
  std::cout << "(" << curr->source()->point() << ")";
  do {
    typename Arrangement::Halfedge_const_handle he = curr->handle();
    std::cout << " [" << e->curve() << "] "
              << "(" << e->target()->point() << ")";
  } while (++curr != circ);
  std::cout << std::endl;
}
\endcode


\subsubsection arr_sssectr_face Traversal Methods for an Arrangement Face


An `Arrangement_2` object `arr` that identifies an arrangement of
bounded curves always has a single unbounded face. The call \link
Arrangement_on_surface_2::unbounded_face()
`arr.unbounded_face()`\endlink returns a handle to this face.  Note
that an empty arrangement contains nothing <em>but</em> the unbounded
face.

Given a handle to a face \f$f\f$, you can use the call \link
Arrangement_on_surface_2::Face::is_unbounded()
`f->is_unbounded()`\endlink to determine whether the face \f$f\f$ is
unbounded. Bounded faces have an outer CCB, and the \link
Arrangement_on_surface_2::Face::outer_ccb() `outer_ccb()`\endlink
method returns a circulator for the halfedges along this CCB. Note
that the halfedges along this CCB wind in a counterclockwise order
around the outer boundary of the face.

A face can also contain disconnected components in its interior,
namely, holes and isolated vertices. You can access these components
as follows:

<UL>

<LI>You can obtain a pair of iterators of type \link
  Arrangement_on_surface_2::Face::Hole_iterator
  `Hole_iterator`\endlink that define the range of holes inside a face
  \f$f\f$ by calling \link
  Arrangement_on_surface_2::Face::holes_begin()
  `f->holes_begin()`\endlink and \link
  Arrangement_on_surface_2::Face::holes_end()
  `f->holes_end()`\endlink. The value type of this iterator type is
  \link Arrangement_on_surface_2::Ccb_halfedge_circulator
  `Ccb_halfedge_circulator`\endlink, defining the CCB that winds in a
  clockwise order around a hole.  The call \link
  Arrangement_on_surface_2::Face::number_of_holes()
  `f->number_of_holes()`\endlink return the number of holes in
  \f$f\f$.

<LI>The calls \link
  Arrangement_on_surface_2::Face::isolated_vertices_begin()
  `f->isolated_vertices_begin()`\endlink and \link
  Arrangement_on_surface_2::Face::isolated_vertices_end()
  `f->isolated_vertices_end()`\endlink return iterators of type \link
  Arrangement_on_surface_2::Isolated_vertex_iterator
  `Isolated_vertex_iterator`\endlink that define the range of isolated
  vertices inside the face \f$f\f$. The value type of this iterator is
  \link Arrangement_on_surface_2::Vertex `Vertex`\endlink.

</UL>

The function `print_face()` listed below prints the outer and inner
boundaries of a given face. It uses the function template
`print_ccb()` listed above.

\code
template <typename Arrangement>
void print_face(typename Arrangement::Face_const_handle f) {
  // Print the outer boundary.
  if (f->is_unbounded()) std::cout << "Unbounded face.\n";
  else {
    std::cout << "Outer boundary: ";
    print_ccb(f->outer_ccb());
  }

  // Print the boundary of each of the holes.
  std::size_t index = 1;
  for (auto hi = f->holes_begin(); hi != f->holes_end(); ++hi) {
    std::cout << " Hole #" << index++ << ": ";
    print_ccb(*hi);
  }

  // Print the isolated vertices.
  index = 1;
  for (auto iv = f->isolated_vertices_begin();
       iv != f->isolated_vertices_end(); ++iv)
  {
    std::cout << " Isolated vertex #" << index++ << ": "
              << "(" << iv->point() << ")\n";
  }
}
\endcode

The function `print_arrangement()` listed below prints the features of
a given arrangement. The file `arr_print.h`, which can be found under
the examples folder, includes the definitions of this function, as
well as the definitions of all other functions listed in this
section. This concludes the preview of the various traversal methods.

\code
void print_arrangement (const Arrangement_2& arr) {
  // Print the arrangement vertices.
  std::cout << arr.number_of_vertices() << " vertices:\n";
  for (auto vit = arr.vertices_begin(); vit != arr.vertices_end(); ++vit) {
    std::cout << "(" << vit->point() << ")";
    if (vit->is_isolated()) std::cout << " - Isolated.\n";
    else std::cout << " - degree " << vit->degree() << std::endl;
  }

  // Print the arrangement edges.
  std::cout << arr.number_of_edges() << " edges:\n";
  for (auto eit = arr.edges_begin(); eit != arr.edges_end(); ++eit)
    std::cout << "[" << eit->curve() << "]\n";

  // Print the arrangement faces.
  std::cout << arr.number_of_faces() << " faces:\n";
  for (auto fit = arr.faces_begin(); fit != arr.faces_end(); ++fit)
    print_face(fit);
}
\endcode


\subsection arr_ssecmodify Modifying the Arrangement


In this section we review the various member functions of the
`Arrangement_2` class that allow users to modify the topological
structure of the arrangement through the introduction of new edges or
vertices, or the modification or removal of existing edges and
vertices.

The arrangement member-functions that insert new \f$x\f$-monotone
curves into the arrangement, thus enabling the construction of a
two-dimensional surface subdivision, are rather specialized, as they
assume that the interior of the inserted curve is disjoint from all
existing arrangement vertices and edges, and in addition require
apriori knowledge of the location of the inserted curve. Indeed, for
most purposes it is more convenient to construct an arrangement using
the free (global) insertion functions, which relax these
restrictions. However, as these free functions are implemented in
terms of the specialized insertion functions, we start by describing
the fundamental functionality of the arrangement class, and describe
the operation of the free functions in Section \ref arr_secgl_funcs.


\subsection arr_sssecmf_insert_cv Inserting Pairwise Disjoint x-Monotone Curves


The most trivial functions that allow users to modify the arrangement
are the specialized functions for the insertion of an \f$x\f$-monotone
curve the interior of which is disjoint from the interior of all other
curves in the existing arrangement and does not contain any point of
the arrangement. In addition, these functions require that the
location of the curve in the arrangement be known.

The rather harsh restrictions on the inserted curves enable an
efficient implementation. While inserting an \f$x\f$-monotone curve,
the interior of which is disjoint from all curves in the existing
arrangement, is quite straightforward, as we show next, (efficiently)
inserting a curve that intersects with the curves already in the
arrangement is much more complicated and requires the application of
nontrivial geometric algorithms. The decoupling of the topological
arrangement representation from the various algorithms that operate on
it dictates that the general insertion operations be implemented as
free functions that operate on the arrangement and the inserted
curve(s); see Section \ref arr_secgl_funcs for more details and
examples.


\cgalFigureBegin{aos_fig-insert,insert.png}
Illustrations of the various specialized insertion procedures. The
inserted \f$x\f$-monotone curve is drawn as a dashed line, surrounded
by two solid arrows that represent the pair of twin halfedges added to
the \dcel. Existing vertices are shown as red discs, while new
vertices are shown as blue discs. Existing halfedges that are
affected by the insertion operations are drawn as dashed arrows.  (a)
Inserting a curve as a new hole inside the face \f$f\f$.  (b)
Inserting a curve from an existing vertex \f$u\f$ that corresponds to
one of its endpoints.  (c) Inserting an \f$x\f$-monotone curve, the
endpoints of which correspond to existing vertices \f$u_1\f$ and
\f$u_2\f$. In this case, the new pair of halfedges closes a new face
\f$f'\f$. The hole \f$h_1\f$, which belonged to \f$f\f$ before
the insertion, becomes a hole in this new face.
\cgalFigureEnd


When an \f$x\f$-monotone curve is inserted into an existing
arrangement, such that the interior of this curve is disjoint from the
interiors of all curves in the arrangement, only the following three
scenarios are possible, depending on the status of the endpoints of
the inserted curve:

<OL>

<LI>Neither curve endpoints correspond to any existing arrangement
vertex. In this case we have to create two new vertices that
correspond to the curve endpoints, respectively, and connect them
using a pair of twin halfedges. This halfedge pair forms a new
hole inside the face that contains the curve in its interior.</LI>

<LI>Exactly one endpoint corresponds to an existing arrangement
vertex. (We distinguish between a vertex that corresponds to the left
endpoint of the inserted curve and a vertex that corresponds to its
right endpoint.) In this case we have to create a new vertex that
corresponds to the other endpoint of the curve and to connect the two
vertices by a pair of twin halfedges that form an "antenna" emanating
from the boundary of an existing connected component. (Note that if
the existing vertex is isolated, we need to form a new hole inside
the face that contains this vertex, essentially falling back to the
handling of the previous case, naturally, skipping the creation of
the existing vertex.)</LI>

<LI>Both endpoints correspond to existing arrangement vertices. In
this case we connect these vertices using a pair of twin halfedges.
(If one or both vertices are isolated, we fall back to the handling of
the first or second case, respectively, naturally, skipping the
creation of the existing vertices.) The two following subcases may
occur:

<UL>

<LI>Two disconnected components are merged into a single connected
  component (as is the case with the segment \f$s_1\f$ in the figure
  below).</LI>

<LI>A new face, which is split from an existing arrangement face, is
  created (as is the case with the segment \f$s_2\f$ in the figure
  below). In this case we also have to examine the holes and isolated
  vertices in the existing face and move the relevant ones inside the
  new face.</LI>

</UL>
</LI>
</OL>

\image html connect_comp.png
\image latex connect_comp.png

The `Arrangement_2` class offers insertion functions that perform the
special insertion procedures listed above, namely, \link
Arrangement_on_surface_2::insert_in_face_interior()
`insert_in_face_interior()`\endlink, \link
Arrangement_on_surface_2::insert_from_left_vertex()
`insert_from_left_vertex()`\endlink, \link
Arrangement_on_surface_2::insert_from_right_vertex()
`insert_from_right_vertex()`\endlink and \link
Arrangement_on_surface_2::insert_at_vertices()
`insert_at_vertices()`\endlink. The first function accepts an
\f$x\f$-monotone curve \f$c\f$ and an arrangement face \f$f\f$ that
contains this curve in its interior. The other functions accept an
\f$x\f$-monotone curve \f$c\f$ and handles to the existing vertices
that correspond to the curve endpoint(s). Each of the four functions
returns a handle to one of the twin halfedges that have been created;
more precisely:

<UL>

<LI>\link Arrangement_on_surface_2::insert_in_face_interior()
`insert_in_face_interior(c, f)`\endlink returns a handle to the
halfedge directed from the left endpoint of \f$c\f$ towards the vertex
corresponding to its right endpoint.

<LI>\link Arrangement_on_surface_2::insert_from_left_vertex()
`insert_from_left_vertex(c, v)`\endlink and \link
Arrangement_on_surface_2::insert_from_right_vertex()
`insert_from_right_vertex(c, v)`\endlink each returns a handle to the
halfedge, the source of which is the vertex \f$v\f$, and the target of
which is the new vertex that has just been created.

<LI>\link Arrangement_on_surface_2::insert_at_vertices()
`insert_at_vertices(c, v1, v2)`\endlink returns a handle to the
halfedge directed from \f$v_1\f$ to \f$v_2\f$.

</UL>


\cgalFigureBegin{aos_fig-edge_insertion,edge_insertion.png}
The arrangement of the line segments \f$s_1, \ldots, s_5\f$
constructed in \ref Arrangement_on_surface_2/edge_insertion.cpp.
The arrows mark the direction of the halfedges returned from the
various insertion functions.
\cgalFigureEnd


The program below demonstrates the usage of the four specialized
insertion functions. It creates an arrangement of five line segments
\f$s_1, \ldots, s_5\f$, as depicted in
\cgalFigureRef{aos_fig-edge_insertion}.  \cgalFootnote{Notice that in
all figures in the rest of this chapter the coordinate axes are drawn
only for illustrative purposes and are <em>not</em> part of the
arrangement.} The first line segment \f$s_1\f$ is inserted in the
interior of the unbounded face, while the four succeeding line
segments \f$s_2, \ldots, s_5\f$ are inserted using the vertices
created by the insertion of preceding segments. The arrows in the
figure mark the direction of the halfedges \f$e_1, \ldots, e_5\f$
returned from the insertion functions. The resulting arrangement
consists of three faces, where the two bounded faces form together a
hole in the unbounded face.

Two header files are included in the code in order to make this and
the following examples more compact. The file
`arr_inexact_construction_segments.h` is listed
immediately after the program. The file `arr_print.h` is
introduced in Section \ref arr_ssectraverse.

\cgalExample{Arrangement_on_surface_2/edge_insertion.cpp}

The statements below define the types for arrangements of line
segments common to all examples that do not construct new geometric
objects. They are kept in the header file
`arr_inexact_construction_segments.h`.  In these examples the `Traits`
parameter of the `Arrangement_2<Traits, Dcel>` class template is
substituted by an instance of the
`Arr_non_caching_segment_traits_2<Kernel>` class template. The
`Arr_non_caching_segment_traits_2` class template is instantiated with
the predefined kernel that evaluates predicates in an exact manner,
but constructs geometric objects in an inexact manner, as none of
these examples construct new geometric objects.  In the remaining
examples the traits class-template is instantiated with a kernel that
evaluates predicates and constructs geometric objects, both in an
exact manner.

\code{.cpp}
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Arr_non_caching_segment_traits_2.h>
#include <CGAL/Arrangement_2.h>

using Kernel = CGAL::Exact_predicates_inexact_constructions_kernel;
using Number_type = Kernel::FT;

using Traits = CGAL::Arr_non_caching_segment_traits_2<Kernel>;
using Point = Traits::Point_2;
using Segment = Traits::X_monotone_curve_2;

using Arrangement = CGAL::Arrangement_2<Traits>;
using Vertex_handle = Arrangement::Vertex_handle;
using Halfedge_handle = Arrangement::Halfedge_handle;
using Face_handle = Arrangement::Face_handle;
\endcode


\subsection arr_sssecmf_iso_verts Manipulating Isolated Vertices


Isolated points are simpler geometric entities than curves, and indeed
the member functions that manipulate them are easier to understand.

The call \link Arrangement_on_surface_2::insert_in_face_interior()
`arr.insert_in_face_interior(p, f)`\endlink inserts an isolated point
\f$p\f$, located in the interior of a given face \f$f\f$, into the
arrangement and returns a handle to the arrangement vertex associated
with \f$p\f$ it has created. Naturally, this function has a
precondition that \f$p\f$ is really an isolated point; namely it does
not coincide with any existing arrangement vertex and does not lie on
any edge. As mentioned in Section \ref arr_ssectraverse, it is
possible to obtain the face containing an isolated vertex calling the
member function `Arrangement_on_surface_2::Vertex::face()`. The member
function \link Arrangement_on_surface_2::remove_isolated_vertex()
`Arrangement_on_surface_2::remove_isolated_vertex(Vertex_handle v)`\endlink
accepts a handle to an isolated vertex and removes it from the
arrangement.


\cgalFigureBegin{aos_fig-isolated_vertices,isolated_vertices.png}
An arrangement of line segments containing three isolated vertices,
as constructed in \ref Arrangement_on_surface_2/isolated_vertices.cpp.
The vertices \f$u_2\f$ and \f$u_3\f$ are eventually removed from the
arrangement.
\cgalFigureEnd


The following program demonstrates the usage of the arrangement
member-functions for manipulating isolated vertices. It first inserts
three isolated vertices, \f$u_1\f$, \f$u_2\f$, and \f$u_3\f$, located
inside the unbounded face of the arrangement. Then, it inserts four
line segments \f$s_1, \ldots, s_4\f$, that form a square hole inside
the unbounded face (see \cgalFigureRef{aos_fig-edge_insertion} for an
illustration). Finally, it traverses the vertices and removes those
isolated vertices that are still contained in the unbounded face
(\f$u_2\f$ and \f$u_3\f$ in this case):

\cgalExample{Arrangement_on_surface_2/isolated_vertices.cpp}


\subsection arr_sssecmf_halfedges Manipulating Halfedges


While reading the previous subsection you learned how to insert new
points that induce isolated vertices into the arrangement. You may
wonder now how you can insert a new point that lies on an
\f$x\f$-monotone curve that is associated with existing arrangement
edge.

The introduction of a vertex, the geometric mapping of which is a
point \f$p\f$ that lies on an \f$x\f$-monotone curve, requires the
splitting of the curve in its interior at \f$p\f$. The two resulting
subcurves induce two new edges, respectively. In general, the
`Arrangement_2` class template relies on the geometry traits to
perform such a split. As a matter of fact, it relies on the geometry
traits to perform all geometric operations. To insert a point \f$p\f$
that lies on an \f$x\f$-monotone curve associated with an existing
edge \f$e\f$ into the arrangement \f$\mathcal{A}\f$, you must first
construct the two curves \f$c_1\f$ and \f$c_2\f$, which are the two
subcurves that result from splitting the \f$x\f$-monotone curve
associated with the edge \f$e\f$ at \f$p\f$. Then, you have to issue
the call \link Arrangement_on_surface_2::split_edge()
`arr.split_edge(he, c1, c2)`\endlink, where `arr` identifies the
arrangement \f$\mathcal{A}\f$ and `he` is a handle to one of the two
halfedges that represent the edge \f$e\f$. The function splits the two
halfedges that represent \f$e\f$ into two pairs of halfedges,
respectively. Two new halfedges are incident to the new vertex \f$v\f$
associated with \f$p\f$. The function returns a handle to the new
halfedge, the source of which is the source vertex of the halfedge
handled by `he`, and the target of which is the new vertex \f$v\f$.



The reverse operation is also possible. Consider a vertex \f$v\f$ of
degree \f$2\f$ that has two incident edges \f$e_1\f$ and \f$e_2\f$
associated with two curves \f$c_1\f$ and \f$c_2\f$, respectively, such
that the union of \f$c_1\f$ and \f$c_2\f$ results in a single
continuous \f$x\f$-monotone curve \f$c\f$ of the type supported by the
traits class in use. To merge the edges \f$e_1\f$ and \f$e_2\f$ into a
single edge associated with the curve \f$c\f$, essentially removing
the vertex \f$v\f$ from the arrangement identified by `arr`, you need
to issue the call \link Arrangement_2.merge_edge() `arr.merge_edge(he1,
he2, c)`\endlink, where `he1` and `he2` are handles to halfedges
representing \f$e_1\f$ and \f$e_2\f$, respectively.

Finally, the call \link Arrangement_2.remove_edge()
`remove_edge(he)`\endlink removes the edge \f$e\f$ from the
arrangement, where `he` is a handle to one of the two halfedges that
represents \f$e\f$. Note that this operation is the reverse of an
insertion operation, so it may cause a connected component to split
into two, or two faces to merge into one, or a hole to disappear.  By
default, if the removal of \f$e\f$ causes one of its end vertices to
become isolated, this vertex is removed as well. However, you can
control this behavior and choose to keep the isolated vertices by
supplying additional Boolean flags to \link
Arrangement_on_surface_2::remove_edge `remove_edge()`\endlink
indicating whether the source or the target vertices are to be removed
should they become isolated.


\cgalFigureBegin{aos_fig-edge_manipulation,edge_manipulation.png}
The three steps of the example program \ref
Arrangement_on_surface_2/edge_manipulation.cpp. In Step (a) it
constructs an arrangement of four line segments. In Step (b) the edges
\f$e_1\f$ and \f$e_2\f$ are split, and the split points are connected
with a new segment \f$s\f$ that is inserted into the arrangement. This
operation is undone in Step (c), where \f$e\f$ is removed from the
arrangement, rendering its end vertices \f$u_1\f$ and \f$u_2\f$
redundant. We therefore remove these vertices by merging their
incident edges and go back to the arrangement depicted in (a).
\cgalFigureEnd


The following example program shows how the edge-manipulation
functions can be used. The program works in three steps, as
demonstrated in \cgalFigureRef{aos_fig-isolated_vertices}. Note that
the program uses the fact that \link
Arrangement_on_surface_2::split_edge() `split_edge()`\endlink returns
one of the new halfedges (after the split) that has the same direction
as the original halfedge (the first parameter of the function) and is
directed towards the split point. Thus, it is easy to identify the
vertices \f$u_1\f$ and \f$u_2\f$ associated with the split points.

\cgalExample{Arrangement_on_surface_2/edge_manipulation.cpp}

The member functions \link Arrangement_on_surface_2::modify_vertex()
`modify_vertex()`\endlink and \link
Arrangement_on_surface_2::modify_edge() `modify_edge()`\endlink modify
the geometric mappings of existing features of the arrangement. The
call \link Arrangement_on_surface_2::modify_vertex
`arr.modify_vertex(v, p)`\endlink accepts a handle to a vertex \f$v\f$
and a reference to a point \f$p\f$, and sets \f$p\f$ to be the point
associated with the vertex \f$v\f$. The call \link
Arrangement_on_surface_2::modify_edge() `arr.modify_edge(he,
c)`\endlink accepts a handle to one of the two halfedges that
represent an edge \f$e\f$ and a reference to a curve \f$c\f$, and sets
\f$c\f$ to be the \f$x\f$-monotone curve associated with
\f$e\f$. (Note that both halfedges are modified; that is, both
expressions `e->curve()` and `e->twin()->curve()` evaluate to
\f$c\f$ after the modification.)  These functions have preconditions
that \f$p\f$ is geometrically equivalent to `v->point()` and \f$c\f$
is equivalent to `e->curve()`, respectively.\cgalFootnote{Roughly
speaking, two curves are equivalent iff they have the same graph. In
Section \ref aos_sssec-geom_traits-concepts_basic we give a formal
definition of curves and curve equivalence.} If these preconditions
are not met, the corresponding operation may invalidate the structure
of the arrangement. At first glance it may seem as if these two
functions are of little use. However, you should keep in mind that
there may be extraneous data (probably non-geometric) associated with
the point objects or with the curve objects, as defined by the traits
class. With these two functions you can modify this data; see more
details in Section \ref arr_sssec_tr_data_decorators. In addition, you can use
these functions to replace a geometric object (a point or a curve)
with an equivalent object that has a more compact representation. For
example, if we use some simple rational-number type to represent the
point coordinates, we can replace the point \f$(\frac{20}{40},
\frac{99}{33})\f$ associated with some vertex \f$v\f$ with an
equivalent point with normalized coordinates, namely \f$(\frac{1}{2},
3)\f$.


\subsection arr_sssecadv_insert Advanced Insertion Functions


\cgalAdvancedBegin

<table border="0" cellspacing="10">
<tr>
<td>
\image html pred_around_vertex.png
\image latex pred_around_vertex.png
</td>
<td>

Assume that the specialized insertion function \link
Arrangement_on_surface_2::insert_from_left_vertex()
`insert_from_left_vertex(c, v)`\endlink is given a curve \f$c\f$, the
left endpoint of which is already associated with a non-isolated
vertex \f$v\f$. Namely, \f$v\f$ has already several incident
halfedges. It is necessary in this case to locate the exact place for
the new halfedge mapped to the inserted new curve \f$c\f$ in the
circular list of halfedges incident to \f$v\f$. More precisely, in
order to complete the insertion, it is necessary to locate the
halfedge \f$e_{\mathrm{pred}}\f$ directed toward \f$v\f$, such that
\f$c\f$ is located between the curves associated with
\f$e_{\mathrm{pred}}\f$ and the next halfedge in the clockwise order
in the circular list of halfedges around \f$v\f$; see
\cgalFigureRef{aos_fig-insert}. This search may take \cgalBigO{d} time,
where \f$d\f$ is the degree of the vertex \f$v\f$. \cgalFootnote{We
can store the handles to the halfedges incident to \f$v\f$ in an efficient
search structure to obtain \cgalBigO{\log d} access time. However, as
\f$d\f$ is usually very small, this may lead to a waste of storage
space without a meaningful improvement in running time in practice.}
However, if the halfedge \f$e_{\mathrm{pred}}\f$ is known in advance,
the insertion can be carried out in constant time, and without
performing any geometric comparisons.  </td> </tr> </table>

The `Arrangement_2` class provides advanced versions of the
specialized insertion functions for a curve \f$c\f$, namely, \link
Arrangement_on_surface_2::insert_from_left_vertex()
`insert_from_left_vertex(c, he_pred)`\endlink and \link
Arrangement_on_surface_2::insert_from_right_vertex()
`insert_from_right_vertex(c, he_pred)`\endlink.  These functions
accept a halfedge \f$e_{\mathrm{pred}}\f$ as specified above, instead
of a handle to a vertex \f$v\f$. They are more efficient, as they take
constant time and do not perform any geometric operations. Thus, you
should use them when the halfedge \f$e_{\mathrm{pred}}\f$ is known. In
cases where the vertex \f$v\f$ is isolated or the predecessor halfedge
for the newly inserted curve is not known, the simpler versions of
these insertion functions should be used. Similarly, the member
function \link Arrangement_on_surface_2::insert_at_vertices()
`insert_at_vertices()`\endlink is overloaded with two additional
versions as follows. One accepts two handles to the two predecessor
halfedges around the two vertices \f$v_1\f$ and \f$v_2\f$,
respectively, that correspond to the curve endpoints. The other one
accepts a handle to one vertex and a handle to the predecessor
halfedge around the other vertex.


\cgalFigureBegin{aos_fig-special_edge_insertion,special_edge_insertion.png}
An arrangement of line segments, as constructed in
\ref Arrangement_on_surface_2/special_edge_insertion.cpp. Note that
\f$p_0\f$ is initially inserted as an isolated point and later on
connected to the other four vertices.
\cgalFigureEnd


The following program shows how to construct the arrangement
depicted in \cgalFigureRef{aos_fig-special_edge_insertion} using the specialized
insertion functions that accept predecessor halfedges:

\cgalExample{Arrangement_on_surface_2/special_edge_insertion.cpp}

It is possible to perform even more refined operations on an
`Arrangement_2` object given specific topological information.
As most of these operations are very fragile and perform no precondition
testing on their input in order to gain efficiency, they are not included
in the public interface of the arrangement class. Instead, the
`Arr_accessor<Arrangement>` class allows access to these internal
arrangement operations; see more details in the Reference Manual.
\cgalAdvancedEnd


\section arr_secqueries Issuing Queries on an Arrangement


One of the most useful query types defined on arrangements is the
<em>point-location</em> query: Given a point, find the arrangement
cell that contains it. Typically, the result of a point-location query
is one of the arrangement faces, but in degenerate situations the
query point can lie on an edge, or it may coincide with a vertex.

Point-location queries are common in many applications, and also
play an important role in the incremental construction of arrangements
(and more specifically in the free insertion-functions described in
Section \ref arr_secgl_funcs). Therefore, it is crucial to have the
ability to answer such queries effectively.


\subsection arr_ssecpl Point-Location Queries


Recall that the arrangement representation is decoupled from the
geometric algorithms that operate on it. Thus, the `Arrangement_2`
class template does not support point-location queries directly.
Instead, the \ref PkgArrangementOnSurface2 package provides a set of
class templates that are capable of answering such queries; all are
models of the concept `AosPointLocation_2`. Each model employs
a different algorithm or <em>strategy</em> for answering queries.  A
model of this concept must define the \link
AosPointLocation_2::locate() `locate()`\endlink member
function, which accepts an input query-point and returns a polymorphic
object representing the arrangement cell that contains this point.
The returned object is of type
`Arr_point_location_result<Arrangement_2>::%Type`, which is a
discriminated union container of the bounded types \link
Arrangement_on_surface_2::Vertex_const_handle
`Vertex_const_handle`\endlink, \link
Arrangement_on_surface_2::Halfedge_const_handle
`Halfedge_const_handle`\endlink, or \link
Arrangement_on_surface_2::Face_const_handle
`Face_const_handle`\endlink. Depending on whether the query point is
located inside a face, lies on an edge, or coincides with a vertex,
the appropriate handle can be obtained with <em>value retrieval</em>
by `std::get` as demonstrated in the example below.

Note that the handles returned by the \link
AosPointLocation_2::locate() `locate()`\endlink functions are
non-mutable (`const`). If necessary, such handles may be cast to
mutable handles using the
`Arrangement_on_surface_2::non_const_handle()` methods.

An object `pl` of any point-location class must be attached to an
`Arrangement_2` object `arr` before it is used to answer
point-location queries on `arr`. This attachment can be performed
when `pl` is constructed or at a later time using the
`pl.init(arr)` call.

The function template `locate_point()` listed below accepts a
point-location object, the type of which is a model of the
`AosPointLocation_2` concept, and a query point. The function
template issues a point-location query for the given point, and prints
out the result.  It is defined in the header file
`point_location_utils.h`.

\anchor lst_pl
\code
template <typename PointLocation>
void locate_point(const PointLocation& pl,
                  const typename PointLocation::Arrangement_2::Point_2& q) {
  using Point_location = PointLocation;
  using Arrangement_2 = typename Point_location::Arrangement_2;
  typename CGAL::Arr_point_location_result<Arrangement_2>::Type obj =
    pl.locate(q);

  // Print the result.
  print_point_location<Arrangement_2>(q, obj);
}
\endcode

The function template `locate_point()` calls an instance of the
function template `print_point_location()`, which inserts the
result of the query into the standard output-stream. It is listed
below, and defined in the header file `point_location_utils.h`.
Observe how the function `std::get()` is used to cast the
resulting object into a handle to an arrangement feature. The
point-location object `pl` is assumed to be already attached
to an arrangement.

\code
template <typename Arrangement_>
void print_point_location
(const typename PointLocation::Arrangement_::Point_2& q
 typename CGAL::Arr_point_location_result<Arrangement_>::Type obj) {
  using Arrangement_2 = Arrangement_;

  using Vertex_const_handle = typename Arrangement_2::Vertex_const_handle;
  using Halfedge_const_handle = typename Arrangement_2::Halfedge_const_handle;
  using Face_const_handle = typename Arrangement_2::Face_const_handle;

  const Vertex_const_handle*   v;
  const Halfedge_const_handle* e;
  const Face_const_handle*     f;

  std::cout << "The point (" << q << ") is located ";
  if (f = std::get_if<Face_const_handle>(&obj)) // located inside a face
    std::cout << "inside "
              << (((*f)->is_unbounded()) ? "the unbounded" : "a bounded")
              << " face.\n";
  else if (e = std::get_if<Halfedge_const_handle>(&obj)) // located on an edge
    std::cout << "on an edge: " << (*e)->curve() << std::endl;
  else if (v = std::get_if<Vertex_const_handle>(&obj)) // located on a vertex
    std::cout << "on " << (((*v)->is_isolated()) ? "an isolated" : "a")
              << " vertex: " << (*v)->point() << std::endl;
  else CGAL_error_msg("Invalid object.");
}
\endcode


\subsection aos_sssec-pl_strategy Choosing a Point-Location Strategy


Each of the various point-location class templates employs a different
algorithm or <em>strategy</em>\cgalFootnote{The term <em>strategy</em>
is borrowed from the design-pattern taxonomy \cgalCite{cgal:ghjv-dpero-95},
Chapter 5. A <em>strategy</em> provides the means to define a family of
algorithms, each implemented by a separate class. All classes that implement
the various algorithms are made interchangeable, letting the algorithm in use
vary according to the user choice.} for answering queries:
<UL>
<LI> `Arr_naive_point_location<Arrangement>` employs the
  <em>naive</em> strategy. It locates the query point naively,
  exhaustively scanning all arrangement cells.

<LI> `Arr_walk_along_line_point_location<Arrangement>` employs
  the <em>walk-along-a-line</em> (or <em>walk</em> for short) strategy.
  It simulates a traversal, in reverse order, along an imaginary
  vertical ray emanating from the query point. It starts from the
  unbounded face of the arrangement and moves downward toward the
  query point until it locates the arrangement cell containing it.

<LI>`Arr_landmarks_point_location<Arrangement,Generator>` uses a set
  of <em>landmark</em> points, the location of which in the
  arrangement is known. It employs the <em>landmark</em>
  strategy. Given a query point, it uses a nearest-neighbor
  search-structure (a <span class="textsc">Kd</span>-tree is used by
  default) to find the nearest landmark, and then traverses the
  straight-line segment connecting this landmark to the query point.

  There are various ways to select the landmark set in the
  arrangement. The selection is governed by the `Generator`
  template parameter. The default generator class, namely
  `Arr_landmarks_vertices_generator`, selects all the vertices of
  the attached arrangement as landmarks. Additional generators that
  select the set in other ways, such as by sampling random
  points or choosing points on a grid, are also available; see the
  Reference Manual for more details.

  The arrangement attached to the landmark strategy must be either (i)
  an instance of the `Arrangement_2<GeomTraits,Dcel>` class template,
  where the `GeomTraits` parameter is substituted by a geometry-traits
  class that models the `AosLandmarkTraits_2` concept, or (ii) an
  instance of the `Arrangement_on_surface_2<GeomTraits,TopolTraits>`
  class template, where the `GeomTraits` is similarly substituted;
  see Section \ref aos_sssec-tr_landmarks_concept for details about
  this concept. Most traits classes included in the \ref
  PkgArrangementOnSurface2 package are models of this refined concept.

<LI>`Arr_trapezoid_ric_point_location<Arrangement>` implements an
  improved variant of Mulmuley's point-location algorithm
  \cgalCite{m-fppa-90}; see also \cgalCite{bkos-cgaa-00}, Chapter 6.
  The (expected) query-time is logarithmic in the size of the
  arrangement. The arrangement faces are decomposed into simpler cells
  each of constant complexity, known as <em>pseudo trapezoids</em>,
  and a search structure (a directed acyclic graph) is constructed on
  top of these cells, facilitating the search of the pseudo trapezoid
  (hence the arrangement cell) containing a query point in expected
  logarithmic time. The trapezoidal map and the search structure are
  built by a randomized incremental construction algorithm (RIC).

<LI> `Arr_triangulation_point_location<Arrangement>` uses a
  constrained triangulation, provided by the \ref PkgTriangulation2
  package, as a search structure. Every time the arrangement is
  modified the constrained triangulation search-structure is
  reconstructed from scratch, where the edges of the arrangement are
  set to be the constrained edges of the triangulation. This strategy
  is inefficient (especially when the number of modifications applied
  to the arrangement is high) and provided only for educational
  purposes.

</UL>

The first two strategies do not require any extra data. The class
templates that implement them store a pointer to an arrangement object
and operate directly on it. Attaching such point-location objects to
an existing arrangement has virtually no running-time cost at all, but
the query time is linear in the size of the arrangement (the
performance of the walk strategy is much better in practice, but its
worst-case performance is linear). Using these strategies is therefore
recommended only when a relatively small number of point-location
queries are issued by the application, or when the arrangement is
constantly changing (That is, changes in the arrangement structure are
more frequent than point-location queries).  On the other hand, the
landmark and the trapezoid RIC strategies require auxiliary data
structures on top of the arrangement structure, which they need to
construct once they are attached to an arrangement object and need to
keep up-to-date as this arrangement changes.

As mentioned above, the triangulation strategy is provided only for
educational purposes, and thus we do not elaborate on this strategy.
The data structure needed by the landmark and the trapezoidal map RIC
strategies can be constructed in \cgalBigO{N \log N} time, where \f$N\f$
is the overall number of edges in the arrangement, but the constant
hidden in the \cgalBigO{~} notation for the trapezoidal map RIC strategy
is much larger. Thus, construction needed by the landmark algorithm is
in practice significantly faster than the construction needed by the
trapezoidal map RIC strategy. In addition, although both resulting
data structures are asymptotically linear in size, the actual amount
of memory consumed by the landmark algorithm is typically smaller than
to the amount used by the trapezoidal map RIC algorithm, due to the
space-efficient <span class="textsc">Kd</span>-tree used by the
landmark algorithm as the nearest-neighbor search-structure.  The
trapezoidal map RIC algorithm has expected logarithmic query time,
while the query time for the landmark algorithm may be as large as
linear. In practice however, the query times of both strategies are
competitive. For a detailed experimental comparison see
\cgalCite{cgal:hh-eplca-05}.

Updating the auxiliary data structures of the trapezoidal map RIC
algorithm is done very efficiently. On the other hand, updating the
nearest-neighbor search-structure of the landmark algorithm may
consume significant time when the arrangement changes frequently,
especially when a <span class="textsc">Kd</span>-tree is used, as it
must be rebuilt each time the arrangement changes. It is therefore
recommended that the `Arr_landmarks_point_location` class template be
used when the application frequently issues point-location queries on
an arrangement that only seldom changes. If the arrangement is more
dynamic and is frequently going through changes, the
`Arr_trapezoid_ric_point_location` class template should be the
selected point-location strategy.


\cgalFigureBegin{aos_fig-point_location,point_location.png}
The arrangement of line segments, as constructed in \ref
Arrangement_on_surface_2/point_location.cpp, \ref
Arrangement_on_surface_2/vertical_ray_shooting.cpp, and \ref
Arrangement_on_surface_2/batched_point_location.cpp. The arrangement
vertices are drawn as small rings, while the query points \f$q_1,
\ldots, q_6\f$ are drawn as crosses.
\cgalFigureEnd


The program listed below constructs a simple arrangement of five line
segments that form a pentagonal face, with a single isolated
vertex in its interior, as depicted in \cgalFigureRef{aos_fig-point_location}.
Notice that we use the same arrangement structure in the next
three example programs. The arrangement construction is performed by
the function `construct_segment_arr()` defined in the header file
`point_location_utils.h`. (Its listing is omitted here.) The
program employs the naive and the landmark strategies to issue
several point-location queries on this arrangement.

\cgalExample{Arrangement_on_surface_2/point_location.cpp}

Note that the program uses the `locate_point()` function template
to locate a point and nicely print the result of each query; see
\ref lst_pl "code example" in Section \ref arr_ssecpl.


\subsection arr_ssecray_shoot Vertical Ray Shooting


Another query frequently issued on arrangements is the vertical
ray-shooting query: Given a query point, which arrangement cell
is encounter by a vertical ray shot upward (or downward) from this
point? In the general case the ray hits an edge, but it is possible
that it hits a vertex, or that the arrangement does not have any
vertex or edge lying directly above (or below) the query point.

All point-location classes listed in the previous section are also
models of the `AosVerticalRayShoot_2` concept. That is, they
all have member functions called `ray_shoot_up(q)` and
`ray_shoot_down(q)` that accept a query point \f$q\f$. These functions
output a polymorphic object of type
`Arr_point_location_result<Arrangement_2>::%Type`, which is a
discriminated union container of the bounded types \link
Arrangement_on_surface_2::Vertex_const_handle
`Vertex_const_handle`\endlink, \link
Arrangement_on_surface_2::Halfedge_const_handle
`Halfedge_const_handle`\endlink, or \link
Arrangement_on_surface_2::Face_const_handle
`Face_const_handle`\endlink. The latter type is used for the unbounded
face of the arrangement, in case there is no edge or vertex lying
directly above (or below) \f$q\f$.

The function template `vertical_ray_shooting_query()` listed
below accepts a vertical ray-shooting object, the type of which
models the `AosVerticalRayShoot_2` concept. It exports
the result of the upward vertical ray-shooting operation from a
given query point to the standard output-stream. The ray-shooting
object `vrs` is assumed to be already attached to an arrangement.
The function template is defined in the header file
`point_location_utils.h.`

\code
template <typename VerticalRayShooting>
void shoot_vertical_ray(const RayShoot& vrs,
                        const typename
                        VerticalRayShooting::Arrangement_2::Point_2& q) {
  using Vertical_ray_shooting = VerticalRayShooting;

  // Perform the point-location query.
  typename Vertical_ray_shooting::result_type obj = vrs.ray_shoot_up(q);

  // Print the result.
  using Arrangement_2 = typename Vertical_ray_shooting::Arrangement_2;
  using Vertex_const_handle = typename Arrangement_2::Vertex_const_handle;
  using Halfedge_const_handle = typename Arrangement_2::Halfedge_const_handle;
  using Face_const_handle = typename Arrangement_2::Face_const_handle;

  const Vertex_const_handle* v;
  const Halfedge_const_handle* e;
  const Face_const_handle* f;

  std::cout << "Shooting up from (" << q << ") : ";
  if (v = std::get_if<Vertex_const_handle>(&obj))         // we hit a vertex
    std::cout << "hit " << (((*v)->is_isolated()) ? "an isolated" : "a")
              << " vertex: " << (*v)->point() << std::endl;
  else if (e = std::get_if<Halfedge_const_handle>(&obj))  // we hit an edge
    std::cout << "hit an edge: " << (*e)->curve() << std::endl;
  else if (f = std::get_if<Face_const_handle>(&obj)) {    // we hit nothing
    CGAL_assertion((*f)->is_unbounded());
    std::cout << "hit nothing.\n";
  }
  else CGAL_error();
}
\endcode

The program below uses the function template listed above to
perform vertical ray-shooting queries on an arrangement. The
arrangement and the query points are exactly the same as in
\ref Arrangement_on_surface_2/point_location.cpp; see
\cgalFigureRef{aos_fig-point_location}.
\cgalExample{Arrangement_on_surface_2/vertical_ray_shooting.cpp}


\subsection arr_ssecbatched_pl Batched Point-Location


Suppose that at a given moment our application has to issue a
relatively large number \f$m\f$ of point-location queries on a
specific arrangement object. Naturally, It is possible to define a
point-location object and use it to issue separate queries on the
arrangement. However, as explained in Section \ref arr_ssecpl choosing
a simple point-location strategy (either the naive or the walk
strategy) means inefficient queries, while the more sophisticated
strategies need to construct auxiliary structures that incur
considerable overhead in running time.

Alternatively, the <em>2D Arrangement</em> package includes a free
`locate()` function that accepts an arrangement and a range of query
points as its input and sweeps through the arrangement to locate all
query points in one pass. The function outputs the query results as
pairs, where each pair consists of a query point and a discriminated
union container, which represents the cell containing the point; see
Section \ref arr_ssecpl. The output pairs are sorted in increasing
\f$xy\f$-lexicographical order of the query point.

The batched point-location operation is carried out by sweeping the
arrangement. Thus, it takes \cgalBigO{(m+N)\log{(m+N)}} time, where
\f$N\f$ is the number of edges in the arrangement. Issuing separate
queries exploiting a point-location strategy with logarithmic query
time per query, such as the trapezoidal map RIC strategy (see Section
\ref aos_sssec-pl_strategy), is asymptotically more efficient. However,
experiments show that when the number \f$m\f$ of point-location
queries is of the same order of magnitude as \f$N\f$, the batched
point-location operation is more efficient in practice.  One of the
reasons for the inferior performance of the alternative
(asymptotically faster) procedures is the necessity to construct and
maintain complex additional data structures.

The program below issues a batched point-location query, which
is essentially equivalent to the six separate queries performed in
\ref Arrangement_on_surface_2/point_location.cpp; see Section
\ref arr_ssecpl.
\cgalExample{Arrangement_on_surface_2/batched_point_location.cpp}


\section arr_secgl_funcs Free Functions


The `Arrangement_on_surface_2` class template is used to represent
subdivisions of two-dimensional surfaces induced by curves that lie on
such surfaces. Its interface is minimal in the sense that the member
functions hardly perform any geometric operations. In this section we
explain how to utilize the free functions that enhance that set of
operations on arrangements. The implementation of these operations
typically require non-trivial geometric algorithms, and occasionally
incurs additional requirements on the geometry traits class; the
implementation of many of the operations is based on two frameworks,
namely the <em>surface sweep</em> and the <em>zone construction</em>.
These operations accepts \f$x\f$-monotone curves; thus, the
geometry-traits class used by the arrangements passed as input to, or
obtained as output from, these operations must be a model of the
`AosXMonotoneTraits_2` concept; see Section \ref
aos_sec-geom_traits for the precise definition of this concept. It
defines the minimal set of geometric primitives, among other things,
required to perform the algorithms of the surface-sweep and
zone-construction frameworks.


\subsection arr_ssec_zone The Zone Construction Algorithm


Given an arrangement of curves \f$\mathcal{A} =
\mathcal{A}(\mathcal{C})\f$ embedded in a two-dimensional surface, the
<em>zone</em> of an additional curve \f$\gamma \notin \mathcal{C}\f$
in \f$\mathcal{A}\f$ is the union of the features of
\f$\mathcal{A}\f$, whose closure is intersected by \f$\gamma\f$.  The
complexity of the zone is defined as the sum of the complexities of
its constituents. (Notice that some vertices are counted multiple
times.)  The zone of a curve \f$\gamma\f$ is computed by locating the
left endpoint of \f$\gamma\f$ in the arrangement and then "walking"'
along the curve towards the right endpoint, keeping track of the
vertices, edges, and faces crossed on the way. The \ref
PkgArrangementOnSurface2 package offers a generic implementation of an
algorithm that computes the zone. It is used to implement a set of
operations that incrementally construct arrangements induced by sets
of curves that lie in two-dimensional surfaces. For simplicity,
however, we continue to consider arrangements embedded in the plane.





Section \ref aos_ssec-basic-arr_class explains how to construct
arrangements of \f$x\f$-monotone curves that are pairwise disjoint in
their interior when the location of the segment endpoints in the
arrangement is known. Here we relax this constraint, and allow the
location of the inserted \f$x\f$-monotone curve endpoints to be
unknown at the time of insertion.


\subsubsection arr_sssecinsert_non_x Inserting Pairwise Disjoint Curves


We retain, for the moment, the requirement that the interior of the
inserted curve is disjoint from all existing arrangement edges and
vertices.

The call \link CGAL::insert_non_intersecting_curve<>
`insert_non_intersecting_curve(arr, c, pl)`\endlink inserts the
\f$x\f$-monotone curve \f$c\f$ into the arrangement `arr`, with the
precondition that the interior of \f$c\f$ is disjoint from all
existing edges and vertices of `arr`. The third argument `pl` is a
point-location object attached to the arrangement; it is used to
locate both endpoints of \f$c\f$ in the arrangement. Each endpoint is
expected to either coincide with an existing vertex or lie inside a
face.  It is possible to invoke one of the specialized insertion
functions (see Section \ref aos_ssec-basic-arr_class), based on the
query results, and insert \f$c\f$ at its proper
location.\cgalFootnote{The \cgalFootnoteCode{CGAL::insert_non_intersecting_curve<>()}
function template, as all other functions reviewed in this section, is
parameterized by an arrangement type and a point-location type (The
latter must be substituted by a model of the
`AosPointLocation_2` concept).} The insertion operation thus
hardly requires any geometric operations on top of the ones needed to
answer the point-location queries. Moreover, it is sufficient that the
traits class that substitutes the `Traits` template parameter of the
`Arrangement_2<Traits,Dcel>` class template when the latter is
instantiated models the concept `AosBasicTraits_2` concept
(and the concept `AosLandmarkTraits_2` if the landmark
point-location strategy is used), and does not have to support the
computation of intersection points between curves. This implies that
using a kernel that provides exact geometric predicates, but
potentially inexact geometric constructions due to round-off errors, is
still sufficient.

The free-function template `CGAL::insert_non_intersecting_curve<>(arr,
c, pl)` is overloaded. There is a variant that instead of accepting a
user-defined point-location object, it constructs a local object of
the walk point-location type, namely, an instance of the
`Arr_walk_along_line_point_location` class template, and uses it to
insert the curve.


\subsubsection arr_sssecinsert_x_mon Inserting X-monotone Curves


The time it takes to insert a curve \f$c\f$ using the
`insert_non_intersecting_curve()` function template is the sum of the
time is takes to locate the two endpoints of \f$c\f$ and the time is
takes to find the exact place for the new two halfedges mapped to
\f$c\f$ in the circular list of halfedges incident to the two vertices
mapped to the endpoints of \f$c\f$, respectively. This makes the
function relatively efficient; however, its preconditions on the input
curves are still rather restricting. Let us assume that the traits
class that substitutes the `Traits` template parameter of the
`Arrangement_2<Traits,Dcel>` class template models the refined
`AosXMonotoneTraits_2` concept and supports curve intersection
computations; see Section \ref aos_sec-geom_traits for the exact
details. Given an \f$x\f$-monotone curve, it is sufficient to locate
its left endpoint in the arrangement and to trace its <em>zone</em>
(see Section \ref arr_ssec_zone) until the right endpoint is
reached. Each time the new curve \f$c\f$ crosses an existing vertex or
edge, the curve is split into subcurves (in the latter case, we have
to split the curve associated with the existing halfedge as well) and
new edges are associated with the resulting subcurves. Recall that an
edge is represented by a pair of twin halfedges, so we split it into
two halfedge pairs.

The call \link CGAL::insert<>() `insert(arr, c, pl)`\endlink performs
this insertion operation. The `CGAL::insert<>()` function template
accepts an \f$x\f$-monotone curve \f$c\f$, which may intersect some of
the curves already in the arrangement `arr`, and inserts it into the
arrangement by computing its zone.  Users may supply a point-location
object `pl` or use the default walk point-location strategy (namely,
the variant `CGAL::insert<>(arr, c)` is also available). The
running-time of this insertion function is proportional to the
complexity of the zone of the curve \f$c\f$.


\cgalAdvancedBegin In some cases users may have a prior knowledge of
the location of the left endpoint of the \f$x\f$-monotone curve
\f$c\f$ they wish to insert, so they can perform the insertion without
issuing any point-location queries. This can be done by calling the
free function template `CGAL::insert<>(arr, c, obj)`, where `obj` is a
polymorphic object of type
`Arr_point_location_result<Arrangement_2>::%Type` that represents the
location of \f$c\f$s left endpoint in the arrangement.  It is a
discriminated union container of the bounded types \link
Arrangement_on_surface_2::Vertex_const_handle
`Vertex_const_handle`\endlink, \link
Arrangement_on_surface_2::Halfedge_const_handle
`Halfedge_const_handle`\endlink, or \link
Arrangement_on_surface_2::Face_const_handle
`Face_const_handle`\endlink; see also Section \ref arr_ssecpl.
\cgalAdvancedEnd



\subsubsection aos_ssec-insert_gen Inserting General Curves


So far, all the examples have constructed arrangements of line
segments, where the `Arrangement_2` template was instantiated with an
instance of the `Arr_segment_traits_2` class template. In this case,
the restriction that `CGAL::insert<>()` requires an \f$x\f$-monotone
is irrelevant, as all line segments are \f$x\f$-monotone. (Note that
we always deal with <em>weakly</em> \f$x\f$-monotone curves, and we
consider vertical line-segments to be weakly \f$x\f$-monotone).

Consider an arrangement of circles. A circle is obviously not
\f$x\f$-monotone, so `CGAL::insert<>()` cannot be used in this
case.\cgalFootnote{A key operation performed by \cgalFootnoteCode{CGAL::insert<>()} is
to locate the left endpoint of the curve in the arrangement. A circle,
however, does not have any endpoints!} , it is necessary to subdivide
each circle into two \f$x\f$-monotone circular arcs, namely, its upper
half and its lower half, and to insert the two individual
\f$x\f$-monotone arcs.

The free function template `CGAL::insert<>()` is overloaded. It is
possible to another version of this function and pass a curve that is
not necessarily \f$x\f$-monotone, but this is subject to an important
condition. Consider the call \link CGAL::insert<>() `insert(arr, c,
pl)`\endlink, where \f$c\f$ is not necessarily \f$x\f$-monotone. In
this case the type of `arr` must be an instance of the
`Arrangement_2<Traits, Dcel>` class template, where the `Traits`
template parameter is substituted by a traits class that models the
concept `AosTraits_2`, which refines the
`AosXMonotoneTraits_2` concept. It has to define an additional
\link AosTraits_2::Curve_2 `Curve_2`\endlink type, which may
differ from the \link AosBasicTraits_2::X_monotone_curve_2
`X_monotone_curve_2`\endlink type.  It also has to support the
subdivision of curves of this new type into \f$x\f$-monotone curves
and possibly singular points; see the exact details in Section \ref
aos_sec-geom_traits. The `CGAL::insert<>(arr, c, pl)` function
performs the insertion of the curve \f$c\f$ that does not need to be
\f$x\f$-monotone, into the arrangement by subdividing it into
\f$x\f$-monotone subcurves and inserting all individual
\f$x\f$-monotone subcurves. Users may supply a point-location object
`pl`, or use the default walk point-location strategy by calling
`CGAL::insert<>(arr, c)`.


\subsubsection arr_sssecinsert_point Inserting Points


The `Arrangement_2` class template has a member function that inserts
a point as an isolated vertex in a given face. The free function
template `CGAL::insert_point<>(arr, p, pl)` inserts a vertex that
corresponds to the point \f$p\f$ into `arr` at an arbitrary
location. It uses the point-location object `pl` to locate the point
in the arrangement (by default, the walk point-location strategy is
used), and acts according to the result as follows:

<UL>

<LI>If \f$p\f$ is located inside a face, it is inserted as an
isolated vertex inside this face.

<LI>If \f$p\f$ lies on an edge, the edge is split to create a
vertex associated with \f$p\f$.

<LI>Otherwise,\f$p\f$  coincides with an existing vertex and
no further actions are needed.
</UL>

In all cases, the function returns a handle to the vertex
associated with \f$p\f$.

The type of `arr` must be and instance of the `Arrangement_2` class
template instantiated with a traits class that models the
`AosXMonotoneTraits_2` concept, as the insertion operation may
involve the splitting of curves.


\subsubsection arr_sssecinsert_ex Inserting Intersecting Line Segments (code example)



\cgalFigureBegin{aos_fig-incremental_insertion,incremental_insertion.png}
An arrangement of five intersecting line segments, as constructed in
\ref Arrangement_on_surface_2/incremental_insertion.cpp and
\ref Arrangement_on_surface_2/aggregated_insertion.cpp. The
segment endpoints are marked by black disks and the arrangement
vertices that correspond to intersection points are marked by
circles. The query point \f$q\f$ is marked with a cross and the face
that contains it is shaded.
\cgalFigureEnd


The program below constructs an arrangement of five intersecting
line-segments \f$s_1, \ldots, s_5\f$. It is known that \f$s_1\f$ and
\f$s_2\f$ do not intersect, so
`CGAL::insert_non_intersecting_curve<>()` is used to insert them into
the empty arrangement. The rest of the segments are inserted using
`CGAL::insert<>()`. Using a kernel that constructs geometric objects
in an inexact manner (due to round-off errors) may yield a program that
computes incorrect results and crashes from time to time. This is
avoided by using a kernel that provides exact geometric-object
constructions as well as exact geometric-predicate evaluations. The
header file `arr_exact_construction_segments.h`, just like the header
file `arr_inexact_construction_segments.h`, contains the definitions
for arrangements of line segments.  Unlike the latter, it uses a
kernel suitable for arrangements induced by curves that intersect each
other, namely a kernel that is exact always. Note that we alternately
use the naive point-location strategy, given explicitly to the
insertion functions, and the default walk point-location strategy.

The resulting arrangement is depicted in
\cgalFigureRef{aos_fig-incremental_insertion}, where the vertices that
correspond to segment endpoints are drawn as dark discs, and the
vertices that correspond to intersection points are drawn as
circles. It consists of 13 vertices, 16 edges, and 5 faces. We also
perform a point-location query on the resulting arrangement. The query
point \f$q\f$ is drawn as a plus sign. The face that contains it is
drawn with a shaded texture. The program calls an instance of the
function template `print_arrangement_size()`, which prints
quantitative measures of the arrangement; see \ref lst_paz
"code example" for its listing in Section \ref aos_ssec-basic-arr_class.

\cgalExample{Arrangement_on_surface_2/incremental_insertion.cpp}


\subsection arr_ssseczone Other Zone Related Functions


In this section we have described so far free functions that insert
curves and points into a given arrangement. Now we describe functions
that do not change the arrangement at all; nevertheless, they are
closely related to the incremental insertion functions, as they also
use the zone framework.

The free function template `%CGAL::do_intersect<>(arr, c, pl)` checks
whether the given query curve \f$c\f$ intersects the curves and points
of an existing arrangement `arr`. If \f$c\f$ is not \f$x\f$-monotone
(that is, it is of type \link AosTraits_2::Curve_2
`Curve_2`\endlink) the curve is subdivided into \f$x\f$-monotone
subcurves and isolated points. Each \f$x\f$-monotone curve (or point)
is checked for intersection in turn using the zone framework. For
points we simply apply point-location. Given an \f$x\f$-monotone
curve, first its left endpoint is located; then, its zone is computed
starting from its left endpoint location. The zone computation
terminates when an intersection with an arrangement curve or point is
found or when the right endpoint is reached.  A given point-location
object is used for locating the left endpoint of the curve in the
existing arrangement. There is a variant that instead of accepting a
user-defined point-location object, it constructs a local object of
the walk point-location type, namely, an instance of the
`Arr_walk_along_line_point_location` class template, and uses it to
locate the endpoint. If the given curve is \f$x\f$-monotone then the
traits type must model the `AosXMonotoneTraits_2` concept. If
the curve is not \f$x\f$-monotone then the traits type must model the
`AosTraits_2` concept.

The `CGAL::zone<>(arr, c, oi, pl)` function template computes the zone
of a given \f$x\f$-monotone curve in a given arrangement. More
precisely, it outputs all the arrangement cells (namely, vertices,
edges, and faces) that the input \f$x\f$-monotone curve \f$C\f$
intersects in the order they are discovered when traversing the curve
from left to right.  The function uses a given point-location object
to locate the left endpoint of the given curve. There is a variant
that instead of accepting a user-defined point-location object, it
constructs a local object of the walk point-location type, namely, an
instance of the `Arr_walk_along_line_point_location` class template,
and uses it to locate the endpoint. The traits type must model the
`AosXMonotoneTraits_2` concept.


\subsection arr_ssec_sweep The Surface-Sweep Algorithm


The famous plane-sweep algorithm introduced by Bentley and Ottmann was
originally formulated for sets of line segments in the plane. The \ref
PkgSurfaceSweep2 package offers a generic implementation of a
generalized version of the original plane-sweep algorithm. It (i)
operates in two-dimensional surfaces (not restricted to the plane),
(ii) accepts various families of \f$x\f$-monotone curves (not only
line segments), and (iii) handles overlaps. (Observe that the original
algorithm did not handle overlaps. Handling overlaps is difficult,
especially for polyline, as two polylines may overlap in more than one
connected component.) The generic implementation serves as the
foundation of a family of concrete operations described in the rest of
this section, such as aggregately constructing an arrangement induced
by a set of curves that lie in a two-dimensional surface and outputting
the overlay of two arrangements.





Given a set of \f$n\f$ input curves, you can insert the curves in the
set into an arrangement incrementally one by one. However, the \ref
PkgArrangementOnSurface2 package also provides a couple of free
(overloaded) functions that aggregately insert a range of curves into
an arrangement using the surface-Sweep framework.

<UL>

<LI>`CGAL::insert_non_intersecting_curves<>(arr, begin, end)` inserts
a range of \f$x\f$-monotone curves given by the range `[begin, end)`
into an arrangement `arr`. The \f$x\f$-monotone curves
should be pairwise disjoint in their interior and also
interior-disjoint from all existing curves and points of `arr`.</LI>

<LI>\link CGAL::insert<>() `insert(arr, begin, end)`\endlink operates
  on a range of \f$x\f$-monotone curves that may intersect one
  another.</LI>

</UL>

We distinguish between two cases:
(i) The given arrangement `arr` is empty (has only an unbounded face),
so it must be construct from scratch.
(ii) The given arrangement `arr` is not empty.

In the first case, we sweep over the input curves, compute their
intersection points, and construct the \dcel that represents their
arrangement. This process is performed in \cgalBigO{(n + k)\log
n} time, where \f$k\f$ is the total number of intersection
points. The running time is asymptotically better than the time needed
for incremental insertion if the arrangement is relatively sparse
(when \f$k\f$ is \cgalBigO{\frac{n^2}{\log n}}), but it is recommended
that this aggregate construction process be used even for dense
arrangements, since the plane-sweep algorithm performs fewer geometric
operations compared to the incremental insertion algorithms, and hence
typically runs much faster in practice.

Another important advantage of the aggregated insertion functions is
that they do not issue point-location queries. Thus, no point-location
object needs to be attached to the arrangement. As explained in
Section \ref arr_ssecpl, there is a trade-off between construction
time and query time in each of the point-location strategies, which
affects the running times of the incremental insertion
process. Naturally, this trade-off is absent in the case of aggregated
insertion.

The example below shows how to construct the same arrangement of five
line segments built incrementally in \ref
Arrangement_on_surface_2/incremental_insertion.cpp depicted in
\cgalFigureRef{aos_fig-incremental_insertion} using the aggregate
insertion function \link CGAL::insert<>() `insert()`\endlink.  Note
that no point-location object needs to be defined and attached to the
arrangement.

\cgalExample{Arrangement_on_surface_2/aggregated_insertion.cpp}

Next we handle the case where we have to insert a set of \f$n\f$
curves into an existing arrangement. Let \f$N\f$ denote the number of
edges in the arrangement.  If \f$n\f$ is very small compared to
\f$N\f$ (in theory, we would say that if \f$n = o(\sqrt{N})\f$), we
insert the curves one by one. For larger input sets, we use the
aggregate insertion procedures.


\cgalFigureBegin{aos_fig-global_insertion,global_insertion.png} An
arrangement of intersecting line segments, as constructed in \ref
Arrangement_on_surface_2/global_insertion.cpp. The segments of
\f$\mathcal{S}_1\f$ are drawn in solid lines and the segments of
\f$\mathcal{S}_2\f$ are drawn in dark dashed lines. Note that the
segment \f$s\f$ (light dashed line) overlaps one of the segments in
\f$\mathcal{S}_1\f$.  \cgalFigureEnd


The program below aggregately construct an arrangement of a set
\f$\mathcal{S}_1\f$ containing five line segments (drawn as solid
lines). Then, it inserts a single segment \f$s\f$ (drawn as a dotted
line) using the incremental insertion function. Finally, it adds a set
\f$\mathcal{S}_2\f$ with five more line segments (drawn as dashed
lines) in an aggregate fashion.  Notice that the line segments of
\f$\mathcal{S}_1\f$ are pairwise interior-disjoint, so
`insert_non_intersecting_curves()` is safely used. \f$\mathcal{S}_2\f$
also contains pairwise interior-disjoint segments, but as they
intersect the existing arrangement, \link
insert(Arrangement_2<Traits,Dcel>&, InputIterator, InputIterator)
`insert()`\endlink must be used to insert them. Also note that the
single segment \f$s\f$ inserted incrementally partially overlaps an
existing arrangement curve; the overlapped portion is drawn as a
dash-dotted line.

\cgalExample{Arrangement_on_surface_2/global_insertion.cpp}

We summarize the three levels of arrangement types
based on curve monotonicity and intersection properties in the table
below. The three levels, starting from the most restrictive, are
(i) \f$x\f$-monotone curves that are pairwise disjoint in their
  interior,
(ii) \f$x\f$-monotone curves (which are possibly intersecting one
  another), and
(iii) general curves. We list the single-curve insertion functions.

<table>
<tr><th>Type of Curves <th>Geometry-Traits Concept <th>Insertion Function
<tr><td>\f$x\f$-monotone and pairwise disjoint <td>`AosBasicTraits_2` or `AosLandmarkTraits_2` <td>`CGAL::insert_non_intersecting_curve<>()`
<tr><td>\f$x\f$-monotone <td>`AosXMonotoneTraits_2` <td> `%CGAL::insert<>()`
<tr><td>general <td>`AosTraits_2` <td>`%CGAL::insert<>()`
</table>

The insertion function template `%insert()` is overloaded to
(i) incrementally insert a single \f$x\f$-monotone curve,
(ii) incrementally insert a single general curve,
(iii) aggregately insert a set of \f$x\f$-monotone curves, and
(iv) aggregately insert a set of general curves.
The `CGAL::insert_non_intersecting_curves<>()` function template
aggregately inserts a set of \f$x\f$-monotone pairwise interior-disjoint
curves into an arrangement.


\subsection arr_ssecgl_remove Removing Vertices and Edges


The free functions `remove_vertex()` and `remove_edge()` handle the
removal of vertices and edges from an arrangement, respectively. The
difference between these functions and the corresponding member
functions of the `Arrangement_2` class template (see Section \ref
arr_sssecmf_iso_verts and Section \ref arr_sssecmf_halfedges) has to do
with the ability to merge two curves associated with adjacent edges to
form a single curve associated with a single edge.  An attempt to
remove a vertex or an edge from an arrangement object `arr` using the
free functions above requires that the traits class used to
instantiate the arrangement type of `arr` models the concept
`AosXMonotoneTraits_2`, which refines the
`AosBasicTraits_2` concept; see Section \ref
aos_sec-geom_traits.

The function template `CGAL::remove_vertex<>(arr, v)` removes the
vertex \f$v\f$ from the given arrangement `arr`, where \f$v\f$ is
either an isolated vertex or is a <em>redundant</em> vertex. Namely,
it has exactly two incident edges that are associated with two curves
that can be merged to form a single \f$x\f$-monotone curve. If
neither of the two cases apply, the function returns an indication
that it has failed to remove the vertex.

The function `CGAL::remove_edge<>(arr, e)` removes the edge \f$e\f$
from the arrangement by simply calling `arr.remove_edge(e)`; see
Section \ref arr_ssecmodify. In addition, if either of the end
vertices of \f$e\f$ becomes isolated or redundant after the removal of
the edge, it is removed as well.

\image html global_removal.png
\image latex global_removal.png

The following example demonstrates the usage of the free removal
functions. It creates an arrangement of four line segment \f$s_1,
\ldots, s_4\f$ forming an H-shape with two horizontal edges induced by
\f$s_1\f$ and \f$s_2\f$ (drawn as dashed lines). Then it removes the
two horizontal edges and clears all redundant vertices (drawn as
lightly shaded discs), such that the final arrangement consists of
just two edges associated with the vertical line segments \f$s_3\f$
and \f$s_4\f$.

\cgalExample{Arrangement_on_surface_2/global_removal.cpp}


\subsection arr_ssec_decompose Vertical Decomposition


As you have already seen, an arrangement face may have a fairly
complicated structure; its outer boundary may be very large, and it
may contain numerous holes.  For many practical applications, it is
more convenient to analyze the faces by decomposing each into a finite
number of cells (preferably convex when dealing with arrangements of
linear curves) of constant complexity. Vertical decomposition is a
generic way to achieve such a simplification of the arrangement.

Given an arrangement, we consider each arrangement vertex \f$v\f$, and
locate the feature lying vertically below the vertex and the feature
lying vertically above it, or the unbounded face in case there is no
such feature. (Such a feature is also the result of the vertical
ray-shooting operation from the vertex \f$v\f$, as described in
Section \ref arr_ssecray_shoot.) It is now possible to construct two
vertical segments connecting \f$v\f$ to the feature above it and to
the feature below it, possibly extending the vertical segments to
infinity. The collection of the vertical segments and rays computed
for all arrangement vertices induces a subdivision of the arrangement
into simple cells. There are two types of bounded two-dimensional
cells, as follows:

<UL>

<LI> Cells whose outer boundaries comprise four edges, of which
two originate from the original arrangement and the other two are
vertical.

<li> Cells whose outer boundaries comprise three edges, of which two
originate from the original arrangement and intersect at a common
vertex and the remaining one is vertical.

</UL>


\cgalFigureBegin{aos_fig-bounded_vd,bounded_vertical_decomposition.png}
An arrangement of four line segments and its vertical decomposition
into pseudo trapezoids, as constructed in \ref
Arrangement_on_surface_2/bounded_vertical_decomposition.cpp. The
segments of the arrangement are drawn in solid blue lines and the
segments of the vertical decomposition are drawn in dark dotted lines.
\cgalFigureEnd


In the case of an arrangement of line segments, two-dimensional cells
of the former type are trapezoids (as they have a pair of parallel
vertical edges), while two-dimensional cells of the latter type are
triangles, which can be viewed as degenerate trapezoids. The unbounded
cells can be similarly categorized into two types. Observe that the
boundary of an unbounded cell contains only one original edge or none
and it may contain only non-vertical edges.  The resulting cells are
therefore referred to as <em>pseudo trapezoids</em>. The
\cgalFigureRef{aos_fig-bounded_vd} depicts the vertical decomposition
of an arrangement induced by four line segments, as constructed in
\ref Arrangement_on_surface_2/bounded_vertical_decomposition.cpp and
listed below. The decomposition consists of 14 pseudo trapezoids, out
of which two are bounded triangles, two are bounded trapezoids, and 10
are unbounded trapezoids.

The function template `decompose()` accepts an arrangement
\f$\mathcal{A}\f$ and outputs for each vertex \f$v\f$ of
\f$\mathcal{A}\f$ a pair of features---one that directly lies below
\f$v\f$ and another that directly lies above \f$v\f$. It is
implemented as a plane-sweep algorithm, which aggregately computes the
set of pairs of features. Let \f$v\f$ be a vertex of
\f$\mathcal{A}\f$. The feature above (respectively below) \f$v\f$ may
be one of the following:

<UL>

<LI> Another vertex \f$u\f$ having the same \f$x\f$-coordinate as \f$v\f$.

<LI> An arrangement edge associated with an \f$x\f$-monotone curve
that contains \f$v\f$ in its \f$x\f$-range.

<LI> An unbounded face in case \f$v\f$ is incident to an unbounded
face, and there is no curve lying above (respectively below) it.

<LI> An empty object, in case \f$v\f$ is the lower (respectively
upper) endpoint of a vertical edge in the arrangement.

</UL>

\cgalExample{Arrangement_on_surface_2/bounded_vertical_decomposition.cpp}

As you might have noticed, the code above contains a call to an
instance of a the function template `read_objects()`. It reads the
description of geometric objects from a file and constructs them. It
accepts the name of an input file that contains the plain-text
description of the geometric objects and an output iterator for
storing the newly constructed objects.  When the function is
instantiated, the first template parameter, namely `Type`, must be
substituted by the type of objects to read. It is assumed that an
extractor operator (`>>`) that extracts objects of the given type from
the input stream is available. The listing of the function template,
which is defined in the file `read_objects.h`, is omitted here

\cgalAdvancedBegin

In Section \ref aos_sec-unbounded you will learn that we also support
arrangements induced by unbounded curves, referred to as
<em>unbounded arrangements</em>.  For such an arrangement we maintain an
imaginary rectangle with left, right, bottom, and top boundaries,
which bound the concrete vertices and edges of the
arrangement. Halfedges that represent the boundaries of the rectangle
are <em>fictitious</em>. The `decompose()` function
template handles unbounded arrangements. If \f$v\f$ is a vertex of an
unbounded arrangement, and \f$v\f$ is incident to an unbounded face
and there is no curve lying above (respectively below) it, the feature
above (respectively below) \f$v\f$ returned by the function template
`decompose()` is a fictitious edge.

\cgalAdvancedEnd


\section aos_sec-unbounded Arrangements of Unbounded Curves


All the arrangements constructed and manipulated in previous chapters
were induced only by line segments, which are, in particular, bounded
curves. Such arrangements always have one unbounded face that contains
all other arrangement features. In this section we explain how to
construct arrangements of unbounded curves. For simplicity of
exposition, we stay with linear objects and restrict our examples in
this section to lines and rays.  However, the discussion in this
section, as well as the software described, apply more generally to
arbitrary curves in two-dimensional surfaces.


\subsection aos_ssec-unbounded-rep Representing Arrangements of Unbounded Curves


Given a set \f$\mathcal{C}\f$ of unbounded curves, a simple approach
for representing the arrangement induced by \f$\mathcal{C}\f$ would be
to clip the unbounded curves using an axis-parallel rectangle that
contains all finite curve endpoints and intersection points between
curves in \f$\mathcal{C}\f$. This process would result in a set of
bounded curves (line segments if \f$\mathcal{C}\f$ consists of lines
and rays), and it would be straightforward to compute the arrangement
induced by this set.  However, we would like to operate directly on
the unbounded curves without having to preprocess them. Moreover, if
we are not given all the curves inducing the arrangement in advance,
then the choice of a good bounding rectangle may change as more curves
are introduced.


\cgalFigureBegin{aos_fig-unb_dcel,unb_dcel.png}
A \dcel representing an arrangement of four lines. Halfedges are
drawn as thin arrows. The vertices \f$v_1, \ldots, v_8\f$ lie at
infinity, and are not associated with valid points. The halfedges that
connect them are fictitious, and are not associated with concrete
curves. The face denoted \f$f_0\f$ (lightly shaded) is the fictitious
"unbounded face" which lies outside the bounding rectangle (dashed)
that bounds the actual arrangement. The four fictitious vertices
\f$v_{\rm bl}, v_{\rm tl}, v_{\rm br}\f$ and \f$v_{\rm tr}\f$
represent the four corners of the imaginary bounding rectangle.
\cgalFigureEnd


Instead of an explicit approach, we use an implicit bounding rectangle
embedded in the \dcel structure. \cgalFigureRef{aos_fig-unb_dcel}
shows the arrangement of four lines that subdivide the plane into
eight unbounded faces and two bounded ones. Notice that in this case
portions of the unbounded faces now have outer boundaries (those
portions inside the bounding rectangle), and the halfedges along these
outer CCBs are drawn as arrows. The bounding rectangle is drawn
dashed. The vertices \f$v_1,v_2,\ldots,v_8\f$, which lie on the
bounding rectangle, represent the unbounded ends of the four lines
that approach infinity. The halfedges connecting them, which overlap
with the bounding rectangle, are not associated with geometric curves.
Thus, we refer to them as <em>fictitious</em>. Note that the outer
CCBs of the unbounded faces contain fictitious halfedges. The twins of
these halfedges form together one connected component that corresponds
to the entire imaginary rectangle. It forms a single hole in the face
\f$\tilde{f}\f$. We refer to \f$\tilde{f}\f$ as <em>fictitious</em>,
since it does not correspond to a real two-dimensional cell of the
arrangement. Finally, there are four additional vertices denoted by
\f$v_{\rm bl}, v_{\rm tl}, v_{\rm br}\f$, and \f$v_{\rm tr}\f$, which
coincide with the bottom-left, top-left, bottom-right, and top-right
corners of the bounding rectangle, respectively. They do not lie on
any curve, and are referred to as <em>fictitious</em> as well. These
four vertices identify each of the fictitious edges as lying on the
top, the bottom, the left, and the right edge of the imaginary
bounding rectangle. The four fictitious vertices exist even when the
arrangement is empty: In this case they are connected by four pairs of
fictitious halfedges that define a single unbounded face (which
represents the entire \f$\mathbb{R}^2\f$ plane) lying inside the
imaginary bounding rectangle and a fictitious face lying outside.

In summary, there are four types of arrangement vertices, which differ
from one another by their location with respect to the imaginary
bounding rectangle as follows:

<OL>

<LI> \anchor type-normal A vertex, associated with a point in
  \f$\mathbb{R}^2\f$. Such a vertex always lies inside the bounding
  rectangle and has bounded coordinates..

<LI> \anchor type-unbounded A vertex that represents an unbounded end
  of an \f$x\f$-monotone curve that approaches \f$x = -\infty\f$ or at
  \f$x = \infty\f$. In case of a horizontal line or a curve with a
  horizontal asymptote, the \f$y\f$-coordinate of the curve end may be
  finite (see, for example, the vertices \f$v_2\f$ and \f$v_7\f$ in
  \cgalFigureRef{aos_fig-unb_dcel}), but in general the curve end also
  approaches \f$y = \pm\infty\f$; see for instance the vertices
  \f$v_1\f$, \f$v_3\f$, \f$v_6\f$ and \f$v_8\f$ in
  \cgalFigureRef{aos_fig-unb_dcel}). For convenience, we always take a
  "tall" enough bounding rectangle and treat such vertices as lying on
  either the left or the right rectangle edges (that is, if a curve
  approaches \f$x = -\infty\f$, its left end will be represented by a
  vertex on the left edge of the bounding rectangle, and if it
  approaches \f$x = \infty\f$, its right end will be represented by a
  vertex on the right edge).

<LI> \anchor typeunboundedvertical A vertex that represents the
  unbounded end of a vertical linear curve (line or ray) or of a curve
  with a vertical asymptote (finite \f$x\f$-coordinate and an
  unbounded \f$y\f$-coordinate). Such a vertex always lies on one of
  the horizontal edges of the bounding rectangle (either the bottom
  one if \f$y = -\infty\f$, or the top one if \f$y = \infty\f$). The
  vertices \f$v_4\f$ and \f$v_5\f$ in \cgalFigureRef{aos_fig-unb_dcel}
  are of this type.

<LI> \anchor typefictitious The fictitious vertices that represent the
  four corners of the bounding rectangle.

</OL>


\cgalFigureBegin{aos_fig-unb_asymptote,unb_asymptote.png}
The portions of a horizontal line, a vertical line, and two rectangular
hyperbolas with horizontal and vertical asymptotes confined to the
imaginary bounding rectangle.
\cgalFigureEnd


A vertex (at infinity) of Type 2 or Type 3 above always has three
incident edges---one concrete edge that is associated with an
unbounded portion of an \f$x\f$-monotone curve, and two fictitious
edges connecting the vertex to its neighboring vertices at infinity or
the corners of the bounding rectangle; see
\cgalFigureRef{aos_fig-unb_asymptote}.  Fictitious vertices (of type 4
above) have exactly two incident fictitious edges. See Section \ref
aos_sec-geom_traits for an explanation on how the traits-class
interface helps impose the fact that a vertex at infinity is incident
to a single non-fictitious edge.

The traits class that substitutes the `Traits` parameter of the
`Arrangement_2<Traits,Dcel>` class template when the latter is
instantiated specifies whether the arrangement instance supports
unbounded curves through the definitions of some tags nested in the
traits class; see Section \ref aos_sssec-geom_traits-concepts_basic
for details. Every arrangement that supports unbounded curves supports
bounded curves as well, but not vice versa. Maintaining an arrangement
that supports unbounded curves incurs an overhead due to the necessity
to manage the imaginary bounding rectangle. If you know beforehand
that all input curves that induce a particular arrangement are
bounded, define your arrangement accordingly. That is, use a traits
class that does not support unbounded curves.


\subsubsection arr_sssecunb_basic Basic Manipulation and Traversal Methods


The types \link Arrangement_on_surface_2::Vertex `Vertex`\endlink,
\link Arrangement_on_surface_2::Halfedge `Halfedge`\endlink, and \link
Arrangement_on_surface_2::Face `Face`\endlink nested in the
`Arrangement_2` class template support the methods described below in
addition to the ones listed in Section \ref arr_ssectraverse. Let
\f$v\f$, \f$e\f$, and \f$f\f$ be handles to a vertex of type \link
Arrangement_on_surface_2::Vertex `Vertex`\endlink, a halfedge of type
\link Arrangement_on_surface_2::Halfedge `Halfedge`\endlink, and a
face of type \link Arrangement_on_surface_2::Face `Face`\endlink,
respectively.

<UL>

<LI>The calls \link
  Arrangement_on_surface_2::Vertex::parameter_space_in_x()
  `v->parameter_space_in_x()`\endlink and \link
  Arrangement_on_surface_2::Vertex::parameter_space_in_y()
  `v->parameter_space_in_y()`\endlink determine the location of the
  geometric embedding of the vertex \f$v\f$. The call \link
  Arrangement_on_surface_2::Vertex::parameter_space_in_x()
  `v->parameter_space_in_x()`\endlink returns `CGAL::ARR_INTERIOR` if
  the \f$x\f$-coordinate associated with \f$v\f$ is finite,
  `CGAL::ARR_LEFT_BOUNDARY` if \f$v\f$ represents the end of a curve
  the \f$x\f$-coordinate of which approaches \f$-\infty\f$, and
  `CGAL::ARR_RIGHT_BOUNDARY` if \f$v\f$ represents the end of a curve
  the \f$x\f$-coordinate of which approaches \f$\infty\f$. Similarly,
  the call \link
  Arrangement_on_surface_2::Vertex::parameter_space_in_y()
  `v->parameter_space_in_y()`\endlink returns `CGAL::ARR_INTERIOR` if
  the \f$y\f$-coordinate associated with \f$v\f$ is finite and
  `CGAL::ARR_BOTTOM_BOUNDARY` or `CGAL::ARR_TOP_BOUNDARY` if \f$v\f$
  represents the end of a curve the \f$y\f$-coordinate of which
  approaches \f$-\infty\f$ or \f$\infty\f$, respectively.

  The nested \link Arrangement_on_surface_2::Vertex `Vertex`\endlink
  type also provides the Boolean predicate \link
  Arrangement_on_surface_2::Vertex::is_at_open_boundary()
  `is_at_open_boundary()`\endlink.  If the call \link
  Arrangement_on_surface_2::Vertex::is_at_open_boundary()
  `v->is_at_open_boundary()`\endlink predicates evaluates to `false`,
  you can access the point associated with \f$v\f$. Otherwise, \f$v\f$
  is not associated with a \link Arrangement_on_surface_2::Point_2
  `Point_2`\endlink object, as it represents the unbounded end of a
  curve that approaches infinity.

<LI>The nested \link Arrangement_on_surface_2::Halfedge
  `Halfedge`\endlink type provides the Boolean predicate \link
  Arrangement_on_surface_2::Halfedge::is_fictitious `is_fictitious()`\endlink. If
  the call \link Arrangement_on_surface_2::Halfedge::is_fictitious
  `e->is_fictitious()`\endlink evaluates to `false`, you can access
  the \f$x\f$-monotone curve associated with \f$e\f$. Otherwise,
  \f$e\f$ is not associated with an \link
  Arrangement_on_surface_2::X_monotone_curve_2 `X_monotone_curve_2`\endlink
  object.

<LI>The nested \link Arrangement_on_surface_2::Face `Face`\endlink
  type provides the Boolean predicate \link
  Arrangement_on_surface_2::Face::is_fictitious()
  `is_fictitious()`\endlink. The call \link
  Arrangement_on_surface_2::Face::is_fictitious()
  `f->is_fictitious()`\endlink evaluates to `true` only when \f$f\f$
  lies outside the bounding rectangle. The method \link
  Arrangement_on_surface_2::Face::outer_ccb() `outer_ccb()`\endlink
  (see Section \ref arr_sssectr_face must not be invoked for the
  fictitious face.  \cgalFootnote{Typically, the code is guarded
  against such malicious calls with adequate preconditions. However,
  these preconditions are suppressed when the code is compiled with
  maximum optimization.}  Note that a valid unbounded face (of an
  arrangement that supports unbounded curves) has a valid outer CCB,
  although the CCB comprises only fictitious halfedges if the
  arrangement is induced only by bounded curves.

</UL>

Let \f$p_l = (x_l,y_l)\f$ and \f$p_r = (x_r,y_r)\f$ be the left and
right endpoints of a bounded \f$x\f$-monotone curve \f$c\f$,
respectively. We say that a point \f$p = (x_p,y_p)\f$ lies in the
\f$x\f$-range of \f$c\f$ if \f$x_l \leq x_p \leq x_r\f$. Let \f$p_l =
(x_l,y_l)\f$ be the left endpoint of an \f$x\f$-monotone curve \f$c\f$
unbounded from the right. A point \f$p = (x_p,y_p)\f$ lies in the
\f$x\f$-range of \f$c\f$ if \f$x_l \leq x_p\f$. Similarly, A point
\f$p = (x_p,y_p)\f$ lies in the \f$x\f$-range of an \f$x\f$-monotone
curve unbounded from the left if \f$x_p \leq x_r\f$. Naturally, every
point \f$p \in \mathbb{R}^2\f$ is in the \f$x\f$-range of an
\f$x\f$-monotone curve unbounded from the left and from the right.

\cgalAdvancedBegin

The function template `is_in_x_range()` listed below, and defined in
the file `is_in_x_range.h`, checks whether a given point \f$p\f$ is in
the \f$x\f$-range of the curve associated with a given halfedge
\f$e\f$. The function template also exemplifies how some of the above
functions can be used. The traits functor \link
AosBasicTraits_2::Compare_x_2 `Compare_x_2`\endlink used in
the code is described in Section \ref
aos_sssec-geom_traits-concepts_basic.

\code
// Check whether the given point is in the x-range of the curve associated
// with the given halfedge.
template <typename Arrangement>
bool is_in_x_range(typename Arrangement::Halfedge_const_handle he,
                   const typename Arrangement::Point_2& p,
                   const typename Arrangement::Traits_2& traits)
{
  auto cmp = traits.compare_x_2_object();

  // Compare p with the source vertex (which may lie at x = +/- oo).
  CGAL::Arr_parameter_space src_px = e->source()->parameter_space_in_x();
  CGAL::Comparison_result res_s =
    (src_px == CGAL::ARR_LEFT_BOUNDARY) ? CGAL::SMALLER :
    ((src_px == CGAL::ARR_RIGHT_BOUNDARY) ? CGAL::LARGER :
     cmp(e->source()->point(), p));
  if (res_s == CGAL::EQUAL) return true;

  // Compare p with the target vertex (which may lie at x = +/- oo).
  CGAL::Arr_parameter_space trg_px = e->target()->parameter_space_in_x();
  CGAL::Comparison_result  res_t =
    (trg_px == CGAL::ARR_LEFT_BOUNDARY) ? CGAL::SMALLER :
    ((trg_px == CGAL::ARR_RIGHT_BOUNDARY) ? CGAL::LARGER :
     cmp(e->target()->point(), p));

  // p lies in the x-range of the halfedge iff its source and target lie
  // at opposite x-positions.
  return (res_s != res_t);
}
\endcode

\cgalAdvancedEnd

It is important to observe that the call \link
Arrangement_on_surface_2::number_of_vertices()
`arr.number_of_vertices()`\endlink does not count the vertices at
infinity in the arrangement `arr`. To find out this number you need to
issue the call \link
Arrangement_on_surface_2::number_of_vertices_at_infinity()
`arr.number_of_vertices_at_infinity()`\endlink. Similarly, \link
Arrangement_on_surface_2::number_of_edges()
`arr.number_of_edges()`\endlink does not count the fictitious edges
(whose number is always \link
Arrangement_on_surface_2::number_of_vertices_at_infinity()
`arr.number_of_vertices_at_infinity()`\endlink + 4) and \link
Arrangement_on_surface_2::number_of_faces()
`arr.number_of_faces()`\endlink does not count the fictitious
faces. The vertex, halfedge, edge, and face iterators defined by the
`Arrangement_2` class template only go over true features of the
arrangement; namely, vertices at infinity and fictitious halfedges and
fictitious faces are skipped. On the other hand, the
`Ccb_halfedge_circulator` of the outer boundary of an unbounded face
or the `Halfedge_around_vertex_circulator` of a vertex at infinity do
traverse fictitious halfedges. While an arrangement induced by bounded
curves has a single unbounded face, an arrangement induced by
unbounded curves may have several unbounded faces. The call \link
Arrangement_on_surface_2::number_of_unbounded_faces()
`arr.number_of_unbounded_faces()`\endlink returns the number of
unbounded arrangement faces (Thus, \link
Arrangement_on_surface_2::number_of_faces()
`arr.number_of_faces()`\endlink - \link
Arrangement_on_surface_2::number_of_unbounded_faces()
`arr.number_of_unbounded_faces()`\endlink is the number of bounded
faces). The calls \link
Arrangement_on_surface_2::unbounded_faces_begin()
`arr.unbounded_faces_begin()`\endlink and \link
Arrangement_on_surface_2::unbounded_faces_end()
`arr.unbounded_faces_end()`\endlink return iterators of the type
`Arrangement_on_surface_2::Unbounded_face_iterator` (or its
non-mutable, `const`, counterpart type) that define the range of the
arrangement unbounded faces. Naturally, the value-type of this
iterator is \link Arrangement_on_surface_2::Face `Face`\endlink.

There is no way to directly obtain the fictitious vertices that
represent the four corners of the imaginary bounding
rectangle. However, you can obtain the fictitious face through the
call \link Arrangement_on_surface_2::fictitious_face()
`arr.fictitious_face()`\endlink, and then iterate over the boundary of
its single hole, which represents the imaginary bounding
rectangle. Recall that an arrangement of bounded curves does not have
a fictitious face. In this case the call above returns a null handle.

The example below exhibits the difference between an arrangement
induced by bounded curves, which has a single unbounded face, and an
arrangement induced by unbounded curves, which may have several
unbounded faces. It also demonstrates the usage of the insertion
function for pairwise interior-disjoint unbounded curves. In this case
we use an instance of the traits class-template
`Arr_linear_traits_2<Kernel>` to substitute the `Traits` parameter of
the `Arrangement_2<Traits,Dcel>` class template when instantiated.
This traits class-template is capable of representing line segments as
well as unbounded linear curves, namely, lines and rays. Observe that
objects of the \link Arr_linear_traits_2::X_monotone_curve_2
`X_monotone_curve_2`\endlink type nested in this traits class-template
are constructible from objects of types \link
Arr_linear_traits_2<Kernel>::Line_2 `Line_2`\endlink, \link
Arr_linear_traits_2<Kernel>::Ray_2 `Ray_2`\endlink, and \link
Arr_linear_traits_2<Kernel>::Segment_2 `Segment_2`\endlink also nested
in the traits class-template. These three types and the \link
Arr_linear_traits_2<Kernel>::Point_2 `Point_2`\endlink type are
defined by the traits class-template `Arr_linear_traits_2<Kernel>` to
be the corresponding types of the kernel used to instantiate the
traits class-template; see Paragraph \ref arr_sssectr_linear.


\cgalFigureBegin{aos_fig-unbounded_non_intersecting,unbounded_non_intersecting.png}
An arrangement of unbounded linear objects, as constructed in
\ref Arrangement_on_surface_2/unbounded_non_intersecting.cpp.
 \cgalFigureEnd
 

The first three curves, \f$c_1\f$, \f$c_2\f$, and \f$c_3\f$, are
inserted using the specialized insertion functions for
\f$x\f$-monotone curves whose location in the arrangement is
known. Notice that inserting an unbounded curve in the interior of an
unbounded face, or from an existing vertex that represents an bounded
end of the curve, may cause an unbounded face to split. (This is never
the case when inserting a bounded curve---compare with Section \ref
arr_sssecmf_insert_cv.) Three additional rays are then inserted
incrementally using the insertion function for \f$x\f$-monotone curves,
the interior of which is disjoint from all arrangement features; see
the illustration in
\cgalFigureRef{aos_fig-unbounded_non_intersecting}). Finally, the
program prints the size of the arrangement using the function template
`print_unbounded_arrangement_size()` defined in the header file
`arr_print.h`. (Its listing is omitted here.) The program also
traverses the outer boundaries of its six unbounded faces and prints
the curves along these boundaries. The header file `arr_linear.h`,
which contains the definitions used by the example program, is listed
immediately after the listing of the main function.

\cgalExample{Arrangement_on_surface_2/unbounded_non_intersecting.cpp}

The type definitions used by the example below, as well as by other
examples that use the `Arr_linear_traits_2` class template, are listed
next.  These types are defined in the header file `arr_linear.h`.

\code
#include <CGAL/Exact_predicates_exact_constructions_kernel.h>
#include <CGAL/Arr_linear_traits_2.h>
#include <CGAL/Arrangement_2.h>

using Kernel = CGAL::Exact_predicates_exact_constructions_kernel;
using Number_type = Kernel::FT;

using Traits = CGAL::Arr_linear_traits_2<Kernel>;
using Point = Traits::Point_2;
using Segment = Traits::Segment_2;
using Ray = Traits::Ray_2;
using Line = Traits::Line_2;
using X_monotone_curve = Traits::X_monotone_curve_2;

using Arrangement = CGAL::Arrangement_2<Traits>;
using Vertex_handle = Arrangement::Vertex_handle;
using Halfedge_handle = Arrangement::Halfedge_handle;
using Face_handle = Arrangement::Face_handle;
\endcode


\subsubsection arr_sssec-unb_global Free Functions


All the free functions that operate on arrangements of bounded curves
(see Section \ref arr_secgl_funcs) can also be applied to arrangements
of unbounded curves. For example, consider a container of linear
curves that has to be inserted into an arrangement object, the type of
which is an instance of the `Arrangement_2<Traits,Dcel>` class
template, where the `Traits` parameter is substituted by the traits
class that handles linear curves; see Section \ref
arr_sssectr_linear. You can do it incrementally; namely, insert the
curves one by one as follows:
\code
  for (auto it = curves.begin(); it != curves.end(); ++it) insert(arr, *it);
\endcode
Alternatively, the curves can be inserted aggregately using a single
call as follows:
\code
  insert(arr, curves.begin(), curves.end());
\endcode
It is also possible to issue point-location queries and vertical
ray-shooting queries (see also Section \ref arr_secqueries) on
arrangements of lines, where the only restriction is that the query
point has finite coordinates. Note that all the point-location
strategies mentioned above, except the trapezoidal map strategy, are
capable of handling arrangements of unbounded curves.


\subsection arr_ssec-unb_duality Point-Line Duality


In the following example we show how an arrangement of unbounded lines
is utilized to solve the following problem: Given a set of points,
does the set contain at least three collinear points? In this example
a set of input points is read from a file. The file `points.dat` is
used by default. It contains definitions of \f$100\f$ points randomly
selected on the grid \f$[-10000,10000]\times[-10000,10000]\f$. We
construct an arrangement of the dual lines, where the line \f$p^{*}\f$
dual to the point \f$p = (x_p, y_p)\f$ is given by the equation \f$y =
x_p*x - y_p\f$, and check whether three (or more) of the dual lines
intersect at a common point, by searching for a (dual) vertex, whose
degree is greater than \f$4\f$. If such a vertex exists, then there
are at least three dual lines that intersect at a common point, which
implies that there are at least three collinear points.

\cgalExample{Arrangement_on_surface_2/dual_lines.cpp}

Note that there are no three collinear points among the points defined
in the input file `points.dat`. In the second part of the example the
existence of a collinear triple is forced and verified as follows. A
line dual to the midpoint of two randomly selected points is
introduced, and inserted into the arrangement. This operation is
followed by a test that verifies that a vertex of degree greater than
\f$4\f$ exists.


\section aos_sec-curved_surfaces Arrangements on Curved Surfaces


We are given a surface \f$S\f$ in \f$\mathbb{R}^3\f$ and a set
\f$\mathcal{C}\f$ of curves embedded in this surface. The curves
subdivide \f$S\f$ into cells of dimension 0 (<em>vertices</em>), 1
(<em>edges</em>), and 2 (<em>faces</em>). This subdivision is the
<em>arrangement</em> \f$\mathcal{A}(\mathcal{C})\f$ induced by
\f$\mathcal{C}\f$ on \f$S\f$. Arrangements embedded in curved surfaces
in \f$\mathbb{R}^3\f$ are generalizations of arrangements embedded in
the plane. In this section we explain how to construct, maintain, and
manipulate two-dimensional arrangements embedded in orientable
parametric surfaces in three dimensions, such as planes, cylinders,
spheres, and tori, and surfaces homeomorphic to them; see
\cgalFigureRef{aos_fig-surfaces}. Such arrangements have many
theoretical and practical applications; see, e.g.,
\cgalCite{as-aa-00}, \cgalCite{cgal:bfhks-apsca-10},
\cgalCite{cgal:bfhmw-apsgf-10}, \cgalCite{cgal:fhktww-a-07}, and
\cgalCite{cgal:h-a-04}.

\cgalFigureAnchor{aos_fig-surfaces}
<center>
<table border=0>
<tr>
<td>\image html sphere.png</td>
<td>\image html cylinder.png</td>
<td>\image html cone.png</td>
<td>\image html ellipsoid.png</td>
<td>\image html torus.png</td>
<td>\image html paraboloid.png</td>
<tr align="center">
<td>(a) Sphere</td>
<td>(b) Cylinder</td>
<td>(c) Cone</td>
<td>(d) Ellipsoid</td>
<td>(e) Torus</td>
<td>(f) Paraboloid</td>
</tr>
</table>
</center>
\cgalFigureCaptionBegin{aos_fig-surfaces}
Various two-dimensional parametric surfaces, arrangements on which
are supported by the framework.
\cgalFigureCaptionEnd


\subsection aos_ssec-curved_surfaces-parametric Parametric Surfaces


We use \f$\overline{\mathbb{R}}\f$ to denote the compactified real line
\f$\mathbb{R} \cup \{-\infty,+\infty\}\f$. The mapping
\f$x \mapsto x/(1 - x^2)\f$ is a homeomorphism between
\f$(-1,+1)\f$ and \f$\mathbb{R}\f$ and between \f$[-1,+1]\f$ and
\f$\overline{\mathbb{R}}\f$. So you may also think of finite intervals
instead of the (compactified) real line in what follows.

A parametric surface \f$S\f$ is given by a continuous function
\f$\phi_S: \Phi \rightarrow \mathbb{R}^3\f$, where the domain \f$\Phi
= X \times Y\f$ is a rectangular two-dimensional parameter space and
\f$S = \phi_S(\Phi)\f$. The sets \f$X\f$ and \f$Y\f$ are open,
half-open, or closed intervals with endpoints in
\f$\overline{\mathbb{R}}\f$. We use \f$x_{\rm min}\f$, \f$x_{\rm
max}\f$, \f$y_{\rm min}\f$, and \f$y_{\rm max}\f$ to denote the
endpoints of \f$X\f$ and \f$Y\f$, respectively.

<ul>

<li>The left side of the boundary of \f$\Phi\f$ consists of the points
\f$(x_{\rm min},y)\f$ with \f$y \in {\rm closure}(Y)\f$. It is
<em>open</em>, if \f$x_{\rm min} \not\in X\f$ or \f$y\not\in Y\f$, and
<em>closed</em>, otherwise. The right side is defined analogously.
The bottom side consists of the points \f$(x, y_{\rm min})\f$ with
\f$x \notin (x_{\rm min},x_{\rm max})\f$; the top side is defined
analogously. The bottom or top sides can also be open. Note that the
"corners" of the parameter space belong to the vertical sides; this
asymmetry corresponds to the fact that we sweep \f$x\f$-monotone
curves, and not \f$y\f$-monotone curves. The four sides together form
the boundary \f$\partial \Phi\f$.</li>

<li>A point \f$p \in S\f$ is <em>regular</em> if it has only one
pre-image under \f$\Phi\f$. All pre-images of a non-regular point lie
in the boundary of \f$\Phi\f$. In particular, \f$\phi_S\f$ is
bijective on \f$(x_{\rm min},x_{\rm max})\times(y_{\rm min},y_{\rm
max})\f$.  More precisely, a non-regular point has either exactly two
pre-images that lie on opposite sides of the domain, or all points of
exactly one side of the domain.</li>

</ul>

A side of the domain is contracted if \f$\phi_S\f$ is constant on it.
The image of the side is called a <em>contraction point</em>.

The bottom and top sides of the domain (similarly for the left and
right sides) are <em>identified</em> if
\f$\phi_S(x,y_{\rm min}) = \phi_S(x, y_{\rm max})\f$ for all
\f$x \in X \f$. The curve \f$x \mapsto \phi_S(x,y_{\rm min})\f$ is
called an <em>identification curve</em>.

Rectangles, strips, quadrants, halfplanes, and planes can be modeled
with \f$\phi_S\f$ being the identity mapping. For example,
\f$\Phi_S(x, y) = (x, y, 0)\f$ with \f$X = Y =(-\infty, +\infty)\f$
parameterizes a plane. Surfaces such as paraboloids can be
modeled through continuous and bijective parameterizations, for
example, \f$\phi_S(x,y) = (x,y,x^2 + y^2)\f$, where
\f$U = V =(-\infty, +\infty)\f$, defines a paraboloid of revolution.
Cylinders, tori, spheres, and surfaces homeomorphic to them, require
more general parameterizations. For example, the unit sphere is
commonly parameterized as
\f$\phi_S(x, y) = (\cos x \cos y, \sin x \cos y, \sin y)\f$, where
\f$\Phi = [-\pi, \pi] \times [-\frac{\pi}{2}, \frac{\pi}{2}]\f$. With
respect to this parameterization, the north and the south pole and
all points on the opposite Prime (Greenwich) Meridian are
non-regular. The north pole \f$(0,0,1)\f$ has infinitely many
pre-images \f$(x, \pi/2)\f$ with \f$-\pi < x < \pi\f$ and so does the
south pole \f$(0,0,-1)\f$. The points on the opposite Prime Meridian
have two pre-images each, namely \f$(-\pi,y)\f$ and \f$(\pi,y)\f$
with \f$-\pi/2 \leq y \leq \pi/2\f$. We say that the top and bottom
side of the domain are <em>contracted</em> and the left and right sides
are <em>identified</em>. These are exactly the kinds of non-injectivity
that we allow.

We give more examples. A <em>triangle</em> with corners
\f$(a_1, b_1), (a_2, b_2)\f$, and \f$(a_3, b_3)\f$ can be
parameterized via \f$\Phi = [0,1] \times [0,1]\f$ with
\f$\phi_S(x,y) = (a_1 + x(a_2 - a_1) + xy(a_3-a_2), b_1 +
x(b_2 - b_1) + xy(b_3-b_2), 0)\f$. The left side of the rectangular
domain contracts to a point. An open or closed <em>cylinder</em> is
modeled by identifying the vertical sides and having \f$Y\f$ open or
closed, respectively. A <em>torus</em> is modeled by identifying the
vertical sides and the horizontal sides. A <em>paraboloid</em> or
<em>half-cone</em> may be modeled by identifying the vertical sides
and contracting one of the horizontal sides to a point. More elegantly,
they are modeled by a bijective parameterization as given above. A
<em>sphere</em> is modeled by identifying the vertical sides and
contracting both horizontal sides. A <em>croissant</em>, a torus with
one pinch point, is modeled by identifying the vertical and
identifying the horizontal sides and, in addition, contracting one of
the pairs. However, the croissant is excluded by our definitions. All
surfaces supported by our framework are locally homeomorphic to a
disk, and hence an \dcel data-structure suffices for representing
arrangements on these surfaces. The croissant is, at the pinch point,
not locally homeomorphic to a disk, and hence a more general
cell-tuple data structure than an \dcel would be needed.

A curve \f$\gamma\f$ is a continuous function \f$\gamma: I \rightarrow
\Phi\f$, where \f$I\f$ is an open, half-open, or closed interval with
endpoints 0 and 1, and \f$\gamma\f$ is injective except at a finite
number of points. If \f$0 \not\in I\f$, the limit \f$\lim_{t
\rightarrow 0+} \gamma(t)\f$ exists (in the closure of \f$\Phi\f$) and
lies in an open side of the boundary. Similarly, if \f$1 \not\in I\f$,
then \f$\lim_{t \rightarrow 1-} \gamma(t)\f$ exists and lies in an
open side of the boundary. A curve \f$c\f$ in \f$S\f$ is the image of
a curve \f$\gamma\f$ in the domain.

A curve is <em>closed in the domain</em> if \f$\gamma(0) =
\gamma(1)\f$; in particular, \f$0 \in I\f$ and \f$1 \in I\f$. A curve
is <em>closed in the surface \f$S\f$ (or simply closed)</em> if
\f$\phi_S(\gamma(0)) = \phi_S(\gamma(1))\f$. A curve \f$\gamma\f$ has
two <em>ends</em>, the 0-end \f$\langle \gamma,0 \rangle\f$ and the
1-end \f$\langle \gamma,1 \rangle\f$. If \f$d \in I\f$, the
\f$d\f$-end has a geometric interpretation. It is a point in
\f$\Phi\f$. If \f$d \not\in I\f$, the \f$d\f$-end has no geometric
interpretation. You may think of it as a point on an open side of the
domain or an initial or terminal segment of \f$\gamma\f$. If \f$d
\not\in I\f$, we say that the \f$d\f$-end of the curve is open. The
equator curve on the sphere in standard parameterization is given by
\f$\gamma(t) = (\pi(2t - 1),0)\f$ for \f$t \in [0,1]\f$. The
\f$0\f$-end of \f$\gamma\f$ is the point \f$(-\pi,0)\f$ in \f$\Phi\f$
and a point on the equator of the sphere. It is closed on the sphere,
but not closed in \f$\Phi\f$. The diagonal \f$(u,u)\f$ in the plane
is, for example, given by \f$\gamma(t) = (x(t),y(t))\f$ and \f$x(t) =
y(t) = (t - 1/2)/(t(1-t))\f$.  Both ends of this curve are open. The
\f$d\f$-end of a curve \f$\gamma\f$ is incident to the left side if
either \f$d \in I\f$ and \f$\gamma(d)\f$ lies on the left side or \f$d
\not\in I\f$ and \f$\lim_{t \rightarrow d} \gamma(t)\f$ lies on the
left side, which is then an open side. Similarly for the other sides.

A <em>strongly \f$x\f$-monotone curve</em> is the image of a curve
\f$\gamma\f$, such that if \f$t_1 < t_2\f$ for \f$t_1, t_2 \in I\f$,
then \f$x(t_1) < x(t_2)\f$. A <em>vertical curve</em> is the image of
a curve \f$\gamma\f$, such that \f$x(t) = C\f$ for all \f$t \in I\f$
and some \f$C \in X\f$ and \f$y(t_1) < y(t_2)\f$ for \f$t_1 <
t_2\f$. For instance, every Meridian curve of a sphere parameterized
as above is vertical. An <em>\f$x\f$-monotone curve</em> is either
vertical or strongly \f$x\f$-monotone.


\subsection aos_ssec-curved_surfaces-aos_class The Arrangement on Surface Class Template


The class template `Arrangement_on_surface_2<GeomTraits, TopolTraits>`
can be used to represent a 2D arrangement embedded in a 3D
surface. The template is parameterized by template parameters
<em>geometry traits</em> and <em>topology traits</em>. The
topology-traits type deals with the topology of the parametric
surface; see Section \ref aos_sec-topol_traits. As explained in the
previous section, a parametric surface \f$S = \phi_S(\Phi)\f$ is given
by a continuous function \f$\phi_S: \Phi \rightarrow \mathbb{R}^3\f$,
where the domain \f$\Phi = X \times Y\f$ is a rectangular
two-dimensional parameter space. \f$X\f$ and \f$Y\f$ are open,
half-open, or closed intervals with endpoints in
\f$\overline{\mathbb{R}}\f$.

The geometry-traits type introduces the type names of the basic
geometric objects (i.e., point, curve, and \f$x\f$-monotone curve)
and the set of operations on objects of these types required to
construct and maintain the arrangement and to operate on it. The
traits-concept hierarchy described in Section \ref aos_sec-geom_traits
accurately defines the requirements imposed on a model of a geometry
traits class. Recall that requirements apply to the parameter space
\f$\Phi = X \times Y\f$; thus, they are defined in terms of \f$x\f$
and \f$y\f$ coordinates.  Most requirements apply to all type of
arrangements regardless of the embedding surface. However, several
refined concepts apply only to arrangements on surfaces that are not
in the plane, that is, modeled with \f$\phi_S\f$ not being the
identity mapping. They differ according to the type of the side
boundaries of the parameter space being open, closed, contracted, or
identified.

At this point only one type of arrangements on non planar surfaces is
supported, namely, arrangements embedded in the sphere and induced by
arcs of great circles, also known as geodesic arcs.
\cgalFigureRef{aos_fig-voronoi} shows various Voronoi diagrams the
bisectors of which are geodesic arcs.  They are represented as
arrangements induced by geodesic arcs embedded in the sphere.

\cgalFigureAnchor{aos_fig-voronoi}
<center>
<table border=0>
<tr>
<td>\image html voronoi.jpg</td>
<td>\image html degenerate_voronoi.jpg</td>
<td>\image html power_diagram.jpg</td>
<td>\image html degenerate_power_diagram.jpg</td>
<tr align="center">
<td>(a)</td>
<td>(b)</td>
<td>(c)</td>
<td>(d)</td>
</tr>
</table>
</center>
\cgalFigureCaptionBegin{aos_fig-voronoi}
Voronoi diagrams on the sphere.
All diagram edges are geodesic arcs.
Sites are drawn in red and Voronoi edges are drawn in blue.
(a) The Voronoi diagram of 32 random points.
(b) A highly degenerate case of Voronoi diagram of 30 point sites on the sphere.
(c) The power diagram of 10 random circles.
(d) A degenerate power diagram of 14 sites on the sphere.
\cgalFigureCaptionEnd


\subsection aos_ssec-curved_surfaces-basic Basic Manipulation and Traversal Methods


The types \link Arrangement_on_surface_2::Vertex `Vertex`\endlink,
\link Arrangement_on_surface_2::Halfedge `Halfedge`\endlink, and \link
Arrangement_on_surface_2::Face `Face`\endlink nested in the
`Arrangement_on_surface_2` class template support the methods listed
in Section \ref arr_ssectraverse and in Section \ref
arr_sssecunb_basic.  Additional methods supported by these types are
described next. Let \f$v\f$, \f$e\f$, and \f$f\f$ be handles to a
vertex of type \link Arrangement_on_surface_2::Vertex
`Vertex`\endlink, a halfedge of type \link
Arrangement_on_surface_2::Halfedge `Halfedge`\endlink, and a face of
type \link Arrangement_on_surface_2::Face `Face`\endlink,
respectively.

<UL>

<LI>The calls \link
  Arrangement_on_surface_2::Vertex::parameter_space_in_x()
  `v->parameter_space_in_x()`\endlink and \link
  Arrangement_on_surface_2::Vertex::parameter_space_in_y()
  `v->parameter_space_in_y()`\endlink determine the location of the
  geometric embedding of the vertex \f$v\f$. The call \link
  Arrangement_on_surface_2::Vertex::parameter_space_in_x()
  `v->parameter_space_in_x()`\endlink returns `ARR_INTERIOR` if the
  geometric embedding of \f$v\f$ is a point \f$p\f$ the pre-image of
  which does not lie on the left nor on the right sides of the
  boundary of the parameter space. If the left and right sides are not
  identified, then `ARR_LEFT_BOUNDARY` or `ARR_RIGHT_BOUNDARY` are
  returned if the pre-image of \f$p\f$ lies on the left or the right
  side, respectively.  If the left and right sides are identified, the
  return value is unspecified and can be either
  `ARR_LEFT_BOUNDARY` or `ARR_RIGHT_BOUNDARY`. Similarly, the call
  \link Arrangement_on_surface_2::Vertex::parameter_space_in_y()
  `v->parameter_space_in_y()`\endlink returns `ARR_INTERIOR` if the
  geometric embedding of \f$v\f$ is a point \f$q\f$, the pre-image of
  which does not lie on the bottom nor on the top sides of the
  boundary of the parameter space. If the bottom and top sides are not
  identified, then `ARR_BOTTOM_BOUNDARY` or `ARR_TOP_BOUNDARY` are
  returned if the pre-image of \f$q\f$ lies on the bottom or the top
  side, respectively.  If the bottom and top sides are identified, the
  return value is unspecified.

  If you want to determine whether the pre-image of a point \f$p\f$
  lies on identified sides, you need to employ one of the two traits
  functors \link
  AosIdentifiedHorizontalTraits_2::Is_on_x_identification_2
  `Is_on_x_identification_2`\endlink or \link
  AosIdentifiedVerticalTraits_2::Is_on_y_identification_2
  `Is_on_y_identification_2`\endlink; see Section \ref
  aos_ssec-traits-curved. If the pre-image of an \f$x\f$-monotone
  curve \f$c\f$ does not entirely lie on identified sides, you can
  determine the location of the pre-image of an endpoint of \f$c\f$
  employing either the \link
  AosVerticalSideTraits_2::Parameter_space_in_x_2
  `Parameter_space_in_x_2`\endlink functor or the \link
  AosHorizontalSideTraits_2::Parameter_space_in_y_2
  `Parameter_space_in_y_2`\endlink functors; see Section \ref
  aos_ssec-traits-curved. The operations in both functors accept an
  enumeration that indicates the curve end, that is,
  `CGAL::ARR_MIN_END` or `CGAL::ARR_MAX_END`, in addition to the curve
  itself.

<LI>A face in a planar arrangement has at most one outer CCB. However,
  an arrangement embedded on a surface may present additional
  scenarios. For example, a face of an arrangement embedded on a torus
  may have two outer CCBs, and a face of an arrangement embedded on a
  sphere might be consider a hole inside the surrounding face or vice
  versa. To this end, outer CCBs and inner CCBs of faces of
  arrangements embedded on surfaces are symmetrically treated (while
  maintaining the invariant that a face always lies to the left of
  every halfedge of every CCB of the face regardless of whether the
  CCB is inner or outer). The classification of a CCB as inner or
  outer becomes an implementation detail.  The calls \link
  Arrangement_on_surface_2::Face::outer_ccbs_begin()
  `f->outer_ccbs_begin()`\endlink and \link
  Arrangement_on_surface_2::Face::outer_ccbs_end()
  `f->outer_ccbs_end()`\endlink return iterators of type \link
  Arrangement_on_surface_2::Face::Outer_ccb_iterator
  `Outer_ccb_iterator`\endlink that define a range of outer CCBs
  inside the face \f$f\f$. Similarly, the methods \link
  Arrangement_on_surface_2::Face::inner_ccbs_begin()
  `f->inner_ccbs_begin()`\endlink and \link
  Arrangement_on_surface_2::Face::inner_ccbs_end()
  `f->inner_ccbs_end()`\endlink return iterators of type \link
  Arrangement_on_surface_2::Face::Inner_ccb_iterator
  `Inner_ccb_iterator`\endlink that define a range of inner CCBs
  inside the face \f$f\f$. (The latter pair of member functions and
  the iterator type are equivalent to the methods \link
  Arrangement_on_surface_2::Face::holes_begin()
  `holes_begin()`\endlink, \link
  Arrangement_on_surface_2::Face::holes_end() `holes_end()`\endlink,
  and \link Arrangement_on_surface_2::Face::Hole_iterator
  `Hole_iterator`\endlink; see Section \ref arr_sssectr_face.) The
  calls \link Arrangement_on_surface_2::Face::number_of_outer_ccbs()
  `f->number_of_outer_ccbs()`\endlink and \link
  Arrangement_on_surface_2::Face::number_of_inner_ccbs()
  `f->number_of_inner_ccbs()`\endlink return the number of outer CCBs
  and the number of inner CCBs in \f$f\f$, respectively.

</UL>

\cgalAdvancedBegin

The function template `is_in_x_range()` listed below, and defined in
the file `spherical_is_in_x_range.h` checks whether a given point
\f$p\f$, in the interior of the parameter space, is in the
\f$x\f$-range of an \f$x\f$-monotone curve \f$c\f$ that represents a
great-circle arc. It assumes that the left and right sides of the
parameter space are identified and the bottom and top sides are
contracted, which is the settings used by the traits class template
`Arr_geodesic_arc_on_sphere_traits_2<Kernel,X,Y>`; see Section \ref
arr_ssectr_spherical. The traits functors \link
AosBasicTraits_2::Construct_min_vertex_2
`Construct_min_vertex_2`\endlink, \link
AosBasicTraits_2::Construct_max_vertex_2
`Construct_min_vertex_2`\endlink, and \link
AosBasicTraits_2::Compare_x_2 `Compare_x_2`\endlink used in
the code are described is Section \ref
aos_sssec-geom_traits-concepts_basic.  The traits functors \link
AosVerticalSideTraits_2::Parameter_space_in_x_2
`Parameter_space_in_x_2`\endlink, \link
AosHorizontalSideTraits_2::Parameter_space_in_y_2
`Parameter_space_in_y_2`\endlink, \link
AosIdentifiedVerticalTraits_2::Is_on_y_identification_2
`Is_on_y_identification_2`\endlink, and \link
AosHorizontalSideTraits_2::Compare_x_on_boundary_2
`Compare_x_on_boundary_2`\endlink, are described is Section \ref
aos_ssec-traits-curved.

\code
template <typename GeometryTraits>
bool is_in_x_range(const typename GeometryTraits::X_monotone_curve_2& c,
                   const typename GeometryTraits::Point_2& p,
                   const GeometryTraits& traits) {
  CGAL_assertion(! traits.is_on_y_identification_2_object()(p));

  if (traits.is_on_y_identification_2_object()(c)) return false;

  // Note that a great-circle arc that is incident to a pole is vertical.
  auto cmp_x_boundary = traits.compare_x_on_boundary_2_object();
  auto psy = traits.parameter_space_in_y_2_object();
  auto psy_min = psy(c, CGAL::ARR_MIN_END);
  if (psy_min == CGAL::ARR_BOTTOM_BOUNDARY)
    return cmp_x_boundary(p, c, CGAL::ARR_MIN_END) == CGAL::EQUAL;
  auto psy_max = psy(c, CGAL::ARR_MAX_END);
  if (psy_max == CGAL::ARR_TOP_BOUNDARY)
    return cmp_x_boundary(p, c, CGAL::ARR_MAX_END) == CGAL::EQUAL;
  auto psx = traits.parameter_space_in_x_2_object();
  auto psx_min = psx(c, CGAL::ARR_MIN_END);
  auto psx_max = psx(c, CGAL::ARR_MAX_END);
  if ((psx_min == CGAL::ARR_LEFT_BOUNDARY) &&
      (psx_min == CGAL::ARR_RIGHT_BOUNDARY))
    return true;
  auto cmp_x = traits.compare_x_2_object();
  if (psx_min == CGAL::ARR_LEFT_BOUNDARY) {
    const auto& p_right = traits.construct_max_vertex_2_object()(c);
    auto res = cmp_x(p, p_right);
    return ((res == CGAL::SMALLER) || (res == CGAL::EQUAL));
  }
  if (psx_max == CGAL::ARR_RIGHT_BOUNDARY) {
    const auto& p_left = traits.construct_min_vertex_2_object()(c);
    auto res = cmp_x(p_left, p);
    return ((res == CGAL::SMALLER) || (res == CGAL::EQUAL));
  }
  const auto& p_left = traits.construct_min_vertex_2_object()(c);
  auto res = cmp_x(p_left, p);
  if (res == CGAL::LARGER) return false;
  const auto& p_right = traits.construct_max_vertex_2_object()(c);
  res = cmp_x(p, p_right);
  if (res == CGAL::LARGER) return false;
  return true;
}
\endcode

\cgalAdvancedEnd


\section aos_sec-geom_traits The Geometry Traits


A geometry traits class encapsulates the definitions of the geometric
entities and the implementation of the geometric predicates and
constructions that handle these geometric entities, used by the
`Arrangement_on_surface_2` class template and by the peripheral
modules. The identified minimal requirements imposed by the various
algorithms that apply to arrangements are organized in a hierarchy of
refined geometry-traits concepts.  The requirements listed by each
concept include only the utterly essential types and operations needed
to implement specific algorithms. This modular structuring yields
controllable parts that can be produced, maintained, and utilized with
less effort. For each operation, all the preconditions that its
operands must satisfy are specified as well, as these may simplify the
implementation of models of these concepts even further. Each traits
class models one or more concepts. This section contains a detailed
description of the concepts in the refinement hierarchy and the
various traits classes that model these concepts.

All the algebra required for constructing and manipulating
arrangements is concentrated in the traits classes. The knowledge
required to devise a good traits class is very different from the
knowledge required for the development of the rest of the package or
for using the package. It has less to do with computational geometry
and it involves mainly algebra and numerical computation. This way,
traits classes for new types of curves can be developed with little
knowledge of algorithms and data structures in computational
geometry. In this section we discuss how to use existing traits
classes, but we also explain the concepts these traits classes
model---a starting point for every novice developer of such classes.

This section is divided into three parts. The first part describes the
refinement hierarchy of the arrangement geometry-traits concepts. The
second part reviews various models of these concepts. These traits
classes handle different curve families, such as line segments,
polylines, conic arcs, B&eacute;zier curves, algebraic curves, and
geodesic arcs on the sphere. The last part introduces decorators for
geometric traits classes. A decorator of a traits class attaches
auxiliary data to the geometric objects handled by the original traits
class, thereby extending it.


\subsection aos_ssec-geom_traits-concepts The Hierarchy of the Geometry Traits Concepts


A hierarchy of related concepts can be viewed as a directed acyclic
graph, where a node of the graph represents a concept and an arc
represents a refinement relation. An arc directed from concept <span
class="textsc">A</span> to concept <span class="textsc">B</span>
indicates that concept <span class="textsc">B</span> refines concept
<span class="textsc">A</span>.  A rather large directed acyclic graph
is required to capture the entire hierarchy of the geometry
traits-class concepts. In the following sections we review individual
clusters of the graph and describe the relations between them.
\cgalFigureRef{aos_fig-central_concept_cluster} depicts the central
cluster.


\cgalFigureBegin{aos_fig-central_concept_cluster,central_concept_cluster.png}
The hierarchy of the main geometry traits concepts.
\cgalFigureEnd



\subsubsection aos_sssec-geom_traits-concepts_basic The Basic Concept


A model of the basic concept `AosBasicTraits_2` needs to
define the types \link AosBasicTraits_2::Point_2
`Point_2`\endlink and \link
AosBasicTraits_2::X_monotone_curve_2
`X_monotone_curve_2`\endlink, where objects of the former type are the
geometric mapping of arrangement vertices, and objects of the latter
type are the geometric mapping of edges. In addition, it has to
support the set of predicates listed below. This basic set of
predicates is sufficient for constructing arrangements of bounded
\f$x\f$-monotone curves that are pairwise disjoint in their interiors
and points that do not lie in the interiors of the curves. The basic
set of predicates is also sufficient for answering vertical
ray-shooting queries and point-location queries with a small
exception: Locating a point using the landmark strategy requires a
traits class that models the concept `AosLandmarkTraits_2`;
see Section \ref aos_sssec-tr_landmarks_concept.

<DL>

<DT>\link AosBasicTraits_2::Compare_x_2 <B>`Compare_x_2`</B>\endlink:
<DD>Compares the \f$x\f$-coordinates of two points.

<DT>\link AosBasicTraits_2::Compare_xy_2 <B>`Compare_xy_2`</B>\endlink:
<DD>Compares two points lexicographically, first by their
  \f$x\f$-coordinates, and if they are equal, by their
  \f$y\f$-coordinates.

<DT>\link AosBasicTraits_2::Equal_2 <B>`Equal_2`</B>\endlink:
<DD>There are two overloaded Boolean operators that test equality. One
  returns `true` iff two given points represent the same geometric point
  in the two-dimensional surface, and the second returns `true` iff the
  graphs of two given \f$x\f$-monotone curves are the
  same.\cgalFootnote{The predicate that tests equality between graphs
  of two \f$x\f$-monotone curves is used only for testing as part of
  the test suite.}

<DT>\link AosBasicTraits_2::Construct_min_vertex_2 <B>`Construct_min_vertex_2`</B>\endlink:
<DD>Returns the lexicographically smallest (or left) endpoint of an
  \f$x\f$-monotone curve.

<DT>\link AosBasicTraits_2::Construct_max_vertex_2 <B>`Construct_max_vertex_2`</B>\endlink:
<DD> Returns the lexicographically largest (or right) endpoint of an
  \f$x\f$-monotone curve.

<DT>\link AosBasicTraits_2::Is_vertical_2 <B>`Is_vertical_2`</B>\endlink:
<DD> Determines whether an \f$x\f$-monotone curve is vertical.

<DT>\link AosBasicTraits_2::Compare_y_at_x_2 <B>`Compare_y_at_x_2`</B>\endlink:
<DD>Given an \f$x\f$-monotone curve \f$c\f$ and a point \f$p\f$ that
  lies in the \f$x\f$-range of \f$c\f$, determines whether \f$p\f$ is
  below, above or lies on \f$c\f$.

<DT>\link AosBasicTraits_2::Compare_y_at_x_right_2 <B>`Compare_y_at_x_right_2`</B>\endlink:
<DD> Given two \f$x\f$-monotone curves \f$c_1\f$ and \f$c_2\f$ that
  share a common minimal (left) endpoint \f$p\f$, determines whether
  \f$c_1\f$ is above or below \f$c_2\f$ immediately to the right of
  \f$p\f$, or whether the two curves overlap there.

<DT>\link AosBasicTraits_2::Do_intersect_2 <B>`Do_intersect_2`</B>\endlink:
<DD> Determines whether two given \f$x\f$-monotone curves intersect.
  An input flag determines whether the curve are closed or open.
</DL>

Every model of the concept `AosBasicTraits_2` needs to define
a nested type named \link AosBasicTraits_2::Has_left_category
`Has_left_category`\endlink. It determines whether the traits class
supports the following predicate:

<DL>

<DT>\link AosBasicTraits_2::Compare_y_at_x_left_2 <B>`Compare_y_at_x_left_2`</B>\endlink:
<DD> Given two \f$x\f$-monotone curves \f$c_1\f$ and \f$c_2\f$ that
  share a common maximal (right) endpoint \f$p\f$, determines whether
  \f$c_1\f$ is above or under \f$c_2\f$ immediately to the left of
  \f$p\f$, or whether the two curves overlap there.

</DL>

If the `AosBasicTraits_2::Has_left_category` type nested in a
model of the basic concept is defined as `Tag_true`\cgalFootnote{In
principle, the category type may only be convertible to the tag type,
but in practice the category is typically explicitly defined as the
tag.} the model must support the predicate. If the type is defined as
`Tag_false`, we resort to an internal version, which is based just on
the reduced set of provided operations.  The internal version might be
less efficient, but it exempts the traits developer from the providing
an (efficient) implementation of this predicate---a task that turns
out to be nontrivial in some cases.

The basic set of predicates is sufficient for constructing
arrangements of \f$x\f$-monotone curves that do not reach or approach
the boundary of the parameter space. The nature of the input curves,
whether they are expected to reach or approach the left, right,
bottom, or top side of the boundary of the parameter space, must be
conveyed by the traits class. This is done through the definition of
four additional nested types, namely
<ol>
<li>\link AosBasicTraits_2::Left_side_category
`Left_side_category`\endlink,
<li>\link AosBasicTraits_2::Right_side_category
`Right_side_category`\endlink,
<li>\link AosBasicTraits_2::Bottom_side_category
`Bottom_side_category`\endlink, and
<li>\link AosBasicTraits_2::Top_side_category
`Top_side_category`\endlink.
</ol>
Each of those types must be convertible
to the type `Arr_oblivious_side_tag` for the class to be a model of
the concept `AosBasicTraits_2`.


\subsubsection aos_sssec-geom_traits-concepts_intersecting Intersections


Constructing an arrangement induced by \f$x\f$-monotone curves that
may intersect in their interior requires operations that are not part
of the `AosBasicTraits_2` concept. The additional operations
are listed by the concept `AosXMonotoneTraits_2`, which
refines the basic arrangement geometry-traits concept described above.
While models of the `AosXMonotoneTraits_2` concept still
handle only \f$x\f$-monotone curves, the curves are not restricted to
be disjoint in their interiors. Such a model must be capable of
computing points of intersection between \f$x\f$-monotone curves,
splitting curves at these intersection points to obtain pairs of
interior-disjoint subcurves, and optionally merging pairs of
subcurves. A point of intersection between two curves is also
represented by the \link AosBasicTraits_2::Point_2
`Point_2`\endlink type. A model of the refined concept must define an
additional type called `Multiplicity`.  An object of this type
indicates the multiplicity of the intersection point of two curves,
also referred to as the <em>intersection
number</em>.\cgalFootnote{See, e.g.,
https://en.wikipedia.org/wiki/Intersection_number for more information
about intersection numbers.} Loosely speaking, if two curves intersect
at a point \f$p\f$ but have different tangents (first derivatives) at
\f$p\f$, The point \f$p\f$ is of multiplicity 1. If the curve tangents
are equal but their curvatures (second derivatives) are not, \f$p\f$
is of multiplicity 2, and so on. The multiplicity of points of
intersection between line segments is always 1, and the multiplicity
of a point of intersection between two polylines is 1 if the
intersection point is interior to the corresponding two line segments
of the polylines, and undefined (coded as 0) otherwise. A model of the
refined concept thus has to support the following additional
operations:

<DL>

<DT>\link AosXMonotoneTraits_2::Split_2 <B>`Split_2`</B>\endlink:
<DD> Splits an \f$x\f$-monotone curve \f$c\f$ into two subcurves at a
  given point \f$p\f$ that lies in the interior of \f$c\f$.

<DT>\link AosXMonotoneTraits_2::Are_mergeable_2 <B>`Are_mergeable_2`</B>\endlink:
<DD> Determines whether two \f$x\f$-monotone curves \f$c_1\f$ and
  \f$c_2\f$ that share a common endpoint can be merged into a single
  continuous \f$x\f$-monotone curve representable by the traits
  class.\cgalFootnote{On the face of it this seems a difficult
  predicate to implement. In practice we use very simple tests to
  decide whether two curves are mergeable: We check whether their
  underlying curves are identical and whether they do not bend to form
  a non-\f$x\f$-monotone curve.}

<DT>\link AosXMonotoneTraits_2::Merge_2 <B>`Merge_2`</B>\endlink:
<DD> Merges two mergeable \f$x\f$-monotone curves into a single curve.

<DT>\link AosXMonotoneTraits_2::Intersect_2 <B>`Intersect_2`</B>\endlink:
<DD> Computes all intersection points and overlapping sections of two
  given \f$x\f$-monotone curves. If possible, computes also the
  multiplicity of each intersection point. Providing the multiplicity
  of an intersection point is not required, but it can expedite the
  arrangement construction. Typically, the multiplicity is a byproduct
  of the intersection computation. However, if it is not available,
  undefined multiplicity (coded as 0) is assumed. Having the
  multiplicity of intersection points while constructing arrangements
  enables the exploitation of the geometric knowledge intersection
  points may have.

</DL>

Using a model of the `AosXMonotoneTraits_2` it is
possible to construct arrangements of sets of \f$x\f$-monotone curves
(and points) that may intersect one another. The two operations
listed above, regarding the merging of curves, are optional, and should
be provided only if the type `Has_merge_category` nested in a model of
the `AosXMonotoneTraits_2` concept is defined as `Tag_true`.
Otherwise, it is not possible to merge \f$x\f$-monotone curve and
redundant vertices may be left in the arrangement due to the removal of
edges.


\subsubsection aos_sssec-geom_traits-concepts_arbitrary Supporting Arbitrary Curves


The concept `AosTraits_2` refines the
`AosXMonotoneTraits_2` concept. A model of the refined concept
must define an additional type that is used to represent general, not
necessarily \f$x\f$-monotone and not necessarily continuous, curves,
named \link AosTraits_2::Curve_2 `Curve_2`\endlink. It also
has to support the subdivision of a curve of that type into a set of
continuous \f$x\f$-monotone curves and isolated points. For example,
the curve \f$c:\ (x^2 + y^2)(x^2 + y^2 - 1) = 0\f$ comprises the unit
circle (the locus of all points for which \f$x^2 + y^2 = 1\f$) and the
origin (the singular point \f$(0,0)\f$). \f$c\f$ should therefore be
subdivided into two circular arcs, the upper part and the lower part
of the unit circle, and a single isolated point.  In particular a
model of the refined concept has to support the following additional
operation:

<DL>

<DT>\link AosTraits_2::Make_x_monotone_2 <B>`Make_x_monotone_2`</B>\endlink:

<DD> Divides a given general curve of type \link
  AosTraits_2::Curve_2 `Curve_2`\endlink into continuous weakly
  \f$x\f$-monotone curves and isolated points.

</DL>

Note that a model of the refined concept `AosTraits_2` is
required only when using the free `insert()` function templates (see
Section \ref arr_secgl_funcs) that accept an object of type \link
AosTraits_2::Curve_2 `Curve_2`\endlink or a range of objects
of that type. In all other cases it is sufficient to use a model of
the `AosXMonotoneTraits_2` concept.


\subsubsection aos_sssec-tr_landmarks_concept The Landmark Concept



\cgalFigureBegin{aos_fig-landmark_concept_cluster,landmark_concept_cluster.png}
The traits-concept hierarchy for arrangements associated with the landmark
point-location strategy.
\cgalFigureEnd


The type of an arrangement associated with the landmark point-location
strategy (see Section \ref arr_ssecpl) must be an instance of the
`Arrangement_on_surface_2<GeomTraits, TopolTraits>` class template,
where the `GeomTraits` parameter is substituted by a model of the
concept `AosLandmarkTraits_2`. (Naturally, it can also model
either the `AosXMonotoneTraits_2` concept or the
`AosTraits_2` concept.) The `AosLandmarkTraits_2`
concept refines the two concepts `AosApproximatePointTraits_2` and
`AosConstructXMonotoneCurveTraits_2`. Each of these two
concepts, in turn, refines the concept `AosBasicTraits_2`.

A model of the `AosApproximatePointTraits_2` concept must define a
fixed precision number type (typically the double-precision
floating-point `double`) and support the operation below (in addition
to fulfilling the requirements listed by the `AosBasicTraits_2`
concept).

<DL>

<DT>\link AosApproximatePointTraits_2::Approximate_2 <B>`Approximate_2`</B>\endlink:
<DD> Given a point `p`, approximate the \f$x\f$ and
\f$y\f$-coordinates of `p` using a not necessarily multi-precision
number type. We use this operation for approximate
computations---there are certain operations performed during the
search for the location of the point that need not be exact, and that
can be performed faster when carried out, for example, using a
fixed-precision number type.

</DL>

A model of the `AosConstructXMonotoneCurveTraits_2` concept
must support the operation below (in addition to fulfilling the
requirements listed by the `AosBasicTraits_2` concept).

<DL>

<DT>\link AosConstructXMonotoneCurveTraits_2::Construct_x_monotone_curve_2 <B>`Construct_x_monotone_curve_2`</B>\endlink:
<DD> Given two points \f$p_1\f$ and \f$p_2\f$, construct
an \f$x\f$-monotone curve connecting \f$p_1\f$ and \f$p_2\f$.

</DL>

Most traits classes model the `AosTraits_2` concept, and some
also model the `AosLandmarkTraits_2` concept.

The concept `AosConstructCurveTraits_2` refines the concept
`AosBasicTraits_2`. A model of the `AosConstructCurveTraits_2` concept
must support the operation below (in addition to fulfilling the
requirements listed by the `AosBasicTraits_2` concept).


\subsubsection aos_sssec-tr_additional_concepts The Construct Curve Concept


<DL>
<DT>\link AosConstructCurveTraits_2::Construct_curve_2 <B>`Construct_curve_2`</B>\endlink:
<DD> Given two points \f$p_1\f$ and \f$p_2\f$, construct
a curve connecting \f$p_1\f$ and \f$p_2\f$.
</DL>

The `Arr_polyline_traits_2<SubcurveTraits_2>` class template handles
polylines; see Section ~\ref arr_sssectr_polylines.
The type that substitutes the template parameter `SubcurveTraits_2`
when `Arr_polyline_traits_2<SubcurveTraits_2>` is instantiated must be
a geometry-traits class that models the concept `AosConstructCurveTraits_2`
to enable the construction of polylines from a sequence of two or more points.


\subsubsection aos_sssec-tr_approximatetion_concept Supporting Approximations of Curves


Operations on arrangements are guaranteed to be robust only if the
operations of the geometry traits used to carry out the high-level
operations are robust. Geometry traits constructors are guaranteed to
be robust only if the kernel in use supports exact constructions, such
as the Epec kernel. Even if you only intend to perform point-location
queries on an arrangement induced by a collection of curves, you need
an exact-construction kernel, if the curves are not pairwise disjoint
in their interiors. However, when using an exact-construction kernel
you still may desire to perform (independent) operations on
approximations of the points or the interior-disjoint \f$x\f$-monotone
curves of the arrangements in order to gain speed, for example drawing
the arrangement on a raster window.  Naturally, reconstructing an
arrangement from the approximations of its points and
interior-disjoint \f$x\f$-monotone curves, may result with an arrangement
of a different topology, or even worse, intersections in the interior
of the curves.

The concept `AosApproximateTraits_2` refines the concept
`AosApproximatePointTraits_2`. In addition to the type
`Approximate_number_type` required by the latter, a model of the
`AosApproximateTraits_2` concept must define the type
`Approximate_point_2`, which is typically defined as
`CGAL::Cartesian<Approximate_number_type>::%Point_2`. Also, it must
support the operations below (in addition to the operation required by
the concept `AosApproximatePointTraits_2`).

<DL>
<DT>\link AosApproximateTraits_2::Approximate_2 <B>`Approximate_2`</B>\endlink:
<DD>This operation is overloaded with three versions. The first one
  returns an approximation of the \f$x\f$- or \f$y\f$-coordinates of a given
  point as required by the concept `AosApproximatePointTraits_2`; see
  Section \ref aos_sssec-tr_landmarks_concept. The description of the remaining
  two follow.

  (i) Given a point \f$p\f$, obtain an approximation of \f$p\f$, which is an
    object of type `Approximate_point_2`. This is trivially
    implemented using the first version.

  (ii) Given an \f$x\f$-monotone curve \f$c\f$, a small number \f$\epsilon\f$ of
    type `Approximate_number_type` that serves as an error bound, an
    output iterator associated with a container
    of approximate points, and a flag that indicates whether to
    approximate \f$c\f$ starting from its smallest lexicographic endpoint,
    compute a polyline that approximates \f$c\f$ in the indicated
    direction, such that the largest distance between \f$c\f$ and the
    polyline is not larger than \f$\epsilon\f$. The polyline is
    represented as a sequence of approximate points.
</DL>


\subsubsection aos_ssec-traits-curved Supporting Unbounded Curves or Curved Surfaces


We descend to the bottom level of the hierarchy. The refinements
described in this section provide the requirements imposed on traits
classes used with arrangements induced by curves with boundary
conditions. In particular, these requirements list additional
operations that handle curves that either reach specific sides of the
parameter-space boundary (the pre-images of their endpoints lie on
boundary sides) or approach them (the pre-images of their endpoints
approach boundary sides). These boundary conditions typically occur
with unbounded curves or with arrangements embedded in curved
surfaces. The category types \link
AosBasicTraits_2::Left_side_category
`Left_side_category`\endlink, \link
AosBasicTraits_2::Right_side_category
`Right_side_category`\endlink, \link
AosBasicTraits_2::Bottom_side_category
`Bottom_side_category`\endlink, and \link
AosBasicTraits_2::Top_side_category
`Top_side_category`\endlink, nested in every geometry traits class
indicate whether the corresponding boundary side (i.e., left, right,
bottom, and top) is open, closed, contracted, or identified, and
whether this information is relevant at all. When all curves inserted
into the arrangement are expected to neither approach nor reach that
particular boundary side, the information is irrelevant. (Note that we
explicitly distinguish closed-only, contracted, and identified sides,
although the latter two are closed in the parameter space as well.)
Each one of the categories above must be convertible to one of the tag
types listed below according to the boundary condition that should be
handled.

<ul>

<li>`Arr_open_side_tag`
<li>`Arr_closed_side_tag`
<li>`Arr_contracted_side_tag`
<li>`Arr_identified_side_tag`
<li>`Arr_oblivious_side_tag`

</ul>

For each of the four sides of the parameter space there are four
available concepts, models of which can be used to handle open,
closed, contracted, and identified sides, respectively. (When curves
are expected to neither reach nor approach a particular side, special
handling is not required; thus, there is no need for a corresponding
concept.) For example, it is required that the category type \link
AosOpenBottomTraits_2::Bottom_side_category
`Bottom_side_category`\endlink, nested in models of the concept
`AosOpenBottomTraits_2`, is convertible to the tag type
`Arr_open_side_tag`.  This makes for a total of 16 abstract concepts
(combine one of left, right, bottom, and top with one of open, closed,
contracted, identified). Any one of these individual abstract concept
is useless on its own; only concepts that refine a combination of 0,
1, 2, 3, or 4 abstract concepts (which capture the conditions that
occur in the four sides simultaneously) are purposeful. Theoretically,
there are \f$\sum_{i=0}^4\binom{i}{4} \cdot 4^i = 5^4 = 625\f$ such
concepts. However, only a subset of them is meaningful. If a side is
identified, the opposite side must also be identified. In addition, a
contracted side must be adjacent to two identified sides. While this
narrows down the number of tangible concepts, the total number is
still high; in practice we have used only two so far (not counting the
"plain" concept, models of which do not handle boundary conditions at
all), namely, `AosOpenBoundaryTraits_2` and
`AosSphericalBoundaryTraits_2`; see below for more
details. Many of the traits class-templates provided by the \ref
PkgArrangementOnSurface2 package do not handle boundary conditions at
all. Some of them, such as the `Arr_segment_traits_2` traits (see
Section \ref arr_ssectr_segs) only handle bounded curves. Thus, the
four category types nested in these models are defined to be
`Arr_oblivious_side_tag`.


\cgalFigureBegin{aos_fig-open_concept_hierarchy,open_concept_hierarchy.png}
Bottom portion of the refinement hierarchy of the geometry-traits
concepts for curves embedded in an open surface, for instance, the
entire plane.
\cgalFigureEnd


Several predicates are required to handle \f$x\f$-monotone curves that
approach the boundary of the parameter space. These predicates are
sufficient to handle not only curves embedded in an unbounded
parameter space, but also curves embedded in a bounded parameter space
with open boundaries. The arrangement type instantiated with a traits
class that models the combined concept
`AosOpenBoundaryTraits_2` shown in
\cgalFigureRef{aos_fig-open_concept_hierarchy} can handle curves that
are open in any direction. Recall that an arrangement that supports
unbounded \f$x\f$-monotone curves maintains an implicit bounding
rectangle in the \dcel structure; see Section \ref
aos_sec-unbounded. If some curves inserted into an arrangement object
are expected to be unbounded; namely, there exists \f$d \in \{0,1\}\f$
such that \f$\lim_{t \rightarrow d}x(t) = \pm\infty\f$ or \f$\lim_{t
\rightarrow d}y(t) = \pm\infty\f$ holds for at least one input curve
\f$c(t) = (x(t),y(t))\f$, the arrangement template must be
instantiated with a model of the `AosOpenBoundaryTraits_2`
concept.\cgalFootnote{A curve that reaches the boundary of the
parameter space in this case is open and unbounded.}


\cgalFigureBegin{aos_fig-spherical_concept_hierarchy,spherical_concept_hierarchy.png}
The entire spherical boundary cluster of the refinement hierarchy of the
geometry-traits concepts for curves embedded in a sphere-like parameterized
surface.
\cgalFigureEnd


A suitable geometry-traits component for arrangements embedded in
surfaces homeomorphic to a sphere is a model of the combined concept
`AosSphericalBoundaryTraits_2` shown in
\cgalFigureRef{aos_fig-spherical_concept_hierarchy}. Here the two
vertical sides of the parameter space are identified and the two
horizontal sides are contracted.


\cgalFigureBegin{aos_fig-left_side_cluster,left_side_cluster.png}
Top portion of the refinement hierarchy of the geometry-traits
concepts for curves that either reach the left side of the boundary
of the parameter space or approach it. A similar hierarchy also
exists for the right, bottom, and top sides.
\cgalFigureEnd


The shared requirements for the four options of a side are collected
in abstract layers called `AosLeftSideTraits_2`,
`AosRightSideTraits_2`, `AosBottomSideTraits_2`, and
`AosTopSideTraits_2`; see, e.g.,
\cgalFigureRef{aos_fig-left_side_cluster}.


\cgalFigureBegin{aos_fig-side_clusters,side_clusters.png}
Top portion of the refinement hierarchy of the geometry-traits
concepts for curves that either reach the vertical sides of the
boundary of the parameter space or approach it, and similarly for
curves that either reach or approach horizontal sides.
\cgalFigureEnd


The shared requirements for the options of opposite sides are
collected in two additional abstract layers called
`AosVerticalSideTraits_2` and
`AosHorizontalSideTraits_2`; see
\cgalFigureRef{aos_fig-side_clusters}.


\cgalFigureBegin{aos_fig-identified_clusters,identified_clusters.png}
Top portion of the refinement hierarchy of the geometry-traits
concepts for curves that reach the identified vertical sides of the
parameter space and for curves that reach the identified horizontal
sides of the parameter space.
\cgalFigureEnd


Individual concepts for curves that reach the identified left side of
the parameter space and for curves that reach the identified right
side of the parameter space do not exist, because if one side is
identified the opposite side must be identified as well. Similarly,
individual concepts for curves that reach the identified bottom side
of the parameter space and for curves that reach the identified top
side of the parameter space do not exist either. Instead, the shared
requirements for opposite identified sides are collected in two
additional abstract concepts called
`AosIdentifiedVerticalTraits_2` and
`AosIdentifiedHorizontalTraits_2`; see
\cgalFigureRef{aos_fig-identified_clusters}. The former lists
requirements for operations that handle curves that reach identified
vertical sides of the parameter space, and the latter lists
requirements for operations that handle curves that reach identified
horizontal sides of the parameter space.

In the following we list the specific requirements of all the
aforementioned concepts.

The abstract concept `AosVerticalSideTraits_2` requires the
following predicate:

<DL>

<DT>\link AosVerticalSideTraits_2::Parameter_space_in_x_2 <B>`Parameter_space_in_x_2`</B>\endlink:

<DD>This three-valued predicate is overloaded with two versions as
  follows:

(i) Given a curve \f$c = (x(t), y(t))\f$ and an enumerator that
specifies either the minimum end or the maximum end of the curve, and
thus maps to a parameter value \f$d \in \{0,1\}\f$, determine the
location of the \f$d\f$-end of \f$c\f$ along the
\f$x\f$-dimension. Formally, if \f$c\f$ is open at its \f$d\f$-end,
determine whether \f$\lim_{t \rightarrow d} x(t)\f$ evaluates to
\f$x_{\rm min}\f$, \f$x_{\rm max}\f$, or a value in between. If
\f$c\f$ is not open at its \f$d\f$-end, determine whether \f$x(d)\f$
is equal to \f$x_{\rm min}\f$, \f$x_{\rm max}\f$, or a value in
between. Return `CGAL::ARR_LEFT_BOUNDARY`, `CGAL::ARR_RIGHT_BOUNDARY`,
or `CGAL::ARR_INTERIOR`, accordingly. If \f$c\f$ is vertical and lies
on a vertical boundary; that is, either \f$\forall p=(x_p, y_p) \in c\f$
we have \f$x_p = x_{\rm min}\f$ or \f$\forall p=(x_p, y_p) \in c\f$ we
have \f$x_p = x_{\rm max}\f$, then the boundary side containing \f$c\f$
cannot be open.

(ii) Given a point \f$p=(x_p, y_p)\f$, determine the location of the
point with respect to the \f$x\f$-axis. Formally, determine whether
\f$x_p\f$ is equal to \f$x_{\rm min}\f$, \f$x_{\rm max}\f$, or a value
in between. Return `CGAL::ARR_LEFT_BOUNDARY`,
`CGAL::ARR_RIGHT_BOUNDARY`, or `CGAL::ARR_INTERIOR`, accordingly. If
\f$p\f$ is on a vertical boundary; that is, \f$x_p \in \{x_{\rm
min},x_{\rm max}\}\f$, then the boundary side containing \f$p\f$
cannot be open and must not be identified. In other words, this
overloaded version is required only for the concepts
`AosClosedLeftTraits_2`, `AosClosedRightTraits_2`,
`AosContractedLeftTraits_2` and
`AosContractedRightTraits_2`.

</DL>

The abstract concept `AosHorizontalSideTraits_2` requires the
following predicate:

<DL>

<DT>\link AosHorizontalSideTraits_2::Parameter_space_in_y_2 <B>`Parameter_space_in_y_2`</B>\endlink:

<DD>This three-valued predicate is overloaded with two versions as
  follows:

(i) Given a curve \f$c = (x(t), y(t))\f$ and an enumerator that
specifies either the minimum end or the maximum end of the curve, and
thus maps to a parameter value \f$d \in \{0,1\}\f$, determine the
location of the \f$d\f$-end of \f$c\f$ along the
\f$y\f$-dimension. Formally, if \f$c\f$ is open at its \f$d\f$-end,
determine whether \f$\lim_{t \rightarrow d} y(t)\f$ evaluates to
\f$y_{\rm min}\f$, \f$y_{\rm max}\f$, or a value in between. If
\f$c\f$ is not open at its \f$d\f$-end, determine whether \f$y(d)\f$
is equal to \f$y_{\rm min}\f$, \f$y_{\rm max}\f$, or a value in
between. Return `CGAL::ARR_BOTTOM_BOUNDARY`, `CGAL::ARR_TOP_BOUNDARY`,
or `CGAL::ARR_INTERIOR`, accordingly. If \f$c\f$ is horizontal and
lies on a horizontal boundary; that is, either \f$\forall p=(x_p, y_p)
\in c, y_p = y_{\rm min}\f$ or \f$\forall p=(x_p, y_p) \in c, y_p =
y_{\rm max}\f$, then the boundary side containing \f$c\f$ cannot be
open and must not be identified.

(ii) Given a point \f$p=(x_p, y_p)\f$, determine the location of the
point along the \f$y\f$-dimension. Formally, determine whether
\f$y_p\f$ is equal to \f$y_{\rm min}\f$, \f$y_{\rm max}\f$, or a value
in between. Return `CGAL::ARR_BOTTOM_BOUNDARY`,
`CGAL::ARR_TOP_BOUNDARY`, or `CGAL::ARR_INTERIOR`, accordingly. If
\f$p\f$ is on a horizontal boundary; that is, \f$y_p \in \{y_{\rm
min},y_{\rm max}\}\f$, then the boundary side containing \f$p\f$
cannot be open and must not be identified. In other words, this
overloaded version is required only for the concepts
`AosClosedBottomTraits_2`, `AosClosedTopTraits_2`,
`AosContractedBottomTraits_2` and
`AosContractedTopTraits_2`.

</DL>

The two symmetric predicates above determine the location of a
curve-end in the parameter space. However, in general,
\f$x\f$-coordinates and \f$y\f$-coordinates are handled
differently. This asymmetry is brought on by the various algorithms
applied to arrangements, the input and output arguments of which are
\f$x\f$-monotone curves. Indeed, all curves maintained by any
arrangement are continuous weakly \f$x\f$-monotone curves. A non
\f$x\f$-monotone curve is divided into \f$x\f$-monotone sub curves
(and perhaps points) before it is inserted into an arrangement. This
asymmetry is also reflected in the predicates listed below. They help
determining the order of curve-ends lying on the boundary of the
parameter space with respect to regular points and among each other.

The concepts `AosClosedLeftTraits_2`,
`AosClosedRightTraits_2`, and
`AosIdentifiedVerticalTraits_2` require the following
additional predicate:

<DL>

<DT>\link AosIdentifiedVerticalTraits_2::Compare_y_on_boundary_2 <B>`Compare_y_on_boundary_2`</B>\endlink:

<DD>Given two points \f$p_1=(x_{p_1},y_{p_1})\f$ and
\f$p_2=(x_{p_2},y_{p_2})\f$, such that at least one of them lies on a
vertical boundary side, compare the \f$y\f$-coordinates of the
points. That is, compare \f$y_{p_1}\f$ and \f$y_{p_2}\f$. If \f$p_1\f$
(resp. \f$p_2\f$) is on the boundary; that is, \f$x_{p_1} \in \{x_{\rm
min},x_{\rm max}\}\f$ (resp. \f$x_{p_2} \in \{x_{\rm min},x_{\rm
max}\}\f$), then the vertical boundary side containing \f$p_1\f$
(resp. \f$p_2\f$) must be either closed or identified. In other words,
this overloaded version is required only for the concepts
`AosClosedLeftTraits_2`, `AosClosedRightTraits_2`, and
`AosIdentifiedVerticalTraits_2`.

</DL>

The concept `AosVerticalSideTraits_2` requires the following additional predicate:

<DL>

<DT>\link AosVerticalSideTraits_2::Compare_y_near_boundary_2 <B>`Compare_y_near_boundary_2`</B>\endlink:

<DD>
<table border="0" cellspacing="10">
<tr>
<td>
\image html compare_y_near_boundary.png
\image latex compare_y_near_boundary.png
</td>
<td>

Given two \f$x\f$-monotone curves \f$c_1\f$ and \f$c_2\f$, and an
enumerator \f$i\f$ that specifies either the minimum ends or the
maximum ends of the two curves, and thus maps to a parameter value
\f$d \in \{0,1\}\f$, compare the \f$y\f$-coordinates of the curves
near their respective ends. More precisely, compare the
\f$y\f$-coordinates of the vertical projections of a point \f$p\f$
onto \f$c_1\f$ and onto \f$c_2\f$. If the enumerator \f$i\f$ specifies
the minimum ends, the curves must approach the left boundary-side. In
this case \f$p\f$ is located sufficiently close to the left
boundary-side, such that the result is invariant under a translation
of \f$p\f$ closer to the left boundary-side. If \f$i\f$ specifies the
maximum ends, the curves must approach the right boundary-side. In
that case \f$p\f$ is located sufficiently close to the right
boundary-side in a similar manner.

</td>
</tr>
</table>

</DL>

The concept `AosHorizontalSideTraits_2` requires two additional
predicates:

<DL>

<DT>\link AosHorizontalSideTraits_2::Compare_x_on_boundary_2 <B>`Compare_x_on_boundary_2`</B>\endlink:

<DD>This predicate is overloaded with three versions.
We distinguish between open and non-open sides as explained below.

(i) Given a regular point \f$p=(x_p,y_p)\f$, an \f$x\f$-monotone curve
\f$c = (x(t),y(t))\f$, and an enumerator that specifies either the
minimum end or the maximum end of the curve, and thus maps to a
parameter value \f$d \in \{0,1\}\f$, compare the \f$x\f$-coordinate of
\f$p\f$ and the \f$x\f$-coordinate of \f$c\f$ at its respective limit
or end depending on whether it is open or non-open. More precisely, if
\f$c\f$ is open at its \f$d\f$-end, compare the values \f$x_p\f$ and
\f$\lim_{t \rightarrow d} x(t)\f$. A precondition assures that \f$c\f$
has a vertical asymptote at its \f$d\f$-end; that is \f$\lim_{t
\rightarrow d} x(t)\f$ is a real value. If \f$c\f$ is not open,
compare the values \f$x_p\f$ and \f$x(d)\f$.

<table border="0" cellspacing="10">
<tr>
<td>
\image html compare_x_on_boundary.png
\image latex compare_x_on_boundary.png
</td>
<td>

(ii) Given two curves \f$c_1 = (x_1(t),y_1(t))\f$ and \f$c_2 =
(x_2(t),x_2(t))\f$ and enumerators that specify either the minimum end
or the maximum end of each curve, and thus map to parameter values
\f$d_1, d_2 \in \{0,1\}\f$, compare the \f$x\f$-coordinates of the
curves at their respective limits or ends. More precisely, if
\f$c_1\f$ (resp. \f$c_2\f$) is open at its \f$d_1\f$-end
(resp. \f$d_2\f$-end), use the value \f$\lim_{t \rightarrow d_1}
x_1(t)\f$ (resp. \f$\lim_{t \rightarrow d_2} x_2(t)\f$) for the
comparison.  A precondition assures that \f$c_1\f$ (resp. \f$c_2\f$)
has a vertical asymptote at its \f$d_1\f$-end (resp. \f$d_2\f$-end);
that is \f$\lim_{t \rightarrow d_1} x_1(t)\f$ is (resp. \f$\lim_{t
\rightarrow d_2} x_2(t)\f$) a real value. If \f$c_1\f$
(resp. \f$c_2\f$) is not open at its \f$d_1\f$-end
(resp. \f$d_2\f$-end), use the value \f$x_1(d_1)\f$
(resp. \f$x_2(d_2)\f$) for the comparison.

</td>
</tr>
</table>

(iii) Given two points \f$p_1=(x_{p_1},y_{p_1})\f$ and
\f$p_2=(x_{p_2},y_{p_2})\f$, such that at least one of them lies on a
horizontal boundary side, compare the \f$x\f$-coordinates of the
points. That is, compare \f$x_{p_1}\f$ and \f$x_{p_2}\f$. If \f$p_1\f$
(resp. \f$p_2\f$) is on the boundary; that is, \f$y_{p_1} \in \{y_{\rm
min},y_{\rm max}\}\f$ (resp. \f$y_{p_2} \in \{y_{\rm min},y_{\rm
max}\}\f$), then the boundary side containing \f$p_1\f$
(resp. \f$p_2\f$) must be either closed or identified. In other words,
this overloaded version is required only for the concepts
`AosClosedBottomTraits_2`, `AosClosedTopTraits_2`,
and `AosIdentifiedHorizontalTraits_2`.

<DT>\link AosHorizontalSideTraits_2::Compare_x_near_boundary_2
<B>`Compare_x_near_boundary_2`</B>\endlink:

<DD>
<table border="0" cellspacing="10">
<tr>
<td>
\image html compare_x_near_boundary.png
\image latex compare_x_near_boundary.png
</td>
<td>

Given two \f$x\f$-monotone curves \f$c_1\f$ and \f$c_2\f$ and an
enumerator \f$i\f$ that specifies either the minimum ends or the
maximum ends of the two curves, and thus map to parameter values
\f$d_1, d_2 \in \{0,1\}\f$, respectively, compare the
\f$x\f$-coordinate of the curves near their respective limits or
ends. A precondition assures that the \f$x\f$-coordinates of the
limits or ends of the curves at their respective ends are equal. That
is, the predicate `Compare_x_on_boundary_2` applied to \f$c_1\f$,
\f$c_2\f$, and \f$i\f$ evaluates to `CGAL::EQUAL`.  Formally, compare
the \f$x\f$-coordinates of the horizontal projection of a point
\f$p\f$ onto \f$c_1\f$ and onto \f$c_2\f$. A precondition assures that
\f$c_1\f$ and \f$c_2\f$ have vertical asymptotes at their respective
ends. Furthermore, both curves approach the same boundary-side, either
the bottom or the top, at their respective ends. If both curves
approach the bottom boundary-side, \f$p\f$ is located far to the
bottom, such that the result is invariant under a translation of
\f$p\f$ farther to the bottom. If both curves approach the top
boundary-side, \f$p\f$ is located far to the top in a similar manner.

</td>
</tr>
</table>

</DL>

The concept `AosIdentifiedVerticalTraits_2` requires the following
additional predicate:

<DL>

<DT>\link AosIdentifiedVerticalTraits_2::Is_on_y_identification_2 <B>`Is_on_y_identification_2`</B>\endlink:

<DD>This predicate is overloaded with two versions.

(i) Given a point \f$p=(x_p, y_p)\f$, determine whether \f$p\f$ lies
in the image of the vertical (and identified) sides of the
boundary. More precisely, determine whether \f$x_p \in \{x_{\rm
min},x_{\rm max}\}\f$ for all pre-images of \f$p\f$.

(ii) Given a curve \f$c\f$, determine whether the entire curve \f$c\f$
lies in the image of the vertical (and identified) sides of the
boundary.

</DL>

Similarly, the concept `AosIdentifiedHorizontalTraits_2`
requires the following additional predicate:

<DL>

<DT>\link AosIdentifiedHorizontalTraits_2::Is_on_x_identification_2 <B>`Is_on_x_identification_2`</B>\endlink:

<DD>This predicate is overloaded with two versions.

(i) Given a point \f$p=(x_p, y_p)\f$, determine whether \f$p\f$ lies
in the image of the horizontal (and identified) sides of the
boundary. More precisely, determine whether \f$y_p \in \{y_{\rm
min},y_{\rm max}\}\f$ for all pre-images of \f$p\f$.

(ii) Given a curve \f$c\f$, determine whether the entire curve \f$c\f$
lies in the image of the horizontal (and identified) sides of the
boundary.

</DL>


\subsection aos_ssec-geom_traits-models Models of the Geometry Traits Concepts


In this section we review the traits classes that are models of
concepts introduced in the previous sections. They handle line
segments, circular arcs, polylines, conic arcs, rational functions,
arcs of B&eacute;zier, and arcs of algebraic curves.  The last
subsection describes decorators for geometric traits classes
distributed with \cgal, which extend geometric traits-classes by
attaching auxiliary data with the geometric objects.


\subsubsection arr_ssectr_segs Traits Classes for Line Segments and Linear Objects


There are two distinct traits classes that handle line segments. One
caches information in the curve records (see Section \ref
arr_sssectr_caching_segs), while the other retains the minimal amount
of data (see Section \ref arr_sssectr_non_caching_segs). Operations
on arrangements instantiated with the former traits class consume more
space, but they are more efficient for dense arrangements (namely,
arrangements induced by line segments with a large number of
intersections). Another model handles not only (bounded) line
segments, but also rays and lines; see Section \ref
arr_sssectr_linear.


\paragraph arr_sssectr_caching_segs The Caching Segment-Traits Class


An instance of the `Arr_segment_traits_2<Kernel>` class template used
in most example programs so far is instantiated by substituting the
`Kernel` template parameter with a geometric kernel that must conform
to the `Kernel` concept; see Package \ref PkgKernel23Concepts. This
traits class defines its point type to be the `Kernel::Point_2`
type. However, neither the \link Arr_segment_traits_2::Curve_2
`Curve_2`\endlink nor the \link
Arr_segment_traits_2::X_monotone_curve_2 `X_monotone_curve_2`\endlink
nested types of the traits are defined as the `Kernel::Segment_2`
type. A kernel segment is represented by its two endpoints, and these
may have a large bit size representation when the segment is the
result of several split operations in comparison with the
representation of the original-segment endpoints. The large bit size
representation may significantly slow down the various traits-class
operations involving such segments. (A straightforward solution would
be to repeatedly normalize the results of all computations. However,
our experience shows that indiscriminate normalization considerably
slows down the arrangement construction.)

In contrast, the `Arr_segment_traits_2` class template represents a
segment using its supporting line in addition to the two endpoints.
Most computations are performed on the supporting line, which never
changes as the segment is split. The `Arr_segment_traits_2` class
template also caches some additional information with each segment to
speed up various predicates, i.e., two Boolean flags indicating (i)
whether the segment is vertical and (ii) whether the segment
target-point is lexicographically larger than its source.  The
calculation of the supporting line and two Boolean flags is delayed to
the point in time when needed to achieve further improvement in
efficiency. An \link Arr_segment_traits_2::X_monotone_curve_2
`X_monotone_curve_2`\endlink object is still constructible from two
endpoints or from a kernel segment and converted to an
`X_monotone_curve_2` object. Moreover, an \link
Arr_segment_traits_2::X_monotone_curve_2 `X_monotone_curve_2`\endlink
instance can also be cast or to a `Kernel::Segment_2` object. The two
types are thus convertible to one another.

Computing the intersection between two segments is preceded by an
application of an efficient predicate that tests whether an
intersection exists at all. This optimization has negligible overhead;
Thus, using an instance of the `Arr_segment_traits_2<Kernel>` class
template is still very efficient when constructing arrangements
induced by line segments with a large number of intersections.
Efficiency is affected by the substituted geometric kernel. Using
`Exact_predicates_exact_constructions_kernel` as the kernel type is in
general not a bad choice; the coordinates of the segment endpoints are
represented as multi-precision rational numbers, which ensures the
correctness of all computations regardless of the input.  Computations
on multi-precision number types (such as `Gmpq`) take longer than
computations on machine-precision floating-point. A kernel object of
the aforementioned type uses numerical filtering to expedite
computation; see `Kernel_2` and `Kernel_3`. If the input set of line
segments do not have degeneracies; namely, no two segments in the set
share a common endpoint, and no three segments intersect at a common
point, or at least, degeneracies exist but their number is relatively
small, then filtered computation incurs only negligible overhead
compared to floating-point arithmetic, which is error-prone. Indeed,
in almost all examples and applications given in this manual, the
predefined filtered kernel
`Exact_predicates_exact_constructions_kernel` is used to instantiate
the line-segment traits class.


\cgalFigureBegin{aos_figpredef_kernels,fan_grids.png,Europe.png}
(a) An arrangement of \f$104\f$ line segments from the input file
`fan_grids.dat`. (b) An arrangement of more than \f$3000\f$ interior
disjoint line segments, defined in the input file `Europe.dat`.
\cgalFigureEnd


In the following example we use the predefined
`Exact_predicates_exact_constructions_kernel` for instantiating our
segment-traits class. This kernel uses interval arithmetic to filter
the exact computations. The program reads a set of line segments with
integer coordinates from a file and computes their arrangement. By
default it opens the `fan_grids.dat` input-file, located in the
examples folder, which contains \f$104\f$ line segments that form
four "fan-like" grids and induce a dense arrangement, as illustrated
in \cgalFigureRef{aos_figpredef_kernels} (a):

\cgalExample{Arrangement_on_surface_2/predefined_kernel.cpp}


\paragraph arr_sssectr_non_caching_segs The Non-Caching Segment-Traits Class


The arrangement package offers an alternative segment-traits class
template that handles line segments, namely the
`Arr_non_caching_segment_basic_traits_2<Kernel>` class template.  This
class template and the `Arr_segment_traits_2<Kernel>` class template
are both parameterized by a geometric kernel and model the concepts
`AosTraits_2` and `AosLandmarkTraits_2`.
\cgalFootnote{They also model the refined concept
\cgalFootnoteCode{AosDirectionalXMonotoneTraits_2}, which enables Boolean set
operations; see Package \ref PkgBooleanSetOperations2.} The class
template `Arr_non_caching_segment_traits_2<Kernel>` derives from the
instance `Arr_non_caching_segment_basic_traits_2<Kernel>`, which
models the `AosLandmarkTraits_2` traits concept but not the
refined `AosXMonotoneTraits_2` concept. Like the
`Arr_segment_traits_2` class template it derives from the `Kernel`
type. Unlike the `Arr_segment_traits_2` class template it defines its
point and segment types as `Kernel::Point_2` and `Kernel::Segment_2`,
respectively, and most of its defined operations are delegations of
the corresponding operations of the `Kernel` type. For example, the
functor `Compare_xy_2` is defined as `Kernel::Compare_xy_2`. The
remaining operations are defined in terms of just a few other kernel
operations. For example, the `Compare_y_at_x_right_2` predicate is
defined in terms of the `Kernel::Compare_slope_2` predicate (ignoring
preconditions for the sake of clarity); see Section \ref
aos_sssec-geom_traits-concepts_basic for the description of this
predicate.  The class template
`Arr_non_caching_segment_basic_traits_2<Kernel>` is slightly less
efficient than the `Arr_segment_traits_2` class template for
constructing arrangements of pairwise interior-disjoint line-segments
in many cases, as it does not exploit caching at all. Nevertheless,
you may choose to use this traits class, as it consumes less
memory. For arrangements of line segments that do intersect you may
use the class template
`Arr_non_caching_segment_traits_2<Kernel>`. However, the performance
difference in favor of the `Arr_segment_traits_2` class template is
much larger, especially when the number of intersections is large.

In the following example we read an input file containing a set of
line segments that are pairwise disjoint in their interior. As the
segments do not intersect, no new points are constructed and we can
instantiate the `Arr_non_caching_segment_traits_basic_2<Kernel>`
class-template with the predefined
`Exact_predicates_inexact_constructions_kernel`. Note that we use the
`insert_non_intersecting_curves()` function to construct the
arrangement.  By default, the example opens the `Europe.dat`
input-file, located in the examples folder, which contains more than
\f$3000\f$ line segments with floating-point coordinates that form
the map of Europe, as depicted in
\cgalFigureRef{aos_figpredef_kernels} (b):

\cgalExample{Arrangement_on_surface_2/predefined_kernel_non_intersecting.cpp}


\paragraph arr_sssectr_linear The Linear-Traits Class


The `Arr_linear_traits_2<Kernel>` class used in Section \ref
aos_sec-unbounded for demonstrating the construction of arrangements
of unbounded curves is capable of handling bounded and unbounded
linear objects, namely, lines, rays, and line segments. It models the
concepts `AosTraits_2`, `AosLandmarkTraits_2`, and
`{AosOpenBoundaryTraits_2`. It is parameterized by a geometric
kernel and its nested \link Arr_linear_traits_2::Point_2
`Point_2`\endlink type is defined to be the kernel-point type. The
\link Arr_linear_traits_2::Curve_2 `Curve_2`\endlink (and \link
Arr_linear_traits_2::X_monotone_curve_2 `X_monotone_curve_2`\endlink)
nested types are constructible from a `Kernel::Line_2`, a
`Kernel::Ray_2`, or from a `Kernel::Segment_2` object. Given a
linear-curve object \f$c\f$, you can use the calls `c.is_line()`,
`c.is_ray()`, and `c.is_segment()` to find out whether it has a source
point or a target point. Based on the curve type, you can access its
endpoints using the methods `c.source()` (for rays and for line
segments) and `c.target()` (for segments only). It is also possible to
cast a curve into a `Kernel::Line_2`, a `Kernel::Ray_2`, or a
`Kernel::Segment_2` type, using the methods `c.line()`, `c.ray()`, and
`c.segment()`, respectively.  Just like the default segment-traits
class, the linear-curve traits class uses caching techniques to speed
up its predicate evaluations and object constructions.


\subsubsection arr_ssectr_polylines The Polyline and Polycurve Traits Classes


Polylines are continuous piecewise linear curves. Polylines are of
particular interest, as they can be used to approximate more complex
curves in the plane. At the same time they are easier to handle in
comparison to higher-degree algebraic curves, as rational arithmetic
is sufficient to carry out computations on polylines, and to construct
arrangements of polylines in an exact and robust manner. Here, we
extend the notion of polylines and use the term to refer to chains of
subcurves that are not necessarily linear. However, each subcurve must
be uniquely defined by (and, thus, can be uniquely constructed from)
two points within the handled family of curves; see Section \ref
arr_sssectr_polylines. We also provide a similar traits class that
handles continuous piecewise curves that are not necessarily linear
and are not subject to the aforementioned constraint; see Section \ref
arr_sssectr_polycurves.


\paragraph arr_sssectr_polylines The Polyline Traits Class


The `Arr_polyline_traits_2<SubcurveTraits_2>` class template handles
polylines. It models the following four concepts:

- `AosTraits_2`,

- `AosDirectionalXMonotoneTraits_2`

- `AosConstructXMonotoneCurveTraits_2`, and

- `AosConstructCurveTraits_2`.

The type that substitutes the template parameter `SubcurveTraits_2`
when `Arr_polyline_traits_2<SubcurveTraits_2>` is instantiated must be
a geometry-traits class that models the same four concepts.  We refer
to the type that substitutes the template parameter `SubcurveTraits_2`
as the <em>subcurve traits</em> hereafter.  If, in addition, the
subcurve traits also models the concept
`AosApproximatePointTraits_2` then the instantiated
`Arr_polyline_traits_2<SubcurveTraits>` type models the concept
`AosApproximatePointTraits_2` as well. (By definition, modeling the
concepts `AosApproximatePointTraits_2` and
`AosConstructXMonotoneCurveTraits_2` implies modeling the
concept `AosLandmarkTraits_2`.) Similarly, if the subcurve
traits also models the concept `AosOpenBoundaryTraits_2` then
the instantiated `Arr_polyline_traits_2<SubcurveTraits>` type models
the concept `AosOpenBoundaryTraits_2` as well. Modeling the
`AosConstructXMonotoneCurveTraits_2` concept implies that the
subcurve traits must support the construction of a unique
(\f$x\f$-monotone) segment given two input points.

An instance of the polyline traits class-template inherits its nested
point type, i.e., \link Arr_polyline_traits_2::Point_2
`Point_2`\endlink, from the subcurve traits, and defines the nested
types \link Arr_polyline_traits_2::Curve_2 `Curve_2`\endlink and \link
Arr_polyline_traits_2::X_monotone_curve_2
`X_monotone_curve_2`\endlink, which are used to represent polylines
and \f$x\f$-monotone polylines, respectively.  A polyline of the
nested type \link Arr_polyline_traits_2::Curve_2 `Curve_2`\endlink is
stored as a vector of `SubcurveTraits_2::Curve_2` objects, and an
\f$x\f$-monotone polyline of the nested type \link
Arr_polyline_traits_2::X_monotone_curve_2 `X_monotone_curve_2`\endlink
is stored as a vector of `SubcurveTraits_2::X_monotone_curve_2`
objects.  The nested `X_monotone_curve_2` type inherits from the
nested type \link Arr_polyline_traits_2::Curve_2 `Curve_2`\endlink.
By default, `Arr_segment_traits_2` is used as the subcurve traits (in
case where the `SubcurveTraits_2` parameter is omitted). In this case
the nested types `SubcurveTraits_2::Curve_2` and
`SubcurveTraits_2::X_monotone_curve_2` are identical types
representing line segments.

A polyline can be constructed given one of the following inputs:

- <b>A range of <em>points</em></b>, where two succeeding points in the
  range represent the endpoints of a segment of the polyline.

- <b>A range of <em>segments</em></b>.

- <b>A pair of points \a or a single segment</b>. In this case a polyline
  that consists of a single segment is constructed.

Note that degenerate polylines are not supported. That is, it is
impossible to construct a polyline that contains a segment of length
zero, or an isolated point. Finally, a polyline is
<b><em>continuous</em></b> and <b><em>well-oriented</em></b>.
Moreover, the target of the \f$i\f$th segment is the source of
the \f$i+1\f$st segment. If the macro `CGAL_ALWAYS_LEFT_TO_RIGHT` is
set to 1, then \f$x\f$-monotone polylines are always directed from
left-to-right. (This option is retained for backward compatibility.)
Also, note that a single polyline can be split into several
\f$x\f$-monotone polylines, and that the number of intersection points
(or overlapping sections) between two polylines can be large.

For example, the general polyline

\image html generic-polyline.png
\image latex generic-polyline.png

can be represented by one of the following two orientations.

\image html well_oriented_polyline.png
\image latex well_oriented_polyline.png

Distinct \f$x\f$-monotone polylines are rendered in different colors.

\cgalAdvancedBegin
Technically speaking, it is possible to construct a general polyline
that is neither well-oriented nor continuous. However, it is
impossible to use such polylines for the purpose of computing an
arrangement.
\cgalAdvancedEnd

The polyline traits class also supports the traversal over the range
of defining segments of a given polyline. The \a first and \a
past-the-end iterators can be obtained through the access methods
\link
CGAL::Arr_polyline_traits_2::X_monotone_curve_2::begin_segments()
`begin_segments()`\endlink and \link
CGAL::Arr_polyline_traits_2::X_monotone_curve_2::end_segments()
`end_segments()`\endlink, respectively, of a polyline \f$c\f$. The
vertices of an \f$x\f$-monotone curve are always stored in a strongly
monotonic lexicographical order.  In other words, \f$x\f$-monotone
polylines can be directed \a either left-to-right \a or right-to-left.

The polyline-traits class does not perform any geometric operations
directly. Instead, it solely relies on the functionality of the
segment traits. For example, when we need to determine the position of
a point with respect to an \f$x\f$-monotone polyline, we use binary
search to locate the relevant segment that contains the point in its
\f$x\f$-range. Then, we compute the position of the point with respect
to this segment. Thus, operations on \f$x\f$-monotone polylines of
size \f$m\f$ typically take \cgalBigO{\log m} time.

You are free to choose the underlying segment traits class. Your
decision could be based, for example, on the number of expected
intersection points; see Section \ref arr_ssectr_segs. Moreover, it is
possible to substitute the `SubcurveTraits_2` template parameter with
a traits class that handles segments with some additional data
attached to each individual segment; see Section \ref
arr_sssec_tr_data_decorators. This makes it possible to associate
different data objects with the different segments that compose a
polyline.


\cgalFigureBegin{aos_fig-polylines,polylines.png}

An arrangement of three polylines, as constructed in \ref
Arrangement_on_surface_2/polylines.cpp. Red disks mark vertices
associated with polyline endpoints, while rings mark vertices that
correspond to intersection points. The target endpoint of \f$\pi_3\f$
is also an intersection point; it is rendered as a ring. Observe that
the polyline \f$\pi_2\f$ is split into three \f$x\f$-monotone
polylines, and that the two curves \f$\pi_1\f$ and \f$\pi_3\f$ have
two overlapping sections---an impossible scenario in arrangements of
line segments.  \cgalFigureEnd


The following example program constructs an arrangement of three
polylines, \f$\pi_1\f$, \f$\pi_2\f$, and \f$\pi_3\f$, as depicted in
\cgalFigureRef{aos_fig-polylines}. In this example, each polyline is
constructed from points stored in a different container, i.e., array,
list, and vector. Points defining the polylines are not necessarily
associated with arrangement vertices. The arrangement vertices are
either the extreme points of each \f$x\f$-monotone polyline (drawn as
red discs) or the intersection points between two polylines (drawn as
rings).

\cgalExample{Arrangement_on_surface_2/polylines.cpp}

The common types used by the example programs involving arrangements
of polylines are listed below, and defined in the header file
`arr_polylines.h`. As we do in the case of segments and linear
objects, we use the predefined kernel to instantiate our traits class.
However, in this case we have yet another layer of template
instantiation, namely the instantiation of the polyline-traits
class-template with an instance of a subcurve traits
class-template. Naturally, we use the `Arr_segment_traits_2` class
template, instantiated with the predefined filtered kernel.

\code{.cpp}
#include <CGAL/Exact_predicates_exact_constructions_kernel.h>
#include <CGAL/Arr_segment_traits_2.h>
#include <CGAL/Arr_polyline_traits_2.h>
#include <CGAL/Arrangement_2.h>

using Kernel = CGAL::Exact_predicates_exact_constructions_kernel;
using Number_type = Kernel::FT;

using Segment_traits = CGAL::Arr_segment_traits_2<Kernel>;
using Traits = CGAL::Arr_polyline_traits_2<Segment_traits>;
using Point = Traits::Point_2;
using Polyline = Traits::Curve_2;
using Arrangement = CGAL::Arrangement_2<Traits>;
\endcode


\paragraph arr_sssectr_polycurves The Polycurve Traits Class


The traits class `Arr_polycurve_traits_2<SubcurveTraits_2>` handles
piecewise curves that are not necessarily linear, such as conic arcs,
circular arcs, B&eacute;zier curves, or line segments. We call such a
compound curve a <em>polycurve</em>. Similar to a polyline, a
polycurve is a chain of subcurves, where each two neighboring
subcurves in the chain share a common endpoint; that is, the polycurve
is continuous. As a matter of fact, most characteristics of the
`Arr_polyline_traits_2<SubcurveTraits_2>` traits class template apply
also to the `Arr_polycurve_traits_2<SubcurveTraits_2>` traits class
template. The only difference between the two, is that the latter is
not a model of the concepts
`AosConstructXMonotoneCurveTraits_2` nor
`AosConstructCurveTraits_2`, and as such, it is not
able to construct a subcurve from only two points. As a consequence,
it does not support the operations that (i) construct a polycurve from
a sequence of points, and (ii) push a point at the back or at the
front of a non-empty polycurve.


\subsubsection arr_ssectr_algebraic Traits Classes for Algebraic Curves


A curve in our context is typically (but not necessarily) defined as
the zero set of a bivariate nonzero polynomial with rational (or,
equivalently, integral) coefficients. We call such polynomials and the
curves they define \a algebraic. When dealing with linear curves
(e.g., line segments and polylines), having rational coefficients
guarantees that all intersection points also have rational
coordinates, such that the arrangement of such curves can be
constructed and maintained using only rational arithmetic. The \ref
PkgArrangementOnSurface2 package also offers geometry traits-classes
that handle algebraic curves defined by algebraic polynomials of
degree higher than~\f$1\f$. Unfortunately, the coordinates of the
intersection points constructed by these traits models are in general
algebraic numbers\cgalFootnote{A number is called \a algebraic, if it
is the root of a univariate algebraic polynomial with rational
coefficients.} of degree higher than \f$1\f$. It is therefore clear
that we have to use number types different from plain rational to
represent point coordinates and be able to apply arithmetic operations
on them.

Several types of algebraic curves are handled by more than one traits
model.  Section \ref arr_sssectr_linear introduces a few different
traits models that handle line segments. This duplication becomes more
evident with the introduction of traits classes that handle algebraic
curves. The different traits models have different properties. In some
cases they were developed by different authors at different times
exploiting different tools that were available at the time they were
developed. As a general rule, you should always use the minimal traits
model that still satisfies your needs, as the most dedicated model is
most likely to be the most efficient.


\paragraph arr_sssectr_circ_seg Circular Arcs and Line Segments


Arrangement of circular arcs and of line segments are very useful and
frequently arise in applications, where curves of interleaved line
segments and circular arcs are used to model the boundaries of complex
shapes. Such curves can fit the original boundary more tightly and
more compactly than, for example, a simple polyline. For example, when
dilating a polygon by some radius we obtain a shape whose boundary
comprises of line segments, which correspond to dilated polygon edges,
and circular arcs, which result from dilated polygon vertices. Using
the arrangement of the boundary curves it is possible, for example, to
compute the union of a set of dilated polygons.  Besides the
importance of arrangements of circular arcs and line segments it turns
out that it is possible to implement efficient traits models that
handle curves restricted to circular arcs and line segments. Rational
numbers cannot represent the coordinates of intersection points that
may arise in such arrangements in an exact manner. Thus, algebraic
numbers must be used. However, the performance impact that (general)
algebraic numbers incur can be reduced by the use of an efficient type
of exact algebraic numbers called <em>square root extension</em> that
uses rational arithmetic in an almost straightforward fashion.

Square root numbers have the form \f$\alpha + \beta\sqrt{\gamma}\f$,
where \f$\alpha\f$, \f$\beta\f$, and \f$\gamma\f$ are rational
numbers. (Square root numbers are also called one-root numbers.) The
rational number \f$\gamma\f$ is referred to as the extension. Each
subset that has a particular extension is closed under arithmetic
operations and order relations; hence, it is a valid algebraic
structure.\cgalFootnote{The term algebraic structure refers to the set
closed under one or more operations satisfying some axioms; see, e.g.,
https://en.wikipedia.org/wiki/Algebraic_structure.  For example, all
numbers that can be expressed as \f$\alpha + \beta\sqrt{K}\f$, where
\f$\alpha\f$ and \f$\beta\f$ are rational and \f$K\f$ is a rational
constant, compose an algebraic structure.}  The class template
`CGAL::Sqrt_extension<NT,Root>` implements the square root extension
type. Instances of this template represent square root numbers. It is
equipped with the implementation of a set of arithmetic operations and
order relations that exploit identical extensions of operands. It also
provides the ability to compare two numbers with different extensions
\f$\gamma_1 \neq \gamma_2\f$ efficiently. Each operation is
implemented using only few rational arithmetic operations. Here, `NT`
is the type of \f$\alpha\f$ and \f$\beta\f$, and `Root` is the type of
\f$\gamma\f$.  The running times of the arithmetic operations and
order relations provided by the square root extension when the
identical-extension condition is met are comparable to the running
times of the corresponding arithmetic operations of rational-number
types. The running times of order relations when the condition is not
met are only slightly larger. In practice, using number types that
represent (arbitrary) algebraic numbers increases the running time of
the application significantly.

We call circles whose center coordinates and squared radii are
rational numbers <em>rational circles</em>. The equation of such a
circle, that is, \f$(x - x_0)^2 + (y - y_0)^2 = r^2\f$, where
\f$(x_0,y_0)\f$ and \f$r\f$ denote the circle center and its radius,
respectively, has rational coefficients. The coordinates of the points
of intersection between two such circles are therefore solutions of
quadratic equations with rational coefficients, in other words,
algebraic numbers of degree~\f$2\f$ or simply square root numbers. The
same applies to intersection points between such a rational circle and
a line, or a line segment, with rational coefficients (a line whose
equation is \f$ax + by + c = 0\f$, where \f$a\f$, \f$b\f$, and \f$c\f$
are rational).

The \ref PkgArrangementOnSurface2 package offers a traits
class-template called `Arr_circle_segment_traits_2<Kernel>` that
exclusively handles line segments, circular arcs, and whole circles
and models the concepts `AosTraits_2` and
`AosDirectionalXMonotoneTraits_2`; see Package \ref
PkgBooleanSetOperations2Ref. Note that it is not a model of the
`AosLandmarkTraits_2` concept.  It exploits efficient
computations with square root numbers, which makes it attractive for
arrangements induced by line segments, circular arcs, and whole
circles.  When the traits class-template is instantiated, the `Kernel`
template parameter must be substituted by a geometric kernel that
models the `Kernel` concept. Always plug in a kernel that uses a
rational number type, such as
`Exact_predicates_exact_constructions_kernel`. Observe that the nested
type \link CGAL::Arr_circle_segment_traits_2::Point_2
`Point_2`\endlink defined by the traits class, whose coordinates are
typically algebraic numbers of degree 2, is \a not the same as the
`Kernel::Point_2` type. The coordinates of a point are represented
using the number type `CoordNT`, nested in the traits class-template.


\cgalFigureBegin{aos_fig-circles,circles.png}
An arrangement of three circles constructed in \ref
Arrangement_on_surface_2/circles.cpp. Each circle is split into two
\f$x\f$-monotone circular arcs, whose endpoints are drawn as red
disks. Rings mark vertices that correspond to intersection points. The
vertex \f$v_{\rm max}\f$ is a common intersection point of all three
circles.
\cgalFigureEnd


In the following example an arrangement of three full circles is
constructed, as shown in \cgalFigureRef{aos_fig-circles}. Each Index is
split into two \f$x\f$-monotone circular arcs, the endpoints of which
are drawn as red discs; rings mark vertices that correspond to
intersection points. Once the arrangement is constructed, we locate
the vertex of maximal degree in the arrangement. The geometric mapping
of this vertex, denoted by \f$v_{\rm max}\f$, is the point
\f$(4,3)\f$, as all three circles intersect at this point and the
associated vertex has six incident edges.

\cgalExample{Arrangement_on_surface_2/circles.cpp}

The types common to the example programs that use the
`Arr_circle_segment_traits_2` class template are listed below and
defined in the header file `arr_circular.h`.  Even though algebraic
numbers are required to represent coordinates of points where the
inducing curves are circles or circular arcs, such as the curves
handled by the `Arr_circle_segment_traits_2` class template, an
(exact) rational kernel suffices, and a filtered one improves the
performance further.

\code{.cpp}
#include <CGAL/Exact_predicates_exact_constructions_kernel.h>
#include <CGAL/Arr_circle_segment_traits_2.h>
#include <CGAL/Arrangement_2.h>

using Kernel = CGAL::Exact_predicates_exact_constructions_kernel;
using Number_type = Kernel::FT;
using Traits = CGAL::Arr_circle_segment_traits_2<Kernel>;
using CoordNT = Traits::CoordNT;
using Point = Traits::Point_2;
using Curve = Traits::Curve_2;
using Rational_point = Traits::Rational_point_2;
using Segment = Traits::Rational_segment_2;
using Circle = Traits::Rational_circle_2;
using Arrangement = CGAL::Arrangement_2<Traits>;
\endcode

The \link Arr_circle_segment_traits_2::Curve_2 `Curve_2`\endlink type
nested in `Arr_circle_segment_traits_2` can be used to represent
circles, circular arcs, or line segments. We now describe and
demonstrate a variety of ways in which the curves of this type can be
constructed. A Curve object can be constructed from a
`Kernel::Circle_2` object or from a `Kernel::Segment_2` object. A
circular arc is typically defined by a supporting circle and two
endpoints, where the endpoints are of type \link
Arr_circle_segment_traits_2::Point_2 `Point_2`\endlink, with rational
or irrational coordinates. The orientation of the arc is determined by
the orientation of the supporting circle. Similarly, we also support
the construction of line segments given their supporting line (of type
`Kernel::Line_2`) and two endpoints, which may have irrational
coordinates (unlike the `Kernel::Segment_2` type).

Note that the `Kernel::Circle_2` type is used to represent a circle
whose <em>squared radius</em> is rational, where the radius itself may
be irrational.  However, if the radius is known to be rational, its
use is recommended for efficiency. It is therefore also possible to
construct a circle, or a circular arc specifying the circle center (a
`Kernel::Point_2`), its rational radius (of type `Kernel::FT`), and
its orientation. Finally, we also support the construction of a
circular arc that is defined by two endpoints and an arbitrary
interior point that lies on the arc in between its endpoints. In this
case, all three points are required to have rational coordinates;
namely, they are all given as `Kernel::Point_2` objects.


\cgalFigureBegin{aos_fig-circular_arcs,circular_arcs.png}
An arrangement of two full circles, two line segments, and three
circular arcs as constructed in \ref
Arrangement_on_surface_2/circular_arcs.cpp. Endpoints are drawn as
red disks and intersection points are drawn as rings.
\cgalFigureEnd


The following example demonstrates the usage of the various
construction methods for circular arcs and line segments. The
resulting arrangement is depicted in
\cgalFigureRef{aos_fig-circular_arcs}. Note the usage of the
constructor of `CoordNT(alpha, beta, gamma)`, which creates a
degree-\f$2\f$ algebraic number whose value is \f$\alpha +
\beta\sqrt{\gamma}\f$.

\cgalExample{Arrangement_on_surface_2/circular_arcs.cpp}

It is also possible to construct \f$x\f$-monotone curve objects that
represent \f$x\f$-monotone circular arcs or line segments using
similar constructors. (Full circles are not \f$x\f$-monotone.)

The traits class-template
`Arr_circular_line_arc_traits_2<CircularKernel>` offered by the
arrangement package also handles circular arcs and line segments. It
is an alternative to the `Arr_circle_segment_traits_2<Kernel>`
class-template. These two class templates, while serve similar
purposes, are based on different concepts, and posses different
characteristics. You are encouraged to experiment with both, compare
their performance, and use the most suitable for your case.




\paragraph arr_sssectr_conic A Traits Class for Conic Arcs


A <em>conic curve</em> is an algebraic curve of degree 2. Namely, it
is the locus of all points \f$(x,y)\f$ satisfying the equation \f$c:\
r x^2 + s y^2 + t xy + u x + v y + w = 0\f$, where the six
coefficients \f$\langle r, s, t, u, v, w \rangle\f$ completely
characterize the curve. The sign of the expression \f$\Delta_{c} = 4 r
s - t^2\f$ determines the type of curve:

<UL>

<LI>If \f$\Delta_{c} > 0\f$, the curve is an ellipse. A circle is a
special case of an ellipse, where \f$r = s\f$ and \f$t = 0\f$.

<LI>If \f$\Delta_{c} = 0\f$, the curve is a parabola---an unbounded
conic curve with a single connected branch. When \f$r = s = t = 0\f$
we have a line, which can be considered as a degenerate parabola.

<LI>If \f$\Delta_{c} < 0\f$, the curve is a hyperbola. That is, it
comprises of two disconnected unbounded branches.

</UL>

The `Arr_conic_traits_2<RatKernel, AlgKernel, NtTraits>` class
template is capable of handling only bounded arcs of conic curves,
referred to as <em>conic arcs</em>. A conic arc \f$a\f$ may be either
(i) a full ellipse, or (ii) defined by the tuple \f$\langle \kappa,
p_s, p_t, o \rangle\f$, where \f$\kappa\f$ is a conic curve and
\f$p_s\f$ and \f$p_t\f$ are two points on \f$c\f$ (namely
\f$\kappa(p_s) = \kappa(p_t) = 0\f$) that define the <em>source</em>
and <em>target</em> of the arc, respectively. The arc is formed by
traversing \f$\kappa\f$ from the source to the target going in the
orientation specified by \f$o\f$, which is typically clockwise or
counterclockwise orientation, but may also be collinear in case of
degenerate conic conic-curves, namely, lines or pairs of lines.

We always assume that the conic coefficients \f$\langle r, s, t, u, v,
w \rangle\f$ are rational. The coordinates of points of intersection
between two conic curves with rational coefficients are in general
algebraic numbers of degree 4. Namely, they are roots of algebraic
polynomials of degree 4. In addition, conic arcs may not necessarily
be \f$x\f$-monotone, and must be split at points where the tangent to
the arc is vertical.  In the general case such points typically have
coordinates that are algebraic numbers of degree 2. Note that as
arrangement vertices induced by intersection points and points with
vertical tangents are likely to have algebraic coordinates, we also
allow the original endpoints of the input arcs \f$p_s\f$ and \f$p_t\f$
to have algebraic coordinates.

The `Arr_conic_traits_2<RatKernel, AlgKernel, NtTraits>` class
template is designed for efficient handling of arrangements of
bounded conic arcs. The template has three parameters, defined as
follows:

<UL>

<LI>The `RatKernel` template parameter must be substituted by a
geometric kernel whose field type is an exact rational type. It is
used to define basic geometric entities (e.g., a line segment or a
circle) with rational coefficients. Typically we use one of the
standard \cgal kernels, instantiated with the number type
`NtTraits::Rational` (see below).

<LI>The `AlgKernel` template parameter must be substituted by a
geometric kernel whose field type is an exact algebraic type. It is
used to define points with algebraic coordinates. Typically, we use
one of the standard \cgal kernels, instantiated with the number type
`NtTraits::Algebraic` (see below).

<LI>The `NtTraits` template parameter must be substituted by a type
that encapsulates all the numeric operations needed for performing
geometric computation carried out by the geometric traits class.  It
defines the `Integer`, `Rational`, and `Algebraic` number-types, and
supports several operations on these types, such as conversion between
these types, solving quadratic equations, and extracting the real
roots of polynomials with integer coefficients. The use of the
`CORE_algebraic_number_traits` class, which is included in the
arrangement package, is highly recommended. The traits class-template
relies on the multi-precision number types implemented in the \core
library and performs exact computations on the number types it
defines.

</UL>

The instantiation of the conic traits class-template is slightly more
complicated than the instantiation of the traits classes you have
encountered so far. This instantiation is exemplified in the header
file `arr_conics.h`. Note how we first define the rational and
algebraic kernels using the number types given by the \core number
type traits-class, then use them to define the conic traits
class-template. Also note the types defined by the rational kernels,
which we need for conveniently constructing conic arcs.

The `Arr_conic_traits_2` models the `AosTraits_2` and
`AosLandmarkTraits_2` concepts. Its \link
Arr_conic_traits_2::Point_2 `Point_2`\endlink type is derived from
`AlgKernel::Point_2`, while the \link Arr_conic_traits_2::Curve_2
`Curve_2`\endlink type represents a bounded, not necessarily
\f$x\f$-monotone, conic arc.  The \link
Arr_conic_traits_2::X_monotone_curve_2 `X_monotone_curve_2`\endlink
type is derived from \link Arr_conic_traits_2::Curve_2
`Curve_2`\endlink, but its constructors are used only by the traits
class.  Users should therefore construct only \link
Arr_conic_traits_2::Curve_2 `Curve_2`\endlink objects and insert them
into the arrangement using the `insert()` function.

Conic arcs are constructible from full ellipses or by specifying a
supporting curve, two endpoints, and an orientation. However, several
constructors of \link Arr_conic_traits_2::Curve_2 `Curve_2`\endlink
are available to allow for some special cases, such as circular arcs
or line segments. The \link Arr_conic_traits_2::Curve_2
`Curve_2`\endlink and the derived \link
Arr_conic_traits_2::X_monotone_curve_2 `X_monotone_curve_2`\endlink
classes also support basic access functions such as `source()`,
`target()`, and `%orientation()`.


\cgalFigureBegin{aos_fig-conics,conics.png}
An arrangement of mixed conic arcs, as constructed in conics.cpp
\cgalFigureEnd


The following example demonstrates the usage of the various
constructors for conic arcs. The resulting arrangement is depicted in
\cgalFigureRef{aos_fig-conics}. Especially noteworthy are the
constructor of a circular arc that accepts three points, the
constructor of a conic arc that accepts five points, and the
constructor that allows specifying approximate endpoints, where the
exact endpoints are given explicitly as intersections of the
supporting conic with two other conic curves. The approximate
endpoints are used to select the specific exact endpoints out of all
intersection points of the pair of curves (the supporting conic curve
and the auxiliary conic curve).  Also note that as the preconditions
required by some of these constructors are rather complicated (see the
Reference Manual for the details), a precondition violation does not
cause the program to terminate---instead, an <em>invalid</em> arc is
created. The call `a.is_valid()` verifies the validity of the arc
\f$a\f$. Naturally, inserting invalid arcs into an arrangement is not
allowed, so the validity of an arc should be checked once it is
constructed.

\cgalExample{Arrangement_on_surface_2/conics.cpp}

The types common to the example programs that use the
`Arr_conic_traits_2` class template are listed below and
defined in the header file `arr_conics.h`.

\code{.cpp}
#include <CGAL/Cartesian.h>
#include <CGAL/CORE_algebraic_number_traits.h>
#include <CGAL/Arr_conic_traits_2.h>
#include <CGAL/Arrangement_2.h>

using Nt_traits = CGAL::CORE_algebraic_number_traits;
using Rational = Nt_traits::Rational;
using Rat_kernel = CGAL::Cartesian<Rational>;
using Rat_point = Rat_kernel::Point_2;
using Rat_segment = Rat_kernel::Segment_2;
using Rat_circle = Rat_kernel::Circle_2;
using Algebraic = Nt_traits::Algebraic;
using Alg_kernel = CGAL::Cartesian<Algebraic>;
using Traits = CGAL::Arr_conic_traits_2<Rat_kernel, Alg_kernel, Nt_traits>;
using Point = Traits::Point_2;
using Conic_arc = Traits::Curve_2;
using X_monotone_conic_arc = Traits::X_monotone_curve_2;
using Arrangement = CGAL::Arrangement_2<Traits>;
\endcode


\cgalFigureBegin{aos_fig-conic_multiplicities,conic_multiplicities.png}
An arrangement of a circular arc and a hyperbolic arc, as constructed
in \ref Arrangement_on_surface_2/conic_multiplicities.cpp.
\cgalFigureEnd


The last example in this section demonstrates how the conic-traits
class can handle intersection points with multiplicity. The resulting
arrangement is depicted in
\cgalFigureRef{aos_fig-conic_multiplicities}. The supporting curves of
the two arcs, a circle centered at \f$(0,\frac{1}{2})\f$ with radius
\f$\frac{1}{2}\f$, and the hyperbola \f$y =
\frac{x^2}{1-x}\f$,\cgalFootnote{This curve can also be written as
\f$c: x^2 + xy - y = 0\f$. It is a hyperbola since \f$\Delta_{c} =
-1\f$.}  intersect at the origin such that the intersection point has
multiplicity \f$3\f$ (note that they both have the same horizontal
tangent at \f$(0,0)\f$ and the same curvature \f$1\f$). In addition,
they have another intersection point at
\f$(\frac{1}{2},\frac{1}{2})\f$ of multiplicity \f$1\f$.

\cgalExample{Arrangement_on_surface_2/conic_multiplicities.cpp}


\paragraph arr_sssectr_ratfunc A Traits Class for Arcs of Rational Functions


A <em>rational function</em> is given by the equation \f$y =
\frac{P(x)}{Q(x)}\f$, where \f$P\f$ and \f$Q\f$ are polynomials of
arbitrary degrees. In particular, if \f$Q(x) = 1\f$, then the
function is simply a polynomial function. A bounded <em>rational
arc</em> is defined by the graph of a rational function over some
interval \f$[x_{\rm min}, x_{\rm max}]\f$, where \f$Q\f$ does not have
any real roots in this interval (thus, the arc does not contain any
singularities). However, we may consider functions defined over
unbounded intervals, namely, over \f$(-\infty, x_{\max}]\f$,
\f$[x_{\min}, \infty)\f$, or \f$(-\infty, \infty)\f$. Rational
functions, and polynomial functions in particular, are not only
interesting in their own right, they are also useful for approximating
more complicated curves and for interpolation; see, e.g.,
\cgalCite{cgal:ptvf-nrcpp-02} Chapter 3.

Using the `Arr_rational_function_traits_2` class template it is
possible to construct and maintain arrangements induced by rational
arcs. Every instance of the `Arr_rational_function_traits_2` class
template models the concepts `AosTraits_2` and
`AosOpenBoundaryTraits_2`, but it does not model the
`AosLandmarkTraits_2` concept. It also models the refined
concept `AosDirectionalXMonotoneTraits_2`, which enables
Boolean set operations; see Package \ref PkgBooleanSetOperations2.
Note that it is not a model of `AosLandmarkTraits_2` concept,
so it is impossible to use the landmark point-location strategy with
this traits class.


\cgalFigureBegin{aos_fig-rat_func_singular,rational_function_singular.png}
An arrangement of an arc of a rational functions that has
singularities at \f$x = 1\f$ and at \f$x = 2\f$.
\cgalFigureEnd


A rational arc is always \f$x\f$-monotone in the mathematical sense.
However, it is not necessarily continuous, as it may have
singularities. An arc that has singularities must be split into
continuous portions before being inserted into the arrangement.
Consider, for example, the rational arc given by the equation \f$y =
\frac{1}{(x-1)(2-x)}\f$ defined over the interval \f$[0,3]\f$, as
depicted in \cgalFigureRef{aos_fig-rat_func_singular}. This arc has
two singularities, at \f$x = 1\f$ and at \f$x = 2\f$. It is split into
three continuous portions defined over the intervals \f$[0,1)\f$,
\f$(1,2)\f$, and \f$(2,3]\f$ by the traits operation \link
AosTraits_2::Make_x_monotone_2
`Make_x_monotone_2`\endlink. Arbitrary rational functions are
represented by the nested type \link
Arr_rational_function_traits_2::Curve_2 `Curve_2`\endlink and
continuous portions of rational functions are represented by the
nested type \link Arr_rational_function_traits_2::X_monotone_curve_2
`X_monotone_curve_2`\endlink.  Constructors for both types are
provided by the traits in form of functors.

When the `Arr_rational_function_traits_2<AlgebraicKernel_d_1>` class
template is instantiated, the template parameter must be substituted
by a model of the `AlgebraicKernel_d_1` concept. Models of this
concept, such as the `Algebraic_kernel_d_1<Coefficient>` class
template provided by the package \ref PkgAlgebraicFoundations are
meant to support algebraic functionalities on univariate polynomials
of arbitrary degree. See the documentation of the concept
`AlgebraicKernel_d_1` for more information. A rational function is
then represented as the quotient of two polynomials, \f$P\f$ and
\f$Q\f$, of type `Polynomial_1` nested in every model of the concept
`AlgebraicKernel_d_1` and in particular in the algebraic-kernel type
that substitutes the template parameter `AlgebraicKernel_d_1` when the
traits class-template is instantiated. Such a rational function is
constructible from a single polynomial \f$P\f$ (with \f$Q(x) = 1\f$),
or from two polynomials \f$P\f$ and \f$Q\f$. The type of the
polynomial coefficients, namely `Coefficient`, and the type of the
interval bounds, namely `Bound`, are also nested in the
algebraic-kernel type. If an instance of the
`Algebraic_kernel_d_1<Coefficient>` class template is used, for
example, as the algebraic-kernel type, the type that substitutes its
template parameter is defined as the `Coefficient` type. This type
cannot be algebraic. Moreover, it is recommended that this type is not
made rational either, since using rational (as opposed to integral)
coefficients does not extend the range of the rational arcs and is
typically less efficient.\cgalFootnote{The \cgalFootnoteCode{Algebraic_kernel_d_1}
class template uses the types provided by the \ref PkgPolynomial
package to define its nested \cgalFootnoteCode{Polynomial_1} type and conveniently
expose it to the user.} The `Bound` type, however, can be algebraic. A
point of type \link Arr_rational_function_traits_2::Point_2
`Point_2`\endlink nested in the `Arr_rational_function_traits_2` class
template is represented by a rational function and its
\f$x\f$-coordinate, which is derived from the type `Algebraic_real_1`
nested in the algebraic-kernel type. An explicit representation by the
nested type `Algebraic_real_1` of the \f$y\f$-coordinate is only
computed upon request, as it can be a rather costly operation.

The aforementioned types, `Polynomial_1`, `Coefficient`,
`Bound`, and `Algebraic_real_1`, are conveniently nested in
the `Arr_rational_function_traits_2` class template among
the others and obtained from there in the type definitions used
in the examples given in this section and listed below. These types
are defined in the header file `arr_rat_functions.h`.

\code{.cpp}
#include <CGAL/basic.h>
#include <CGAL/CORE_BigInt.h>
#include <CGAL/Algebraic_kernel_d_1.h>
#include <CGAL/Arr_rational_function_traits_2.h>
#include <CGAL/Arrangement_2.h>

using Number_type = CORE::BigInt;
using AK1 = CGAL::Algebraic_kernel_d_1<Number_type>;
using Traits = CGAL::Arr_rational_function_traits_2<AK1>;

using Polynomial = Traits::Polynomial_1;
using Alg_real = Traits::Algebraic_real_1;
using Bound = Traits::Bound;

using Arrangement = CGAL::Arrangement_2<Traits>;
\endcode

The constructed rational functions are cached by the traits class. The
cache is local to each traits class object. It is therefore necessary
to construct curves using only the constructor objects provided by
member functions of the traits class. Moreover, a curve must only be
used by the traits class object that was used to construct it. The
cache is automatically cleaned up from time to time. The amortized
clean up costs are constant. In addition, there is also a separate
member function that cleans up the cache upon request.


\cgalFigureBegin{aos_fig-rational_functions,rational_functions.png}
An arrangement of four arcs of rational functions, as constructed in
\ref Arrangement_on_surface_2/rational_functions.cpp.
\cgalFigureEnd


The following example demonstrates the construction of an arrangement
induced by rational arcs depicted in
\cgalFigureRef{aos_fig-rational_functions}. It uses constructors both
for polynomial arcs and for rational arcs.

\cgalExample{Arrangement_on_surface_2/rational_functions.cpp}


\cgalFigureBegin{aos_fig-unbounded_rational_functions,unbounded_rational_functions.png}
An arrangement of six arcs of rational functions, as constructed in
\ref Arrangement_on_surface_2/unbounded_rational_functions.cpp.
\cgalFigureEnd


The following example demonstrates the construction of an arrangement
of six rational arcs, four unbounded arcs and two bounded ones, as
depicted in \cgalFigureRef{aos_fig-unbounded_rational_functions}. Note
the usage of the constructors of an entire rational function and of an
infinite "ray" of such a function. Also observe that the hyperbolas
\f$y = \pm\frac{1}{x}\f$ and \f$y = \pm\frac{1}{2x}\f$ never
intersect, although they have common vertical and horizontal
asymptotes, so very "thin" unbounded faces are created between them:

\cgalExample{Arrangement_on_surface_2/unbounded_rational_functions.cpp}

The curve constructors have an additional advantage. They conveniently
enable the provision of two polynomials that define a rational arc
using rational coefficients. For example, let \f$P\f$ and \f$Q\f$
denote two polynomials with integral coefficients that define a
rational arc of interest, and let \f$P'\f$ and \f$Q'\f$ denote two
polynomials with rational coefficients that define the same rational
arc; that is, the quotients \f$P/Q\f$ and \f$P'/Q'\f$ are
identical. You can construct the rational arc providing the
coefficients of \f$P'\f$ and \f$Q'\f$ to the constructor. In this case
the constructor normalizes the coefficients and generates the desired
polynomials \f$P\f$ and \f$Q\f$. To this end, the curve constructors
of both types, namely \link Arr_rational_function_traits_2::Curve_2
`Curve_2`\endlink and \link
Arr_rational_function_traits_2::X_monotone_curve_2
`X_monotone_curve_2`\endlink, have operators that accept ranges of
polynomial coefficients as well as polynomials. The coefficients in a
given range must be in the order of the degrees of the corresponding
variables starting from the constant term.


\paragraph arr_sssectr_bez A Traits Class for Planar B&eacute;zier Curves


A planar <em>B&eacute;zier curve</em> \f$B\f$ is a parametric curve
defined by a sequence of <em>control points</em> \f$p_0, \ldots,
p_n\f$ as follows:

\f{eqnarray*}{
B(t) = \left(X(t), Y(t)\right)
= \ccSum{k=0}{n}{p_k \cdot \frac{n!}{k! (n-k)!} \cdot
t^k (1-t)^{n-k}}\ .
\f}

where \f$t \in [0, 1]\f$. The degree of the curve is therefore \f$n\f$;
namely, \f$X(t)\f$ and \f$Y(t)\f$ are polynomials of degree
\f$n\f$. B&eacute;zier curves have numerous applications in computer
graphics and solid modeling. They are used, for example, in free-form
sketches and for defining the true-type fonts.

Using the `Arr_Bezier_curve_traits_2<RatKernel, AlgKernel, NtTraits>`
class template you can construct and maintain arrangements induced by
B&eacute;zier curves (including self-intersecting B&eacute;zier
curves) of arbitrary degree. The curves are given by rational control
points, that is, a sequence of objects of the `RatKernel::Point_2`
type.  (In general, a sequence of \f$n+1\f$ control points define a
B&eacute;zier curve of degree \f$n\f$.)  The three types that
substitute the template parameters `RatKernel`, `AlgKernel`, and
`NtTraits`, respectively, when the traits is instantiated must fulfill
the same requirements of the corresponding types used to instantiate
the `Arr_conic_traits_2` class template. Here, the use of the
`CORE_algebraic_number_traits` class is also recommended with
%Cartesian kernels instantiated with the `Rational` and `Algebraic`
number types defined by this class. The examples given in this manual
use the type definitions listed below. These types are defined in the
header file `arr_Bezier.h`.

\code{.cpp}
#include <CGAL/Cartesian.h>
#include <CGAL/CORE_algebraic_number_traits.h>
#include <CGAL/Arr_Bezier_curve_traits_2.h>
#include <CGAL/Arrangement_2.h>

using Nt_traits = CGAL::CORE_algebraic_number_traits;
using NT = Nt_traits::Rational;
using Rational = Nt_traits::Rational;
using Algebraic = Nt_traits::Algebraic;
using Rat_kernel = CGAL::Cartesian<Rational>;
using Alg_kernel = CGAL::Cartesian<Algebraic>;
using Rat_point = Rat_kernel::Point_2;
using Traits =
  CGAL::Arr_Bezier_curve_traits_2<Rat_kernel, Alg_kernel, Nt_traits>;
using Bezier_curve = Traits::Curve_2;
using Arrangement = CGAL::Arrangement_2<Traits>;
\endcode

As mentioned above, we assume that the coordinates of all control
points that define a B&eacute;zier curve are rational numbers, so both
\f$X(t)\f$ and \f$Y(t)\f$ are polynomials with rational
coefficients. The intersection points between curves are, however,
algebraic numbers, and their exact computation is time-consuming. The
traits class therefore contains a layer of geometric filtering that
performs all computations in an approximate manner whenever
possible. Thus, it resorts to exact computations only when the
approximate computation fails to produce an unambiguous result. Most
arrangement vertices are therefore associated with approximated
points. You cannot access the coordinates of such points as algebraic
numbers. However, access to the approximate coordinates is possible.
See the Reference Manual for the exact interface of the \link
Arr_Bezier_curve_traits_2::Point_2 `Point_2`\endlink, \link
Arr_Bezier_curve_traits_2::Curve_2 `Curve_2`\endlink, and \link
Arr_Bezier_curve_traits_2::X_monotone_curve_2
`X_monotone_curve_2`\endlink types defined by the traits class.

Every instance of the `Arr_Bezier_curve_traits_2` class templates
models the concept `AosTraits_2` (but it does not model the
`AosLandmarkTraits_2` concept). It also models the refined
concept `AosDirectionalXMonotoneTraits_2`, which enables
Boolean set operations; see Package \ref PkgBooleanSetOperations2.


\cgalFigureBegin{aos_fig-bezier_curves,bezier_curves.png}
An arrangement of ten B&eacute;zier curves of degree \f$5\f$, as
constructed in \ref Arrangement_on_surface_2/Bezier_curves.cpp.
\cgalFigureEnd


The following example reads a set of B&eacute;zier curves from an
input file, where each file is specified by an integer stating its
number of control points, followed by the sequence of control points
given as integer or rational coordinates. By default, the program uses
the `Bezier.dat` file, which contains ten curves of degree \f$5\f$
each; their resulting arrangement is depicted in
\cgalFigureRef{aos_fig-bezier_curves}.

\cgalExample{Arrangement_on_surface_2/Bezier_curves.cpp}


\paragraph arr_sssectr_alg A Traits Class for Planar Algebraic Curves of Arbitrary Degree


The traits class, namely `Arr_algebraic_segment_traits_2`, is based on
the `Algebraic_kernel_d_1` class template, which models the
algebraic-kernel concept `AlgebraicKernel_d_1`; see Section \ref
arr_sssectr_ratfunc. The traits class handles (i) algebraic curves and
(ii) continuous (weakly) \f$x\f$-monotone segments of algebraic
curves, which, however, are not necessarily maximal. (A formal
definition is given below.)  Observe that non-\f$x\f$-monotone
segments are not supported. Still, it is the traits class that
supports the most general type of curves among the traits classes
included in the package.

Recall that an algebraic curve \f$c\f$ in the plane is defined as the
(real) zero set of a bivariate polynomial \f$f(x,y)\f$. The curve is
uniquely defined by \f$f\f$, although several polynomials might define
the same curve.  We call \f$f\f$ a <em>defining polynomial</em> of
\f$c\f$.

A formal definition of (weakly) \f$x\f$-monotone segments of algebraic
curves follows. A point \f$p\f$ on a curve \f$c_f \subset \mathbb{R}^2\f$
(with defining polynomial \f$f\f$) is called <em>semi-regular</em> if,
locally around \f$p\f$, the curve \f$c_f\f$ can be written as a
function graph of some continuous function in \f$x\f$ or in
\f$y\f$. (We also say that \f$p\f$ is parameterizable in \f$x\f$ or
\f$y\f$, respectively.)  The only two cases of non-semi-regular points
are isolated points and self-intersections. A <em>segment</em> of a
curve in this context is a closed and continuous point set such that
each interior point is semi-regular. It follows that a segment is
either vertical or a closed connected point set, with all interior
points parameterizable in \f$x\f$.

Every instance of the `Arr_algebraic_segment_traits_2<Coefficient>`
class template models the `AosTraits_2` and
`AosOpenBoundaryTraits_2` concepts (but it does not model the
`AosLandmarkTraits_2` concept).  The template argument
`Coefficient` determines the type of the scalar coefficients of the
polynomial.  Currently supported integral number types are `Gmpz`,
`leda_integer`, and `CORE::BigInt`. This is reflected in the
statements included in the header file `integer_type.h`, the listings
of which are omitted here. This header file is used by the two example
programs listed in this section. The template parameter `Coefficient`
can be substituted in addition by an instance of the
`Sqrt_extension<A,B>` class template, where the template parameters
`NT` and `Root` are substituted in turn by one of the integral
number types above. Finally, the template parameter `Coefficient` can
be substituted also by a rational number type, where the type of the
numerator and denominator is one of the types above.

The type \link Arr_algebraic_segment_traits_2::Curve_2
`Curve_2`\endlink nested in the `Arr_algebraic_segment_traits_2` class
template defines an algebraic curve. An object of this type can be
constructed by the \link
Arr_algebraic_segment_traits_2::Construct_curve_2
`Construct_curve_2`\endlink functor also nested in the class
template. Its function operator accepts as an argument an object of
type \link Arr_algebraic_segment_traits_2::Polynomial_2
`Polynomial_2`\endlink, nested as well in the traits class-template.
The type \link Arr_algebraic_segment_traits_2::Polynomial_2
`Polynomial_2`\endlink models the concept `Polynomial_d`. An object of
the nested type \link Arr_algebraic_segment_traits_2::Polynomial_2
`Polynomial_2`\endlink represents a bivariate polynomial. It can be
constructed in a few convenient ways, some are exemplified by the
programs listed below. Consult the reference guide for the complete
set of options.


\cgalFigureBegin{aos_fig-algebraic_curves,algebraic_curves.png}
An arrangement of algebraic curves of degrees \f$1\f$, \f$2\f$,
\f$3\f$, and \f$6\f$, as constructed in
\ref Arrangement_on_surface_2/algebraic_curves.cpp.
\cgalFigureEnd


The following examples computes the arrangement depicted in
\cgalFigureRef{aos_fig-algebraic_curves}. The arrangement is induced
by four algebraic curves, \f$c_1\f$, \f$c_2\f$, \f$c_3\f$, and
\f$c_4\f$, of degrees \f$1\f$, \f$2\f$, \f$3\f$, and \f$6\f$,
respectively. For each curve the defining polynomial is constructed
first. Then, the algebraic curve is constructed using the \link
Arr_algebraic_segment_traits_2::Construct_curve_2
`Construct_curve_2`\endlink functor.  Finally, the curve is inserted
into the arrangement.

\cgalExample{Arrangement_on_surface_2/algebraic_curves.cpp}

The `Arr_algebraic_segment_traits_2` class template carries state to
expedite some of its computations. Thus, it is essential to have only
one copy of the traits object during the life time of a program that
utilizes this traits class. To this end, the example above uses the
constructor of the `Arrangement_2` data structure that accepts the traits
object as input. Carrying state is not a unique property of the
`Arr_algebraic_segment_traits_2` class template; it is common to many
traits classes, especially to traits classes that handle algebraic
curves.  Therefore, as a general rule, if your application requires
direct access to a traits object, define it locally, and pass it to
the constructor of the `Arrangement_2` data structure to avoid the
construction of a duplicate traits-class object.

A weakly \f$x\f$-monotone segment of an algebraic curve is represented
by the \link Arr_algebraic_segment_traits_2::X_monotone_curve_2
`X_monotone_curve_2`\endlink type nested in the traits
class-template. You can construct such segments in two ways as
follows: (i) using the \link AosTraits_2::Make_x_monotone_2
`Make_x_monotone_2`\endlink functor or (ii) using the \link
Arr_algebraic_segment_traits_2::Construct_x_monotone_segment_2
`Construct_x_monotone_segment_2`\endlink functor.  Both functors are
nested in the traits class-template. The former is required by the
concept `AosTraits_2` our traits class models; see Section
\ref aos_sssec-geom_traits-concepts_arbitrary. The latter enables the
construction of individual segments. The \link
Arr_algebraic_segment_traits_2::X_monotone_curve_2
`X_monotone_curve_2`\endlink type represents weakly \f$x\f$-monotone
segments of a curve; however, for technical reasons, segments may need
to be further subdivided into several sub-segments, called terminal
segments. Therefore, \link
Arr_algebraic_segment_traits_2::Construct_x_monotone_segment_2
`Construct_x_monotone_segment_2`\endlink constructs a sequence of
\link Arr_algebraic_segment_traits_2::X_monotone_curve_2
`X_monotone_curve_2`\endlink objects, whose union represents the
desired weakly \f$x\f$-monotone segment. The function operator of the
\link Arr_algebraic_segment_traits_2::Construct_x_monotone_segment_2
`Construct_x_monotone_segment_2`\endlink functor accepts as arguments
the underlying algebraic curve, the leftmost point of the segment, the
rightmost point of the segment, and an output iterator associated with
a container of output terminal segments. The function operator is
overloaded. In addition to the variant above, there is one that
accepts the underlying algebraic curve, a single point \f$p\f$, an
enumerator that delimits the segment, and an output iterator. It
returns the maximal \f$x\f$-monotone segment that contains
\f$p\f$. The enumerator specifies whether \f$p\f$ is interior to the
returned segment, its left endpoint, or its right endpoint. The third
variant accepts only two delimiting points and an output iterator. It
constructs line segments.

\cgalAdvancedBegin The subdivision terminal segments is due to the
internal representation of \f$x\f$-monotone segments, which is based
on a vertical decomposition.  We assume the defining polynomial
\f$f\f$ of the curve \f$c\f$ to be <em>square-free</em>. That is, it
contains no divisor \f$g^2\f$ of total degree greater than zero. We
define a <em>(complex) critical point</em> \f$p\in\mathbb{C}^2\f$ by
\f[ f(p)=0=\frac{\partial f}{\partial y}(p). \f] An \f$x\f$-coordinate
\f$\alpha\in\mathbb{R}\f$ is <em>critical</em> either if some critical
point has \f$x\f$-coordinate \f$\alpha\f$, or if the leading
coefficient of \f$f\f$, considered as a polynomial in \f$y\f$,
vanishes. In particular, vertical lines and isolated points of \f$c\f$
can only take place at critical \f$x\f$-coordinates.  Between two
consecutive critical \f$x\f$-coordinates the curve decomposes into a
finite number of \f$x\f$-monotone segments (the same holds to the left
of the leftmost, and to the right of the rightmost critical
\f$x\f$-coordinate).  The type \link
Arr_algebraic_segment_traits_2::X_monotone_curve_2
`X_monotone_curve_2`\endlink is only capable of representing such
segments (and sub-segments of them). Formally, a terminal segment is
either a vertical line-segment or a segment of an \f$x\f$-monotone
curve whose \f$x\f$-range does not contain critical points in its
interior. See \cgalFigureRef{aos_fig-algebraic_curves_decomposition}
for an example of a quartic curve and its decomposition into terminal
segments.  Notice that six vertices split the curve into
\f$x\f$-monotone segments, and four additional vertices further split
the corresponding \f$x\f$-monotone segments into terminal segments.
\cgalAdvancedEnd


\cgalFigureBegin{aos_fig-algebraic_curves_decomposition,algebraic_curves_decomposition.png}

The critical \f$x\f$-coordinates of an algebraic curve (dashed
lines), and its decomposition into terminal segments (in different
colors). The segment from \f$p\f$ to \f$q\f$ consists of the union
of three terminal segments.
\cgalFigureEnd


The type `Algebraic_real_1` must be defined by any model of the
`AlgebraicKernel_d_1` concept. The traits class-template
`Arr_algebraic_segment_traits_2` exploits an instance of the
`Algebraic_kernel_d_1` class template, which models the concept
`AlgebraicKernel_d_1`. The exploited instance is nested in the traits
class-template. You can use this model to create algebraic numbers as
roots of univariate polynomials, and process them, for instance,
compare them or approximate them to any precision. See the
documentation of the concept `AlgebraicKernel_1` for more information.
Coordinates of points are represented by the type `Algebraic_real_1`
nested in the traits class-template. This type is defined as the
corresponding type nested in the instance of `Algebraic_kernel_d_1`.

You can construct an object of type \link
Arr_algebraic_segment_traits_2::Point_2 `Point_2`\endlink using the
\link Arr_algebraic_segment_traits_2::Construct_point_2
`Construct_point_2`\endlink functor nested in the traits
class-template. Its function operator is overloaded with a couple of
variants that accepts the \f$x\f$ and \f$y\f$ coordinates of the
point. Their types must be either `Algebraic_real_1` or
`Coefficient`. Another efficient variant accepts a triple
\f$(x_0,c,i)\f$, which identifies the \f$i\f$-th point (counted from
below) in the fiber of \f$c\f$ at the \f$x\f$-coordinate
\f$x_0\f$. \cgalFootnote{The fiber of a curve \f$c\f$ at some
\f$x\f$-coordinate \f$x'\f$ is the set of all points on \f$c\f$ with
\f$x\f$-coordinate \f$x'\f$.  Formally, for a curve \f$c\f$ and \f$x'
\in \mathbb{R}\f$, the fiber of \f$c\f$ at \f$x'\f$ is \f$c \cap
\{(x',b)\,|\,b \in \mathbb{R}\}\f$.} In the example depicted in
\cgalFigureRef{aos_fig-algebraic_curves_decomposition}, if \f$x_1\f$
denotes the \f$x\f$-coordinate of \f$p\f$, and \f$c\f$ represents the
algebraic curve, then \f$p\f$ could be represented by
\f$(x_1,c,3)\f$. If \f$x_2\f$ is the \f$x\f$-coordinate of \f$q\f$,
then \f$(x_2,c,1)\f$ is a valid representation of \f$q\f$. Points are
represented internally using the triple described above. Although the
\f$y\f$-coordinate of a point represented by an object of the nested
type `Algebraic_real_1` can be obtained, we advise caution with that
option, since computing an explicit representation of the
\f$y\f$-coordinate can be rather expensive.


\cgalFigureBegin{aos_fig-algebraic_segments,algebraic_segments.png}
An arrangement of algebraic segments (solid lines), as constructed in
\ref Arrangement_on_surface_2/algebraic_segments.cpp. The supporting
curves are drawn as dashed lines.
\cgalFigureEnd


The following code exemplifies the method to construct points and the
various methods to construct algebraic segments. The computed
arrangement is depicted in \cgalFigureRef{aos_fig-algebraic_segments}.

\cgalExample{Arrangement_on_surface_2/algebraic_segments.cpp}


\subsubsection arr_ssectr_spherical Arcs of Great Circles Embedded in the Sphere


A great circle of a sphere is the intersection of the sphere and a
plane that passes through the center point of the sphere. For all
pairs of distinct points on the sphere except for antipodal points,
there is a unique great circle through the two points. There are
infinitely many great circles through antipodal points. The minor arc
of a great circle between two points is the shortest spherical-path
between them. In this sense, minor arcs are analogous to line
segments in Euclidean geometry.

The `Arr_geodesic_arc_on_sphere_traits_2<Kernel,X,Y>` class template
handles arcs of great circles (also known as geodesic arcs) of a unit
sphere (centered at the origin in \f$\mathbb{R}^3\f$). It is a model of the
concept `AosSphericalBoundaryTraits_2`; see Section \ref
aos_ssec-traits-curved. An arrangement type (an instance of the
template `Arrangement_on_surface_2<GeomTraits, TopolTraits>`) that
uses an instance of this traits class as the geometry traits must use
a matching topology traits.  Currently, this package provides one
template, namely, `Arr_spherical_topology_traits_2<GeometryTraits_2,
Dcel>` an instance of which can be used as the topology traits.

The unit sphere is defined over a parameter space \f$\Phi =
[\tau,2\pi+\tau] \times [-\frac{\pi}{2}, \frac{\pi}{2}]\f$, where
\f$\tau = \arctan(X, Y)\f$. By default, \f$X = -1, Y = 0\f$, which
implies \f$\tau = -\pi\f$, which implies a default parameterization
\f$\Phi = [-\pi, \pi] \times [-\frac{\pi}{2}, \frac{\pi}{2}]\f$. The
equator curve, for example, is given by \f$\gamma(t) = (2t\pi + \tau,
0)\f$, for \f$t \in [0,1]\f$. The surface is given by
\f$\phi_S(\alpha,\beta) = (\cos \alpha \cos \beta, \sin \alpha \cos
\beta, \sin \beta)\f$; see Section \ref aos_sec-curved_surfaces for
more details. This parameterization induces two contraction points
\f$(0,0,-1) = \phi_S(\alpha,-\frac{\pi}{2})\f$ and \f$(0,0,1) =
\phi_S(\alpha,\frac{\pi}{2})\f$, for all \f$\alpha\f$, referred to as
the south and north poles, respectively, and an identification curve
\f$\{\phi_S(\alpha,\beta)\,|\,-\frac{\pi}{2} \leq \beta \leq
\frac{\pi}{2}\}\f$, as \f$\phi_S(\pi,\beta) = \phi_S(2\pi +
\tau,\beta)\f$ for all \f$\beta\f$. When \f$\tau = -\pi\f$ (the
default), the identification curve coincides with the opposite Prime
(Greenwich) Meridian. In other words, the left and right boundary
sides of the parameter space are identified and the top and bottom
boundary sides are contracted.  The arguments that substitute the
template parameters `X` and `Y` when
`Arr_geodesic_arc_on_sphere_traits_2<Kernel, X, Y>` is instantiated
determine the value of \f$\tau\f$. Essentially, overriding their default
values rotates the identification curve about the vertical axes of the
image coordinate system (that is, the sphere coordinate system). These
arguments must be integral values. They define a not-necessarily
normalized vector \f$(x,y)\f$ in the \f$xy\f$-plane in the image
coordinate system, that bisects the identification curve. The explicit
expression for the surface above is not used at all in the
implementation of the traits. Indeed, all the required geometric
operations listed in the traits concept are implemented using only
rational arithmetic.

The following example constructs an arrangement induced by 12 arcs of
great circles embedded in the sphere. The arrangement is depicted in
\cgalFigureRef{spherical_insert}.


\cgalFigureBegin{spherical_insert,spherical_insert.png}
An arrangement induced by 12 arcs of great circles, as constructed in
\ref Arrangement_on_surface_2/spherical_insert.cpp. The number of
vertices, edges, and faces of the arrangement is 7, 13, and 8,
respectively. The intersection of the curve \f$(-1,0,0),(0,1,0)\f$
with the identification curve induces a vertex at
\f$(\frac{-11}{\sqrt{11^2+7^2}},\frac{7}{\sqrt{11^2+7^2}},0)\f$ drawn
in green. The north and south poles are drawn as little spheres. The
identification curve is drawn as a gray tube.
\cgalFigureEnd


\cgalExample{Arrangement_on_surface_2/spherical_insert.cpp}

Use the `Arr_geodesic_arc_on_sphere_traits_2::Construct_point_2`,
`Arr_geodesic_arc_on_sphere_traits_2::Construct_x_monotone_curve_2`,
and `Arr_geodesic_arc_on_sphere_traits_2::Construct_curve_2` functors
to construct a point, an \f$X\f$-monotone curve and a curve objects,
respectively. Observe that an \f$X\f$-monotone curve cannot intersect
the identification curve in its interior. A curve can be constructed
from either (i) two endpoints, (ii) two endpoints and a normal, or
(iii) a normal. The two endpoints determine the plane. The normal
determines the orientation of the plane and the final arc (whether it
is the minor arc or the major arc). If the normal is not provided, the
minor arc is constructed. If a curve is constructed and only the
normal is provided a full great circle is constructed. If an
\f$X\f$-monotone curve is constructed and only the normal is provided
an arc that resembles a full circle is constructed; this arc has one
endpoint that lies on the identification curve; this point is
considered both the source and target (and also the left and right)
point of the arc. See \cgalFigureRef{aos_fig-right_hand_rule} for an
illustration of the right-hand rule, which depicts the relation
between the arc and the normal.


\cgalFigureBegin{aos_fig-right_hand_rule,right_hand_rule.png}
To use the right hand rule, point your right thumb in the direction of
the normal and curl your fingers in the direction of the arc starting
with source endpoint and ending at the target endpoint.
\cgalFigureEnd



\subsection arr_ssec_tr_decorators Traits-Class Decorators


Decorator is a structural pattern that allows adding new behaviors to
objects by placing them inside special wrapper objects, called
decorators. One type of decorators attaches auxiliary data to the
geometric objects handled by the original traits. Another type enables
the retrieval of debugging and informative metadata.


\subsubsection arr_sssec_tr_data_decorators Data Decorators


Geometric traits-class decorators allow you to attach auxiliary data
to the geometric objects (curves and to points). The data is
automatically manipulated by the decorators and distributed to the
constructed geometric entities. Additional information can
alternatively be maintained by extending the vertex, halfedge, or face
types provided by the \dcel class used by the arrangement; see
Section \ref arr_ssecex_dcel for details. In many cases, however, it is
convenient to attach the data to the curve itself, exploiting the
automatic proliferation of the additional data fields from each curve
to all its induced subcurves. Moreover, as two halfedges are
associated with a single curve, storing the data once in the curve
record either saves space or avoids an indirect access from one
halfedge to its twin.

The \ref PkgArrangementOnSurface2 package includes a traits-class
decorator used to attach a data field to curves and to
\f$x\f$-monotone curves. It is a class template named
`Arr_curve_data_traits_2<BaseTraits, XMonotoneCurveData, Merge,
CurveData, Convert>` parameterized by a base-traits class, which must
be substituted by one of the geometric traits models described in
the previous subsections or with a user-defined traits model, when the
decorator is instantiated. The curve-data decorator derives from the
base-traits class, and in particular inherits its \link
Arr_curve_data_traits_2::Point_2 `Point_2`\endlink type. The remaining
nested types are defined as follows:

<UL>

<LI>\link Arr_curve_data_traits_2::Curve_2 `Curve_2`\endlink is
  derived from the basic `BaseTraits::Curve_2` class, extending it by
  an extra field of type `CurveData`.

<LI>\link Arr_curve_data_traits_2::X_monotone_curve_2
  `X_monotone_curve_2`\endlink is derived from the basic
  `BaseTraits::X_monotone_curve_2` class, extending it by an extra
  field of type `XMonotoneCurveData`, which must model the concepts
  CopyConstructible, EqualityComparable, and DefaultConstructible.
  The latter ensures that every instance of the class template
  `Arr_curve_data_traits_2` obtained by substituting the `BaseTraits`
  template parameter with a model of the `AosLandmarkTraits_2`
  concept models the `AosLandmarkTraits_2` concept as well

</UL>

Note that the nested \link Arr_curve_data_traits_2::Curve_2
`Curve_2`\endlink and \link
Arr_curve_data_traits_2::X_monotone_curve_2
`X_monotone_curve_2`\endlink are not the same, even if the
`BaseTraits::Curve_2` and `BaseTraits::X_monotone_curve_2` are (as in
the case of the segment-traits class, for example). The extended curve
types support the additional methods \link
CGAL::Arr_curve_data_traits_2<Tr, XData, Mrg, CData,
Cnv>::Curve_2::data() `data()`\endlink and \link
CGAL::Arr_curve_data_traits_2<Tr, XData, Mrg, CData,
Cnv>::Curve_2::set_data() `set_data()`\endlink for accessing and
modifying the data field.

You can create an extended curve (or an extended \f$x\f$-monotone curve)
from a basic curve and a curve-data object. When curves are
inserted into an arrangement, they may be split, and the
decorator handles their data fields automatically  as follows:

<UL>

<LI>When a curve is subdivided into \f$x\f$-monotone subcurves, its
  data field of type `CurveData` is converted to an object of type
  `XMonotoneCurveData` using the `Convert` functor. The object is
  automatically associated with each of the resulting \f$x\f$-monotone
  subcurves.

  Note that by default, the `CurveData` type is identical to the
  `XMonotoneCurveData` type (and the conversion functor `Convert` is
  trivially defined). Thus, the data field associated with the
  original curve is just duplicated and stored with the
  \f$x\f$-monotone subcurves.

<LI>When an \f$x\f$-monotone curve is split into two (typically, when
  it intersects another curve), the decorator class automatically
  copies its data field to both resulting subcurves.

<LI>When two \f$x\f$-monotone curves, \f$c_1\f$ and \f$c_2\f$,
intersect, the result may include overlapping sections represented as
\f$x\f$-monotone curves. In this case the data fields of \f$c_1\f$ and
\f$c_2\f$ are merged into a single `XMonotoneCurveData` object using
the `Merge` functor, which is supplied as a parameter to the traits
class-template. The resulting object is assigned to the data field of
the overlapping subcurves.

<LI>Merging two \f$x\f$-monotone curves is allowed only when (i) the
two curves are geometrically mergeable---that is, the base-traits
class allows to merge them, and (ii) the two curves store the same
data field.

</UL>

Another decorator supported by the \ref PkgArrangementOnSurface2
package is the `Arr_consolidated_curve_data_traits_2<BaseTraits,
Data>` class template. It derives from the `Arr_curve_data_traits_2`
class template, and it extends the basic type `BaseTraits::Curve_2` by
a single `Data` field, and the basic `BaseTraits::X_monotone_curve_2`
with a <em>set</em> of (distinct) data objects. The `Data` type must
model the concept `EqualityComparable` to ensure that each set
contains only distinct data objects with no duplicates. When a curve
with a data field \f$d\f$ is subdivided into \f$x\f$-monotone
subcurves, each subcurve is associated with a set \f$S = \{d\}\f$. In
the case of an overlap between two \f$x\f$-monotone curves \f$c_1\f$
and \f$c_2\f$ with associated data sets \f$S_1\f$ and \f$S_2\f$,
respectively, the overlapping subcurve is associated with the
consolidated set \f$S_1 \cup S_2\f$.


\cgalFigureBegin{aos_fig-consolidated_curve_data,consolidated_curve_data.png}
An arrangement of six red and blue segments, as constructed in \ref
Arrangement_on_surface_2/consolidated_curve_data.cpp. Disks correspond
to red-blue intersection points, while circles mark the endpoints of
red-blue overlaps.
\cgalFigureEnd


The following example uses `Arr_segment_traits_2` as the base-traits
class, attaching an additional <em>color</em> field to the segments
using the consolidated curve-data traits class. A color may be either
<em>blue</em> or <em>red</em>. Having constructed the arrangement of
colored segments, as depicted in
\cgalFigureRef{aos_fig-consolidated_curve_data}, we detect the
vertices that have incident edges mapped to both blue and red
segments. These vertices, drawn as black discs in the figure,
correspond to red-blue intersection points. We also locate the edge
that corresponds to overlap between a red and a blue line segment (its
endpoints are also drawn as black discs)

\cgalExample{Arrangement_on_surface_2/consolidated_curve_data.cpp}


\cgalFigureBegin{aos_fig-generic_curve_data,generic_curve_data.png}
An arrangement of four polylines, named A-D, as constructed in
\ref Arrangement_on_surface_2/generic_curve_data.cpp.
\cgalFigureEnd


The following example uses `Arr_polyline_traits_2` as the base-traits
class, attaching an additional <em>name</em> field to each polyline
using the generic curve-data traits class. It constructs an
arrangement of four polylines, named \f$A\f$, \f$B\f$, \f$c\f$, and
\f$D\f$, as illustrated in
\cgalFigureRef{aos_fig-generic_curve_data}.  In the case of
overlaps, it simply concatenate the names of the overlapping
polylines. At the end of the program the curve associated with the
edges that correspond to overlapping polylines are replaced with
geometrically equivalent curves, but with different data fields.

\cgalExample{Arrangement_on_surface_2/generic_curve_data.cpp}

The third example we give in this section is based on \ref
Arrangement_on_surface_2/dual_lines.cpp given in Section \ref
arr_ssec-unb_duality. It constructs the arrangement of the dual lines
for a set of point given in an input file (by default we use
`coll_points.dat`, which contains \f$50\f$ points randomly selected on
the grid \f$[-100,100]\times[-100,100]\f$; the file contains two
distinct triplets of collinear points). Here we use the generic
curve-data decorator to attach the index of the primal point to each
of the lines.  Doing so, we can go over the incident edges of each
vertex whose degree is greater than \f$4\f$ and report the subsets of
collinear points (if we have a vertex of degree \f$d\f$, we actually
need to go over \f$\frac{d}{2}\f$ edges, as each incident line
contributes exactly \f$2\f$ edges). Note that in this case the dual
line cannot overlap, so we use a dummy merge functor to instantiate
the curve-data traits:

\cgalExample{Arrangement_on_surface_2/dual_with_data.cpp}


\subsubsection arr_sssec_tr_metadata_decorators Metadata Decorators


The package provides two traits-class decorators, namely
`Arr_counting_traits_2<BaseTraits>` and
`Arr_tracing_traits_2<BaseTraits>`, that can be used to insert
debugging and informative metadata to an output stream. The former is
used to count the number of invocations of traits-class functors, and
the latter is used to trace these invocations. Note that the
constructors of each of these class templates apply perfect
forwarding. The counting traits also exports the count of traits-class
objects of specific types constructed during the execution of the
program. The tracing traits supports filtering of traced functors. The
calls `traits.enable_trace(id)` and `traits.disable_trace(id)` enables
and disables the tracing of a functor identified by `id`,
respectively. A functor is identified by an enumeration. For example,
the functor \link AosTraits_2::Make_x_monotone_2
`Make_x_monotone_2`\endlink is identified by the enumeration
`Arr_tracing_traits_2::MAKE_X_MONOTONE_OP`. The calls
`traits.enable_all_traces()` and `traits.disable_all_traces()` enables
and disables the traces of all functors, respectively. The example
program listed below demonstrates the use of both of these metadata
decorators.

\cgalExample{Arrangement_on_surface_2/count_and_trace.cpp}


\section aos_sec-topol_traits The Topology Traits

A topology traits class encapsulates the definitions of the
topological entities and the implementation of the functions that
handle these topological entities, used by the
`Arrangement_on_surface_2<GeometryTraits_2, TopologyTraits>` class
template and by the peripheral modules. Every topology traits class
must model the basic concept `AosBasicTopologyTraits`. A model
of this basic concept holds the (\dcel) data structure used to
represent the arrangement cells (i.e., vertices, edges, and facets)
and the incidence relations between them. At this point we do not
expose the concepts that refine the basic concept.  The package
contains three topology traits class templates, namely,
`Arr_bounded_planar_topology_traits_2`,
`Arr_unb_planar_topology_traits_2`, and
`Arr_spherical_topology_traits_2`. The first two are internally used
to define any instance of the class template
`Arrangement_2<GeometryTraits_2, Dcel>`. In particular, an instance
`Arrangement_2<Geometry_traits_2, Dcel_>` is derived from the instance
`Arrangement_on_surface_2<Geometry_traits_2,Topology_traits>`, where
the `Topology_traits` type is selected based on the provided geometry
traits `Geometry_traits_2`, or more precisely, on the boundary
conditions defined by the geometry traits. If all sides of the
boundary of the parameter space are closed, the instance
`Arr_bounded_planar_topology_traits_2<Geometry_traits_2,Dcel_>` is
selected; otherwise the instance
`Arr_unb_planar_topology_traits_2<Geometry_traits_2,Dcel_>` is
selected.  The third topology traits serves as a topology traits for
an arrangement embedded on a sphere. More precisely, for an
arrangement embedded on a sphere defined over a parameter space, the
left and right boundary sides of which are identified, and the top and
bottom boundary sides are contracted.


\section arr_sec_extending Extending the Arrangement


Developing applications that use arrangements to solve problems that
are a bit more complicated than the problems presented in previous
chapters requires the ability to adapt the arrangement data structure
to the application needs. One technique to do this is to extend the
arrangement with auxiliary, usually non-geometric, data. In this
chapter we describe several ways to extend an arrangement data
structure.


\subsection arr_ssecnotif The Notification Mechanism


In some cases it is essential to know exactly what happens inside a
specific arrangement object. For example, when a new curve is inserted
into an arrangement, it may be necessary to keep track of the faces
that are split due to this insertion operation.  Other important
examples are the point-location strategies that require auxiliary data
structures (see Section \ref arr_ssecpl), which must be kept
up-to-date when the arrangement changes. The \ref
PkgArrangementOnSurface2 package offers a mechanism that uses
<em>observers</em> (see \cgalCite{cgal:ghjv-dpero-95}). The objective
behind this mechanism is to define a one-to-many dependency between
objects, so that when one object changes state, all its dependents are
notified and updated automatically. The observed object does not know
anything about the observers. It merely "publishes" information about
changes when they occur. In our case observers can be attached to an
arrangement object.

An observer object that observes changes in an arrangement object
stores a pointer to the attached arrangement object. It receives
notifications about the changes this arrangement undergoes. The
observer receives notifications <em>just before</em> a structural
change occurs in the arrangement and <em>immediately after</em> such a
change takes place.  An observer object that observes changes in an
arrangement object of type `Arrangement` must be of a type derived
from `Arrangement::Observer`, which is an alias to
`Aos_observer<Arrangement_on_surface_2>`, where
`Arrangement_on_surface_2` is the type of the arrangement object or
its base type. An instance of `Aos_observer<>` serves as a base type
for other observer classes and defines a set of virtual notification
functions, with default empty implementations.  You can also use the
template alias `Arr_observer<Arrangement_2>`, where `Arrangement_2` is
the type of the arrangement object in case it is derived from an
instance of the template `Arrangement_on_surface_2`.  The set of
functions can be divided into three categories, as follows:

<OL>

<LI>Notifiers of changes that affect the entire topological structure
of the arrangement. This category consists of two pairs
(<em>before</em> and <em>after</em>) that notify the observer of the
following changes:

<UL>
<LI>The arrangement is cleared.
<LI>The arrangement is assigned with the contents of another arrangement.
</UL>

<LI>Pairs of notifiers before and after a local change that occurs in
the topological structure. Most notifier functions belong to this
category. The relevant local changes include:

<UL>

<LI>A new vertex is constructed and associated with a point.

<li>An edge\cgalFootnote{The term "edge" refers here to a pair of twin
halfedges.} is constructed and associated with an \f$x\f$-monotone
curve.

<LI>An edge is split into two edges.

<LI>An existing face is split into two faces, as a consequence of the
insertion of a new edge.

<LI>A hole is created in the interior of a face.

<LI>Two holes are merged to form a single hole, as a consequence of
the insertion of a new edge.

<LI>A hole is moved from one face to another, as a consequence of a
face split.

<LI>Two edges are merged into one edge.

<LI>Two faces are merged into one face, as a consequence of the
removal of an edge that used to separate them.

<LI>One hole is split into two, as a consequence of the deletion of an
edge that used to connect the two components.

<LI>A vertex is removed.
<LI>An edge is removed.
<LI>A hole is deleted from the interior of a face.

</UL>

<LI>Notifiers about a change caused by a free function; see Section
\ref arr_secgl_funcs for a discussion on the free functions.  This
category consists of a single pair of notifiers, namely
`before_global_change()` and `after_global_change()`. Neither of these
functions is invoked by methods of the `Arrangement_2` class template.
Instead, they are called by the free functions themselves. It is
implied that no point-location queries (or any other queries for that
matter) are issued between the call to `before_global_change()` and
the call to `after_global_change()`.

</OL>

See the Reference Manual for a detailed specification of the
`Aos_observer` class template and the prototypes of all notification
functions.

Each arrangement object stores a list of pointers to `Aos_observer`
objects. This list may be empty, in which case the arrangement does
not have to notify any external class on the structural changes it
undergoes. If, however, there are observers associated with the
arrangement object, then whenever one of the structural changes listed
in the first two categories above is about to take place, the
arrangement object performs a <em>forward</em> traversal on this list
and invokes the appropriate function of each observer. After the
change takes place the observer list is traversed <em>backward</em>
(from tail to head), and the appropriate notification function is
invoked for each observer.


Concrete arrangement-observer classes should inherit from
`Aos_observer`. When an observer is constructed, it is attached to a
valid arrangement supplied to the observed constructor, or
alternatively the observer can be attached to the arrangement at a
later time.  When this happens, the observer object inserts itself
into the observer list of the associated arrangement and starts
receiving notifications whenever this arrangement changes
thereafter. Subsequently, the observer object unregisters itself by
removing itself from this list just before it is destroyed. Most
concrete observer-classes do not need to use the full set of
notifications. Thus, the bodies of all notification methods defined in
the base class `Aos_observer` are empty. A concrete observer that
inherits from `Aos_observer` needs to override only the relevant
notification methods. The remaining methods are invoked when
corresponding changes occur, but they do nothing.

The trapezoidal map RIC and the landmark point-location strategies
both use observers to keep their auxiliary data structures
up-to-date. In addition, you can define your own observer classes,
inheriting from the base observer class and overriding the relevant
notification functions, as required by their applications.


\cgalFigureBegin{aos_fig-observer,observer.png}
An arrangement of six line segments, as constructed in \ref
Arrangement_on_surface_2/observer.cpp.  The halfedge \f$e_v\f$
(dashed) is eventually removed, so that the final arrangement consists
of four faces (one unbounded and three bounded ones).
\cgalFigureEnd


The following example shows how to define and use an observer
class. The observer in the example responds to changes in the
arrangement faces. It prints a message whenever a face is split into
two due to the insertion of an edge and whenever two faces merge into
one due to the removal of an edge. The layout of the arrangement is
depicted in \cgalFigureRef{aos_fig-observer}; it comprises six line
segments and eight edges (the horizontal segment \f$s_h\f$ and the
vertical segment \f$s_v\f$ induce two edges each).  The halfedge
\f$e_v\f$ is induced by the vertical segment \f$s_v\f$. First, it is
associated with the (entire) segment, as obtained by the `insert()`
function; see Line 40 in the code excerpt below. After the insertion
of \f$s_h\f$ (see Line 41) the halfedge is split. After the split
\f$e_v\f$ (drawn dashed in the figure) is associated with the lower
split curve. Eventually, it is removed (along with its twin
halfedge). Note the face-split notifications that are invoked as a
consequence of the insertion of \f$s_v\f$ and \f$s_h\f$ and the
face-merge notification that is invoked as a consequent of the removal
of \f$e_v\f$.

\cgalExample{Arrangement_on_surface_2/observer.cpp}

Observers are especially useful when the \dcel records are
extended and store additional data-fields, since they help update
this data stored in these fields, as the following sections reveal.


\subsection arr_ssecex_dcel Extending the DCEL


For many applications of the \ref PkgArrangementOnSurface2 package it
is necessary to store additional information (perhaps of non-geometric
nature) with the arrangement features. Vertices are associated with
\link Arrangement_on_surface_2::Point_2 `Point_2`\endlink objects and
edges (halfedge pairs) are associated with \link
Arrangement_on_surface_2::X_monotone_curve_2
`X_monotone_curve_2`\endlink objects, both defined by the traits
class. Extending the geometric traits-class types by using a
traits-class decorator, as explained in Section \ref arr_ssec_tr_decorators,
might be a sufficient solution for some applications.  However, the
\dcel faces are not associated with any geometric object, so
traits-class decorators cannot help here. Extending the \dcel face
records comes in handy is such cases. As a matter of fact, it is
possible to conveniently extend all \dcel records (namely
vertices, halfedges, and faces), which is advantageous for some
applications.

All examples presented so far use the default \dcel; namely, they
employ the `Arr_default_dcel<Traits>` instance. This is done
implicitly, as this instance of the `Arr_default_dcel` class template
serves as the default parameter for the `Arrangement_2` class
template; see Section \ref aos_ssec-basic-arr_class. The default \dcel
class associates points with vertices and \f$x\f$-monotone curves with
halfedges, but nothing more.  In this section we show how to use
alternative \dcel types to extend the desired \dcel records.


\subsubsection arr_sssecex_dcel_face Extending the DCEL Faces


The `Arr_face_extended_dcel<Traits, FaceData>` class-template is used
to associate auxiliary data field of type `FaceData` to each face
record in the \dcel.  When the `Arrangement_2<Traits,Dcel>` class
template is instantiated, substituting the \dcel parameter with an
instance of this class template, the interface of the nested `Face`
type is extended with the access function `data()` and with the
modifier `set_data()`. Using these extra functions it is
straightforward to access and maintain the auxiliary face-data field.

Note that the extra data-fields must be maintained by the user
application. User may choose to construct their arrangement, and may
only then go over the faces and store data in the appropriate
data-fields of the arrangement faces. However, in some cases the face
data can only be computed when the face is created (split from another
face or merged with another face). In such cases one can use an
arrangement observer tailored for this task, which receives updates
whenever a face is modified and sets its data field accordingly.


\cgalFigureBegin{aos_fig-dcel_extension,dcel_extension.png}
An arrangement of six line segments, as constructed in \ref
Arrangement_on_surface_2/face_extension.cpp and \ref
Arrangement_on_surface_2/dcel_extension.cpp (in \ref
Arrangement_on_surface_2/dcel_extension.cpp we treat the segments as
directed, so they are drawn as arrows directed from the source to the
target). The indices associated with the halfedges in
\ref Arrangement_on_surface_2/face_extension.cpp are shown in brackets.
\cgalFigureEnd


The next example constructs an arrangement that contains seven bounded
faces induced by six line segments, \f$s_1, \ldots, s_6\f$, as shown
in \cgalFigureRef{aos_fig-dcel_extension}. An observer gets notified
each time a new face \f$f\f$ is created, and it associates \f$f\f$
with a running index, where the index of the unbounded face is 0. As a
result, the faces are numbered according to their creation order,
These numbers are shown in brackets, and their order can easily be
verified by examining the insertion order of the
segments.\cgalFootnote{For simplicity, the particular observer used
must be attached to an empty arrangement. It is not difficult however
to modify the program to handle the general case of attaching a
similar observer to a non-empty arrangement.}

\cgalExample{Arrangement_on_surface_2/face_extension.cpp}


\subsubsection arr_sssecex_dcel_all Extending All DCEL Records


As you continue to use arrangements to solve various problems you will
find out that the ability to extend the face records is
crucial. Perhaps less common, but also important to satisfy, is the
need to extend the vertex and halfedge records as well. The
`Arr_extended_dcel<Traits, VertexData, HalfedgeData, FaceData>`
class-template is used to associate auxiliary data fields of types
`VertexData`, `HalfedgeData`, and `FaceData` with \dcel vertex,
halfedge, and face record types, respectively.  When the
`Arrangement_2<Traits,Dcel>` class template is instantiated,
substituting the `Dcel` parameter with an instance of this \dcel
class-template, the interfaces of the nested types Vertex, Halfedge,
and Face are extended with the access function `data()` and with the
modifier `set_data()`.

The next example shows how to use a \dcel with extended vertex,
halfedge, and face records. In this example each vertex is associated
with a color, which is either blue, red, or white, depending on whether
the vertex is isolated, represents a segment endpoint, or represents
an intersection point. (Notice that the coloring rules suggested here
apply only to non-degenerate arrangements, where the sets of isolated
points, curve endpoints, and intersection points are mutually
exclusive.) In this example segments are treated as directed objects.
Each halfedge is associated with Boolean flag indicating whether its
direction is the same as the direction of its associated segment. Each
face is also extended to store the size of its outer boundary, that
is, the number of halfedges along its outer boundary.

The constructed arrangement, depicted in
\cgalFigureRef{aos_fig-dcel_extension}, is similar to the
arrangement constructed in the previous example.  In this case,
however, we do not use an observer; instead, all auxiliary data-fields
are set after the construction phase.  Also note that the data fields
are properly maintained when the arrangement is copied to another
arrangement object.

\cgalExample{Arrangement_on_surface_2/dcel_extension.cpp}

\cgalAdvancedBegin

The various \dcel classes presented in this section are well
suited for most applications based on the \ref
PkgArrangementOnSurface2 package. They are all defined using helper
constructs, and in particular the base \dcel class-template
`Arr_dcel_base}`.  However, there are cases where special
requirements, not addressed by these \dcel classes, are needed.
In such cases you may explicitly extend the base \dcel
class-template, as described in the next paragraph, or implement your
own \dcel class from scratch and use the resulting \dcel to
instantiate the `Arrangement_2` class template. In any case such a
class must model the concept `AosDcel` or its refinement
`AosDcelWithRebind`. The latter requires a `rebind` struct
template, which implements a policy-clone idiom. Here, the \dcel
class is the policy class and the `rebind` member template struct
is used to pass a different traits type parameter to the policy class
template.

In some cases you may want to extend a certain feature type with
several fields. You can gather all these fields (and perhaps methods
that access and retrieve these fields) in a single construct, and
substitute the appropriate parameter of the class template
`Arr_extended_dcel<Traits, VertexData, HalfedgeData, FaceData>` with
this construct. Naturally, you can define three constructs, one for
each feature type, and substitute all the three corresponding template
parameters appropriately. For example, consider an arrangement that
represents a map where features of the same type represent different
cartographic entities, e.g., an edge represents a road, a river, or a
railway. We would like to associate two strings with each feature,
namely, the name and the type of the feature. Following the solution
above, accessing or retrieving a specific field will always require an
indirection through one of the member functions `set_data()` and
`data()`. While this indirection is typically resolved at compile
time, and thus has no negative effect on the running time of the
generated code, it may have some implication on the space consumption
due to compiler padding.\cgalFootnote{Compilers add pad bytes into
user-defined constructs to comply with alignment restrictions imposed
by target microprocessors.} Moreover, the code may look cumbersome.

The extended \dcel class that addresses the problem raised above
is listed below. Here, each feature type is explicitly extended with
two strings, namely, `name` and `type`, eliminating the data
constructs.

\code{.cpp}
#include <string>

#include <CGAL/basic.h>
#include <CGAL/Arr_dcel_base.h>

// The map-extended dcel vertex.
template <typename Point_2>
class Arr_map_vertex : public CGAL::Arr_vertex_base<Point_2> {
public:
  std::string name, type;
};

// The map-extended dcel halfedge.
template <typename X_monotone_curve_2>
class Arr_map_halfedge : public CGAL::Arr_halfedge_base<X_monotone_curve_2> {
public:
  std::string name, type;
};

// The map-extended dcel face.
class Arr_map_face : public CGAL::Arr_face_base {
public:
  std::string name, type;
};

// The map-extended dcel.
template <typename Traits>
class Arr_map_dcel : public
  CGAL::Arr_dcel_base<Arr_map_vertex<typename Traits::Point_2>,
                      Arr_map_halfedge<typename Traits::X_monotone_curve_2>,
                      Arr_map_face>
{};
\endcode

\cgalAdvancedEnd


\subsection arr_ssecoverlay Overlaying Arrangements


Assume that we are given two geographic maps represented as
arrangements, with some data objects attached to their faces,
representing some geographic information---for instance, a map of the
annual precipitation in some country and a map of the vegetation in
the same country---and you are asked to locate, for example, places
where there is a pine forest <em>and</em> the annual precipitation is
between 1,000mm and 1,500mm. Overlaying the two maps may help you
figure out the answer.  Computing the overlay of two two-dimensional
arrangements is also useful for supporting Boolean set operations on
polygons or general polygons; see e.g., \cgalCite{cgal:behhms-cbcab-02}).

Formally, the <em>map overlay</em> of two two-dimensional subdivisions
\f$\mathcal{S}_1\f$ and \f$\mathcal{S}_2\f$ is a two-dimensional
subdivision \f$\mathcal{S}\f$, such that there is a face \f$f\f$ in
\f$\mathcal{S}\f$ iff there are faces \f$f_1\f$ and \f$f_2\f$ in
\f$\mathcal{S}_1\f$ and \f$\mathcal{S}_2\f$, respectively, such that
\f$f\f$ is a maximal connected component of \f$f_1 \cap f_2\f$.

The overlay of two given arrangements, conveniently referred to as the
"blue" and the "red" arrangements, is implemented as a plane-sweep
algorithm employing a dedicated visitor; see Section
\ref arr_ssec_sweep.  The \f$x\f$-monotone curve type is extended with
a color attribute (whose value is either blue or red); see Section \ref
arr_ssec_tr_decorators. With the help of the extended type unnecessary
computations are filtered out while the plane is swept, yielding an
efficient process. For example, monochromatic intersections are not
computed.

The plane-sweep visitor that concretizes the overlay operation needs
to construct a \dcel that properly represents the overlay of two
input arrangements. A face in the overlay arrangement corresponds to
overlapping regions of the blue and red faces. An edge in the overlay
arrangement is due to a blue edge, a red edge, or an overlap of two
differently colored edges. An overlay vertex is due to a blue vertex,
a red vertex, a coincidence of two differently colored vertices, or an
intersection of a blue and a red curve.

The call \link overlay() `overlay(arr_r, arr_b, arr_o,
ovl_traits)`\endlink constructs the arrangement `arr_o`, which is the
overlay of two input arrangement `arr_r` and `arr_b`. All three
arrangements must use the same geometric primitives. In other words,
their types are instances of the `Arrangement_2<Traits,Dcel>` class
template, where the `Traits` parameter is substituted by three
geometry-traits classes, respectively. The geometry-traits classes of
the input arrangements must be convertible to the geometry-traits
class of the resulting arrangement.\cgalFootnote{It is sufficient that
all three geometry-traits classes used to instantiate the three types
of arrangements derive from a common ancestor that models the
geometry-traits concept.} Typically, all three arrangements use the
same geometry-traits class.

The `overlay()` function template is suitable for arrangements that do
not store any additional data with their \dcel records; namely,
arrangements defined using the default \dcel, which is the instance
`Arr_default_dcel<Traits>`. Typically, the overlay arrangement in this
case does not store extra data with its \dcel records as well. (If it
does, the additional data-fields cannot be computed by the overlay
operation in this case.) The overlay arrangement is equivalent to the
arrangement induced by all curves of `arr_r` and `arr_b`. Indeed, it
is possible to obtain the same result using the standard
insertion-operations instead, but, as mentioned above, this is less
efficient.


\cgalFigureBegin{aos_figex_overlay,overlay.png}
Overlaying two simple arrangements of line segments, as done in \ref
Arrangement_on_surface_2/overlay.cpp and \ref
Arrangement_on_surface_2/face_extension_overlay.cpp. In \ref
Arrangement_on_surface_2/face_extension_overlay.cpp the two bounded
faces are considered as <em>marked</em>, and the octagonal face which
is the intersection of the two marked faces is denoted by \f$f_0\f$.
\cgalFigureEnd


The next program constructs two simple arrangements; each comprises
four line segments that form a square, as depicted in
\cgalFigureRef{aos_figex_overlay}. The program computes the overlay of the
two arrangements. The resulting arrangement has 16 vertices, 24
edges, and 10 faces (including the unbounded one.

\cgalExample{Arrangement_on_surface_2/overlay.cpp}

The `overlay()` function template is overloaded with a variant that
accepts four arguments, that is, `overlay(arr_r, arr_b, arr_o,
ovl_traits)`. The type of the `ovl_traits` additional argument,
referred to as the overlay traits, must model the `OverlayTraits`
concept described below. Assume that `arr_r` is of type
`Arrangement_2<Traits,Dcel_R>`, `arr_b` is of type
`Arrangement_2<Traits,Dcel_B>`, and the resulting `arr_o` is of type
`Arrangement_2<Traits,Dcel_O>`. The overlay traits enables the
creation of `Dcel_O` records in the overlay arrangement from the
features of `Dcel_R` and `Dcel_B` records from the arrangements
`arr_r` and `arr_b`, respectively.

We distinguish between (i) an overlay of two arrangements that store
additional data-fields only with their faces e.g., the geographic-map
example given at the beginning of this section) and (ii) an overlay of
two arrangements that store additional data fields with all their
\dcel records (or at least not only with their faces).  The
arrangement that results from overlaying two face-extended
arrangements typically also stores additional data-fields with its
faces. The types of such arrangements, for example, could be instances
of the `Arrangement_2<Traits,Dcel>` class template, where the `Dcel`
parameters are substituted by instances of the
`Arr_face_extended_dcel` class template (see Section \ref
arr_sssecex_dcel_face). The data field that is attached to an overlay
face can be computed from the data fields of the two faces (in `arr_r`
and `arr_b`) that induce the overlay face. Similarly, the arrangement
that results from overlaying two arrangements that store additional
data fields with all their \dcel records typically also stores
additional data-fields with all its \dcel records. The types of
such arrangements, for example, could be instances of the
`Arrangement_2<Traits,Dcel>` class template, where the `Dcel`
parameters are substituted by instances of the `Arr_extended_dcel`
class template (see Section \ref arr_sssecex_dcel_all). The data field
attached to an overlay feature can be computed from the data fields of
the two features (in `arr_r` and `arr_b`) that induce the overlay
feature.

As mentioned in the previous paragraph, if any of the \dcel
records of your arrangements are extended, you can pass a fourth
argument to the `overlay()` call, also referred to as the overlay
traits, to control the generation of the extended data in the
resulting arrangement. If only the face records are extended, the type
of the overlay traits can be an instance of the class template
`Arr_face_overlay_traits<ArrangementR,ArrangementB,ArrangementO,OverlayFaceData>`,
which models the concept `OverlayTraits`. An object of this type
operates on face-extended arrangements. When instantiated, the
`OverlayFaceData` parameter must be substituted by a functor that is
capable of combining two face-data fields of types
`ArrangementR::Dcel::Face_data` and `ArrangementB::Dcel::Face_data`
and computing the output `ArrangementO::Dcel::Face_data` object. The
face-overlay traits-class uses this functor to properly construct the
overlay faces.

The following example shows how to compute the intersection of two
polygons using the `overlay()` function template. It uses a
face-extended \dcel type to instantiate the arrangement
classes. Each face of the \dcel is extended with a Boolean
flag. A polygon is represented as a <em>marked</em> arrangement face
(whose flag is set). The example uses an instance of the
`Arr_face_overlay_traits<ArrR,ArrB,ArrO,OverlayFaceData>` class
template as the face-overlay traits class where the `OverlayFaceData`
template parameter is substituted by a functor that simply performs
a logical <em>and</em> operation on Boolean flags. As a result, a face
in the overlay arrangement is marked only when it corresponds to an
overlapping region of two marked faces in the input
arrangements. Namely, it is part of the intersection of the two
polygons. The example computes the intersection between a
parallel-axis square and a congruent square rotated
\f$45^\circ\f$. The resulting polygon from the intersection operation
is an octagon, which corresponds to the face~\f$\hat{f}\f$ in the
arrangement depicted in \cgalFigureRef{aos_figex_overlay}.

\cgalExample{Arrangement_on_surface_2/face_extension_overlay.cpp}


\cgalFigureBegin{aos_figex_overlay_unbounded,overlay_unbounded.png}
Overlaying two arrangements of lines that have unbounded faces, as
done in \ref Arrangement_on_surface_2/overlay_unbounded.cpp.
\cgalFigureEnd


The next example, depicted in
\cgalFigureRef{aos_figex_overlay_unbounded}, demonstrates the face
overlay of two arrangements that have unbounded faces as well as
bounded ones.  The first arrangement (blue) is induced by the two
lines \f$y = x\f$ and \f$y = -x\f$, which subdivide the plane into
four unbounded faces, labeled \f$A\f$, \f$B\f$, \f$C\f$ and
\f$D\f$. The second arrangement (red) comprises four line segments
that form a square-shaped face indexed \f$1\f$. The unbounded face is
indexed 2. When the two arrangements are overlaid, each of the four
faces \f$A\f$, \f$B\f$, \f$C\f$ and \f$D\f$ is split into an unbounded
face (indexed 2) and a bounded face (indexed 1), so the faces of the
resulting arrangement are labeled \f$A_1, A_2, \ldots, D_1,
D_2\f$. `boost::lexical_cast` is used to cast the integral indices
into strings to produce the final labels.

\cgalExample{Arrangement_on_surface_2/overlay_unbounded.cpp}

If the red and blue arrangements store additional data-fields with all
their \dcel records, and the data associated with the overlay
\dcel features should be computed from the red and blue \dcel
features that induce it, then an appropriate overlay-traits argument
must be passed to the `overlay()` call. The overlay-traits type models
the `OverlayTraits` concept, which requires the provision of ten
functions that handle all possible cases as listed below. Let
\f$v_r\f$, \f$e_r\f$, and \f$f_r\f$ denote input <span
style="color:red;">red</span> features, i.e., a vertex, an edge, and a
face, respectively, \f$v_b\f$, \f$e_b\f$, and \f$f_b\f$ denote input
<span style="color:blue;">blue</span> features, and \f$v\f$, \f$e\f$,
and \f$f\f$ denote output features.

<OL>

<LI> A new vertex \f$v\f$ is induced by coinciding vertices
\f$v_r\f$ and \f$v_b\f$.</LI>

<LI> A new vertex \f$v\f$ is induced by a vertex \f$v_r\f$ that lies
on an edge \f$e_b\f$.</LI>

<LI> An analogous case of a vertex \f$v_b\f$ that lies on an edge
\f$e_r\f$.</LI>

<LI> A new vertex \f$v\f$ is induced by a vertex \f$v_r\f$ that is
  contained in a face \f$f_b\f$.</LI>

<LI> An analogous case of a vertex \f$v_b\f$ contained in a face
  \f$f_r\f$.</LI>

<LI> A new vertex \f$v\f$ is induced by the intersection of two edges
  \f$e_r\f$ and \f$e_b\f$.</LI>

<LI> A new edge \f$e\f$ is induced by the (possibly partial) overlap
  of two edges \f$e_r\f$ and \f$e_b\f$.</LI>

<LI> A new edge \f$e\f$ is induced by the an edge \f$e_r\f$ that is
  contained in a face \f$f_b\f$.</LI>

<LI> An analogous case of an edge \f$e_b\f$ contained in a face
  \f$f_r\f$.</LI>

<LI> A new face \f$f\f$ is induced by the overlap of two faces
  \f$f_r\f$ and \f$f_b\f$.</LI>

</OL>

The `Overlay_color_traits` class template listed below models the
concept `OverlayTraits`.  It assumes that each feature of the input
arrangements and of the overlay arrangement is extended with an RGB
color stored as an `unsigned int`. It defines ten member functions
that correspond to the ten cases listed above. Each of these functions
accepts three handles as follows: two handles to the two features of
the input arrangements, respectively, that induce a feature of the
overlay arrangement and a handle to the induced overlay-arrangement
feature. Each of these member functions blends the colors attached to
the inducing features and assigns the resulting color to the induced
feature. The `Overlay_color_traits` class template is defined in the
header file `Overlay_color_traits.h`.

\code{.cpp}
template <typename Arrangement> struct Overlay_color_traits {
  using Color = unsigned int;
  using V_const_handle = typename Arrangement::Vertex_const_handle;
  using H_const_handle = typename Arrangement::Halfedge_const_handle;
  using F_const_handle = typename Arrangement::Face_const_handle;
  using V_handle = typename Arrangement::Vertex_handle;
  using H_handle = typename Arrangement::Halfedge_handle;
  using F_handle = typename Arrangement::Face_handle;

  // Compute the average of the red, green, and blue components separately.
  Color blend(Color color1, Color color2) const {
    return
      ((((color1 & 0x000000ff) + (color2 & 0x000000ff)) / 2) & 0x000000ff) |
      ((((color1 & 0x0000ff00) + (color2 & 0x0000ff00)) / 2) & 0x0000ff00) |
      ((((color1 & 0x00ff0000) + (color2 & 0x00ff0000)) / 2) & 0x00ff0000);
  }

  void create_face(F_const_handle f1, F_const_handle f2, F_handle f) const
  { f->set_data(blend(f1->data(), f2->data())); }
  void create_vertex(H_const_handle h1, H_const_handle h2, V_handle v) const
  { v->set_data(blend(h1->data(), h2->data())); }
  void create_vertex(V_const_handle v1, V_const_handle v2, V_handle v) const
  { v->set_data(blend(v1->data(), v2->data())); }
  void create_vertex(V_const_handle v1, H_const_handle h2, V_handle v) const
  { v->set_data(blend(v1->data(), h2->data())); }
  void create_vertex(H_const_handle h1, V_const_handle v2, V_handle v) const
  { v->set_data(blend(h1->data(), v2->data())); }
  void create_vertex(F_const_handle f1, V_const_handle v2, V_handle v) const
  { v->set_data(blend(f1->data(), v2->data())); }
  void create_vertex(V_const_handle v1, F_const_handle f2, V_handle v) const
  { v->set_data(blend(v1->data(), f2->data())); }
  void create_edge(H_const_handle h1, H_const_handle h2, H_handle h) const
  {
    h->set_data(blend(h1->data(), h2->data()));
    h->twin()->set_data(blend(h1->data(), h2->data()));
  }
  void create_edge(H_const_handle h1, F_const_handle f2, H_handle h) const
  {
    h->set_data(blend(h1->data(), f2->data()));
    h->twin()->set_data(blend(h1->data(), f2->data()));
  }
  void create_edge(F_const_handle f1, H_const_handle h2, H_handle h) const
  {
    h->set_data(blend(f1->data(), h2->data()));
    h->twin()->set_data(blend(f1->data(), h2->data()));
  }
};
\endcode


\cgalFigureBegin{aos_figex_overlay_color,overlay_color.png}

The overlay of two extended arrangements]{The overlay (c) of two
arrangements (a) and (b). Each feature of the arrangements is extended
with a color. The color of each feature of the overlay arrangement is
the blend of the colors of the two inducing features.

\cgalFigureEnd


The example program listed below computes the overlay, depicted in
\cgalFigureRef{aos_figex_overlay_color}, of the two arrangements
depicted in (a) and (d). Each feature of the input arrangements and of
the overlay arrangement is extended with an RGB color stored as an
`unsigned int`. The vertices, halfedges, and faces of the red
arrangement are assigned three different shades of red. Similarly, the
vertices, halfedges, and faces of the blue arrangement are assigned
three different shades of blue. Using an instance of the
`Overlay_color_traits` class template as the overlay traits, each
feature of the overlay arrangement is assigned a color that is a blend
of the colors attached to the inducing features.

\cgalExample{Arrangement_on_surface_2/overlay_color.cpp}


\subsection arr_ssecarr_with_hist Storing the Curve History


When you constructs an arrangement induced by a set \f$\mathcal{C}\f$
of arbitrary two-dimensional curves, you end up with a collection
\f$\mathcal{C}''\f$ of \f$x\f$-monotone subcurves of \f$\mathcal{C}\f$
that are pairwise disjoint in their interior; see Section \ref
aos_sec-intro. These subcurves are associated with the arrangement
edges (more precisely, with pairs of \dcel halfedges). The connection
between the originating input curves and the arrangement edges is lost
during the construction process. This loss might be acceptable for
some applications. However, in many practical cases it is important to
determine the input curves that give rise to the final subcurves.

The
`Arrangement_on_surface_with_history_2<GeometryTraits,TopologyTraits>`
class-template extends the
`Arrangement_on_surface_2<GeometryTraits,TopologyTraots>` class
template by keeping an additional container of input curves
representing \f$\mathcal{C}\f$, and by maintaining a cross-mapping
between these curves and the arrangement edges they induce. Similarly,
the `Arrangement_with_history_2<GeometryTraits,Dcel>` class-template
extends the `Arrangement_2<GeometryTraits,Dcel>` class template. The
`GeometryTraits` template parameter, of either class templates, must
be substituted by a model of the `AosTraits_2` concept; see
Section \ref aos_ssec-insert_gen. It should define the \link
AosTraits_2::Curve_2 `Curve_2`\endlink type and support its
subdivision into \link AosBasicTraits_2::X_monotone_curve_2
`X_monotone_curve_2`\endlink objects, among the others.  The `Dcel`
parameter must be substituted by a model of the `AosDcel`
concept. You can use either the default \dcel class or an extended
\dcel class (see Section \ref arr_ssecex_dcel) based on your needs. An
arrangement that support the cross-mapping mentioned above is referred
to as an arrangement with history. In the following we use the
`Arrangement_with_history_2<>` class template to demonstrate
arrangements with history. However, the explanation applies also to
`Arrangement_on_surface_with_history_2<>`, as the type of the
embedding surface is irrelevant to the discussion.


\subsubsection arr_sssecarrwh_traverse Traversing an Arrangement with History


The `Arrangement_with_history_2` class template extends the
`Arrangement_2` class template. Thus, all the iterator and circulator
types that are defined in the base class are also available in
`Arrangement_with_history_2`.  (Refer to Section \ref
arr_ssectraverse for a comprehensive review of this functionality.)

As mentioned above, the `Arrangement_with_history_2` class template
maintains a container of input curves, which can be accessed using
curve handles.  Let `arr` identify an object, the type of which is an
instance of this template. The call \link
Arrangement_with_history_2::number_of_curves()
`arr.number_of_curves()`\endlink returns the number of input curves
stored in the container, while \link
Arrangement_with_history_2::curves_begin()
`arr.curves_begin()`\endlink and \link
Arrangement_with_history_2::curves_end() `arr.curves_end()`\endlink
return `Arrangement_with_history_2::Curve_iterator` objects that
define the range of curves that induce the arrangement.  The value
type of this iterator is \link Arrangement_with_history_2::Curve_2
`Curve_2`\endlink. Moreover, the curve-iterator type is convertible to
`Arrangement_with_history_2::Curve_handle`, which is used for
accessing the stored curves. For convenience, the corresponding
constant-iterator and constant-handle types are also defined.

As mentioned in the previous paragraph, a `Curve_handle` object `ch`
serves as a pointer to a curve stored in an arrangement-with-history
object `arr`. Using this handle, it is possible to obtain the number
of arrangement edges this curve induces by calling \link
Arrangement_with_history_2::number_of_induced_edges()
`arr.number_of_induced_edges(ch)`\endlink. The functions \link
Arrangement_with_history_2::induced_edges_begin()
`arr.induced_edges_begin(ch)`\endlink and \link
Arrangement_with_history_2::induced_edges_end()
`arr.induced_edges_end(ch)`\endlink return iterators of type
`Arrangement_with_history_2::Induced_edges_iterator` that define the
range of edges induced by `ch`. The value type of these iterators is
\link Arrangement_on_surface_2::Halfedge_handle
`Halfedge_handle`\endlink. It is thus possible to traverse all
arrangement edges induced by an input curve.

The ability to perform the inverse mapping is also important. Given an
arrangement edge, you may want to determine which input curve induces
it. In case the edge represents an overlap of several curves, you
should be able to trace all input curves that overlap in this edge.
The `Arrangement_with_history_2` class template is extended by several
member functions that enable such an inverse mapping. Given a handle
to halfedge `e` in an arrangement with history object `arr`, the call
\link Arrangement_with_history_2::number_of_originating_curves()
`arr.number_of_originating_curves(e)`\endlink returns the number of
curves that induce the edge (which should be 1 in non-degenerate
cases, and 2 or more in case of overlaps), while \link
Arrangement_with_history_2::originating_curves_begin()
`arr.originating_curves_begin(e)`\endlink and \link
Arrangement_with_history_2::originating_curves_end()
`arr.originating_curves_end(e)`\endlink return
`Arrangement_with_history_2::Originating_curve_iterator` objects that
define the range of curves that induce `e`. The value type of these
iterators is \link Arrangement_with_history_2::Curve_2
`Curve_2`\endlink.

Overlaying two arrangement-with-history objects is possible only if
their types are instances of the
`Arrangement_with_history_2<Traits,Dcel>` class template, where the
respective `Traits` parameters are substituted by two traits classes
that are convertible to one another. In this case, the resulting
arrangement stores a consolidated container of input curves, and
automatically preserves the cross-mapping between the arrangement
edges and the consolidated curve-set. You may also employ an
overlay-traits class to maintain any type of auxiliary data stored
with the \dcel cells; see Section \ref arr_ssecoverlay.


\subsubsection arr_sssecmodif_traverse Modifying an Arrangement with History


The `Arrangement_with_history_2` class template extends the
`Arrangement_2` class template; thus, it inherits the fundamental
modification operations, such as \link
Arrangement_on_surface_2::assign() `assign()`\endlink and \link
Arrangement_on_surface_2::clear() `clear()`\endlink, from it. The
vertex-manipulation functions are also inherited and supported; see
Sections \ref arr_sssecmf_iso_verts and \ref arr_sssecinsert_point for
details. However, there are some fundamental differences between the
interfaces of the two class templates, which we highlight next.

The most significant difference between the arrangement-with-history
class template and the basic arrangement class template is the way
they handle their input curves.  `Arrangement_with_history_2` always
stores the \link Arrangement_with_history_2::Curve_2 `Curve_2`\endlink
objects that induce it. Thus, it is impossible to insert
\f$x\f$-monotone curves into an arrangement with history. The free
functions `insert_non_intersecting_curve()` and the version of
`insert()` that accept \f$x\f$-monotone curves, as well as their
aggregated versions), are therefore not available for
arrangement-with-history instances. Only the free overloaded functions
`insert()` that accept general curves, namely, the incremental
insertion function and the aggregate insertion function, are
supported; see Section \ref aos_ssec-insert_gen for a review of these
functions. Notice however that while the incremental insertion
function `insert(arr, c)` for an `Arrangement_2` object `arr` does not
have a return value, the corresponding arrangement-with-history
function returns a `Curve_handle` object that points to the inserted
curve.

As we are able to keep track of all edges induced by an input curve,
we also provide a free function that removes a curve from an
arrangement. By calling `remove_curve(arr,ch)`, where `ch` is a valid
curve handle, the given curve is deleted from the curve container, and
all edges induced solely by this curve (i.e., excluding overlapping
edges) are removed from the arrangement. The function returns the
number of edges that have been removed.

In some cases, users may need to operate directly on the arrangement
edges.  We first mention that the specialized insertion functions (see
Section \ref arr_sssecmf_insert_cv) are not supported, as they accept
\f$x\f$-monotone curves. Insertion can only be performed via the free
insertion-functions. The other edge-manipulation functions (see
Section \ref arr_sssecmf_halfedges) are, however, available, but have
a different interface that does not use \f$x\f$-monotone curves.

<UL>

<LI>Invoking \link Arrangement_with_history_2::split_edge()
  `split_edge(e,p)`\endlink splits the edge `e` at a given point `p`
  that lies in its interior.

<LI>Invoking \link Arrangement_with_history_2::merge_edge()
  `merge_edge(e1,e2)`\endlink merges the two given edges. There is a
  precondition that `e1` and `e2` shared a common end-vertex of degree
  2 prior to the merge, and that the \f$x\f$-monotone subcurves
  associated with these edges are mergeable.

<LI>It is possible to remove an edge by simply invoking \link
  Arrangement_with_history_2::remove_edge()
  `remove_edge(e)`\endlink.</LI>

</UL>

In all cases, the maintenance of cross-pointers for the appropriate
input curves will be done automatically.

Note that it is possible to attach observers to an
arrangement-with-history object in order to get detailed notifications
of the changes the arrangements undergoes; see Section \ref
arr_ssecnotif for the details).


\cgalFigureBegin{aos_fig-curve_history,curve_history.png}
An arrangement with history as constructed in \ref
Arrangement_on_surface_2/curve_history.cpp. Note that \f$s_1\f$ and
\f$s_3\f$ overlap over two edges. The point-location query points
\f$q_1\f$, \f$q_2\f$, and \f$q_3\f$ are drawn as lightly shaded dots.
\cgalFigureEnd


In the following example we construct a simple arrangement of six line
segments, as depicted in \cgalFigureRef{aos_fig-curve_history}, while
maintaining the curve history. Note that the input segments \f$s_1\f$
and \f$s_3\f$ overlap over two edges. The example demonstrates the
usage of the special traversal functions. It also shows how to issue
point-location queries on the resulting arrangement (the query points
\f$q_1\f$, \f$q_2\f$, and \f$q_3\f$ are drawn as crosses), using the
auxiliary function `locate_point()` defined in the header file
`point_location_utils.h`; see also Section \ref arr_ssecpl.

\cgalExample{Arrangement_on_surface_2/curve_history.cpp}


\cgalFigureBegin{aos_fig-edge_manipulation_curve_history,edge_manipulation_curve_history.png}
An arrangement with history of nine circles as constructed in \ref
Arrangement_on_surface_2/edge_manipulation_curve_history.cpp. Note the
vertical tangency points of \f$c_0\f$, marked as dark dots, which
subdivide this circle into an upper half and a lower half, each
consists of 9 edges. The large circle \f$c_0\f$ is eventually removed
from the arrangement, with all 18 edges it induces.
\cgalFigureEnd


The following example demonstrates the usage of the free
`remove_curve()` function. We construct an arrangement of nine
circles, while keeping a handle to each inserted circle. We then
remove the large circle \f$c_0\f$, which induces \f$18\f$ edges, as
depicted in \cgalFigureRef{aos_fig-edge_manipulation_curve_history}.
The example also shows how to use the \link
Arrangement_with_history_2::split_edge() `split_edge()`\endlink and
\link Arrangement_with_history_2::merge_edge() `merge_edge()`\endlink
member functions when operating on an arrangement-with-history object.

\cgalExample{Arrangement_on_surface_2/edge_manipulation_curve_history.cpp}


\section aos_sec-io Input/Output Streams and Visualization


In some cases, one would like to save an arrangement object
constructed by some application, so that later on it can be
restored. In other cases one would like to create nice drawings that
represent arrangements constructed by some application. These
drawings can be hard printed or displayed on a computer screen.


\subsection aos_ssec-io-stream Input/Output Stream


Consider an arrangement that represents a very complicated geographical
map, and assume that there are various applications that need to answer
point-location queries on this map. Naturally, you can store the set of
curves that induces the arrangement, but this implies that you would need
to construct the arrangement from scratch each time you need to reuse it.
A more efficient solution is to write the arrangement to a file in a format
that other applications can read.

This package provides an <em>inserter</em> (the `<<` operator) and an
<em>extractor</em> (the `>>` operator) for the
`Arrangement_2<Traits,Dcel>` class that inserts an arrangement object
into an output stream and extracts an arrangement object from an input
stream, respectively. The arrangement is written using a simple
predefined \ascii format that encodes the arrangement topology, as well
as all geometric entities associated with vertices and edges.

The ability to use the input/output operators, requires that the \link
AosBasicTraits_2::Point_2 `Point_2`\endlink type and the \link
AosBasicTraits_2::X_monotone_curve_2
`X_monotone_curve_2`\endlink type defined by the traits class both
support the `<<` and `>>` operators. The `Arr_conic_traits_2` class
(see Section \ref arr_sssectr_conic), the
`Arr_rational_function_traits_2` class (see Section \ref
arr_sssectr_ratfunc), and the `Arr_linear_traits_2` class (see Section
\ref arr_ssectr_segs) currently do not provide these operators for the
geometric types they define.  Thus, only arrangements of line segments
or of polylines can be written or read.

The following example constructs the arrangement depicted in
\cgalFigureRef{aos_fig-special_edge_insertion} and writes it to an
output file. It also demonstrates how to re-read the arrangement from
a file.

\cgalExample{Arrangement_on_surface_2/io.cpp}


\subsection arr_ssecarr_io_aux_data Arrangements with Auxiliary Data


\cgalAdvancedBegin The inserter and extractor both ignore any
auxiliary data stored with the arrangement features. Thus, they are
ideal for arrangements instantiated using the default \dcel, which is
the instance `Arr_default_dcel<Traits>`.  However, as explained in
Section \ref arr_ssecex_dcel, one can easily extend the arrangement
faces by using the `Arr_face_extended_dcel` template, extend all \dcel
records by using the `Arr_extended_dcel` template, or use the
`Arr_dcel` template. In such cases, it might be crucial that the
auxiliary data fields are written to the file and read from there.

The arrangement package includes the free functions
`write(arr, os, formatter)`, which writes the arrangement `arr`
to an output stream `os`, and `read(arr, os, formatter)`, which
reads the arrangement `arr` from an input stream `is`. Both
operations are performed using a `formatter` object, which defines
the I/O format. The package contains three formatter classes:
<UL>
<LI>`Arr_text_formatter<Arrangement>` defines a simple textual
I/O format for the arrangement topology and geometry, disregarding any
auxiliary data that may be associated with the arrangement features.
This is the default formatter used by the arrangement inserter and the
arrangement extractor, as defined above.
<LI>`Arr_face_extended_text_formatter<Arrangement>` operates on
arrangements whose \dcel representation is based on the
`Arr_face_extended_dcel<Traits,FaceData>` class (see
Section \ref arr_sssecex_dcel_face). It supports reading and writing
the auxiliary data objects stored with the arrangement faces provided
that the `FaceData` class supports an inserter and an extractor.
<LI>`Arr_extended_dcel_text_formatter<Arrangement>` operates on
arrangements whose \dcel representation is based on the
`Arr_extended_dcel<Traits,VertexData,HalfedgeData,FaceData>` class
(see Section \ref arr_sssecex_dcel_all). It supports reading and writing
the auxiliary data objects stored with the arrangement vertices, edges
and faces, provided that the `VertexData`, `HalfedgeData` and
`FaceData` classed all have inserters and extractors.
</UL>

The following example constructs the same arrangement as the example
`dcel_extension` does (see Section \ref arr_sssecex_dcel_all),
depicted in \cgalFigureRef{aos_fig-dcel_extension}, and writes it to
an output file. It also demonstrates how to re-read the arrangement
from a file:

\cgalExample{Arrangement_on_surface_2/dcel_extension_io.cpp}

You may develop your own formatter classes - models of the
`AosInputFormatter` and `AosOutputFormatter`
concepts, as defined in the Reference Manual.
Doing so, you can define other I/O formats, such as an XML-based
format or a binary format.
\cgalAdvancedEnd


\subsection arr_ssecarr_io_hist Arrangements with Curve History


Section \ref arr_ssecarr_with_hist introduces the
`Arrangement_with_history_2<Traits,Dcel>` class, which saves the
set of curves inducing an arrangement and maintains the relations between
these curves and the edges they induce. Naturally, when reading or writing
an arrangement-with-history instance we would like this information to be
saved to the output stream or restored from the input stream alongside
with the basic arrangement structure.

The arrangement package supplies an inserter and an extractor for the
`Arrangement_with_history_2<Traits,Dcel>` class. The arrangement is
represented using a simple predefined \ascii format. An object of the
`Arrangement_with_history_2<Traits,Dcel>` type can be saved and
restored, as long as the \link Arrangement_with_history_2::Curve_2
`Curve_2`\endlink type defined by the traits class---as well as the
\link Arrangement_with_history_2::Point_2 `Point_2`\endlink type and
the \link Arrangement_with_history_2::X_monotone_curve_2
`X_monotone_curve_2`\endlink types---support the `<<` and`>>`
operators.

The following example constructs the same arrangement as example
`curve_history` does, depicted in \cgalFigureRef{aos_fig-curve_history}, and
writes it to an output file. It also demonstrates how to re-read the
arrangement-with-history from a file:

\cgalExample{Arrangement_on_surface_2/io_curve_history.cpp}

\cgalAdvancedBegin
The arrangement package also includes the free functions
`write(arr, os, formatter)` and `read(arr, os, formatter)` that operate
on a given arrangement-with-history instance `arr`.  Both functions are
parameterized by a `formatter` object, which defines the I/O
format. The package contains a template called,
`Arr_with_hist_text_formatter<ArranagmentFormatter>`, which extends an
arrangement formatter class (see Section \ref arr_ssecarr_io_aux_data)
and defines a simple textual input/output format.
\cgalAdvancedEnd


\subsection arr_ssecarr_io_vis Drawing an Arrangement


An arrangement data structure can be visualized by calling one of the
\link PkgArrangementOnSurface2Draw `CGAL::draw()` \endlink
overloaded template functions. Every variant opens a new window
showing the given arrangement. A call to any \link
PkgArrangementOnSurface2Draw `CGAL::draw()` \endlink function is
blocking; that is, the program continues execution only after the user
closes the window. The most simple variant accepts the arrangement to
draw and an optional string used as the title of the window. In the
following example we exploit a variant that also accepts an object the
type of which is an instance of the class template
`Graphics_scene_options`. It allows us to tune the drawings.

\cgalExample{Arrangement_on_surface_2/draw_arr.cpp}

This function requires `CGAL_Qt6`, and is only available if the macro
`CGAL_USE_BASIC_VIEWER` is defined.  Linking with the cmake target
`CGAL::CGAL_Basic_viewer` will link with `CGAL_Qt6` and add the
definition `CGAL_USE_BASIC_VIEWER`.

\cgalFigureBegin{aos_fig-draw_arr,draw_arr.png}
A snapshot of the window created by the program
\ref Arrangement_on_surface_2/draw_arr.cpp. The constructed arrangement consists
of 14 vertices, 15 edges, and 3 faces. Notice that the colors are generated at random.
\cgalFigureEnd

Another pair of overloaded \link PkgArrangementOnSurface2Draw
`CGAL::draw()` \endlink functions also accept a bounding box. Each
of these two variants can be ised to draw arrangements induced by
unbounded curves.


\section aos_sec-bgl Adapting to Boost Graphs


\boost\cgalFootnote{See also \boost's homepage at:
\cgalFootnoteCode{www.boost.org}.}  is a collection of portable \cpp libraries
that extend the \cpp Standard Library. The \boost Graph Library
(\bgl), which one of the libraries in the collection, offers an
extensive set of generic graph algorithms parameterized through
templates.  As our arrangements are embedded as planar graphs, it is
only natural to extend the underlying data structure with the
interface that the \bgl expects, and gain the ability to perform the
operations that the \bgl supports, such as shortest-path
computation. This section describes how to apply the graph algorithms
implemented in the \bgl to `Arrangement_2` instances.

An instance of `Arrangement_2` is adapted to a \boost graph through
the provision of a set of free functions that operate on the
arrangement features and conform with the relevant BGL
concepts. Besides the straightforward adaptation, which associates a
vertex with each \dcel vertex and an edge with each \dcel halfedge,
the package also offer a <em>dual</em> adaptor, which associates a
graph vertex with each \dcel face, such that two vertices are
connected, iff there is a \dcel halfedge that connects the two
corresponding faces.


\subsection arr_ssecbgl_primal The Primal Arrangement Representation


Arrangement instances are adapted to \boost graphs by specializing the
\link BGLArgtGT `boost::graph_traits` \endlink template for
`Arrangement_2` instances. The graph-traits states the graph concepts
that the arrangement class models (see below) and defines the types
required by these concepts.

In this specialization the `Arrangement_2` vertices correspond to the
graph vertices, where two vertices are adjacent if there is at least
one halfedge connecting them. More precisely, \link
Arrangement_on_surface_2::Vertex_handle `Vertex_handle`\endlink is the
graph-vertex type, while \link
Arrangement_on_surface_2::Halfedge_handle `Halfedge_handle`\endlink is
the graph-edge type. As halfedges are directed, we consider the graph
to be directed as well. Moreover, as several interior-disjoint
\f$x\f$-monotone curves (say circular arcs) may share two common
endpoints, inducing an arrangement with two vertices that are
connected with several edges, we allow parallel edges in our \boost.

Given an `Arrangement_2` instance, we can efficiently traverse its
vertices and halfedges. Thus, the arrangement graph is a model of the
concepts `VertexListGraph` and `EdgeListGraph` introduced by the \bgl.
At the same time, we use an iterator adapter of the circulator over
the halfedges incident to a vertex
(`Halfedge_around_vertex_circulator` - see Section \ref
arr_sssectr_vertex), so it is possible to go over the ingoing and
outgoing edges of a vertex in linear time. Thus, our arrangement graph
is a model of the concept `BidirectionalGraph` (this concept refines
`IncidenceGraph`, which requires only the traversal of outgoing
edges).

It is important to notice that the vertex descriptors we use are \link
Arrangement_2 Vertex_handle `Vertex_handle`\endlink objects and
<em>not</em> vertex indices. However, in order to gain more efficiency
in most \bgl algorithms, it is better to have them indexed \f$0, 1,
\ldots, (n-1)\f$, where \f$n\f$ is the number of vertices. We
therefore introduce the `Arr_vertex_index_map<Arrangement>`
class-template, which maintains a mapping of vertex handles to
indices, as required by the \bgl. An instance of this class must be
attached to a valid arrangement vertex when it is created. It uses the
notification mechanism (see Section \ref arr_ssecnotif) to
automatically maintain the mapping of vertices to indices, even when
new vertices are inserted into the arrangement or existing vertices
are removed.

In most algorithms provided by the \bgl, the output is given by
<em>property maps</em>, such that each map entry corresponds to a
vertex.  For example, when we compute the shortest paths from a given
source vertex \f$s\f$ to all other vertices we can obtain a map of
distances and a map of predecessors - namely for each \f$v\f$ vertex
we have its distance from \f$s\f$ and a descriptor of the vertex that
precedes \f$v\f$ in a shortest path from \f$s\f$.

If the vertex descriptors are simply indices, boost supplies tools to
easily represent property maps using vectors.  The
`Arr_vertex_index_map<Arrangement>` class template enables the
creation of such indices, and together with
`boost::vector_property_map<Type, IndexMap>` it generates an efficient
mapping from \link Arrangement_on_surface_2::Vertex_handle
`Vertex_handle`\endlink objects to properties of type `Type`. Note,
however, that unlike the `Arr_vertex_index_map` class template, the
vertex property-map class is not kept synchronized with the number of
vertices in the arrangement, so it should not be reused in calls to
\bgl functions in case the arrangement is modified in between these
calls.

The first example of this section demonstrates the application of
Dijkstra's shortest path algorithm to compute the shortest-path length
between a given vertex of an arrangement of linear curves and all
other vertices. The length of a path is defined as the sum of squared
Euclidean lengths of its segments. It uses an instance of the functor
template `Edge_length<Arrangement>}` to compute the squared Euclidean
length of the linear curve associated with a given halfedge of the
arrangement. The functor implements a \boost property-map that
attaches square lengths to edges; when the \bgl algorithm queries the
property map for a squared length of an edge the property map computes
and returns it. The functor template is defined in the header file
`Edge_length.h`.

\code
#include <CGAL/Exact_predicates_exact_constructions_kernel.h>
#include <CGAL/property_map.h>

using Kernel = CGAL::Exact_predicates_exact_constructions_kernel;
using Number_type = Kernel::FT;

template <typename Arrangement> struct Edge_length {
  // Boost property-type definitions.
  using category = boost::readable_property_map_tag;
  using value_type = Number_type;
  using reference = value_type;
  using key_type = typename Arrangement::Halfedge_handle;

  value_type operator()(typename Arrangement::Halfedge_handle e) const {
    const auto diff_x = e->target()->point().x() - e->source()->point().x();
    const auto diff_y = e->target()->point().y() - e->source()->point().y();
    return diff_x * diff_x + diff_y * diff_y;
  }

  friend value_type get(const Edge_length& edge_length, key_type key)
  { return edge_length(key); }
};
\endcode


\cgalFigureBegin{aos_fig-bgl_primal_adapter,bgl_primal_adapter.png}
An arrangement of seven line segments, as constructed by
\ref Arrangement_on_surface_2/bgl_primal_adapter.cpp and
\ref Arrangement_on_surface_2/bgl_dual_adapter.cpp.
\cgalFigureEnd


In the following example we construct an arrangement of seven line
segments, as shown in \cgalFigureRef{aos_fig-bgl_primal_adapter}.
Then, it uses the \bgl generic implementation of Dijkstra's
shortest-paths algorithm to compute the sum of squared distances to
all vertices from the lexicographically smallest vertex \f$v_0\f$ in
the arrangement. Note the usage of the `Arr_vertex_property_map` class
template in the call to `boost::dijkstra_shortest_paths()` and in the
definition of the distance property-map. We instantiate a property map
that attaches a number of type `Number_type` (which is a type of
unlimited precision) to each vertex. The number represents the sum of
squared distances of the vertex from \f$v_0\f$.

\cgalExample{Arrangement_on_surface_2/bgl_primal_adapter.cpp}


\subsection arr_ssecbgl_dual The Dual Arrangement Representation


An arrangement instance can be represented as a graph other than the
one described in the previous section. A dual-graph representation
refers to the graph, where each arrangement face corresponds to a
graph vertex, and two vertices are adjacent iff the corresponding faces
share a common edge on their boundaries. This is done by specializing
the `boost::graph_traits` template for `Dual<Arrangement_2>` instances,
where `Dual<Arrangement_2>` is a template specialization that gives a
dual interpretation to an arrangement instance.

In a dual representation, \link Arrangement_on_surface_2::Face_handle
`Face_handle`\endlink is the graph-vertex type, while \link
Arrangement_on_surface_2::Halfedge_handle `Halfedge_handle`\endlink is
the graph-edge type. We treat the graph edges as directed, such that a
halfedge `e` is directed from \f$f_1\f$, which is its incident face,
to \f$f_2\f$, which is the incident face of its twin halfedge. As two
arrangement faces may share more than a single edge on their boundary,
we allow parallel edges (loops) in our \boost graph. As is the case in
the primal graph, the dual arrangement graph is also a model of the
concepts `VertexListGraph`, `EdgeListGraph` and `BidirectionalGraph`
(thus also of `IncidenceGraph`).

Since we use \link Arrangement_on_surface_2::Face_handle
`Face_handle`\endlink objects as the vertex descriptors, we define the
`Arr_face_index_map<Arrangement>` class-template, which maintains an
efficient mapping of face handles to indices.

The next example demonstrates how a property map can be used to update
or receive information directly from a feature of the arrangement
without the need to search for its index. The example also
demonstrates the application of the breadth-first search} (BFS)
algorithm on a dual arrangement. It uses the functor template
`Extended_face_property_map<Arrangement, Type>` to directly access
information stored inside the faces. The functor implements a property
map that utilizes the `data()` and `set_data()` member functions of the
extended face to update or obtain the property. When the property map
is instantiated, the `Type` parameter must be substituted by the
same type that is used to extend the arrangement face; see Section
\ref arr_sssecex_dcel_face. The functor template is defined in the
header file `Extended_face_property_map.h` listed below.

\code
// A property map that reads/writes the information to/from the extended face.
template <typename Arrangement, class Type> class Extended_face_property_map {
public:
  using Face_handle = typename Arrangement::Face_handle;

  // Boost property type definitions.
  using category = boost::read_write_property_map_tag;
  using value_type = Type;
  using reference = value_type&;
  using key_type = Face_handle;

  // The get function is required by the property map concept.
  friend reference get(const Extended_face_property_map& map, key_type key)
  { return key->data(); }

  // The put function is required by the property map concept.
  friend void put(const Extended_face_property_map& map,
                  key_type key, value_type val)
  { key->set_data(val); }
};
\endcode


\cgalFigureBegin{aos_fig-bgl_dual_adapter,bgl_dual_adapter.png}
An arrangement of seven line segments, as constructed by \ref
Arrangement_on_surface_2/bgl_dual_adapter.cpp and its dual face graph,
where every arrangement face is a vertex of the graph. The index of a
dual vertex is the discovery time of a breadth-first search applied to
the face graph, starting from the unbounded face \f$f_0\f$.
\cgalFigureEnd


The following example constructs the same arrangement constructed by
the program coded in \ref
Arrangement_on_surface_2/bgl_primal_adapter.cpp; see
\cgalFigureRef{aos_fig-bgl_primal_adapter}. Then, it performs a
breadth-first search traversal on the face graph, starting from the
unbounded face. The \dcel faces are extended with an unsigned
integer indicating the discovered time of the face. The code uses a
visitor that obtains the times and writes them into a property map
that updates the faces
accordingly. \cgalFigureRef{aos_fig-bgl_dual_adapter} shows the graph
dual to the arrangement. It is clear that the unbounded face \f$f_0\f$
is discovered at time \f$0\f$, the neighboring faces \f$f_1\f$,
\f$f_3\f$, and \f$f_4\f$ are discovered at times \f$1\f$, \f$2\f$, and
\f$3\f$, and finally \f$f_2\f$ is discovered at time \f$4\f$.

\cgalExample{Arrangement_on_surface_2/bgl_dual_adapter.cpp}


\section aos_sec-tips How To Speed Up Your Computation


Before the specific tips, we remind you that compiling programs with
debug flags disabled and with optimization flags enabled significantly
reduces the running time.

<OL>

<LI>When the curves to be inserted into an arrangement are
\f$x\f$-monotone and pairwise disjoint in their interior to start
with, then it is more efficient (in running time) and less demanding
(in traits-class functionality) to use the non-intersecting
insertion-functions instead of the general ones; e.g., `insert()`.

<LI>When the curves to be inserted into an arrangement are segments that
are pairwise disjoint in their interior, it is more efficient to use
the traits class `Arr_non_caching_segment_traits_2` rather than
the default one (`Arr_segment_traits_2`).

If the segments may intersect each other, the default traits class
`Arr_segment_traits_2` can be safely used with the somehow limited
number type `Quotient<MP_float>`.

On rare occasions the traits class `Arr_non_caching_segment_traits_2`
exhibits slightly better performance than the default one
(`Arr_segment_traits_2` even when the segments intersect each other,
due to the small overhead of the latter (optimized) traits class. (For
example, when the so-called \leda rational kernel is used.)

<LI>Prior knowledge of the combinatorial structure of the arrangement
can be used to accelerate operations that insert \f$x\f$-monotone
curves, whose interior is disjoint from existing edges and vertices of
the arrangement. The specialized insertion functions, i.e.,
`Arrangement_on_surface_2::insert_in_face_interior()`,
`Arrangement_on_surface_2::insert_from_left_vertex()`,
`Arrangement_on_surface_2::insert_from_right_vertex()`, and
`Arrangement_on_surface_2::insert_at_vertices()` can be used according
to the available information. These functions hardly involve any
geometric operations, if at all. They accept topologically related
parameters, and use them to operate directly on the \dcel records,
thus saving algebraic operations, which are especially expensive when
high-degree curves are involved.

A polygon, represented by a list of segments along its boundary, can
be inserted into an empty arrangement as follows. First, one segment
is inserted using
`Arrangement_on_surface_2::insert_in_face_interior()` into the
unbounded face. Then, a segment with a common end point is inserted
using either `Arrangement_on_surface_2::insert_from_left_vertex()` or
`Arrangement_on_surface_2::insert_from_right_vertex()`, and so on with
the rest of the segments except for the last, which is inserted using
`Arrangement_on_surface_2::insert_at_vertices()`, as both endpoints of
which are the mapping of known vertices.

<LI>The main trade-off among point-location strategies is between
time and storage. Using the naive or walk strategies, for example,
takes more query time but does not require preprocessing or
maintenance of auxiliary structures and saves storage space.

<LI>If point-location queries are not performed frequently, but other
modifying functions, such as removing, splitting, or merging edges
are, then using a point-location strategy that does not require the
maintenance of auxiliary structures, such as the naive or walk
strategies, is preferable.

<LI>There is a trade-off between two modes of the trapezoidal RIC
strategy that enables the user to choose whether preprocessing should
be performed or not. If preprocessing is not used, the creation of the
structure is faster. However, for some input sequences the structure
might be unbalanced and therefore queries and updates might take
longer, especially, if many removal and split operations are
performed.

<LI>When the curves to be inserted into an arrangement are available
in advance (as opposed to supplied on-line), it is advised to use the
more efficient aggregate (sweep-based) insertion over the incremental
insertion; e.g., \link insert<Traits,Dcel,InputIterator>()
`insert(arr, first, last)`\endlink.

<LI>The various traits classes should be instantiated with an exact
number type to ensure robustness when the input of the operations to
be carried out might be degenerate. Inexact number types can be used
at the user's own risk.

<LI>Maintaining short bit-lengths of coordinate representations may
drastically decrease the time consumption of arithmetic operations on
the coordinates. This can be achieved by caching certain information
or normalization (of rational numbers). However, both solutions should
be used cautiously, as the former may lead to an undue space
consumption, and indiscriminate normalization may considerably slow
down the overall process.

<LI>Geometric functions (e.g., traits methods) dominate the time
consumption of most operations. Thus, calls to such function should be
avoided or at least their number should be decreased, perhaps at the
expense of increased combinatorial-function calls or increased space
consumption. For example, repetition of geometric-function calls could
be avoided by storing the results obtained by the first call, and
reusing them when needed.
</OL>


\section aos_sec-design Design and Implementation History


The code of this package is the result of a long development process.
Initially (and until version 3.1), the code was spread among several
components, namely, `Topological_map`, `Planar_map_2`,
`Planar_map_with_intersections_2` and `Arrangement_2`, that were
developed by Ester Ezra, Eyal Flato, Efi Fogel, Dan Halperin, Iddo
Hanniel, Idit Haran, Shai Hirsch, Eugene Lipovetsky, Oren Nechushtan,
Sigal Raab, Ron Wein, Baruch Zukerman, and Tali Zvi.

In version 3.2, as part of the ACS project, the packages have gone
through a major re-design, resulting in an improved and unified
<em>2D Arrangements</em> package.
The code of the new package was restructured and developed by
Efi Fogel, Idit Haran, Ron Wein, and Baruch Zukerman. This
version included for the first time a new geometry-traits
class that handles circular and linear curves, and is based
on the circular kernel. The circular kernel was developed
by Monique Teillaud, Sylvain Pion, and Julien Hazebrouck.

Version 3.3 features arrangements of unbounded curves for the first
time. The design and development of this feature required yet another
restructuring of the entire package. All this was done by Eric
Berberich, Efi Fogel, Dan Halperin, Ophir Setter, and Ron
Wein. Michael Hemmer helped tuning up parts of the geometry-traits
concept related to unbounded curves.

Version 3.7 introduced a geometry-traits class
that handles planar algebraic curves of arbitrary degree.
It was developed by Eric Berberich and Michael Kerber.

Version 3.9 introduced a new geometry-traits class that handles
rational arcs. It was developed by Oren Salzman and Michael Hemmer.
It replaced an old traits, which handled the same family of
curves, developed by Ron Wein.

Version 4.1 introduces a revised implementation of the point location class
via a randomized incremental construction of the trapezoidal map.
The old class was implemented by Oren Nechushtan, while the revamp
was done by Michal Kleinbort and Michael Hemmer. The new class adds support
for unbounded curves and can now guarantee logarithmic query time in all
cases.

*/
} /* namespace CGAL */

---

### Arrangement On Surface 2 Doc Arrangement On Surface 2 PackageDescription (`Arrangement_on_surface_2/doc/Arrangement_on_surface_2/PackageDescription.txt`)

/// \defgroup PkgArrangementOnSurface2Ref Reference Manual

/// \defgroup PkgArrangementOnSurface2Concepts Concepts
/// \ingroup PkgArrangementOnSurface2Ref

/// \cgalConceptNamespace
/// The namespace containing concepts specific to Arrangements.
namespace AosTraits {}

/// \defgroup PkgArrangementOnSurface2ConceptsTopologyTraits Topology Traits Concepts
/// \ingroup PkgArrangementOnSurface2Concepts

/// \defgroup PkgArrangementOnSurface2ConceptsDCEL DCEL Concepts
/// \ingroup PkgArrangementOnSurface2Concepts

/// \defgroup PkgArrangementOnSurface2ConceptsGeometricObjects Geometric Object Concepts
/// \ingroup PkgArrangementOnSurface2Concepts

/// \defgroup PkgArrangementOnSurface2ConceptsFunctionObjects Function Object Concepts
/// \ingroup PkgArrangementOnSurface2Concepts

/// \defgroup PkgArrangementOnSurface2ConceptsTraits Geometry Traits Concepts
/// \ingroup PkgArrangementOnSurface2Concepts

/// \defgroup PkgArrangementOnSurface2TraitsClasses Geometry Traits Classes
/// \ingroup PkgArrangementOnSurface2Ref

/// \defgroup PkgArrangementOnSurface2DCEL DCEL
/// \ingroup PkgArrangementOnSurface2Ref

/// \defgroup PkgArrangementOnSurface2IO I/O
/// \ingroup PkgArrangementOnSurface2Ref

/// \defgroup PkgArrangementOnSurface2op_left_shift operator<<
/// \ingroup PkgArrangementOnSurface2IO

/// \defgroup PkgArrangementOnSurface2op_right_shift operator>>
/// \ingroup PkgArrangementOnSurface2IO

/// \defgroup PkgArrangementOnSurface2PointLocation Point Location
/// \ingroup PkgArrangementOnSurface2Ref

/// \defgroup PkgArrangementOnSurface2Overlay Overlay
/// \ingroup PkgArrangementOnSurface2Ref

/// \defgroup PkgArrangementOnSurface2Funcs Free Functions
/// \ingroup PkgArrangementOnSurface2Ref

/*!
\cgalInclude{CGAL/draw_arrangement_2.h}
*/
/// \defgroup PkgArrangementOnSurface2Draw Drawing
/// \ingroup PkgArrangementOnSurface2Ref

/// \defgroup PkgArrangementOnSurface2Insert CGAL::insert()
/// \ingroup PkgArrangementOnSurface2Funcs

/// \defgroup PkgArrangementOnSurface2Tags Tags
/// \ingroup PkgArrangementOnSurface2Ref

/// \defgroup PkgArrangementOnSurface2Macros Macros
/// \ingroup PkgArrangementOnSurface2Ref

/// \defgroup PkgArrangementOnSurface2Enums Enumerations
/// \ingroup PkgArrangementOnSurface2Ref

/*!
\addtogroup PkgArrangementOnSurface2Ref
\cgalPkgDescriptionBegin{2D Arrangements,PkgArrangementOnSurface2}
\cgalPkgPicture{Arrangement_2.png}
\cgalPkgSummaryBegin
\cgalPkgAuthors{Ron Wein, Eric Berberich, Efi Fogel, Dan Halperin, Michael Hemmer, Oren Salzman, and Baruch Zukerman}
\cgalPkgDesc{This package can be used to construct, maintain, alter, and display arrangements in the plane. Once an arrangement is constructed, the package can be used to obtain results of various queries on the arrangement, such as point location. The package also includes generic implementations of two algorithmic frameworks, that are, computing the zone of an arrangement, and line-sweeping the plane, the arrangements is embedded on. These frameworks are used in turn in the implementations of other operations on arrangements. Computing the overlay of two arrangements, for example, is based on the sweep-line framework.   Arrangements and arrangement components can also be extended to store additional data. An important extension stores the construction history of the arrangement, such that it is possible to obtain the originating curve of an arrangement subcurve.}
\cgalPkgManuals{Chapter_2D_Arrangements,PkgArrangementOnSurface2Ref}
\cgalPkgSummaryEnd
\cgalPkgShortInfoBegin
\cgalPkgSince{2.1}
\cgalPkgBib{cgal:wfzh-a2}
\cgalPkgLicense{\ref licensesGPL "GPL"}
\cgalPkgDemo{2D Arrangements,arrangements_2.zip}
\cgalPkgShortInfoEnd
\cgalPkgDescriptionEnd

Given a set \f$\mathcal{C}\f$ of planar curves, the <I>arrangement</I>
\f$ {\mathcal A}({\mathcal C})\f$ is the subdivision of the plane induced
by the curves in \f$\mathcal{C}\f$ into maximally connected cells. The cells
can be \f$0\f$-dimensional (<I>vertices</I>), \f$1\f$-dimensional (<I>edges</I>)
or \f$2\f$-dimensional (<I>faces</I>).

The class `CGAL::Arrangement_2<Traits,Dcel>` encapsulates a data structure
that maintains arrangements of arbitrary bounded planar curves. It comes
with a variety of algorithms that operate on planar arrangement,
such as point-location queries and overlay computations, which are
implemented as peripheral classes or as free (global) functions.

\cgalClassifedRefPages

\cgalCRPSection{Enumerations}

- `CGAL::Arr_parameter_space`
- `CGAL::Arr_curve_end`
- `CGAL::Arr_halfedge_direction`

\cgalCRPSection{Tags}

- `CGAL::Arr_oblivious_side_tag`
- `CGAL::Arr_open_side_tag`
- `CGAL::Arr_closed_side_tag`
- `CGAL::Arr_contracted_side_tag`
- `CGAL::Arr_identified_side_tag`

\cgalCRPSection{Concepts}

- `AosApproximateTraits_2`
- `AosApproximatePointTraits_2`
- `AosApproximateUnboundedTraits_2`
- `AosBasicTopologyTraits`
- `AosBasicTraits_2`
- `AosBottomSideTraits_2`
- `AosClosedBottomTraits_2`
- `AosClosedLeftTraits_2`
- `AosClosedRightTraits_2`
- `AosClosedTopTraits_2`
- `AosConstructCurveTraits_2`
- `AosConstructXMonotoneCurveTraits_2`
- `AosContractedBottomTraits_2`
- `AosContractedLeftTraits_2`
- `AosContractedRightTraits_2`
- `AosContractedTopTraits_2`
- `AosDcel`
- `AosDcelFace`
- `AosDcelHalfedge`
- `AosDcelInnerCcb`
- `AosDcelIsolatedVertex`
- `AosDcelOuterCcb`
- `AosDcelVertex`
- `AosDcelWithRebind`
- `AosHorizontalSideTraits_2`
- `AosIdentifiedHorizontalTraits_2`
- `AosIdentifiedVerticalTraits_2`
- `AosInputFormatter`
- `AosLandmarkTraits_2`
- `AosLeftSideTraits_2`
- `AosOpenBottomTraits_2`
- `AosOpenBoundaryTraits_2`
- `AosOpenLeftTraits_2`
- `AosOpenRightTraits_2`
- `AosOpenTopTraits_2`
- `AosOutputFormatter`
- `AosPointLocation_2`
- `AosRightSideTraits_2`
- `AosSphericalBoundaryTraits_2`
- `AosTopologyTraits`
- `AosTopSideTraits_2`
- `AosTraits_2`
- `AosVerticalRayShoot_2`
- `AosVerticalSideTraits_2`
- `AosWithHistoryInputFormatter`
- `AosWithHistoryOutputFormatter`
- `AosXMonotoneTraits_2`

\cgalCRPSection{Geometric Object Concepts}

- `AosTraits::Point_2`
- `AosTraits::XMonotoneCurve_2`
- `AosTraits::Curve_2`

\cgalCRPSection{Function Object Concepts}

- `AosTraits::Approximate_2`
- `AosTraits::ApproximatePoint_2`
- `AosTraits::ApproximateUnbounded_2`
- `AosTraits::AreMergeable_2`
- `AosTraits::CompareX_2`
- `AosTraits::CompareXy_2`
- `AosTraits::CompareYAtX_2`
- `AosTraits::CompareYAtXLeft_2`
- `AosTraits::CompareYAtXRight_2`
- `AosTraits::ConstructMinVertex_2`
- `AosTraits::ConstructMaxVertex_2`
- `AosTraits::CompareXOnBoundary_2`
- `AosTraits::CompareYOnBoundary_2`
- `AosTraits::CompareXNearBoundary_2`
- `AosTraits::CompareYNearBoundary_2`
- `AosTraits::CompareXOnBoundaryOfCurveEnd_2`
- `AosTraits::ConstructCurve_2`
- `AosTraits::ConstructXMonotoneCurve_2`
- `AosTraits::DoIntersect_2`
- `AosTraits::Equal_2`
- `AosTraits::Intersect_2`
- `AosTraits::IsVertical_2`
- `AosTraits::IsOnXIdentification_2`
- `AosTraits::IsOnYIdentification_2`
- `AosTraits::MakeXMonotone_2`
- `AosTraits::Merge_2`
- `AosTraits::ParameterSpaceInX_2`
- `AosTraits::ParameterSpaceInY_2`
- `AosTraits::Split_2`

\cgalCRPSection{Classes}

- `CGAL::Arrangement_on_surface_2<GeometryTraits_2,TopologyTraits>`
- `CGAL::Arrangement_on_surface_with_history_2<GeometryTraits_2,TopologyTraits>`
- `CGAL::Arrangement_2<Traits,Dcel>`
- `CGAL::Arrangement_with_history_2<Traits,Dcel>`
- `CGAL::Arrangement_2::Vertex`
- `CGAL::Arrangement_2::Halfedge`
- `CGAL::Arrangement_2::Face`
- `CGAL::Arr_accessor<Arrangement>`
- `CGAL::Arr_algebraic_segment_traits_2<Coefficient>`
- `CGAL::Arr_Bezier_curve_traits_2<RatKernel,AlgKernel,NtTraits>`
- `CGAL::Arr_bounded_planar_topology_traits_2<GeometryTraits_2,Dcel>`
- `CGAL::Arr_circle_segment_traits_2<Kernel>`
- `CGAL::Arr_circular_arc_traits_2<CircularKernel>`
- `CGAL::Arr_circular_line_arc_traits_2<CircularKernel>`
- `CGAL::Arr_conic_traits_2<RatKernel,AlgKernel,NtTraits>`
- `CGAL::Arr_consolidated_curve_data_traits_2<Traits,Data>`
- `CGAL::Arr_counting_traits_2<BaseTraits>`
- `CGAL::Arr_curve_data_traits_2<Tr,XData,Mrg,CData,Cnv>`
- `CGAL::Arr_dcel_base<V,H,F>`
- `CGAL::Arr_dcel<Traits,V,H,F>`
- `CGAL::Arr_default_dcel<Traits>`
- `CGAL::Arr_face_extended_dcel<Traits,FData,V,H,F>`
- `CGAL::Arr_face_index_map<Arrangement>`
- `CGAL::Arr_extended_dcel<Traits,VData,HData,FData,V,H,F>`
- `CGAL::Arr_extended_dcel_text_formatter<Arrangement>`
- `CGAL::Arr_face_extended_text_formatter<Arrangement>`
- `CGAL::Arr_geodesic_arc_on_sphere_traits_2<Kernel,x,y>`
- `CGAL::Arr_landmarks_point_location<Arrangement,Generator>`
- `CGAL::Arr_line_arc_traits_2<CircularKernel>`
- `CGAL::Arr_linear_traits_2<Kernel>`
- `CGAL::Arr_naive_point_location<Arrangement>`
- `CGAL::Arr_non_caching_segment_traits_2<Kernel>`
- `CGAL::Arr_observer<Arrangement_2>`
- `CGAL::Arr_polyline_traits_2<SegmentTraits>`
- `CGAL::Arr_point_location_result<Arrangement>`
- `CGAL::Arr_rational_function_traits_2<AlgebraicKernel_d_1>`
- `CGAL::Arr_segment_traits_2<Kernel>`
- `CGAL::Arr_spherical_topology_traits_2<GeometryTraits_2,Dcel>`
- `CGAL::Arr_text_formatter<Arrangement>`
- `CGAL::Arr_tracing_traits_2<BaseTraits>`
- `CGAL::Arr_trapezoid_ric_point_location<Arrangement>`
- `CGAL::Arr_unb_planar_topology_traits_2<GeometryTraits_2,Dcel>`
- `CGAL::Arr_vertex_index_map<Arrangement>`
- `CGAL::Arr_walk_along_line_point_location<Arrangement>`
- `CGAL::Arr_with_history_text_formatter<ArrFormatter>`
- `CGAL::Aos_observer<ArrangementOnSurface_2>`
- `CGAL::CORE_algebraic_number_traits`

\cgalCRPSection{Functions}

- `CGAL::is_valid()`
- `CGAL::insert()`
- `CGAL::insert_non_intersecting_curve()`
- `CGAL::insert_non_intersecting_curves()`
- `CGAL::insert_point()`
- `CGAL::remove_edge()`
- `CGAL::remove_vertex()`
- `CGAL::locate()`
- `CGAL::decompose()`
- `CGAL::overlay()`
- `CGAL::IO::read()`
- `CGAL::IO::write()`
- `CGAL::remove_curve()`
- \link PkgArrangementOnSurface2op_left_shift `CGAL::operator<<` \endlink
- \link PkgArrangementOnSurface2op_right_shift `CGAL::operator<<` \endlink

\cgalCRPSection{Draw an `Arrangemen_2` object}
- \link PkgArrangementOnSurface2Draw CGAL::draw<>() \endlink

*/

---

### Arrangement On Surface 2 Doc Arrangement On Surface 2 Examples (`Arrangement_on_surface_2/doc/Arrangement_on_surface_2/examples.txt`)

/*!
 * \example Arrangement_on_surface_2/aggregated_insertion.cpp
 * \example Arrangement_on_surface_2/algebraic_curves.cpp
 * \example Arrangement_on_surface_2/algebraic_segments.cpp
 * \example Arrangement_on_surface_2/batched_point_location.cpp
 * \example Arrangement_on_surface_2/Bezier_curves.cpp
 * \example Arrangement_on_surface_2/bgl_dual_adapter.cpp
 * \example Arrangement_on_surface_2/bgl_primal_adapter.cpp
 * \example Arrangement_on_surface_2/bounded_vertical_decomposition.cpp
 * \example Arrangement_on_surface_2/circles.cpp
 * \example Arrangement_on_surface_2/circular_arcs.cpp
 * \example Arrangement_on_surface_2/conics.cpp
 * \example Arrangement_on_surface_2/conic_multiplicities.cpp
 * \example Arrangement_on_surface_2/consolidated_curve_data.cpp
 * \example Arrangement_on_surface_2/count_and_trace.cpp
 * \example Arrangement_on_surface_2/curve_history.cpp
 * \example Arrangement_on_surface_2/dcel_extension.cpp
 * \example Arrangement_on_surface_2/dcel_extension_io.cpp
 * \example Arrangement_on_surface_2/draw_agas.cpp
 * \example Arrangement_on_surface_2/draw_arr.cpp
 * \example Arrangement_on_surface_2/dual_lines.cpp
 * \example Arrangement_on_surface_2/dual_with_data.cpp
 * \example Arrangement_on_surface_2/edge_insertion.cpp
 * \example Arrangement_on_surface_2/edge_manipulation.cpp
 * \example Arrangement_on_surface_2/edge_manipulation_curve_history.cpp
 * \example Arrangement_on_surface_2/ellipses.cpp
 * \example Arrangement_on_surface_2/face_extension.cpp
 * \example Arrangement_on_surface_2/face_extension_overlay.cpp
 * \example Arrangement_on_surface_2/generic_curve_data.cpp
 * \example Arrangement_on_surface_2/global_insertion.cpp
 * \example Arrangement_on_surface_2/global_removal.cpp
 * \example Arrangement_on_surface_2/hyperbolas.cpp
 * \example Arrangement_on_surface_2/incremental_insertion.cpp
 * \example Arrangement_on_surface_2/io.cpp
 * \example Arrangement_on_surface_2/io_curve_history.cpp
 * \example Arrangement_on_surface_2/io_unbounded.cpp
 * \example Arrangement_on_surface_2/isolated_vertices.cpp
 * \example Arrangement_on_surface_2/linear_conics.cpp
 * \example Arrangement_on_surface_2/observer.cpp
 * \example Arrangement_on_surface_2/overlay.cpp
 * \example Arrangement_on_surface_2/overlay_color.cpp
 * \example Arrangement_on_surface_2/overlay_unbounded.cpp
 * \example Arrangement_on_surface_2/parabolas.cpp
 * \example Arrangement_on_surface_2/point_location.cpp
 * \example Arrangement_on_surface_2/polycurve_bezier.cpp
 * \example Arrangement_on_surface_2/polycurve_circular_arc.cpp
 * \example Arrangement_on_surface_2/polycurve_conic.cpp
 * \example Arrangement_on_surface_2/polycurve_geodesic.cpp
 * \example Arrangement_on_surface_2/polylines.cpp
 * \example Arrangement_on_surface_2/predefined_kernel.cpp
 * \example Arrangement_on_surface_2/predefined_kernel_non_intersecting.cpp
 * \example Arrangement_on_surface_2/rational_functions.cpp
 * \example Arrangement_on_surface_2/special_edge_insertion.cpp
 * \example Arrangement_on_surface_2/spherical_insert.cpp
 * \example Arrangement_on_surface_2/unbounded_non_intersecting.cpp
 * \example Arrangement_on_surface_2/unbounded_rational_functions.cpp
 * \example Arrangement_on_surface_2/unb_planar_vertical_decomposition.cpp
 * \example Arrangement_on_surface_2/vertical_ray_shooting.cpp
 */

---

### BGL Doc BGL BGL (`BGL/doc/BGL/BGL.txt`)

namespace CGAL {
/*!

\mainpage User Manual
\anchor Chapter_CGAL_and_the_Boost_Graph_Library
\anchor chapterBGL
\cgalAutoToc
\authors Andreas Fabri, Fernando Cacciola, Philipp Moeller, and Ron Wein

Many geometric data structures can be interpreted as graphs as they consist of
vertices and edges. This is the case for the halfedge data structure,
for the polyhedral surface, for the arrangement, and for the 2D triangulation classes. With means of
duality one can also interpret faces as vertices and edges between adjacent
faces as edges of the dual graph.

The scope of \cgal is geometry and not graph algorithms. Nevertheless, this package
provides the necessary classes and functions that enable using the
algorithms of the <A HREF="https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/index.html">Boost Graph Library</A> \cgalCite{cgal:sll-bgl-02}
(\bgl for short) with \cgal data structures.
Furthermore, this package extends the \bgl
by introducing concepts such as `HalfedgeGraph` and `FaceGraph`
allowing to handle *halfedges* and *faces*.
These concepts reflect the design of the halfedge data structure described
in Chapter \ref PkgHalfedgeDS, with opposite halfedges and circular
sequences of halfedges around vertices and around faces.

This chapter is organized as follows:
- The first section, Section \ref BGLA, summarizes the main ideas of the \bgl.
- Section \ref BGLHeader then explains where to find header files and the chosen naming conventions, as we blend two
different libraries.
- The four following sections give examples on how to use CGAL graph and mesh data structures
such as
\link PkgSurfaceMesh Surface_mesh \endlink,
\link PkgPolyhedron Polyhedron \endlink,
\link PkgArrangementOnSurface2 Arrangement_2 \endlink, and the
\link PkgTriangulation2 2D triangulation \endlink classes as models of the \bgl concepts.
- Starting with Section \ref BGLExtensions, we introduce new graph concepts, classes,
and functions that extend the functionalities of the \bgl.

\section BGLA A Short Introduction to the Boost Graph Library

The algorithms of the \bgl operate on models of various <I>graph concepts</I>.
The <I>traits class</I> `boost::graph_traits` enable algorithms to determine the types of vertices and edges
(similar to `std::iterator_traits` for iterators).
<I>Free functions</I> that operate on graphs enable algorithms to obtain,
for example, the source vertex of an edge, or all edges incident to a vertex. The algorithms
use <I>property maps</I> to associate information with vertices and edges.
The algorithms enable <I>visitors</I> to register callbacks that are called
later on during the execution of the algorithms. Finally, the graph algorithms use
the <I>named parameter</I> mechanism, which enables passing the arguments in
arbitrary order.

\subsection BGLGraphConcepts Graph Concepts

The \bgl introduces several <a href="https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/concepts/graph_concepts.html">graph concepts</a>,
which have different sets of characteristics and requirements.
For example, iterating through all vertices or all edges in a graph, obtaining the outgoing
or in-going edges of a vertex, inserting vertices and edges into a graph,
and removing vertices and edges from a graph.

\subsection BGLTheGraphTraitsClass The Graph Traits Class

An algorithm operating on a graph model determines types with the help of the traits class
<a href="https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/traits/graph_traits.html">boost::graph_traits</a>.
Such types are the `vertex_descriptor`,
which is similar to a vertex handle in \cgal data structures, or
the `edge_descriptor`, which is similar to the \link HalfedgeDSHalfedge halfedge handle \endlink in
the halfedge data structure or to the type \link Triangulation_2::Edge Edge \endlink in 2D triangulations.
There are also iterators, such as the `vertex_iterator`, which is similar
to a vertex iterator in \cgal data structures, and the `out_edge_iterator`,
which is similar to the edge circulator; it enables to iterate through the edges
incident to a vertex. The iterators are similar and not equivalent,
because their value type is a `vertex_descriptor`, whereas in
\cgal handles, iterators, and circulators all have the same value
type, namely the vertex or edge types.

Given a graph type `G`, definitions of descriptors and iterators look as follows:

\code {.cpp}
boost::graph_traits<Graph>::vertex_descriptor vd;
boost::graph_traits<Graph>::edge_iterator ei;
...
\endcode

\subsection BGLFreeFunctionsforExploringaGraph Free Functions for Exploring a Graph

Algorithms obtain incidence information in graphs with the help of global
functions such as:
- \ref VertexListGraph::vertices(const VertexListGraph&) "std::pair<vertex_iterator,vertex_iterator> vertices(const Graph& g)" to obtain an iterator range providing access to all the vertices, or
- \link VertexListGraph::num_vertices(const VertexListGraph&) `vertices_size_type num_vertices(const Graph&)`\endlink to obtain the number of vertices of a graph, or
- \link IncidenceGraph `vertex_descriptor source(edge_descriptor, const Graph&)` \endlink to obtain the source vertex of an edge.

Note, that the way we have written the types is a simplification; in reality,
the signature of the first of the above functions is:

\code{.cpp}
typedef boost::graph_traits<Graph>::vertex_iterator vertex_iterator;
std::pair<vertex_iterator,vertex_iterator> vertices(const Graph& g);
\endcode

\subsection BGLPropertyMaps Property Maps

Another feature extensively used in the \bgl is the *property map*,
which is offered by the <a href="https://www.boost.org/doc/libs/latest/libs/property_map/doc/property_map.html">Boost Property Map Library</a>. Property maps
are a general purpose interface for mapping key objects to
corresponding value objects.

The \bgl uses property maps to associate information with vertices and edges.
This mechanism uses a traits class (`boost::property_traits`) and free
functions to read (`get`) and write (`put`) information in vertices,
edges, and also in halfedges and faces for models of the \cgal graph concepts.
For example, the \bgl
Dijksta's shortest path algorithm writes the predecessor of each vertex, as
well as the distance to the source in such a property map.

Some default property maps are associated with the graph types. They
are called *internal property maps* and can be retrieved using an
overload of the function `get()`. For example,
\code{.cpp}
pm = get(boost::vertex_index, g)
\endcode
returns a property map that associates an index
in the range `[0, num_vertices(g))` with each vertex of the graph.
This reduces the number of parameters to pass.
The data itself may be stored in the vertex or the edge, or it may
be stored in an external data structure, or it may be computed on
the fly. This is an implementation detail of a particular property map.

See also Chapter \ref PkgPropertyMap.

\subsection BGLVisitors Visitors

Visitors are objects that provide functions to be called at
specified event points by the algorithm that they visit.
The functions as well as the event points are algorithm-specific.
Examples of such event points in graph algorithms are when a vertex is traversed the first time,
or when all outgoing edges of a vertex have been traversed.<BR>

See also Section <A HREF="https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/visitors/overview.html">Visitor Concepts</A>
in the \bgl manual.

\subsection BGLNamedParameters Named Parameters

The notion of <I>named parameters</I> was introduced in the \bgl,
and allow the user to specify only those parameters which are really needed, by name, making the parameter ordering unimportant.
See also <a href="https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/about/bgl_named_params.html">this page</a>
in the manual of the \bgl for more information.

Say there is a function `f()` that takes 3 parameters called name, age and gender,
and you have variables `n`, `a` and `g` to pass as parameters to that function.
Without named parameters, you would call it like this: `f(n,a,g)`,
whereas with named parameters, you call it like this: `f(name(n).age(a).gender(g))`.
That is, you give each parameter a name by wrapping it into a function whose name
matches that of the parameter. The entire list of named parameters is really
a composition of function calls separated by a dot ("."). Thus, if the function
takes a mix of mandatory and named parameters, you use a comma to separate
the last non-named parameter from the first named parameters, like this:
\code{.cpp}
f(non_named_par0, non_named_par1, name(n).age(a).gender(g))
\endcode
When you use named parameters, the ordering is irrelevant, so `f(name(n).age(a).gender(g))`
is equivalent to `f(age(a).gender(g).name(n))`, and you can just omit any named parameter that has a default value.

The sequence of named parameters should start with `CGAL::parameters::`.

\subsubsection BGLNamedParametersExample Example

Below is a sample call of a function that uses the optional BGL named parameters.

\code
// pmesh : polygon mesh with patches to be refined
// faces : the range of faces defining the patches to refine
// faces_out : output iterator into which descriptors of new faces are put
// vertices_out : output iterator into which descriptors of new vertices are put
// vertex_point_map : the property map with the points associated to the vertices of `pmesh`
// density_control_factor : factor to control density of the output mesh
refine(pmesh,
       faces,
       faces_out,
       vertices_out,
       CGAL::parameters::vertex_point_map(vpmap)
                        .density_control_factor(d));
\endcode

\section BGLHeader Header Files, Namespaces, and Naming Conventions

This package provides the necessary classes and functions that enable using
\cgal data structures as models of the \bgl graph concepts.
To this end, we offer partial specializations of the `boost::graph_traits<Graph>` for various \cgal packages.
For each such package, denoted `PACKAGE`, the partial specializations live in
the namespace `boost` and are located in the header file `CGAL/boost/graph/graph_traits_PACKAGE.h`.
Free functions are in the namespace `CGAL`, and the compiler uses argument-dependent lookup to find them.
%Euler operations, described in Section \ref BGLEulerOperations, are in the namespace `CGAL::Euler`, as the function `remove_face()` is at
the same time a low-level and an %Euler operation.
Concerning the naming conventions, we have to use those of the \bgl,
as to fulfill the requirements of the concepts defined in the \bgl.

Note that these partial specializations are often providing more than
is required, making these classes not only models of the graph concepts
of the \bgl, but also models of the CGAL graph concepts, that will be
described in detail in Section \ref BGLExtensions. Correspondence tables
between the types of a \cgal data structure and their \bgl equivalents
can be found in the \ref PkgBGLTraits documentation page.

We present in the following sections some examples of utilization of some
\cgal data structures as \bgl graphs.

\section BGLSurface_mesh The Class Surface_mesh as Model of the Boost Graph Concept

The class `Surface_mesh` is a model of most of the graph concepts of the \bgl
as well as the concepts provided by \cgal. A complete list can
be found in the documentation of \link BGLSMGT boost::graph_traits \endlink.
The examples show how to use some of the \bgl algorithms with `Surface_mesh` and show how to use
the concepts provided by \cgal to implement a simple algorithm.

\subsection BGLExampleMinimumSpanningTreeofaSurfaceMesh Example: Minimum Spanning Tree of a Surface_mesh

The following example program computes the minimum spanning tree on a surface mesh.
More examples can be found in Chapters
\ref PkgSurfaceMeshSimplification, \ref PkgSurfaceMeshSegmentation, and \ref PkgSurfaceMeshDeformation.

The surface mesh class uses integer indices to address vertices and edges,
and it comes with a built-in property mechanism that maps nicely on the \bgl.

\cgalExample{BGL_surface_mesh/prim.cpp}

\section BGLPolyhedral The Class Polyhedron_3 as Model of the Boost Graph Concept

The class `Polyhedron_3` is a model of most of the graph concepts of the \bgl
as well as the concepts provided by \cgal. A complete list can
be found in the documentation of \link BGLPolyGT boost::graph_traits \endlink.
The examples show how to use some of the \bgl algorithms with `Polyhedron_3` and show how to use
the concepts provided by \cgal to implement a simple algorithm.

\subsection BGLExampleMinimumSpanningTreeofaPolyhedral Example: Minimum Spanning Tree of a Polyhedral Surface

The following example program computes the minimum spanning tree on a polyhedral surface.
More examples can be found in the Chapter
\ref PkgSurfaceMeshSimplification.

\cgalExample{BGL_polyhedron_3/kruskal.cpp}

\subsection BGLExampleUsingVerticesandEdgeswithanID Example: Using Vertices, and Edges with an ID

The following example program shows a call to the \bgl
Kruskal's minimum spanning tree algorithm accessing the `id()`
field stored in a polyhedron vertex.

The main function illustrates the access to the `id()` field.

\cgalExample{BGL_polyhedron_3/kruskal_with_stored_id.cpp}

\section BGLTriangulations Triangulations as Models of the Boost Graph Concept

Triangulations have vertices and faces, allowing for a direct translation
as a graph. A halfedge is defined as a pair of a face handle and the
index of the edge. A complete list can be found in the documentation
of \link BGLT2GT boost::graph_traits \endlink.

A classical example for an algorithm that is a combination of
computational geometry and graph theory is the <I>Euclidean Minimum
Spanning Tree</I> for a point set in the plane. It can be computed by
running the minimum spanning tree algorithm on a Delaunay
triangulation of the point set.

\subsection BGLExampleEuclideanMinimumSpanningTree Example: Euclidean Minimum Spanning Tree

In the following example we create a Delaunay triangulation and run Kruskal's minimum
spanning tree algorithm on it. Because the vertex handles of the triangulation are not indices
in an array, we have to provide a property map that maps vertex handles to
integers in the range `[0, t.number_of_vertices())`.

\cgalExample{BGL_triangulation_2/emst.cpp}

\subsection BGLExampleStoringtheVertexIDintheVertex Example: Storing the Vertex ID in the Vertex

The algorithms of the \bgl extensively use of the indices of
vertices. In the previous example we stored the indices in a `std::map`
and turned that map in a property map. This property map was then
passed as argument to the shortest path function.

If the user does not pass explicitly a property map, the graph algorithms
use the property map returned by the call `get(boost::vertex_index,ft)`.
This property map assumes that the vertex has a
member function `id()` that returns a reference to an int.
Therefore \cgal offers a class `Triangulation_vertex_base_with_id_2`.
It is in the user's responsibility to set the indices properly.

The example further illustrates that the graph traits also works
for the Delaunay triangulation.

\cgalExample{BGL_triangulation_2/dijkstra_with_internal_properties.cpp}

\section BGLArrangements Arrangements as Models of the Boost Graph Concept

\cgal offers a partial specialization of the boost graph traits for its arrangement
class as well as for its dual graph.

\subsection arr_sssecbgl_primal Example for the Arrangement as Graph

Arrangement instances are adapted to <I>boost</I> graphs by specializing the
`boost::graph_traits` template for `Arrangement_2` instances. The
graph-traits states the graph concepts that the arrangement class models
(see below) and defines the types required by these concepts.

In this specialization the `Arrangement_2` vertices correspond to the
graph vertices, where two vertices are adjacent if there is at least one
halfedge connecting them. More precisely, `Arrangement_2::Vertex_handle`
is the graph-vertex type, while `Arrangement_2::Halfedge_handle` is the
graph-edge type. As halfedges are directed, we consider the graph to be
directed as well. Moreover, as several interior-disjoint \f$ x\f$-monotone curves
(say circular arcs) may share two common endpoints, inducing an arrangement
with two vertices that are connected with several edges, we allow parallel
edges in our <I>boost</I> graph.

Given an `Arrangement_2` instance, we can efficiently traverse its
vertices and halfedges. Thus, the arrangement graph is a model of the concepts
`VertexListGraph` and `EdgeListGraph` introduced by the \bgl.
At the same time, we use an iterator adapter of the circulator over the
halfedges incident to a vertex (`Halfedge_around_target_circulator` - see
Section \ref arr_sssectr_vertex "Traversal Methods for an Arrangement Vertex"
of the chapter on arrangements), so it is possible to go over the ingoing
and outgoing edges of a vertex in linear time. Thus, our arrangement graph
is a model of the concept `BidirectionalGraph` (this concept refines
`IncidenceGraph`, which requires only the traversal of outgoing edges).

It is important to notice that the vertex descriptors we use are
`Vertex_handle` objects and <I>not</I> vertex indices. However, in order
to gain more efficiency in most \bgl algorithm, it is better to have them
indexed \f$ 0, 1, \ldots, (n-1)\f$, where \f$ n\f$ is the number of vertices. We
therefore introduce the `Arr_vertex_index_map<Arrangement>` class-template,
which maintains a mapping of vertex handles to indices, as required by the
\bgl. An instance of this class must be attached to a valid arrangement
vertex when it is created. It uses the notification mechanism (see
Section \ref arr_ssecnotif) to automatically maintain the mapping of vertices
to indices, even when new vertices are inserted into the arrangement or
existing vertices are removed.

A complete description of the types correspondences
can be found in the documentation of \link BGLArgtGT boost::graph_traits \endlink.

In most algorithm provided by the \bgl, the output is given by
<I>property maps</I>, such that each map entry corresponds to a vertex.
For example, when we compute the shortest paths from a given source vertex
\f$ s\f$ to all other vertices we can obtain a map of distances and a map of
predecessors - namely for each \f$ v\f$ vertex we have its distance from \f$ s\f$
and a descriptor of the vertex that precedes \f$ v\f$ in the shortest path from \f$ s\f$.
If the vertex descriptors are simply indices, one can use vectors to
efficiently represent the property maps. As this is not the case with the
arrangement graph, we offer the `Arr_vertex_property_map<Arrangement,Type>`
template allows for an efficient mapping of `Vertex_handle` objects to
properties of type `Type`. Note however that unlike the
`Arr_vertex_index_map` class, the vertex property-map class is not
kept synchronized with the number of vertices in the arrangement, so it
should not be reused in calls to the \bgl functions in case the arrangement
is modified in between these calls.

\cgalFigureBegin{figex_bgl,ex_bgl.png}
An arrangement of 7 line segments, as constructed by `bgl_primal_adapter.cpp`
and `bgl_dual_adapter.cpp`. The breadth-first visit times for the arrangement
faces, starting from the unbounded face \f$ f_0\f$, are shown in brackets.
\cgalFigureEnd

In the following example we construct an arrangement of 7 line segments,
as shown in \cgalFigureRef{figex_bgl},
then use the \bgl Dijkstra's shortest-paths algorithm to compute
the graph distance of all vertices from the leftmost vertex in the
arrangement \f$ v_0\f$. Note the usage of the `Arr_vertex_index_map` and
the `Arr_vertex_property_map` classes. The latter one, instantiated with
the type `double` is used to map vertices to their distances from \f$ v_0\f$.

\cgalExample{BGL_arrangement_2/primal.cpp}

\subsection arr_sssecbgl_dual Example for the Dual of an Arrangement as Graph

It is possible to give a dual graph representation for an arrangement instance,
such that each arrangement face corresponds to a graph vertex and two vertices
are adjacent iff the corresponding faces share a common edge on their
boundaries. This is done by specializing the
`boost::graph_traits` template for `Dual<Arrangement_2>` instances,
where `Dual<Arrangement_2>` is a template specialization that gives a
dual interpretation to an arrangement instance.

In dual representation, `Arrangement_2::Face_handle`
is the graph-vertex type, while `Arrangement_2::Halfedge_handle` is the
graph-edge type. We treat the graph edges as directed, such that a halfedge
`e` is directed from \f$ f_1\f$, which is its incident face, to \f$ f_2\f$, which
is the incident face of its twin halfedge. As two arrangement faces may
share more than a single edge on their boundary, we allow parallel
edges in our <I>boost</I> graph. As is the case in the primal graph, the dual
arrangement graph is also a model of the concepts `VertexListGraph`,
`EdgeListGraph` and `BidirectionalGraph` (thus also of
`IncidenceGraph`).

Since we use `Face_handle` objects as the vertex descriptors, we define
the `Arr_face_index_map<Arrangement>` class-template, which maintains an
efficient mapping of face handles to indices. We also provide the template
`Arr_face_property_map<Arrangement,Type>` for associating arbitrary
data with the arrangement faces.

In the following example we construct the same arrangement as in
example `ex_bgl_primal_adapter.cpp` (see
\cgalFigureRef{aos_fig-bgl_primal_adapter}), and perform breadth-first
search on the graph faces, starting from the unbounded face. We extend
the \dcel faces with an unsigned integer, marking the discover
time of the face and use a breadth-first-search visitor to obtain
these times and update the faces accordingly:

\cgalExample{BGL_arrangement_2/arrangement_dual.cpp}

\section BGLExtensions Extensions of the BGL

The previous sections introduced partial specializations
and free functions so that several \cgal data structures are adapted as models of some
of the \bgl graph concepts.
In this section, we introduce new concepts, iterators, and property maps inspired
by the functionalities of the \bgl.

\subsection BGLExtensionsGraphConcepts Graph concepts

In order to match \ref PkgHalfedgeDS more closely and to enable writing generic algorithms
which operate on data structures that have faces and halfedges, we define
a set of new concepts to extend the <a href="https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/concepts/graph_concepts.html">graph concepts of the BGL</a>:

- `HalfedgeGraph` refines <a href="https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/concepts/Graph.html">`Graph`</a>
with operations to accommodate halfedge data structures:
given a halfedge, say `h`, the concept `HalfedgeGraph` requires the provision
of the halfedge opposite to `h`, the halfedge that succeeds `h`,
and the halfedge that precedes `h`.
- `HalfedgeListGraph` adds the requirement for efficient traversal of
the halfedges of the graph.
- `MutableHalfedgeGraph` adds the requirement for operations to
change next/previous relations and to adjust the target of a halfedge.
- `FaceGraph` adds the requirements to explicitly handle faces in
a graph, to provide quick access to the incident halfedges of a face, and to
enable access from every halfedge to an adjacent face.
- `FaceListGraph` adds the requirement for efficient traversal of
the faces of a graph.
- `MutableFaceGraph` adds requirements to change adjacency of
faces and halfedges, and to remove and add faces.

A summary of the expressions and types associated with each of these concepts
as well as a refinement relation graph can be found in the
\ref PkgBGLConcepts documentation page.

\subsection BGLIteratorsAndCirculators Iterators and Circulators

By combining basic operations on graphs, we create various useful
\link devman_iterators_and_circulators iterators and circulators\endlink
to traverse specific types of elements. For example:

- Starting at a halfedge `h` of a halfedge graph `g`, applying several times `next(h,g)` brings us back
to the halfedge where we started. All halfedges traversed on the way are incident to the same face.
- Using the composition of the functions `next(h,g)` and `opposite(h,g)` results
in another cycle, namely the cycle of halfedges which are incident to
the same vertex.

A complete list of these traversal tools can be found in \link PkgBGLIterators the reference manual\endlink.

For convenience, two iterator and circulator types enable the traversal of all halfedges
incident to a given face, and all halfedges having a given vertex as target.
These types are not part of the concept `HalfedgeGraph`, but they
are class templates that work for any model of this concept.

\subsubsection BGLExampleIncidentVertices Example: Finding Incident Vertices in a HalfedgeGraph

The following example shows several functions to navigate in a `HalfedgeGraph`.
We have two implementations of the operation that finds the vertices adjacent to a vertex `v`.

Let us have a look at the first version. Given a vertex descriptor `vd`,
we first call `halfedge(vd,g)` to obtain the halfedge with `vd` as target.
Applying `source()` then gives us an adjacent vertex. We then get to the next halfedge
with `vd` as target, by first going to the next halfedge around the face, and then
going to the opposite halfedge.

The second version does the `%next()` and `%opposite()` jumping with an iterator.
Note that when calling `source()` we have to dereference `hi`, as the function
expects a halfedge descriptor and not a halfedge iterator.
Also observe that `halfedges_around_target()` expects a halfedge, and not a vertex.
This provides the user with the ability to start the traversal at a specific
halfedge incident to the input vertex (and not the arbitrary incident halfedge
stored in the vertex record.)

\cgalExample{BGL_polyhedron_3/incident_vertices.cpp}

\subsubsection BGLExampleNormalHalfedgeGraph Example: Calculating Facet Normals using HalfedgeGraph

The following example program shows a simple algorithm for calculating
facet normals for a polyhedron using the \bgl API. A
<a href="https://www.boost.org/doc/libs/latest/libs/property_map/doc/vector_property_map.html">boost::vector_property_map</a>
is used to to store the calculated normals instead of changing the Polyhedron items class.

\cgalExample{BGL_polyhedron_3/normals.cpp}

\subsection BGLProperties Properties and Dynamic Properties

As the concepts `HalfedgeGraph` and `FaceGraph` add the notion of halfedges and faces,
as well as a geometric embedding of the vertices, we have to add
property tags such as `face_index_t` and `vertex_point_t`.

We further add <em>dynamic properties</em> that enable the user
to add properties to vertices, halfedges, edges, and faces on the fly.
The lifetime of a dynamic property is bound to the lifetime
of the property map: reference counting is used to delete the property
when no map refers to it.

Dynamic property tags, such as `dynamic_vertex_property_t`, are a generalization of
`boost::vertex_index_t`, as they have a template parameter for the
value type of the dynamic property map, and a default value.
`boost::property_map<G,T>::%type` is used to obtain the
type of the dynamic property map for a graph of type `G`, for a
dynamic property tag `T`.  This type must be assignable, and if no
default is provided it must be default constructible.
As for ordinary properties, the function `%get()` is overloaded and
serves for retrieving a property map for a given graph and dynamic
property tag, as well as for retrieving a value for a given key and
property map. The default value is provided as third parameter.

The following example shows how to attach a `string` property to vertices and
a `double` value to the halfedges of a graph.

\cgalExample{Property_map/dynamic_properties.cpp}

\subsection BGLGraphIO Graph I/O

Using a common graph concept enables having common input/output functions for all the models
of this concept. The following file formats are supported for models of `FaceGraph`:
- \ref IOStreamOFF (`.off`)
- \ref IOStreamOBJ (`.obj`)
- \ref IOStreamSTL (`.stl`)
- \ref IOStreamPLY (`.ply`)
- \ref IOStreamGocad (`.ts`)
- \ref IOStreamVTK (`.vtp`)

See the page \ref PkgBGLIOFct for an exhaustive description of the I/O functions of this package.

\section BGLEulerOperations Euler Operations

There are two categories of mutating operations. The first category comprises
low level operations that change incidences such as the target vertex of a
halfedge.
A halfedge graph might turn invalid by the application of inconsistent
low lever operations. The second category of operations
are called <em>%Euler Operations</em>. These are high level operations such
as adding a center vertex to a face, which means also adding halfedges
and faces, and updating incidence information. The %Euler operations
enable manipulating models of `MutableFaceGraph`.

The complete list of Euler operations provided by this package can be found in
\link PkgBGLEulerOperations the reference manual\endlink.

\section BGLGraphAdaptors Graph Adaptors

Graph adaptors are classes that build an interface over an existing graph to provide
new functionalities. By operating almost entirely on the input graph, adaptors
can avoid potentially expensive operations, both in term of time and memory.

\subsection BGLDual The Dual Graph

The <em>dual graph</em> of a `FaceGraph` `G` is a graph that has a vertex for each
face of `G`. The dual graph has an edge whenever two faces of `G` are
separated from each other by an edge. Thus, each edge `e` of `G` has a
corresponding dual edge, the edge that connects the two faces on
either side of `e`.
Computing the dual graph of a graph has many uses, for example when one wishes
to compute the connected components of a mesh.

The class template `Dual` is an adaptor that creates the dual view of
a `FaceGraph`. Faces of the original graph correspond to vertices in
the `Dual` and vice versa.

Note that border edges in a `Dual` have the `null_face` of the
original graph as either source or target. This is unusual and might
break other algorithms since edges are always assumed to have non-null
vertices as a source and target. It is nevertheless possible to filter border edges
using <a href="https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/adaptors/filtered_graph.html">boost::filtered_graph</a>,
as shown in the following example.

\cgalExample{BGL_surface_mesh/surface_mesh_dual.cpp}

\subsection BGLSeamMesh The Seam Mesh

The class `Seam_mesh` allows to mark edges of a mesh as <em>seam edges</em>
so that they <em>virtually</em> become border edges when exploring a seam mesh with the \bgl API.
The input mesh is referred to as <em>underlying</em> mesh of the seam mesh.
We denote `tm` and `sm` the underlying mesh and the seam mesh respectively.

\cgalFigureRef{fig_Seam_mesh_1} shows an example of mesh on which two
edges, defined by the halfedge pairs `h2-h3` and `h6-h7`, are marked as seams.
The introduction of virtual borders modifies the elementary \bgl graph traversal
operations: when we circulate around the target of `h7` in the underlying mesh,
we traverse `h7`, `h1`, `h3`, `h5`, before arriving at `h7` again.
However, when we circulate in the seam mesh, we traverse `h7`, `h1`, `h3*`,
before arriving at `h7` again.
Similarly, if we start at `h3`, we traverse `h3`, `h5`, `h7*`, and `h3` again.

\cgalFigureBegin{fig_Seam_mesh_1, seam_mesh_1.svg}
A seam mesh with two seam edges `(h2, h3)` and `(h6, h7)`.
\cgalFigureEnd

A vertex of the underlying mesh may correspond to multiple vertices in the seam mesh.
For example in \cgalFigureRef{fig_Seam_mesh_1}, the target of `h7` corresponds to two
vertices in the seam mesh, on either side of the virtual border created by the seam edges.
For this reason, a vertex `v` of the seam mesh is internally represented as a halfedge `h`
of the seam mesh. To obtain a canonical definition, the halfedge `h` is defined as the halfedge
that has `v` as target, that lies on the seam, and that is not a border
halfedge. The function `target(hd, sm)` will return this halfedge.
For vertices `v` in the underlying mesh that are not on a seam edge, we choose
`halfedge(v, tm)` as its canonical halfedge.

\subsubsection BGLSeamMeshTraversal Seam Mesh Traversal

Using the function `next(halfedge_descriptor, FaceGraph)`, we can walk around a face but also around
a border of a mesh. For the seam mesh `sm` from \cgalFigureRef{fig_Seam_mesh_1},
we have `opposite(h2, sm) == h3*`, and it holds that `face(h3*, sm) == null_face()`.
We can walk along this virtual border: starting at `h3*` and repeatedly calling `next(..,sm)`,
we will traverse `h6*`, `h7*`, `h2*`, before reaching `h3*` again.

All other traversal functions, iterators, and circulators (see \ref PkgBGLIterators) can
be used on a seam mesh, but their behavior is similarly modified by the (virtual and real)
border edges of the seam mesh.

\subsubsection BGLSeamMeshNature Seams

A collection of seam edges, or simply a <em>seam</em>, is not necessarily a simple polyline
as we can see in the next figure:
<UL>
<LI>In <em>(a)</em>, the seam forms a tree. Consequently, we pass at a vertex as often as
there are incident seam edges.
<LI>In <em>(b)</em>, the seam has a vertex `v` on the border of the underlying mesh.
While walking along the border of the seam mesh, we leave the border of the underlying mesh
when we reach `v` and walk on a virtual border until we reach `v` again, from the other side
of the seam.
<LI>In <em>(c)</em>, the seam forms a closed polyline. While the first two define a single border,
a cycle defines two borders and splits the set of faces in two connected components.
Something similar happens when the seam touches the same border more than once.
A seam can also connect different borders, potentially changing the genus of the mesh.
Finally, a seam may have more than one connected component.
</UL>

\cgalFigureBegin{fig_Seam_mesh_2, seam_mesh_2.svg}
Walking around a seam <em>(a)</em> with no seam vertex on the real border,
<em>(b)</em> with a seam vertex on the real border, <em>(c)</em> with a closed polyline.
Vertices of the seam mesh that are linked by a green dashed segment correspond
to the same vertex in the underlying mesh.
\cgalFigureEnd

Seam meshes are for example used in Chapter \ref PkgSurfaceMeshParameterization
to parameterize a topological sphere by first virtually cutting it into a topological
disk.

\subsection BGLInheriting Inheriting from a Model of a Face Graph Concept
In order for a type `FG` to be a model of one of the face graph concepts, a specialization of
`boost::graph_traits<FG>` must exist. When you derive a class from `FG` this graph traits class specialization does not match.
For such cases, a header file consuming some user defined macros is provided to make the derived class a valid model
of the same concept. See `CGAL/boost/graph/graph_traits_inheritance_macros.h` for more details.

\section BGLPartitioning Graph Partitioning

For algorithms that operate locally, partitioning is often an easy way to parallelize
the algorithm at little cost.
The functions `CGAL::METIS::partition_graph()` and `CGAL::METIS::partition_dual_graph()`
provide wrappers to the graph partitioning library METIS \cgalCite{karypis1998fast},
allowing to split triangular meshes that are models of the concept `FaceListGraph`
into a given number of subdomains.

The following example shows how to read, partition, and write a mesh using
`partition_dual_graph()`. The class template `CGAL::Face_filtered_graph`
and the free function `copy_face_graph()` are used to create an independent mesh from one
of the subdomains of the partition. Note that the copy is optional as writing
can be done directly using `Face_filtered_graph`.

\cgalExample{BGL_surface_mesh/surface_mesh_partition.cpp}

Using \ref BGLNamedParameters some of the many options of METIS can be customized,
as shown in \ref BGL_polyhedron_3/polyhedron_partition.cpp "this example".

\section BGLGraphcut Graph Cut

An optimal partition from a set of labels can be computed through a
graph cut approach called alpha expansion
\cgalCite{Boykov2001FastApproximate}. \cgal provides
`CGAL::alpha_expansion_graphcut()` which, for a graph \f$(V,E)\f$,
computes the partition `f` that minimizes the following cost function:

\f[
  \mathrm{C}(f) = \sum_{\{v0,v1\} \in E} C_E(v0,v1) + \sum_{v \in V} C_V(f_v)
  \f]

where \f$C_E(v0,v1)\f$ is the edge cost of assigning a different label
to \f$v0\f$ and \f$v1\f$, and \f$C_V(f_v)\f$ is the vertex cost of
assigning the label \f$f\f$ to the vertex \f$v\f$.

Three different implementations are provided and can be selected by
using one of the following tags:

- `CGAL::Alpha_expansion_boost_adjacency_list_tag` (default)
- `CGAL::Alpha_expansion_boost_compressed_sparse_raw_tag`
- `CGAL::Alpha_expansion_MaxFlow_tag`, released under GPL
  license and provided by the \ref PkgSurfaceMeshSegmentation
  package

All these implementations produce the exact same result but behave
differently in terms of timing and memory (see
\cgalFigureRef{alpha_exp}). The _MaxFlow_ implementation is the
fastest, but it grows rapidly in memory when increasing the complexity
of the input graph and labeling; the _compressed sparse raw_ (CSR) is very
efficient from a memory point of view but becomes very slow as the
complexity of the input graph and labeling increases; the _adjacency
list_ version provides a good compromise and is therefore the default
implementation.

\cgalFigureBegin{alpha_exp, alpha_expansion.png}
Comparison of time and memory consumed by the different alpha
expansion implementations.
\cgalFigureEnd

\subsection BGLGraphcutExample Example

The following example shows how to apply the alpha expansion algorithm
to a `boost::adjacency_list` describing a 2D array with 3 labels "X",
" " and "O":

\cgalExample{BGL_graphcut/alpha_expansion_example.cpp}

The output of this program shows how the initial 2D array is
regularized spatially:

```
Input:
XOX
XX X O
OX  OO
X  OOX
  OXOO

Alpha expansion...

Output:
XXX
XX   O
XX  OO
X  OOO
  OOOO
```

\subsection BGLGraphcutRegularizeSelection Application to Regularization of the Borders of a Face Selection

Manually selecting faces on a triangle mesh may create irregular
borders (sawtooth) because of the shape of the triangles. Such borders
can be regularized using the alpha expansion algorithm.

\cgal provides a function `CGAL::regularize_face_selection_borders()`
to apply this algorithm to the borders of a face selection on a
`FaceGraph`. \cgalFigureRef{regularization_fig} shows how this
function affects a selection depending on the parameters.

\cgalFigureBegin{regularization_fig, regularize_selection.png}
Regularization of the borders of a face selection using alpha
expansion. Different outputs are shown for different weight
parameters, with and without preventing unselection.
\cgalFigureEnd

The following example shows how to apply this alpha expansion
regularization to the borders of a face selection of a
`CGAL::Surface_mesh` object:

\cgalExample{BGL_graphcut/face_selection_borders_regularization_example.cpp}


*/
} /* namespace CGAL */

---

### BGL Doc BGL NamedParameters (`BGL/doc/BGL/NamedParameters.txt`)

/*!
\defgroup bgl_namedparameters Named Parameters
\ingroup PkgBGLRef

The algorithms of the Boost Graph Library (\bgl) often have many parameters with default
values that are appropriate for most cases. In general, when no
special treatment is applied, the values of such parameters are passed
as a sequence. Deviating from the default for a certain parameter
requires the user to explicitly pass values for all preceding
parameters. The solution to this problem
is to first write a tag and then the parameter, which for
Dijkstra's shortest path algorithm might look as follows:

\code {.cpp}
std::vector<vertex_descriptor> p(num_vertices(g));
std::vector<int> d(num_vertices(g));
vertex_descriptor s = vertex(A, g);
dijkstra_shortest_paths(g, s, predecessor_map(&p[0]).distance_map(&d[0]));
\endcode

In the \bgl manual, this is called
<a href="https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/about/bgl_named_params.html">named parameters</a>.
The named parameters in the snippet use the tags `predecessor_map` and `distance_map`
and they are concatenated using the dot operator.<BR>

A similar mechanism was introduced in \cgal, with the small difference that the named parameters
tag live in the `CGAL::parameters::` namespace and `CGAL::parameters::default_values()` can be used to indicate
that default values of optional named parameters must be used.
As in the \bgl, named parameters in \cgal are also concatenated using
the dot operator, and a typical usage is thus:

\code {.cpp}
Graph g1, g2;
Vertex_point_map_2 vpm_2; // a hypothetical custom property map assigning a Point to the vertices of g2

// without any named parameter (default values are used)
CGAL::copy_face_graph(g1, g2);

// specifying named parameters for the second graph
CGAL::copy_face_graph(g1, g2,
                      CGAL::parameters::vertex_point_map(vpm)  //parameter for g1
                      .vertex_to_vertex_map(v2v),              //other parameter for g1
                      CGAL::parameters::default_values());        //parameter for g2
\endcode
*/


˛

---

### BGL Doc BGL PackageDescription (`BGL/doc/BGL/PackageDescription.txt`)

/// \defgroup PkgBGLRef Reference Manual

/*! \defgroup PkgBGLConcepts Concepts
 \ingroup PkgBGLRef

 We extend the Boost Graph Library (\bgl for short) with a set of new concepts.
 In order to make this documentation self-contained we here also document
 concepts that are defined in the original version of the \bgl.
 The documentation of the concepts lists at the same time the functions
 related to it. Models of the concept and their related functions
 must be in the same namespace (they will be found by Koenig lookup).

\dot
digraph example {
  node [shape=record, fontname=Helvetica, fontsize=10];
  rankdir=BT

  "boost Graph" [ URL="https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/concepts/Graph.html" ];
  HalfedgeGraph [ URL="\ref HalfedgeGraph"];
  HalfedgeListGraph [ URL="\ref HalfedgeListGraph"];
  MutableHalfedgeGraph [ URL="\ref MutableHalfedgeGraph"];
  FaceGraph [ URL="\ref FaceGraph"];
  FaceListGraph [ URL="\ref FaceListGraph"];
  MutableFaceGraph [ URL="\ref MutableFaceGraph"];

  MutableHalfedgeGraph -> HalfedgeGraph -> "boost Graph" [ arrowhead="open", label="refines" ];
  FaceListGraph -> FaceGraph -> HalfedgeGraph [ arrowhead="open", label="refines" ];
  MutableFaceGraph -> MutableHalfedgeGraph [ arrowhead="open", label="refines" ];
  MutableFaceGraph -> FaceGraph [ arrowhead="open", label="refines" ];
  HalfedgeListGraph -> HalfedgeGraph [ arrowhead="open", label="refines" ];
}
\enddot

\cgalHeading{Notations}

 <dl>
 <dt>`G`</dt>         <dd>A type that is a model of a graph concept.</dd>
 <dt>`g`</dt>         <dd>An object of type `G`.</dd>
 <dt>`u`, `v`</dt>         <dd>Objects of type `boost::graph_traits<G>::%vertex_descriptor`.</dd>
 <dt>`h`</dt>         <dd>An object of type `boost::graph_traits<G>::%halfedge_descriptor`.</dd>
 <dt>`e`</dt>         <dd>An object of type `boost::graph_traits<G>::%edge_descriptor`.</dd>
 <dt>`f`</dt>         <dd>An object of type `boost::graph_traits<G>::%face_descriptor`.</dd>
 </dl>

\cgalHeading{%VertexListGraph}

The concept `VertexListGraph` refines the concept
<a href="https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/concepts/Graph.html">`Graph`</a>
and adds the requirement for traversal of all vertices in a graph.

<center>
<table>
 <tr>
  <th class="associated-type">Associated Type</th>
  <th class="description">Description</th>
 </tr>
 <tr>
  <td>`boost::graph_traits<G>::%vertex_iterator`</td>
  <td>%Iterator over all vertices</td>
 </tr>
 <tr>
  <td>`boost::graph_traits<G>::%vertices_size_type`</td>
  <td>Unsigned integer type for number of vertices</td>
 </tr>
</table>

<table>
 <tr>
  <th class="valid-expression">Valid Expression</th>
  <th class="return-type">Return Type</th>
  <th class="description">Description</th>
 </tr>
 <tr>
  <td>`vertices(g)`</td>
  <td>`std::pair<vertex_iterator, vertex_iterator>`</td>
  <td>An iterator range over all vertices</td>
 </tr>
 <tr>
  <td>`num_vertices(g)`</td>
  <td>`vertices_size_type`</td>
  <td>An upper bound of the number of vertices of the graph</td>
 </tr>
</table>
</center>

\cgalHeading{%EdgeListGraph}

The concept `EdgeListGraph` refines the concept
<a href="https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/concepts/Graph.html">`Graph`</a>
and adds the requirement for traversal of all edges in a graph.

<center>
<table>
 <tr>
  <th class="associated-type">Associated Type</th>
  <th class="description">Description</th>
 </tr>
 <tr>
  <td>`boost::graph_traits<G>::%edge_iterator`</td>
  <td>%Iterator over all edges</td>
 </tr>
 <tr>
  <td>`boost::graph_traits<G>::%edges_size_type`</td>
  <td>Unsigned integer type for number of edges</td>
 </tr>
</table>

<table>
 <tr>
  <th class="valid-expression">Valid Expression</th>
  <th class="return-type">Return Type</th>
  <th class="description">Description</th>
 </tr>
 <tr>
  <td>`edges(g)`</td>
  <td>`std::pair<edge_iterator, edge_iterator>`</td>
  <td>An iterator range over all edges</td>
 </tr>
 <tr>
  <td>`num_edges(g)`</td>
  <td>`edges_size_type`</td>
  <td>An upper bound of the number of edges of the graph</td>
 </tr>
 <tr>
  <td>`source(e, g)`</td>
  <td>`vertex_descriptor`</td>
  <td>The source vertex of `e`</td>
 </tr>
 <tr>
  <td>`target(e, g)`</td>
  <td>`vertex_descriptor`</td>
  <td>The target vertex of `e`</td>
 </tr>
</table>
</center>

\cgalHeading{%HalfedgeGraph}

The concept `HalfedgeGraph` refines the concept
<a href="https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/concepts/Graph.html">`Graph`</a>
and adds the notion of halfedges, where each edge corresponds to two opposite halfedges.

<center>
<table>
 <tr>
  <th class="associated-type">Associated Type</th>
  <th class="description">Description</th>
 </tr>
 <tr>
  <td>`boost::graph_traits<G>::%halfedge_descriptor`</td>
  <td>A `halfedge_descriptor` corresponds to a halfedge in a graph. Must be `DefaultConstructible`, `Assignable`, `EqualityComparable` and `LessThanComparable`</td>
 </tr>
</table>

<table>
 <tr>
  <th class="valid-expression">Valid Expression</th>
  <th class="return-type">Return Type</th>
  <th class="description">Description</th>
 </tr>
 <tr>
  <td>`edge(h, g)`</td>
  <td>`edge_descriptor`</td>
  <td>The edge corresponding to the halfedges `h` and `opposite(h)`</td>
 </tr>
 <tr>
  <td>`halfedge(e, g)`</td>
  <td>`halfedge_descriptor`</td>
  <td>One of the halfedges corresponding to the edge `e`</td>
 </tr>
 <tr>
  <td>`halfedge(v, g)`</td>
  <td>`halfedge_descriptor`</td>
  <td>A halfedge with target the vertex `v`</td>
 </tr>
 <tr>
  <td>`halfedge(u, v, g)`</td>
  <td>`std::pair<halfedge_descriptor, bool>`</td>
  <td>The halfedge with source `u` and target `v`. The Boolean is `true`, iff this halfedge exists</td>
 </tr>
 <tr>
  <td>`opposite(h, g)`</td>
  <td>`halfedge_descriptor`</td>
  <td>The halfedge with source and target swapped</td>
 </tr>
 <tr>
  <td>`source(h, g)`</td>
  <td>`vertex_descriptor`</td>
  <td>The source vertex of `h`</td>
 </tr>
 <tr>
  <td>`target(h, g)`</td>
  <td>`vertex_descriptor`</td>
  <td>The target vertex of `h`</td>
 </tr>
 <tr>
  <td>`next(h, g)`</td>
  <td>`halfedge_descriptor`</td>
  <td>The next halfedge around its face</td>
 </tr>
 <tr>
  <td>`prev(h, g)`</td>
  <td>`halfedge_descriptor`</td>
  <td>The previous halfedge around its face</td>
 </tr>
 <tr>
  <td>`boost::graph_traits<G>::%null_halfedge()`</td>
  <td>`halfedge_descriptor`</td>
  <td>Returns a special halfedge that is not equal to any other halfedge</td>
 </tr>
</table>
</center>

The `HalfedgeGraph` has the invariant  `halfedge(edge(h,g))==h`.

\cgalHeading{%MutableHalfedgeGraph}

The concept `MutableHalfedgeGraph` refines the concept `HalfedgeGraph`
and adds the requirements for operations to add vertices and edges, and to
update the incidence information between vertices and halfedges.

<center>
<table>
 <tr>
  <th class="valid-expression">Valid Expression</th>
  <th class="return-type">Return Type</th>
  <th class="description">Description</th>
 </tr>
 <tr>
  <td>`add_vertex(g)`</td>
  <td>`vertex_descriptor`</td>
  <td>Adds a new vertex to the graph without initializing the connectivity</td>
 </tr>
 <tr>
  <td>`remove_vertex(v, g)`</td>
  <td>`void`</td>
  <td>Removes the vertex `v` from the graph</td>
 </tr>
 <tr>
  <td>`add_edge(g)`</td>
  <td>`edge_descriptor`</td>
  <td>Adds two opposite halfedges to the graph without initializing their connectivity</td>
 </tr>
 <tr>
  <td>`remove_edge(e, g)`</td>
  <td>`void`</td>
  <td>Removes the two halfedges corresponding to the edge `e` from the graph</td>
 </tr>
 <tr>
  <td>`set_target(h, v, g)`</td>
  <td>`void`</td>
  <td>Sets the target vertex of the halfedge `h` and the source of `opposite(h)` to the vertex `v`</td>
 </tr>
 <tr>
  <td>`set_halfedge(v, h, g)`</td>
  <td>`void`</td>
  <td>Sets the halfedge of the vertex `v` to `h`. The target vertex of `h` must be `v`</td>
 </tr>
 <tr>
  <td>`set_next(h1, h2, g)`</td>
  <td>`void`</td>
  <td>Sets the successor of `h1` around a face to `h2`, and the prededecessor of `h2` to `h1`</td>
 </tr>
</table>
</center>

\cgalHeading{%HalfedgeListGraph}

The concept `HalfedgeListGraph` refines the concept `HalfedgeGraph`
and adds the requirements for traversal of all halfedges in the graph.

<center>
<table>
 <tr>
  <th class="associated-type">Associated Type</th>
  <th class="description">Description</th>
 </tr>
 <tr>
  <td>`boost::graph_traits<G>::%halfedge_iterator`</td>
  <td>A `BidirectionalIterator` over all halfedges in a graph. Must be `DefaultConstructible`, `Assignable`, `EqualityComparable`</td>
 </tr>
 <tr>
  <td>`boost::graph_traits<G>::%halfedges_size_type`</td>
  <td>Unsigned integer type for number of halfedges</td>
 </tr>
</table>

<table>
 <tr>
  <th class="valid-expression">Valid Expression</th>
  <th class="return-type">Return Type</th>
  <th class="description">Description</th>
 </tr>
 <tr>
  <td>`halfedges(g)`</td>
  <td>`std::pair<halfedge_iterator, halfedge_iterator>`</td>
  <td>An iterator range over all halfedges</td>
 </tr>
 <tr>
  <td>`num_halfedges(g)`</td>
  <td>`halfedges_size_type`</td>
  <td>An upper bound of the number of halfedges of the graph</td>
 </tr>
</table>
</center>

\cgalHeading{%FaceGraph}

The concept `FaceGraph` refines the concept `HalfedgeGraph`.
It adds the requirements for a graph to explicitly
maintain faces described by halfedges, to provide access from a face to
an incident halfedge, and to provide access from a halfedge to its incident
face.

<center>
<table>
 <tr>
  <th class="associated-type">Associated Type</th>
  <th class="description">Description</th>
 </tr>
 <tr>
  <td>`boost::graph_traits<G>::%face_descriptor`</td>
  <td>A `face_descriptor` corresponds to a unique face in a graph. Must be `DefaultConstructible`, `Assignable`, `EqualityComparable` and `LessThanComparable`</td>
 </tr>
</table>

<table>
 <tr>
  <th class="valid-expression">Valid Expression</th>
  <th class="return-type">Return Type</th>
  <th class="description">Description</th>
 </tr>
 <tr>
  <td>`face(h, g)`</td>
  <td>`face_descriptor`</td>
  <td>The face incident to halfedge `h`</td>
 </tr>
 <tr>
  <td>`halfedge(f, g)`</td>
  <td>`halfedge_descriptor`</td>
  <td>A halfedge incident to face `f`</td>
 </tr>
 <tr>
  <td>`degree(f, g)`</td>
  <td>`degree_size_type`</td>
  <td>The number of halfedges incident to face `f`</td>
 </tr>
 <tr>
  <td>`boost::graph_traits<G>::%null_face()`</td>
  <td>`face_descriptor`</td>
  <td>A special face that is not equal to any other face</td>
 </tr>
</table>
</center>

\cgalHeading{%MutableFaceGraph}

The concept `MutableFaceGraph` refines the concepts `FaceGraph` and `MutableHalfedgeGraph` and adds
the requirement for operations to add faces and to modify face-halfedge relations.

<center>
<table>
 <tr>
  <th class="valid-expression">Valid Expression</th>
  <th class="return-type">Return Type</th>
  <th class="description">Description</th>
 </tr>
 <tr>
  <td>`add_face(g)`</td>
  <td>`face_descriptor`</td>
  <td>Adds a new face to the graph without initializing the connectivity</td>
 </tr>
 <tr>
  <td>`remove_face(f, g)`</td>
  <td>`void`</td>
  <td>Removes `f` from the graph</td>
 </tr>
 <tr>
  <td>`set_face(h, f, g)`</td>
  <td>`void`</td>
  <td>Sets the corresponding face of `h` to `f`</td>
 </tr>
 <tr>
  <td>`set_halfedge(f, h, g)`</td>
  <td>`void`</td>
  <td>Sets the corresponding halfedge of `f` to `h`</td>
 </tr>
 <tr>
  <td>`reserve(g, nv, ne, nf)`</td>
  <td>`void`</td>
  <td>Called to indicate the expected size of vertices (`nv`), edges (`ed`) and faces (`nf`)</td>
 </tr>
</table>
</center>

\cgalHeading{%FaceListGraph}

The concept `FaceListGraph` refines the concept `FaceGraph` and adds
the requirement for traversal of all faces in a graph.

<center>
<table>
 <tr>
  <th class="associated-type">Associated Type</th>
  <th class="description">Description</th>
 </tr>
 <tr>
  <td>`boost::graph_traits<G>::%face_iterator`</td>
  <td>%Iterator over all faces</td>
 </tr>
 <tr>
  <td>`boost::graph_traits<G>::%faces_size_type`</td>
  <td>Unsigned integer type for number of faces</td>
 </tr>
</table>

<table>
 <tr>
  <th class="valid-expression">Valid Expression</th>
  <th class="return-type">Return Type</th>
  <th class="description">Description</th>
 </tr>
 <tr>
  <td>`faces(g)`</td>
  <td>`std::pair<face_iterator, face_iterator>`</td>
  <td>An iterator range over all faces</td>
 </tr>
 <tr>
  <td>`num_faces(g)`</td>
  <td>`faces_size_type`</td>
  <td>An upper bound of the number of faces of the graph</td>
 </tr>
</table>
</center>

*/

/// The property tags model of the boost concept <a href="https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/concepts/property_types/PropertyTag.html"><code>PropertyTag</code></a>.
/// These tags are used to retrieve default property maps using the traits class <a href="https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/property_maps/overview.html">boost::property_map</a>.
/// \defgroup PkgBGLProperties Properties
/// \ingroup PkgBGLRef

/// \defgroup PkgBGLPropertiesDynamic Dynamic Properties
/// \ingroup PkgBGLRef

/// \defgroup BGLGraphExternalIndices External Indices
/// \ingroup PkgBGLRef

/// \defgroup PkgBGLHelperFct Helper Functions
/// \ingroup PkgBGLRef

/// \defgroup PkgBGLGeneratorFct Generator Functions
/// \ingroup PkgBGLRef

/// \defgroup PkgBGLIterators Iterators and Circulators
/// \ingroup PkgBGLRef

/// \defgroup PkgBGLSelectionFct Selection Functions
/// \ingroup PkgBGLRef

/// \defgroup PkgBGLAdaptors Graph Adaptors
/// \ingroup PkgBGLRef

/// \defgroup PkgBGLEulerOperations Euler Operations
/// \ingroup PkgBGLRef

/// \defgroup PkgBGLPartition Partitioning Operations
/// \ingroup PkgBGLRef

/// \defgroup PkgBGLTraversal Graph Traversal
/// \ingroup PkgBGLRef

/// \defgroup PkgBGLIOFct I/O Functions
/// \ingroup PkgBGLRef

/// \defgroup PkgBGLIoFuncsSTL STL I/O Functions
/// I/O Functions for the \ref IOStreamSTL
/// \ingroup PkgBGLIOFct

/// \defgroup PkgBGLIoFuncsPLY PLY I/O Functions
/// I/O Functions for the \ref IOStreamPLY
/// \ingroup PkgBGLIOFct

/// \defgroup PkgBGLIoFuncsOBJ OBJ I/O Functions
/// I/O Functions for the \ref IOStreamOBJ
/// \ingroup PkgBGLIOFct

/// \defgroup PkgBGLIoFuncsOM OM I/O Functions
/// I/O Functions for the \ref IOStreamOM
/// \ingroup PkgBGLIOFct

/// \defgroup PkgBGLIoFuncsOFF OFF I/O Functions
/// I/O Functions for the \ref IOStreamOFF
/// \ingroup PkgBGLIOFct

/// \defgroup PkgBGLIoFuncsVTP VTP I/O Functions
/// I/O Functions for the \ref IOStreamVTK
/// \ingroup PkgBGLIOFct

/// \defgroup PkgBGLIoFuncsGOCAD GOCAD I/O Functions
/// I/O Functions for the \ref IOStreamGocad
/// \ingroup PkgBGLIOFct

/// \defgroup PkgBGLIoFuncsWRL WRL I/O Functions
/// I/O Functions for the \ref IOStreamWRL
/// \ingroup PkgBGLIOFct

/// \defgroup PkgBGLIoFuncs3MF 3MF I/O Functions
/// I/O Functions for the \ref IOStream3MF
/// \ingroup PkgBGLIOFct



/*!
\addtogroup PkgBGLPropertiesDynamic
The dynamic property tags enable to associate information to simplices of a `FaceGraph` on the fly.
*/

/*!
\addtogroup BGLGraphExternalIndices
A number of BGL and \cgal algorithms require the graph to have (initialized) integer-like indices
for its vertices, edges, or faces. However, not all graphs intrinsically offer a natural way
to attach a unique ID to each element. The following classes and functions paliate this
by attaching and initializing external IDs to the elements of the graph.
*/

/*!
\addtogroup PkgBGLHelperFct
Generic convenience functions for testing if an edge is a border edge, if a mesh is triangular,
for conversion between models of different `FaceGraph` concepts, etc.

All functions are in the header file `<CGAL/boost/graph/helpers.h>`
*/

/*!
\addtogroup PkgBGLGeneratorrFct
Generic convenience functions for generating meshes such as a triangle, a quad, or a grid.

All functions are in the header file `<CGAL/boost/graph/generators.h>`
*/

/*!
\addtogroup PkgBGLIterators

Several iterators and circulators are provided that enable, for example,
to iterate through the  halfedges incident to a given face or vertex.

Starting at a halfedge `h`, applying several times `next(h,g)` brings us back
to the halfedge where we started. All halfedges traversed on the way are
incident to the same face.
Using the composition of the `next(h,g)` and `opposite(h,g)` functions results
in another cycle, namely the cycle of halfedges which are incident to
the same vertex.
For convenience, two iterator and circulator types enable iterating through all the halfedges
incident to a given face, and all the halfedges having a given vertex as target.

All functions are in the header file `<CGAL/boost/graph/iterator.h>`
*/

/*!
\addtogroup PkgBGLSelectionFct
Several functions to enlarge or reduce a k-ring selection of vertices, edges, or faces.
*/

/*!
\addtogroup PkgBGLTraits



*/

/*!
\addtogroup PkgBGLAdaptors

Graph adaptors are classes that build an interface over an existing graph to provide
new functionalities. For example, `CGAL::Dual` allows to traverse and query
the dual graph of a graph without actually building the dual. By operating
almost entirely on the input graph, adaptors can avoid potentially expensive operations,
both in term of time and memory.

*/

/*!
\addtogroup PkgBGLPartition

Methods to split a mesh into subdomains, using the library
<a href="https://github.com/KarypisLab/METIS">METIS</a> or a graphcut
implementation.
*/

/*!
\addtogroup PkgBGLTraversal

Methods to traverse a graph, for example to find the shortest path between two vertices.
*/

/*!
\addtogroup PkgBGLIOFct

Methods to read and write graphs.
*/


/*!
\addtogroup PkgBGLRef
\cgalPkgDescriptionBegin{CGAL and the Boost Graph Library,PkgBGL}
\cgalPkgPicture{emst-detail.png}
\cgalPkgSummaryBegin
\cgalPkgAuthors{Andreas Fabri, Fernando Cacciola, Philipp Moeller, and Ron Wein}
\cgalPkgDesc{This package provides a framework for interfacing \cgal data structures
             with the algorithms of the Boost Graph Library, or \bgl for short.
             It allows to run graph algorithms directly on \cgal data structures which are model
             of the \bgl graph concepts, for example the shortest path algorithm
             on a Delaunay triangulation in order to compute the Euclidean minimum spanning tree.
             Furthermore, it introduces several new graph concepts describing halfedge data structures.}
\cgalPkgManuals{Chapter_CGAL_and_the_Boost_Graph_Library,PkgBGLRef}
\cgalPkgSummaryEnd
\cgalPkgShortInfoBegin
\cgalPkgSince{3.3}
\cgalPkgBib{cgal:cfw-cbgl}
\cgalPkgLicense{\ref licensesLGPL "LGPL"}
\cgalPkgShortInfoEnd
\cgalPkgDescriptionEnd

\cgalClassifedRefPages

\cgalCRPSection{Concepts}
- `VertexListGraph`
- `EdgeListGraph`
- `HalfedgeGraph`
- `HalfedgeListGraph`
- `MutableHalfedgeGraph`
- `FaceGraph`
- `FaceListGraph`
- `MutableFaceGraph`

\cgalCRPSection{Properties}
- `CGAL::vertex_index_t`
- `CGAL::halfedge_index_t`
- `CGAL::edge_index_t`
- `CGAL::face_index_t`
- `CGAL::vertex_point_t`

\cgalCRPSection{%CGAL Classes Adapted for the Graph API}

A number of \cgal structures have been adapted as graphs for the \bgl. All
adapted types are listed here. The pages document which concepts they
model, the properties they support, and any possible caveats that a
user might encounter.

- \link BGLSMGT `boost::graph_traits<CGAL::Surface_mesh<P> >` \endlink
- \link BGLPolyGT  `boost::graph_traits< CGAL::Polyhedron_3<K> >` \endlink
- \link BGLLCCGT `boost::graph_traits<CGAL::Linear_cell_complex_for_combinatorial_map<...> >` \endlink
- \link BGLSeam_meshGT `boost::graph_traits< CGAL::Seam_mesh<G> >` \endlink
- \link BGLT2GT `boost::graph_traits<CGAL::Triangulation_2<GT, TDS> >` \endlink and other 2D triangulations
- \link BGLArgtGT `boost::graph_traits<CGAL::Arrangement_2<T, DC> >` \endlink
- \link BGLOMPAK `boost::graph_traits<OpenMesh::PolyMesh_ArrayKernelT<K> >` \endlink
- \link BGLOMTMAK `boost::graph_traits<OpenMesh::TriMesh_ArrayKernelT<K> >` \endlink

\cgalCRPSection{Helper Classes}
- `CGAL::Triangulation_vertex_base_with_id_2`
- `CGAL::Triangulation_face_base_with_id_2`
- `CGAL::Arr_vertex_index_map`
- `CGAL::Arr_face_index_map`
- `CGAL::HalfedgeDS_vertex_max_base_with_id`
- `CGAL::HalfedgeDS_halfedge_max_base_with_id`
- `CGAL::HalfedgeDS_face_max_base_with_id`
- `CGAL::Polyhedron_items_with_id_3`
- `CGAL::set_halfedgeds_items_id()`
- `CGAL::Linear_cell_complex_bgl_min_items`
- `CGAL::Linear_cell_complex_for_bgl_combinatorial_map_helper`

\cgalCRPSection{Helper Functions}
- `CGAL::is_border()`
- `CGAL::is_border_edge()`
- `CGAL::border_halfedges()`
- `CGAL::extract_boundary_cycles()`
- `CGAL::is_bivalent()`
- `CGAL::is_bivalent_mesh()`
- `CGAL::is_trivalent()`
- `CGAL::is_trivalent_mesh()`
- `CGAL::is_isolated_triangle()`
- `CGAL::is_closed()`
- `CGAL::is_triangle()`
- `CGAL::is_triangle_mesh()`
- `CGAL::is_quad()`
- `CGAL::is_quad_mesh()`
- `CGAL::is_isolated_quad()`
- `CGAL::is_valid_halfedge_graph()`
- `CGAL::is_valid_face_graph()`
- `CGAL::is_valid_polygon_mesh()`

\cgalCRPSection{Generator Functions}
- `CGAL::is_tetrahedron()`
- `CGAL::is_hexahedron()`
- `CGAL::make_triangle()`
- `CGAL::make_tetrahedron()`
- `CGAL::make_quad()`
- `CGAL::make_hexahedron()`
- `CGAL::make_icosahedron()`
- `CGAL::make_regular_prism()`
- `CGAL::make_pyramid()`
- `CGAL::make_grid()`

- `CGAL::clear()`
- `CGAL::remove_all_elements()`
- `CGAL::copy_face_graph()`

- `CGAL::set_triangulation_ids()`

- `CGAL::parameters::default_values()`

\cgalCRPSection{Iterators}
- `CGAL::Halfedge_around_source_iterator`
- `CGAL::Halfedge_around_target_iterator`
- `CGAL::Halfedge_around_face_iterator`
- `CGAL::Vertex_around_target_iterator`
- `CGAL::Vertex_around_face_iterator`
- `CGAL::Face_around_face_iterator`
- `CGAL::Face_around_target_iterator`
- `CGAL::halfedges_around_source()`
- `CGAL::halfedges_around_target()`
- `CGAL::halfedges_around_face()`
- `CGAL::faces_around_face()`
- `CGAL::faces_around_target()`
- `CGAL::vertices_around_face()`
- `CGAL::vertices_around_target()`

\cgalCRPSection{Circulators}
- `CGAL::Halfedge_around_source_circulator`
- `CGAL::Halfedge_around_target_circulator`
- `CGAL::Halfedge_around_face_circulator`
- `CGAL::Vertex_around_target_circulator`
- `CGAL::Vertex_around_face_circulator`
- `CGAL::Face_around_target_circulator`
- `CGAL::Face_around_face_circulator`

\cgalCRPSection{Euler Operations}
- `CGAL::Euler::add_center_vertex()`
- `CGAL::Euler::add_edge()`
- `CGAL::Euler::add_face()`
- `CGAL::Euler::add_face_to_border()`
- `CGAL::Euler::add_vertex_and_face_to_border()`
- `CGAL::Euler::collapse_edge()`
- `CGAL::Euler::does_satisfy_link_condition()`
- `CGAL::Euler::fill_hole()`
- `CGAL::Euler::flip_edge()`
- `CGAL::Euler::join_face()`
- `CGAL::Euler::join_loop()`
- `CGAL::Euler::join_vertex()`
- `CGAL::Euler::make_hole()`
- `CGAL::Euler::remove_center_vertex()`
- `CGAL::Euler::remove_degree_2_vertex()`
- `CGAL::Euler::remove_face()`
- `CGAL::Euler::split_edge()`
- `CGAL::Euler::split_face()`
- `CGAL::Euler::split_loop()`
- `CGAL::Euler::split_vertex()`

\cgalCRPSection{Selection}
- `CGAL::expand_face_selection()`
- `CGAL::reduce_face_selection()`
- `CGAL::expand_edge_selection()`
- `CGAL::reduce_edge_selection()`
- `CGAL::expand_vertex_selection()`
- `CGAL::reduce_vertex_selection()`
- `CGAL::select_incident_faces()`
- `CGAL::expand_face_selection_for_removal()`
- `CGAL::regularize_face_selection_borders()`

\cgalCRPSection{Conversion Functions}
- `CGAL::split_graph_into_polylines()`

\cgalCRPSection{Graph Traversal}
- `CGAL::dijkstra_shortest_path()`

\cgalCRPSection{Graph Adaptors}
- `CGAL::Dual`
- `CGAL::Face_filtered_graph`
- `CGAL::Graph_with_descriptor_with_graph`
- `CGAL::Graph_with_descriptor_with_graph_property_map`
- `CGAL::Seam_mesh`
- `CGAL/boost/graph/graph_traits_inheritance_macros.h`

\cgalCRPSection{Partitioning Methods}
- `CGAL::METIS::partition_graph()`
- `CGAL::METIS::partition_dual_graph()`
- `CGAL::alpha_expansion_graphcut()`

\cgalCRPSection{I/O Functions}
- \link PkgBGLIOFct `CGAL::IO::read_polygon_mesh()` \endlink
- `CGAL::IO::write_polygon_mesh()`
- \link PkgBGLIoFuncsSTL I/O for STL files \endlink
- \link PkgBGLIoFuncsPLY I/O for PLY files \endlink
- \link PkgBGLIoFuncsOBJ I/O for OBJ files \endlink
- \link PkgBGLIoFuncsOFF I/O for OFF files \endlink
- \link PkgBGLIoFuncsGOCAD I/O for GOCAD files \endlink
- \link PkgBGLIoFuncsVTP I/O for VTP files \endlink
- \link PkgBGLIoFuncs3MF I/O for 3MF files \endlink
- \link PkgBGLIoFuncsWRL I/O for WRL files \endlink
*/

/*!
\addtogroup PkgBGLEulerOperations

We call high-level operations that maintain the validity of a halfedge graph <em>%Euler Operations</em>.

*/

---

### BGL Doc BGL Examples (`BGL/doc/BGL/examples.txt`)

/*!
\example BGL_arrangement_2/arr_print.h
\example BGL_arrangement_2/arr_rational_nt.h
\example BGL_arrangement_2/arrangement_dual.cpp
\example BGL_arrangement_2/primal.cpp
\example BGL_graphcut/alpha_expansion_example.cpp
\example BGL_graphcut/face_selection_borders_regularization_example.cpp
\example BGL_polyhedron_3/copy_polyhedron.cpp
\example BGL_polyhedron_3/distance.cpp
\example BGL_polyhedron_3/incident_vertices.cpp
\example BGL_polyhedron_3/kruskal.cpp
\example BGL_polyhedron_3/kruskal_with_stored_id.cpp
\example BGL_polyhedron_3/normals.cpp
\example BGL_polyhedron_3/polyhedron_partition.cpp
\example BGL_polyhedron_3/range.cpp
\example BGL_polyhedron_3/transform_iterator.cpp
\example BGL_triangulation_2/dijkstra.cpp
\example BGL_triangulation_2/dijkstra_with_internal_properties.cpp
\example BGL_triangulation_2/emst.cpp
\example BGL_triangulation_2/emst_regular.cpp
\example BGL_triangulation_2/emst_cdt_plus_hierarchy.cpp
\example BGL_surface_mesh/prim.cpp
\example BGL_surface_mesh/gwdwg.cpp
\example BGL_surface_mesh/seam_mesh.cpp
\example BGL_surface_mesh/shortest_path.cpp
\example BGL_surface_mesh/write_inp.cpp
\example BGL_surface_mesh/surface_mesh_dual.cpp
\example BGL_surface_mesh/connected_components.cpp
\example BGL_surface_mesh/surface_mesh_partition.cpp
\example Surface_mesh_skeletonization/simple_mcfskel_example.cpp
\example Surface_mesh_segmentation/extract_segmentation_into_mesh_example.cpp
\example Polygon_mesh_processing/face_filtered_graph_example.cpp
\example Property_map/dynamic_properties.cpp
\example Surface_mesh/sm_derivation.cpp
\example Polyhedron/poly_derivation.cpp
*/

---

### BGL Doc BGL Graph Traits (`BGL/doc/BGL/graph_traits.txt`)

/*!
\defgroup PkgBGLTraits Specializations of boost::graph_traits

\ingroup PkgBGLRef

The \bgl defines the class template
<A HREF="https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/traits/graph_traits.html">`boost::graph_traits`</A>
as a uniform interface to the properties and types of %graph types.

We provide specializations of this class template for several \cgal data structures.

\section BGLSMGT Specialization for the Surface_mesh Class
Defined in `<CGAL/boost/graph/graph_traits_Surface_mesh.h>`

We provide partial specialization for the class `CGAL::Surface_mesh` so that it is a model
of the graph concepts `BidirectionalGraph`, `VertexAndEdgeListGraph`, `AdjacencyMatrix`,
and `MutableFaceGraph`.

The const specialization, `boost::graph_traits< CGAL::Surface_mesh<Traits> const>`
is also defined, using the constant handles in the surface mesh.

The traits class `boost::graph_traits< CGAL::Surface_mesh<T> >` provides the following types:

| Member                   | Value  | Description |
| :----------------------- | :----: | :---------- |
| `vertex_descriptor`      | `Surface_mesh::Vertex_index`     | Identify vertices in the graph. |
| `edge_descriptor`        | `Surface_mesh::Edge_index`   | Identify edges in the graph. |
| `halfedge_descriptor`    | `Surface_mesh::Halfedge_index`   | Identify halfedges in the graph. |
| `face_descriptor`        | `Surface_mesh::Face_index`       | Identify faces in the graph. |
| `adjacency_iterator`     | `CGAL::Vertex_around_target_iterator<Surface_mesh<P> >` | An iterator to traverse through the vertices adjacent to a vertex. Its value type is `vertex_descriptor`. |
| `out_edge_iterator`      | `CGAL::Out_edge_iterator<Surface_mesh<P> >` | An iterator to traverse through the outgoing edges incident to a vertex. Its value type is `edge_descriptor`. |
| `in_edge_iterator`       | `CGAL::In_edge_iterator<Surface_mesh<P> >` | An iterator to traverse through the incoming edges incident to a vertex. Its value type is `edge_descriptor`. |
| `vertex_iterator`        | `Surface_mesh::Vertex_iterator`     | An iterator to traverse through the vertices of the graph. Its value type is `vertex_descriptor`. |
| `edge_iterator`          | `Surface_mesh::Edge_iterator`     | An iterator to traverse through the edges of the graph. Its value type is `edge_descriptor`. |
| `halfedge_iterator`      | `Surface_mesh::Halfedge_iterator`     | An iterator to traverse through the halfedges of the graph. Its value type is `halfedge_descriptor`. |
| `face_iterator`          | `Surface_mesh::Face_iterator`         | An iterator to traverse through the faces of the graph. Its value type is `face_descriptor`. |
| `directed_category`      | `boost::undirected_tag`      | This graph is not directed. |
| `edge_parallel_category` | `boost::disallow_parallel_edge_tag`   | This graph does not support multiedges. |
| `traversal_category`     | Inherits from `boost::bidirectional_graph_tag`, `boost::vertex_list_graph_tag`, `boost::edge_list_graph_tag`, and `boost::adjacency_graph_tag`  | The ways in which the vertices in the graph can be traversed. |
| `vertices_size_type`     | `Surface_mesh::vertices_size_type` | The size type of the vertex list. |
| `edges_size_type`        | `Surface_mesh::edges_size_type` | The size type of the edge list. |
| `degree_size_type`       | `Surface_mesh::degree_size_type` | The size type of the adjacency list. |

\section BGLPolyGT Specialization for the Polyhedron Class

Defined in `<CGAL/boost/graph/graph_traits_Polyhedron_3.h>`

We provide partial specialization for the class `CGAL::Polyhedron_3` so that it is a model
of the graph concepts `BidirectionalGraph`, `VertexAndEdgeListGraph`, `AdjacencyMatrix`,
and `MutableFaceGraph`.

The const specialization, `boost::graph_traits< CGAL::Polyhedron_3<Traits> const>`
is also defined, using the constant handles in the polyhedron.

The traits class `boost::graph_traits< CGAL::Polyhedron_3<T> >` provides the following types:

| Member                   | Value  | Description |
| :----------------------- | :----: | :---------- |
| `vertex_descriptor`      | `Polyhedron_3::Vertex_handle`     | Identify vertices in the graph. |
| `edge_descriptor`        | `unspecified_type`   | Identify edges in the graph. |
| `halfedge_descriptor`    | `Polyhedron_3::Halfedge_handle`   | Identify halfedges in the graph. |
| `face_descriptor`        | `Polyhedron_3::Face_handle`       | Identify faces in the graph. |
| `adjacency_iterator`     | `CGAL::Vertex_around_target_iterator<Polyhedron_3<T> >` | An iterator to traverse through the vertices adjacent to a vertex. Its value type is `vertex_descriptor`. |
| `out_edge_iterator`      | `CGAL::Out_edge_iterator<Polyhedron_3<T> >` | An iterator to traverse through the outgoing edges incident to a vertex. Its value type is `edge_descriptor`. |
| `in_edge_iterator`       | `CGAL::In_edge_iterator<Polyhedron_3<T> >` | An iterator to traverse through the incoming edges incident to a vertex. Its value type is `edge_descriptor`. |
| `vertex_iterator`        | `unspecified_type`     | An iterator to traverse through the vertices of the graph. Its value type is `vertex_descriptor`. |
| `edge_iterator`          | `unspecified_type`     | An iterator to traverse through the edges of the graph. Its value type is `edge_descriptor`. |
| `halfedge_iterator`      | `unspecified_type`     | An iterator to traverse through the halfedges of the graph. Its value type is `halfedge_descriptor`. |
| `face_iterator`          | `unspecified_type`         | An iterator to traverse through the faces of the graph. Its value type is `face_descriptor`. |
| `directed_category`      | `boost::undirected_tag`      | This graph is not directed. |
| `edge_parallel_category` | `boost::disallow_parallel_edge_tag`   | This graph does not support multiedges. |
| `traversal_category`     | Inherits from `boost::bidirectional_graph_tag`, `boost::vertex_list_graph_tag`, `boost::edge_list_graph_tag`, and`boost::adjacency_graph_tag`  | The ways in which the vertices in the graph can be traversed. |
| `vertices_size_type`     | `Polyhedron_3::size_type` | The size type of the vertex list. |
| `edges_size_type`        | `Polyhedron_3::size_type` | The size type of the edge list. |
| `degree_size_type`       | `Polyhedron_3::size_type` | The size type of the adjacency list. |

For convenience, the type `edge_descriptor` is hashable using the functor `CGAL::Handle_hash_function`,
which is the default hash functor of `CGAL::Unique_hash_map`.

\section BGLLCCGT Specialization for the Linear_cell_complex_for_combinatorial_map Class

Defined in `<CGAL/boost/graph/graph_traits_Linear_cell_complex_for_combinatorial_map.h>`

We provide partial specialization for the class `CGAL::Linear_cell_complex_for_combinatorial_map` so that it is a model of the graph concepts
`BidirectionalGraph`, `VertexAndEdgeListGraph`, `AdjacencyMatrix`, and `MutableFaceGraph`.

The const specialization is also defined, using the constant handles in the linear cell complex.

Let us denote by LCC an instantiation of CGAL::Linear_cell_complex_for_combinatorial_map<...> class.
The traits class `boost::graph_traits<LCC>` provides the following types:

| Member                   | Value  | Description |
| :----------------------- | :----: | :---------- |
| `vertex_descriptor`      | `LCC::Vertex_attribute_handle`                 | The vertex descriptor |
| `edge_descriptor`        | `unspecified_type`                             | The edge descriptor |
| `halfedge_descriptor`    | `LCC::Dart_handle`   | The halfedge descriptor |
| `face_descriptor`        | `unspecified_type`                             | The face descriptor |
| `adjacency_iterator`     | `CGAL::Vertex_around_target_iterator<LCC>`     | Iterates through adjacent vertices|
| `out_edge_iterator`      | `CGAL::Out_edge_iterator<LCC>`                 | Iterate through the out-edges of a vertex. |
| `in_edge_iterator`       | `CGAL::Out_edge_iterator<LCC>`                 | Iterate through the in-edges of a vertex. |
| `vertex_iterator`        | `unspecified_type`         | Iterate through the vertices of LCC.|
| `edge_iterator`          | `unspecified_type`         | Iterate through the edges of LCC.|
| `halfedge_iterator`      | `unspecified_type`         | Iterate through the halfedges of LCC.|
| `face_iterator`          | `unspecified_type`         | Iterate through the faces of LCC.|
| `directed_category`      | Inherits from `boost::bidirectional_graph_tag`, `boost::vertex_list_graph_tag`, `boost::edge_list_graph_tag`, and `boost::adjacency_graph_tag`  | |
| `edge_parallel_category` | `boost::disallow_parallel_edge_tag`   | Indicates that this graph does not support multiedges |
| `traversal_category`     | `boost::bidirectional_graph_tag`      | Indicates that this graph is bidirectional |
| `vertices_size_type`     | `LCC::size_type` | The size type of the vertex list |
| `edges_size_type`        | `LCC::size_type` | The size type of the edge list |
| `degree_size_type`       | `LCC::size_type` | The size type of the adjacency list |

For convenience, the type `edge_descriptor` is hashable using the functor `CGAL::Handle_hash_function` that is the default hash functor of `CGAL::Unique_hash_map`.

\subsection Requirements

<ul>
<li> The item class used by `CGAL::Linear_cell_complex_for_combinatorial_map` must have both 0-attributes and 2-attributes enabled.</li>

<li> No dart is 1-free, nor 2-free. Holes in a mesh are represented by using the same convention than for `CGAL::Polyhedron_3` and `CGAL::Surface_mesh`: a dart <code>d</code> belongs to a border if the 2-attribute of <code>beta<2>(d)</code> is nullptr.</li>

<li> All darts of the linear cell complexes must be associated with a 2-attribute, except darts that represent holes.</li>

<li> In order to use property maps, darts and types associated with of 0- and 2-attributes must define the two functions:
\code
int id() const; // Returns the index.
int& id();      // Returns a reference to the index stored in the attribute.
\endcode
</ul>

For darts, this can be done by defining `Darts_with_id` as `CGAL::Tag_true` in the `Dart_wrapper` struct of the item class. <br>
For attributes, it is possible to use `CGAL::Cell_attribute_with_id` and `CGAL::Cell_attribute_with_point_and_id` classes to define your item class using attributes with id.

You can also use the `CGAL::Linear_cell_complex_bgl_min_items` item class, or you can use directly the `CGAL::Linear_cell_complex_for_bgl_combinatorial_map_helper` class.

\section BGLT2GT Specializations for the 2D Triangulation Classes

Defined in `<CGAL/boost/graph/graph_traits_Triangulation_2.h>`,
`<CGAL/boost/graph/graph_traits_Delaunay_triangulation_2.h>`,
`<CGAL/boost/graph/graph_traits_Regular_triangulation_2.h>`,
`<CGAL/boost/graph/graph_traits_Constrained_Delaunay_triangulation_2.h>`,
`<CGAL/boost/graph/graph_traits_Constrained_triangulation_2.h>`,
`<CGAL/boost/graph/graph_traits_Constrained_triangulation_plus_2.h>`, and
`<CGAL/boost/graph/graph_traits_Triangulation_hierarchy_2.h>`.

We provide partial specialization for the classes
`CGAL::Triangulation_2`, `CGAL::Delaunay_triangulation_2`,
`CGAL::Regular_triangulation_2`, `CGAL::Constrained_triangulation_2`,
`CGAL::Constrained_Delaunay_triangulation_2`, `CGAL::Constrained_triangulation_plus_2`,
and `CGAL::Triangulation_hierarchy_2`
so that they are model of the graph concepts
`BidirectionalGraph`, `VertexAndEdgeListGraph`, and `FaceListGraph`.

Only finite simplices exist when viewed through the scope of these graph traits classes.
The infinite vertex, halfedges, edges, and faces will thus not appear when looping around a border
vertex, or walking through the faces container.

The mapping between vertices, edges, and faces of the triangulation and the
graph is rather straightforward, but there are some subtleties. The
value type of the \bgl iterators is the vertex or edge descriptor,
whereas in \cgal all iterators and circulators are also handles and
hence have as value type Vertex or Edge.

| Member                   | Value  | Description |
| :----------------------- | :----: | :---------- |
| `vertex_descriptor`      | `unspecified_type` | Identify vertices in the graph. |
| `halfedge_descriptor`    | `unspecified_type` | Identify halfedges in the graph. It is constructible from and convertible to `Triangulation::Edge`. It is not a simple typedef, but a proper class, because there is no representation for halfedges in the 2D triangulation data structure. |
| `edge_descriptor`        | `unspecified_type` | Identify edges in the graph. It is constructible from and convertible to `Triangulation::Edge`. It is not a simple typedef, but a proper class, because in an undirected graph the edges `(u,v)` and `(v,u)` must be equal. This is not the case for the Edge type of the triangulation. |
| `face_descriptor`        | `unspecified_type` | Identify faces in the graph. |
| `adjacency_iterator`     | `unspecified_type` | An iterator to traverse through the vertices adjacent to a vertex. Its value type is `vertex_descriptor`. |
| `out_edge_iterator`      | `unspecified_type` | An iterator to traverse through the outgoing edges incident to a vertex. Its value type is `edge_descriptor`. |
| `in_edge_iterator`       | `unspecified_type` | An iterator to traverse through the incoming edges incident to a vertex. Its value type is `edge_descriptor`. |
| `vertex_iterator`        | `unspecified_type` | An iterator to traverse through the vertices of the graph. Its value type is `vertex_descriptor`. |
| `halfedge_iterator`      | `unspecified_type` | An iterator to traverse through the halfedges of the graph. Its value type is `halfedge_descriptor`. |
| `edge_iterator`          | `unspecified_type` | An iterator to traverse through the edges of the graph. Its value type is `edge_descriptor`. |
| `face_iterator`          | `unspecified_type` | An iterator to traverse through the faces of the graph. Its value type is `face_descriptor`. |
| `directed_category`      | `boost::undirected_tag`      | This graph is not directed. |
| `edge_parallel_category` | `boost::disallow_parallel_edge_tag` | This graph does not support multiedges. |
| `traversal_category`     | Inherits from `boost::bidirectional_graph_tag`, `boost::adjacency_graph_tag`, `boost::vertex_list_graph_tag`, and `boost::edge_list_graph_tag` | The ways in which the vertices in the graph can be traversed.. |
| `vertices_size_type`     | `Triangulation::size_type` | The size type of the vertex list. |
| `edges_size_type`        | `Triangulation::size_type` | The size type of the edge list. |
| `degree_size_type`       | `Triangulation::size_type` | The size type of the adjacency list. |

\section BGLArgtGT Specialization for the Arrangement Classes

Defined in `<CGAL/boost/graph/graph_traits_Arrangement_2.h>`

We provide partial specialization for the class `CGAL::Arrangement_2`
so that it is model of the graph concepts `BidirectionalGraph` and `VertexAndEdgeListGraph`.

The const specialization, `boost::graph_traits< CGAL::Arrangement_2<Traits, Dcel> const>`
is also defined, using the constant handles in the arrangement.

The traits class `boost::graph_traits< CGAL::Arrangement_2<T, Dcel> >`
provides the following types:

| Member                   | Value  | Description |
| :----------------------- | :----: | :---------- |
| `vertex_descriptor`      | `Arrangement_2::Vertex_handle`     | Identify vertices in the graph. |
| `edge_descriptor`        | `Arrangement_2::Halfedge_handle`   | Identify edges in the graph. |
| `adjacency_iterator`     | `Vertex_around_target_iterator<Arrangement_2>`| An iterator to traverse through the vertices adjacent to a vertex. Its value type is `vertex_descriptor`.|
| `out_edge_iterator`      | `unspecified_type` | An edge iterator which only iterates over the outgoing halfedges around a vertex. It corresponds to a `Arrangement_2::Halfedge_around_vertex_circulator` with the difference that its value type is an edge descriptor and not `Arrangement_2::Halfedge`|
| `in_edge_iterator`       | `unspecified_type` | An edge iterator which only iterates over the incoming edges around a vertex. It corresponds to a `Arrangement_2::Halfedge_around_vertex_circulator` with the difference that its value type is an edge descriptor and not `Arrangement_2::Halfedge`|
| `vertex_iterator`        | `unspecified_type` | An iterator corresponding to `Arrangement_2::Vertex_iterator`, with the difference that its value type is a vertex descriptor and not `Arrangement_2::Vertex`  |
| `edge_iterator`          | `unspecified_type` | An iterator corresponding to `Arrangement_2::Halfedge_iterator` with the difference that its value type is an edge descriptor and not `Arrangement_2::Halfedge`|
| `directed_category`      | `boost::directed_tag`      | This graph is directed. |
| `edge_parallel_category` | `boost::allow_parallel_edge_tag` | This graph supports multiedges. |
| `traversal_category`     | Inherits from `boost::bidirectional_graph_tag`, `boost::vertex_list_graph_tag`, `boost::edge_list_graph_tag`, and `boost::adjacency_graph_tag`  | The ways in which the vertices in the graph can be traversed. |
| `vertices_size_type`     | `Arrangement_2::Size` | The size type of the vertex list. |
| `edges_size_type`        | `Arrangement_2::Size` | The size type of the edge list. |
| `degree_size_type`       | `Arrangement_2::Size` | The size type of the adjacency list. |

\section BGLOMPAK Specialization for the OpenMesh::PolyMesh_ArrayKernelT Class

Defined in `<CGAL/boost/graph/graph_traits_PolyMesh_ArrayKernelT.h>`

We provide partial specialization for the class `OpenMesh::PolyMesh_ArrayKernelT` so that it is a model
of the graph concepts `BidirectionalGraph`, `VertexAndEdgeListGraph`, `AdjacencyMatrix`,
and `MutableFaceGraph`.

The traits class `boost::graph_traits<OpenMesh::PolyMesh_ArrayKernelT<K> >` provides the following types:

| Member                   | Value  | Description |
| :----------------------- | :----: | :---------- |
| `vertex_descriptor`      | `OpenMesh::PolyMesh_ArrayKernelT<K>::%VertexHandle`     | Identify vertices in the graph. |
| `edge_descriptor`        | `unspecified_type`   | Identify edges in the graph. |
| `halfedge_descriptor`    | `OpenMesh::PolyMesh_ArrayKernelT<K>::%HalfedgeHandle`   | Identify halfedges in the graph. |
| `face_descriptor`        | `OpenMesh::PolyMesh_ArrayKernelT<K>::%FaceHandle`       | Identify faces in the graph. |
| `adjacency_iterator`     | `CGAL::Vertex_around_target_iterator<OpenMesh::PolyMesh_ArrayKernelT<K> >` | An iterator to traverse through the vertices adjacent to a vertex. Its value type is `vertex_descriptor`. |
| `out_edge_iterator`      | `CGAL::Out_edge_iterator<OpenMesh::PolyMesh_ArrayKernelT<K> >` | An iterator to traverse through the outgoing edges incident to a vertex. Its value type is `edge_descriptor`. |
| `in_edge_iterator`       | `CGAL::In_edge_iterator<OpenMesh::PolyMesh_ArrayKernelT<K> >` | An iterator to traverse through the incoming edges incident to a vertex. Its value type is `edge_descriptor`. |
| `vertex_iterator`        | `OpenMesh::PolyMesh_ArrayKernelT<K>::%VertexIter`     | An iterator to traverse through the vertices of the graph. Its value type is `vertex_descriptor`. |
| `edge_iterator`          | `unspecified_type`     | An iterator to traverse through the edges of the graph. Its value type is `edge_descriptor`. |
| `halfedge_iterator`      | `OpenMesh::PolyMesh_ArrayKernelT<K>::%HalfedgeIter`     | An iterator to traverse through the halfedges of the graph. Its value type is `halfedge_descriptor`. |
| `face_iterator`          | `OpenMesh::PolyMesh_ArrayKernelT<K>::%FaceIter`         | An iterator to traverse through the faces of the graph. Its value type is `face_descriptor`. |
| `directed_category`      | `boost::undirected_tag`      | This graph is not directed. |
| `edge_parallel_category` | `boost::disallow_parallel_edge_tag`   | This graph does not support multiedges. |
| `traversal_category`     | Inherits from `boost::bidirectional_graph_tag`, `boost::vertex_list_graph_tag`,`boost::edge_list_graph_tag`, and`boost::adjacency_graph_tag`  | The ways in which the vertices in the graph can be traversed. |
| `vertices_size_type`     | `unsigned int` | The size type of the vertex list. |
| `edges_size_type`        | `unsigned int` | The size type of the edge list. |
| `degree_size_type`       | `unsigned int` | The size type of the adjacency list. |

\section BGLOMTMAK Specialization for the OpenMesh::TriMesh_ArrayKernelT Class

Defined in `<CGAL/boost/graph/graph_traits_TriMesh_ArrayKernelT.h>`

We provide partial specialization for the class `OpenMesh::TriMesh_ArrayKernelT` so that it is a model
of the graph concepts `BidirectionalGraph`, `VertexAndEdgeListGraph`, `AdjacencyMatrix`,
and `MutableFaceGraph`.

The traits class `boost::graph_traits<OpenMesh::TriMesh_ArrayKernelT<K> >` provides the following types:

| Member                   | Value  | Description |
| :----------------------- | :----: | :---------- |
| `vertex_descriptor`      | `OpenMesh::TriMesh_ArrayKernelT<K>::%VertexHandle`     | Identify vertices in the graph. |
| `edge_descriptor`        | `unspecified_type`   | Identify edges in the graph. |
| `halfedge_descriptor`    | `OpenMesh::TriMesh_ArrayKernelT<K>::%HalfedgeHandle`   | Identify halfedges in the graph. |
| `face_descriptor`        | `OpenMesh::TriMesh_ArrayKernelT<K>::%FaceHandle`       | Identify faces in the graph. |
| `adjacency_iterator`     | `CGAL::Vertex_around_target_iterator<OpenMesh::TriMesh_ArrayKernelT<K> >` | An iterator to traverse through the vertices adjacent to a vertex. Its value type is `vertex_descriptor`. |
| `out_edge_iterator`      | `CGAL::Out_edge_iterator<OpenMesh::TriMesh_ArrayKernelT<K> >` | An iterator to traverse through the outgoing edges incident to a vertex. Its value type is `edge_descriptor`. |
| `in_edge_iterator`       | `CGAL::In_edge_iterator<OpenMesh::TriMesh_ArrayKernelT<K> >` | An iterator to traverse through the incoming edges incident to a vertex. Its value type is `edge_descriptor`. |
| `vertex_iterator`        | `OpenMesh::PolyMesh_ArrayKernelT<K>::%VertexIter`     | An iterator to traverse through the vertices of the graph. Its value type is `vertex_descriptor`. |
| `edge_iterator`          | `unspecified_type`     | An iterator to traverse through the edges of the graph. Its value type is `edge_descriptor`. |
| `halfedge_iterator`      | `OpenMesh::TriMesh_ArrayKernelT<K>::%HalfedgeIter`     | An iterator to traverse through the halfedges of the graph. Its value type is `halfedge_descriptor`. |
| `face_iterator`          | `OpenMesh::TriMesh_ArrayKernelT<K>::%FaceIter`         | An iterator to traverse through the faces of the graph. Its value type is `face_descriptor`. |
| `directed_category`      | `boost::undirected_tag`      | This graph is not directed. |
| `edge_parallel_category` | `boost::disallow_parallel_edge_tag`   | This graph does not support multiedges. |
| `traversal_category`     | Inherits from `boost::bidirectional_graph_tag`, `boost::vertex_list_graph_tag`, `boost::edge_list_graph_tag`, and `boost::adjacency_graph_tag` | The ways in which the vertices in the graph can be traversed. |
| `vertices_size_type`     | `unsigned int` | The size type of the vertex list. |
| `edges_size_type`        | `unsigned int` | The size type of the edge list. |
| `degree_size_type`       | `unsigned int` | The size type of the adjacency list. |

\section BGLSeam_meshGT Specialization for the Seam_mesh Class

Defined in `<CGAL/boost/graph/graph_traits_Seam_mesh.h>`

We provide partial specialization for the class `CGAL::Seam_mesh` so that it is a model of the graph concepts
`BidirectionalGraph`, `VertexAndEdgeListGraph`, `AdjacencyMatrix`, and `FaceListGraph`.

The traits class `boost::graph_traits< CGAL::Seam_mesh<T> >` provides the following types:

| Member                   | Value  | Description |
| :----------------------- | :----: | :---------- |
| `vertex_descriptor`      | `Seam_mesh::vertex_descriptor`     | Identify vertices in the graph. |
| `edge_descriptor`        | `Seam_mesh::edge_descriptor`   | Identify edges in the graph. |
| `halfedge_descriptor`    | `Seam_mesh::halfedge_descriptor`   | Identify halfedges in the graph. |
| `face_descriptor`        | `Seam_mesh::face_descriptor`       | Identify faces in the graph. |
| `adjacency_iterator`     | `CGAL::Vertex_around_target_iterator<CGAL::Seam_mesh<T> >` | An iterator to traverse through the vertices adjacent to a vertex. Its value type is `vertex_descriptor`. |
| `out_edge_iterator`      | `CGAL::Out_edge_iterator<CGAL::Seam_mesh<T> >` | An iterator to traverse through the outgoing edges incident to a vertex. Its value type is `edge_descriptor`. |
| `in_edge_iterator`       | `CGAL::In_edge_iterator<CGAL::Seam_mesh<T> >` | An iterator to traverse through the incoming edges incident to a vertex. Its value type is `edge_descriptor`. |
| `vertex_iterator`        | `Seam_mesh::vertex_iterator`     | An iterator to traverse through the vertices of the graph. Its value type is `vertex_descriptor`. |
| `edge_iterator`          | `Seam_mesh::edge_iterator`     | An iterator to traverse through the edges of the graph. Its value type is `edge_descriptor`. |
| `halfedge_iterator`      | `Seam_mesh::halfedge_iterator`     | An iterator to traverse through the halfedges of the graph. Its value type is `halfedge_descriptor`. |
| `face_iterator`          | `Seam_mesh::face_iterator`         | An iterator to traverse through the faces of the graph. Its value type is `face_descriptor`. |
| `directed_category`      | `boost::undirected_tag`      | This graph is not directed. |
| `edge_parallel_category` | `boost::disallow_parallel_edge_tag`   | This graph does not support multiedges. |
| `traversal_category`     | Inherits from `boost::bidirectional_graph_tag`, `boost::vertex_list_graph_tag`, and `boost::edge_list_graph_tag` | The ways in which the vertices in the graph can be traversed. |
| `vertices_size_type`     | `Seam_mesh::vertices_size_type` | The size type of the vertex list. |
| `edges_size_type`        | `Seam_mesh::edges_size_type` | The size type of the edge list. |
| `degree_size_type`       | `Seam_mesh::degree_size_type` | The size type of the adjacency list. |

*/

---

### Barycentric Coordinates 2 Doc Barycentric Coordinates 2 Barycentric Coordinates 2 (`Barycentric_coordinates_2/doc/Barycentric_coordinates_2/Barycentric_coordinates_2.txt`)

namespace CGAL {
namespace Barycentric_coordinates {

/*!
\mainpage User Manual
\anchor Chapter_2D_Generalized_Barycentric_Coordinates
\cgalAutoToc

\authors Dmitry Anisimov, David Bommes, Kai Hormann, and Pierre Alliez


\section gbc_introduction Introduction

Barycentric coordinates are widely used in computer graphics and computational mechanics
to determine a position of a point in the plane with respect to a triangle. These coordinates
have been later generalized to support simple polygons in 2D and polyhedra in 3D.

This package offers an efficient and robust implementation of 2D generalized barycentric
coordinates defined for simple polygons in the plane. If coordinates with respect to multivariate
scattered points instead of a polygon are required, please refer to natural neighbor coordinates
from the package \ref chapinterpolation "2D and Surface Function Interpolation".

In particular, this package includes an implementation of \ref wp_example "Wachspress",
\ref dh_example "discrete harmonic", \ref mv_example "mean value", and \ref hm_example "harmonic"
coordinates, and provides some extra functions to compute barycentric coordinates with respect
to \ref seg_example "segments" and \ref tri_example "triangles".

\cgalFigureBegin{overview, overview.svg}
Wachspress (WP), discrete harmonic (DH), mean value (MV), and harmonic (HM) coordinate functions
for a convex polygon plotted with respect to the marked vertex.
\cgalFigureEnd


\section gbc_interface Software Design

Mean value and harmonic coordinates are the most generic coordinates in this package,
because they allow an arbitrary simple polygon as input. Wachspress and discrete harmonic coordinates
are, by definition, limited to strictly convex polygons. Segment coordinates take as input
any non-degenerate segment, and triangle coordinates allow an arbitrary non-degenerate triangle.

Wachspress, discrete harmonic, mean value, and harmonic coordinates are all generalized
barycentric coordinates. However, while Wachspress, discrete harmonic, and mean value
coordinates can be computed analytically, harmonic coordinates cannot. They first need
to be approximated over a triangulation of the interior part of the polygon. Once approximated,
they can be evaluated analytically at any point inside the polygon.

For all analytic coordinates, we provide two algorithms. One has a linear time complexity,
but may suffer imprecisions near the polygon boundary, while the second one is precise
but has a quadratic time complexity. The user can choose the preferred algorithm by
specifying a computation policy `Barycentric_coordinates::Computation_policy_2`.

All analytic barycentric coordinates for polygons can be computed either by instantiating a class
or through one of the free functions. Harmonic coordinates can be computed only by
instantiating a class that must be parameterized by a model of the concept `DiscretizedDomain_2`.
Segment and triangle coordinates can be computed only through the free functions.
For more information see the \ref PkgBarycentricCoordinates2Ref.

Any point in the plane may be taken as a query point. However, we do not recommend using
Wachspress and discrete harmonic coordinates with query points outside the closure
of a polygon, because they are not well-defined for some of these points. The same holds
for harmonic coordinates, which are not defined everywhere outside the polygon. For more
information see Section \ref gbc_degeneracies.

The output of the computation is a set of coordinate values at the given query point
with respect to the polygon vertices. That means that the number of returned coordinates
per query point equates the number of polygon vertices. The ordering of the coordinates
is the same as the ordering of polygon vertices.

All class and function templates are parameterized by a traits class, which is a model
of the concept `BarycentricTraits_2`. It provides all necessary geometric primitives,
predicates, and constructions, which are required for the computation. All models of `Kernel`
can be used. A polygon is provided as a range of vertices with a
\ref PkgPropertyMapRef "property map" that maps a vertex from the polygon to `CGAL::Point_2`.

If you do not know which coordinate function best fits your application, you can address the
table below for some advise.

<table class="markdownTable" align="center">
<tr class="markdownTableHead">
<th class="markdownTableHeadCenter">Coordinates</th>
<th class="markdownTableHeadCenter">Properties</th>
<th class="markdownTableHeadCenter">Valid domain</th>
<th class="markdownTableHeadCenter">Closed form</th>
<th class="markdownTableHeadCenter">Queries</th>
<th class="markdownTableHeadCenter">Speed</th>
</tr>
<tr class="markdownTableBody">
<td class="markdownTableBodyCenter">Segment</td>
<td class="markdownTableBodyCenter">All</td>
<td class="markdownTableBodyCenter">2D non-degenerate segments</td>
<td class="markdownTableBodyCenter">Yes</td>
<td class="markdownTableBodyCenter">Everywhere on the supporting line</td>
<td class="markdownTableBodyCenter">+++</td>
</tr>
<tr class="markdownTableBody">
<td class="markdownTableBodyCenter">Triangle</td>
<td class="markdownTableBodyCenter">All</td>
<td class="markdownTableBodyCenter">2D non-degenerate triangles</td>
<td class="markdownTableBodyCenter">Yes</td>
<td class="markdownTableBodyCenter">Everywhere in 2D</td>
<td class="markdownTableBodyCenter">+++</td>
</tr>
<tr class="markdownTableBody">
<td class="markdownTableBodyCenter">Discrete harmonic</td>
<td class="markdownTableBodyCenter">May be negative</td>
<td class="markdownTableBodyCenter">Strongly convex polygons</td>
<td class="markdownTableBodyCenter">Yes</td>
<td class="markdownTableBodyCenter">Everywhere inside the polygon</td>
<td class="markdownTableBodyCenter">++</td>
</tr>
<tr class="markdownTableBody">
<td class="markdownTableBodyCenter">Wachspress</td>
<td class="markdownTableBodyCenter">All</td>
<td class="markdownTableBodyCenter">Strongly convex polygons</td>
<td class="markdownTableBodyCenter">Yes</td>
<td class="markdownTableBodyCenter">Everywhere inside the polygon</td>
<td class="markdownTableBodyCenter">++</td>
</tr>
<tr class="markdownTableBody">
<td class="markdownTableBodyCenter">Mean value</td>
<td class="markdownTableBodyCenter">May be negative</td>
<td class="markdownTableBodyCenter">Simple polygons</td>
<td class="markdownTableBodyCenter">Yes</td>
<td class="markdownTableBodyCenter">Everywhere in 2D</td>
<td class="markdownTableBodyCenter">++</td>
</tr>
<tr class="markdownTableBody">
<td class="markdownTableBodyCenter">Harmonic</td>
<td class="markdownTableBodyCenter">All</td>
<td class="markdownTableBodyCenter">Simple polygons</td>
<td class="markdownTableBodyCenter">No</td>
<td class="markdownTableBodyCenter">Everywhere inside the polygon</td>
<td class="markdownTableBodyCenter">+</td>
</tr>
</table>

\note This is the second version of the package with the modified and improved API.
The package still supports the old API. See more details \ref depr_example "here".


\section gbc_examples Examples

In order to facilitate the process of learning this package, we provide various examples
with a basic usage of different barycentric components.


\subsection seg_example Segment Coordinates

This example illustrates the use of the global function `segment_coordinates_2()`.
We compute coordinates at three green points along the segment \f$[v_0, v_1]\f$ and at two blue points outside this segment
but along its supporting line. The symmetry of the query points helps recognizing errors that
may have occurred during construction of the example. The used `Kernel` is exact.

\anchor seg_coord_example
\cgalFigureBegin{seg_example, seg_coord_example.svg}
Example's point pattern.
\cgalFigureEnd

\cgalExample{Barycentric_coordinates_2/segment_coordinates.cpp}


\subsection tri_example Triangle Coordinates

In this example, we show how to use the global function `triangle_coordinates_2()`.
We compute coordinates for three sets of points: interior (green), boundary (red), and exterior (blue).
Note that some of the coordinate values for the exterior points are negative.
The used `Kernel` is inexact.

\anchor tri_coord_example
\cgalFigureBegin{tri_example, tri_coord_example.svg}
Example's point pattern.
\cgalFigureEnd

\cgalExample{Barycentric_coordinates_2/triangle_coordinates.cpp}


\subsection wp_example Wachspress Coordinates

In the following example, we generate 100 random points (green/red/black), then we take the
convex hull (red/black) of this set of points as our polygon (black), and compute Wachspress
coordinates at all the generated points. The used `Kernel` is inexact.

\anchor wp_coord_example
\cgalFigureBegin{wp_example, wp_coord_example.svg}
Example's point pattern.
\cgalFigureEnd

\cgalExample{Barycentric_coordinates_2/wachspress_coordinates.cpp}


\subsection dh_example Discrete Harmonic Coordinates

In this example, we compute discrete harmonic coordinates for a set of green (interior),
red (boundary), and blue (exterior) points with respect to a unit square. We also demonstrate
the use of various containers, both random access and serial access, different property maps,
and the ability to choose a computation policy. For points on the polygon boundary,
we use the free function `boundary_coordinates_2()`.
The used `Kernel` is exact.

\anchor dh_coord_example
\cgalFigureBegin{dh_example, dh_coord_example.svg}
Example's point pattern.
\cgalFigureEnd

\cgalExample{Barycentric_coordinates_2/discrete_harmonic_coordinates.cpp}


\subsection mv_example Mean Value Coordinates

This is an example that illustrates how to compute mean value coordinates for a set of green points
in a star-shaped polygon. We note that this type of coordinates is well-defined for such a concave polygon
while Wachspress and discrete harmonic coordinates are not. However, it may yield negative
coordinate values for points outside <a href="https://en.wikipedia.org/wiki/Star-shaped_polygon">the polygon's kernel</a>
(shown in red). We speed up the computation using the linear time complexity algorithm by specifying
a computation policy `Barycentric_coordinates::Computation_policy_2`. The used `Kernel` is inexact.

\anchor mv_coord_example
\cgalFigureBegin{mv_example, mv_coord_example.svg}
Example's point pattern.
\cgalFigureEnd

\cgalExample{Barycentric_coordinates_2/mean_value_coordinates.cpp}


\subsection hm_example Harmonic Coordinates
This example illustrates how to \ref terrain_triangulation_fig "discretize" the interior part
of the \ref terrain_example_fig "polygon" and compute harmonic coordinates at the vertices
of the discretized domain, which is represented by a 2D Delaunay triangulation. Once computed,
harmonic coordinate functions can be evaluated at any point in the closure of the polygon.
To illustrate such an evaluation, we compute the barycenter of each triangle and evaluate harmonic coordinates
at this barycenter. Since harmonic coordinates can only be approximated, the used `Kernel` is inexact.

\anchor hm_coord_example
\cgalExample{Barycentric_coordinates_2/harmonic_coordinates.cpp}


\subsection height_inter_example Terrain Modeling

This is an advanced example that illustrates how to use generalized barycentric coordinates
for height interpolation with applications to terrain modeling. It also shows how to use
a non-default traits class with our package instead of a `Kernel` traits class.
Suppose we know the boundary of three-dimensional piece of terrain that can be represented
as a polygon with several three-dimensional vertices, where the third dimension indicates
the corresponding height. The task is to propagate the height from the known sample points
on the boundary to the polygon's interior. This gives an approximate estimation of
the terrain's surface in this region.

\anchor terrain_example_fig
\cgalFigureBegin{terrain_example, terrain.svg}
A 2D polygon with 50 vertices representing a piece of terrain with convex and concave parts. The height is not shown.
\cgalFigureEnd

In this example, we project a 3D polygon orthogonally onto the 2D plane using the class
`CGAL::Projection_traits_xy_3`, triangulate its interior using the class `Delaunay_domain_2`,
and compute mean value coordinates at the vertices of this triangulation with respect to the polygon vertices.
Finally, we interpolate the height data from the polygon boundary to its interior
using the computed coordinates and the global interpolation function from the
package \ref chapinterpolation "2D and Surface Function Interpolation".

\anchor terrain_example
\cgalExample{Barycentric_coordinates_2/terrain_height_modeling.cpp}

As a result, we get a smooth function inside the polygon that approximates the underlying terrain surface.

\cgalFigureBegin{terrain_interpolation_example, terrain_interpolation.png}
The interpolated data. The color bar represents the corresponding height.
\cgalFigureEnd


\subsection shape_deform_example Shape Deformation

This is another advanced example that shows how to use generalized barycentric coordinates
in order to deform a given 2D shape into another shape as shown in the figure below.
Harmonic coordinates satisfy all the properties of barycentric coordinates for complicated
concave polygons and hence this is our choice to perform a shape deformation. Note that
even though harmonic coordinates are guaranteed to be positive inside a polygon, they
do not guarantee a bijective mapping between the source and target shapes that is
the target mesh can fold-over the target polygon after the mapping (see the little fold-over
in the left shoulder of the target shape).

\cgalFigureBegin{shape_deformation_example, shape_deformation.svg}
The shape on the left is deformed into the shape on the right. The zoom shows a fold-over
in the left shoulder of the target shape where the red triangle goes over the polygon boundary.
\cgalFigureEnd

\anchor deformation_example
\cgalExample{Barycentric_coordinates_2/shape_deformation.cpp}

But despite the possible fold-overs, a similar technique can be used for image warping
in 2D and character articulation in 3D. For example in 2D, we first enclose an image,
which we want to deform, into a simple polygon so-called *cage*, we then
bound each image pixel to this cage using barycentric coordinates, and finally deform
this cage into a new one, which also deforms the underlying image, as shown
in the figure below for harmonic coordinates.

\cgalFigureBegin{image_warping_example, image_warping.png}
An image on the left is deformed into a new image on the right using a 2D concave polygon (grey)
and harmonic coordinates computed at each image pixel with respect to the vertices of this polygon.
\cgalFigureEnd


\subsection aff_example Affine Coordinates

This is an example, where we show how a
<a href="https://en.cppreference.com/w/cpp/language/lambda">lambda expression</a>
can be used to define a model of generalized barycentric coordinates. To make this example
useful, we implement affine generalized coordinates for a set of scattered points.
The used `Kernel` is inexact.

\anchor aff_coord_example_fig
\cgalFigureBegin{aff_example, aff_coord_example.svg}
Example's point pattern.
\cgalFigureEnd

\anchor aff_coord_example
\cgalExample{Barycentric_coordinates_2/affine_coordinates.cpp}


\subsection depr_example Deprecated Coordinates

This example illustrates how to use the deprecated API of this package.
The used `Kernel` is inexact and the used coordinates are mean value coordinates.
The result is identical to the one from \ref mv_coord_example "this example".

\anchor depr_coord_example
\cgalExample{Barycentric_coordinates_2/deprecated_coordinates.cpp}

\note The headers `Segment_coordinates_2.h` and `Triangle_coordinates_2.h` are
not capitalized in the new version that is they are named `segment_coordinates_2.h`
and `triangle_coordinates_2.h`.


\section gbc_degeneracies Edge Cases

Not all presented coordinates are general enough to handle any query point in the plane, that is
why we highly recommend reading this section in order to learn what can be expected from
each coordinate function. If you want to get more mathematical details about each coordinate
function as well as the complete history and theory behind barycentric coordinates, you should
read \cgalCite{cgal:bc:hs-gbcicg-17}. You can also read an overview
<a href="https://susi.usi.ch/usi/documents/318813">here</a>
(chapters 1 and 2).


\anchor compute_seg_coord
\subsection gbc_deg_segment_coordinates Segment Coordinates

The segment coordinate function with respect to a given segment vertex is a linear
function along the supporting line of this segment that grows from zero at the opposite
vertex to one at the chosen vertex (see the figure below).

\cgalFigureBegin{seg_coord, seg_coord.svg}
The segment coordinate function with respect to the vertex \f$v_0\f$.
\cgalFigureEnd

Segment coordinates can be computed exactly if an exact number type is chosen.
The segment itself, with respect to which we compute coordinates, must be non-degenerate.
If both conditions are satisfied, then the computation never fails. However, to compute coordinates,
the user must ensure that the query point lies exactly on the line \f$L\f$ supporting the segment.
Since in many applications this is not the case, and a query point may lie very close but not exactly on this line,
we provide a solution to remedy this situation.

\cgalFigureBegin{seg_coord_projection, seg_coord_projection.svg}
The orthogonal projection \f$p'\f$ of the vector \f$p\f$ (green) onto the vector \f$q\f$ (red).
\cgalFigureEnd

Suppose that some query point \f$v\f$ does not lie exactly on the line \f$L\f$,
but is some distance \f$d\f$ away as shown in the figure above. If we want to compute
the segment coordinate \f$b_1(v)\f$ with respect to the vertex \f$v_1\f$, we first find the
orthogonal projection \f$p'\f$ of the vector \f$p\f$ onto the vector \f$q\f$ and
then normalize it by the length of \f$q\f$. This yields the segment coordinate \f$b_1(v') = b_1(v)\f$
if \f$v\f$ lies exactly on the line. The other segment coordinate \f$b_0(v')\f$ that is equal
to \f$b_0(v)\f$ when \f$v\f$ is on the line \f$L\f$ is computed the same way but with the
projection of the vector \f$\vec{vv_1}\f$.

\b Warning: do not abuse the feature described above, because it does not yield correct
segment coordinates for the point \f$v\f$ but rather those for \f$v'\f$. Moreover, segment
coordinates for a point \f$v\f$, which does not lie exactly on the line \f$L\f$, do not exist.
But if the non-zero distance \f$d\f$ is due to some numerical instability when computing the
location of the point \f$v\f$ or any other problem, which causes the point to be not exactly on
the line, the final segment coordinates will be, at least approximately, correct.

With inexact number types, the resulting coordinate values are correct up to the precision of the chosen type.


\anchor compute_tri_coord
\subsection gbc_deg_triangular_coordinates Triangle Coordinates

The triangle coordinate function with respect to a given triangle vertex is a linear function
that grows from zero along the opposite edge to one at the chosen vertex (see the figure below).

\cgalFigureBegin{tri_coord, tri_coord.svg}
The triangle coordinate function with respect to the vertex \f$v_0\f$.
\cgalFigureEnd

To compute the triangle coordinates of the query point \f$v\f$, we adopt the standard simple formula

<center>
\f$b_i = \frac{A_i}{A}\f$ with \f$i = 0\dots 2\f$
</center>

where \f$A_i\f$ is the signed area of the sub-triangle opposite to the
vertex \f$i\f$ and \f$A\f$ is the total area of the triangle that is \f$A = A_0 + A_1 + A_2\f$
(see the figure below).

\anchor tri_notations
\cgalFigureBegin{tri_notations, tri_notations.svg}
Notation for triangle coordinates.
\cgalFigureEnd

These coordinates can be computed exactly if an exact number type is chosen, for any query point in the plane
and with respect to any non-degenerate triangle. No special cases are handled. The computation always
yields the correct result. The notion of correctness depends on the precision of the used number type.
Note that for exterior points some coordinate values will be negative.


\anchor compute_wp_coord
\subsection gbc_deg_wachspress_coordinates Wachspress Coordinates

Wachspress coordinates are well-defined in the closure of any <em>strictly convex polygon</em>.
Therefore, when using an exact number type, for any query point from the polygon's closure,
these coordinates are computed exactly and no false result is expected. For exterior query points,
the coordinates can also be computed but not everywhere (see below for more details). For inexact number types,
the resulting precision of the computation is due to the involved algorithm and a chosen number type.
In the following paragraph, we discuss two available algorithms for computing Wachspress coordinates
when an inexact number type is used. The chosen algorithm is specified by a computation policy
`Barycentric_coordinates::Computation_policy_2`.

\anchor wp_polygon
\cgalFigureBegin{wp_notations, wp_notations.svg}
Notation for Wachspress coordinates.
\cgalFigureEnd

To compute Wachspress weights, we follow \cgalCite{cgal:bc:fhk-gcbcocp-06} and use the formula

<center>
\f$w_i = \frac{C_i}{A_{i-1}A_i}\f$
</center>

with \f$i = 1\dots n\f$ where \f$n\f$ is the number of polygon vertices.
In order to compute the coordinates, we normalize these weights,

<center>
\f$b_i = \frac{w_i}{W^{wp}}\qquad\f$ with \f$\qquad W^{wp} = \sum_{j=1}^n w_j.\f$
</center>

This formula becomes unstable when approaching the boundary of the polygon (\f$\approx 1.0e-10\f$ and closer).
To fix the problem, we modify the weights \f$w_i\f$ as

<center>
\f$\bar{w}_i = C_i\prod_{j\not=i-1,i} A_j\f$.
</center>

After the above normalization, this gives us the precise algorithm to compute Wachspress coordinates
but with \cgalBigO{n^2} performance only. The max speed \cgalBigO{n} algorithm uses the standard
weights \f$w_i\f$. Note that mathematically this modification does not change the coordinates. One should
be cautious when using the unnormalized Wachspress weights. In that case, you must choose the
\cgalBigO{n} type.

It is known that for strictly convex polygons the denominator's zero set of the
Wachspress coordinates (\f$W^{wp} = 0~\f$) is a curve, which (in many cases) lies quite
far away from the polygon. More specifically, it interpolates the intersection points of
the supporting lines of the polygon edges. Therefore, the computation of Wachspress coordinates
outside the polygon is possible only at points that do not belong to this curve.

\cgalFigureBegin{wp_zero_set, wp_zero_set.svg}
Zero set (red) of the Wachspress coordinates' denominator \f$W^{wp}\f$ for a non-regular hexagon.
\cgalFigureEnd

\b Warning: we do not recommend using Wachspress coordinates for exterior points!


\anchor compute_dh_coord
\subsection gbc_deg_discrete_harmonic_coordinates Discrete Harmonic Coordinates

Discrete harmonic coordinates have the same requirements as Wachspress coordinates.
They are well-defined in the closure of any <em>strictly convex polygon</em> and,
if an exact number type is chosen, they are computed exactly. However, and unlike Wachspress basis functions,
these coordinates are not necessarily positive. In particular, the weight \f$w_i\f$ is positive
if and only if \f$\alpha+\beta < \pi\f$ (see the figure below for notation). For inexact number types,
the precision of the computation is due to the involved algorithm and a chosen number type. Again,
we describe two algorithms to compute the coordinates when an inexact number type is used:
one is of max precision and one is of max speed.

\anchor dh_polygon
\cgalFigureBegin{dh_notations, dh_notations.svg}
Notation for discrete harmonic coordinates.
\cgalFigureEnd

To compute discrete harmonic weights, we follow \cgalCite{cgal:bc:fhk-gcbcocp-06} and use the formula

<center>
\f$w_i = \frac{r_{i+1}^2A_{i-1}-r_i^2B_i+r_{i-1}^2A_i}{A_{i-1}A_i}\f$
</center>

with \f$i = 1\dots n\f$ where \f$n\f$ is the number of polygon vertices.
In order to compute the coordinates, we normalize these weights,

<center>
\f$b_i = \frac{w_i}{W^{dh}}\qquad\f$ with \f$\qquad W^{dh} = \sum_{j=1}^n w_j.\f$
</center>

This formula becomes unstable when approaching the boundary of the polygon (\f$\approx 1.0e-10\f$ and closer).
To fix the problem, similarly to the previous subsection, we modify the weights \f$w_i\f$ as

<center>
\f$\bar{w}_i = (r_{i+1}^2A_{i-1}-r_i^2B_i+r_{i-1}^2A_i)\prod_{j\not=i-1,i} A_j\f$.
</center>

After the above normalization, this yields the precise algorithm to compute discrete harmonic coordinates
but with \cgalBigO{n^2} performance only. The max speed \cgalBigO{n} algorithm uses the standard
weights \f$w_i\f$. Again, mathematically this modification does not change the coordinates,
one should be cautious when using the unnormalized discrete harmonic weights. In that case,
you must choose the \cgalBigO{n} type.

\b Warning: as for Wachspress coordinates, we do not recommend using discrete harmonic coordinates
for exterior points, because the curve \f$W^{dh} = 0\f$ may have several components,
and one of them interpolates the polygon vertices. However, if you are sure that
the query point does not belong to this curve, you can compute the coordinates
as shown in \ref dh_example " this example".


\anchor compute_mv_coord
\subsection gbc_deg_mean_value_coordinates Mean Value Coordinates

Unlike the previous coordinates, mean value coordinates cannot be computed exactly due to
an inevitable square root operation. Although, if an exact number type is used, the default precision
of the computation depends only on two \cgal functions: `CGAL::to_double()` and `CGAL::sqrt()`.
It is worth saying that providing a number type that supports exact or nearly exact computation
of the square root is possible, however since such types are usually impractical due to the
large overhead, the conversion to a floating-point format above is always effective. On the other hand,
mean value coordinates are well-defined everywhere in the plane for any simple polygon. In addition,
if your traits class provides a more precise version of the square root function, the final precision
of the computation with exact number types will depend only on the precision of that function.

\anchor mv_polygon
\cgalFigureBegin{mv_notations, mv_notations.svg}
Notation for mean value coordinates.
\cgalFigureEnd

For these coordinates, we provide two algorithms: one is of max precision and one is of max speed.
The first one works everywhere in the plane, and the precision of the computation depends only
on the chosen number type, including the remarks above. This algorithm is based on the following weight
formula from \cgalCite{cgal:bc:f-wmvc-14}

<center>
\f$w_i = \sigma_i\bar{w}_i\qquad\f$ with \f$\qquad\bar{w}_i = (r_{i-1}r_{i+1}-d_{i-1}d_{i+1})^{1/2}\prod_{j\not= i-1,i}(r_jr_{j+1} + d_jd_{j+1})^{1/2}\qquad\f$
where \f$\qquad r_i = \|d_i\|.\f$
</center>

Since \f$\bar{w}_i\f$ is always positive, we must append to it the proper sign \f$\sigma_i\f$
of the signed mean value weight, which can be found efficiently (see the figures below).
This weight is always positive to the left of the red piecewise linear curve,
and it is negative to the right of this curve, moving in the counterclockwise direction.

\cgalFigureBegin{mv_weight_signs, mv_weight_signs.svg}
Signs of the mean value weight \f$w_i\f$ depending on the region with respect to a
convex polygon \f$P\f$ and a concave polygon \f$P'\f$.
\cgalFigureEnd

After the normalization of these weights as before

<center>
\f$b_i = \frac{w_i}{W^{mv}}\qquad\f$ with \f$\qquad W^{mv} = \sum_{j=1}^n w_j\f$
</center>

we obtain the max precision \cgalBigO{n^2} algorithm. The max speed \cgalBigO{n} algorithm computes the
weights \f$w_i\f$ using the pseudocode from <a href="https://www.inf.usi.ch/hormann/nsfworkshop/presentations/Hormann.pdf">here</a>.
These weights

<center>
\f$w_i = \frac{t_{i-1} + t_i}{r_i}\qquad\f$
with \f$\qquad t_i = \frac{\text{det}(d_i, d_{i+1})}{r_ir_{i+1} + d_id_{i+1}}\f$
</center>

are also normalized. Note that they are unstable if a query point is closer than \f$\approx 1.0e-10\f$
to the polygon boundary, similarly to Wachspress and discrete harmonic coordinates and
one should be cautious when using the unnormalized mean value weights. In that case, you must choose the
\cgalBigO{n} type.


\anchor compute_hm_coord
\subsection gbc_deg_harmonic_coordinates Harmonic Coordinates

The harmonic coordinates are computed by solving the Laplace equation

<center>
\f$\Delta b = 0\f$
</center>

subject to suitable Dirichlet boundary conditions. Harmonic coordinates are the only coordinates
in this package, which are guaranteed to be non-negative in the closure of any simple polygon and
satisfy all properties of barycentric coordinates, however such desirable properties come with the fact
that these coordinates are well-defined only inside a polygon. If an exterior query point is provided,
its coordinates are set to zero.

Another disadvantage of these coordinates is that they cannot be computed
exactly, because harmonic coordinates do not have a simple closed-form expression and
must be approximated. The common way to approximate these coordinates is
by discretizing over the space of piecewise linear functions with respect to
a triangulation of the polygon. The denser triangulation of the interior part of
the polygon, the better approximation of the coordinates. To get a high quality
approximation of the coordinates, the user should provide a rather dense partition
of the polygon's interior domain that in turn leads to larger running times when
computing the coordinates.

\anchor terrain_triangulation_fig
\cgalFigureBegin{terrain_triangulation, terrain_triangulation.svg}
Sparse triangulation of the polygon's interior domain (left): smaller running times,
lower coordinates quality; dense triangulation (right): larger running times,
higher coordinates quality.
\cgalFigureEnd

From all this follows, that any exact `Kernel` will be rejected and it is not possible
to compute analytic harmonic weights. However, once the coordinates are computed at the
vertices of the triangulation, they can be evaluated analytically at any interior
query point. For evaluation, we first locate a triangle that contains the query point
and then linearly interpolate harmonic coordinates defined at the vertices of this
triangle to the query point with the help of \ref gbc_deg_triangular_coordinates "triangle coordinates" as

<center>
\f$b_i = b_0^{tr} b_i^0 + b_1^{tr} b_i^1 + b_2^{tr} b_i^2\f$
</center>

with \f$i = 1\dots n\f$, where \f$n\f$ is the number of polygon vertices, \f$b_{0}^{tr}\f$,
\f$b_{1}^{tr}\f$, and \f$b_{2}^{tr}\f$ are the triangle coordinates of the query point with
respect the three vertices of the located triangle, and \f$b_i^{0}\f$, \f$b_i^{1}\f$, and \f$b_i^{2}\f$
are the harmonic coordinates pre-computed at the triangle vertices.


\section gbc_performance Performance

We strive for robustness and efficiency at the same time. Efficiency is especially important.
These coordinates are used in many applications where they must be computed for millions of points
and, thus, the real time computation of coordinates has been made possible. In this section,
we present next the computation runtimes of the implemented algorithms.

The structure of the speed test that we use to evaluate the running times consists
of computing coordinate values (or weights) at >= 1 million strictly interior points
with respect to a polygon (or triangle, or segment). At each iteration of the loop,
we create a query point and compute its coordinates. The time presented in the log-log scale plot
at the end of the section is the arithmetic mean of all trials in the loop of 10 iterations.
The time presented in the plot is for analytic coordinates only since harmonic coordinates
of a reasonable (application-dependent) quality are substantially slower to compute and
cannot be fairly compared to the analytic coordinate functions.

The time to compute coordinates depends on many factors such as memory allocation, input kernel, output container,
number of points, etc. In our tests, we used the most standard C++ and \cgal features with minimum memory allocation.
Therefore, the final time presented is the average time that can be expected without deep optimization
but still with efficient memory allocation. It also means that it may vary depending on the usage of the package.

To benchmark analytic coordinates, we used a MacBook Pro 2011 with 2 GHz Intel Core i7 processor (2 cores)
and 8 GB 1333 MHz DDR3 memory. The installed operating system was OS X 10.9 Maverick.
The resulting timings for all closed-form coordinates can be found in the figure below.

\cgalFigureBegin{analytic_timings, analytic_timings.png}
Time in seconds to compute \f$n\f$ coordinate values for a polygon with \f$n\f$ vertices
at 1 million query points with the max speed \cgalBigO{n} algorithms (dashed) and
the max precision \f$0(n^2)\f$ algorithms (solid) for Wachspress (blue), discrete
harmonic (red), and mean value (green) coordinates.
\cgalFigureEnd

From the figure above we observe that the \cgalBigO{n^2} algorithm is as fast
as the \cgalBigO{n} algorithm if we have a polygon with a small number of vertices.
But as the number of vertices is increased, the linear algorithm outperforms the squared one,
as expected. One of the reasons for this behavior is that for a small number of vertices
the multiplications of \f$n-2\f$ elements inside the \cgalBigO{n^2} algorithm take almost the
same time as the corresponding divisions in the \cgalBigO{n} algorithm. For a polygon with
many vertices, these multiplications are substantially slower.

To benchmark harmonic coordinates, we used a MacBook Pro 2018 with 2.2 GHz Intel Core i7 processor (6 cores)
and 32 GB 2400 MHz DDR4 memory. The installed operating system was OS X 10.15 Catalina.
The average time to compute harmonic coordinates in the loop of 10 iterations can be found in the tables below.

The first table shows how the time to compute the coordinates on a unit square depends on the number of
triangulation vertices. We show separately the time to setup the matrix, factorize it, and solve it
with respect to the four vertices of the unit square.

<table class="markdownTable" align="center">
<tr class="markdownTableHead">
<th class="markdownTableHeadCenter">Number of queries (approx.)</th>
<th class="markdownTableHeadCenter">Setup (in seconds)</th>
<th class="markdownTableHeadCenter">Factorize (in seconds)</th>
<th class="markdownTableHeadCenter">Solve (in seconds)</th>
<th class="markdownTableHeadCenter">Total (in seconds)</th>
</tr>
<tr class="markdownTableBody">
<td class="markdownTableBodyCenter">100</td>
<td class="markdownTableBodyCenter">0.000056</td>
<td class="markdownTableBodyCenter">0.000099</td>
<td class="markdownTableBodyCenter">0.000015</td>
<td class="markdownTableBodyCenter">0.000170</td>
</tr>
<tr class="markdownTableBody">
<td class="markdownTableBodyCenter">500</td>
<td class="markdownTableBodyCenter">0.000266</td>
<td class="markdownTableBodyCenter">0.000574</td>
<td class="markdownTableBodyCenter">0.000064</td>
<td class="markdownTableBodyCenter">0.000904</td>
</tr>
<tr class="markdownTableBody">
<td class="markdownTableBodyCenter">1,000</td>
<td class="markdownTableBodyCenter">0.000509</td>
<td class="markdownTableBodyCenter">0.001194</td>
<td class="markdownTableBodyCenter">0.000147</td>
<td class="markdownTableBodyCenter">0.001850</td>
</tr>
<tr class="markdownTableBody">
<td class="markdownTableBodyCenter">25,000</td>
<td class="markdownTableBodyCenter">0.014749</td>
<td class="markdownTableBodyCenter">0.071152</td>
<td class="markdownTableBodyCenter">0.008191</td>
<td class="markdownTableBodyCenter">0.094092</td>
</tr>
<tr class="markdownTableBody">
<td class="markdownTableBodyCenter">50,000</td>
<td class="markdownTableBodyCenter">0.034255</td>
<td class="markdownTableBodyCenter">0.184237</td>
<td class="markdownTableBodyCenter">0.018166</td>
<td class="markdownTableBodyCenter">0.236658</td>
</tr>
<tr class="markdownTableBody">
<td class="markdownTableBodyCenter">100,000</td>
<td class="markdownTableBodyCenter">0.065117</td>
<td class="markdownTableBodyCenter">0.543177</td>
<td class="markdownTableBodyCenter">0.044088</td>
<td class="markdownTableBodyCenter">0.652382</td>
</tr>
<tr class="markdownTableBody">
<td class="markdownTableBodyCenter">500,000</td>
<td class="markdownTableBodyCenter">0.576530</td>
<td class="markdownTableBodyCenter">7.697143</td>
<td class="markdownTableBodyCenter">0.310765</td>
<td class="markdownTableBodyCenter">8.584438</td>
</tr>
<tr class="markdownTableBody">
<td class="markdownTableBodyCenter">1,000,000</td>
<td class="markdownTableBodyCenter">1.295163</td>
<td class="markdownTableBodyCenter">26.76945</td>
<td class="markdownTableBodyCenter">0.737372</td>
<td class="markdownTableBodyCenter">28.80199</td>
</tr>
</table>

The same results can be seen in the figure.

\cgalFigureBegin{hm_4_bench, hm_4_bench.svg}
Time in seconds to setup (red), factorize (green), and solve (blue) for harmonic
coordinate values with respect to a unit square.
\cgalFigureEnd

The second table shows how the time to compute the coordinates for 100k queries depends on the number of
the polygon vertices. We show separately the time to setup the matrix, factorize it, and solve it
with respect to the \f$n\f$ vertices of the polygon. It can be seen that, unlike in the
first table, the time to factorize the matrix here stays constant.

<table class="markdownTable" align="center">
<tr class="markdownTableHead">
<th class="markdownTableHeadCenter">Number of vertices (approx.)</th>
<th class="markdownTableHeadCenter">Setup (in seconds)</th>
<th class="markdownTableHeadCenter">Factorize (in seconds)</th>
<th class="markdownTableHeadCenter">Solve (in seconds)</th>
<th class="markdownTableHeadCenter">Total (in seconds)</th>
</tr>
<tr class="markdownTableBody">
<td class="markdownTableBodyCenter">5</td>
<td class="markdownTableBodyCenter">0.083444</td>
<td class="markdownTableBodyCenter">0.631823</td>
<td class="markdownTableBodyCenter">0.059827</td>
<td class="markdownTableBodyCenter">0.775094</td>
</tr>
<tr class="markdownTableBody">
<td class="markdownTableBodyCenter">10</td>
<td class="markdownTableBodyCenter">0.060294</td>
<td class="markdownTableBodyCenter">0.450534</td>
<td class="markdownTableBodyCenter">0.094583</td>
<td class="markdownTableBodyCenter">0.605411</td>
</tr>
<tr class="markdownTableBody">
<td class="markdownTableBodyCenter">25</td>
<td class="markdownTableBodyCenter">0.062760</td>
<td class="markdownTableBodyCenter">0.478683</td>
<td class="markdownTableBodyCenter">0.254953</td>
<td class="markdownTableBodyCenter">0.796396</td>
</tr>
<tr class="markdownTableBody">
<td class="markdownTableBodyCenter">50</td>
<td class="markdownTableBodyCenter">0.097359</td>
<td class="markdownTableBodyCenter">0.492233</td>
<td class="markdownTableBodyCenter">0.539654</td>
<td class="markdownTableBodyCenter">1.129246</td>
</tr>
<tr class="markdownTableBody">
<td class="markdownTableBodyCenter">100</td>
<td class="markdownTableBodyCenter">0.129487</td>
<td class="markdownTableBodyCenter">0.450771</td>
<td class="markdownTableBodyCenter">1.152544</td>
<td class="markdownTableBodyCenter">1.732802</td>
</tr>
<tr class="markdownTableBody">
<td class="markdownTableBodyCenter">500</td>
<td class="markdownTableBodyCenter">0.430694</td>
<td class="markdownTableBodyCenter">0.460321</td>
<td class="markdownTableBodyCenter">6.620061</td>
<td class="markdownTableBodyCenter">7.511076</td>
</tr>
<tr class="markdownTableBody">
<td class="markdownTableBodyCenter">1000</td>
<td class="markdownTableBodyCenter">0.812362</td>
<td class="markdownTableBodyCenter">0.480052</td>
<td class="markdownTableBodyCenter">16.14239</td>
<td class="markdownTableBodyCenter">17.43480</td>
</tr>
</table>

The same results can be seen in the figure.

\cgalFigureBegin{hm_n_bench, hm_n_bench.svg}
Time in seconds to setup (red), factorize (green), and solve (blue) for harmonic
coordinate values with respect to a polygon with \f$n\f$ vertices at 100k query points.
\cgalFigureEnd

While, in the first table, the most significant step is to factorize the matrix, in the
second table, the slowest step is to solve for coordinates, as expected.


\section gbc_history History

The package was first released in 2015 and included segment, triangle, Wachspress,
discrete harmonic, and mean value coordinates. The API of that version is now deprecated
but can still be used. An example of the old API can be found \ref depr_example "here".
The docs of that API are also preserved and maintained \ref PkgBarycentricCoordinates2RefDeprecated "here".

In 2018, this package was modified and improved by Keyu Chen and Dmitry Anisimov
during the Google Summer of Code. The API was changed to the current version. In 2020, the new version
was cleaned up and documented that includes:
- the classes `Segment_coordinates_2` and `Triangle_coordinates_2` have been removed, only the free
functions are preserved;
- the entry class `Generalized_barycentric_coordinates_2` was removed since it is not
flexible enough to accommodate all types of 2D barycentric coordinates;
- the classes `Wachspress_2`, `Discrete harmonic_2`, and `Mean_value_2` have been renamed
and modified so that they can be used now on their own without the class `Generalized_barycentric_coordinates_2`;
- harmonic coordinates have been added;
- the free functions for segment and triangle coordinates have been modified and improved;
- the free functions for Wachspress, discrete harmonic, and mean value weights and coordinates have been added;
- the free functions to compute barycentric coordinates for points on the polygon boundary have been added;
- all functions and classes are now using ranges and property maps;
- examples, tests, and benchmarks are modified/extended/improved;
- the docs are refactored and simplified.


\section gbc_acknowledgments Acknowledgments

The authors wish to thank <a href="https://cs.nyu.edu/~teseo/">Teseo Schneider</a>
and Randolf Schaerfig for helpful comments and discussions. We also appreciate the
great effort invested in this package by our reviewers Andreas Fabri, Sébastien Loriot,
and Efi Fogel.
*/

} /* namespace Barycentric_coordinates */
} /* namespace CGAL */

---

### Barycentric Coordinates 2 Doc Barycentric Coordinates 2 PackageDescription (`Barycentric_coordinates_2/doc/Barycentric_coordinates_2/PackageDescription.txt`)

/*!
\defgroup PkgBarycentricCoordinates2Ref Reference Manual

\defgroup PkgBarycentricCoordinates2RefConcepts Concepts
\ingroup PkgBarycentricCoordinates2Ref

Generalized barycentric concepts.

\defgroup PkgBarycentricCoordinates2RefAnalytic Analytic Coordinates
\ingroup PkgBarycentricCoordinates2Ref

Analytic coordinates and related classes.

\defgroup PkgBarycentricCoordinates2RefHarmonic Harmonic Coordinates
\ingroup PkgBarycentricCoordinates2Ref

Harmonic coordinates and related classes.

\defgroup PkgBarycentricCoordinates2RefFunctions Free Functions
\ingroup PkgBarycentricCoordinates2Ref

Free functions to compute barycentric weights and coordinates.

\defgroup PkgBarycentricCoordinates2RefDeprecated Deprecated
\ingroup PkgBarycentricCoordinates2Ref

Deprecated classes and functions.

\addtogroup PkgBarycentricCoordinates2Ref

\cgalPkgDescriptionBegin{2D Generalized Barycentric Coordinates, PkgBarycentricCoordinates2}
\cgalPkgPicture{barcoord_thumb.png}

\cgalPkgSummaryBegin
\cgalPkgAuthors{Dmitry Anisimov, David Bommes, Kai Hormann, and Pierre Alliez}
\cgalPkgDesc{This package offers an efficient and robust implementation of 2D generalized barycentric
coordinates defined for simple polygons in the plane. If coordinates with respect to multivariate
scattered points instead of a polygon are required, please refer to natural neighbor
coordinates from the Package \ref PkgInterpolation2.}
\cgalPkgManuals{Chapter_2D_Generalized_Barycentric_Coordinates, PkgBarycentricCoordinates2Ref}
\cgalPkgSummaryEnd

\cgalPkgShortInfoBegin
\cgalPkgSince{4.6}
\cgalPkgBib{cgal:abha-gbc}
\cgalPkgLicense{\ref licensesGPL "GPL"}
\cgalPkgShortInfoEnd
\cgalPkgDescriptionEnd

\cgalClassifedRefPages

## Concepts ##
- `BarycentricTraits_2`
- `DiscretizedDomain_2`
- `BarycentricCoordinates_2`

## Analytic Coordinates ##
- `CGAL::Barycentric_coordinates::Wachspress_coordinates_2<VertexRange, GeomTraits, PointMap>`
- `CGAL::Barycentric_coordinates::Mean_value_coordinates_2<VertexRange, GeomTraits, PointMap>`
- `CGAL::Barycentric_coordinates::Discrete_harmonic_coordinates_2<VertexRange, GeomTraits, PointMap>`

## Harmonic Coordinates ##
- `CGAL::Barycentric_coordinates::Delaunay_domain_2<VertexRange, GeomTraits, PointMap>`
- `CGAL::Barycentric_coordinates::Harmonic_coordinates_2<VertexRange, DiscretizedDomain, GeomTraits, PointMap>`

## Free Functions ##
- `CGAL::Barycentric_coordinates::segment_coordinates_2()`
- `CGAL::Barycentric_coordinates::triangle_coordinates_2()`
- `CGAL::Barycentric_coordinates::wachspress_weights_2()`
- `CGAL::Barycentric_coordinates::wachspress_coordinates_2()`
- `CGAL::Barycentric_coordinates::mean_value_weights_2()`
- `CGAL::Barycentric_coordinates::mean_value_coordinates_2()`
- `CGAL::Barycentric_coordinates::discrete_harmonic_weights_2()`
- `CGAL::Barycentric_coordinates::discrete_harmonic_coordinates_2()`
- `CGAL::Barycentric_coordinates::boundary_coordinates_2()`
*/

---

### Barycentric Coordinates 2 Doc Barycentric Coordinates 2 Examples (`Barycentric_coordinates_2/doc/Barycentric_coordinates_2/examples.txt`)

/*!
\example Barycentric_coordinates_2/segment_coordinates.cpp
\example Barycentric_coordinates_2/triangle_coordinates.cpp
\example Barycentric_coordinates_2/wachspress_coordinates.cpp
\example Barycentric_coordinates_2/discrete_harmonic_coordinates.cpp
\example Barycentric_coordinates_2/mean_value_coordinates.cpp
\example Barycentric_coordinates_2/harmonic_coordinates.cpp
\example Barycentric_coordinates_2/terrain_height_modeling.cpp
\example Barycentric_coordinates_2/shape_deformation.cpp
\example Barycentric_coordinates_2/affine_coordinates.cpp
\example Barycentric_coordinates_2/deprecated_coordinates.cpp
*/

---

### Barycentric Coordinates 3 Doc Barycentric Coordinates 3 Barycentric Coordinates 3 (`Barycentric_coordinates_3/doc/Barycentric_coordinates_3/Barycentric_coordinates_3.txt`)

namespace CGAL {
namespace Barycentric_coordinates {

/*!
\mainpage User Manual
\anchor Chapter_3D_Generalized_Barycentric_Coordinates
\cgalAutoToc

\authors Antonio Gomes, Dmitry Anisimov


\section gbc_3_introduction Introduction

Barycentric coordinates are an important tool in computer graphics and geometric modeling.
Originally, these coordinates were used to represent a given point with respect to a simplex but have been later
generalized to more complex shapes.

The package 3D Generalized Barycentric Coordinates offers an efficient and robust implementation
of three-dimensional closed-form, generalized barycentric coordinates defined for convex simplicial polytopes.

In particular, this package includes an implementation of Wachspress, discrete harmonic, mean value, and
one extra function to calculate barycentric coordinates with respect to tetrahedra. In this implementation,
we restrict our polyhedra to convex ones with triangular faces, although some of the coordinates may
accept non-convex polyhedra. The calculated coordinates are not normalized.


\section gbc_3_interface Software Design

Wachspress, discrete harmonic, and mean value coordinates are all generalized barycentric coordinates
that can be computed analytically.
Each of the three analytic coordinates can be computed either by a free function or a function object (Functor).
Tetrahedron coordinates can be computed only through the free function.

Similarly to `Barycentric_coordinates::Computation_policy_2` in the 2D package, we can specify a computation
policy Barycentric_coordinates::Computation_policy_3, which can be FAST or
FAST_WITH_EDGE_CASES for each of the three analytical coordinates. The difference between them is that FAST_WITH_EDGE_CASES
treats points near the boundaries by projecting them onto the face of the polyhedron and then calculating triangle coordinates.
Note that, unlike the 2D package, no implementation of a PRECISE algorithm is yet available.

The output of each method are the coordinates for a point with respect to each vertex of the mesh. The number of coordinates being the same as the number of vertices, and the ordering is also the same.

All class and function templates are parameterized by a traits class, which is a model of the concept
BarycentricTraits_3. It provides all necessary geometric primitives, predicates, and constructions,
which are required for the computation. All models of Kernel can be used. A polyhedron is provided as
a model of the concept FaceListGraph with a property map that maps a vertex from the polyhedron to BarycentricTraits_3::Point_3.


\section gbc_3_examples Examples

To facilitate the process of learning this package, we provide various examples
with basic usage of different barycentric components.


\subsection tetra_example Tetrahedron Coordinates

In this example, we use the global function `tetrahedron_coordinates()`.
We compute coordinates for the tetrahedron defined by the points (0,0,0), (1,0,0),
(0,1,0), and (0,0,1). We use points inside, outside and
at the boundary of the tetrahedron.

\cgalExample{Barycentric_coordinates_3/tetrahedron_coordinates_3.cpp}

\subsection wp_3_example Wachspress Coordinates

In this example, we generate 250 random points inside a unit sphere,
centered at the origin. Then we take the convex hull of this set of points
and use this as our polyhedron. Finally, we calculate Wachspress coordinates
for each of these 250 points.

\cgalExample{Barycentric_coordinates_3/wachspress_coordinates_3.cpp}

\subsection dh_3_example Discrete Harmonic Coordinates

This example is very similar to the one used with tetrahedron coordinates.
We start with a regular icosahedron and for points inside, outside and
on the boundary, we calculate discrete harmonic coordinates. In this example,
we use the fast with edge cases algorithm because it properly handles points very close
to the boundaries.

\cgalExample{Barycentric_coordinates_3/discrete_harmonic_coordinates_3.cpp}

\subsection mv_3_example Mean Value Coordinates

This example shows how to compute mean value coordinates for a set of points in a
star-shaped polyhedron. We note that this type of coordinate is well-defined for a
concave polyhedron but it may yield negative coordinate values for points outside
the polyhedron's kernel (shown in blue).

\cgalFigureBegin{mv_3_example, mv_coords_example_3.png}
The star-shaped polyhedron used in mean_value_coordinates_3.cpp and the six query points, for which the mean value barycentric coordinates are computed.
\cgalFigureEnd

\cgalExample{Barycentric_coordinates_3/mean_value_coordinates_3.cpp}

\subsection shape_deform_example_3 Shape Deformation

This example shows how to deform a simple smooth sphere into
another topologically equivalent shape. To achieve this, we create a box that encloses the
sphere; then we calculate the barycentric
coordinates of each vertex with respect to the box. After deforming
the box, we use the barycentric coordinates to relocate the vertices of the sphere.

\cgalFigureBegin{shape_deform_example_3, shape_deform_example_3.png}
The shape on the left is deformed into the shape on the right.
\cgalFigureEnd

\cgalExample{Barycentric_coordinates_3/shape_deformation_3.cpp}

\section gbc_3_degeneracies Edge Cases

The precision of each coordinate depends on the used `Kernel`. If an inexact kernel
is used and the user is not sure whether the points are located near the boundaries, `FAST_WITH_EDGE_CASES`
algorithm should be used.
Implementation details are described in \cgalCite{cgal:bc:f-wmvc-14} for Wachspress and mean value
coordinates, and in \cgalCite{cgal:bc:jlw-ggcccsp-07} for discrete harmonic coordinates.

For each coordinate, it is necessary to make divisions by the signed distance between the query
point and each face. So, if one of these distances is zero or close to zero (query point on the boundary),
it will cause a division by zero error or numerical instability, respectively.
To this end we introduce the FAST_WITH_EDGE_CASES algorithm. Its main purpose is to extend the region where the analytical
coordinates are well-defined. It adds the guarantee to calculate points near the boundaries. The
way it works is simple: before calculating any coordinate, the algorithm checks, for each face,
if the distance between the query point and the supporting plane of the face is less than a predetermined tolerance. If so,
instead of calculating the analytical form of the coordinates, it decomposes the query point with
respect to this particular face and then calculates triangle coordinates. However, for Wachspress
coordinates, the 2D version is used because the faces are not necessarily triangular. Note that for
every vertex that does not belong to this face, the coordinate value will be zero.

\subsection gbc_3_degeneracies_tetrahedron Tetrahedron Coordinates

We adopt the simple formula below to compute tetrahedron coordinates of the query point `q`:
<center>
\f$w_i = \frac{V_i}{V}\f$
</center>

where \f$V_i\f$ is the signed volume of the sub-tetrahedron opposite to the vertex \f$i\f$, i.e., the tetrahedron where the vertex \f$i\f$ is replaced by the query point `q`. \f$V\f$
is the total volume of the tetrahedron, that is \f$V = V_0 + V_1 + V_2 + V_3\f$.

These coordinates can be computed exactly if an exact number type is chosen, for any query point and with respect to any non-degenerate tetrahedron. No special cases are handled.
The computation always yields the correct result. The notion of correctness depends on the precision
of the used number type. Note that for exterior points some coordinate values will be negative.

\subsection gbc_3_degeneracies_wachspress Wachspress Coordinates

For each vertex \f$v\f$, let \f$f_0, f_1, ..., f_{k-1}\f$ be the \f$k\f$ faces incident to \f$v\f$. We
are assuming that the faces are taken in counterclockwise order.

We can define \f${p_f}({q}) = \frac{{n_f}}{h_f({q})}\f$,
and \f$h_f({q}) = ({v} - {q})\cdot {n_f}\f$ as the perpendicular distance of \f$q\f$ to \f$f\f$.
For the face \f$f\f$, let \f${n_f}\f$ denote its unit outward normal.

The following formula is adopted to compute Wachspress coordinates of the query point `q`:
<center>
\f$w_v({q}) = \sum_{i=1}^{k-2}det({p_{f_0}}({q}), {p_{f_i}}({q}), {p_{f_{i+1}}}({q}))\f$
</center>

In this implementation, Wachspress coordinates are well defined in the closure of any convex
polyhedra. If an exact number type is chosen, they are computed in an exact manner.

\subsection gbc_3_degeneracies_discrete_harmonic Discrete Harmonic Coordinates

We adopt the formula below to compute discrete harmonic coordinates of the query point `q`:
<center>
\f$w_i = \sum_{T : v_i \in T} \frac{cot[\theta_i^T]h_i^T}{2}\f$
</center>

where, within a triangle face \f$T = \{v0, v1, v2\}\f$, \f$\theta_i^T\f$ is the dihedral angle between \f$T\f$ and
triangle \f$\{x,v_{i+1}\f$, \f$v_{i−1}\}\f$, and \f$h_i^T\f$ is the edge length \f$|v_{i+1} − v_{i−1}|\f$.

Discrete harmonic coordinates cannot be computed exactly due to a square root operation.
Although, if an exact number type is used, the default precision of the computation depends only on
two %CGAL functions: CGAL::to_double() and CGAL::sqrt(). In this implementation, discrete harmonic
coordinates are well defined in the closure of any convex polyhedra with triangular faces. Unlike
Wachspress coordinates, they are not necessarily positive.

\subsection gbc_3_degeneracies_mean_value Mean Value Coordinates

The following formula is adopted to compute mean value coordinates of the query point `q`:
<center>
\f$w_i = \frac{1}{2}\sum_{j=0}^2 \beta_j\frac{{m_j}\cdot {m_{i+1}}}{{e_i}\cdot {m_{i+1}}}\f$
</center>

where a vertex v is projected onto the point (unit vector) \f$e_v = \frac{({v} - {q})}{|{v - q}|}\f$, and
\f${m_i} = \frac{{e_i} \times {e_{i+1}}}{|{e_i} \times {e_{i+1}}|}\f$. \f$\beta_j \in (0, \pi)\f$ is the angle
between \f$e_i\f$ and \f$e_{i+1}\f$.

Like discrete harmonic, mean value coordinates cannot be exactly computed due to a square root
operation. In this implementation, mean value coordinates are well defined everywhere in the space,
but just for polyhedra with triangular faces. Also, they are non-negative in the kernel of a
star-shaped polyhedron.

\section gbc_3_performance Performance

Efficiency is crucial in this implementation.
These coordinates are used in applications that require
calculations for millions of points; thus, developing metrics
to evaluate performance is necessary. In this section,
we present benchmark results for each algorithm.

The benchmark and runtimes are evaluated by regularly sampling
\f$n^3\f$ (\f$n\f$ varying from 1 to 100) points from the interior
of the unit cube, and calculating their coordinate values (see figure below).

The results are averaged over 10 executions and represented in a log-log
scale plot.

\cgalFigureBegin{bc_coords_bench_structure_3, bc_coords_bench_structure_3.png}
The points shown in red are the sample points used to make the benchmark.
\cgalFigureEnd

The performance strongly depends on the chosen kernel,
for this test, we choose to use `Simple_cartesian<double>` because is much faster than others.
Also, we can see that time (WP) << time (DH) < time (MV). This happens because the Wachspress
implementation has fewer instructions per loop than the other two. For 100k points those generalized barycentric coordinates are calculated within a convex hull with 500 vertices the timings are 17.5s (WP), 25.4s (DH) and 33.3s (MV).

\cgalFigureBegin{bc_coords_bench_3, bc_coords_bench_3.png}
Time in seconds to compute \f$n^3\f$ coordinate values for a cube.
Wachspress (blue), discrete harmonic (orange), and mean value (green).
\cgalFigureEnd

Tetrahedron coordinates are not shown in the same plot because the test is
slightly different. For this one, we simply show in the table below
the results for some pre-defined quantity of points. The test is done by regularly
sampling strictly interior points with respect to a tetrahedron with
unit sides that lie on the coordinate axis.

<table class="markdownTable" align="center">
<tr class="markdownTableHead">
<th class="markdownTableHeadCenter">Number of points </th>
<th class="markdownTableHeadCenter">Total time (in seconds)</th>
</tr>
<tr class="markdownTableBody">
<td class="markdownTableBodyCenter">50000</td>
<td class="markdownTableBodyCenter">0.09</td>
</tr>
<tr class="markdownTableBody">
<td class="markdownTableBodyCenter">100000</td>
<td class="markdownTableBodyCenter">0.19</td>
</tr>
<tr class="markdownTableBody">
<td class="markdownTableBodyCenter">500000</td>
<td class="markdownTableBodyCenter">0.82</td>
</tr>
<tr class="markdownTableBody">
<td class="markdownTableBodyCenter">1000000</td>
<td class="markdownTableBodyCenter">1.67</td>
</tr>
<tr class="markdownTableBody">
<td class="markdownTableBodyCenter">5000000</td>
<td class="markdownTableBodyCenter">8.36</td>
</tr>
</table>

To benchmark each coordinate, we used a 2.5 GHz Intel Core i7 processor (8 cores)
and 32 GB DDR4 2933MHz memory. The installed operating system was Windows 11.

\section gbc_3_history History

This package was introduced during GSoC 2021 and implemented by Antonio Gomes
under the supervision of Dmitry Anisimov. Sven Oesau finished the final work on API and documentation.

*/

} /* namespace Barycentric_coordinates */
} /* namespace CGAL */

---

### Barycentric Coordinates 3 Doc Barycentric Coordinates 3 PackageDescription (`Barycentric_coordinates_3/doc/Barycentric_coordinates_3/PackageDescription.txt`)

/*!
\defgroup PkgBarycentricCoordinates3Ref 3D Generalized Barycentric Coordinates Reference

\defgroup PkgBarycentricCoordinates3RefConcepts Concepts
\ingroup PkgBarycentricCoordinates3Ref

Generalized barycentric concepts.

\defgroup PkgBarycentricCoordinates3RefAnalytic Analytic Coordinates
\ingroup PkgBarycentricCoordinates3Ref

Analytic coordinates and related classes.

\defgroup PkgBarycentricCoordinates3RefFunctions Free Functions
\ingroup PkgBarycentricCoordinates3Ref

Free functions to compute barycentric coordinates.

\addtogroup PkgBarycentricCoordinates3Ref

\cgalPkgDescriptionBegin{3D Generalized Barycentric Coordinates, PkgBarycentricCoordinates3}
\cgalPkgPicture{barcoord_thumb_3.png}

\cgalPkgSummaryBegin
\cgalPkgAuthors{Antonio Gomes, Dmitry Anisimov}
\cgalPkgDesc{The package 3D Generalized Barycentric Coordinates offers an efficient and robust
implementation of three-dimensional closed-form generalized barycentric coordinates
defined for convex simplicial polytopes.}
\cgalPkgManuals{Chapter_3D_Generalized_Barycentric_Coordinates, PkgBarycentricCoordinates3Ref}
\cgalPkgSummaryEnd

\cgalPkgShortInfoBegin
\cgalPkgSince{6.2}
\cgalPkgBib{abha-gbc}
\cgalPkgLicense{\ref licensesGPL "GPL"}
\cgalPkgShortInfoEnd
\cgalPkgDescriptionEnd

\cgalClassifedRefPages

## Concepts ##
- `BarycentricTraits_3`

## Analytic Coordinates ##
- `CGAL::Barycentric_coordinates::Wachspress_coordinates_3<TriangleMesh, VertexPointMap, GeomTraits>`
- `CGAL::Barycentric_coordinates::Mean_value_coordinates_3<TriangleMesh, VertexPointMap, GeomTraits>`
- `CGAL::Barycentric_coordinates::Discrete_harmonic_coordinates_3<TriangleMesh, VertexPointMap, GeomTraits>`

## Free Functions ##
- `CGAL::Barycentric_coordinates::apply_barycentric_coordinates_3()`
- `CGAL::Barycentric_coordinates::tetrahedron_coordinates_3()`
- `CGAL::Barycentric_coordinates::wachspress_coordinates_3()`
- `CGAL::Barycentric_coordinates::mean_value_coordinates_3()`
- `CGAL::Barycentric_coordinates::discrete_harmonic_coordinates_3()`
- `CGAL::Barycentric_coordinates::boundary_coordinates_3()`
*/

---

### Barycentric Coordinates 3 Doc Barycentric Coordinates 3 Examples (`Barycentric_coordinates_3/doc/Barycentric_coordinates_3/examples.txt`)

/*!
\example Barycentric_coordinates_3/tetrahedron_coordinates_3.cpp
\example Barycentric_coordinates_3/wachspress_coordinates_3.cpp
\example Barycentric_coordinates_3/discrete_harmonic_coordinates_3.cpp
\example Barycentric_coordinates_3/mean_value_coordinates_3.cpp
\example Barycentric_coordinates_3/shape_deformation_3.cpp
*/

---

### Basic Viewer Doc Basic Viewer Basic Viewer (`Basic_viewer/doc/Basic_viewer/Basic_viewer.txt`)

namespace CGAL {
/*!

\mainpage User Manual
\anchor Chapter_Basic_viewer
\anchor ChapterBasicViewer

\author Guillaume Damiand and Mostafa Ashraf
\cgalAutoToc


\section BV_Intro Introduction

The basic viewer package provides interactive visualization for most \cgal packages, such as
\ref PkgArrangementOnSurface2Ref "2D Arrangements",
\ref PkgBooleanSetOperations2Ref "2D Boolean Set",
\ref PkgLinearCellComplexRef "Linear cell complex",
\ref PkgNef3Ref "3D Nef",
\ref PkgPeriodic2Triangulation2Ref "2D Periodic Triangulations",
\ref PkgPointSet3Ref "3D Point Set",
\ref PkgPolygon2Ref "2D Polygon",
\ref PkgPolyhedronRef "3D Polyhedral Surface",
\ref PkgStraightSkeleton2Ref "2D Straight Skeleton",
\ref PkgSurface_mesh "Surface Mesh",
\ref PkgTriangulation2Ref "2D Triangulation",
\ref PkgTriangulation3Ref "3D Triangulation",
\ref PkgVoronoiDiagram2Ref "2D Voronoi Diagram",
and more.

The most simple use case of the basic viewer is the call of the global `draw()` function. There is one draw function for each \cgal package. Such a call opens a new interactive window showing the given model and allowing to navigate in the scene, show or hide some specific cells, show the interior of the model if any, etc.

The drawing can be tuned using `Graphics_scene_options`, for example to change the color of some cells or hide some cells.

More complex usage can be achieved by using the `Graphics_scene` class. Different \cgal data structures can be added in a same `Graphics_scene` allowing to visualize them simultaneously in a same window. Like for the draw function, the drawing parameters can be tuned thanks to the `Graphics_scene_options`.

Two classes are based on \qt.
  - `CGAL::Qt::Basic_viewer` is a \qt widget that inherits from `QGLViewer` (libQGLViewer is an open source C++ library based on \qt that eases the creation of OpenGL 3D viewers).
  - `CGAL::Qt::QApplication_and_basic_viewer` which regroups a `Qt::QApplication` and a `CGAL::Qt::Basic_viewer`.


\section BV_SoftwareDesign Software Design

The diagram in \cgalFigureRef{fig_basic_viewer_diagram_class} shows the main classes and functions of this package.

\cgalFigureBegin{fig_basic_viewer_diagram_class,basic_viewer_diagramme_class.svg}
UML diagram of the classes and functions of the package (only partial representation).
\cgalFigureEnd


\section BV_BasicUsage Basic Usage: The Global Draw Functions

A first simple solution provided to draw the different data structures of \cgal is the global `draw()` function. This function is templated by the type of the data structure to draw. The following example shows how it can be used.

\cgalExample{Basic_viewer/draw_lcc.cpp}

This example creates a 3D linear cell complex of a hexahedron, and draws it. The result is shown in the following figure.

\cgalFigureBegin{basic_viewer_ex1,lcc_draw.png}
Example of drawing of a 3D LCC.
\cgalFigureEnd

Users can interact with the viewer using some specific keys or mouse interactions. Pressing key 'h'  makes pop up a help window showing the different shortcuts and mouse interactions. The main functionalities of the viewer are:

<ul>
<li> Versatile Rendering:

The viewer supports the rendering of various geometric elements, such as points, edges, faces, rays, and lines.
Different rendering modes, including mono and colored representation, are available for these elements.</li>

<li> Camera Control:

The viewer allows users to move the camera, switch between 2D and 3D viewing modes, adjusting the camera accordingly.
Camera settings, such as orthographic or perspective projection, can be configured based on the dimension of the scene.</li>

<li> User Interaction:

Users can interact with the viewer through keyboard inputs, enabling them to control rendering options, toggle the display of elements, and adjust visual parameters.
Key presses are mapped to specific actions, such as toggling the clipping plane, changing rendering modes, adjusting the size of elements, and modifying ambient light color.</li>

<li> Clipping Plane:

The viewer includes support for a clipping plane, enabling users to selectively render parts of the scene.
The clipping plane can be toggled on and off, and its rendering style can be modified (solid, wireframe, etc.).</li>
</ul>

\subsection BV_GraphicSceneOptions Tuning with Graphics Scene Options

There is one specialization of each draw function that takes  graphics scene options as additional parameter, allowing to tune the drawing.

The `Graphics_scene_options` class provides a set of options and customization parameters for rendering geometric structures in a graphics scene. Its main purpose is to allow users to control the visual appearance of various cells such as vertices, edges, faces, and volumes in a graphical representation of a given data structure.

The following example shows how to use graphics scene options to tune the drawing of a surface mesh. We define our own class `My_graphics_scene_options` that inherits from `Graphics_scene_options` to get all the default parameters. In this class, we only override the two methods `colored_vertex` and `vertex_color` to draw all vertices in color, and chose randomly green or blue colors for one out of two vertices.

\cgalExample{Basic_viewer/draw_surface_mesh_vcolor.cpp}

The result of this example can be shown in \cgalFigureRef{basic_viewer_ex2}.

\cgalFigureBegin{basic_viewer_ex2,draw_surface_mesh_vcolor.png}
Example of tuned drawing of a 3D surface mesh where some vertex colors are changed.
\cgalFigureEnd

The drawing options can depend on the cells. In the following example the color of each face depends on its height.

\cgalExample{Basic_viewer/draw_surface_mesh_height.cpp}

The result of this example is shown in \cgalFigureRef{basic_viewer_ex3}.

\cgalFigureBegin{basic_viewer_ex3,draw_surface_height.png}
Example of mesh drawing with a color for each face computed depending on its height.
\cgalFigureEnd


\section BV_GraphicsScene The Graphics Scene

It is possible to do more advanced visualizations by using the class `Graphics_scene`. It is a container class for various geometric elements, such as points, segments, rays, lines, faces and texts. It provides several methods to add elements, possibly with individual colors. Things are a little bit different for faces. You must call `face_begin()` to start a new face (possibly with a color), add all the points in the face by using `add_point_in_face()`, and call `face_end()` to finish the face. Note that the given polygonal face is internally triangulated.

This class also stores the normal of the faces (computed automatically), and possibly the normal of the vertices that can be provided by the users.

Users can either fill directly a `Graphics_scene` using these methods, or by using a global function `add_to_graphics_scene()` that fills the scene using all the geometric elements of a given \cgal data structure. Like for the draw functions, there is an overload of `add_to_graphics_scene()` for each \cgal package.

A `Graphics_scene` can be drawn using the basic viewer thanks to the `draw_graphics_scene()` function.

The following example shows in a same viewer both a `Point_set_3` and a `Polyhedron_3`. Note that, like the draw functions, each `add_to_graphics_scene()` can use an optional `Graphics_scene_options` as parameter allowing to tune the drawing of the given data structure. In the example, we change the color of all vertices of the point set.

\cgalExample{Basic_viewer/draw_mesh_and_points.cpp}

The result of this example is shown in \cgalFigureRef{basic_viewer_ex4} where we can see in green the original points of the point cloud, superposed with the polyhedron surface reconstructed by the Poisson surface reconstruction method.

\cgalFigureBegin{basic_viewer_ex4,draw_mesh_and_points.png}
Example of drawing of a point cloud and a polyhedron in a same viewer.
\cgalFigureEnd


\section BV_BasicViewer The Qt Basic Viewer Class

The class `CGAL::Qt::Basic_viewer` is a \qt widget that inherits from `QGLViewer` and mainly stores a `Graphics_scene` and allows to visualize it and interact with the scene. Since this class is a \qt widget, it can be used into more complex \qt code to create more advanced demos.

In the following example, we create two graphics scenes, one filled with a point cloud, a second one filled with the polyhedral surface reconstructed by the Poisson surface reconstruction method. Then, we create two basic viewers associated with these two scenes. The two basic viewers are added into a \qt layout allowing to visualize the two scenes side by side.

\cgalExample{Basic_viewer/draw_several_windows.cpp}

The result of this example is shown in \cgalFigureRef{basic_viewer_ex5}.

\cgalFigureBegin{basic_viewer_ex5,draw_several_windows.png}
Example of drawing of two `Basic_viewer` side by side.
\cgalFigureEnd



\section BV_Interactions Adding Interaction

In the previous examples, the models are only drawn once and there is no interaction with the user to update the drawing.

It is possible to define such interactions thanks to the class `CGAL::Qt::QApplication_and_basic_viewer`. In this class, you can define your own function that is called automatically by the viewer when a user presses a key. This can be used to change some parameters and update the drawing accordingly.

We illustrate this possibility in the following example that shows a surface mesh, while coloring the small faces in red. To do so, we use our own graphics scene options than change the color of a face depending on its size. A face is considered small if its size is below a certain threshold. This threshold can be updated by the user, pressing key 'I' to increase it and 'D' to decrease it. This is done in the key pressed function defined in the `QApplication_and_basic_viewer`. When the threshold changes, the graphics scene is recomputed to take the modification of the size threshold into account.

\cgalExample{Basic_viewer/draw_surface_mesh_small_faces.cpp}

The result of this example is shown in \cgalFigureRef{basic_viewer_ex6}, showing to the left the initial drawing of the 3D model, and to the right the same model after having changed the size threshold.

\cgalFigureBegin{basic_viewer_ex6,draw_surface_mesh_small_faces.png}
Two examples of drawing of a mesh with small faces in red. <B>Left</B>: With the initial threshold. <B>Right</B>: After having increased the threshold.
\cgalFigureEnd


\section BV_Design Design and Implementation History

This package was started by Mostafa Ashraf during his 2022 GSoC project. Guillaume Damiand, who mentored the project, reworked large parts of the package, wrote examples and the manual.

*/

} /* namespace CGAL */

---

### Basic Viewer Doc Basic Viewer PackageDescription (`Basic_viewer/doc/Basic_viewer/PackageDescription.txt`)

/// \defgroup PkgBasicViewerRef Reference Manual

/// \defgroup PkgBasicViewerConcepts Concepts
/// \ingroup PkgBasicViewerRef

/// \defgroup PkgBasicViewerClasses Classes
/// \ingroup PkgBasicViewerRef

/*!
\addtogroup PkgBasicViewerRef
\cgalPkgDescriptionBegin{Basic Viewer,PkgBasicViewer}
\cgalPkgPicture{basic_viewer_logo.png}
\cgalPkgSummaryBegin
\cgalPkgAuthor{Guillaume Damiand and Mostafa Ashraf}
\cgalPkgDesc{This package provides interactive visualization for most \cgal packages.
First, the function `draw()` is provided for each data structure.
Several data structures can be added to a same graphics scene and visualized simultaneously.
Rendering can be controlled (color, point size, etc.).
Finally a \qt widget is provided that can be integrated in the GUI of a user application.}
\cgalPkgManuals{Chapter_Basic_viewer,PkgBasicViewerRef}
\cgalPkgSummaryEnd
\cgalPkgShortInfoBegin
\cgalPkgSince{6.0}
\cgalPkgBib{cgal:d-bv}
\cgalPkgLicense{\ref licensesLGPL "LGPL"}
\cgalPkgShortInfoEnd
\cgalPkgDescriptionEnd

\cgalClassifedRefPages

\cgalCRPSection{Concepts}
- `GraphicsSceneOptions`
- `GraphicsSceneOptionsWithVolumes`

\cgalCRPSection{Classes}
- `CGAL::Qt::Basic_viewer`
- `CGAL::Graphics_scene`
- `CGAL::Graphics_scene_options<DS, VertexDescriptor, EdgeDescriptor, FaceDescriptor, VolumeDescriptor>`
- `CGAL::Qt::QApplication_and_basic_viewer`

\cgalCRPSubsection{Draw a Graphics Scene}

- `CGAL::draw_graphics_scene()`

\cgalCRPSubsection{Draw for Different Packages}

- `CGAL::Arrangement_2` \link PkgArrangementOnSurface2Draw CGAL::draw<ARR>() \endlink
- `CGAL::Constrained_triangulation_2` \link PkgDrawTriangulation2 CGAL::draw<CT2>() \endlink
- `CGAL::Linear_cell_complex_for_combinatorial_map` \link PkgDrawLinearCellComplex CGAL::draw<LCC>() \endlink
- `CGAL::Linear_cell_complex_for_generalized_map` \link PkgDrawLinearCellComplex CGAL::draw<LCC>() \endlink
- `CGAL::Nef_polyhedron_3` \link PkgDrawNef3 CGAL::draw<Nef3>() \endlink
- `CGAL::Periodic_2_triangulation_2` \link PkgDrawPeriodic2Triangulation2 CGAL::draw<P2T2>() \endlink
- `CGAL::Point_set_3` \link PkgDrawPointSet3D CGAL::draw<PS>() \endlink
- `CGAL::Polygon_2` \link PkgDrawPolygon2 CGAL::draw<P2>() \endlink
- `CGAL::Polygon_set_2` \link PkgDrawPolygonSet2 CGAL::draw<PS>() \endlink
- `CGAL::Polygon_with_holes_2` \link PkgDrawPolygonWithHoles2 CGAL::draw<PH2>() \endlink
- `CGAL::Polyhedron_3` \link PkgDrawPolyhedron CGAL::draw<POLY>() \endlink
- `CGAL::Surface_mesh` \link PkgDrawSurfaceMesh CGAL::draw<SM>() \endlink
- `CGAL::Surface_mesh_topology` \link PkgDrawFaceGraphWithPaths CGAL::draw<SMT>() \endlink
- `CGAL::Triangulation_2` \link PkgDrawTriangulation2 CGAL::draw<T2>() \endlink
- `CGAL::Triangulation_3` \link PkgDrawTriangulation3 CGAL::draw<T3>() \endlink
- `CGAL::Voronoi_diagram_2` \link PkgDrawVoronoiDiagram2 CGAL::draw<V2>() \endlink

\cgalCRPSubsection{Fill Graphics Scene for Different Packages}

- `CGAL::Arrangement_2` \link PkgArrangementOnSurface2Draw CGAL::add_to_graphics_scene<ARR>() \endlink
- `CGAL::Constrained_triangulation_2` \link PkgDrawTriangulation2 CGAL::add_to_graphics_scene<CT2>() \endlink
- `CGAL::Linear_cell_complex_for_combinatorial_map` \link PkgDrawLinearCellComplex CGAL::add_to_graphics_scene<LCC>() \endlink
- `CGAL::Linear_cell_complex_for_generalized_map` \link PkgDrawLinearCellComplex CGAL::add_to_graphics_scene<LCC>() \endlink
- `CGAL::Nef_polyhedron_3` \link PkgDrawNef3 CGAL::add_to_graphics_scene<Nef3>() \endlink
- `CGAL::Periodic_2_triangulation_2` \link PkgDrawPeriodic2Triangulation2 CGAL::add_to_graphics_scene<P2T2>() \endlink
- `CGAL::Point_set_3` \link PkgDrawPointSet3D CGAL::add_to_graphics_scene<PS>() \endlink
- `CGAL::Polygon_2` \link PkgDrawPolygon2 CGAL::add_to_graphics_scene<P2>() \endlink
- `CGAL::Polygon_set_2` \link PkgDrawPolygonSet2 CGAL::add_to_graphics_scene<PS>() \endlink
- `CGAL::Polygon_with_holes_2` \link PkgDrawPolygonWithHoles2 CGAL::add_to_graphics_scene<PH2>() \endlink
- `CGAL::Polyhedron_3` \link PkgDrawPolyhedron CGAL::add_to_graphics_scene<POLY>() \endlink
- `CGAL::Surface_mesh` \link PkgDrawSurfaceMesh CGAL::add_to_graphics_scene<SM>() \endlink
- `CGAL::Surface_mesh_topology` \link PkgDrawFaceGraphWithPaths CGAL::add_to_graphics_scene<SMT>() \endlink
- `CGAL::Triangulation_2` \link PkgDrawTriangulation2 CGAL::add_to_graphics_scene<T2>() \endlink
- `CGAL::Triangulation_3` \link PkgDrawTriangulation3 CGAL::add_to_graphics_scene<T3>() \endlink
- `CGAL::Voronoi_diagram_2` \link PkgDrawVoronoiDiagram2 CGAL::add_to_graphics_scene<V2>() \endlink

*/

---

### Basic Viewer Doc Basic Viewer Examples (`Basic_viewer/doc/Basic_viewer/examples.txt`)

/*!
\example Basic_viewer/draw_lcc.cpp
\example Basic_viewer/draw_mesh_and_points.cpp
\example Basic_viewer/draw_several_windows.cpp
\example Basic_viewer/draw_surface_mesh_small_faces.cpp
\example Basic_viewer/draw_surface_mesh_height.cpp
\example Basic_viewer/draw_surface_mesh_vcolor.cpp
*/

---

### Boolean Set Operations 2 Doc Boolean Set Operations 2 Boolean Set Operations 2 (`Boolean_set_operations_2/doc/Boolean_set_operations_2/Boolean_set_operations_2.txt`)

namespace CGAL {
/*!

\mainpage User Manual
\anchor Chapter_2D_Regularized_Boolean_Set-Operations

\anchor chapter_Boolean_set_operations_2

\cgalAutoToc
\authors Efi Fogel, Ophir Setter, Ron Wein, Guy Zucker, Baruch Zukerman, and Dan Halperin

\section bso_secintro Introduction

\cgalFigureBegin{figteaser,teaser.png}
Examples of Boolean set-operations on general polygons.
\cgalFigureEnd

This package consists of the implementation of Boolean set-operations
on point sets bounded by weakly \f$ x\f$-monotone curves\cgalFootnote{A continuous planar curve \f$ C\f$ is <I>weakly \f$ x\f$-monotone</I> if every vertical line intersects it at most once, or if it is vertical. Hereafter we refer to weakly \f$ x\f$-monotone curves as \f$ x\f$-monotone curves.} in 2-dimensional Euclidean space. In particular,
it contains the implementation of <I>regularized</I> Boolean set-operations,
intersection predicates, and point containment predicates.
\cgalFigureRef{figteaser} shows simple examples of such operations.

Ordinary Boolean set-operations, which distinguish between the
interior and the boundary of a polygon, are not implemented within this
package. The Chapter \ref PkgNef2 supports these operations for (linear)
polygons.

In the rest of this chapter we use, unless otherwise stated, the
traditional notation to denote regularized operations; e.g., \f$ P \cap Q\f$
means the <I>regularized</I> intersection of \f$ P\f$ and \f$ Q\f$.

Our package supports the following Boolean set-operations on two point
sets \f$ P\f$ and \f$ Q\f$ that each is the union of one or more general polygons:
<DL>
<DT><B>Intersection</B><DD> computes the intersection \f$ R = P \cap Q\f$.
<DT><B>Join</B><DD> computes the union \f$ R = P \cup Q\f$.
<DT><B>Difference</B><DD> computes the difference \f$ R = P \setminus Q\f$.
<DT><B>Symmetric Difference</B><DD> computes the symmetric
difference \f$ P = P \oplus Q = (P \setminus Q) \cup (Q \setminus P)\f$.
<DT><B>Complement</B><DD> computes the complement \f$R = \overline{P}\f$.
<DT><B>Intersection predicate</B><DD> tests whether the two sets \f$ P\f$ and \f$ Q\f$
overlap, distinguishing three possible scenarios: (i) the two sets
intersect on their interior (that is, their regularized intersection
is not empty \f$ P \cap Q \neq \emptyset\f$); (ii) the boundaries of two
sets intersect but their interiors are disjoint; namely they have a
finite number of common points or even share a boundary curve (still
in this case \f$ P \cap Q = \emptyset\f$; and (iii) the two sets are
disjoint.
</DL>
In general, the set \f$ R\f$, resulting from a regularized Boolean
set-operation, is considered as being a closed point-set; see definition of regularized boolean set operations below.

In the rest of this chapter we review the Boolean set-operations package
in more depth. In Section \ref bso_secbso_lin we focus on Boolean
set-operations on linear polygons, introducing the notion of polygons with
holes and of a general polygon set. Section \ref bso_secbso_gen
introduces general polygons.
We first discuss polygons whose edges are either line segments or circular
arcs and then explain how to construct and use general polygons whose edges
can be arbitrary weakly \f$ x\f$-monotone curves.

\section bso_secbso_def Terms and Definitions

\cgalFigureBegin{simpleDefsExamples,simpleDefsExamples.png}
Examples of polygons. (a) A simple polygon. (b) A relatively simple polygon (c) A polygon that is neither simple nor relatively simple.
\cgalFigureEnd


<UL>

<LI>The counterclockwise cyclic sequence of alternating polygon edges and
polygon vertices is referred to as the polygon <B>(outer) boundary</B>.

<LI>A polygon whose curves are pairwise disjoint in their interior, and whose vertices' degree equals two is defined as a <B>Simple polygon</B>. Such a polygon has a well-defined interior and exterior and is topologically equivalent to a disk. Note that while traversing the edges of the relatively simple polygon illustrated above (B), no curve is crossed over.

<LI>A <B>Relatively simple</B> polygon allows vertices with a degree\f$> 2\f$, but all of its edges are disjoint in their interior. Furthermore, it must be an orientable polygon. Namely when it is inserted into an arrangement and its outer boundary is traversed, the same face is adjacent to all of the halfedges (no crossing over any curve during the traversal).
Note that while polygon C has the same curves as polygon B, traversal of the curves leads to crossing over a previously traversed curve, and is therefore neither simple nor relatively simple.

<LI>A polygon in our context must be relatively simple and its outer boundary vertices must be ordered in a counterclockwise direction around the interior of the polygon.
We extend the notion of a polygon to a <B>point set</B> in \f$ \mathbb{R}^2\f$
that has a topology of a polygon and its boundary edges must map to
\f$ x\f$-monotone curves, and refer to it as a <B>general polygon</B>. We
sometimes use the term <I>polygon</I> instead of general polygon for
simplicity hereafter.

<LI>A <B>polygon with holes</B> represents a point set that may
be bounded or unbounded. In case of a bounded set, its <I>outer
boundary</I> is represented as a <I>relatively simple </I> (but not necessarily simple) polygon, whose vertices are oriented in a <I>counterclockwise </I>
order around the interior of the set. In addition, the set may contain
<I>holes</I>, where each hole is represented as a <I>simple</I>
polygon, whose vertices are oriented in a <I>clockwise</I> order around the
interior of the hole. Note that an unbounded polygon without holes
spans the entire plane. Vertices of holes may coincide with vertices
of the boundary.

<LI>A <B>regularized Boolean set-operation</B> \f$ \mbox{op}^*\f$ can be obtained by
first taking the interior of the resultant point set of an <I>ordinary</I>
Boolean set-operation \f$ (P\ \mbox{op}\ Q)\f$ and then by taking the
closure \cgalCite{cgal:h-sm-04}. That is,
\f$ P\ \mbox{op}^*\ Q = \mbox{closure}(\mbox{interior} (P\ \mbox{op}\ Q))\f$.
Regularized Boolean set-operations appear in Constructive Solid
Geometry (CSG), because regular sets are closed under regularized
Boolean set-operations, and because regularization eliminates lower
dimensional features, namely isolated vertices and antennas, thus
simplifying and restricting the representation to physically meaningful
solids. Our package provides regularized operations on polygons and
general polygons, where the edges of a general polygon may be
general \f$ x\f$-monotone curves, rather than being simple line segments.
</UL>

\subsection bso_ssecpolygon_validation Conditions for Valid Polygons

In our context, a polygon must uphold the following conditions:

<OL>
<LI><I>Closed Boundary</I> - the polygon's outer boundary must be a connected sequence of curves, that start and end at the same vertex.
<LI><I>Simplicity</I> - the polygon must be simple.
<LI><I>Orientation</I> - the polygon's outer boundary must be <I>counterclockwise oriented</I>.
</OL>

\subsection bso_ssecpolygon_with_holes_validation Conditions for Valid Polygons with Holes

In our context, a polygon with holes must uphold the following conditions:

<OL>
<LI><I>Closed Boundary</I> - both the outer boundary and the holes must be closed polygons as defined above.
<LI><I>Simplicity</I> - the outer boundary must be a <I></I><B><I>relatively</I></B><I> simple</I> polygon (as defined above). Every hole must be a <I>simple</I> polygon.
<LI><I>Orientation</I> - The polygon with holes must have an outer boundary with <I>counter clockwise orientation</I>. Every hole's outer boundary should have <I>clockwise orientation</I>.
<LI><I>The holes and the outer boundary must be pairwise disjoint,except maybe on vertices</I>.
<UL>
<LI><I>All holes are contained in the outer boundary</I> - holes must be contained inside the outer boundary and must be disjoint from it (except on vertices).
<LI><I>Pairwise disjoint holes (on interior)</I> - the polygon's holes must be <I>pairwise disjoint</I>, except for intersection on a joint vertex/vertices.

</UL>
</OL>

\section bso_secbso_lin Boolean Set-Operations on Linear Polygons

The basic library of \cgal includes the `Polygon_2<Kernel,Container>`
class-template that represents a linear polygon in the plane. The
polygon is represented by its vertices stored in a container of
objects of type `Kernel::Point_2`. The polygon edges are line
segments (`Kernel::Segment_2` objects) between adjacent points in
the container. By default, the `Container` is a vector of
`Kernel::Point_2` objects.

The following function demonstrates how to use the basic access
functions of the `Polygon_2` class. It accepts a polygon \f$ P\f$ and
prints it in a readable format:
\code{.cpp}
template<class Kernel, class Container>
void print_polygon (const CGAL::Polygon_2<Kernel, Container>& P)
{
  typename CGAL::Polygon_2<Kernel, Container>::Vertex_const_iterator vit;

  std::cout << "[ " << P.size() << " vertices:";
  for (vit = P.vertices_begin(); vit != P.vertices_end(); ++vit)
    std::cout << " (" << *vit << ')';
  std::cout << " ]" << std::endl;
}
\endcode

In this section we use the term <I>polygon</I> to indicate a
`Polygon_2` instance, namely, a polygon having linear
edges. General polygons are only discussed in
Section \ref bso_secbso_gen.

The basic components of our package are the free (global) functions
`complement()` that accepts a single `Polygon_2` object, and
`intersection()`, `join()`,\cgalFootnote{The function that computes the union of two polygons is called \cgalFootnoteCode{join()}, since the word \cgalFootnoteCode{union} is reserved in \cpp.} `difference()`,
`symmetric_difference()` and the predicate `do_intersect()`
that accept two `Polygon_2` objects as their input. We explain how
these functions should be used through several examples in the
following sections.

\subsection Boolean_set_operations_2ASimpleExample A Simple Example

\image html triangles.png
\image latex triangles.png

Testing whether two polygons intersect results with a Boolean value,
and does not require any additional data beyond the provision of the
two input polygons. The example listed below tests whether the two
triangles depicted on the right intersect. It uses, as do the other
example programs in this chapter, the auxiliary header file
`bso_rational_nt.h`, which defines the type `Number_type` as
\gmp's rational number-type (`Gmpq`), or as the
number type `Quotient<MP_Float>` that is included in the support
library of \cgal, based on whether the \gmp library is installed
or not. It also uses the function `print_polygon.h` listed above,
which is located in the header file `print_utils.h`.

\cgalExample{Boolean_set_operations_2/do_intersect.cpp}

\subsection bso_ssecpolygons_with_holes Polygons with Holes

\cgalFigureBegin{figsimple,simple.png}
Operations on simple polygons. (a) The union of two polygons, resulting in a point set whose outer boundary is defined by a simple polygon and contains a polygonal hole in its interior. (b) The intersection (darkly shaded) of two polygons (lightly shaded), resulting in two disjoint polygons. (c) The complement (darkly shaded) of a simple polygon (lightly shaded).
\cgalFigureEnd

In many cases a binary operation that operates on two simple
polygons that have no holes may result in a set of polygons that
contain holes in their interior (see \cgalFigureRef{figsimple} (a)),
or a set of disjoint polygons (see \cgalFigureRef{figsimple} (b); a similar
set may result from the union, or the symmetric difference, of two disjoint
polygons). Moreover, the complement of a simple polygon is an unbounded set
that contains a hole; see \cgalFigureRef{figsimple} (c).

Regular sets are closed under regularized Boolean set-operations.
These operations accept as input, and may result as output, polygons
with holes.
A <I>polygon with holes</I> represents a point set that may
be bounded or unbounded. In case of a bounded set, its <I>outer
boundary</I> is represented as a relatively simple (but not necessarily simple) polygon, whose vertices are oriented in a counterclockwise
order around the interior of the set. In addition, the set may contain
<I>holes</I>, where each hole is represented as a simple
polygon, whose vertices are oriented in a clockwise order around the
interior of the hole. Note that an unbounded polygon without holes
spans the entire plane. Vertices of holes may coincide with vertices
of the boundary; see below for an example.

A point set represented by a polygon with holes is considered to be
closed. Therefore, the boundaries of the holes are parts of the set
(and not part of the holes).
The exact definition of the obtained polygon with holes as a result of
a Boolean set-operation or a sequence of such operations is closely
related to the definition of regularized Boolean set-operations, being
the closure of the interior of the corresponding ordinary operation as
explained next.

\image html unique.png
\image latex unique.png

Consider, for example, the regular set depicted on the right, which is
the result of the union of three small triangles translated
appropriately. Alternatively, the same set can be reached by taking
the difference between a large triangle and a small
upside-down triangle. In general, there are many ways to arrive at
a particular point set. However, the set of polygons with holes
obtained through the application of any sequence of operations is
unique. The set depicted on the right is represented as a single
polygon having a triangular outer boundary with a single triangular
hole in its interior - and not as three triangles that have no holes
at all. As a general rule, if two point sets are connected, then they
belong to the same polygon with holes.

The class template `Polygon_with_holes_2<Kernel,Container>`
represents polygons with holes as described above, where the outer
boundary and the hole boundaries are realized as
`Polygon_2<Kernel,Container>` objects. Given an instance \f$ P\f$ of
the `Polygon_with_holes_2` class, you can use the predicate
`is_unbounded()` to check whether \f$ P\f$ is a unbounded set. If it is
bounded, you can obtain the counterclockwise-oriented polygon that
represents its outer boundary through the member function
`outer_boundary()`. You can also traverse the holes of \f$ P\f$ through
`holes_begin()` and `holes_end()`. The two functions return
iterators of the nested type
`Polygon_with_holes_2::Hole_const_iterator` that
defines the valid range of \f$ P\f$'s holes. The value type of this
iterator is `Polygon_2`.

The following function demonstrates how to traverse a polygon with holes.
It accepts a `Polygon_with_holes_2` object and uses the auxiliary
function `print_polygon()` to prints all its components in a readable
format:
\code{.cpp}
template<class Kernel, class Container>
void print_polygon_with_holes(const CGAL::Polygon_with_holes_2<Kernel, Container> & pwh)
{
  if (! pwh.is_unbounded()) {
    std::cout << "{ Outer boundary = ";
    print_polygon (pwh.outer_boundary());
  } else
    std::cout << "{ Unbounded polygon." << std::endl;

  typename CGAL::Polygon_with_holes_2<Kernel,Container>::Hole_const_iterator hit;
  unsigned int k = 1;

  std::cout << " " << pwh.number_of_holes() << " holes:" << std::endl;
  for (hit = pwh.holes_begin(); hit != pwh.holes_end(); ++hit, ++k) {
    std::cout << " Hole #" << k << " = ";
    print_polygon (*hit);
  }
  std::cout << " }" << std::endl;
}
\endcode

The simple versions of the free functions mentioned therefore
accept two `Polygon_2` object \f$ P\f$ and \f$ Q\f$ as their input, while
their output is given using polygon with holes instances:
<UL>
<LI>The complement of a simple polygon \f$ P\f$ is always an unbounded set
with a single polygonal hole. The function `complement(P)` therefore
returns a polygon-with-holes object that represents the complement of \f$ P\f$.
<LI>The union of two polygons \f$ P\f$ and \f$ Q\f$ is always a single connected
set, unless of course the two input polygons are completely disjoint. In
the latter case \f$ P \cup Q\f$ trivially consists of the two input polygons.
The free function `join(P, Q, R)` therefore returns a Boolean value
indicating whether \f$ P \cap Q \neq \emptyset\f$. If the two polygons are not
disjoint, it assigns the polygon with holes object \f$ R\f$ (which it
accepts by reference) with the union of the regularized union operation
\f$ P \cup Q\f$.
<LI>The other three functions, namely `intersection(P, Q, oi)`,
`difference(P, Q, oi)` and `symmetric_difference(P, Q, oi)`, all
have a similar interface. As the result of these operation may consist
of several disconnected components, they all accept an output iterator
`oi`, whose value type is `Polygon_with_holes_2`, and adds the
output polygons to its associated container.
</UL>

\subsection bso_sssecex_simple_bops Joining and Intersecting Simple Polygons

The following example demonstrates the usage of the free functions
`join()` and `intersection()` for computing the union and the
intersection of the two simple polygons depicted in
\cgalFigureRef{figsimple} (b). The example uses the auxiliary function
`print_polygon_with_holes()` listed above, which is located in
the header file `print_utils.h` under the examples folder.

\cgalExample{Boolean_set_operations_2/simple_join_intersect.cpp}

\subsection bso_sssecpwh_bops Operations on Polygons with Holes

We have demonstrated that free functions that perform Boolean set
operations on simple polygons may output polygons with holes. In
addition to these functions, the Boolean set-operations package
provides the following overridden free functions that accept
`General_polygon_with_holes_2` objects as their input: `complement()`,
`intersection()`, `join()`, `difference()`, `symmetric_difference()`,
and `do_intersect()` The prototypes of most functions are the same as
of their simpler counterparts that operate on simple polygons. The
only exception is `complement(P, oi)`, which outputs a range of
polygons with holes that represents the complement of the polygon with
holes \f$ P\f$.

\image html symm_diff.png
\image latex symm_diff.png

The following example demonstrates how to compute the symmetric
difference between two sets that contain holes. Each set is a
rectangle that contains a rectangular hole in its interior, such that
the symmetric difference between the two sets is a single polygon that
contains of five holes:

\cgalExample{Boolean_set_operations_2/symmetric_difference.cpp}

In some cases it is convenient to connect the outer boundary of a
polygon with holes with the holes inside it. The
function `connect_holes()` accepts a polygon with
holes, and connects the topmost vertex in each hole with the polygon
feature located directly above it (a vertex or an edge of the outer
boundary, or of another hole). It produces an output sequence of
points that match the traversal of all vertices in the connected
polygon (note that there are additional vertices, induced by the
vertical walls).

\cgalExample{Boolean_set_operations_2/connect_polygon.cpp}

\subsection bso_ssecmain_component Operating on Polygon Sets

The result of a regularized operation on two polygons (or polygons
with holes) \f$ P\f$ and \f$ Q\f$ is typically a collection of several
disconnected polygons with holes. It is only natural to represent such
a collection in terms of a class, making it possible to operate on the
set resulting from computing, for example, \f$ P \setminus Q\f$.

A central component in the Boolean set-operations package is the
`Polygon_set_2<Kernel, Container, Dcel>` class-template. An instance of
this class represents a point set formed by the collection of several
disconnected polygons with holes. It employs the `Arrangement_2` class
to represent this point set in the plane as a planar arrangement; see
Chapter \ref chapterArrangement_on_surface_2 "2D Arrangements". The instantiated `Dcel`
type is used to represent the underlying internal arrangement. It must model
the concept `GeneralPolygonSetDcel`, and defaults to `Gps_default_dcel`.
You can override this default, with a different \dcel class, typically
an extension of the default. Overriding the default is necessary only if
you intend to obtain the underlying internal arrangement and process it further.

An instance \f$ S\f$ of a `Polygon_set_2` class usually represents
the result of a sequence of operations that were applied on some input
polygons. The representation of \f$ S\f$ is unique, regardless of the particular
sequence of operations that were applied in order to arrive at it.

In addition, a polygon-set object can be constructed from a single
polygon object or from a polygon-with-holes object. Once constructed,
it is possible to insert new polygons (or polygons with holes) into
the set using the `insert()` method, as long as the inserted polygons
and the existing polygons in the set are disjoint.  The
`Polygon_set_2` class also provides access functions for obtaining the
polygons with holes it contains, and a few queries. An important query
is `S.oriented_side(q)`, which determined whether the query point \f$
q\f$ is contained in the interior of the set \f$ S\f$, lies on the
boundary of the set, or neither.

Similar to the `Polygon_set_2` class template, which applies to linear
polygons (or polygons with holes), the `General_polygon_set_2` class
applies to general polygons (or general polygons with holes). Each of
these class templates defines the predicate `do_intersect()` and the
methods `complement()`, `intersection()`, `join()`, `difference()` and
`symmetric_difference()` as member functions. The operands to these
functions may be simple polygons (`Polygon_2` or `General_polygon_2`
objects), polygons with holes (`Polygon_with_holes_2` or
`General_polygon_with_holes_2` objects), or polygon sets
(`cpolygon_set_2` or `General_polygon_set_2` objects). Each of the
aforementioned free functions is actually realized by a set overriding
member function.

member functions of the `Polygon_set_2`
(respectively `General_polygon_set_2`) that perform Boolean set-operations
come in two flavors: for example, `S.join(P, Q)` computes the union of
\f$ P\f$ and \f$ Q\f$ and assigned the result to \f$ S\f$, while
`S.join(P)` performs the operation \f$ S \longleftarrow S \cup P\f$.
Similarly, `S.complement(P)` sets \f$ S\f$ to be the complement of \f$
P\f$, while `S.complement()` assigns \f$ S\f$ with its complement.

\subsection bso_sssecsequence A Sequence of Set Operations

The free functions reviewed in Section \ref bso_ssecpolygons_with_holes
serve as a wrapper for the polygon-set class, and are only provided for
convenience. A typical such function constructs a pair of
`General_polygon_set_2` objects, invokes the appropriate method to
apply the desired Boolean operation, and transforms the resulting
polygon set to the required output format. Thus, when several
operations are performed in a sequence, it is much more efficient to
use the member functions of the `General_polygon_set_2` type
directly, as the extraction of the polygons from the internal
representation for some operation, and the reconstruction of the
internal representation for the succeeding operation could be time
consuming.

\image html sequence.png
\image latex sequence.png

The next example performs a sequence of three Boolean set-operations.
First, it computes the union of two simple polygons depicted in
\cgalFigureRef{figsimple} (a). It then computes the complement of the result
of the union operation. Finally, it computes the intersection of the result
of the complement operation with a rectangle, confining the final result to
the area of the rectangle. The resulting set \f$ S\f$ is comprised of two
components: a polygon with a hole, and a simple polygon contained in the
interior of this hole.

\cgalExample{Boolean_set_operations_2/sequence.cpp}

\subsection bso_ssecinsert_ni Inserting Non Intersecting Polygons

If you want to compute the union of a polygon \f$ P\f$ (\f$ P\f$ may be a simple
polygon or a polygon-with-holes object) with a general-polygon set
\f$ R\f$, and store the result in \f$ R\f$, you can construct a polygon set
\f$ S(P)\f$, and apply the <I>union</I> operation as follows:
\code{.cpp}
General_polygon_2 S (P);
R.join (S);
\endcode

As a matter of fact, you can apply the union operation directly:
\code{.cpp}
R.join (P);
\endcode

However, if you know that the polygon does not intersect any one of the
polygons represented by \f$ R\f$, you can use the more efficient method
`insert()`:
\code{.cpp}
R.insert (P);
\endcode

As `insert()` assumes that \f$ P \cap R = \emptyset\f$, it does not try to
compute intersections between the boundaries of \f$ P\f$ and of \f$ R\f$. This
fact significantly speeds up the insertion process in comparison with the
insertion of a non-disjoint polygon that intersects \f$ R\f$.

The `insert()` function is also overloaded, so it can also accept a
range of polygons. When a range of polygons are inserted into a
polygon set \f$ S\f$, all the polygons in the range and the polygons represented
by \f$ S\f$ must be pairwise disjoint in their interiors.

\subsection bso_ssecagg_ops Performing Aggregated Operations

There are a few options to compute the union of a set of polygons
\f$ P_1, \ldots P_m\f$. You can do it incrementally as follows. At each step
compute the union of \f$ S_{k-1} = \bigcup_{i=1}^{k-1}{P_i}\f$
with \f$ P_{k}\f$ and obtain \f$ S_k\f$. Namely, if the polygon set is given
as a pair of iterator `[begin, end)`, the following loop computes
their union in \f$ S\f$.
\code{.cpp}
InputIterator iter = begin;
Polygon_set_2 S (*iter);

while (++iter != end) {
  S.join (*iter);
  ++iter;
}
\endcode
A second option is to use a divide-and-conquer approach. You bisect
the set of polygons into two sets. Compute the union of each set
recursively and obtain the partial results in \f$ S_1\f$ and \f$ S_2\f$, and
finally, you compute the union \f$ S_1 \cup S_2\f$. However, the union
operation can be done more efficiently for sparse polygons, having
a relatively small number of intersections, using a third option that
simultaneously computes the union of all polygons. This is done by
constructing a planar arrangement of all input polygons, utilizing the
sweep-line algorithm, then extracting the result from the
arrangement. Similarly, it is also possible to aggregately compute the
intersection \f$ \bigcap_{i=1}^{m}{P_i}\f$ of a set of input polygons.

Our package provides the free overloaded functions `join()` and
`intersection()` that aggregately compute the union and the
intersection of a range of input polygons. There is no restriction on
the polygons in the range; naturally, they may intersect each other.
The package provides the overloaded free function \ref do_intersect
"do_intersect(begin, end)" that determines whether the polygons in the
range defined by the two input iterators `[begin, end)` intersect.

The class `General_polygon_set_2` also provides equivalent member
functions that aggregately operate on a range of input polygons or
polygons with holes. When such a member function is called, the general
polygons represented by the current object are considered operands as
well. Thus, you can easily compute the union of our polygon range as
follows:
\code{.cpp}
Polygon_set_2 S;
S.join (begin, end);
\endcode

\subsection bso_ssectraits_sel Traits Selection

All the free function-templates that apply Boolean set operations
accept an optional traits argument; see next Section for more
information. If a traits class is not provided, a default one that can
handle the type of the curves that comprise the boundaries of the
input polygons is selected. You somehow can influence this selection
using a template parameter as described below.

The set of free function-templates that handle (linear) polygons
include overloaded versions that are parameterized by the template
parameter `UsePolylines`. For each such function template the
`UsePolylines` template parameter determmines whether to treat the
boundary of each input (linear) polygon as a cyclic sequence of single
(\f$x\f$-monotone) segments or as a cyclic sequence of
(\f$x\f$-monotone) polylines. By default, `UsePolylines` is set to
`CGAL::Tag_true`, which implies that the boundary of the each input
(linear) polygon is treated as a cyclic sequence of (\f$x\f$-monotone)
polylines. In most cases this behavior is superior (that is, less
time-consuming) because the number of events handled as part of the
execution of the plane-sweep algorithm is reduced. In cases where the
boundaries of the input polygons frequently intersect, treating them
as polylines may become less efficient. In these cases substitute the
`UsePolylines` template parameter with `CGAL::Tag_false` to restore
the original behavior (where the boundary of each input linear
polygon is treated as a cyclic sequence of single \f$x\f$-monotone
segments).

\cgalAdvancedBegin

A Boolean set operation can be apppplied on general polygons (or
general polygons with holes) directly using an instance of the class
template `General_polygon_set_2` or by using a free function, which
internally uses an instance of the class template
`General_polygon_set_2`. Similarly, a Boolean set operation can be
apppplied on linear polygons (or linear polygons with holes) directly
using an instance of the class template `Polygon_set_2` or by using a
free function, which internally uses an instance of the class template
`Polygon_set_2` by default. An instance of the `Polygon_set_2` class
template treats every edge of the polygon as a single
(\f$x\f$-monotone) segment, as it utilizes, in turn, the
`Arr_segment_traits_2` class template; see Section \ref
arr_ssectr_segs in the 2D Arrangements package.

If the `UsePolylines` template parameter is substitited with
`CGAL::Tag_true` the following occurs:

<ol>

<li>Instead of using an instance of the `Polygon_set_2` class
template, as described above, an instance of the
`General_polygon_set_2` class template is used, which utilizes the
`Arr_polyline_traits_2` class template; see Section \ref
arr_ssectr_polylines in the 2D Arrangements package.

<li>Each input linear polygon (respectively linear polygon with holes) is
converted into a general polygon (respectively general polygon with holes)
bounded by \f$x\f$-monotone polylines. Then, the resulting general
polygons, which are also bounded by \f$x\f$-monotone polylines, are
converted back to standard polygons.

</ol>

\cgalAdvancedEnd

\section bso_secbso_gen Boolean Set-Operations on General Polygons

\image html general_polygon.png
\image latex general_polygon.png

In previous sections only ordinary (linear) polygons were dealt
with. Namely, closed point sets bounded by piecewise linear
curves. The Boolean set-operations package allows a more general
geometric mapping of the polygon edges. The operations provided by the
package operate on point sets bounded by \f$ x\f$-monotone segments of
general curves (e.g., conic arcs and segments of polynomial
functions). For example, the point set depicted on the right is a
general polygon bounded by two \f$ x\f$-monotone circular arcs that
correspond to the lower half and the upper half of a circle,
respectively.

Using the topological terminology, a general polygon can represent any
simply-connected point set whose boundary is a strictly simple curve.
Such a polygon is a model of the `GeneralPolygon_2` concept. A model
of this concept must fulfill the following requirements:
<UL>
<LI>A general polygon is constructible from a range of pairwise
interior disjoint \f$ x\f$-monotone curves \f$ c_1, \ldots, c_n\f$. The target
point of the \f$ k\f$th curve \f$ c_k\f$ and the source point of the next curve
in the range (in a cyclic order) must coincide, such that this point
defines the \f$ k\f$th polygon vertex.
<LI>It is possible to traverse the \f$ x\f$-monotone curves that form the
edges of a general polygon.
</UL>

\image html general_polygon_with_holes.png
\image latex general_polygon_with_holes.png

The concept `GeneralPolygonWithHoles_2` is defined in an analogous
way to the definition of linear polygons with holes. A model of this
concept represent a bounded or an unbounded set that may not be simply
connected, and must provide the following operations:

<UL>
<LI>Construction for a general polygon that represent the outer boundary
and a range of general polygons that represent the holes.
<LI>Accessing the general polygons that represents the outer boundary
(in case of a bounded set).
<LI>Traversing the holes.
</UL>
In Section \ref bso_secbso_lin we introduce the classes
`Polygon_2` and `Polygon_with_holes_2` that model the concepts
`GeneralPolygon_2` and `GeneralPolygonWithHoles_2`
respectively. In this section we introduce other models of these two
concepts.

The central class-template `General_polygon_set_2<Traits,Dcel>` is
used to represent point sets that are comprised of a finite number of
pairwise disjoint general polygons with holes, and provides various
Boolean set-operations on such sets. It is parameterized by a <I>traits</I>
class and a \dcel class. The former defines the type of points used
to represent polygon vertices and the type of \f$ x\f$-monotone curves that
represent the polygon edges. The traits class also provides primitive
geometric operations that operate on objects of these types.
The \dcel class is used to represent the underlying internal
`Arrangement_2` data structure. The instantiated `Dcel` type is
used to represent the underlying internal arrangement. It must model the
concept `GeneralPolygonSetDcel`, and defaults to `Gps_default_dcel`.
You can override this default, with a different \dcel class, typically
an extension of the default. Overriding the default is necessary only if
you intend to obtain the underlying internal arrangement and process it further.

An instantiated
`General_polygon_set_2` class defines the nested types
`General_polygon_set_2<Traits,Dcel>::%Polygon_2` and
`General_polygon_set_2<Traits,Dcel>::%Polygon_with_holes_2`, which model
the concepts `GeneralPolygon_2` and
`GeneralPolygonWithHoles_2` respectively.

\subsection bso_ssectraits_concepts The Traits-Class Concepts

The traits class used to instantiate the `General_polygon_set_2`
class template must model the concept `GeneralPolygonSetTraits_2`,
and is tailored to handle a specific family of curves. The concept
`GeneralPolygonSetTraits_2` refines the concept
`AosDirectionalXMonotoneTraits_2` specified next.

The concept `AosDirectionalXMonotoneTraits_2` refines the
concept `AosXMonotoneTraits_2` (see
Section \ref arr_sssecinsert_x_mon in the 2D Arrangements package).
Thus, a model of this concept must define the type `X_monotone_curve_2`,
which represents an \f$ x\f$-monotone curve, and the type `Point_2`,
with represents a planar point. Such a point may be an endpoint of an
\f$ x\f$-monotone curve or an intersection point between two curves.
It must also provide various geometric predicates and operations
on these types listed by the base concept, such as determining whether
a point lies above or below an \f$ x\f$-monotone curve, computing the
intersections between two curves, etc. Note that the base concept does
not assume that \f$ x\f$-monotone curves are directed: an \f$ x\f$-monotone
curve is not required to have a designated <I>source</I> and <I>target</I>, it is only required to determine the left (lexicographically
smaller) and the right (lexicographically larger) endpoints of a given
curve.

The `AosDirectionalXMonotoneTraits_2` concept treats its
\f$ x\f$-monotone curves as directed objects. It thus requires two additional
operations on \f$ x\f$-monotone curves:
<UL>
<LI>Given an \f$ x\f$-monotone curve, compare its source and target points
lexicographically.
<LI>Given an \f$ x\f$-monotone curve, construct its opposite curve (namely,
swap its source and target points).
</UL>

The traits classes `Arr_segment_traits_2`,
`Arr_non_caching_segment_traits_2`, `Arr_circle_segment_traits_2`,
`Arr_conic_traits_2` and `Arr_rational_function_traits_2`, which are
bundled in the `Arrangement_2` package and distributed with \cgal, are
all models of the refined concept
`AosDirectionalXMonotoneTraits_2`.\cgalFootnote{The
\cgalFootnoteCode{Arr_polyline_traits_2} class is <I>not</I> a model
of the, \cgalFootnoteCode{AosDirectionalXMonotoneTraits_2} concept, as
the \f$ x\f$-monotone curve it defines is always directed from left to
right. Thus, an opposite curve cannot be constructed. However, it is
not very useful to construct a polygon whose edges are polylines, as
an ordinary polygon with linear edges can represent the same entity.}

Operations on polygons (or general polygons) are guaranteed to be
robust only if the operations of the geometry traits used to carry out
the high-level operations are robust. Most operations on polygons use
geometry traits constructors, as they generate new polygons; such
constructors are guaranteed to be robust only if the kernel in use
supports exact constructions, such as the EPEC (Exact Predicate Exact
Construction) kernel. The `do_intersect()` overloaded predicates that
operate on (linear) polygons are exceptions, as they only use geometry
traits predicates; such predicates are guaranteed to be robust only if
the kernel in use supports exact predicates, such as the EPIC (Exact
Predicate Inexact Construction) kernel. When inexact arithmetic is
used, (nearly) degenerate configurations may result in abnormal
termination of the program or even incorrect results.

\subsection bso_sseccirc_seg Operating on Polygons with Circular Arcs

Two traits classes are distributed with \cgal. The first one is named
`Gps_segment_traits_2`, and it is used to perform Boolean
set-operations on ordinary polygons and polygons with holes. In fact,
the class `Polygon_set_2` introduced in
Section \ref bso_ssecmain_component is a specialization of
`General_polygon_set_2<Gps_segment_traits_2>`. This class defined
its polygon and polygon with holes types, such that the usage of this
traits class is encapsulated in the polygon-set class.

The other predefined traits class is named
`Gps_circle_segment_traits_2<Kernel>` and is parameterized by a
geometric \cgal kernel. By instantiating the `General_polygon_set_2`
with this traits class, we obtain the representation of a polygon whose
boundary may be comprised of line segments and circular arcs.
The circle-segment traits class provides predicates and constructions
on non-linear objects; yet, it uses only rational arithmetic and is
very efficient as a consequence.

\image html circles_rects.png
\image latex circles_rects.png

The following example uses the `Gps_circle_segment_traits_2` class
to compute the union of four rectangles and four circles. Each circle
is represented as a general polygon having two \f$ x\f$-monotone circular arcs.
The union is computed incrementally, resulting with a single polygon with
a single hole, as depicted on the right. Note that as the four circles
are disjoint, their union is computed with the `insert` method,
while the union with the rectangles is computed with the `join`
operator.

\cgalExample{Boolean_set_operations_2/circle_segment.cpp}

\subsection bso_ssecgeneral_polygon_concept General Polygon Set Traits Adapter

The concept `GeneralPolygon_2` and its generic model
`General_polygon_2<ArrDirectionalXMonotoneTraits>` facilitate the
production of general-polygon set traits classes. A model of the concept
`GeneralPolygon_2` represents a simple point-set in the plane bounded
by \f$ x\f$-monotone curves. As opposed to the plain `Traits::Polygon_2` type
defined by any traits class, it must define the type
`X_monotone_curve_2`, which represents an \f$ x\f$-monotone curve of the
point-set boundary. It must provide a constructor from a range of such
curves, and a pair of methods, namely `curves_begin()` and
`curves_end()`, that can be used to iterate over the point-set boundary
curves.

The class-template `General_polygon_2<ArrDirectionalXMonotoneTraits>`
models the concept `GeneralPolygon_2`. Its sole template parameter
must be instantiated with a model of the concept
`AosDirectionalXMonotoneTraits_2` from which it obtains the
`X_monotone_curve_2` type. It uses the geometric operations
on this type provided by such a model to maintain a container of
directed curves of type `X_monotone_curve_2`, which represents a
boundary of the general polygon.

The class-template
`Gps_traits_2<ArrDirectionalXMonotoneTraits,GeneralPolygon>`
models the concept `GeneralPolygonSetTraits_2`, and can be used to
instantiate the class template `General_polygon_set_2`.
It serves as an adapter for a geometric traits class, which models the
concept `AosDirectionalXMonotoneTraits_2`.
It can be used for performing set-operations on general polygons.
The implementation of the adapter is rather simple, as it is derived
from the instantiated template-parameter `ArrXMonotoneTraits_2`
inheriting its necessary types and methods. It further exploits
the methods provided by the instantiated parameter
`GeneralPolygon`, which is a model of the concept
`GeneralPolygon_2`. By default, the `GeneralPolygon` parameter
is defined as
`General_polygon_2<AosDirectionalXMonotoneTraits_2>`.

The code excerpt listed below defines a general-polygon set type that
can be used to perform Boolean set-operations on point sets bounded by
the \f$ x\f$-monotone curve type defined by the arrangement-traits class
`Arr_traits_2`, which is some representative model of the concept
`AosDirectionalXMonotoneTraits_2`.

\code{.cpp}
#include <CGAL/General_polygon_2.h>
#include <CGAL/Gps_traits_2.h>

typedef CGAL::General_polygon_2<Arr_traits_2> General_polygon_2;
typedef CGAL::Gps_traits_2<Arr_traits_2, General_polygon_2> Traits_2;
typedef CGAL::General_polygon_set_2<Traits_2> General_polygon_set_2;
\endcode

\image html tnr_m_g.png
\image latex tnr_m_g.png

Instantiating the arrangement-traits `Arr_traits_2` above with the
traits class that handle B&eacute;zier curves `Arr_Bezier_curve_traits_2`,
results with the definition of a general-polygon set type that can be
used to perform Boolean set-operations on point sets bounded by B&eacute;zier
curves.

The next example computes the intersection of two general polygons
bounded by B&eacute;zier curves read from two input files respectively. The
default input files our example uses (`char_g.dat` and
`char_m.dat`) define two general polygons shaped in the form of
the characters <B>g</B> and <B>m</B> in the Times New Roman font
respectively. Their intersection comprises nine simple polygons, as
depicted to the right.

Recall that every B&eacute;zier curve is defined by a sequence of control
points that form chains (see Section \ref arr_sssectr_bez. The last
control point of every curve must be identical to the first control
point of its successor. The function `read_Bezier_polygon()`
included in the example reads the curves from an input file until they
form a closed chain, which is assumed to be the outer boundary of the
polygon. If more curves are available, its starts constructing
polygons that correspond to holes in the area bounded by the outer
boundary. Note that this function is also responsible for subdividing
the input B&eacute;zier curves into \f$ x\f$-monotone subcurves, as required by
the `Gps_traits_2` adapter.

\cgalExample{Boolean_set_operations_2/bezier_traits_adapter.cpp}

\subsection bso_ssecaggregated_gen_ops Aggregated Operations

In Section \ref bso_ssecagg_ops we describe how aggregated union
and intersection operations can be applied to a collection of ordinary
polygons or polygons with holes. Naturally, the aggregated operations
can be applied also to collections of general polygons. As was the
case with ordinary polygons, using aggregated operations is
recommended when the number of intersections of the input polygons
is of the same order of magnitude as the complexity of the result. If
this is not the case, computing the result incrementally may prove
faster.

\image html disks.png
\image latex disks.png

The next example computes the union of eight unit discs whose centers are
placed a unit distance from the origin, as depicted to the right. The example
also allows users to provide a different number of discs through the command
line.

\cgalExample{Boolean_set_operations_2/set_union.cpp}

*/
} /* namespace CGAL */

---

### Boolean Set Operations 2 Doc Boolean Set Operations 2 PackageDescription (`Boolean_set_operations_2/doc/Boolean_set_operations_2/PackageDescription.txt`)

/// \defgroup PkgBooleanSetOperations2Ref Reference Manual
/// \defgroup PkgBooleanSetOperations2Concepts Concepts
/// \ingroup PkgBooleanSetOperations2Ref

/// \cgalConceptNamespace
/// The namespace containing concepts specific to 2D Boolean Set Operations.
namespace ArrDirectionalTraits {}

/*!
\cgalInclude{CGAL/draw_polygon_set_2.h}
*/
/// \defgroup PkgDrawPolygonSet2 Draw a 2D Polygon Set
/// \ingroup PkgBooleanSetOperations2Ref

/*!
\addtogroup PkgBooleanSetOperations2Ref
\cgalPkgDescriptionBegin{2D Regularized Boolean Set-Operations,PkgBooleanSetOperations2}
\cgalPkgPicture{Boolean_set_operations_2.png}
\cgalPkgSummaryBegin
\cgalPkgAuthors{Efi Fogel, Ophir Setter, Ron Wein, Guy Zucker, Baruch Zukerman, and Dan Halperin}
\cgalPkgDesc{This package consists of the implementation of Boolean set-operations on point sets bounded by weakly x-monotone curves in 2-dimensional Euclidean space. In particular, it contains the implementation of regularized Boolean set-operations, intersection predicates, and point containment predicates.}
\cgalPkgManuals{Chapter_2D_Regularized_Boolean_Set-Operations,PkgBooleanSetOperations2Ref}
\cgalPkgSummaryEnd
\cgalPkgShortInfoBegin
\cgalPkgSince{3.2}
\cgalPkgDependsOn{\ref PkgArrangementOnSurface2}
\cgalPkgBib{cgal:fwzh-rbso2}
\cgalPkgLicense{\ref licensesGPL "GPL"}
\cgalPkgShortInfoEnd
\cgalPkgDescriptionEnd

This package consists of the implementation of Boolean set-operations
on point sets bounded by \f$x\f$-monotone curves in 2-dimensional
Euclidean space. In particular, it contains the implementation of
regularized Boolean set-operations, intersection predicates, and point
containment predicates.

\cgalClassifedRefPages

\cgalCRPSection{Concepts}
- `GpsTraitsGeneralPolygon_2`
- `GpsTraitsGeneralPolygonWithHoles_2`
- `GeneralPolygon_2`
- `AosDirectionalXMonotoneTraits_2`
- `GeneralPolygonSetTraits_2`
- `GeneralPolygonSetDcel`
- `GeneralPolygonSetDcelFace`
- `GeneralPolygonSetDcelHalfedge`

\cgalCRPSection{Classes}
- `CGAL::Polygon_set_2<Kernel,Container,Dcel>`
- `CGAL::General_polygon_set_2<Traits,Dcel>`
- `CGAL::General_polygon_2<ArrTraits>`
- `CGAL::General_polygon_with_holes_2<Polygon>`
- `CGAL::Gps_segment_traits_2<Kernel,Container,ArrSegmentTraits>`
- `CGAL::Gps_circle_segment_traits_2<Kernel>`
- `CGAL::Gps_traits_2<ArrTraits,GeneralPolygon>`
- `CGAL::Gps_default_dcel<Traits>`

\cgalCRPSection{Functions}
- \link boolean_complement `CGAL::complement()` \endlink
- \link boolean_do_intersect `CGAL::do_intersect()` \endlink
- \link boolean_intersection `CGAL::intersection()` \endlink
- \link boolean_join `CGAL::join()` \endlink
- \link boolean_difference `CGAL::difference()` \endlink
- \link boolean_symmetric_difference `CGAL::symmetric_difference()` \endlink
- \link boolean_oriented_side `CGAL::oriented_side()` \endlink
- \link boolean_connect_holes `CGAL::connect_holes()` \endlink

\cgalCRPSection{Draw a Polygon_set_2}
- \link PkgDrawPolygonSet2 CGAL::draw<PS>() \endlink
- `GraphicsSceneOptionsPolygonSet2`
- `CGAL::Graphics_scene_options_polygon_set_2`

*/

---

### Boolean Set Operations 2 Doc Boolean Set Operations 2 Examples (`Boolean_set_operations_2/doc/Boolean_set_operations_2/examples.txt`)

/*!
\example Boolean_set_operations_2/bezier_traits_adapter2.cpp
\example Boolean_set_operations_2/bezier_traits_adapter.cpp
\example Boolean_set_operations_2/circle_segment.cpp
\example Boolean_set_operations_2/conic_traits_adapter.cpp
\example Boolean_set_operations_2/connect_polygon.cpp
\example Boolean_set_operations_2/do_intersect.cpp
\example Boolean_set_operations_2/draw_polygon_set.cpp
\example Boolean_set_operations_2/dxf_union.cpp
\example Boolean_set_operations_2/sequence.cpp
\example Boolean_set_operations_2/set_union.cpp
\example Boolean_set_operations_2/simple_join_intersect.cpp
\example Boolean_set_operations_2/symmetric_difference.cpp
*/

---

### Bounding Volumes Doc Bounding Volumes Bounding Volumes (`Bounding_volumes/doc/Bounding_volumes/Bounding_volumes.txt`)

namespace CGAL {
/*!

\mainpage User Manual
\anchor Chapter_Bounding_Volumes
\anchor chapBoundingVolumes
\cgalAutoToc
\authors Kaspar Fischer, Bernd G&auml;rtner, Thomas Herrmann, Michael Hoffmann, and Sven Sch&ouml;nherr

\image html ball.png

This chapter describes algorithms which for a given point set compute
the <i>best</i> circumscribing object from a specific
class. If the class consists of all spheres in \f$ d\f$-dimensional
Euclidean space and <i>best</i> is defined as having smallest radius,
then we obtain the smallest enclosing sphere.



\section SectBoundingIntroduction Introduction

Bounding volumes can be used to obtain simple approximations of
complicated objects. For example, consider the problem of deciding
whether two moving polygons currently intersect. An obvious solution
is to discretize time and perform a full intersection test for any
time step. If the polygons are far apart most of the time, this is
unnecessary. Instead, simple bounding volumes (for examples, circles)
are computed for both polygons at their initial positions. At
subsequent time steps, an intersection test between the moving
bounding circles replaces the actual intersection test; only if the
circles do intersect, the expensive intersection test between the
polygons is performed. In practice, bounding volume hierarchies are
often used on top of simple bounding volumes to approximate
complicated objects more accurately.

Bounding volumes are also frequently applied to extract
geometric properties of objects. For example, the smallest enclosing
annulus of a point set can be used to test whether a set of points is
approximately cospherical. Here, the width of the annulus (or its
area, or still another criterion that we use) is a good measure for
this property.

\section SectBoundingSphere Bounding Spheres in dD

We provide the class `Min_sphere_of_spheres_d<Traits>` for arbitrary dimensions
to compute the smallest enclosing spheres for points as well as for spheres.
The dimension as well as the input type depend on the chosen traits class.

The following example is for 2D points

\cgalExample{Min_circle_2/min_circle_2.cpp}

The example for 2D circles as input looks rather similar.


\cgalExample{Min_sphere_of_spheres_d/min_sphere_of_spheres_d_2.cpp}



\subsection  SectBoundingSphereHomogeneous Bounding Spheres for the Homogeneous Kernel

In the previous section we saw that we used `Min_sphere_of_spheres_d`
to compute the smallest circle for points. This package also provides
the classes `Min_circle_2` and `Min_sphere_d`, but they are slower,
and they should only be used in case of homogeneous coordinates which
are not supported by `Min_sphere_of_spheres_d`.

In the following example a smallest enclosing circle
(`Min_circle_2<Traits>`) is constructed from points
on a line and written to standard output. The example
shows that it is advisable to switch on random shuffling
in order to deal with a <i>bad</i> order of the input points.

\cgalExample{Min_circle_2/min_circle_homogeneous_2.cpp}


\section SectBoundingAnnulus Bounding Annulus in dD

We provide the class `Min_annulus_d<Traits>` for arbitrary dimensions
to compute the smallest enclosing annulus for a set of points.
In 2D the annulus consists of two concentric circles, in 3D of
two concentric spheres.

\image html annulus.png




\section SectBounding2D Various Bounding Areas in 2D

Other classes for which we provide solutions are ellipses
(`Min_ellipse_2<Traits>`), rectangles
(`min_rectangle_2()`), parallelograms
(`min_parallelogram_2()`) and strips (`min_strip_2()`)
in the plane, with appropriate optimality criteria.


\section SectBoundingEllipsoid Approximate Bounding Ellipsoid in dD

While this package provides an exact smallest 2D ellipse, it also
provides the class `Approximate_min_ellipsoid_d<Traits>` to compute
an approximate minimum-volume enclosing ellipsoid with user-specified
approximation ratio.




\section SectBoundingPcenter Rectangular P-Center

Bounding volumes also define geometric "center points" of objects.
For example, if two objects are to be matched (approximately), one
approach is to first apply the translation that maps the centers of
their smallest enclosing spheres onto each other. Simpler centers are
possible, of course (center of gravity, center of bounding box), but
more advanced bounding volumes might give better results in some
cases. It can also make sense to consider several center points
instead of just one. For example, we provide algorithms to cover a
planar point set with between two and four minimal boxes
(`rectangular_p_center_2()`). Below is an example covering with
three boxes; the center points are shown in red.

\image html pcenter.png

*/
} /* namespace CGAL */

---

### Bounding Volumes Doc Bounding Volumes PackageDescription (`Bounding_volumes/doc/Bounding_volumes/PackageDescription.txt`)

/// \defgroup PkgBoundingVolumesRef Reference Manual
/// \defgroup PkgBoundingVolumesConcepts Concepts
/// \ingroup PkgBoundingVolumesRef
/*!
\addtogroup PkgBoundingVolumesRef
\cgalPkgDescriptionBegin{Bounding Volumes,PkgBoundingVolumes}
\cgalPkgPicture{minCircle.png}
\cgalPkgSummaryBegin
\cgalPkgAuthors{Kaspar Fischer, Bernd Gärtner, Thomas Herrmann, Michael Hoffmann, and Sven Schönherr}
\cgalPkgDesc{This package provides algorithms for computing optimal bounding volumes of point sets. In d-dimensional space, the smallest enclosing sphere, ellipsoid (approximate), and annulus can be computed. In 3-dimensional space, the smallest enclosing strip is available as well, and in 2-dimensional space, there are algorithms for a number of additional volumes (rectangles, parallelograms, \f$ k=2,3,4\f$ axis-aligned rectangles). The smallest enclosing sphere algorithm can also be applied to a set of d-dimensional spheres.}
\cgalPkgManuals{Chapter_Bounding_Volumes,PkgBoundingVolumesRef}
\cgalPkgSummaryEnd
\cgalPkgShortInfoBegin
\cgalPkgSince{1.1}
\cgalPkgDependsOn{\ref thirdpartyEigen}
\cgalPkgBib{cgal:fghhs-bv}
\cgalPkgLicense{\ref licensesGPL  "GPL"}
\cgalPkgDemo{2D Bounding Volumes,bounding_volumes_2.zip}
\cgalPkgShortInfoEnd
\cgalPkgDescriptionEnd


\cgalClassifedRefPages

\cgalCRPSection{Bounding Areas and Volumes}

- `CGAL::Min_circle_2<Traits>`
- `CGAL::Min_circle_2_traits_2<K>`
- `MinCircle2Traits`<BR>

- `CGAL::Min_ellipse_2<Traits>`
- `CGAL::Min_ellipse_2_traits_2<K>`
- `MinEllipse2Traits`<BR>

- `CGAL::Approximate_min_ellipsoid_d<Traits>`
- `ApproximateMinEllipsoid_d_Traits_d`<BR>

- `CGAL::min_rectangle_2`
- `CGAL::min_parallelogram_2`
- `CGAL::min_strip_2`
- `CGAL::Min_quadrilateral_default_traits_2<K>`
- `MinQuadrilateralTraits_2`<BR>

- `CGAL::rectangular_p_center_2`
- `CGAL::Rectangular_p_center_default_traits_2<K>`
- `RectangularPCenterTraits_2`<BR>

- `CGAL::Min_sphere_d<Traits>`
- `CGAL::Min_annulus_d<Traits>`
- `CGAL::Min_sphere_annulus_d_traits_2<K,ET,NT>`
- `CGAL::Min_sphere_annulus_d_traits_3<K,ET,NT>`
- `CGAL::Min_sphere_annulus_d_traits_d<K,ET,NT>`
- `MinSphereAnnulusDTraits`<BR>

- `CGAL::Min_sphere_of_spheres_d<Traits>`
- `MinSphereOfSpheresTraits`
*/

---

### Bounding Volumes Doc Bounding Volumes Examples (`Bounding_volumes/doc/Bounding_volumes/examples.txt`)

/*!
\example Approximate_min_ellipsoid_d/ellipsoid.cpp
\example Approximate_min_ellipsoid_d/ellipsoid_for_maple.cpp
\example Min_annulus_d/min_annulus_d.cpp
\example Min_annulus_d/min_annulus_d_fast_exact.cpp
\example Min_circle_2/min_circle_2.cpp
\example Min_circle_2/min_circle_homogeneous_2.cpp
\example Min_ellipse_2/min_ellipse_2.cpp
\example Min_quadrilateral_2/minimum_enclosing_parallelogram_2.cpp
\example Min_quadrilateral_2/minimum_enclosing_rectangle_2.cpp
\example Min_quadrilateral_2/minimum_enclosing_strip_2.cpp
\example Min_sphere_d/min_sphere_3.cpp
\example Min_sphere_d/min_sphere_homogeneous_3.cpp
\example Min_sphere_of_spheres_d/benchmark.cpp
\example Min_sphere_of_spheres_d/min_sphere_of_spheres_d_2.cpp
\example Min_sphere_of_spheres_d/min_sphere_of_spheres_d_3.cpp
\example Min_sphere_of_spheres_d/min_sphere_of_spheres_d_d.cpp
\example Rectangular_p_center_2/rectangular_p_center_2.cpp
*/

---

### Box Intersection D Doc Box Intersection D Box Intersection D (`Box_intersection_d/doc/Box_intersection_d/Box_intersection_d.txt`)

namespace CGAL {
/*!

\mainpage User Manual
\anchor Chapter_Intersecting_Sequences_of_dD_Iso-oriented_Boxes
\anchor chapterBoxIntersection
\cgalAutoToc
\authors Lutz Kettner, Andreas Meyer, and Afra Zomorodian

\section Box_intersection_dIntroduction Introduction

Simple questions on geometric primitives, such as intersection and
distance computations, can themselves become quite expensive if the
primitives are not so simple anymore, for example, three-dimensional
triangles and facets of polyhedral surfaces. Thus algorithms operating
on these primitives tend to be slow in practice. A common (heuristic)
optimization approximates the geometric primitives with their
axis-aligned bounding boxes, runs a suitable modification of the
algorithm on the boxes, and whenever a pair of boxes has an
interesting interaction \cgalFootnote{Boxes represent volumes or
point-sets. So, <I>intersection</I> means intersection of the
point-set enclosed by the box and not only intersection of the
boundary, of course.}, only then the exact answer is computed on the
complicated geometric primitives contained in the boxes.

\image html box_inters.png
\image latex box_inters.png

We provide an efficient algorithm \cgalCite{cgal:ze-fsbi-02} for finding all
intersecting pairs for large numbers of iso-oriented boxes, i.e.,
typically these will be such bounding boxes of more complicated geometries.
One immediate application of this algorithm is the detection of all
intersections (and self-intersections) for polyhedral surfaces, i.e.,
applying the algorithm on a large set of triangles in space, we give
an example program later in this chapter. Not so obvious applications
are proximity queries and distance computations among such surfaces,
see Section \ref secbox_inters_example_proximity for an example
and \cgalCite{cgal:ze-fsbi-02} for more details.

\section secboxintersdef Definition

A \f$ d\f$-dimensional iso-oriented box is defined as the
%Cartesian product of \f$ d\f$ intervals. We call the
box <I>half-open</I> if the \f$ d\f$ intervals \f$ \{ [lo_i,hi_i) \,|\, 0 \leq
i < d\}\f$ are half-open intervals, and we call the box <I>closed</I> if
the \f$ d\f$ intervals \f$ \{ [lo_i,hi_i] \,|\, 0 \leq i < d\}\f$ are closed
intervals. Note that closed boxes support zero-width boxes and they
can intersect at their boundaries, while non-empty half-open boxes
always have a positive volume and they only intersect iff their
interiors overlap. The distinction between closed and half-open boxes
does not require a different representation of boxes, just a different
interpretation when comparing boxes, which is selected with the two
possible values for the `topology` parameter:

<UL>
<LI>`Box_intersection_d::HALF_OPEN` and
<LI>`Box_intersection_d::CLOSED`.
</UL>

The number type of the interval boundaries must be one of the built-in
types <TT>int</TT>, <TT>unsigned int</TT>, <TT>double</TT> or
<TT>float</TT>.

In addition, a box has a unique `id`-number. It is used to order
boxes consistently in each dimension even if boxes have identical
coordinates. In consequence, the algorithm guarantees that a pair of
intersecting boxes is reported only once. Note that boxes with equal
`id`-number are not reported since they obviously intersect trivially.

The box intersection algorithm comes in two flavors: One algorithm
works on a single sequence of boxes and computes all pairwise
intersections, which is called the <I>complete</I> case, and used,
for example, in the self-intersection test. The other algorithm works
on two sequences of boxes and computes the pairwise intersections
between boxes from the first sequence with boxes from the second
sequence, which is called the <I>bipartite</I> case. For each
pairwise intersection found a callback function is called with two
arguments; the first argument is a box from the first sequence and the
second argument a box from the second sequence. In the complete case,
the second argument is a box from an internal copy of the first
sequence.

\section Box_intersection_dSoftware Software Design

The box intersection algorithm is implemented as a family of generic
functions; the functions for the complete case accept one iterator
range, and the functions for the bipartite case accept two iterator
ranges. The callback function for reporting the intersecting pairs is
provided as a template parameter of the `BinaryFunction` concept.
The two principle function calls utilizing all default arguments look
as follows:

\code{.cpp}
#include <CGAL/box_intersection_d.h>

template< class RandomAccessIterator, class Callback >
void box_intersection_d(RandomAccessIterator begin,
                        RandomAccessIterator end,
                        Callback callback);

template< class RandomAccessIterator1,
          class RandomAccessIterator2,
          class Callback >
void box_intersection_d(RandomAccessIterator1 begin1, RandomAccessIterator1 end1,
                        RandomAccessIterator2 begin2, RandomAccessIterator2 end2,
                        Callback callback);
\endcode

Additional parameters to the functions calls are a <I>cutoff</I>
value to adjust performance trade-offs, and a <I>topology</I> parameter
selecting between topologically closed boxes (the default) and
topologically half-open boxes.

The algorithm reorders the boxes in the course of the algorithm. Now,
depending on the size of a box it can be faster to copy the boxes, or
to work with pointers to boxes and copy only pointers. We offer
automatic support for both options. To simplify the description, let us
call the `value_type` of the iterator ranges <I>box handle</I>.
The <I>box handle</I> can either be our box type itself or a
pointer (or const pointer) to the box type; these choices represent
both options from above.

In general, the algorithms treat the box type as opaque type and just
assume that they are models of the `Assignable` concept, so that
the algorithms can modify the input sequences and reorder the boxes.
The access to the box dimension and box coordinates is mediated with a
traits class of the `BoxIntersectionTraits_d` concept. A default
traits class is provided that assumes that the box type is a model of
the `BoxIntersectionBox_d` concept and that the box handle, i.e.,
the iterators value type, is identical to the box type or a pointer
to the box type (see the previous paragraph for the value versus
pointer nature of the box handle).

Three implementations of iso-oriented boxes are provided;
`Box_intersection_d::Box_d` as a plain box, and
`Box_intersection_d::Box_with_info_d`  and
`Box_intersection_d::Box_with_handle_d` as a box plus respectively an info
or a handle that can be used to point to the full geometry that is
approximated by the box. Their implementations have template parameters
for the number type used for the interval bounds, for the fixed
dimension of the box, and for a policy class \cgalCite{cgal:a-mcdgp-01}
selecting among several solutions for providing the `id`-number.

The function signatures for the bipartite case look as follows. The
signatures for the complete case with the `box_self_intersection_d()`
function look the same except for the single iterator range.

\code{.cpp}
#include CGAL/box_intersection_d.h

template< class RandomAccessIterator1,
          class RandomAccessIterator2,
          class Callback >
void box_intersection_d(RandomAccessIterator1 begin1, RandomAccessIterator1 end1,
                        RandomAccessIterator2 begin2, RandomAccessIterator2 end2,
                        Callback callback, std::ptrdiff_t cutoff = 10,
                        Box_intersection_d::Topology topology = Box_intersection_d::CLOSED,
                        Box_intersection_d::Setting setting = Box_intersection_d::BIPARTITE);

template< class RandomAccessIterator1,
          class RandomAccessIterator2,
          class Callback, class BoxTraits >
void box_intersection_d(RandomAccessIterator1 begin1, RandomAccessIterator1 end1,
                        RandomAccessIterator2 begin2, RandomAccessIterator2 end2,
                        Callback callback, BoxTraits box_traits,
                        std::ptrdiff cutoff = 10,
                        Box_intersection_d::Topology topology = Box_intersection_d::CLOSED,
                        Box_intersection_d::Setting setting = Box_intersection_d::BIPARTITE);
\endcode

We provide an example using boxes of different types to detect proximity between points and segments.

\cgalExample{Box_intersection_d/boxes_with_different_types.cpp}

\section secboxintersectminimal Minimal Example for Intersecting Boxes

The box implementation provided with
`Box_intersection_d::Box_d<double,2>` has a dedicated
constructor for the \cgal bounding box type `Bbox_2`
(similar for dimension 3). We use this in our minimal example to
create easily nine two-dimensional `boxes` in a grid layout of \f$ 3
\times 3\f$ boxes. Additionally we pick the center box and the box in
the upper-right corner as our second box sequence `query`.

The default policy of the box type implements the `id`-number with
an explicit counter in the boxes, which is the default choice since it
always works, but it costs space that could potentially be avoided,
see the example in the next section. We use the `id`-number in our
callback function to report the result of the intersection algorithm.
The result will be that the first `query` box intersects all nine
`boxes` and the second `query` box intersects the four boxes
in the upper-right quadrant. See Section \ref secboxintersparams
for the change of the `topology` parameter and its effect.

\cgalExample{Box_intersection_d/minimal.cpp}

\section Box_intersection_dExample_1 Example for Finding Intersecting 3D Triangles

The conventional application of the axis-aligned box intersection
algorithm will start from complex geometry, here 3D triangles,
approximate them with their bounding box, compute the intersecting
pairs of boxes, and check only for those if the original triangles
intersect as well.

We start in the `main` function and create ten triangles with
endpoints chosen randomly in a cube \f$ [-1,+1)^3\f$. We store the
triangles in a vector called `triangles`.

Next we create a vector for the bounding boxes of the triangles called
`boxes`. For the boxes we choose the type
`Box_with_handle_d<double,3,Iterator>` that works nicely together
with the \cgal bounding boxes of type `Bbox_3`. In
addition, each box stores the iterator to the corresponding triangle.

The default policy of this box type uses for the `id`-number the
address of the value of the iterator, i.e., the address of the
triangle. This is a good choice that works correctly iff the boxes
have unique iterators, i.e., there is a one-to-one mapping between
boxes and approximated geometry, which is the case here. It saves us
the extra space that was needed for the explicit `id`-number in
the previous example.

We run the self intersection algorithm with the `report_inters()`
function as callback. This callback reports the intersecting boxes. It
uses the `handle` and the global `triangles` vector to
calculate the triangle numbers. Then it checks the triangles
themselves for intersection and reports if not only the boxes but also
the triangles intersect. We take some precautions before the
intersection test in order to avoid problems, although unlikely, with
degenerate triangles that we might have created with the random
process.

This example can be easily extended to test polyhedral surfaces of the
`Polyhedron_3` class for (self-) intersections. The main
difference are the numerous cases of incidences between triangles in
the polyhedral surface that should not be reported as intersections,
see the <TT>examples/Polyhedron/polyhedron_self_intersection.cpp</TT>
example program in the \cgal distribution.

\cgalExample{Box_intersection_d/triangle_self_intersect.cpp}

\section Box_intersection_dExample_2 Example for Using Pointers to Boxes

We modify the previous example, finding intersecting 3D triangles,
and add an additional vector `ptr` that stores pointers to the bounding
boxes, so that the intersection algorithm will work on a sequence of
pointers and not on a sequence of boxes. The change just affects the
preparation of the additional vector and the call of the box intersection
function. The box intersection function (actually its default traits
class) detects automatically that the value type of the iterators is a
pointer type and not a class type.

\code{.cpp}

// Create the corresponding vector of pointers to bounding boxes
std::vector<Box *> ptr;
for ( std::vector<Box>::iterator i = boxes.begin(); i != boxes.end(); ++i)
ptr.push_back( &*i);

// Run the self intersection algorithm with all defaults on the
// indirect pointers to bounding boxes. Avoids copying the boxes.
CGAL::box_self_intersection_d( ptr.begin(), ptr.end(), report_inters);

\endcode

In addition, the callback function `report_inters()` needs to be
changed to work with pointers to boxes. The full example program looks
as follows:

\cgalExample{Box_intersection_d/triangle_self_intersect_pointers.cpp}

A note on performance: The algorithm sorts and partitions the input
sequences. It is clearly costly to copy a large box compared to a
simple pointer. However, the algorithm benefits from memory locality
in the latter stages when it copies the boxes, while the pointers would
refer to boxes that become wildly scattered in memory. These two
effects, copying costs and memory locality, counteract each other. For
small box sizes, i.e., small dimension, memory locality wins and one
should work with boxes, while for larger box sizes one should work
with pointers. The exact threshold depends on the memory hierarchy
(caching) of the hardware platform and the size of the boxes, most
notably the type used to represent the box coordinates. A concrete
example; on a laptop with an Intel Mobile Pentium4 running at 1.80GHz
with 512KB cache and 254MB main memory under Linux this version with
pointers was 20% faster than the version above that copies the boxes
for 10000 boxes, but the picture reversed for 100000 boxes, where the
version above that copies the boxes becomes 300% faster.

Note that switching to the built-in type `float` is supported by
the box intersection algorithm, but the interfacing with the \cgal
bounding box `Bbox_3` would not be that easy. In particular,
just converting from the `double` to the `float`
representation incurs rounding that needs to be controlled properly,
otherwise the box might shrink and one might miss intersections.

\section secboxintersparams Example Using the Topology and the Cutoff Parameters

Boxes can be interpreted by the box intersection algorithm as closed
or as half-open boxes, see also Section \ref secboxintersdef. Closed
boxes support zero-width boxes and they can intersect at their
boundaries, while half-open boxes always have a positive volume and
they only intersect iff their interiors overlap. The choice between
closed or half-open boxes is selected with the `topology`
parameter and its two values:

<UL>
<LI>`Box_intersection_d::HALF_OPEN` and
<LI>`Box_intersection_d::CLOSED`.
</UL>

The example program uses a two-dimensional box with `int`
coordinates and `id`-numbers that are by default explicitly
stored. We create the same boxes as in the minimal example in
Section \ref secboxintersectminimal. We create a \f$ 3 \times 3\f$ grid
of `boxes`, and two boxes for the `query` sequence, namely the
box at the center and the box from the upper-right corner of the grid.

We write a more involved callback function object `Report` that
stores an output iterator and writes the `id`-number of the
box in the first argument to the output iterator. We also provide a
small helper function `report()` that simplifies the use of the function
object.

We call the box intersection algorithm twice; once for the default
`topology`, which is the closed box topology, and once for the
half-open box topology. We sort the resulting output for better
readability and verify its correctness with the `check1` and
`check2` data. For the closed box topology, the center box in
`query` intersects all `boxes`, and the upper-right box in
`query` intersects the four boxes of the upper-right quadrant in
`boxes`. Almost all intersections are with the box boundaries,
thus, for the half-open topology only one intersection remains per
`query` box, namely its corresponding box in `boxes`. So, the
output of the algorithm will be:

\verbatim
0 1 2 3 4 4 5 5 6 7 7 8 8
4 8
\endverbatim

For the second box intersection function call we have to specify the
`cutoff` parameter explicitly. See the
Section \ref secboxintersperformance below for a detailed
discussion.

\cgalExample{Box_intersection_d/box_grid.cpp}

\section secboxintersperformance Runtime Performance

The implemented algorithm is described in \cgalCite{cgal:ze-fsbi-02} as
version two. Its performance depends on a `cutoff` parameter.
When the size of both iterator ranges drops below the `cutoff`
parameter the function switches from the streamed segment-tree
algorithm to the two-way-scan algorithm, see \cgalCite{cgal:ze-fsbi-02}
for the details.

The streamed segment-tree algorithm needs \cgalBigO{n \log^d (n) + k}
worst-case running time and \cgalBigO{n} space, where \f$ n\f$ is the number of
boxes in both input sequences, \f$ d\f$ the (constant) dimension of the
boxes, and \f$ k\f$ the output complexity, i.e., the number of pairwise
intersections of the boxes. The two-way-scan algorithm needs \cgalBigO{n \log
(n) + l} worst-case running time and \cgalBigO{n} space, where \f$ l\f$ is the
number of pairwise overlapping intervals in one dimensions (the
dimension where the algorithm is used instead of the segment tree).
Note that \f$ l\f$ is not necessarily related to \f$ k\f$ and using the
two-way-scan algorithm is a heuristic.

Unfortunately, we have no general method to automatically determine an
optimal cutoff parameter, since it depends on the used hardware, the
runtime ratio between callback runtime and segment-tree runtime, and
of course the number of boxes to be checked and their distribution. In
cases where the callback runtime is dominant, it may be best to make
the threshold parameter small. Otherwise a `cutoff`\f$ =\sqrt{n}\f$ can
lead to acceptable results. For well distributed boxes the original
paper \cgalCite{cgal:ze-fsbi-02} gives optimal cutoffs in the thousands.
Anyway, for optimal runtime some experiments to compare different
cutoff parameters are recommended.

To demonstrate that box intersection can be done quite fast, different
box sequences are intersected in the range between 4 and 800000 boxes
total. We use three-dimensional default boxes of closed topology with
`float` coordinates and without additional data fields. The
algorithm works directly on the boxes, not on pointer to boxes. Each
box intersection is reported to an empty dummy callback.

For each box set, a near-optimal cutoff parameter is determined using
an adaptive approximation. The runtime required for streaming is
compared against usual scanning. Results on a Xeon 2.4GHz with 4GB
main memory can be seen in \cgalFigureRef{fig_benchmark}. For a small
number of boxes, pure scanning is still faster than streaming with
optimal cutoff, which would just delegate the box sets to the scanning
algorithm. As there are more and more boxes, the overhead becomes less
important.

\cgalFigureBegin{fig_benchmark,benchmark.png}
Runtime comparison between the scanning and the streaming algorithm.
\cgalFigureEnd

\section Box_intersection_dExample_3 Example Using a Custom Box Implementation

The example in the previous Section \ref secboxintersparams uses
an array to provide the coordinates and then creates another array for
the boxes. In the following example we write our own box class
`Box` that we can initialize directly with the four coordinates and
create the array of boxes directly. We also omit the explicitly stored
`id`-number and use the address of the box itself as
`id`-number. This works only if the boxes do not change their
position, i.e., we work with pointers to the boxes in the intersection
algorithm.

We follow with our own box class `Box` the
`BoxIntersectionBox_d` concept, which allows us to reuse the
default traits implementation, i.e., we can use the same default
function call to compute all intersections. See the example in the
next section for a self-written traits class. So, in principle, the
remainder of the example stays the same and we omit the part from the
previous example for brevity that illustrates the half-open box topology.

The requirements for the box implementation are best studied on
the reference manual page of `BoxIntersectionBox_d`. In a
nutshell, we have to define the type `NT` for the box coordinates
and the type `ID` for the `id`-number. Member functions
give access to the coordinates and the `id`-number. A static
member function returns the dimension.

\cgalExample{Box_intersection_d/custom_box_grid.cpp}

\section secbox_inters_example_proximity Example for Point Proximity Search with a Custom Traits Class

Given a set of 3D points, we want to find all pairs of points that are
less than a certain distance apart. We use the box intersection
algorithm to find good candidates, namely those that are less than
this specified distance apart in the \f$ L_\infty\f$ norm, which is a good
approximation of the Euclidean norm.

We use an unusual representation for the box, namely pointers to the 3D points
themselves. We implement a special box traits class that interprets
the point as a box of the dimensions \f$ [-\f$`eps`\f$ ,+\f$`eps`\f$ ]^3\f$
centered at this point. The value for `eps` is half the specified distance
from above, i.e., points are reported if their distance is smaller
than `2*eps`.

The requirements for the box traits class are best studied on
the reference manual page of  `BoxIntersectionTraits_d`. In a
nutshell, we have to define the type `NT` for the box coordinates,
the type `ID` for the `id`-number, and the type `Box_parameter`
similar to the box handle, here `Point_3*` since we work with the pointers.
All member functions in the traits class are static. Two functions give
access to the max and min coordinates that we compute from the point
coordinates plus or minus the `eps` value, respectively. For the
`id`-number function the address of the point itself is
sufficient, since the points stay stable. Another function
returns the dimension.

The `report` callback function computes than the Euclidean
distance and prints a message for points that are close enough.

Note that we need to reserve sufficient space in the `points`
vector to avoid reallocations while we create the `points` vector
and the `boxes` vector in parallel, since otherwise the
`points` vector might reallocate and invalidate all pointers
stored in the `boxes` so far.

\cgalExample{Box_intersection_d/proximity_custom_box_traits.cpp}

\section secbox_inters_example_polylines Example for Polyline Intersection Test

Given two polylines we want to know if they intersect. This implementation
creates a box for each segment of the polyline and creates two sets of boxes.
The callback throws an exception as soon as an intersection is detected.

\cgalExample{Box_intersection_d/box_d_do_intersect_polylines.cpp}

\section Box_intersection_dDesign Design and Implementation History

Lutz Kettner and Andreas Meyer implemented the algorithms starting
from the publication \cgalCite{cgal:ze-fsbi-02}. We had access to the
original C implementation of Afra Zomorodian, which helped clarifying
some questions, and we are grateful to the help of Afra Zomorodian in
answering our questions during his visit. We thank Steve Robbins for
an excellent review for this package. Steve Robbins provided an
independent and earlier implementation of this algorithm,
however, we learned too late about this implementation.

*/
} /* namespace CGAL */

---

### Box Intersection D Doc Box Intersection D PackageDescription (`Box_intersection_d/doc/Box_intersection_d/PackageDescription.txt`)

/// \defgroup PkgBoxIntersectionDRef Reference Manual
/// \defgroup PkgBoxIntersectionDConcepts Concepts
/// \ingroup PkgBoxIntersectionDRef

/// \defgroup PkgBoxIntersectionDEnums Enumerations
/// \ingroup PkgBoxIntersectionDRef

/// \defgroup PkgBoxIntersectionDClasses Classes
/// \ingroup PkgBoxIntersectionDRef

/// \defgroup PkgBoxIntersectionD_box_intersection_d CGAL::box_intersection_d()
/// \ingroup PkgBoxIntersectionDRef


/// \defgroup PkgBoxIntersectionD_box_intersection_all_pairs_d CGAL::box_intersection_all_pairs_d()
/// \ingroup PkgBoxIntersectionDRef

/// \defgroup PkgBoxIntersectionD_box_self_intersection_d CGAL::box_self_intersection_d()
/// \ingroup PkgBoxIntersectionDRef

/// \defgroup PkgBoxIntersectionD_box_self_intersection_all_pairs_d CGAL::box_self_intersection_all_pairs_d()
/// \ingroup PkgBoxIntersectionDRef
/*!
\addtogroup PkgBoxIntersectionDRef

\todo de-math and change D to d for the dimension

\cgalPkgDescriptionBegin{Intersecting Sequences of dD Iso-oriented Boxes,PkgBoxIntersectionD}
\cgalPkgPicture{box_inters-small.png}
\cgalPkgSummaryBegin
\cgalPkgAuthors{Lutz Kettner, Andreas Meyer, and Afra Zomorodian}
\cgalPkgDesc{An efficient algorithm for finding all intersecting pairs for large numbers of iso-oriented boxes, in order to apply a user defined callback on them.  Typically these boxes will be bounding boxes of more complicated geometries. The algorithm is useful for (self-) intersection tests of surfaces etc. }
\cgalPkgManuals{Chapter_Intersecting_Sequences_of_dD_Iso-oriented_Boxes,PkgBoxIntersectionDRef}
\cgalPkgSummaryEnd
\cgalPkgShortInfoBegin
\cgalPkgSince{3.1}
\cgalPkgBib{cgal:kmz-isiobd}
\cgalPkgLicense{\ref licensesGPL  "GPL"}
\cgalPkgDemo{CGAL Lab,CGALlab.zip}
\cgalPkgShortInfoEnd
\cgalPkgDescriptionEnd

\cgalClassifedRefPages

\cgalCRPSection{Concepts}
- `BoxIntersectionBox_d`
- `BoxIntersectionTraits_d`

\cgalCRPSection{Enumerations}
- `CGAL::Box_intersection_d::Setting`
- `CGAL::Box_intersection_d::Topology`

\cgalCRPSection{Classes}
- `CGAL::Box_intersection_d::Box_d<NT,int D,IdPolicy>`
- `CGAL::Box_intersection_d::Box_with_info_d<NT, int D, Info, IdPolicy>`
- `CGAL::Box_intersection_d::Box_with_handle_d<NT, int D, Handle, IdPolicy>`
- `CGAL::Box_intersection_d::Box_traits_d<BoxHandle>`

\cgalCRPSection{Functions}
- `CGAL::box_intersection_d`
- `CGAL::box_self_intersection_d`

- `CGAL::box_intersection_all_pairs_d`
- `CGAL::box_self_intersection_all_pairs_d`

*/

---

### Box Intersection D Doc Box Intersection D Examples (`Box_intersection_d/doc/Box_intersection_d/examples.txt`)

/*!
\example Box_intersection_d/box_grid.cpp
\example Box_intersection_d/custom_box_grid.cpp
\example Box_intersection_d/minimal.cpp
\example Box_intersection_d/progress.cpp
\example Box_intersection_d/minimal_self.cpp
\example Box_intersection_d/proximity_custom_box_traits.cpp
\example Box_intersection_d/triangle_self_intersect.cpp
\example Box_intersection_d/triangle_self_intersect_pointers.cpp
\example Box_intersection_d/box_d_do_intersect_polylines.cpp
\example Box_intersection_d/boxes_with_different_types.cpp
*/

---

### CGAL Ipelets Doc CGAL Ipelets CGAL Ipelets (`CGAL_ipelets/doc/CGAL_ipelets/CGAL_ipelets.txt`)

namespace CGAL {
/*!

\mainpage User Manual
\anchor Chapter_CGAL_Ipelets
\anchor chapcgalipelets
\cgalAutoToc
\author Olivier Devillers, S&eacute;bastien Loriot, and Sylvain Pion

\section CGAL_ipeletsIntroduction Introduction

The Ipe extensible drawing editor (<A HREF="https://ipe.otfried.org/">https://ipe.otfried.org/</A>) \cgalCite{schwarzkopf1995ede}, \cgalCite{ipe:man-09}
is a tool used by computational geometry researchers to produce 2D figures for inclusion in articles or presentations.
The extensible adjective sheds a light on an important feature:
the possibility for users to write small extensions (called <I>ipelets</I>)
to interface any algorithm with Ipe. This feature is especially interesting
to produce illustrations in a paper describing a new algorithm.
This package provides one class
that eases the writing of ipelets based on \cgal, reducing the needed knowledge of the API of Ipe.
This class is designed to fulfill most of the needs to implement an ipelet for a 2D \cgal algorithm.
In addition, this package comes with more than ten complete examples
of ipelets: alpha-shape, arrangements, Voronoi diagrams, convex hulls, Hilbert curve, k-order Delaunay,
2D mesh, Minkowski sum, polygon partition, random generators, triangulations \f$ \dots\f$

\section seccgal_ipelets CGAL Ipelets

The class `Ipelet_base` derives from the class `Ipelets` from Ipe
and has one template parameter indicating
which kernel must be used within the ipelet.
In practice, we recommend to use either `Exact_predicates_exact_constructions_kernel`
or `Exact_predicates_inexact_constructions_kernel`.

Two main methods are provided by the `Ipelet_base` class.
The first one, `read_active_objects` retrieves all
primitives selected in Ipe when calling an ipelet, and converts them into equivalent \cgal objects.
The second method, `draw_in_ipe` draws \cgal objects in the Ipe
window. These functions handle basic objects such as points, segments, polygons, circles and circular arcs.

The registration of an ipelet into Ipe can be done using the macro
`CGAL_IPELET`. `CGAL_IPELET(ipelet_class_name)`
must follow the definition of the ipelet class, in the same file source file.

\section CGAL_ipeletsExample Example

The following example shows how the class `Ipelet_base` can be used to easily
interface the \cgal 2D Delaunay triangulation with Ipe.

\cgalExample{CGAL_ipelets/simple_triangulation.cpp}

The ipelet should be compiled and placed in a directory where Ipe can find it.
These directories are listed in the "Show Configuration" entry of the "Help" menu of Ipe.
Along with the compiled ipelet, a LUA file must be created to load the ipelet in Ipe.
Below is an example of the LUA file that can be associated to the previous C++ ipelet.

\code
----------------------------------------------------------------------
-- Simple Triangulation ipelet description
----------------------------------------------------------------------

label = "Simple triangulation"

about = [[
This ipelet is an example of ipelet from the CGAL documentation. See www.cgal.org.
]]

-- this variable will store the C++ ipelet when it has been loaded
ipelet = false

function run(model, num)
  if not ipelet then ipelet = assert(ipe.Ipelet(dllname)) end
  model:runIpelet(methods[num].label, ipelet, num)
end

methods = {
  { label="Simple Triangulation" },
  { label="Help" },
}

----------------------------------------------------------------------
\endcode

Once both the compiled ipelet and the LUA file are in place, the ipelet can be called
from the "Ipelets" menu of Ipe.

\image html example.png
\image latex example.png

For more advanced information, we refer to the <a href="https://ipe.otfried.org/ipelib/ipelets.html">documentation of Ipe</a>.

\section CGAL_ipeletsInstallation Installation of the Demo Ipelets

Some working ipelets can be found within
the demo directory of this package. To install them you need
to go to the demo directory of the package and run cmake.
The compilation of these demo requires the source tree and the library of Ipe.
If your Ipe installation is not detected you need to set the cmake
variables `IPE_INCLUDE_DIR` and `IPE_LIBRARIES`. If you want
to install ipelets automatically (using `make install` for example)
you also need to set the cmake variable `IPELET_INSTALL_DIR`,
if the ipelet installation path has not already been detected.
These ipelets have been tested with the versions 6.0pre28 to 6.0pre32 of Ipe,
as well as with the version 7 (at least up to version 7.10).
These ipelets are a good starting point to design your own ipelet. For more details on how
to compile an ipelet, please refer to the Ipe manual.

Below is the list of ipelets provided by the demo:

\section Ipelets_list List of provided Ipelets

\subsection alpha_shapes_ipelet Alpha Shapes

The input selection must be a set of points or circles
(considered as weighted points).
The whole spectrum of critical alpha values are computed and a dialog box
allows to choose one.


\subsection arrangement_ipelet Arrangement

The input selection can feature segments, circles, and arcs of circles.
The selected primitives are split at intersection points and arcs and
circles are split at their x-extrema.

\subsection bbox_restriction_ipelet Bounding Box Restriction

The input selection can feature segments, circles and arcs of circles, and
at least two points.
The selected primitives are clipped to the bounding box of the set of
points selected.


\subsection circle_pencils_ipelet Pencils of Circles

The input selection must be three circles or points (considered as
zero radius circles).

<ul>
<li><b> Circle in pencil, orthogonal to one circle</b>
draws the circle orthogonal to the primary
selection belonging to the pencil defined by the two other circles.
<li><b> Circle orthogonal to three circles</b>
draws the circle orthogonal to the three selected circles.
</ul>

\subsection cone_spanners_ipelet Cone spanners

The input selection must be a set of points. The value of k is asked
in a dialog box.

<ul>
<li><b>Theta-k-graph:</b>
Draws a theta-graph with k cones
<li><b>Yao-k-graph:</b>
Draws a Yao-graph with k cones
<li><b>Half-theta-k-graph with even cones:</b>
Draws a half-theta-graph with the even of k cones.
<li><b>Half-Yao-k-graph with even cones:</b>
Draws a half-Yao-graph with the even of k cones.
<li><b>Half-theta-k-graph with odd cones:</b>
Draws a half-theta-graph with the odd of k cones.
<li><b>Half-Yao-k-graph with odd cones:</b>
Draws a half-Yao-graph with the odd of k cones.
<li><b>k cones:</b> For each selected point.
Draws the k cones around the point.
</ul>

\subsection diagrams_ipelet Diagrams
<ul>
<li><b> Voronoi:</b>
The input selection can feature points and segments. The Voronoi diagram
is computed and clipped to a box a bit larger than the selection.
The bisectors between a segment and its endpoints are drawn.
The Voronoi diagram partitions the plane depending on the closest
point or segment.
<li><b> Segment Voronoi skeleton:</b>
Same as the previous one, but the bisectors between a segment and its
endpoints are not drawn (the Voronoi region of the segment endpoints are
merged with that of the segment)
<li><b>Power diagram:</b>
The input selection must feature circles and points (zero radius circles). The power diagram
is computed and clipped to a box a bit larger than the selection.
The power diagram partitions the plane depending on the circle with smaller power.
<li><b> Apollonius:</b>
The input selection must feature circles and points (zero radius circles).
The Apollonius diagram is computed and clipped to a box a bit larger
than the selection.
The Apollonius diagram partitions the plane depending on the closest
circle (also called additively weighted Voronoi diagram).
</ul>

\subsection distance_ipelet Distance
The input selection must be two marks.
The distance between the two marks is output (for few seconds)
in the bottom of Ipe window. Can be computed in points, centimeters, or inches.
<ul>
<li><b> Distance between two marks (pts):</b>
<li><b> Distance between two marks (cm):</b>
<li><b> Distance between two marks (inch):</b>
</ul>


\subsection generator_ipelet Generators
A number of points to generate is asked in a dialog box.
<ul>
<li><b> Points in a disk</b>
generates random points in the selected circle.
 <li><b> Points on a grid</b>
generates a grid inside a square bounding the selection.
 <li><b> Points in a square</b>
generates random points inside a square bounding the selection.
 <li><b> Points on a convex hull</b>
generates a random convex polygon of given size  inside a square bounding the selection and
draw their convex hull.
 <li><b> Polygon</b>
generates a random simple polygon inside a square bounding the selection.
 <li><b> Segments in a square</b>
generates random line segments inside a square bounding the selection.
 <li><b> Circles (center in a square)</b>
generates random circles whose centers are inside a square bounding the selection.
</ul>

\subsection hilbert_sort_ipelet Hilbert Sort
The input selection must be a set of points.
<ul>
<li><b> Hilbert sorting curve, median policy</b>
splits the set of points in two at the median, alternatively in x and
y directions and draws the curve connecting the sorted points.
 <li><b> Hilbert sorting curve, middle policy</b>
splits the set of points in two at the middle, alternatively in x and
y directions and draws the curve connecting the sorted points.
</ul>

\subsection hull_ipelet Hulls
<ul>
 <li><b> Convex minimal:</b>
The input selection must feature points, segments or circles.
The convex hull of the selected primitive is drawn.
 <li><b>Crust:</b>
The input section must be a set of points.
The crust of the point set is drawn (curve reconstruction).
</ul>

\subsection hyperbolic_ipelet Hyperbolic
Tools for hyperbolic geometry in the Poincare disk model.

<ul>
 <li><b> Line through two points:</b>
The input selection must be the Poincare circle and two points inside the
circle. The hyperbolic line through the points is drawn.
 <li><b> Segment through two points:</b>
The input selection must be the Poincare circle and two points inside the
circle. The hyperbolic line segment through the points is drawn.
 <li><b> Bisector of two points:</b>
The input section must be the Poincare circle and two points inside the
circle. The hyperbolic bisector of the points is drawn.
 <li><b> Circle by center and point:</b>
The input selection must be the Poincare circle and two points inside the
circle, one of these points being the primary selection.
 The hyperbolic circle centered at the primary selection through the
 other point is drawn.
 <li><b> Circle center:</b>
The input selection must be the Poincare circle and another circle inside
the latter being the primary selection.
 The hyperbolic center of the primary selection is drawn.
</ul>

\subsection mesh_2_ipelet Mesh_2
The input selection must be a set of polygons defining a domain,
and a set of circles defining connected region that are not part
of the domains (holes).
A mesh of the domain is computed and drawn using the maximal edge
length provided asked in a dialog box.

\subsection minkowski_ipelet Minkowski Sum
<ul>
 <li><b>Minkowski Sum:</b>
The input selection must be two simple polygons.
The Minkowski sum of the two polygons is computed and drawn.
 <li><b>Polygon Offset:</b>
The input selection must be a circle and simple polygons.
The Minkowski sum of the polygons with the circle is computed and drawn.
</ul>

\subsection mst_ipelet Minimum Spanning Tree
The input selection must be a set of points. The Euclidean minimum spanning
tree of the points is computed and drawn.

\subsection nng_ipelet Nearest-neighbor graph
The input selection must be a set of points. The nearest-neighbor graph of the points is computed and drawn.

\subsection multi_delaunay_ipelet k Order Delaunay
The input selection must be a set of points.
The order k Voronoi diagram or its dual the order k Delaunay is drawn.
<ul>
 <li><b> Delaunay:</b>
Ordinary Delaunay triangulation.
 <li><b> Delaunay 2:</b>
Triangulation of middle of Delaunay edges.
 <li><b> Delaunay 3:</b>
Triangulation of barycenters of some triangles.
 <li><b> Delaunay n-1:</b>
Dual of farthest neighbor Voronoi diagram.
 <li><b> Delaunay k:</b>
k is asked in a dialog box.
 <li><b> Voronoi:</b>
Ordinary Voronoi diagram.
 <li><b> Voronoi 2:</b>
Order 2 Voronoi diagram.
 <li><b> Voronoi 3:</b>
Order 3 Voronoi diagram.
 <li><b> Voronoi n-1:</b>
Farthest neighbor Voronoi diagram.
 <li><b> Voronoi k:</b>
k is asked in a dialog box.
</ul>

\subsection multi_regular_ipelet k Order Regular
The input selection must be a set of points and circles.
The order k power diagram or its dual the order k regular triangulation is drawn.
<ul>
 <li><b>Regular:</b> Ordinary regular triangulation.
 <li><b>Regular 2:</b> Triangulation of middle of  edges
 of the regular triangulation.
 <li><b>Regular 3:</b>
Triangulation of barycenters of some triangles.
 <li><b>Regular n-1:</b>
Dual of farthest neighbor power diagram.
 <li><b>Regular k:</b>
k is asked in a dialog box.
 <li><b>Power Diagram:</b> Ordinary power diagram.
 <li><b>Power Diagram 2:</b> Order 2 power diagram.
 <li><b>Power Diagram 3:</b> Order 3 power diagram.
 <li><b>Power Diagram n-1:</b> Farthest neighbor power diagram.
 <li><b>Power Diagram k:</b>
k is asked in a dialog box.
</ul>

\subsection partition_ipelet Polygon Partition
The input selection must be simple polygons.
The polygons are divided using different algorithms.
<ul>
 <li><b> Y monotone partition:</b> Regions of the partition are \f$ y
 \f$ monotone
 <li><b> Greene's approx Convex Partition:</b> Regions of the
 partition are convex.
 <li><b> Approx Convex Partition:</b>Regions of the
 partition are convex.
 <li><b> Optimal Convex Partition:</b>Regions of the
 partition are convex and their number is minimized.
</ul>

\subsection pca_ipelet PCA
The input selection must be a set of points.
A line segment giving the principal direction of the selection is drawn.

\subsection skeleton_ipelet  Skeleton and Offset
The input selection must be a simple polygon.
The straight skeleton and associated offsets of the polygon are drawn.
 <ul>
<li><b> Interior skeleton</b> draws the interior skeleton.
 <li><b> Exterior skeleton</b> draws the exterior skeleton.
 <li><b> Interior offset</b>
 draws an interior offset using the value provided in the dialog box.
 <li><b> Exterior offset</b>
 draws an exterior offset using the value provided in the dialog box.
 <li><b> Interior offsets</b>
draws several equally spaced  interior offsets are drawn
using the value provided in the dialog box.
 <li><b> Exterior offsets</b>
draws several equally spaced exterior offsets using the value provided in the dialog box.
</ul>

\subsection triangulation_ipelet Triangulations
<ul>
 <li><b> Delaunay:</b>
The input selection must be a set of points. The Delaunay triangulation of the
 points is drawn.
 <li><b> Constrained Delaunay:</b>
The input selection must be a set of points and line segments. The Delaunay
 triangulation of the points and segment's endpoints that respects the constraints is drawn.
 <li><b>Conforming Delaunay:</b>
The input selection must be a set of points and line segments. Points are
 added so that the Delaunay of selected points, segment's endpoints,
 and added points respects the constraints. The triangulation  is drawn.
 <li><b> Conforming Gabriel:</b>
The input selection must be a set of points and line segments. Points are
 added so that the pieces of segments have Gabriel property (their
 diametral disk is empty). The Delaunay triangulation  is drawn.
 <li><b> Regular:</b>
The input selection must be a set of points and circles (weighted points). The
 regular triangulation (dual of power diagram) of the
 points and circle's centers is drawn.
</ul>

\section CGAL_ipeletsDesign Design and Implementation History

A first draft of the \cgal ipelets has been implemented during the
internship of Nicolas Carrez, in 2005, supervised by Olivier Devillers.
Since then, the ipelets have been rewritten and extended by Sebastien
Loriot as a stand-alone software with the help of Laurent Rineau.
Finally, an enhanced version has been formally contributed to \cgal in 2009
by Sebastien Loriot. Sylvain Pion has participated in the discussion
of the overall design, and contributed the Hilbert sort ipelet demo.
Olivier Devillers added the pencil of circles and hyperbolic geometry
ipelets in 2014.

*/
} /* namespace CGAL */

---

### CGAL Ipelets Doc CGAL Ipelets PackageDescription (`CGAL_ipelets/doc/CGAL_ipelets/PackageDescription.txt`)

/// \defgroup PkgCGALIpeletsRef Reference Manual
/*!
\addtogroup PkgCGALIpeletsRef
\cgalPkgDescriptionBegin{CGAL Ipelets,PkgCGALIpelets}
\cgalPkgPicture{ipeico.jpg}
\cgalPkgSummaryBegin
\cgalPkgAuthors{Olivier Devillers, Sébastien Loriot, and Sylvain Pion}
\cgalPkgDesc{This package provides  a generic framework to easily write ipelets (plug-in's) using \cgal for the Ipe extensible drawing editor.}
\cgalPkgManuals{Chapter_CGAL_Ipelets,PkgCGALIpeletsRef}
\cgalPkgSummaryEnd
\cgalPkgShortInfoBegin
\cgalPkgSince{3.5}
\cgalPkgBib{cgal:lp-gi}
\cgalPkgLicense{\ref licensesLGPL  "LGPL"}
\cgalPkgShortInfoEnd
\cgalPkgDescriptionEnd

\cgalClassifedRefPages

\cgalCRPSection{Classes}
- `CGAL::Ipelet_base<Kernel,int nbf>`

*/

---

### Circular Kernel 2 Doc Circular Kernel 2 Circular Kernel 2 (`Circular_kernel_2/doc/Circular_kernel_2/Circular_kernel_2.txt`)

namespace CGAL {
/*!

\mainpage User Manual
\anchor Chapter_2D_Circular_Geometry_Kernel
\cgalAutoToc

\authors Pedro Machado Manh&atilde;es de Castro, Sylvain Pion, and Monique Teillaud

\section Circular_kernel_2Introduction Introduction

The goal of the circular kernel is to offer to the user a large set of
functionalities on circles and circular arcs in the plane. All the
choices (interface, robustness, representation, and so on) made here
are consistent with the choices made in the \cgal kernel, for which we
refer the user to the 2D kernel manual.

In this first release, all functionalities necessary for computing an
arrangement of circular arcs and these line segments are
defined. Three traits classes are provided for the \cgal arrangement
package.

\section Circular_kernel_2Software Software Design

The design is done in such a way that the algebraic concepts and the
geometric concepts are clearly separated. `Circular_kernel_2`
has therefore two template parameters:
<UL>
<LI> the first parameter must model the \cgal
three dimensional `Kernel` concept. The circular kernel derives
from it, and it provides all elementary geometric objects like points,
lines, circles, and elementary functionality on them.
<LI> the second parameter is the algebraic kernel, which is
responsible for computations on polynomials and algebraic numbers. It
has to be a model of concept `AlgebraicKernelForCircles`. The
robustness of the package relies on the fact that the algebraic kernel
provides exact computations on algebraic objects.
</UL>

The circular kernel uses the extensibility scheme presented in the 2D
kernel manual (see Section \ref sectionextensiblekernel).
The types of `Kernel` are inherited
by the circular kernel and some types are taken from the
`AlgebraicKernelForCircles` parameter. Three new main geometric objects are
introduced by `Circular_kernel_2`: circular arcs, points of
circular arcs (used in particular for endpoints of arcs and
intersection points between arcs) and line segments whose endpoints
are points of this new type.

In fact, the circular kernel is documented as a concept, `CircularKernel`,
and two models are provided:
<UL>
<LI> `Circular_kernel_2<Kernel,AlgebraicKernelForCircles>`, the basic kernel,
<LI> and
a predefined filtered kernel `Exact_circular_kernel_2`,
that is based on similar techniques as
`Exact_predicates_exact_constructions_kernel`.
</UL>

\section Circular_kernel_2Examples Examples

The first example shows how to construct circles or circular arcs from
points, and how to compute intersections between them using the global
function.

\cgalExample{Circular_kernel_2/intersecting_arcs.cpp}

The following example shows how to use a functor of the kernel.

\cgalExample{Circular_kernel_2/functor_has_on_2.cpp}

\section Circular_kernel_2Design Design and Implementation History

The first pieces of prototype code were comparisons of algebraic
numbers of degree 2, written by Olivier Devillers
\cgalCite{cgal:dfmt-amafe-00},\cgalCite{cgal:dfmt-amafe-02}.

Some work was then done in the direction of a "kernel" for
\cgal.\cgalFootnote{Monique Teillaud, First Prototype of a \cgal Geometric Kernel with Circular Arcs, Technical Report ECG-TR-182203-01, 2002
Sylvain Pion and Monique Teillaud, Towards a \cgal-like kernel for curves, Technical Report ECG-TR-302206-01, 2003} and the first design emerged in
\cgalCite{cgal:ekptt-tock-04}.

The code of this package was initially written by Sylvain Pion and
Monique Teillaud who also wrote the manual. Athanasios Kakargias had
worked on a prototype version of this kernel in 2003. Julien
Hazebrouck participated in the implementation in July and August
2005. The contribution of Pedro Machado Manh&atilde;es de Castro in
summer 2006 improved significantly the efficiency of this kernel. He
also added more functionality in 2008.

This work was partially supported by the IST Programme of the EU as a
Shared-cost RTD (FET Open) Project under Contract No IST-2000-26473
(<A HREF="https://www-sop.inria.fr/prisme/ECG/">ECG</A> - Effective
Computational Geometry for Curves and Surfaces) and by the IST
Programme of the 6th Framework Programme of the EU as a STREP (FET
Open Scheme) Project under Contract No IST-006413
(ACS - Algorithms for Complex
Shapes).


@todo fix manual for operator>>

@todo manual filtered bbox kernel, ref counting

@todo manual orientation: NO (only when points have same delta, so don't document)

@todo clean manual AK (concepts like Polynomial_1_2, access to a() b() c() ?
used in solve to check that solutions are the same)

@todo rendre Bbox filtered kernel completement generique ->
        utilisation dans linear kernel aussi

@todo echecs de filtres

@todo voir make_x_monotone pour que ca retourne des arcs
(necessite bricolage de la traits car Arr_2 demande des Object)

@todo interface intersect avec plusieurs outputIt types (types de retour differents)

@todo --> a transferer dans linear kernel ?
        - unoriented equal (pb general orientation dans noyau cgal...)

@todo construct intersection for *arcs* should use solve or solve in range

@todo  done (?)

@todo memory leaks in Filtered_bbox_circular_kernel_2

@todo from Andreas:
  there are new statements in constructors having no corresponding
  delete statements.
  This concerns the files in the directory:
  CGAL-3.3.1/include/CGAL/Filtered_bbox_circular_kernel_2/...with_bbox_2.h
  It should be enough to add destructors and add conditional
  deletes.

@todo  Reading the code I think that the IO routines also don't
  do what they should do, namely computing new bboxes.


*/
} /* namespace CGAL */

---

### Circular Kernel 2 Doc Circular Kernel 2 PackageDescription (`Circular_kernel_2/doc/Circular_kernel_2/PackageDescription.txt`)

/// \defgroup PkgCircularKernel2Ref Reference Manual

/// \defgroup PkgCircularKernel2GeometricConcepts Geometric Concepts
/// \ingroup PkgCircularKernel2Ref


/// \defgroup PkgCircularKernel2GeometricClasses Geometric Kernel and Classes
/// \ingroup PkgCircularKernel2Ref


/// \defgroup PkgCircularKernel2GeometricFunctions Geometric Global Functions
/// \ingroup PkgCircularKernel2Ref


/// \defgroup PkgCircularKernel2AlgebraicConcepts Algebraic Concepts
/// \ingroup PkgCircularKernel2Ref


/// \defgroup PkgCircularKernel2AlgebraicClasses Algebraic Kernel and Classes
/// \ingroup PkgCircularKernel2Ref


/*!
\addtogroup PkgCircularKernel2Ref
\cgalPkgDescriptionBegin{2D Circular Geometry Kernel,PkgCircularKernel2}
\cgalPkgPicture{Boolean_operation_detail.png}
\cgalPkgSummaryBegin
\cgalPkgAuthors{Pedro Machado Manhães de Castro, Sylvain Pion, and Monique Teillaud}
\cgalPkgDesc{This package is an extension of the linear \cgal kernel. It offers functionalities on circles, circular arcs and line segments in the plane.  }
\cgalPkgManuals{Chapter_2D_Circular_Geometry_Kernel,PkgCircularKernel2Ref}
\cgalPkgSummaryEnd
\cgalPkgShortInfoBegin
\cgalPkgSince{3.2}
\cgalPkgBib{cgal:cpt-cgk2}
\cgalPkgLicense{\ref licensesGPL "GPL"}
\cgalPkgDemo{Arrangement of Circular Arcs,circular_kernel.zip}
\cgalPkgShortInfoEnd
\cgalPkgDescriptionEnd

\cgalClassifedRefPages

\cgalCRPSection{Geometric Concepts}

- `CircularKernel`

\cgalCRPSubsection{Functors}

- `CircularKernel::ConstructLine_2`
- `CircularKernel::ConstructCircle_2`
- `CircularKernel::ConstructCircularArcPoint_2`
- `CircularKernel::ConstructLineArc_2`
- `CircularKernel::ConstructCircularArc_2`
- `CircularKernel::ComputeCircularX_2`
- `CircularKernel::ComputeCircularY_2`
- `CircularKernel::ConstructCircularMinVertex_2`
- `CircularKernel::ConstructCircularMaxVertex_2`
- `CircularKernel::ConstructCircularSourceVertex_2`
- `CircularKernel::ConstructCircularTargetVertex_2`
- `CircularKernel::ConstructBbox_2`
- `CircularKernel::CompareX_2`
- `CircularKernel::CompareY_2`
- `CircularKernel::CompareXY_2`
- `CircularKernel::Equal_2`
- `CircularKernel::CompareYatX_2`
- `CircularKernel::CompareYtoRight_2`
- `CircularKernel::HasOn_2`
- `CircularKernel::DoOverlap_2`
- `CircularKernel::DoIntersect_2`
- `CircularKernel::BoundedSide_2`
- `CircularKernel::HasOnBoundedSide_2`
- `CircularKernel::HasOnUnboundedSide_2`
- `CircularKernel::InXRange_2`
- `CircularKernel::IsVertical_2`
- `CircularKernel::IsXMonotone_2`
- `CircularKernel::IsYMonotone_2`
- `CircularKernel::MakeXMonotone_2`
- `CircularKernel::MakeXYMonotone_2`
- `CircularKernel::Intersect_2`
- `CircularKernel::Split_2`
- `CircularKernel::GetEquation`

\cgalCRPSection{Geometric Kernels and Classes}

\cgalCRPSubsection{Kernels}

- `CGAL::Circular_kernel_2<Kernel,AlgebraicKernelForCircles>`
- `CGAL::Exact_circular_kernel_2`

\cgalCRPSubsection{Points}

- `CGAL::Circular_arc_point_2<CircularKernel>`

\cgalCRPSubsection{Arcs}

- `CGAL::Circular_arc_2<CircularKernel>`
- `CGAL::Line_arc_2<CircularKernel>`

\cgalCRPSection{Geometric Global Functions}

- \link compare_x_circular_grp `CGAL::compare_x()` \endlink
- \link compare_y_circular_grp `CGAL::compare_y()` \endlink
- \link compare_xy_circular_grp `CGAL::compare_xy()` \endlink
- \link compare_y_at_x_grp `CGAL::compare_y_at_x()` \endlink
- `CGAL::compare_y_to_right()`
- `CGAL::has_in_x_range()`
- `CGAL::has_on()`
- \link do_intersect_circular_grp `CGAL::do_intersect()` \endlink
- \link intersection_circular_grp `CGAL::intersection()` \endlink
- `CGAL::x_extremal_point()`
- `CGAL::y_extremal_point()`
- `CGAL::x_extremal_points()`
- `CGAL::y_extremal_points()`
- `CGAL::make_x_monotone()`
- `CGAL::make_xy_monotone()`

\cgalCRPSection{Algebraic Concepts}

- `AlgebraicKernelForCircles`

\cgalCRPSubsection{Functors}


- `AlgebraicKernelForCircles::ConstructPolynomial_1_2`
- `AlgebraicKernelForCircles::ConstructPolynomialForCircles_2_2`
- `AlgebraicKernelForCircles::CompareX`
- `AlgebraicKernelForCircles::CompareY`
- `AlgebraicKernelForCircles::CompareXY`
- `AlgebraicKernelForCircles::SignAt`
- `AlgebraicKernelForCircles::XCriticalPoints`
- `AlgebraicKernelForCircles::YCriticalPoints`
- `AlgebraicKernelForCircles::Solve`

\cgalCRPSection{Algebraic %Kernel and Classes}

\cgalCRPSubsection{%Kernel}

- `CGAL::Algebraic_kernel_for_circles_2_2<RT>`

\cgalCRPSubsection{Polynomials}

- `CGAL::Polynomial_1_2<RT>`
- `CGAL::Polynomial_for_circles_2_2<FT>`

\cgalCRPSubsection{Roots of Polynomials}

- `CGAL::Sqrt_extension<NT,ROOT>`
- `CGAL::Root_for_circles_2_2<FT>`
- `CGAL::Root_of_traits<RT>`


*/

---

### Circular Kernel 2 Doc Circular Kernel 2 Examples (`Circular_kernel_2/doc/Circular_kernel_2/examples.txt`)

/*!
\example Circular_kernel_2/intersecting_arcs.cpp
\example Circular_kernel_2/functor_has_on_2.cpp
*/

---

### Circular Kernel 3 Doc Circular Kernel 3 Circular Kernel 3 (`Circular_kernel_3/doc/Circular_kernel_3/Circular_kernel_3.txt`)

namespace CGAL {
/*!

\mainpage User Manual
\anchor Chapter_3D_Spherical_Geometry_Kernel
\anchor chaptersphericalkernel

\authors Pedro Machado Manh&atilde;es de Castro, Fr&eacute;d&eacute;ric Cazals, S&eacute;bastien Loriot, and Monique Teillaud

\section Circular_kernel_3Introduction Introduction

The goal of the 3D spherical kernel is to offer to the user a large
set of functionalities on spheres, circles and circular arcs, in the 3D
space or restricted on a given sphere. These functionalities require
computing on algebraic numbers,
which motivates the creation of a new kernel concept extending the
\cgal `Kernel` concept, that is restricted to objects
and functionality in a `FieldNumberType`.

All the choices (interface, robustness, representation, and so on)
made here are consistent with the choices made in the \cgal kernel,
for which we refer the user to the \ref chapterkernel23 "2D and 3D Linear Kernel").

\section sectionSKobjects Spherical Kernel Objects

New main geometric objects are introduced by `Spherical_kernel_3`:
circular arcs (model of `SphericalKernel::CircularArc_3`), points
of circular arcs (model of `SphericalKernel::CircularArcPoint_3`),
and line segments (model of `SphericalKernel::LineArc_3`) whose
endpoints are points of this new type.

`SphericalKernel::CircularArcPoint_3` is used in particular for
endpoints of arcs and intersection points between spheres, circles or
arcs. The coordinates of these points are algebraic numbers of degree
two. Therefore, general predicates offered by the `Kernel` on
`Point_3`, which have coordinates in a `FieldNumberType`,
would require heavy algebraic computations in algebraic extensions
of higher degrees and thus are not provided on
them, which explains the need for a new point type.

A consistent set of predicates and constructions is offered on these
new types.

<b>General Functionalities</b>

The spherical kernel currently implements a set of
fundamental functionalities like intersection, comparisons, inclusion,
etc. More might be provided in the future, as long as only algebraic
numbers of degree two are used.

<b>Functionalities Relative to a Sphere</b>

The interface of the underlying objects is extended by providing
additional operations that make sense only if the objects are
considered on the same sphere. For example, the result of the comparison of the
cylindrical or spherical coordinates of two points is well-defined
only when looking at them on a given common sphere. The presentation
of these operations requires the following definitions:

<I>Coordinate system.</I>
Let consider a sphere with center `c` and radius `r`. Using
the %Cartesian frame centered at `c`, we define a cylindrical
coordinate system \f$ (\theta,z)\f$ on that sphere, with \f$ \theta \in \left[
0,2\pi \right)\f$ and \f$ z \in \left[ -r,r \right]\f$. \f$ \theta\f$ is given
in radian and measured in the \f$ xy\f$-plane around the \f$ z\f$-axis, starting
from \f$ x>0\f$, \f$ y=0\f$. The \f$ z\f$-extremal points of a sphere are its North
and South poles defined as \f$ (\theta,r)\f$ and \f$ (\theta,-r)\f$
respectively, for any value of \f$ \theta\f$. Observe that each point on
the sphere different from a pole corresponds to a unique pair
\f$ (\theta,z)\f$.

<I>Definition of a meridian.</I>
Given a sphere and its associated cylindrical coordinate system, a meridian of that
sphere is a circular arc consisting of the points having the same theta-coordinate
(the poles are the end points).
A plane containing the two poles of that sphere defines two meridians, one on each side
of the line passing through the poles. A vector \f$ M\f$ whose direction is different from that of the latter
line defines a unique meridian on that sphere. The plane of that meridian is defined by the
direction of \f$ M\f$ and the two poles. The sense of \f$ M\f$ disambiguates the choice among the
pair of meridians thus defined.
On \cgalFigureRef{figdefmeridian}, the normal vectors \f$ n_0\f$ and \f$ n_1\f$ define
two meridians of \f$ S\f$: the circular arcs \f$ A_0\f$ and \f$ A_1\f$ respectively.

\cgalFigureBegin{figdefmeridian,def_meridian.png}
Definition of two meridians on \f$ S\f$, a sphere of center \f$
c\f$. The intersection of the plane \f$ P\f$ (passing through the two
poles of \f$ S\f$) and the sphere \f$ S\f$ is a circle. The two poles
of \f$ S\f$ split that circle into two circular arcs \f$ A_0\f$ and
\f$ A_1\f$, each being a meridian of \f$ S\f$. The \f$
\theta\f$-coordinates of meridians \f$ A_0\f$ and \f$ A_1\f$ are \f$
\theta_0\f$ and \f$ \theta_1= \theta_0 + \pi\f$ respectively.
\cgalFigureEnd

<I>Types of circles on a sphere.</I>
Given a sphere, a circle on that sphere is termed
<I>polar</I> if it goes through only one pole, <I>bipolar</I> if
it goes through the two poles of that sphere and <I>threaded</I> if
it separates the sphere into two connected components, each
containing one pole. Any other circle is termed <I>normal</I>. These
definitions are illustrated on \cgalFigureRef{figdefcircles}.

\cgalFigureBegin{figdefcircles,def_circles_extreme_pt.png}
The four types of circles on a sphere. Black dots are the \f$ \theta\f$-extremal points.
\cgalFigureEnd

<I>\f$ \theta\f$-extremal points.</I>
Given a sphere one has:
a <I>\f$ \theta\f$-extremal point</I> of a normal circle is a point of
tangency between the circle and a meridian anchored at the poles of
that sphere. Each normal circle defines two such points;
the \f$ \theta\f$-extremal point of a polar circle is the pole the circle
goes through. No such point is defined on a bipolar or a threaded
circle.
These definitions are illustrated on \cgalFigureRef{figdefcircles}.
Notice that the \f$ \theta\f$-extremal points should not be confused with
the endpoints of an arbitrary arc on a sphere.

The \f$ \theta\f$-coordinate of a \f$ \theta\f$-extremal point of a normal
circle on a sphere is well defined.
For a polar circle on a sphere, the plane containing the two poles and which is
tangent to that circle contains two different meridians. The
\f$ \theta\f$-values of these meridians are the two \f$ \theta\f$-coordinates
associated to the same \f$ \theta\f$-extremal point of a polar circle.

<I>\f$ \theta\f$-monotone circular arcs.</I>
An arc on a sphere is said to be <I>\f$ \theta\f$-monotone</I> if any meridian
on that sphere intersects that arc in at most one point. With this definition, a
circular arc on a threaded circle is always \f$ \theta\f$-monotone, and an
arc on a polar or normal circle is \f$ \theta\f$-monotone if it does not
contain a \f$ \theta\f$-extremal point, unless it is an endpoint. No such
arc is defined on a bipolar circle.

\section Circular_kernel_3Software Software Design

The design of `Spherical_kernel_3` is similar to the design of
`Circular_kernel_2` (see Chapter \ref Chapter_2D_Circular_Geometry_Kernel
"2D Circular Geometry Kernel").

It has two template parameters:
<UL>
<LI> the first parameter must model the \cgal
three dimensional `Kernel` concept. The spherical kernel derives
from it, and it provides all elementary geometric objects like points,
lines, spheres, circles and elementary functionality on them.
<LI> the second parameter is the algebraic kernel, which is
responsible for computations on polynomials and algebraic numbers. It
must model the concept `AlgebraicKernelForSpheres`. The
robustness of the package relies on the fact that the algebraic kernel
provides exact computations on algebraic objects.
</UL>

The 3D spherical kernel uses the extensibility scheme presented in the
kernel manual (see Section \ref sectionextensiblekernel "Extensible Kernel").
The types of `Kernel` are inherited by the 3D spherical kernel and some
types are taken from the `AlgebraicKernelForSpheres`
parameter. `Spherical_kernel_3` introduces new geometric objects
as mentioned in Section \ref sectionSKobjects.

In fact, the spherical kernel is documented as a concept,
`SphericalKernel` and two models are provided:
<UL>
<LI> `Spherical_kernel_3<Kernel,AlgebraicKernelForSpheres>`, the basic kernel,
<LI> and a predefined kernel `Exact_spherical_kernel_3`.
</UL>

\section Circular_kernel_3Examples Examples

The first example shows how to construct spheres and compute
intersections on them using the global function.

\cgalExample{Circular_kernel_3/intersecting_spheres.cpp}

The second example illustrates the use of a functor.

\cgalExample{Circular_kernel_3/functor_has_on_3.cpp}

The third example illustrates the use of a functor on objects on the
same sphere. The intersection points of two circles on
the same sphere are computed and their cylindrical coordinates are
then compared.

\cgalExample{Circular_kernel_3/functor_compare_theta_3.cpp}

\section Circular_kernel_3Design Design and Implementation History

This package follows the design of the package
\ref Chapter_2D_Circular_Geometry_Kernel "2D Circular Geometry Kernel").

Julien Hazebrouck and Damien Leroy participated in a first
prototype.

The first version of the package was co-authored by Pedro Machado
Manh&atilde;es de Castro and Monique Teillaud, and integrated in CGAL
3.4. Fr&eacute;d&eacute;ric Cazals and S&eacute;bastien Loriot extended the
package by providing functionalities restricted on a given sphere
\cgalCite{cclt-dc3sk-08}.

Sylvain Pion is acknowledged for helpful discussions.

This work was partially supported by the IST Programme of the 6th
Framework Programme of the EU as a STREP (FET Open Scheme) Project
under Contract No IST-006413 (ACS -
Algorithms for Complex Shapes).

*/
} /* namespace CGAL */

---

### Circular Kernel 3 Doc Circular Kernel 3 PackageDescription (`Circular_kernel_3/doc/Circular_kernel_3/PackageDescription.txt`)

/// \defgroup PkgCircularKernel3Ref Reference Manual

/// \defgroup PkgCircularKernel3GeometricConcepts Geometric Concepts
/// \ingroup PkgCircularKernel3Ref

/// \defgroup PkgCircularKernel3GeometricClasses Geometric Kernel and Classes
/// \ingroup PkgCircularKernel3Ref


/// \defgroup PkgCircularKernel3GeometricFunctions Geometric Global Functions
/// \ingroup PkgCircularKernel3Ref


/// \defgroup PkgCircularKernel3AlgebraicConcepts Algebraic Concepts
/// \ingroup PkgCircularKernel3Ref


/// \defgroup PkgCircularKernel3AlgebraicClasses Algebraic Kernel and Classes
/// \ingroup PkgCircularKernel3Ref

/*!
\addtogroup PkgCircularKernel3Ref
\cgalPkgDescriptionBegin{3D Spherical Geometry Kernel,PkgCircularKernel3}
\cgalPkgPicture{segment_sphere_intersection_detail.png}
\cgalPkgSummaryBegin
\cgalPkgAuthors{Pedro Machado Manhães de Castro, Frédéric Cazals, Sébastien Loriot, and Monique Teillaud}
\cgalPkgDesc{This package is an extension of the linear \cgal %Kernel. It offers functionalities on spheres, circles, circular arcs and line segments, in the 3D space or restricted on a reference sphere.}
\cgalPkgManuals{Chapter_3D_Spherical_Geometry_Kernel,PkgCircularKernel3Ref}
\cgalPkgSummaryEnd
\cgalPkgShortInfoBegin
\cgalPkgSince{3.4}
\cgalPkgBib{cgal:cclt-sgk3}
\cgalPkgLicense{\ref licensesGPL "GPL"}
\cgalPkgShortInfoEnd
\cgalPkgDescriptionEnd

\cgalClassifedRefPages

\cgalCRPSection{Geometric Concepts}

- `SphericalKernel`

\cgalCRPSubsection{Object Types}

- `SphericalKernel::CircularArc_3`
- `SphericalKernel::CircularArcPoint_3`
- `SphericalKernel::LineArc_3`

\cgalCRPSubsection{Functors}

- `SphericalKernel::ConstructPlane_3`
- `SphericalKernel::ConstructSphere_3`
- `SphericalKernel::ConstructLine_3`
- `SphericalKernel::ConstructCircle_3`
- `SphericalKernel::ConstructCircularArcPoint_3`
- `SphericalKernel::ConstructLineArc_3`
- `SphericalKernel::ConstructCircularArc_3`
- `SphericalKernel::ConstructCircularMinVertex_3`
- `SphericalKernel::ConstructCircularMaxVertex_3`
- `SphericalKernel::ConstructCircularSourceVertex_3`
- `SphericalKernel::ConstructCircularTargetVertex_3`
- `SphericalKernel::ConstructBbox_3`
- `SphericalKernel::CompareX_3`
- `SphericalKernel::CompareY_3`
- `SphericalKernel::CompareZ_3`
- `SphericalKernel::CompareXY_3`
- `SphericalKernel::CompareXYZ_3`
- `SphericalKernel::CompareTheta_3`
- `SphericalKernel::CompareThetaZ_3`
- `SphericalKernel::CompareZAtTheta_3`
- `SphericalKernel::CompareZToRight_3`
- `SphericalKernel::Equal_3`
- `SphericalKernel::HasOn_3`
- `SphericalKernel::DoOverlap_3`
- `SphericalKernel::DoIntersect_3`
- `SphericalKernel::IsThetaMonotone_3`
- `SphericalKernel::BoundedSide_3`
- `SphericalKernel::HasOnBoundedSide_3`
- `SphericalKernel::HasOnUnboundedSide_3`
- `SphericalKernel::Intersect_3`
- `SphericalKernel::Split_3`
- `SphericalKernel::MakeThetaMonotone_3`
- `SphericalKernel::ComputeCircularX_3`
- `SphericalKernel::ComputeCircularY_3`
- `SphericalKernel::ComputeCircularZ_3`
- `SphericalKernel::ComputeApproximateSquaredLength_3`
- `SphericalKernel::ComputeApproximateAngle_3`
- `SphericalKernel::GetEquation`

\cgalCRPSection{Geometric Kernels and Classes}

\cgalCRPSubsection{Kernels}

- `CGAL::Spherical_kernel_3<Kernel,AlgebraicKernelForSpheres>`
- `CGAL::Exact_spherical_kernel_3`

\cgalCRPSubsection{Points}

- `CGAL::Circular_arc_point_3<SphericalKernel>`

\cgalCRPSubsection{Arcs}

- `CGAL::Line_arc_3<SphericalKernel>`
- `CGAL::Circular_arc_3<SphericalKernel>`

\cgalCRPSection{Constants and Enumerations}

- `CGAL::Circle_type`

\cgalCRPSection{Geometric Global Functions}

- \link compare_x_spherical_grp `CGAL::compare_x()` \endlink
- \link compare_y_spherical_grp `CGAL::compare_y()` \endlink
- \link compare_z_spherical_grp `CGAL::compare_z()` \endlink
- \link compare_xy_spherical_grp `CGAL::compare_xy()` \endlink
- \link compare_xyz_spherical_grp `CGAL::compare_xyz()` \endlink
- `CGAL::compare_theta()`
- `CGAL::compare_theta_z()`
- `CGAL::is_theta_monotone()`
- `CGAL::classify()`
- `CGAL::x_extremal_point()`
- `CGAL::y_extremal_point()`
- `CGAL::z_extremal_point()`
- `CGAL::theta_extremal_point()`
- `CGAL::x_extremal_points()`
- `CGAL::y_extremal_points()`
- `CGAL::z_extremal_points()`
- `CGAL::theta_extremal_points()`
- \link do_intersect_grp `CGAL::do_intersect()` \endlink
- \link intersection_grp `CGAL::intersection()` \endlink

\cgalCRPSection{Algebraic Concepts}

- `AlgebraicKernelForSpheres`

\cgalCRPSubsection{Functors}

- `AlgebraicKernelForSpheres::ConstructPolynomial_1_3`
- `AlgebraicKernelForSpheres::ConstructPolynomialForSpheres_2_3`
- `AlgebraicKernelForSpheres::ConstructPolynomialsForLines_3`
- `AlgebraicKernelForSpheres::CompareX`
- `AlgebraicKernelForSpheres::CompareY`
- `AlgebraicKernelForSpheres::CompareZ`
- `AlgebraicKernelForSpheres::CompareXY`
- `AlgebraicKernelForSpheres::CompareXYZ`
- `AlgebraicKernelForSpheres::SignAt`
- `AlgebraicKernelForSpheres::XCriticalPoints`
- `AlgebraicKernelForSpheres::YCriticalPoints`
- `AlgebraicKernelForSpheres::ZCriticalPoints`
- `AlgebraicKernelForSpheres::Solve`

\cgalCRPSection{Algebraic %Kernel and Classes}

\cgalCRPSubsection{%Kernel}

- `CGAL::Algebraic_kernel_for_spheres_2_3<RT>`

\cgalCRPSubsection{Polynomials}

- `CGAL::Polynomial_1_3<RT>`
- `CGAL::Polynomial_for_spheres_2_3<FT>`
- `CGAL::Polynomials_for_lines_3<FT>`

\cgalCRPSubsection{Roots of Polynomials}

- `CGAL::Sqrt_extension<NT,ROOT>`
- `CGAL::Root_for_spheres_2_3<RT>`
- `CGAL::Root_of_traits<RT>`


*/

---

### Circular Kernel 3 Doc Circular Kernel 3 Examples (`Circular_kernel_3/doc/Circular_kernel_3/examples.txt`)

/*!
\example Circular_kernel_3/intersecting_spheres.cpp
\example Circular_kernel_3/functor_has_on_3.cpp
\example Circular_kernel_3/functor_compare_theta_3.cpp
*/

---

### Circulator Doc Circulator Circulator (`Circulator/doc/Circulator/Circulator.txt`)

namespace CGAL {
/*!

\mainpage User Manual
\anchor Chapter_Handles_Ranges_and_Circulators
\anchor chapterCirculators

\cgalAutoToc
\authors Olivier Devillers, Lutz Kettner, Sylvain Pion, Michael Seel, and Mariette Yvinec

\section CirculatorHandles Handles

Most data structures in \cgal use the concept of `Handle` in their user
interface to refer to the elements they store. This concept describes what is
sometimes called a trivial iterator. A `Handle` is akin to a pointer to
an object providing the dereference operator `operator*()` and member
access `operator->()` but no increment or decrement operators like
iterators. A `Handle` is intended to be used whenever the referenced
object is not part of a logical sequence.

<b>Model for a handle</b> A simple pointer `T*`, an iterator or a circulator with value type
`T`, are also handles.

\section CirculatorRanges Ranges

Most data structures in \cgal use the concept of an iterator range. The
`Range` and `ConstRange` concepts encapsulate the access to the first
and the past-the-end iterators of an iterator range. STL containers are models
of `Range`. The Boost.Range library provides good support around this
concept as well.

\section circulatorsCirculators Circulators

An introduction to the concept of circulators is given here. A couple
of adaptors are presented that convert between iterators and
circulators. Some useful functions for circulators follow. This
chapter concludes with a discussion of the design decisions taken. For
the full description of the circulator requirements, the provided base
classes, the circulator tags, and the support for generic algorithms
that work for iterators as well as for circulators please refer to the
reference pages. Note that circulators are not part of \stl, but of \cgal.

\subsection sectionIntroduction Introduction

The concept of iterators in \stl is tailored for linear
sequences \cgalCite{cgal:ansi-is14882-98}, \cgalCite{cgal:ms-strg-96}. In contrast, circular
sequences occur naturally in many combinatorial and geometric
structures. Examples are polyhedral surfaces and planar maps, where
the edges emanating from a vertex or the edges around a facet form a
circular sequence.

Since circular sequences do not allow for efficient iterators, we have
introduced the new concept of <I>circulators</I>. They share most of
the requirements of iterators, while the main difference is the lack
of a past-the-end position in the sequence. Appropriate adaptors are
provided between iterators and circulators to integrate circulators
smoothly into the framework of \stl. An example of a generic `contains` function illustrates the use of circulators. As usual for
circular structures, a `do`-`while` loop is preferable, such
that for the specific input, `c == d`, all elements in the
sequence are reached.

\code{.cpp}
template <class Circulator, class T>
bool contains( Circulator c, Circulator d, const T& value) {
  if (c != 0) {
    do {
      if (*c == value)
        return true;
    } while (++c != d);
  }
  return false;
}
\endcode

Three circulator categories are defined: forward, bidirectional and
random-access circulators. Given a circulator `c`, the operation
`*c` denotes the item the circulator refers to. The operation `++c` advances the circulator by one item and `-c` steps a
bidirectional circulator one item backwards. For random-access
circulators `c+n` advances the circulator `n` steps. Two
circulators can be compared for equality.

Circulators have a different notion of reachability and ranges than
iterators. A circulator `d` is called <I>reachable</I> from a
circulator `c` if `c` can be made equal to `d` with
finitely many applications of the operator `++`. Due to the
circularity of the sequence this is always true if both circulators
refer to items of the same sequence. In particular, `c` is always
reachable from `c`. Given two circulators `c` and `d`, the
range `[c,d)` denotes all circulators obtained by starting with
`c` and advancing `c` until `d` is reached, but does not
include `d`, for `d != c`. So far it is the same
range definition as for iterators. The difference lies in the use of
`[c,c)` to denote all items in the circular sequence, whereas for
an iterator `i` the range `[i,i)` denotes the empty range. As
long as `c != d` the range `[c,d)` behaves like an iterator
range and could be used in \stl algorithms. For circulators however,
an additional test `c == nullptr` is required that returns true if
and only if the circular sequence is empty. As for
\cpp, we recommend the use of 0 instead of `nullptr`.

Besides the conceptual cleanness, the main reason for inventing a new
concept with a similar intent as iterators is efficiency. An iterator
is supposed to be a light-weight object - merely a pointer and a
single indirection to advance the iterator. Although iterators could
be written for circular sequences, we do not know of an efficient
solution. The missing past-the-end situation in circular sequences can
be solved with an arbitrary sentinel in the cyclic order, but this
would destroy the natural symmetry in the structure (which is in
itself a bad idea) and additional bookkeeping in the items and
checking in the iterator advance method reduces efficiency. Another
solution may use more bookkeeping in the iterator, e.g. with a start
item, a current item, and a kind of winding-number that is zero for
the `begin()`-iterator and one for the past-the-end
situation\cgalFootnote{This is currently implemented as the adaptor class which provides a pair of iterators for a given circulator.}. We have introduced the concept of circulators
that allows light-weight implementations and the \cgal support
library provides adaptor classes that convert between iterators and
circulators (with the corresponding penalty in efficiency), so as to
integrate this new concept into the framework of \stl.

A serious design problem is the slight change of the semantic for
circulator ranges as compared to iterator ranges. Since this semantic
is defined by the intuitive operators `++` and `==`, which we
would like to keep for circulators as well, circulator ranges can be
used in \stl algorithms. This is in itself a useful feature, if there
would not be the definition of a full range `[c, c)` that
an \stl algorithm will treat as an empty range. However, the
likelihood of a mistake may be overestimated, since for a container
`C` supporting circulators there is no `end()` member
function, and an expression such as `std::sort( C.begin(),
C.end())` will fail. It is easy to distinguish iterators and
circulators at compile time, which allows for generic algorithms
supporting both as arguments. It is also possible to protect
algorithms against inappropriate arguments using the same technique,
see the reference pages for circulators, specifically the
`Assert_iterator()` and `is_empty_range()` functions.

\anchor sectionCirculatorWarning
\attention Please note that the definition of a range is different
from that of iterators. An interface of a data structure must declare
whether it works with iterators, circulators, or both. \stl
algorithms always specify only iterators in their interfaces. A range
`[c, d)` of circulators used in an interface for iterators
will work as expected as long as `c != d`. A range `[c, c)` will be
interpreted as the empty range like for iterators,
which is different than the full range that it should denote for
circulators.

\subsection sectionCirculatorAdaptor Adaptors Between Iterators and Circulators

Algorithms working on iterator ranges can not be applied to circulator
ranges in full generality, only to subranges as pointed out in the
previous section. The following adaptors
convert circulators to iterators and vice versa (with the unavoidable
space and time penalty) to reestablish this generality.


- `Container_from_circulator` is a container-like class with iterators built from a circulator
- `Circulator_from_iterator` is a circulator over a range of two iterators
- `Circulator_from_container` is a circulator for a container


The following example applies the generic `std::reverse()` algorithm
from \stl to a sequence given by a bidirectional circulator `c`.
It uses the `Container_from_circulator` adaptor.

\code{.cpp}
Circulator c; // c must be at least bidirectional.
CGAL::Container_from_circulator<Circulator> container(c);
std::reverse( container.begin(), container.end());
\endcode

Another example defines a circulator `c` for a vector of
`int`'s. However, since there are no elements in the vector, the
circulator denotes an empty sequence. If there were elements in the
vector, the circulator would implement a random access modulus the
size of the sequence.

\code{.cpp}
std::vector<int> v;
typedef CGAL::Circulator_from_iterator< std::vector<int>::iterator > Circulator;
Circulator c( v.begin(), v.end());
\endcode

\subsection sectionCirculatorFunctions Functions on Circulators

Several functions deal with circulators and circulator ranges. The type
`C` denotes a circulator. The type `IC` denotes either a circulator
or an iterator. More on algorithms that work with circulators as well with
iterators can be found in the reference pages.

\code{.cpp}
C c, d;
IC ic1, ic2;

circulator_size(c);          // size of the sequence reachable by c
circulator_distance(c, d);   // number of elements in the range [c, d)
iterator_distance(ic1, ic2); // number of elements in the range [ic2, ic1)
is_empty_range(ic1, ic2);    // test the range [ic2, ic1) for emptiness
\endcode

*/
} /* namespace CGAL */

---

### Circulator Doc Circulator PackageDescription (`Circulator/doc/Circulator/PackageDescription.txt`)

/// \defgroup PkgHandlesAndCirculatorsRef Reference Manual
/// \defgroup PkgHandlesAndCirculatorsConcepts Concepts
/// \ingroup PkgHandlesAndCirculatorsRef


/// \defgroup PkgHandlesAndCirculatorsAdapter Adapters for Iterators and Containers
/// \ingroup PkgHandlesAndCirculatorsRef


/// \defgroup PkgHandlesAndCirculatorsFunctions Functions
/// \ingroup PkgHandlesAndCirculatorsRef

/// \defgroup PkgHandlesAndCirculatorsTags Compile Time Tags
/// \ingroup PkgHandlesAndCirculatorsRef

/// \defgroup PkgHandlesAndCirculatorsAssert Assertions
/// \ingroup PkgHandlesAndCirculatorsRef

/// \defgroup PkgHandlesAndCirculatorsBaseClasses Base Classes
/// \ingroup PkgHandlesAndCirculatorsRef


/*!
\addtogroup PkgHandlesAndCirculatorsRef
\cgalPkgDescriptionBegin{Handles and Circulators,PkgHandlesAndCirculators}
\cgalPkgPicture{circulator.png}
\cgalPkgSummaryBegin
\cgalPkgAuthors{Olivier Devillers, Lutz Kettner, Sylvain Pion, Michael Seel, and Mariette Yvinec}
\cgalPkgDesc{This package describes handles and circulators. They are related to iterators. Handles allow to dereference but neither to increment nor to decrement. Circulators have no notion of past-the-end, and they are used in \cgal whenever we have cyclic structures. }
\cgalPkgManuals{Chapter_Handles_Ranges_and_Circulators,PkgHandlesAndCirculatorsRef}
\cgalPkgSummaryEnd
\cgalPkgShortInfoBegin
\cgalPkgSince{1.0}
\cgalPkgBib{cgal:dksy-hc}
\cgalPkgLicense{\ref licensesLGPL  "LGPL"}
\cgalPkgShortInfoEnd
\cgalPkgDescriptionEnd

The concept of iterators in the \stl is tailored for linear sequences.

\cgal extends this in several directions.  First, it supports the notion
of `Handle` (also sometimes referred to as the trivial iterator) which is
used to document that no traversal operation is needed, only reference to an
element.  It also uses the `Range` and `ConstRange` concepts which
encapsulates the access to both the first and the past-the-end iterators of an
iterator range.

Besides linear sequences, circular sequences also occur naturally in many combinatorial
and geometric structures. Examples are polyhedral surfaces and planar
maps, where the edges emanating from a vertex or the edges around a
facet form a circular sequence.

We provide several functions, classes and macros to assist in working
with circulators: distance computation, adaptor classes converting
between circulators and iterators, base classes to ease the implementation
of circulators, and support for generic algorithms that work with
circulators as well as with iterators.

\cgalClassifedRefPages

\cgalCRPSection{Concepts}
- `Handle`
- `Range`
- `ConstRange`
- `Circulator`
- `ForwardCirculator`
- `BidirectionalCirculator`
- `RandomAccessCirculator`

\cgalCRPSection{Classes}
- `CGAL::Container_from_circulator<C>`
- `CGAL::Circulator_from_iterator<I>`
- `CGAL::Circulator_from_container<C>`
- \link CGAL::Circulator_from_container `CGAL::Const_circulator_from_container<C>` \endlink

- `CGAL::Circulator_tag`
- `CGAL::Iterator_tag`
- `CGAL::Forward_circulator_tag`
- `CGAL::Bidirectional_circulator_tag`
- `CGAL::Random_access_circulator_tag`

- `CGAL::Circulator_base`
- `CGAL::Forward_circulator_base`
- `CGAL::Bidirectional_circulator_base`
- `CGAL::Random_access_circulator_base`

- `CGAL::Circulator_traits<C>`

*/

---

### Circulator Doc Circulator Examples (`Circulator/doc/Circulator/examples.txt`)

/*!
\example Circulator/circulator_prog1.cpp
\example Circulator/circulator_prog2.cpp
\example Circulator/circulator_prog3.cpp
*/

---

### Classification Doc Classification Classification (`Classification/doc/Classification/Classification.txt`)

namespace CGAL {
/*!

\mainpage User Manual
\anchor Chapter_Classification
\cgalAutoToc
\authors Simon Giraudot, Florent Lafarge

This component implements the algorithm described in \cgalCite{cgal:lm-clscm-12} (section 2), generalized to handle different types of data, multiple features and multiple labels. It classifies a data set into a user-defined set of labels, such as _ground_, _vegetation_ and _buildings_. A flexible API is provided so that users can classify any type of data which they can index and for which they can compute relevant features, compute their own local features on the input data set and define their own labels.

\section Classification_Organization Package Organization

%Classification of data sets is achieved as follows (see \cgalFigureRef{Classification_organization_fig}):

- some analysis is performed on the input data set;
- features are computed based on this analysis;
- a set of labels (for example: _ground_, _building_, _vegetation_) is defined by the user;
- a classifier is defined and trained: from the set of values taken by the features at an input item, it measures the likelihood of this item to belong to one label or another;
- classification is computed itemwise using the classifier;
- additional regularization can be used by smoothing either locally or globally through a _graph cut_ \cgalCite{Boykov2001FastApproximate} approach.

\cgalFigureBegin{Classification_organization_fig,organization.svg}
Organization of the package.
\cgalFigureEnd

This package is designed to be easily extended by users: more specifically, features and labels can be defined by users to handle any data they need to classify.

Currently, \cgal provides data structures to handle classification of point sets, surface meshes and clusters.

\section Classification_structures Common Data Structures

\subsection Classification_labels Label Set

A label represents how an item should be classified, for example: _vegetation_, _building_, _road_, etc. In \cgal, a label has a name, an index (in a label set), a standard index (for example, the index of the label in the ASPRS standard) and a color. It is simply identified by a [Label_handle](@ref CGAL::Classification::Label_handle). Note that names, standard indices and colors are not used for identification: two labels in the same set can have the same name, standard index and color but not the same handle.

If labels are initialized with their names only, standard indices and colors can be deduced in some cases (see [Label_set::add()](@ref CGAL::Classification::Label_set::add)).

The following code snippet shows how to add labels to the classification object:

\snippet Classification/example_classification.cpp Labels

\subsection Classification_features Feature Set

Features are defined as scalar fields that associate each input item with a specific value. Note that in order to limit memory consumption, we use the type `float` for these scalar values (as well as for every floating point value in this package). A feature has a name and is identified by a [Feature_handle](@ref CGAL::Classification::Feature_handle).

The computation of features and their addition to the feature set is done in a single step using the [Feature_set::add<Feature>()](@ref CGAL::Classification::Feature_set::add) method. If \cgal was linked with \ref thirdpartyTBB, features can be computed in parallel (see below).

\cgal provides some predefined features (see \ref Classification_point_sets for example). In the following code snippet, a subset of these predefined features are instantiated (in parallel if \ref thirdpartyTBB is available). Note that all the predefined features can also be automatically generated in multiple scales (see \ref Classification_point_sets for example).

\snippet Classification/example_classification.cpp Features

Users may want to define their own features, especially if the input data set comes with additional properties that were not anticipated by \cgal. A user-defined feature must inherit from [Feature_base](@ref CGAL::Classification::Feature_base) and provide a method [value()](@ref CGAL::Classification::Feature_base::value) that associates a scalar value to each input item.

The following example shows how to define a feature that discriminates
points that lie inside a 2D box from the others:

\snippet Classification/example_feature.cpp Feature

This feature can then be instantiated from the feature set the same way as the others:

\snippet Classification/example_feature.cpp Addition

\section Classification_structures_specialized Specialized Data Structures

%Classification is based on the computation of local features. These features can take advantage of shared data structures that are precomputed and stored separately. Both these features and the underlying data structures depend on the type of data that needs to be classified. \cgal provides data structures to classify point sets, surface meshes and clusters.

\subsection Classification_point_sets Point Set Classification

\cgal provides the following structures:

- [Point_set_neighborhood](@ref CGAL::Classification::Point_set_neighborhood) stores spatial searching structures and provides adapted queries for points;
- [Local_eigen_analysis](@ref CGAL::Classification::Local_eigen_analysis) precomputes covariance matrices on local neighborhoods of points and stores the associated eigenvectors and eigenvalues;
- [Planimetric_grid](@ref CGAL::Classification::Planimetric_grid) is a 2D grid used for digital terrain modeling.

Most of these data structures depend on a scale parameter. \cgal provides a method to estimate the average spacing based on a number of neighbors (see [CGAL::compute_average_spacing()](@ref compute_average_spacing)), which usually provides satisfying results in the absence of noise. In the presence of noise, [CGAL::estimate_global_range_scale()](@ref estimate_global_range_scale) provides an estimation of the smallest scale such that the point set has the local dimension of a surface (this method is both robust to noise and outliers, see \ref Classification_sowf_result).

The eigen analysis can be used to estimate normals. Note however that this analysis (based on Principal Component Analysis) might not be robust to a high level of noise. \cgal also provides more robust normal estimation functions (see for example [CGAL::jet_estimate_normals()](@ref jet_estimate_normals)).

The following code snippet shows how to instantiate such data structures from an input PLY point set (the [full example](@ref Classification_example_general) is given at the end of the manual).

\snippet Classification/example_classification.cpp Analysis

\cgal provides some predefined features:

- [Distance_to_plane](@ref CGAL::Classification::Feature::Distance_to_plane) measures how far away a point is from a locally estimated plane;
- [Eigenvalue](@ref CGAL::Classification::Feature::Eigenvalue) measures one of the three local eigenvalues;
- [Elevation](@ref CGAL::Classification::Feature::Elevation) computes the local distance to an estimation of the ground;
- [Height_above](@ref CGAL::Classification::Feature::Elevation) computes the distance between the local highest point and the point;
- [Height_below](@ref CGAL::Classification::Feature::Elevation) computes the distance between the point and the local lowest point;
- [Vertical_dispersion](@ref CGAL::Classification::Feature::Vertical_dispersion) computes how noisy the point set is on a local Z-cylinder;
- [Vertical_range](@ref CGAL::Classification::Feature::Elevation) computes the distance between the local highest and lowest points;
- [Verticality](@ref CGAL::Classification::Feature::Verticality) compares the local normal vector to the vertical vector.

These features are designed for point sets but can easily be used with surface meshes as well (see \ref Classification_meshes). For more details about how these different features can help to identify one label or the other, please refer to their associated reference manual pages.

In addition, if the input data set has additional properties, these can also be used as features. For example, \cgal provides the following features:

- [Color_channel](@ref CGAL::Classification::Feature::Color_channel) uses input color information if available;
- [Echo_scatter](@ref CGAL::Classification::Feature::Echo_scatter) uses the number of returns (echo) provided by most LIDAR scanners if available;
- [Simple_feature](@ref CGAL::Classification::Feature::Simple_feature) uses any property map applicable to the input range and whose value type is castable to `float` (useful if an additional property of the input set should be used as is, for example an `intensity` measurement).

Users commonly want to use all predefined features to get the best result possible. \cgal provides a class [Point_set_feature_generator](@ref CGAL::Classification::Point_set_feature_generator)  that performs the following operations:

- it estimates the smallest relevant scale;
- it generates all needed analysis structures and provides access to them;
- it generates all possible features (among all the \cgal predefined ones) based on which property maps are available (they use colors if available, etc.).

Multiple scales that are sequentially larger can be used to increase the quality of the results \cgalCite{cgal:hws-fsso3-16}.

Note that using this class in order to generate features is not mandatory, as features and data structures can all be handled by hand. It is mainly provided to make the specific case of point sets simpler to handle. Users can still add their own features within their feature set.

Some data structure instantiated by the generator will be used by feature: for this reason, the generator should be instantiated _within the same scope_ as the feature set and should not be deleted before the feature set.

The following snippet shows how to use the point set feature generator:

\snippet Classification/example_generation_and_training.cpp Generator

\cgalFigureBegin{Classification_point_set_fig,point_set.png}
Example of point set classification (left: input, right: output). _Ground_ is grey, _roofs_ are orange, _vegetation_ is green.
\cgalFigureEnd

\subsection Classification_meshes Mesh Classification

%Classification of mesh is performed by considering the face of a mesh as an atomic element that should be assign one label or another. Some structures such as neighborhood or Eigen analysis are significantly different from their equivalent for point sets; other data structures from point sets can be directly used by viewing the mesh as a point set through the use of a property map that associates each face with a representative point.

Hereafter, a _mesh_ refers to a model of `FaceListGraph`.

\cgal provides the following structures:

- [Face_descriptor_to_center_of_mass_map](@ref CGAL::Classification::Face_descriptor_to_center_of_mass_map) is a property map that takes the face of a mesh as key type and returns the `CGAL::Point_3` located at the center of mass of the face. It is useful to apply point set structures and features to surface meshes;
- [Face_descriptor_to_face_descriptor_with_bbox_map](@ref CGAL::Classification::Face_descriptor_to_face_descriptor_with_bbox_map) is a property map that takes the face of a mesh as key type and returns the same face along with its bounding box as a value type. It is useful to call `CGAL::Classification::classify_with_graphcut()` which requires objects that provide a `bbox()` method (see \ref Classification_classification_functions);
- [Mesh_neighborhood](@ref CGAL::Classification::Mesh_neighborhood) provides adapted queries for surface meshes;
- [Local_eigen_analysis](@ref CGAL::Classification::Local_eigen_analysis) precomputes covariance matrices on local neighborhoods of triangles and stores the associated eigenvectors and eigenvalues (it is the same object as for point sets called with a different named constructor);
- [Planimetric_grid](@ref CGAL::Classification::Planimetric_grid) is the 2D grid used for digital terrain modeling of point sets, it can be used with meshes through [Face_descriptor_to_center_of_mass_map](@ref CGAL::Classification::Face_descriptor_to_center_of_mass_map).

The point set features can be used for mesh classification as well:

- [Eigenvalue](@ref CGAL::Classification::Feature::Eigenvalue) takes the [Local_eigen_analysis](@ref CGAL::Classification::Local_eigen_analysis) object computed on faces as input;
- the other ones are computed by considering the mesh as a point set.

Similarly to [Point_set_feature_generator](@ref CGAL::Classification::Point_set_feature_generator), \cgal provides a class [Mesh_feature_generator](@ref CGAL::Classification::Mesh_feature_generator) that estimates the smallest scale automatically and computes all predefined features on several scales. As for point sets, using this class in order to generate features is not mandatory, as features and data structures can all be handled by hand. It is mainly provided to make the specific case of meshes simpler to handle. Users can still add their own features within their feature set.

The following snippet shows how to use the mesh feature generator:

\snippet Classification/example_mesh_classification.cpp Generator

The [full example](@ref Classification_example_mesh) is given at the end of the manual.

\cgalFigureBegin{Classification_mesh_fig,mesh.png}
Example of mesh classification (left: input, right: output). _Ground_ is grey, _roofs_ are orange, _vegetation_ is green.
\cgalFigureEnd

\subsection Classification_clusters Cluster Classification

Classifying clusters of items instead of raw sets of items can have several advantages:

- if the data set is very large, using clusters can drastically decrease the complexity and thus the need for computation time and memory;
- clusters are more complex objects than raw items (isolated points or triangles of a mesh) and thus provide additional information (size of cluster, spatial consistency, etc.);
- by construction, the output classification is less noisy (if all points of a facade are in the same cluster, then they are guaranteed to all be classified in the same label).

For example, when dealing with urban scenes that typically contain large planar sections, it may be more efficient to first detect planes (with `CGAL::Shape_detection::Region_growing` or `CGAL::Shape_detection::Efficient_RANSAC` for example) and then to classify each subset of points belonging to a specific plane as clusters.

\cgal provides some tools to classify clusters:

- the class `CGAL::Classification::Cluster` can be used to represent a cluster of items (points, for example);
- the function `CGAL::Classification::create_clusters_from_indices()` takes indices over items as input (for example, shape indices taken from shape detection) and generates one cluster per index.

The following snippet shows how to create classification clusters from a shape detection algorithm ([Region Growing](@ref CGAL::Shape_detection::Region_growing)):

\snippet Classification/example_cluster_classification.cpp Cluster

The class [Local_eigen_analysis](@ref CGAL::Classification::Local_eigen_analysis) can also take point clusters as input:

\snippet Classification/example_cluster_classification.cpp Eigen

As clusters are based on simple items, users can compute cluster features based on statistics over the itemwise features:

- [Cluster_mean_of_feature](@ref CGAL::Classification::Feature::Cluster_mean_of_feature) computes, for a cluster, the mean value of an itemwise feature over the inliers of this cluster;
- [Cluster_variance_of_feature](@ref CGAL::Classification::Feature::Cluster_variance_of_feature) computes, for a cluster, the variance of an itemwise feature over the inliers of this cluster.

Some additional features are provided specifically for clusters:

- [Cluster_size](@ref CGAL::Classification::Feature::Cluster_size) uses the number of items in a cluster;
- [Cluster_vertical_extent](@ref CGAL::Classification::Feature::Cluster_vertical_extent) computes the length of the smallest interval
on the `Z` axis that contains all the items of a cluster;
- [Eigenvalue](@ref CGAL::Classification::Feature::Eigenvalue), similarly to point sets and meshes, can use the [Local_eigen_analysis](@ref CGAL::Classification::Local_eigen_analysis) object computed on clusters.

The following snippet shows, from a pointwise feature set, how to generate the statistical features from a pointwise feature set (along with these latest cluster features):

\snippet Classification/example_cluster_classification.cpp Features

The [full example](@ref Classification_example_cluster) is given at the end of the manual.

\cgalFigureBegin{Classification_cluster_fig,clusters.png}
Example of cluster classification mesh (left: input, middle: clusters computed from region growing, right: output). _Ground_ is grey, _roofs_ are orange, _vegetation_ is green, points not assigned to a cluster are _black_.
\cgalFigureEnd

\section Classification_classifiers Classifiers

%Classification relies on a classifier: this classifier is an object that, from the set of values taken by the features at an input item, computes the probability that an input item belongs to one label or another. A model of the concept `CGAL::Classification::Classifier` must take the index of an input item and store the probability associated to each label in a vector. If a classifier returns the value 1 for a pair of label and input item, it means that this item belongs to this label with certainty; values close to 0 mean that this item is not likely to belong to this label.

\cgal provides three models for this concept, [ETHZ::Random_forest_classifier](@ref CGAL::Classification::ETHZ::Random_forest_classifier), [OpenCV::Random_forest_classifier](@ref CGAL::Classification::OpenCV::Random_forest_classifier), and [Sum_of_weighted_features_classifier](@ref CGAL::Classification::Sum_of_weighted_features_classifier).

\note Currently, [ETHZ::Random_forest_classifier](@ref CGAL::Classification::ETHZ::Random_forest_classifier)
is the best classifier available in \cgal and we strongly advise users
to use it.

To perform classification based on four classifiers, please refer to \ref Classification_classification_functions.

\subsection Classification_ETHZ_random_forest ETHZ Random Forest

\cgal provides [ETHZ::Random_forest_classifier](@ref CGAL::Classification::ETHZ::Random_forest_classifier),
a classifier based on the Random Forest Template Library developed by
Stefan Walk at ETH Zurich \cgalCite{cgal:w-erftl-14} (the library is
distributed under the MIT license and is included with the \cgal release,
the user does not have to install anything more). This classifier uses
a ground truth training set to construct several decision trees that
are then used to assign a label to each input item.

This classifier cannot be set up by hand and requires a ground truth
training set. The training algorithm is fast but usually requires a
high number of inliers. The training algorithm uses more memory at
runtime and the configuration files are larger than those produced by
[Sum_of_weighted_features_classifier](@ref CGAL::Classification::Sum_of_weighted_features_classifier), but the
output quality is usually significantly better, especially in the
cases where many labels are used (more than five).

An [example](\ref Classification_example_ethz_random_forest) shows how to
use this classifier. For more details about the algorithm, please refer
to README provided in the [ETH Zurich's code archive](https://ethz.ch/content/dam/ethz/special-interest/baug/igp/photogrammetry-remote-sensing-dam/documents/sourcecode-and-datasets/Random%20Forest/rforest.zip).

\subsubsection Classification_ETHZ_random_forest_deprecated Deprecated IO

The IO functions of this classifier were changed in \cgal
5.2. Configurations generated from previous versions are not valid
anymore and should be converted first as shown in the following example:

\cgalExample{Classification/example_deprecated_conversion.cpp}

\subsection Classification_OpenCV_random_forest OpenCV Random Forest

The second classifier is [OpenCV::Random_forest_classifier](@ref CGAL::Classification::OpenCV::Random_forest_classifier).
It uses the \ref thirdpartyOpenCV library, more specifically the
[Random Trees](https://docs.opencv.org/2.4/modules/ml/doc/random_trees.html)
package.

Note that this classifier usually produces results with a lower
quality than [ETHZ::Random_forest_classifier](@ref CGAL::Classification::ETHZ::Random_forest_classifier).
It is provided for the sake of completeness and for testing purposes,
but if you are not sure what to use, we advise using the ETHZ Random
Forest instead.

An [example](\ref Classification_example_opencv_random_forest) shows how to
use this classifier. For more details about the algorithm, please refer
to [the official documentation](https://docs.opencv.org/2.4/modules/ml/doc/random_trees.html)
of OpenCV.

\subsection Classification_sowf Sum of Weighted Features

This latest classifier defines the following attributes:

- a weight applied to each feature;
- an effect applied to each pair of feature and label.

For each label, the classifier computes an energy as a sum of features normalized with both their weight and the effect they have on this specific label.

The main advantage of this classifier is that it can be set up by hand. Nevertheless, it also embeds a training algorithm.

\subsubsection Classification_sowf_weights_effects Weights and Effects

Each feature is assigned a weight that measures its strength with respect to the other features.

Each pair of feature and label is assigned an effect that can either be:

- [FAVORING](@ref CGAL::Classification::Sum_of_weighted_features_classifier::FAVORING): the label is favored by high values of the feature;
- [NEUTRAL](@ref CGAL::Classification::Sum_of_weighted_features_classifier::NEUTRAL): the label is not affected by the feature;
- [PENALIZING](@ref CGAL::Classification::Sum_of_weighted_features_classifier::PENALIZING): the label is favored by low values of the feature.

For example, _vegetation_ is expected to have a high distance to plane and have a color close to green (if colors are available); _facades_ have a low distance to plane and a low verticality; etc.

Let \f$x=(x_i)_{i=1..N}\f$ be a potential classification result with \f$N\f$ the number of input items and \f$x_i\f$ the class of the \f$i^{th}\f$ item (for example: _vegetation_, _ground_, etc.). Let \f$f_j(i)\f$ be the raw value of the \f$j^{th}\f$ feature at the \f$i^{th}\f$ item and \f$w_j\f$ be the weight of this feature. We define the normalized value \f$F_j(x_i) \in [0:1]\f$ of the \f$j^{th}\f$ feature at the \f$i^{th}\f$ item as follows:

\f{eqnarray*}{
    F_j(x_i) = & (1 - \min(\max(0,\frac{f_j(i)}{w_j}), 1)) & \mbox{if } f_j \mbox{ favors } x_i \\
    & 0.5 & \mbox{if } f_j \mbox{ is neutral for } x_i \\
    & \min(\max(0,\frac{f_j(i)}{w_j}), 1) & \mbox{if } f_j \mbox{ penalizes } x_i
    \f}

The itemwise energy measures the coherence of the label \f$x_i\f$ at
the \f$i^{th}\f$ item and is defined as:

\f[
  E_{di}(x_i) = \sum_{j = 1..N_f} F_j(x_i)
\f]


The following code snippet shows how to define the weights and effects of features and labels:

\snippet Classification/example_classification.cpp Weights

\subsubsection Classification_sowf_training Training

Each feature has a specific weight and each pair of feature-label has a specific effect. This means that the number of parameters to set up can quickly explode: if 6 features are used to classify between 4 labels, 30 parameters have to be set up (6 weights + 6x4 feature-label relationships).

Though it is possible to set them up one by one, \cgal also provides a method [train()](@ref CGAL::Classification::Sum_of_weighted_features_classifier::train)  that requires a small set of ground truth items provided by users. More specifically, users must provide, for each label they want to classify, a set of known inliers among the input data set (for example, selecting one roof, one tree and one section of the ground). The training algorithm works as follows:

- for each feature, a range of weights is tested: the effect each feature has on each label is estimated. For a given weight, if a feature has the same effect on each label, it is non-relevant for classification. The range of weights such that the feature is relevant is estimated;

- for each feature, uniformly picked weight values are tested and their effects are estimated;

- each inlier provided by the user is classified using this set of weights and effects;

- the mean intersection-over-union (see @ref Classification_evaluation) is used to evaluate the quality of this set of weights and effects;

- the same mechanism is repeated until all features' ranges have been tested. Weights are only changed one by one, the other ones are kept to the values that gave the latest best score.

This usually converges to a satisfying solution (see \cgalFigureRef{Classification_trainer_fig}). The number of trials is user defined, set to 300 by default. Using at least 10 times the number of features is advised (for example, at least 300 iterations if 30 features are used). If the solution is not satisfying, more inliers can be selected, for example, in a region that the user identifies as misclassified with the current configuration. The training algorithm keeps, as initialization, the best weights found at the previous round and carries on trying new weights by taking new inliers into account.

\cgalFigureBegin{Classification_trainer_fig,classif_training.png}
Example of evolution of the mean intersection-over-union. The purple curve is the score computed at the current iteration, green curve is the best score found so far.
\cgalFigureEnd

\subsubsection Classification_sowf_result Result

\cgalFigureRef{Classification_sowf_result_fig} shows an example of output on a defect-laden point set. The accuracy on this example is 0.97 with a mean intersection-over-union of 0.85 (see section \ref Classification_evaluation).

\cgalFigureBegin{Classification_sowf_result_fig,noise_outliers.png}
Example of classification on a point set with medium noise and outliers (left: input, right: output). _Ground_ is orange, _roofs_ are pink, _vegetation_ is green. Outliers are classified with an additional label _outlier_ in black.
\cgalFigureEnd

\section Classification_classification_functions Classification Functions

%Classification is performed by minimizing an energy over the input data set that may include regularization. \cgal provides three different methods for classification, ranging from high speed / low quality to low speed / high quality:

- `CGAL::Classification::classify()`
- `CGAL::Classification::classify_with_local_smoothing()`
- `CGAL::Classification::classify_with_graphcut()`

On a point set of 3 millions of points, the first method takes about 4 seconds, the second about 40 seconds and the third about 2 minutes.

\cgalFigureBegin{Classification_image,classif.png}
Top-Left: input point set. Top-Right: raw output classification represented by a set of colors (_ground_ is orange, _facades_ are blue, _roofs_ are pink and _vegetation_ is green). Bottom-Left: output classification using local smoothing. Bottom-Right: output classification using graphcut.
\cgalFigureEnd


Mathematical details are provided hereafter.

\subsection Classification_classify Raw Classification

- `CGAL::Classification::classify()`: this is the fastest method
that provides acceptable but usually noisy results (see Figure
\cgalFigureRef{Classification_image}, top-right).

Let \f$x=(x_i)_{i=1..N}\f$ be a potential classification result with \f$N\f$ the number of input items and \f$x_i\f$ the label of the \f$i^{th}\f$ item (for example: _vegetation_, _ground_, etc.). The classification is performed by minimizing the following energy:

\f[
  E(x) = \sum_{i = 1..N} E_{di}(x_i)
\f]

This energy is a sum of itemwise energies provided by the classifier and involves no regularization.

The following snippet shows how to classify points based on a label
set and a classifier. The result is stored in `label_indices`,
following the same order as the input set and providing for each point
the index (in the label set) of its assigned label.

\snippet Classification/example_classification.cpp Classify

\subsection Classification_smoothing Local Regularization

- `CGAL::Classification::classify_with_local_smoothing()`: this
method is a tradeoff between quality and efficiency (see Figure
\cgalFigureRef{Classification_image}, bottom-left). The minimized
energy is defined as follows:


\f[
  E(x) = \sum_{i = 1..N} E_{si}(x_i)
\f]

The energy \f$E_{si}(x_i)\f$ is defined on a small local neighborhood
\f$Nb(i)\f$ of the \f$i^{th}\f$ item (including itself):

\f[
  E_{si}(x_i) = \frac{\sum_{k \in Nb(i)} E_{di}(x_k)}{\left| Nb(i) \right|}
\f]

This allows to eliminate local noisy variations of assigned
labels. Increasing the size of the neighborhood
increases the noise reduction at the cost of higher computation times.

The following snippet shows how to classify points using local
smoothing by providing a model of `CGAL::Classification::NeighborQuery`.

\snippet Classification/example_classification.cpp Smoothing

\subsection Classification_graphcut Global Regularization (Graph Cut)

- `CGAL::Classification::classify_with_graphcut()`: this method
offers the best quality but requires longer computation time (see
\cgalFigureRef{Classification_image}, bottom-right). The
total energy that is minimized is the sum of the partial data term
\f$E_{di}(x_i)\f$ and of a pairwise interaction energy defined by the
standard Potts model \cgalCite{cgal:l-mrfmi-09} :

\f[
  E(x) = \sum_{i = 1..N} E_{di}(x_i) + \gamma \sum_{i \sim j} \mathbf{1}_{x_i \neq x_j}
\f]

where \f$\gamma>0\f$ is the parameter of the Potts model that
quantifies the strength of the regularization, \f$i \sim j\f$
represents the pairs of neighboring items and
\f$\mathbf{1}_{\{.\}}\f$ the characteristic function.

A _graph cut_ based algorithm (alpha expansion) is used to quickly reach
an approximate solution close to the global optimum of this energy.

This method allows to consistently segment the input data set in
piecewise constant parts and to correct large wrongly classified
clusters. Increasing \f$\gamma\f$ produces more regular result with a
constant computation time.

To speed up computations, the input domain can be subdivided into
smaller subsets such that several smaller graph cuts are applied
instead of a big one. The computation of these smaller graph cuts can
be done in parallel. Increasing the number of subsets allows for
faster computation times but can also reduce the quality of the
results.

The following snippet shows how to classify points using a graph cut
regularization providing a model of
`CGAL::Classification::NeighborQuery`, a strength parameter
\f$\gamma\f$ and a number of subdivisions.

\snippet Classification/example_classification.cpp Graph_cut

\section Classification_evaluation Evaluation

The class [Evaluation](@ref CGAL::Classification::Evaluation) allows
users to evaluate the reliability of the classification with respect
to a provided ground truth. The following measurements are available:

- [precision()](@ref CGAL::Classification::Evaluation::precision) computes, for one label, the ratio of true positives over the total number of detected positives;
- [recall()](@ref CGAL::Classification::Evaluation::recall) computes, for one label, the ratio of true positives over the total number of provided inliers of this label;
- [f1_score()](@ref CGAL::Classification::Evaluation::f1_score) is the harmonic mean of precision and recall;
- [intersection_over_union()](@ref CGAL::Classification::Evaluation::intersection_over_union) computes the ratio of true positives over the union of the detected positives and of the provided inliers;
- [accuracy()](@ref CGAL::Classification::Evaluation::accuracy) computes the ratio of all true positives over the total number of provided inliers;
- [mean_f1_score()](@ref CGAL::Classification::Evaluation::mean_f1_score);
- [mean_intersection_over_union()](@ref CGAL::Classification::Evaluation::mean_intersection_over_union).

All these values range from 0 (poor quality) to 1 (perfect quality).

\section Classification_examples Full Examples

\subsection Classification_example_general Simple Point Set Classification

The following example:

- reads an input file (LIDAR point set in PLY format);
- computes useful structures from this input;
- computes features from the input and the precomputed structures;
- defines 3 labels (_vegetation_, _ground_ and _roof_);
- sets up the classification classifier [Sum_of_weighted_features_classifier](@ref CGAL::Classification::Sum_of_weighted_features_classifier);
- classifies the point set with the 3 different methods (this is for
the sake of the example: each method overwrites the previous result,
users should only call one of the methods);
- saves the result in a colored PLY format.

\cgalExample{Classification/example_classification.cpp}

\subsection Classification_example_feeature Defining a Custom Feature

The following example shows how to define a custom feature and how to integrate it in the \cgal classification framework.

\cgalExample{Classification/example_feature.cpp}

\subsection Classification_example_training Feature Generation and Training

The following example:

- reads a point set with a training set (embedded as a PLY feature _label_);
- automatically generates features on 5 scales;
- trains the classifier [Sum_of_weighted_features_classifier](@ref CGAL::Classification::Sum_of_weighted_features_classifier) using 800 trials;
- runs the algorithm using the graphcut regularization;
- prints some evaluation measurements;
- saves the configuration of the classifier for further use.

\cgalExample{Classification/example_generation_and_training.cpp}

\subsection Classification_example_ethz_random_forest ETHZ Random Forest

The following example shows how to use the classifier [ETHZ::Random_forest_classifier](@ref CGAL::Classification::ETHZ::Random_forest_classifier) using an input training set.

\cgalExample{Classification/example_ethz_random_forest.cpp}

\subsection Classification_example_opencv_random_forest OpenCV Random Forest

The following example shows how to use the classifier [OpenCV::Random_forest_classifier](@ref CGAL::Classification::OpenCV::Random_forest_classifier) using an input training set.

\cgalExample{Classification/example_opencv_random_forest.cpp}

\subsection Classification_example_mesh Mesh Classification

The following example:

- reads a mesh in OFF format;
- automatically generates features on 5 scales;
- loads a configuration file for classifier [ETHZ::Random_forest_classifier](@ref CGAL::Classification::ETHZ::Random_forest_classifier);
- runs the algorithm using the graphcut regularization.

\cgalExample{Classification/example_mesh_classification.cpp}

\subsection Classification_example_cluster Cluster Classification

The following example:

- reads a point set in PLY format;
- estimates the normal vectors of the point set;
- automatically generates pointwise features on 5 scales;
- detects plane using the algorithm `CGAL::Shape_detection::Region_growing`;
- creates [Cluster](@ref CGAL::Classification::Cluster) objects from these detected planes;
- computes cluster features from the pointwise features;
- loads a configuration file for classifier [ETHZ::Random_forest_classifier](@ref CGAL::Classification::ETHZ::Random_forest_classifier);
- runs the algorithm using the raw algorithm.

\cgalExample{Classification/example_cluster_classification.cpp}


\section Classification_history History

This package is based on a research code by [Florent Lafarge](https://www-sop.inria.fr/members/Florent.Lafarge/)
that was generalized, extended and packaged by [Simon Giraudot](https://geometryfactory.com/who-we-are/)
in \cgal 4.12. %Classification of surface meshes and of clusters were introduced in \cgal 4.13.
The Neural Network classifier was introduced in \cgal 4.14.



*/
} /* namespace CGAL */

---

### Classification Doc Classification PackageDescription (`Classification/doc/Classification/PackageDescription.txt`)

/// \defgroup PkgClassificationRef Reference Manual

/*!
\defgroup PkgClassificationConcepts Concepts
\ingroup PkgClassificationRef

\defgroup PkgClassificationMain Main Functions
\ingroup PkgClassificationRef

Functions that perform classification based on a set of labels and a classifier, with or without regularization.

\defgroup PkgClassificationClassifiers Classifiers
\ingroup PkgClassificationRef

Classifiers are functors that, given a label set and an input item, associate this input item with an energy for each label. This energy measures the likelihood of the item to belong to this label.

\defgroup PkgClassificationClassifiersETHZ ETHZ
\ingroup PkgClassificationClassifiers

Classifiers that use the ETHZ library.

\defgroup PkgClassificationClassifiersOpenCV OpenCV
\ingroup PkgClassificationClassifiers

Classifiers that use the \ref thirdpartyOpenCV library.

\defgroup PkgClassificationDataStructures Common Data Structures
\ingroup PkgClassificationRef

Useful data structures that are used to compute features (computation of eigenvalues, for example).

\defgroup PkgClassificationLabel Label
\ingroup PkgClassificationRef

A label represents how an item should be classified, for example: _vegetation_, _building_, _road_, etc.

\defgroup PkgClassificationFeature Feature
\ingroup PkgClassificationRef

Features are defined as scalar fields that associates each input item with a specific value.

\defgroup PkgClassificationFeatures Predefined Features
\ingroup PkgClassificationRef

\cgal provides some predefined features that are relevant for classification of point sets.

\defgroup PkgClassificationPointSet Point Set Classification
\ingroup PkgClassificationRef

Data structures specialized to classify point sets.

\defgroup PkgClassificationMesh Mesh Classification
\ingroup PkgClassificationRef

Data structures specialized to classify surface meshes.

\defgroup PkgClassificationCluster Cluster Classification
\ingroup PkgClassificationRef

Data structures specialized to classify clusters.

\addtogroup PkgClassificationRef

\cgalPkgDescriptionBegin{Classification, PkgClassification}
\cgalPkgPicture{data_classif.png}

\cgalPkgSummaryBegin
\cgalPkgAuthors{Simon Giraudot and Florent Lafarge}
\cgalPkgDesc{This component implements an algorithm that classifies a data set into a user-defined set of labels (such as ground, vegetation, buildings, etc.). A flexible API is provided so that users can classify any type of data, compute their own local features on the input data set, and define their own labels.}
\cgalPkgManuals{Chapter_Classification, PkgClassificationRef}
\cgalPkgSummaryEnd

\cgalPkgShortInfoBegin
\cgalPkgSince{4.12}
\cgalPkgDependsOn{\ref PkgSolverInterface, \ref PkgSpatialSearchingD}
\cgalPkgBib{cgal:lm-clscm-12}
\cgalPkgLicense{\ref licensesGPL "GPL"}
\cgalPkgDemo{CGAL Lab,CGALlab.zip}
\cgalPkgShortInfoEnd

\cgalPkgDescriptionEnd

\cgalClassifedRefPages

\cgalCRPSection{Concepts}

- `CGAL::Classification::Classifier`
- `CGAL::Classification::NeighborQuery`

\cgalCRPSection{Main Functions}

- `CGAL::Classification::classify()`
- `CGAL::Classification::classify_with_local_smoothing()`
- `CGAL::Classification::classify_with_graphcut()`

\cgalCRPSection{Classifiers}

- `CGAL::Classification::ETHZ::Random_forest_classifier`
- `CGAL::Classification::OpenCV::Random_forest_classifier`
- `CGAL::Classification::Sum_of_weighted_features_classifier`

\cgalCRPSection{Common Data Structures}

- `CGAL::Classification::Local_eigen_analysis`
- `CGAL::Classification::Planimetric_grid<GeomTraits, PointRange, PointMap>`
- `CGAL::Classification::Evaluation`

\cgalCRPSection{Label}

- `CGAL::Classification::Label`
- `CGAL::Classification::Label_handle`
- `CGAL::Classification::Label_set`

\cgalCRPSection{Feature}

- `CGAL::Classification::Feature_base`
- `CGAL::Classification::Feature_handle`
- `CGAL::Classification::Feature_set`

\cgalCRPSection{Predefined Features}

- `CGAL::Classification::Feature::Color_channel<GeomTraits, PointRange, ColorMap>`
- `CGAL::Classification::Feature::Distance_to_plane<PointRange, PointMap>`
- `CGAL::Classification::Feature::Echo_scatter<GeomTraits, PointRange, PointMap, EchoMap>`
- `CGAL::Classification::Feature::Eigenvalue`
- `CGAL::Classification::Feature::Elevation<GeomTraits, PointRange, PointMap>`
- `CGAL::Classification::Feature::Height_above<GeomTraits, PointRange, PointMap>`
- `CGAL::Classification::Feature::Height_below<GeomTraits, PointRange, PointMap>`
- `CGAL::Classification::Feature::Simple_feature<InputRange, PropertyMap>`
- `CGAL::Classification::Feature::Vertical_dispersion<GeomTraits, PointRange, PointMap>`
- `CGAL::Classification::Feature::Vertical_range<GeomTraits, PointRange, PointMap>`
- `CGAL::Classification::Feature::Verticality<GeomTraits>`

\cgalCRPSection{Point Set Classification}

- `CGAL::Classification::Point_set_feature_generator<GeomTraits, PointRange, PointMap, ConcurrencyTag, DiagonalizeTraits>`
- `CGAL::Classification::Point_set_neighborhood<GeomTraits, PointRange, PointMap>`

\cgalCRPSection{Mesh Classification}

- `CGAL::Classification::Mesh_feature_generator<GeomTraits, FaceGraph, PointMap, ConcurrencyTag, DiagonalizeTraits>`
- `CGAL::Classification::Mesh_neighborhood<FaceListGraph>`
- `CGAL::Classification::Face_descriptor_to_center_of_mass_map<FaceListGraph, VertexPointMap>`
- `CGAL::Classification::Face_descriptor_to_face_descriptor_with_bbox_map<FaceListGraph, VertexPointMap>`

\cgalCRPSection{Cluster Classification}

- `CGAL::Classification::Cluster<ItemRange, ItemMap>`
- `CGAL::Classification::create_clusters_from_indices()`
- `CGAL::Classification::Feature::Cluster_mean_of_feature`
- `CGAL::Classification::Feature::Cluster_variance_of_feature`
- `CGAL::Classification::Feature::Cluster_size`
- `CGAL::Classification::Feature::Cluster_vertical_extent`

*/

---

### Classification Doc Classification Examples (`Classification/doc/Classification/examples.txt`)

/*!
\example Classification/example_classification.cpp
\example Classification/example_feature.cpp
\example Classification/example_generation_and_training.cpp
\example Classification/example_ethz_random_forest.cpp
\example Classification/example_deprecated_conversion.cpp
\example Classification/example_opencv_random_forest.cpp
\example Classification/example_mesh_classification.cpp
\example Classification/example_cluster_classification.cpp
*/

---

### Combinatorial Map Doc Combinatorial Map Combinatorial Map (`Combinatorial_map/doc/Combinatorial_map/Combinatorial_map.txt`)

namespace CGAL {
/*!

\mainpage User Manual
\anchor Chapter_Combinatorial_Maps
\anchor ChapterCombinatorialMap

\author Guillaume Damiand
\cgalAutoToc

\section Combinatorial_mapIntroduction Introduction

A <I>d</I>-dimensional combinatorial map is a data structure representing an orientable subdivided <I>d</I>-dimensional object obtained by taking <I>d</I>D cells, and allowing to glue <I>d</I>D cells along <I>(d-1)</I>D cells. It provides a description of all the cells of the subdivision (for example vertices and edges), together with incidence and adjacency relationships. This package is a generalization of the \ref chapterHalfedgeDS "halfedge data structure" to higher dimension. Indeed, a 2D combinatorial map is equivalent to a halfedge data structure: there is a one-to-one mapping between elements of both data structures, halfedges corresponding to darts.

Note that you can use the \ref ChapterGeneralizedMap "Generalized Map package" if you need to represent non-orientable objects.

We denote <I>i</I>-cell for an <I>i</I>-dimensional cell (for example in 3D, 0-cells are <I>vertices</I>, 1-cells are <I>edges</I>, 2-cells are <I>facets</I>, and 3-cells are <I>volumes</I>). A <I>boundary relation</I> is defined on these cells, giving for each <I>i</I>-cell <I>c</I> the set of <I>(i-1)</I>-cells contained in the boundary of <I>c</I>. Two cells <I>c1</I> and <I>c2</I> are <I>incident</I> if there is a path of cells, starting from the cell of highest dimension to the other cell, such that each cell of the path (except the first one) belongs to the boundary of the previous cell in the path. Two <I>i</I>-cells <I>c3</I> and <I>c4</I> are <I>adjacent</I> if there is an <I>(i-1)</I>-cell incident to both <I>c3</I> and <I>c4</I>. You can see an example of a 2D object and a 3D object in \cgalFigureRef{fig_cmap_example_subdivisions} showing some cells of the subdivision and some adjacency and incidence relations.

\cgalFigureBegin{fig_cmap_example_subdivisions,cmap_example_subdivisions.svg}
Example of subdivided objects that can be described by combinatorial maps. Left: A 2D object composed of three facets (2-cells), named <I>f1</I>, <I>f2</I> and <I>f3</I>, nine edges (1-cells) and seven vertices (0-cells). <I>f1</I> and <I>f2</I> are adjacent along edge <I>e1</I>, thus <I>e1</I> is incident both to <I>f1</I> and <I>f2</I>. Vertex <I>v1</I> is incident to edge <I>e1</I>, thus <I>v1</I> is incident to <I>f1</I> and <I>f2</I> by transitivity. Right: A 3D object (only partially represented for vertices and edges) composed of three volumes (3-cells), named <I>vol1</I>, <I>vol2</I> and <I>vol3</I>, twelve facets (2-cells) (there is one facet <I>f4</I> between <I>vol1</I> and <I>vol2</I>, and similarly between <I>vol1</I> and <I>vol3</I> and <I>vol2</I> and <I>vol3</I>), sixteen edges (1-cells), and eight vertices (0-cells). <I>vol1</I> and <I>vol2</I> are adjacent along facet <I>f4</I>, thus <I>f4</I> is incident both to <I>vol1</I> and <I>vol2</I>. Edge <I>e4</I> is incident to the three facets between <I>vol1</I> and <I>vol2</I>, <I>vol1</I> and <I>vol3</I>, and <I>vol2</I> and <I>vol3</I>. <I>e4</I> is also incident to the three volumes by transitivity.
\cgalFigureEnd

A combinatorial map is an edge-centered data structure, describing the cells and the incidence and adjacency relations. It uses only one basic element called <I>dart</I>, and a set of <I>pointers</I> between these darts. A dart can be thought as a part of an oriented edge (1-cell), together with a part of incident cells of dimensions 0, 2, 3, ..., <I>d</I>. When a dart <I>d0</I> describes a part of an <I>i</I>-cell <I>c</I>, we say that <I>d0</I> <I>belongs</I> to <I>c</I>, and that <I>c</I> <I>contains</I> <I>d0</I>. Let us look at the example in \cgalFigureRef{fig_cmap_examples} showing the 2D and 3D combinatorial maps describing the two objects of \cgalFigureRef{fig_cmap_example_subdivisions}.

\cgalFigureBegin{fig_cmap_examples,cmap_examples.svg}
Combinatorial maps representing the objects given in \cgalFigureRef{fig_cmap_example_subdivisions}. Left: The 2D combinatorial map which contains 12 darts. Right: The 3D combinatorial map which contains 54 darts (18 for each volume).
\cgalFigureEnd


First let us start in 2D (\cgalFigureRef{fig_cmap_examples} (Left)). Facet <I>f1</I> contains four darts. These darts are linked together with pointers. Starting from a dart and following a \f$ \beta_1\f$ pointer, we get to a dart which belongs to the same facet but to the next edge (1-cell, which explains the index 1 of \f$ \beta_1\f$).  Starting from any dart and following \f$ \beta_1\f$ pointers, we can reach exactly all the darts belonging to the facet. Starting from a dart and following a \f$ \beta_2\f$ pointer, we get to a dart which belongs to the same edge but to the neighboring facet (2-cell, which explains the index 2 of \f$ \beta_2\f$). Starting from any dart and following \f$ \beta_2\f$ pointers, we can reach exactly all the darts that belong to the edge (in 2D one or two darts).

Things are slightly different for vertices. Indeed, each \f$ \beta_i\f$ points to a dart belonging to a different <I>i</I>-cell, but also to a different 0-cell (vertex). This is so because two linked darts have opposite orientations. For this reason, starting from any dart belonging to a vertex <I>v</I>, we have to follow \f$ \beta_2\f$ then \f$ \beta_1\f$ to reach exactly the darts belonging to vertex <I>v</I>. In fact, by composing two \f$ \beta_i\f$s, we always obtain a dart belonging to the same vertex (if we do not start by following a \f$ \beta_1\f$ pointer).

The main interest of combinatorial map definition based on darts and \f$ \beta_i\f$ pointers is to be able to increase the dimension <em>only</em> by adding new pointers. This is illustrated thanks to the 3D example given in \cgalFigureRef{fig_cmap_examples} (Right). In addition to \f$ \beta_1\f$ and \f$ \beta_2\f$ of the 2D case, there is a new pointer \f$ \beta_3\f$.

If we take a closer look at the central edge <I>e4</I> shown in \cgalFigureRef{fig_cmap_examples_zoom} (Left), we can see that it contains six darts linked together. Starting from a dart and following a \f$ \beta_3\f$ pointer, we get to a dart which belongs to the same edge, to the same facet, but to the neighboring volume (a 3-cell, which explains the index 3 in \f$ \beta_3\f$). Similarly, starting from a dart and following a \f$ \beta_2\f$ pointer, we get to a dart which belongs to the same edge, to the same volume, but to the neighboring facet (2-cell). Starting from any of these six darts and following \f$ \beta_2\f$ and \f$ \beta_3\f$ pointers, we can reach exactly the six darts that belong to edge <I>e4</I>.

\cgalFigureBegin{fig_cmap_examples_zoom,cmap_examples_zoom.svg}
Two zooms on the 3D combinatorial map given in \cgalFigureRef{fig_cmap_examples} (Right). Left: Zoom around the central edge <I>e4</I> which details the six darts belonging to the edge. Right: Zoom around the facet between volumes <I>vol2</I> and <I>vol3</I> which details the eight darts belonging to the facet.
\cgalFigureEnd

For facets, by following a \f$ \beta_1\f$ pointer, we get to a dart which belongs to the same facet, to the same volume, but to the next edge (1-cell, which explains the index 1 of \f$ \beta_1\f$). Starting from any dart and following \f$ \beta_1\f$ and \f$ \beta_3\f$ pointers, we can reach exactly all the darts belonging to the facet (see \cgalFigureRef{fig_cmap_examples_zoom} (Right)). For volumes, starting from any dart and following \f$ \beta_1\f$ and \f$ \beta_2\f$ pointers, we can reach exactly all the darts belonging to the volume.

For vertices, we have to follow \f$ \beta_2\f$ then \f$ \beta_1\f$, and \f$ \beta_3\f$ then \f$ \beta_1\f$ to reach exactly the darts belonging to the vertex <I>v</I>. Indeed, as in 2D, we have to compose two \f$ \beta_i\f$s to obtain a dart belonging to the same vertex (if we do not start by following a \f$ \beta_1\f$ pointer).

In some cases, the general rule that by following a \f$ \beta_i\f$ we get a dart which belongs to the neighboring <I>i</I>-cell is not true, as for example for darts belonging to the boundary of the represented object. For example, in \cgalFigureRef{fig_cmap_example_subdivisions} (Left), any dart <I>d0</I> that does not belong to edge <I>e1</I>, <I>e2</I> and <I>e3</I> belongs to a 2-cell, and there is no neighboring facet along the edge containing <I>d0</I>.  Another example is in \cgalFigureRef{fig_cmap_example_subdivisions} (Right), for any dart <I>d0</I> that belongs to facet <I>f5</I>.  <I>d0</I> belongs to volume <I>vol2</I>, but there is no neighboring volume along this facet. The general rule is also not true for unbounded cells. For example if we remove a dart in \cgalFigureRef{fig_cmap_examples} (Left), we obtain an unbounded facet having a dart without next dart for \f$ \beta_1\f$, and if we remove a facet in \cgalFigureRef{fig_cmap_examples} (Right), we obtain an unbounded volume having some darts without neighboring facet for \f$ \beta_2\f$. In such a case, there is a particular value called \f$ \varnothing\f$ used to describe that a dart <I>d0</I> is not linked to another dart in dimension <I>i</I>.

Combinatorial maps are defined in any dimension. A 0D combinatorial map is a set of isolated darts describing isolated vertices. A 1D combinatorial map describes paths or cycles of darts corresponding to paths or cycles of edges, and equivalent to double linked lists. The most useful cases are 2D and 3D combinatorial maps. Since 2D combinatorial maps are equivalent to halfedge data structure, notions are illustrated in 3D in the following examples to help the reader understand this specific case. But it is important to keep in mind that one main interest of combinatorial maps is their generic definition in any dimension, and that everything presented in this manual is valid in any dimension.

A <I>d</I>D combinatorial map is useful when you want to describe <I>d</I>D objects and the adjacency relations between these objects, and you want to be able to efficiency traverse these objects by using the different relations. For example, we can use a 3D combinatorial map to describe a 3D segmented image: each 3-cell corresponds to a region in the image and each 2-cell corresponds to a contact area between two regions.

A combinatorial map does not contain any geometric information. However, this package allows to associate any information to the cells of the combinatorial map. A specific information, which is often used in practice, consists in adding linear geometry to a combinatorial map by associating a point to each vertex of the map: this is the object of the \ref ChapterLinearCellComplex "Linear cell complex" package (when an object has a point associated to each vertex, each edge is thus a straight line segment, which explains the name <em>linear geometry</em>). The \ref ChapterLinearCellComplex "Linear cell complex" package  can for example be useful to describe 3D buildings as set of walls, rooms, doors and windows (both combinatorial and geometric descriptions) and all the adjacency relations between these elements allowing for example to move a camera in a given building from rooms to rooms by traversing doors.

\section sec_presentation Data Structure Presentation

In this section, we describe <I>d</I>D combinatorial maps in terms of data structure and operations. Mathematical definitions are provided in Section \ref sec_definition "Mathematical Definitions", and a package description is given in Section \ref secsoftwaredesign "Software Design".

\subsection sseccombimapanddarts Combinatorial Map and Darts

A <I>d</I>D combinatorial map is a set of darts <I>D</I>. A dart <I>d0</I> is an element that can be <I>linked</I> with <I>d</I>+1 darts by pointers called \f$ \beta_i\f$, with 0 \f$ \leq \f$ <I>i</I> \f$ \leq \f$ <I>d</I>. %Dart <I>d0</I> is said <I>i-free</I> when \f$ \beta_i\f$(<I>d0</I>)=\f$ \varnothing\f$. Each \f$ \beta_i\f$, for 2 \f$ \leq \f$ <I>i</I> \f$ \leq \f$ <I>d</I>, is its own inverse, i.e., if dart <I>d0</I> is not <I>i</I>-free, then \f$ \beta_i\f$(\f$ \beta_i\f$(<I>d0</I>))=<I>d0</I>. This is different for \f$ \beta_0\f$ and \f$ \beta_1\f$: \f$ \beta_0\f$ is the inverse of \f$ \beta_1\f$, i.e., if darts <I>d1</I> and <I>d2</I> are such that \f$ \beta_1\f$(<I>d1</I>)=<I>d2</I>, then \f$ \beta_0\f$(<I>d2</I>)=<I>d1</I>. Given dart <I>d1</I>, if there is no dart <I>d2</I> such that \f$ \beta_1\f$(<I>d2</I>)=<I>d1</I>, then \f$ \beta_0\f$(<I>d1</I>)=\f$ \varnothing\f$. \f$ \varnothing\f$ is a constant, which does not belong to the set of darts <I>D</I> of the combinatorial map. However, by definition \f$ \varnothing\f$ is linked with itself for all \f$ \beta_i\f$s: \f$ \forall \f$ <I>i</I>, 0 \f$ \leq \f$ <I>i</I> \f$ \leq \f$ <I>d</I>, \f$ \beta_i\f$(\f$ \varnothing)\f$=\f$ \varnothing\f$.

A combinatorial map is <I>without i-boundary</I> if there is no <I>i</I>-free dart, and it is <I>without boundary</I> if it is without <I>i</I>-boundary for all dimensions 1 \f$ \leq \f$ <I>i</I> \f$ \leq \f$<I>d</I>.

We show in \cgalFigureRef{fig_cmap_detailed_example} a 3D object and the corresponding 3D combinatorial map. This map has 40 darts represented by arrows, some darts being numbered. In this combinatorial map, we have for example \f$ \beta_1\f$(1)=2, \f$ \beta_2\f$(1)=10, and \f$ \beta_3\f$(1)=5. This combinatorial map is without 1-boundary and 2-boundary, but has some 3-boundary, because some darts are 3-free, for example \f$ \beta_3\f$(10)=\f$ \varnothing\f$ and \f$ \beta_3\f$(12)=\f$ \varnothing\f$.

\cgalFigureBegin{fig_cmap_detailed_example,cmap_detailed_example.svg}
Example of a 3D combinatorial map. Left: A 3D object made of two volumes adjacent along facet <I>f2</I>. Right: The corresponding 3D combinatorial map. Darts are drawn with arrows, sometimes numbered. Two darts linked by \f$ \beta_1\f$ are drawn consecutively (for example \f$ \beta_1\f$(10)=11), and two darts linked by \f$ \beta_2\f$ are drawn parallel, in reverse orientations, with a little gray segment joining them (for example \f$ \beta_2\f$(1)=10). \f$ \beta_3\f$ pointers are represented by blue segments (for example \f$ \beta_3\f$(1)=5).
\cgalFigureEnd

\subsection sseccellsinmap Cells as Sets of Darts

A cell in a <I>d</I>D combinatorial map is implicitly represented by a subset of darts.  In this section, we will see how to retrieve all cells containing a given dart, how to retrieve all darts belonging to a cell containing a given dart, and how incidence and adjacency relations are defined in terms of darts.

The first important property of a combinatorial map is that each dart belongs to an <I>i</I>-cell, \f$ \forall \f$ <I>i</I>, 0 \f$ \leq \f$ <I>i</I> \f$ \leq \f$ <I>d</I>.  For example in 3D, a dart belongs to a vertex, an edge, a facet, and a volume. This means that a 3D combinatorial map containing an isolated dart contains exactly one vertex, one edge, one facet and one volume.

The second important property is that cells of a combinatorial map correspond to specific <I>orbits</I>. Given a set  <I>S</I>\f$ \subseteq\f${\f$ \beta_1\f$,...,\f$ \beta_d\f$} and a dart <I>d0</I>, the <I>orbit</I> \f$ \langle{}\f$ <I>S</I>\f$ \rangle{}\f$(<I>d0</I>) is the set of darts that can be reached from <I>d0</I> by following any combination of any \f$ \beta_i\f$'s in <I>S</I> and their inverses (to simplify notations, we can use for example \f$ \langle{}\f$\f$ \beta_1\f$,\f$ \beta_4\f$\f$\rangle{}\f$(<I>d0</I>) to denote \f$ \langle{}\f$ <I>S</I>\f$ \rangle{}\f$(<I>d0</I>) with <I>S</I>={\f$ \beta_1\f$,\f$ \beta_4\f$}).

Given a dart <I>d0</I>, in general, \f$ \beta_i\f$(<I>d0</I>) (with 1 \f$ \leq \f$ <I>i</I> \f$ \leq \f$ <I>d</I>) belongs to the same cells as <I>d0</I>, only the <I>i</I>-cell and 0-cell are different. There are two exceptions:
<ol type="1">
<li>if <I>d0</I> is <I>i</I>-free, then \f$ \beta_i\f$(<I>d0</I>)=\f$ \varnothing\f$;</li>
<li>if \f$ \beta_i\f$(<I>d0</I>) belongs to the same <I>i</I>-cell as <I>d0</I> (case of multi-incidence). For example if an edge is an isolated loop, it is incident twice to the same vertex, then given a dart <I>d0</I> belonging to this edge, \f$ \beta_1\f$(<I>d0</I>) goes to the next edge, which is in fact the same edge.</li>
</ol>

Since \f$ \beta_i\f$(<I>d0</I>) (with 1 \f$ \leq \f$ <I>i</I> \f$ \leq \f$ <I>d</I>) allows to change the current <I>i</I>-cell, all the darts that can be reached from <I>d0</I> by using any combination of \f$ \beta_j\f$'s, \f$ \forall \f$ <I>j</I>, 1 \f$ \leq \f$ <I>j</I> \f$ \leq \f$ <I>d</I> and <I>j</I> \f$ \neq \f$ <I>i</I> and their inverse are contained in the same <I>i</I>-cell as <I>d0</I>. The <I>i</I>-cell containing <I>d0</I> is defined in terms of orbit by \f$ \langle{}\f$\f$ \beta_1\f$,...,\f$ \beta_{i-1}\f$,\f$ \beta_{i+1}\f$,...,\f$ \beta_d\f$\f$ \rangle{}\f$(<I>d0</I>).

There is a special case for vertices. Given a dart <I>d0</I>, the set of darts contained in the same vertex as <I>d0</I> are the darts that can be reached from <I>d0</I> by using any combination of \f$\beta_i \circ\f$\f$ \beta_j\f$, \f$ \forall \f$ <I>i</I>,<I>j</I>, 1 \f$ \leq \f$ <I>i</I> \f$ < \f$ <I>j</I> \f$ \leq \f$ <I>d</I>, and their inverse. The 0-cell containing <I>d0</I> is defined in terms of orbit by \f$ \langle{}\f${\f$ \beta_i\f$\f$ \circ\f$\f$ \beta_j\f$\f$ |\f$\f$ \forall \f$ <I>i,j</I>: 1 \f$ \leq \f$ <I>i</I> \f$ < \f$ <I>j</I> \f$ \leq \f$ <I>d</I>}\f$ \rangle{}\f$(<I>d0</I>).

Orbit \f$ \langle{}\f$\f$ \beta_1\f$,...,\f$ \beta_d\f$\f$ \rangle{}\f$(<I>d0</I>) is the <I>connected component</I> containing dart <I>d0</I>. A combinatorial map is <I>connected</I> if this set is equal to the set of all the darts of the combinatorial map.

A last important property of cells is that for all dimensions <I>i</I> the set of <I>i</I>-cells forms a partition of the set of darts <I>D</I>, i.e.\ for any <I>i</I>, the union of the sets of darts of all the <I>i</I>-cells is equal to <I>D</I>, and the sets of darts of two different <I>i</I>-cells are disjoint.

Let us give some examples of cells in 3D, for the 3D combinatorial map of \cgalFigureRef{fig_cmap_detailed_example} :
<UL>
<LI>All the darts belonging to the same edge can be obtained by any combination of \f$ \beta_2\f$ and \f$ \beta_3\f$: for example edge <I>e</I> of the object corresponds in the combinatorial map to the set of darts {1,5,9,10}. Given any dart belonging to this edge, we retrieve all the other darts by, for example, a breadth-first traversal. In terms of orbits, this 1-cell corresponds to \f$ \langle{}\f$\f$ \beta_2\f$,\f$ \beta_3\f$\f$ \rangle{}\f$(1).
<LI>All the darts belonging to the same facet can be obtained by any combination of \f$ \beta_1\f$ and \f$ \beta_3\f$: for example facet <I>f2</I> corresponds in the combinatorial map to the set of darts {1,2,3,4,5,6,7,8}. Facet <I>f1</I> corresponds to the set of darts {10,11,12,13}. Note that these last darts are 3-free since there is no other volume sharing this facet. In terms of orbits, <I>f2</I> corresponds to \f$ \langle{}\f$\f$ \beta_1\f$,\f$ \beta_3\f$\f$ \rangle{}\f$(1) and <I>f1</I> corresponds to \f$ \langle{}\f$\f$ \beta_1\f$,\f$ \beta_3\f$\f$ \rangle{}\f$(10).
<LI>All the darts belonging to the same volume can be obtained by any combination of \f$ \beta_1\f$ and \f$ \beta_2\f$: for example volume <I>vol1</I> corresponds in the combinatorial map to the set of the twenty-four darts belonging to the cube. In terms of orbits, <I>vol1</I> corresponds to \f$ \langle{}\f$\f$ \beta_1\f$,\f$ \beta_2\f$\f$ \rangle{}\f$(1).
<LI>All the darts belonging to the same vertex can be obtained by any combination of \f$ \beta_1\f$\f$ \circ\f$\f$ \beta_2\f$, \f$ \beta_1\f$\f$ \circ\f$\f$ \beta_3\f$ and \f$ \beta_2\f$\f$ \circ\f$\f$ \beta_3\f$ and their inverse functions. In our example, vertex <I>v</I> of the object corresponds in the combinatorial map to the set of darts {1,6,9,11,14,15}.  Starting from dart 1, we obtain for example dart 14=(\f$ \beta_1\f$\f$ \circ\f$\f$ \beta_2\f$)\f$ ^{-1}\f$(1)=\f$ \beta_2\f$\f$ \circ\f$\f$ \beta_0\f$(1), dart 11=\f$ \beta_1\f$\f$ \circ\f$\f$ \beta_2\f$(1), and dart 9=\f$ \beta_2\f$\f$ \circ\f$\f$ \beta_3\f$(1).  Intuitively, the set of darts corresponding to a vertex contains all the darts represented by arrows starting from this vertex. In terms of orbits, <I>v</I> corresponds to \f$ \langle{}\f$\f$ \beta_1\f$\f$ \circ\f$\f$ \beta_2\f$, \f$ \beta_1\f$\f$ \circ\f$\f$ \beta_3\f$, \f$ \beta_2\f$\f$ \circ\f$\f$ \beta_3\f$\f$ \rangle{}\f$(1).
</UL>

Using this definition of cells as sets of darts, we can retrieve all the incidence and adjacency relations between the cells of the subdivision in a combinatorial map. Two cells are <I>incident</I> if the intersection of their two sets of darts is non empty (whatever the dimension of the two cells). Two <I>i</I>-cells <I>c1</I> and <I>c2</I>,  1 \f$ \leq \f$ <I>i</I> \f$ \leq \f$<I>d</I>, are <I>adjacent</I> if there is  <I>d1</I>\f$ \in \f$ <I>c1</I> and <I>d2</I>\f$ \in \f$ <I>c2</I> such that <I>d1</I> and <I>d2</I> belong to the same <I>(i-1)</I>-cell.

In the example of \cgalFigureRef{fig_cmap_detailed_example}, vertex <I>v</I> and edge <I>e</I> are incident since the intersection of the two corresponding sets of darts is {1,9} \f$ \neq \f$ \f$ \emptyset\f$. Vertex <I>v</I> is incident to facet <I>f2</I> since the intersection of the two corresponding sets of darts is {1,6} \f$ \neq \f$ \f$ \emptyset\f$. Edge <I>e</I> and facet <I>f1</I> are incident since the intersection of the two corresponding sets of darts is {10} \f$ \neq \f$ \f$ \emptyset\f$. Finally, facets <I>f1</I> and <I>f2</I> are adjacent because 10\f$ \in \f$ <I>f1</I>, 1\f$ \in \f$ <I>f2</I> and 1 and 10 belong to the same edge.

We can consider <I>i</I>-cells in a dimension <I>d'</I> with <I>i</I> \f$ \leq \f$ <I>d'</I> \f$ \leq\f$ <I>d</I>. The idea is to consider the <I>i</I>-cells as if the combinatorial map was in <I>d'</I> dimension. For that, we only take into account the \f$ \beta_j \f$s for <I>j</I> \f$ \leq \f$ <I>d'</I>. The <I>i</I>-cell containing <I>d0</I> in dimension <I>d'</I> is the orbit \f$ \langle{}\f$\f$ \beta_1\f$,...,\f$ \beta_{i-1}\f$,\f$ \beta_{i+1}\f$,...,\f$ \beta_{d'}\f$\f$ \rangle{}\f$(<I>d0</I>), and  the 0-cell is the orbit \f$ \langle{}\f${\f$ \beta_i\f$\f$ \circ\f$\f$ \beta_j\f$\f$ |\f$\f$ \forall \f$ <I>i,j</I>:  2 \f$ \leq \f$ <I>i</I> \f$ < \f$ <I>j</I> \f$ \leq \f$ <I>d'</I>}\f$ \rangle{}\f$(<I>d0</I>). By default, <I>i</I>-cells are considered in dimension <I>d</I>, the dimension of the combinatorial map.

In the example of \cgalFigureRef{fig_cmap_detailed_example}, the 2-cell containing dart 1 is facet <I>f2</I> which is the set of darts {1,2,3,4,5,6,7,8}. If we consider the same 2-cell in dimension 2, we obtain the set of darts {1,2,3,4}. Intuitively we <em>forget</em> \f$ \beta_3\f$ and we obtain the set of darts of the facet containing dart 1 restricted to the volume containing this dart.

\subsection ssecassociateattributes How to Associate Information to Cells

Combinatorial maps only describe the cells of the subdvision, and all the incidence and adjacency relations between these cells. This is not enough for many applications which need to associate <I>information</I> to cells. This can be geometric or non-geometric information, such as 3D points associated to vertices, the edge length associated to edges, or a color or normal to a facet.

To answer this need, a combinatorial map allows to create <I>attributes</I> which are able to store any information, and to associate attributes to cells of the combinatorial map. We denote <I>i</I>-attributes for the attributes associated with <I>i</I>-cells. Attributes may exist for only some of the dimensions, and if they exist for dimension <I>i</I>, they do not necessarily exist for each of the <I>i</I>-cells. More precisely, <I>i</I>-attributes are associated to <I>i</I>-cells by an injection:
<UL>
<LI>two different <I>i</I>-cells are associated to two different <I>i</I>-attributes;
<LI>an <I>i</I>-cell may have no associated <I>i</I>-attribute.
</UL>

Since <I>i</I>-cells are not explicitly represented in combinatorial maps, the association between <I>i</I>-cells and <I>i</I>-attributes is transferred to darts: if attribute <I>a</I> is associated to <I>i</I>-cell <I>c</I>, all the darts belonging to <I>c</I> are associated to <I>a</I>.

We can see two examples of combinatorial maps having some attributes in \cgalFigureRef{fig_cmap_with_attribs}. In the first example (Left), a 2D combinatorial map has 1-attributes containing a float, for example corresponding to the length of the associated 1-cell, and 2-attributes containing a color in RGB format. In the second example (Right), a 3D combinatorial map has 2-attributes containing a color in RGB format.

\cgalFigureBegin{fig_cmap_with_attribs,cmap_with_attribs.svg}
Example of combinatorial maps with attributes. Attributes are represented by black rectangles containing an information, and association between darts and attributes are represented by small red lines. Left: A 2D combinatorial map with 1-attributes containing a double, for example corresponding to the length of the 1-cell, and 2-attributes containing a color in RGB format. Only three edges of the combinatorial map, among the nine, are associated to a 1-attribute. All the 2-cells are associated to a 2-attribute. Right: A 3D combinatorial map with 2-attributes containing a color in RGB format. Only three 2-cells of the combinatorial map, among the ten, are associated to a 2-attribute.
\cgalFigureEnd

\subsection sseccombimapvalidity Combinatorial Map Properties

There are some conditions that a combinatorial map must satisfy to be valid. Some of them have already been given about the \f$ \beta\f$ pointers (see Section \ref sseccombimapanddarts "Combinatorial Map and Darts") and about the association between darts and attributes (see Section \ref ssecassociateattributes "How to Associate Information to Cells").

There is an additional condition related to the type of represented objects, which are <I>quasi-manifold</I> orientable <I>d</I>D objects. A <I>d</I>D quasi-manifold is an object obtained by taking some isolated <I>d</I>-cells, and allowing to glue <I>d</I>-cells along <I>(d-1)</I>-cells. It is orientable if it is possible to embed it in the Euclidean space and to define a global "left" and "right" direction in each point of the embedded object. In 2D, quasi-manifolds are manifolds, but this is no longer true in higher dimension as we can see in the example presented in \cgalFigureRef{fig_cmap_quasi_manifold}. In this example, the object to the right is not a manifold since the neighborhood of the point <I>p</I> in the object is not homeomorphic to a 3D ball (intuitively, two objects are homeomorphic if each object can be continuously deformed into the second one; in such a case, the two objects have exactly the same topological properties).

\cgalFigureBegin{fig_cmap_quasi_manifold,cmap_quasi_manifold.svg}
Example of a 3D quasi-manifold which is not a manifold. The object to the right is made of the four pyramids (shown to the left) glued together along facets, thus it is a quasi-manifold.
\cgalFigureEnd


Combinatorial maps can only represent quasi-manifolds due to the definition of \f$ \beta\f$ pointers. As we have seen in Section \ref sseccellsinmap "Cells as Sets of Darts", \f$ \beta_i\f$(<I>d0</I>) (with 1 \f$ \leq \f$ <I>i</I> \f$ \leq \f$ <I>d</I>) belongs to the same cells as <I>d0</I>, only the <I>i</I>-cell and 0-cell are different. In other words, \f$ \beta_i\f$ links two <I>i</I>-cells that share a common <I>(i-1)</I>-cell: it is not possible to link more than two <I>i</I>-cells along a same <I>(i-1)</I>-cell.  For this reason, it is not possible to describe non quasi-manifold objects as those shown in \cgalFigureRef{fig_cmap_non_manifolds} by combinatorial maps.


\cgalFigureBegin{fig_cmap_non_manifolds,cmap_non_manifolds.svg}
Three examples of non quasi-manifold objects. Left: A 2D object which is not a quasi-manifold since the two 2-cells share a common vertex but no common 1-cell. Middle: A 3D object which is not a quasi-manifold since is it not only composed by 3D cells glued together (there is an isolated 2-cell in dark gray). Right: A 3D object which is not a quasi-manifold since the two 3-cells share a common edge but no common 2-cell.
\cgalFigureEnd

Due to this additional condition, any objects can not be represented by a combinatorial map but only orientable quasi-manifolds. We need to study now the inverse relation. Does any set of darts linked together by \f$ \beta_i\f$'s, with 0 \f$ \leq \f$ <I>i</I> \f$ \leq \f$ <I>d</I> correspond to a quasi-manifold? As we can see in \cgalFigureRef{fig_cmap_non_valid}, the answer is no.

\cgalFigureBegin{fig_cmap_non_valid,cmap_non_valid.svg}
Two examples of darts linked together by some \f$ \beta_1\f$, \f$ \beta_2\f$ and \f$ \beta_3\f$ which does not represent a 3D quasi-manifold, and thus which are not 3D combinatorial map. Left: In this example, all the darts are 3-free except \f$ \beta_3\f$(1)=5 and \f$ \beta_3\f$(4)=6 (and vice-versa). Right: In this example, darts linked by \f$ \beta_3\f$ are not in the same order in both 3-cells.
\cgalFigureEnd


In the first example (Left), there are two 3-cells (one to the left for the cube, a second to the right for the pyramid) which are <em>partially adjacent</em> along one 2-cell. Indeed, only two darts of the 2-cell are linked by \f$ \beta_3\f$. We have \f$ \beta_3\f$(1)=5 and \f$ \beta_3\f$(4)=6 (and reciprocally). This configuration is not possible in a quasi-manifold: two <I>d</I>-cells are always glue along an <em>entire</em> <I>(d-1)</I>-cells.

But as we can see in the second example (Right), the condition that all the darts of the cell are linked in not sufficient. Indeed, in this example, all the darts of the 2-cell between the cube and the pyramid are linked together by \f$ \beta_3\f$. However, this configuration does not correspond to an orientable 3D quasi-manifold. Indeed, the operation of gluing two <I>d</I>-cells along one <I>(d-1)</I>-cell must preserve the structure of the initial <I>(d-1)</I>-cell.

To avoid these two kinds of configurations, conditions are added on \f$ \beta\f$ pointers compositions (see Section \ref sec_definition "Mathematical Definitions", condition (4) of the definition of combinatorial maps). Intuitively these conditions say that if two darts are linked by \f$ \beta_i\f$, then all the required darts are linked by \f$ \beta_i\f$ two by two in such a way that neighborhood relations are preserved.

We say that a combinatorial map is <I>valid</I> if it satisfies all the conditions on \f$ \beta\f$ pointers and on association between darts and attributes. High level operations provided on combinatorial maps ensure that these conditions are always satisfied. Sometimes, it can be useful to use low level operations in a specific algorithm, for example to modify locally a combinatorial map in a really fast way. In such a case, additional operations may be needed to restore these validity conditions.

\subsection ssec-comparison-cmaps-with-gmaps Comparison with Generalized Maps

Combinatorial maps and \ref ChapterGeneralizedMap "generalized maps" are very similar: they are both based on darts and functions, and they both allow to represent quasi-manifold <I>n</I>D objects. This explains that they share their main concepts.

However, they have three main differences. Firstly, generalized maps allow to represent non-orientable and orientable objects while combinatorial maps allow only to represent orientable objects. Secondly, generalized maps are homogeneous in each dimension since all functions are involutions, while combinatorial maps are not homogeneous since one function is a permutation while other ones are involutions. This homogeneity simplifies algorithms for generalized maps since it allows to avoid a specific case for the first dimension. Thirdly, a generalized map requires twice the number of darts of a combinatorial map in order to represent an orientable object.

Considering these different advantages and drawbacks, you can choose to use generalized maps or combinatorial maps depending on the needs of your application.

\section secsoftwaredesign Software Design

The diagram in \cgalFigureRef{fig_cmap_diagramme_class} shows the different classes of the package. `Combinatorial_map` is the main class (see Section \ref sseccombinatorialmap "Combinatorial Maps"). It allows to manage darts and attributes (see Section \ref ssecattributes "Cell Attributes"). Users can customize a combinatorial map thanks to an items class (see Section \ref ssecitem "Combinatorial Map Items"), which defines the information associated with darts and the attribute types. These types may be different for different dimensions, and they may also be void (note that the main concepts of `GenericMap`, `GenericMapItems` and `CellAttribute` are shared between combinatorial maps and generalized maps).

The darts and attributes are accessed through <I>descriptors</I> (either Indices or Handles). A handle is a model of the `Handle` concept, thus supporting the two dereference operators `operator*` and `operator->`. All handles are model of `LessThanComparable` and `Hashable`, that is they can be used as keys in containers such as `std::map` and `std::unordered_map`. An index is a model of the `Index` concept, which is mainly an integer which is convertible from and to std::size_t. Indices can be used as index into vectors which store properties (cf. one example in Section \ref ssecexample3DCMWI "3D Combinatorial Map Using Indices").

\cgalFigureBegin{fig_cmap_diagramme_class,cmap_diagramme_class.svg}
UML diagram of the main classes of the package. k is the number of non void attributes.
\cgalFigureEnd

\subsection sseccombinatorialmap Combinatorial Maps

The class `Combinatorial_map<d,Items,Alloc>` is a model of the `CombinatorialMap` concept which refines the generic concept of `GenericMap`. It has three template parameters standing for the dimension of the combinatorial map (an  `unsigned int`), an items class (a model of the  `GenericMapItems` concept), and an allocator which must be a model of the allocator concept of the \stl. %Default classes are provided for the items and the allocator classes.

The main role of the class `Combinatorial_map` is the storage and the management of darts. It allows to create or remove an isolated dart from the combinatorial map. The \link GenericMap::Dart_descriptor `Dart_descriptor`\endlink type defines a descriptor to the type of used darts (given in the items class). `Combinatorial_map` provides several <I>ranges</I> which allow to iterate over specific subsets of darts of the combinatorial map (see Section \ref ssecrange "Iterating over Orbits, Cells, and Attributes"). It also defines several methods to link and to unlink darts by \f$ \beta_i\f$s (see Section \ref sseclinkdarts "Sewing Orbits and Linking Darts"). We said that a dart <I>d0</I> is <I>i</I>-free  if \f$ \beta_i\f$(<I>d0</I>)=\f$ \varnothing\f$. The \f$ \varnothing\f$ constant is represented in the class `Combinatorial_map` through a `Dart_descriptor` called \link CombinatorialMap::null_dart_descriptor `null_dart_descriptor`\endlink. Finally, some high level operations are defined as global functions taking a `Combinatorial_map` as argument (see Section \ref ssecoperations "Removal and Insertion Operations")

The second role of the class `Combinatorial_map` is the storage and the management of attributes. It allows to create or remove an attribute, and provides methods to associate attributes and cells. A range is defined for each <I>i</I>-attribute allowing to iterate over all the <I>i</I>-attributes of the combinatorial map. Finally, `Combinatorial_map` defines several types allowing to manage the attributes. We can use \link GenericMap::Attribute_descriptor `Combinatorial_map::Attribute_descriptor<i>::type`\endlink for a descriptor to the <I>i</I>-attributes (and the const version \link GenericMap::Attribute_const_descriptor `Combinatorial_map::Attribute_const_descriptor<i>::type` \endlink) and \link GenericMap::Attribute_type  `Combinatorial_map::Attribute_type<i>::type` \endlink for the type of the <I>i</I>-attributes.

All information associated to darts (information, \f$ \beta\f$ links and attributes) are accessed through member functions in `CombinatorialMap`.

\subsection ssecitem Combinatorial Map Items

The `GenericMapItems` concept defines information associated with darts, and attribute types of a combinatorial map. It contains one inner class named \link GenericMapItems::Dart_wrapper `Dart_wrapper`\endlink, having one template parameter, `Map`, a model of `GenericMap` concept. The \link GenericMapItems::Dart_wrapper `Dart_wrapper<Map>`\endlink class can provide two local types: `%Dart_info` for the information associated with darts, and `%Attributes` which defines the attributes and their types.

If `%Dart_info` is not defined or if it is equal to `void`, no information is associated with darts.

The `%Attributes` tuple must contain at most <I>d</I>+1 types (one for each possible cell dimension of the combinatorial map). Each type of the tuple must be either a model of the `CellAttribute` concept or `void`. The first type corresponds to 0-attributes, the second to 1-attributes and so on. If the <i>i <sup>th</sup></i> type in the tuple is  `void`, <I>(i-1)</I>-attributes are disabled: we say that <I>(i-1)</I>-attributes are <I>void</I>. Otherwise, <I>(i-1)</I>-attributes are enabled and have the given type: we say <I>(i-1)</I>-attributes are <I>non void</I>. If the size of the tuple is <I>k</I>, with <I>k</I> \f$ < \f$ \link GenericMap::dimension `dimension`\endlink +1, \f$ \forall \f$ <I>i</I>: <I>k</I> \f$ \leq \f$ <I>i</I> \f$ \leq \f$ \link GenericMap::dimension `dimension`\endlink, <I>i</I>-attributes are void. If this type is not defined, all attributes are disabled.

The class `Generic_map_min_items` is a model of the `GenericMapItems` concept which can be used for default behaviors. It defines `void` as type of information associated with darts, and `Attributes` as empty tuple.

\subsection ssecattributes Cell Attributes

The class `Cell_attribute<Map,Info_,Tag,OnMerge,OnSplit>`, a model of the `CellAttribute` concept, represents an attribute associated with a cell of a combinatorial map. The  template parameter `Map` must be a model of the `GenericMap` concept. The attribute stores a descriptor to one dart of its associated cell when the template parameter `Tag` is \link CGAL::Tag_true `Tag_true`\endlink. `Info_` is the type of information stored in the attribute. It may be `void`. `OnMerge` and `OnSplit` must be either `Null_functor`, or models of the `Binary Function` concept having two references to a model of `CellAttribute` as type of both parameters and `void` as return type. There are two default parameters for `OnMerge` and `OnSplit`, which are `Null_functor`, a default parameter for `Tag` which is `Tag_true`, and a default parameter for `Info_` which is `void`.

If `Info_` is different from `void`, the class `Cell_attribute` contains two methods `info()` returning the information contained in the attribute (const and non const version). The information is returned by reference, thus the non const version allows the modification of the information.

Two attributes are merged when their corresponding cells are merged into one cell during some operation. In this case, the functor `OnMerge` is called, unless it is equal to `Null_functor`.  This functor allows the user to define its own custom behavior when two attributes are merged (for example if the information is a color, we can compute the average color of the two initial attributes, and affect this value to the first attribute, see example in Section \ref sseccombimapwithcolor "Combinatorial Map With Attributes"). Similarly, the functor `OnSplit` is called when one attribute is split in two, because its corresponding cell is split in two during some operation, unless it is equal to `Null_functor`. In any high level operation, `OnMerge` is called before to start the operation (i.e.\ before modifying the combinatorial map), and `OnSplit` is called when the operation is finished (i.e.\ after all the modifications were made).

In addition, there are dynamic onmerge and onsplit functions that can be associated to i-attributes, and modified, thanks to the \link GenericMap::onmerge_function() `onmerge_function()`\endlink and \link GenericMap::onsplit_function() `onsplit_function()`\endlink. When these functions are set, they are also called in addition to the previous mechanism when two attributes are merged or one attribute is split into two (see example in Section \ref sseccombimapdynamicattibute "Use of Dynamic Onmerge and Onsplit Functors").

What we said for the dart also holds for the cell attribute. The combinatorial map can be used with any user defined model of the `CellAttribute` concept.

\subsection ssecexampledef Example of Combinatorial Map Definition

Here comes an example of two combinatorial map definitions. The first case `Example_cmap4` defines a 4D combinatorial map which uses all the default values (`Generic_map_min_items`). The second example `Example_custom_cmap3` uses its own model of the `GenericMapItems` concept. In this model, a `double` is associated as information on darts, and an attribute containing an integer is associated to edges.

\code{.cpp}

typedef CGAL::Combinatorial_map<4> Example_cmap4;

struct Example_items_3
{
  template <class CMap>
  struct Dart_wrapper
  {
    typedef double Dart_info;
    typedef CGAL::Cell_attribute<CMap, int> Edge_attrib;
    typedef std::tuple<void,Edge_attrib> Attributes;
  };
};
typedef CGAL::Combinatorial_map<3, Example_items_3> Example_custom_cmap3;

\endcode

\subsection ssecCMapIndicesHandles Indices or Handles

By default, descriptors used to access darts and attributes are handles, and the darts and attributes are stored in a `Compact_container`. To use the index version, you should define the type `Use_index` to `CGAL::Tag_true` in the item class like in the code below. You can also define the type `Index_type` used to store indices (`std::uint32_t` by default when this type is not defined).

\code{.cpp}

struct Items_with_indices
{
  typedef CGAL::Tag_true Use_index; // CGAL::Tag_false by default
  typedef std::uint16_t Index_type; // std::uint32_t by default
  template <class CMap>
  struct Dart_wrapper
  {
    typedef CGAL::Cell_attribute<CMap, int> Edge_attrib;
    typedef std::tuple<void,Edge_attrib> Attributes;
  };
};
typedef CGAL::Combinatorial_map<3, Items_with_indices> Cmap3_with_index;

\endcode

The two main interests of the index version comparing to the handle ones are: (1) it has a lower memory footprint than a 64-bit pointer based version; (2) indices are contiguous, they can be used as index into vectors which store properties. The main interest of the handle version is the fact that handles can be dereferenced, which can simplify some code.

\section Combinatorial_mapIteration Iteration and Creation Operations

An important operation in combinatorial maps consists in iterating over specific subsets of darts or over attributes. For that, several <I>ranges</I> are offered (see Section \ref ssecrange "Iterating over Orbits, Cells, and Attributes"). A range is a model of the `Range` concept, thus supporting the two methods `begin()` and `end()` allowing to iterate over all the elements in the range. Several functions allow to create specific configurations of darts into a combinatorial map (see Section \ref ssecconstruction "Construction Operations"). Darts can be marked during operations, for example when performing a breadth-first search traversal, thanks to Boolean marks (see Sections \ref ssecadvmarks "Boolean Marks"). In the following, we denote by `d0`, `d1`, `d2` for dart descriptors, and identify in explanations the descriptor and the object it describes.

\subsection ssecrange Iterating over Orbits, Cells, and Attributes

The combinatorial map offers iterators to traverse the darts of a specific orbit, to traverse all darts of one cell, or one dart per cell, and to traverse all <I>i</I>-attributes.

Instead of the `begin()/end()` member function pair as we know it from \stl containers, and from most \cgal data structures, the combinatorial map defines range classes which are all models of the `Range` concept.

There are three different categories of dart range classes:
<UL>

<LI>\link GenericMap::Dart_range `Dart_range`\endlink: range of all the darts of a combinatorial map;

<LI>\link GenericMap::Dart_of_orbit_range `Dart_of_orbit_range<Beta...>`\endlink: range of all the darts of the orbit \f$ \langle{}\f$`Beta...`\f$ \rangle{}\f$(<I>d0</I>) for a given <I>d0</I>. `Beta...` is a sequence of integers  \f$ i_1\f$,..., \f$ i_k\f$,  each \f$ i_j\f$\f$ \in \f${0, ..., <I>d</I>}.  These integers must satisfy: \f$ i_1\f$\f$ <\f$\f$ i_2\f$\f$ <\f$...\f$ <\f$\f$ i_k\f$, and (\f$ i_1\f$ \f$ \neq \f$ 0 or \f$ i_2 \f$ \f$ \neq \f$ 1)  (for example \link GenericMap::Dart_of_orbit_range `Dart_of_orbit_range<1,2>`\endlink for the orbit \f$ \langle{}\f$\f$ \beta_1\f$,\f$ \beta_2\f$\f$ \rangle{}\f$(<I>d0</I>));

<LI>\link GenericMap::Dart_of_cell_range `Dart_of_cell_range<i,dim>`\endlink: range of all the darts of the <I>i</I>-cell containing a given dart. The <I>i</I>-cell is considered in dimension `dim` (with 0 \f$  \leq \f$ <I>dim</I> \f$ \leq \f$ <I>d</I>, <I>dim</I>=<I>d</I> by default), with 0 \f$ \leq \f$ <I>i</I> \f$ \leq \f$ <I>dim+1</I>. If <I>i</I>=<I>dim+1</I>, \link GenericMap::Dart_of_cell_range `Dart_of_cell_range<i,dim>`\endlink is the range of all the darts of the connected component containing a given dart.
</UL>

There are also two different classes of ranges containing one dart per <I>i</I>-cell. Note that in these classes, the dart of each <I>i</I>-cell can be any dart of the cell. Moreover, each <I>i</I>-cell (and <I>j</I>-cell in the second case) is considered in dimension `dim` (with  0 \f$ \leq \f$ <I>dim</I> \f$ \leq \f$ <I>d</I>, <I>dim=d</I> by default).
<UL>
<LI>\link GenericMap::One_dart_per_cell_range `One_dart_per_cell_range<i,dim>`\endlink: range containing one dart of each <I>i</I>-cell of the combinatorial map, 0 \f$ \leq \f$ <I>i</I> \f$ \leq \f$ <I>dim+1</I> (for example \link GenericMap::One_dart_per_cell_range `One_dart_per_cell_range<2>`\endlink for the range of one dart per 2-cell of the combinatorial map);

<LI>\link GenericMap::One_dart_per_incident_cell_range `One_dart_per_incident_cell_range<i,j,dim>`\endlink: range containing one dart of each <I>i</I>-cell incident to the <I>j</I>-cell containing a given dart, with 0 \f$ \leq \f$ <I>i</I> \f$ \leq \f$ <I>dim+1</I> and  0 \f$ \leq \f$ <I>j</I> \f$ \leq \f$ <I>dim+1</I> (for example \link GenericMap::One_dart_per_incident_cell_range `One_dart_per_incident_cell_range<0,3>`\endlink for the range of one dart per vertex of the volume incident to the starting dart). If <I>i</I>=<I>j</I>, the range contains only the given dart.
</UL>

The iterators of the \link GenericMap::Dart_range `Dart_range`\endlink are bidirectional iterators,  while the iterators of the other four ranges are forward iterators.  The value type of all these iterators is `Dart` thus all these iterators can be directly used as \link GenericMap::Dart_descriptor `Dart_descriptor`\endlink.

Additionally, there is a range over non void <I>i</I>-attributes: \link GenericMap::Attribute_range `Attribute_range<i>::type`\endlink, having a bidirectional iterator with value type \link GenericMap::Attribute_type `Attribute_type<i>::type`\endlink.

For each range, there is an associated const range, a model of the `ConstRange` concept. You can find some examples of ranges in Section \ref ssecexample3DCM "A 3D Combinatorial Map".

\subsection ssecconstruction Construction Operations

Several functions allow to create specific configurations of darts into a combinatorial map. Existing darts in the combinatorial map are not modified. Note that the dimension of the combinatorial map must be large enough: darts must contain all the \f$ \beta\f$ pointers used by the operation. All these functions return a \link GenericMap::Dart_descriptor `Dart_descriptor`\endlink to a new dart created during the operation.

<UL>
<LI>`cm.`\link GenericMap::make_edge `make_edge()`\endlink: creates an isolated edge (two darts linked by \f$ \beta_2\f$); dimension must be greater or equal than two;
<LI>`cm.`\link GenericMap::make_combinatorial_polygon `make_combinatorial_polygon(lg)`\endlink: creates an isolated combinatorial polygon of length `lg` (`lg` darts linked by \f$ \beta_1\f$), for `lg>0`; dimension must be greater or equal than one;
<LI>`cm.`\link GenericMap::make_combinatorial_tetrahedron `make_combinatorial_tetrahedron()`\endlink: creates an isolated combinatorial tetrahedron (four combinatorial triangles linked together by \f$ \beta_2\f$); dimension must be greater or equal than two;
<LI>`cm.`\link GenericMap::make_combinatorial_hexahedron `make_combinatorial_hexahedron()`\endlink: creates an isolated combinatorial hexahedron (six combinatorial quadrangles linked together by \f$ \beta_2\f$); dimension must be greater or equal than two.
</UL>

\subsection ssecadvmarks Boolean Marks

It is often necessary to mark darts, for example to retrieve in \cgalBigO{1} if a given dart was already processed during a specific algorithm, for example,  iteration over a given range. Users can also mark specific parts of a combinatorial map (for example mark all the darts belonging to objects having specific semantics). To answer these needs, a `GenericMap` has a certain number of Boolean marks (fixed by the constant \link GenericMap::NB_MARKS `NB_MARKS`\endlink). When one wants to use a Boolean mark, the following methods are available (with `cm` an instance of a combinatorial map):
<ul>
<li> get a new free mark: `size_type m = cm.`\link GenericMap::get_new_mark `get_new_mark()`\endlink (throws the exception Exception_no_more_available_mark if no mark is available);
<li> set mark `m` for a given dart `d0`: `cm.`\link GenericMap::mark `mark(d0,m)`\endlink;
<li> unset mark `m` for a given dart `d0`: `cm.`\link GenericMap::unmark `unmark(d0,m)`\endlink;
<li> test if a given dart `d0` is marked for `m`: `cm.`\link GenericMap::is_marked `is_marked(d0,m)`\endlink;
<li> unmark all the darts of `cm` for `m`: `cm.`\link GenericMap::unmark_all `unmark_all(m)`\endlink;
<li> negate mark `m` of all the darts of `cm`: `cm.`\link GenericMap::negate_mark `negate_mark(m)`\endlink. All the marked darts become unmarked and all the unmarked darts become marked;
<li> free mark `m`: `cm.`\link GenericMap::free_mark `free_mark(m)`\endlink. This method unmarks all the darts of `cm` for `m` before freeing it.
</ul>

It is important to free a mark when it is no longer needed, otherwise you may at some point run out of marks.

The following example illustrates how to use marks. Two combinatorial tetrahedra are created and 3-sewn (see Section \ref sseclinkdarts "Sewing Orbits and Linking Darts" for a detailed description of the sew operation). Then a mark is reserved and used to mark all the darts belonging to the first combinatorial tetrahedron. Finally, these tetrahedron are merged. The marks allow us to know which darts come from the first and second tetrahedron.

\cgalExample{Combinatorial_map/map_3_marks.cpp}

\section ssecmodoperations Modification Operations

Several operations allow to modify a given combinatorial map. There are two main categories of modification operations:
<UL>
<LI>\ref CombinatorialMap::sew "Sew", \ref CombinatorialMap::link_beta "link_beta", \ref CombinatorialMap::unsew "unsew" and \ref CombinatorialMap::unlink_beta "unlink_beta" which modify some existing \f$ \beta\f$ pointers, without creating or removing darts (see Section \ref sseclinkdarts "Sewing Orbits and Linking Darts");
<LI>Removal and insertion of cells which modify both darts and \f$ \beta\f$ pointers (see Section \ref ssecoperations "Removal and Insertion Operations").
</UL>

\subsection sseclinkdarts Sewing Orbits and Linking Darts

The `CombinatorialMap` defines two groups of methods to modify the \f$ \beta\f$ pointers of existing darts.

The sew and unsew methods iterate over two orbits in order to link or unlink specific darts two by two. Intuitively, a \link CombinatorialMap::sew `sew<i>`\endlink operation glues two <I>i</I>-cells by identifying two of their <I>(i-1)</I>-cells (see example in \cgalFigureRef{fig_cmap_example_3d_sew} where \link CombinatorialMap::sew `sew<3>`\endlink is used to glue two 3-cells along one 2-cell). Reciprocally, a \link CombinatorialMap::unsew `unsew<i>`\endlink operation un-glues two <I>i</I>-cells which were glued along one of their <I>(i-1)</I>-cells. These methods guarantee that given a valid combinatorial map and a possible operation we obtain a valid combinatorial map as result of the operation.

\cgalAdvancedBegin
The \link CombinatorialMap::link_beta `link_beta`\endlink and \link CombinatorialMap::unlink_beta `unlink_beta`\endlink methods only modify the pointer of two darts: the obtained combinatorial maps may be not valid. These operations can be useful to use low level operations in a specific algorithm, for example to modify locally a combinatorial map in a really fast way. In such a case, additional operations may be needed to restore the validity conditions.
\cgalAdvancedEnd


Linking two darts <I>d1</I> and <I>d2</I> by \f$ \beta_i\f$, with 2 \f$ \leq \f$ <I>i</I> \f$ \leq \f$ <I>d</I> and <I>d1</I> \f$ \neq \f$ <I>d2</I>, consists in modifying two \f$ \beta_i\f$ pointers such that \f$ \beta_i\f$(<I>d1</I>)=<I>d2</I> and \f$ \beta_i\f$(<I>d2</I>)=<I>d1</I>. For <I>i</I>=1, the modification is \f$ \beta_1\f$(<I>d1</I>)=<I>d2</I> (and thus \f$ \beta_0\f$(<I>d2</I>)=<I>d1</I> by definition of \f$ \beta_0\f$); in this case we can have <I>d1=d2</I> (a dart linked with itself corresponds to an edge which is a loop).

Reciprocally, unlinking a given dart <I>d0</I> by \f$ \beta_i\f$, with 2 \f$ \leq \f$ <I>i</I> \f$ \leq \f$ <I>d</I>, consists in modifying two \f$ \beta_i\f$ pointers such that \f$ \beta_i\f$(\f$ \beta_i\f$(<I>d0</I>))=\f$ \varnothing\f$ and \f$ \beta_i\f$(<I>d0</I>)=\f$ \varnothing\f$. For <I>i=1</I>, the modification is \f$ \beta_1\f$(<I>d0</I>)=\f$ \varnothing\f$ (and thus \f$ \beta_0\f$(\f$ \beta_1\f$(<I>d0</I>))=\f$ \varnothing\f$ by definition of \f$ \beta_0\f$). Note that is it possible to unlink a given dart for \f$ \beta_i\f$ only if it is not <I>i</I>-free.

\cgalFigureBegin{fig_cmap_example_3d_sew,cmap_example_3d_sew.svg}
Example of 3-sew operation. Left: A 3D combinatorial map containing two volumes that are not connected, with 2-attributes. Each attribute contains a color in RGB format, and there are four 2-cells associated with attributes. Associations between darts and attributes are drawn with red segments. Right: The 3D combinatorial map obtained as result of \link CombinatorialMap::sew `sew<3>(1,5)`\endlink (or \link CombinatorialMap::sew `sew<3>(2,8)`\endlink, or \link CombinatorialMap::sew `sew<3>(3,7)`\endlink, or \link CombinatorialMap::sew `sew<3>(4,6)`\endlink). Darts (1,5), (2,8), (3,7) and (4,6) are linked together by \f$ \beta_3\f$. The two 2-cells <I>c1</I>={1,2,3,4} and <I>c2</I>={5,6,7,8} are merged after the sew into the 2-cell {1,2,3,4,5,6,7,8}. We are in the case where the two attributes are non `nullptr`, thus the first one is kept, and all the darts of <I>c2</I> are associated with the first attribute.
\cgalFigureEnd

The \link CombinatorialMap::sew `sew<i>(d1,d2)`\endlink method consists mainly to link two by two several darts by \f$ \beta_i\f$. This operation is possible only if there is a bijection <I>f</I> between all the darts of the orbit <I>D1</I>=\f$ \langle{}\f$\f$ \beta_1\f$,...,\f$ \beta_{i-2}\f$,\f$ \beta_{i+2}\f$,...,\f$ \beta_d\f$\f$ \rangle{}\f$(<I>d1</I>) and <I>D2</I>=\f$ \langle{}\f$\f$ \beta_1\f$,...,\f$ \beta_{i-2}\f$,\f$ \beta_{i+2}\f$,..., \f$ \beta_d\f$\f$ \rangle{}\f$(<I>d2</I>) satisfying: <I>f</I>(<I>d1</I>)=<I>d2</I>, and for all <I>e</I>\f$ \in \f$ <I>D1</I>,  for all <I>j</I>\f$ \in \f${1,..., i-2,i+2,...,<I>d</I>}, <I>f</I>(\f$ \beta_j\f$(<I>e</I>))=\f$ \beta_j^{-1}\f$(<I>f</I>(<I>e</I>)). Intuitively, this condition ensures the validity of the combinatorial map by verifying that condition discussed in Section \ref sseccombimapvalidity "Combinatorial Map Properties" will be satisfied after the operation. This condition can be tested by using the method \link CombinatorialMap::is_sewable `is_sewable<i>(d1,d2)`\endlink. For example, the function \link CombinatorialMap::is_sewable `is_sewable<3>`\endlink would return `false` if we tried to 3-sew a triangular facet with a quad facet. Note that given two darts <I>d1</I> and <I>d2</I>, if there is such a bijection, it is uniquely defined. So giving the two darts as arguments of the \link CombinatorialMap::sew `sew<i>`\endlink is enough to retrieve all the pairs of darts to link.  If such a bijection exists, the \link CombinatorialMap::sew `sew<i>(d1,d2)`\endlink operation consists only in linking by \f$ \beta_i\f$ each couple of darts <I>d3</I> and <I>d4</I> such that <I>d3</I>=<I>f</I>(<I>d4</I>).

In addition, the sew operation updates the associations between darts and non void attributes in order to guarantee that all the darts belonging to a given cell are associated with the same attribute (which is a condition of combinatorial map validity). For each couple of <I>j</I>-cells <I>c1</I> and <I>c2</I> that are merged into one <I>j</I>-cell during the sew, we have to update the two associated attributes <I>attr1</I> and <I>attr2</I>. If both are `nullptr`, there is nothing to do. If one is `nullptr` and the other not, we only associate the non `nullptr` attribute to all the darts of the resulting cell. When the two attributes are non `nullptr`, we first apply functor \link CellAttribute::On_merge `On_merge`\endlink on the two attributes <I>attr1</I> and <I>attr2</I> (see Section \ref ssecattributes "Cell Attributes"). Then, we associate the attribute <I>attr1</I> to all darts of the resulting <I>j</I>-cell. Finally, attribute <I>attr2</I> is removed from the combinatorial map.

Note that when the two attributes are non `nullptr`, the first one is kept. But user can customize this behavior in order to update the information contained in the attributes according to its needs. For that, we can define a specific functor, and use it as template argument for \link CellAttribute::On_merge `On_merge`\endlink parameter of the `Cell_attribute` definition. This functor can for example copy the information of the second attribute in the information of the first one to make as if the second attribute is kept.

For example, in \cgalFigureRef{fig_cmap_example_3d_sew}, we want to 3-sew the two initial volumes. \link CombinatorialMap::sew `sew<3>(1,5)`\endlink links by \f$ \beta_3\f$ the pairs of darts (1,5), (2,8), (3,7) and (4,6), thus the combinatorial map obtained is valid. 2-attributes are updated so that all the darts belonging to the 2-cell containing dart 1 become associated to the same 2-attribute after the operation.

Similarly, \link CombinatorialMap::unsew `unsew<i>(d0)`\endlink operation unlinks \f$ \beta_i\f$ for all the darts in the orbit  \f$ \langle{}\f$\f$ \beta_1\f$,..., \f$ \beta_{i-2}\f$,\f$ \beta_{i+2}\f$,...,\f$ \beta_d\f$\f$ \rangle{}\f$(<I>d0</I>),  and thus guarantees to obtain a valid combinatorial map. This operation is possible for any non <I>i</I>-free dart.

As for the sew operations, attributes are updated to guarantee that two darts belonging to two different <I>j</I>-cells are associated to two different <I>j</I>-attributes. If the unsew operation splits a <I>j</I>-cell <I>c</I> in two <I>j</I>-cells <I>c1</I> and <I>c2</I>, and if <I>c</I> is associated to a <I>j</I>-attribute <I>attr1</I>, then this attribute is duplicated into <I>attr2</I>, and all the darts belonging to <I>c2</I> are associated with this new attribute. Finally, we call the functor \link CellAttribute::On_split `On_split`\endlink on the two attributes <I>attr1</I> and <I>attr2</I> (see Section \ref ssecattributes "Cell Attributes").

Let us consider the combinatorial map given in \cgalFigureRef{fig_cmap_example_3d_sew} (Right). If we call \link CombinatorialMap::unsew `unsew<3>(2)`\endlink, we obtain the combinatorial map in \cgalFigureRef{fig_cmap_example_3d_sew} (Left) (except for the color of the attribute associated to the 2-cell {5,6,7,8} which would be <TT>#00ff00</TT>). The \link CombinatorialMap::unsew `unsew<3>`\endlink operation has duplicated the 2-attribute associated to the 2-cell {1,2,3,4,5,6,7,8} since this 2-cell is split in two after the unsew operation.

\cgalAdvancedBegin
If one wants to modify a combinatorial map <I>manually</I>, it is  possible to switch off the updating between darts and attributes by calling \link GenericMap::set_automatic_attributes_management `set_automatic_attributes_management(false)`\endlink before to call \link CombinatorialMap::sew `sew<i>(d1,d2)`\endlink and \link CombinatorialMap::unsew `unsew<i>(d0)`\endlink. In these cases, the combinatorial map obtained may be no longer valid due to incorrect associations between darts and attributes.  A call later to \link GenericMap::set_automatic_attributes_management `set_automatic_attributes_management(true)`\endlink will correct the invalid non void attributes.

In \cgalFigureRef{fig_cmap_example_3d_sew} (Left), if we call \link CombinatorialMap::sew `sew<3>(1,5)`\endlink, the resulting combinatorial map is similar to the combinatorial map of \cgalFigureRef{fig_cmap_example_3d_sew} (Right) (we have linked by \f$ \beta_3\f$ the pairs of darts (1,5), (2,8), (3,7) and (4,6)), but associations between darts and attributes are not valid. Indeed, we have kept the four initial attributes and all the associations between darts and attributes, thus two darts belonging to the same 2-cell (for example darts 1 and 5) are associated with two different attributes.

We can also use the \link CombinatorialMap::link_beta `link_beta<i>(d1,d2)`\endlink which links `d1` and `d2` by \f$ \beta_i\f$ without modifying the other links.  Association between darts and attributes are only modified for darts `d1` and `d2`, and similarly as for \link CombinatorialMap::sew `sew<i>`\endlink, this updating can be avoided by calling \link GenericMap::set_automatic_attributes_management `set_automatic_attributes_management(false)`\endlink before to call \link CombinatorialMap::link_beta `link_beta<i>(d1,d2)`\endlink. Lastly, we can use \link CombinatorialMap::unlink_beta `unlink_beta<i>(d0)`\endlink to unlink `d0` for \f$ \beta_i\f$. In this last case, there is no modification of association between darts and attributes.

In \cgalFigureRef{fig_cmap_example_3d_sew} (Left), if we call \link CombinatorialMap::link_beta `link_beta<3>(1,5)`\endlink, in the resulting combinatorial map we have now \f$ \beta_3\f$(1)=5 and \f$ \beta_3\f$(5)=1. This combinatorial map is no longer valid (for example dart 2 is 3-free and we should have \f$ \beta_3\f$(2)=8).
\cgalAdvancedEnd

\subsection ssecoperations Removal and Insertion Operations

The following high level operations are defined. All these methods ensure that given a valid combinatorial map and a possible operation, the modified combinatorial map is also valid.

The first one is `cm.`\link GenericMap::remove_cell `remove_cell<i>(d0)`\endlink which modifies the combinatorial map to remove the <I>i</I>-cell containing dart `d0`, with 0 \f$ \leq \f$ <I>i</I>\f$ \leq \f$ <I>d</I>. This operation is possible  if <I>i</I>=<I>d</I> or if the given <I>i</I>-cell is incident to at most two <I>(i+1)</I>-cells which can be tested thanks to `cm.`\link GenericMap::is_removable `is_removable<i>(d0)`\endlink. If the removed <I>i</I>-cell was incident to two different <I>(i+1)</I>-cells, these two cells are merged into one <I>(i+1)</I>-cell. In this case, the \link CellAttribute::On_merge `On_merge`\endlink functor is called if two <I>(i+1)</I>-attributes are associated to the two <I>(i+1)</I>-cells. If the <I>i</I>-cell is associated with a non void attribute, it is removed from the combinatorial map (see three examples on \cgalFigureRef{fig_cmap_insert_vertex}, \cgalFigureRef{fig_cmap_insert_edge} and \cgalFigureRef{fig_cmap_insert_facet}).

\cgalFigureBegin{fig_cmap_insert_vertex,cmap_insert_vertex.svg}
Example of \link GenericMap::insert_cell_0_in_cell_1 `insert_cell_0_in_cell_1`\endlink and \link GenericMap::remove_cell `remove_cell<0>`\endlink operations. Left: Initial combinatorial map. Right: After the insertion of a 0-cell in the 1-cell containing dart `d1`. Now if we remove the 0-cell containing dart `d2`, we obtain the initial combinatorial map.
\cgalFigureEnd

The inverse operation of the removal is the insertion operation. Several versions exist, sharing a common principle. They consist in adding a new <I>i</I>-cell <em>inside</em> an existing <I>j</I>-cell, <I>i</I>\f$ <\f$<I>j</I>, by splitting the <I>j</I>-cell into several <I>j</I>-cells. Contrary to `remove_cell<i>`, is it not possible to define a unique `insert_cell_i_in_cell_j<i,j>` function because parameters are different depending on `i` and `j`.

`cm.`\link GenericMap::insert_cell_0_in_cell_1 `insert_cell_0_in_cell_1(d0)`\endlink adds a 0-cell in the 1-cell containing dart `d0`. The 1-cell is split in two. This operation is possible if `d0`\f$ \in \f$ \link GenericMap::darts `cm.darts()`\endlink (see example on \cgalFigureRef{fig_cmap_insert_vertex}).

`cm.`\link GenericMap::insert_cell_0_in_cell_2 `insert_cell_0_in_cell_2(d0)`\endlink adds a 0-cell in the 2-cell containing dart `d0`. The 2-cell is split in triangles, one for each initial edge of the facet. This operation is possible if `d0`\f$ \in \f$ \link GenericMap::darts `cm.darts()`\endlink (see example on \cgalFigureRef{fig_cmap_triangulation}).

\cgalFigureBegin{fig_cmap_triangulation,cmap_triangulation.svg}
Example of \link GenericMap::insert_cell_0_in_cell_2 `insert_cell_0_in_cell_2`\endlink operation.
\cgalFigureEnd

`cm.`\link GenericMap::insert_cell_1_in_cell_2 `insert_cell_1_in_cell_2(d1,d2)`\endlink adds a 1-cell in the 2-cell containing darts `d1` and `d2`, between the two 0-cells containing darts `d1` and `d2`. The 2-cell is split in two. This operation is possible if <I>d1</I>\f$ \in \f$ \f$ \langle{}\f$\f$ \beta_1\f$\f$ \rangle{}\f$(<I>d2</I>) which can be tested thanks to `cm.`\link GenericMap::is_insertable_cell_1_in_cell_2 `is_insertable_cell_1_in_cell_2(d1,d2)`\endlink. In the example on \cgalFigureRef{fig_cmap_insert_edge}, it is possible to insert an edge between darts <I>d2</I> and <I>d3</I>, but it is not possible to insert an edge between <I>d1</I> and <I>d3</I>.

\cgalFigureBegin{fig_cmap_insert_edge,cmap_insert_edge.svg}
Example of \link GenericMap::insert_cell_1_in_cell_2 `insert_cell_1_in_cell_2`\endlink and \link GenericMap::remove_cell `remove_cell<1>`\endlink operations. Left: Initial combinatorial map. Right: After the insertion of two 1-cells: a first one between the two 0-cells containing darts `d2` and `d3`, and a second one incident to the 0-cell containing dart `d1`. Now if we remove the two 1-cells containing darts `d4` and `d5`, we obtain the initial combinatorial map.
\cgalFigureEnd

`cm.`\link GenericMap::insert_dangling_cell_1_in_cell_2 `insert_dangling_cell_1_in_cell_2(d0)`\endlink adds a 1-cell in the 2-cell containing dart `d0`, the 1-cell being attached by only one of its vertex to the 0-cell containing dart `d0`.  This operation is possible if `d0`\f$ \in \f$ \link GenericMap::darts `cm.darts()`\endlink.

`cm.`\link GenericMap::insert_cell_1_between_two_cells_2 `insert_cell_1_between_two_cells_2(d1,d2)`\endlink adds a 1-cell between the two faces containing containing darts `d1` and `d2`, between the two 0-cells containing darts `d1` and `d2`. The 2-cells are merged in one. This operation is possible if <I>d1</I>\f$ \not \in \f$ \f$ \langle{}\f$\f$ \beta_1\f$\f$ \rangle{}\f$(<I>d2</I>) which can be tested thanks to `cm.`\link GenericMap::is_insertable_cell_1_between_two_cells_2 `is_insertable_cell_1_between_two_cells_2(d1,d2)`\endlink.

`cm.`\link GenericMap::insert_cell_2_in_cell_3 `insert_cell_2_in_cell_3(itbegin,itend)`\endlink adds a 2-cell in the 3-cell containing all the darts between `itbegin` and `itend`, along the path of 1-cells containing darts in [`itbegin`,`itend`). The 3-cell is split in two. This operation is possible if all the  darts in [`itbegin`,`itend`) form a closed path inside a same 3-cell  which can be tested thanks to `cm.`\link GenericMap::is_insertable_cell_2_in_cell_3 `is_insertable_cell_2_in_cell_3(itbegin,itend)`\endlink (see example on \cgalFigureRef{fig_cmap_insert_facet}).

\cgalFigureBegin{fig_cmap_insert_facet,cmap_insert_facet.svg}
Example of \link GenericMap::insert_cell_2_in_cell_3 `insert_cell_2_in_cell_3`\endlink and \link GenericMap::remove_cell `remove_cell<2>`\endlink operations.  Left: Initial combinatorial map. Right: After the insertion of a 2-cell along the path of 1-cells containing respectively `d1,d2,d3,d4`. Now if we remove the 2-cell containing dart `d5`, we obtain the initial combinatorial map. \cgalFigureEnd

Some examples of use of these operations are given in Section \ref ssecexempleoperations "High Level Operations".

\cgalAdvancedBegin
If \link GenericMap::set_automatic_attributes_management `set_automatic_attributes_management(false)`\endlink is called, all the future insertion or removal operations will not update non void attributes. These attributes will be updated later by the call to \link GenericMap::set_automatic_attributes_management `set_automatic_attributes_management(true)`\endlink. This can be useful to speed up an algorithm which uses several successive insertion and removal operations. See example \ref ssecAttributesManagement "Automatic attributes management".
\cgalAdvancedEnd

\section Combinatorial_mapExamples Examples

\subsection ssecexample3DCM A 3D Combinatorial Map

In this example, a 3-dimensional combinatorial map is constructed. Two combinatorial tetrahedra are created, then the numbers of cells of the combinatorial map are displayed, and the validity of the combinatorial map is checked. Then, we illustrate the use of ranges to iterate over specific darts. The first loop enumerates all the darts of the first tetrahedron by using the range \link GenericMap::Dart_of_orbit_range `Dart_of_orbit_range<1,2>`\endlink, and the second loop enumerates all the darts of the facet containing dart `d2` by using the range \link GenericMap::Dart_of_orbit_range `Dart_of_orbit_range<1>`\endlink.

\cgalExample{Combinatorial_map/map_3_simple_example.cpp}

The output is:
\verbatim
#Darts=24, #0-cells=8, #1-cells=12, #2-cells=8, #3-cells=2, #ccs=2, valid=1
Number of darts of the first tetrahedron: 12
Number of darts of the facet containing d2: 3
\endverbatim

which gives the number of darts of the combinatorial map, the numbers of different cells, the number of connected components, and finally a Boolean showing the validity of the combinatorial map (a tetrahedron is made up of 12 darts because there are 3 darts per facet and there are 4 facets).

Note the creation in the for loops of the two instances of \link GenericMap::Dart_of_orbit_range `Dart_of_orbit_range`\endlink::`const_iterator`: `it` is the current iterator, and `itend` an iterator to the end of the range. Having `itend` avoids calling \link GenericMap::darts_of_orbit `cm.darts_of_orbit<1,2>(d1)`\endlink`.end()` again and again as in the following example (which is a bad solution):

\code{.cpp}

for (CMap_3::Dart_of_orbit_range<1,2>::const_iterator
     it(cm.darts_of_orbit<1,2>(d1).begin());
     it!=cm.darts_of_orbit<1,2>(d1).end()); ++it)
{...}

\endcode

\subsection Combinatorial_mapHighLevelOperations High Level Operations

\anchor ssecexempleoperations

This example shows some uses of high level operations. First we create a combinatorial hexahedron, the combinatorial map obtained is shown in \cgalFigureRef{fig_cmap_example_insertions} (Left). Then we insert two 1-cells along two opposite 2-cells of the hexahedron. The combinatorial map obtained is shown in \cgalFigureRef{fig_cmap_example_insertions} (Middle). Finally, we insert a 2-cell in the diagonal of the hexahedron in order to split it into two parts. We obtain the combinatorial map shown in \cgalFigureRef{fig_cmap_example_insertions} (Right). We display the characteristics of the combinatorial map and check its validity.

The second part of this example removes the inserted elements. First we remove the inserted 2-cell, then the two inserted 1-cells. We get back the initial combinatorial hexahedron, which is verified by displaying once again the characteristics of the combinatorial map.

\cgalExample{Combinatorial_map/map_3_operations.cpp}

The output is:
\verbatim
#Darts=36, #0-cells=8, #1-cells=14, #2-cells=9, #3-cells=2, #ccs=1, valid=1
#Darts=24, #0-cells=8, #1-cells=12, #2-cells=6, #3-cells=1, #ccs=1, valid=1
\endverbatim

The first line gives the characteristics of the combinatorial map after all the insertions (the combinatorial map drawn in \cgalFigureRef{fig_cmap_example_insertions} (Right)). There are two 3-cells (since the combinatorial hexahedron was split in two by the 2-cell insertion), nine 2-cells (since two 2-cells of the original hexahedron were split in two by the two 1-cell insertions, and a new 2-cell was created during the 2-cell insertion), fourteen 1-cells (since there are two new 1-cells created by the 1-cell insertion) while the number of 0-cells remains unchanged.

The second line is the result after the removal operations. We retrieve the original combinatorial hexahedron since we have removed all the inserted elements.

\cgalFigureBegin{fig_cmap_example_insertions,cmap_example_insertions.svg}
Example of high level operations. Left: Initial 3D combinatorial map after the creation of the combinatorial hexahedron. Middle: Combinatorial map obtained after the two 1-cell insertions. The two 2-cells were split in two. Right: Combinatorial map obtained after the 2-cell insertion. The 3-cell was split in two.
\cgalFigureEnd

\subsection Combinatorial_mapInsertion Insert an Edge Between Two Different Faces

\anchor ssecexempleinsertion

This example shows the use of \link GenericMap::insert_cell_1_between_two_cells_2 `insert_cell_1_between_two_cells_2`\endlink operation. First we create a combinatorial hexahedron and a face with 4 edges. This face is inserted in the face of the hexahedron containing dart d1. We display the characteristics of the combinatorial map and check its validity. Then we count and display the number of 2-free darts.

\cgalExample{Combinatorial_map/map_3_insert.cpp}

The output is:
\verbatim
#Darts=30, #0-cells=12, #1-cells=17, #2-cells=6, #3-cells=1, #ccs=1, valid=1
Number of 2-free darts: 4
\endverbatim

We can verify that there are 6 2-cells after the insertion since the squared face was inserted as a hole in one face of the hexahedron. We can also see that there are 4 2-free darts, which are the darts of the squared face. Since they bound a hole, there is no face filling the hole and thus 4 darts are 2-free.

See also a similar example for Linear cell complex \ref Linear_cell_complexInsert "Insert an Edge Between Two Different Faces".

\subsection Combinatorial_mapA4DGenericMap A 4D Combinatorial Map

In this example, a 4-dimensional combinatorial map is used. Two tetrahedral cells are created and sewn by \f$ \beta_4\f$. Then the numbers of cells of the combinatorial map are displayed, and its validity is checked.

By looking at these numbers of cells, we can see that the 4D combinatorial map contains only one 3-cell. Indeed, the \link CombinatorialMap::sew `sew<4>`\endlink operation has identified by pairs all the darts of the two 3-cells by definition of the sew operation (see Section \ref sseclinkdarts "Sewing Orbits and Linking Darts") which, in 4D, links by \f$ \beta_3\f$ all the darts in \f$ \langle{}\f$\f$ \beta_1\f$,\f$ \beta_2\f$\f$ \rangle{}\f$(<I>d1</I>) and in  \f$ \langle{}\f$\f$ \beta_1\f$,\f$ \beta_2\f$\f$ \rangle{}\f$(<I>d2</I>). The situation is similar (but in higher dimension) to the configuration where we have two triangles in a 3D combinatorial map, and you use  \link CombinatorialMap::sew `sew<3>`\endlink between these two triangles. The two triangles are identified since all their darts are linked by \f$ \beta_3\f$, thus we obtain a 3D combinatorial map containing only one 3-cell. Note that this 3-cell is unbounded since the darts of the two triangles are all 2-free. In the 4D case, the 4-cell is unbounded since all its darts are 3-free.

In this example, we also illustrate how to use the basic methods to build <em>by hand</em> some specific configuration in a combinatorial map. In fact, these functions are already present in the package: function `make_triangle(cm)` is equivalent to \link GenericMap::make_combinatorial_polygon `cm.make_combinatorial_polygon(3)`\endlink and `make_tetrahedral(cm)` is equivalent to \link GenericMap::make_combinatorial_tetrahedron `cm.make_combinatorial_tetrahedron()`\endlink. If we want to create a 4D simplex, we must create five 3D simplexes, and sew them correctly two by two by \f$ \beta_3\f$ (and so on if you want to create higher dimensional combinatorial map).

\cgalExample{Combinatorial_map/map_4_simple_example.cpp}

The output is:
\verbatim
#Darts=24, #0-cells=4, #1-cells=6, #2-cells=4, #3-cells=1, #4-cells=2, #ccs=1, valid=1
\endverbatim

\subsection sseccombimapwithcolor Combinatorial Map With Attributes

In the following example, we illustrate how to specify the 2-attributes in a 3D combinatorial map. For that, we define our own item class using \link Cell_attribute `Cell_attribute<CMap,int,Tag_true,Sum_functor,Divide_by_two_functor>`\endlink as attributes which contain an `int` and which are associated to 2-cells of the combinatorial map.

Functors `Sum_functor` and `Divide_by_two_functor` define a custom behavior: when two attributes `ca1` and `ca2` are merged into `ca1`, the value of `ca1` is the sum of the two initial values. When an attribute `ca1` is split in the two attributes `ca1` and `ca2`, the value of each attribute is half of the first value.

\cgalExample{Combinatorial_map/map_3_with_colored_facets.cpp}

The output is:
\verbatim
20; 7; 7; 7; 7; 7; 13; 13; 13; 13; 13;
2; 7; 7; 7; 7; 7; 2; 13; 13; 13; 13; 13; 5; 10;
#Darts=64, #0-cells=13, #1-cells=24, #2-cells=14, #3-cells=2, #ccs=1, valid=1
\endverbatim

Before the `cm.`\link CombinatorialMap::sew `sew<3>`\endlink, each 2-cell of the first cube is associated with an attribute having 7 as value, and each 2-cell of the second cube with an attribute having 13 as value. During the `cm.`\link CombinatorialMap::sew `sew<3>`\endlink, two 2-cells are merged, thus the functor `Sum_functor` is called on the two associated 2-attributes, and the value of the new 2-cell is the sum of the two previous one: 20.

Then we call \link GenericMap::insert_cell_0_in_cell_2 `insert_cell_0_in_cell_2`\endlink on a dart which belong to this 2-cell. This method splits the existing 2-cell in <I>k</I> 2-cells, <I>k</I> being the number of 1-cells of the initial 2-cell (4 in this example). These splits are made consecutively, thus for the first split, we create a new attribute as copy of the initial one and call functor `Divide_by_two_functor` on these two attributes: the value of each attribute is thus 20/2=10. For the second split, the value of each attribute is thus 10/2=5, and for the last split the value of each attribute is thus 5/2=2 (remember that information contained in 2-attributes in an `int`). At the end, we obtain five 2-attributes with 7 as value, five 2-attributes with 13 as value, and four 2-attributes having respectively 2, 2, 5 and 10 as values.

\subsection sseccombimapdynamicattibute Use of Dynamic Onmerge and Onsplit Functors

In the following example, we show an example of use of dynamic onmerge and onsplit functor. We define our 3D combinatorial map with 2-attributes. Then we create two hexahedra and create all the 2-attributes, having their info initialized to 1.

Step 2 defines the onsplit and onmerge dynamic functors. We can see here that with this mechanism, functors can store data member. This is the case in the example for `Split_functor` which stores a reference to the combinatorial map.

The next operations will call these functors when 2-cells are split or merged. The \link CombinatorialMap::sew `sew<3>`\endlink operation calls 1 onmerge as two faces are identified; the \link GenericMap::insert_cell_0_in_cell_2 `insert_cell_0_in_cell_2`\endlink operation calls 3 onsplit as one face is split in 4.

Lastly we remove the dynamic onmerge functor (step 7). This is done by initializing the functor to a default boost::function. After this initialization, no dynamic merge functor is called when two faces are merged.

\cgalExample{Combinatorial_map/map_3_dynamic_onmerge.cpp}

\subsection ssecexample3DCMWI 3D Combinatorial Map Using Indices

In this example, a 3-dimensional combinatorial map is used, but using indices instead of handles. Two vectors are created to store some external information associated with darts and 3-attributes. Since descriptors are indices, they can directly be used to access elements of the vector.

\cgalExample{Combinatorial_map/map_3_index.cpp}

\section sec_definition Mathematical Definitions

The initial definition of combinatorial map in any dimension is given in \cgalCite{cgal:l-tmbrc-91}, \cgalCite{l-ndgcm-94}. But it allows only to represent objects without boundaries. This definition was extended \cgalCite{cgal:pabl-cco-07}, \cgalCite{cgal:d-ccccg-10} in order to allow to represent  objects with boundaries, based on the notions of partial permutations  and partial involutions. See also the book \cgalCite{cgal:dl-cmeds-14} which regroups many definitions, operations and algorithms about combinatorial and generalized maps.

Intuitively, a <I>partial permutation</I> on a finite set <I>E</I> is a mapping from <I>E</I>\f$ \cup\{\varnothing\}\f$ to <I>E</I>\f$ \cup\{\varnothing\}\f$ which is injective on the subset of the domain that does not map to \f$\varnothing\f$. More precisely, a mapping <I>p</I>: <I>E</I>\f$ \cup\{\varnothing\} \rightarrow\f$ <I>E</I>\f$ \cup\{\varnothing\}\f$ is a <I>partial permutation</I> defined on <I>E</I> if:
<OL>
<LI><I>p</I>\f$(\varnothing)=\varnothing\f$;
<LI>\f$ \forall \f$ <I>e1</I>\f$ \in \f$ <I>E</I>, \f$ \forall \f$ <I>e2</I>\f$ \in \f$ <I>E</I>, <I>p</I>(<I>e1</I>)=<I>p</I>(<I>e2</I>) \f$ \neq \f$ \f$ \varnothing\f$ \f$ \Rightarrow\f$ <I>e1</I>=<I>e2</I>.
</OL>

The inverse \f$ p^{-1}\f$ of this partial permutation is also a partial permutation and is defined by:
<OL>
<LI>\f$ p^{-1}(\varnothing)=\varnothing\f$;
<LI>\f$ \forall \f$ <I>e</I>\f$ \in \f$ <I>E</I>, if it exists <I>a</I>\f$ \in \f$ <I>E</I> such that <I>p</I>(<I>a</I>)=<I>e</I>, then \f$ p^{-1}\f$(<I>e</I>)=a, otherwise \f$ p^{-1}\f$(<I>e</I>)\f$= \varnothing\f$.
</OL>

Let <I>E</I> be a set, and <I>p</I> a partial permutation on <I>E</I>. An element <I>e</I> is called a <I>fixed point</I> for <I>p</I> if <I>p(e)=e</I>. <I>p</I> is a <I>partial involution</I> if \f$ \forall \f$ <I>e</I>\f$ \in \f$ <I>E</I>: <I>p</I>(<I>e</I>) \f$ \neq \f$ \f$ \varnothing\f$ \f$ \Rightarrow\f$ <I>p</I>(<I>p</I>(<I>e</I>))=<I>e</I>.

Now we can give the definition of a combinatorial map in any dimension.  Let <I>d</I>\f$ \geq\f$ 0. A <I>d</I>-dimensional combinatorial map (or  <I>d</I>-map) is a (d+1)-tuple <I>M</I>=(<I>D</I>,\f$ \beta_1\f$,...,\f$ \beta_d\f$) where:
<OL>
<LI><I>D</I> is a finite set of darts;
<LI>\f$ \beta_1\f$ is a partial permutation on <I>D</I>;  let \f$ \beta_0\f$ denote \f$ \beta_1^{-1}\f$;
<LI>\f$ \forall \f$ <I>i</I>, 2 \f$ \leq \f$ <I>i</I> \f$ \leq \f$ <I>d</I>, \f$ \beta_i\f$ is a partial involution on <I>D</I> without fixed point;
<LI>\anchor condcomposition \f$ \forall \f$ <I>i</I>: 0 \f$ \leq \f$ <I>i</I> \f$ \leq\f$ <I>d</I>-2, \f$ \forall \f$ <I>j</I>: 3 \f$ \leq \f$<I>j</I> \f$ \leq \f$ <I>d</I>, <I>i</I>+2 \f$ \leq \f$ <I>j</I>, \f$ \beta_i \f$ \f$ \circ \f$ \f$ \beta_j \f$ is a partial involution.
</OL>

A <I>d</I>-dimensional combinatorial map represents a subdivision of an orientable <I>d</I>-dimensional quasi-manifold. A dart is an abstract element which is only required to define partial permutations. The last line of the definition fixes constraints which guarantee the topological validity of the represented object, i.e., the fact that it is a quasi-manifold. This definition allows us to verify the validity of a given combinatorial map by checking if each item of the definition is satisfied.

Given a set of partial permutations  <I>S</I>=\f$\{f_1\f$,..., \f$ f_k\}\f$,  we denote by \f$ \langle{}\f$ <I>S</I> \f$ \rangle{}\f$ the <I>permutation group</I> generated by \f$\{f_1\f$,..., \f$ f_k\}\f$  and whose group operation is the composition of partial permutations.  The orbit \f$ \langle{}\f$\f$ f_1\f$,..., \f$ f_k\f$\f$ \rangle{}\f$(<I>a</I>)  is the set of darts which can be obtained from <I>a</I> by elements of \f$ \langle{}\f$ <I>S</I> \f$ \rangle{}\f$: \f$ \langle{}\f$\f$ f_1\f$,..., \f$ f_k\f$\f$ \rangle{}\f$(<I>a</I>)=\f$\{ \phi\f$(<I>a</I>)\f$ |\f$\f$ \phi\f$\f$ \in \f$\f$ \langle{}\f$<I>S</I>\f$ \rangle{}\}\setminus\{\varnothing\}\f$.

Let <I>d0</I>\f$ \in \f$ <I>D</I> be a dart. Given <I>i</I>, 1 \f$ \leq \f$ <I>i</I> \f$ \leq \f$ <I>d</I>, the <I>i</I>-cell containing <I>d0</I> is  \f$ \langle{}\f$\f$ \beta_1\f$,...,\f$ \beta_{i-1}\f$,\f$ \beta_{i+1}\f$,...,\f$ \beta_d\f$\f$ \rangle{}\f$(<I>d0</I>).  The <I>0</I>-cell containing <I>d0</I> is \f$ \langle{}\f${\f$ \beta_i\f$\f$ \circ\f$\f$ \beta_j\f$\f$ |\f$\f$ \forall \f$ <I>i,j</I>: 1 \f$ \leq \f$ <I>i</I> \f$ < \f$ <I>j</I> \f$ \leq \f$ <I>d</I>}\f$ \rangle{}\f$(<I>d0</I>).

\section Combinatorial_mapDesign Design and Implementation History

The code of this package is inspired by Moka, a 3D topological modeler mainly developed by Fr&eacute;d&eacute;ric Vidil and Guillaume Damiand (see https://projet.liris.cnrs.fr/moka/index.php and https://github.com/gdamiand/moka). However, Moka was based on Generalized maps (and not Combinatorial maps), and the design was not \cgal "compatible". Thus, Guillaume Damiand started to develop a totally new package by mixing ideas taken from Moka with the design of the Halfedge data structure package of \cgal. Andreas Fabri and S&eacute;bastien Loriot contributed to the design, the coding, and to the documentation of the package, and Laurent Rineau helped for the design. Emma Michel contributed to the manual. Monique Teillaud and Bernd G&auml;rtner contributed to the manual by giving useful remarks, really numerous and detailed for Monique. Ken Arroyo Ohori contributed to the two reverse orientation functions.

*/
} /* namespace CGAL */

---

### Combinatorial Map Doc Combinatorial Map PackageDescription (`Combinatorial_map/doc/Combinatorial_map/PackageDescription.txt`)

/// \defgroup PkgCombinatorialMapsRef Reference Manual

/// \defgroup PkgCombinatorialMapsConcepts Concepts
/// \ingroup PkgCombinatorialMapsRef

/// \defgroup PkgCombinatorialMapsClasses Classes
/// \ingroup PkgCombinatorialMapsRef

/// \defgroup PkgCombinatorialMapsRefIO IO Functions for CMap
/// \ingroup PkgCombinatorialMapsRef

/*!
\addtogroup PkgCombinatorialMapsRef
\cgalPkgDescriptionBegin{Combinatorial Maps,PkgCombinatorialMaps}
\cgalPkgPicture{cmap_logo.png}
\cgalPkgSummaryBegin
\cgalPkgAuthor{Guillaume Damiand}
\cgalPkgDesc{This package implements Combinatorial Maps in <I>d</I> dimensions. A combinatorial map is a data structure enabling to represent an orientable subdivided object by describing all the cells of the subdivision (for example in 3D vertices, edges, faces, volumes) and all the incidence and adjacency relationships between these cells. Information can be associated to cells thanks to attributes. In 2D, a combinatorial map is equivalent to a halfedge data structure. The package provides basic creation, modification operations, and several iterators enabling to run through some specific part of the object.}
\cgalPkgManuals{Chapter_Combinatorial_Maps,PkgCombinatorialMapsRef}
\cgalPkgSummaryEnd
\cgalPkgShortInfoBegin
\cgalPkgSince{3.9}
\cgalPkgBib{cgal:d-cm}
\cgalPkgLicense{\ref licensesLGPL "LGPL"}
\cgalPkgShortInfoEnd
\cgalPkgDescriptionEnd

\cgalClassifedRefPages

\cgalCRPSection{Concepts}
- `GenericMap`
- `GenericMapItems`
- `CellAttribute`
- `CombinatorialMap`

\cgalCRPSection{Classes}
- `CGAL::Combinatorial_map<d,Items,Alloc>`
- `CGAL::Cell_attribute<CMap,Info_,Tag,OnMerge,OnSplit>`
- `CGAL::Cell_attribute_with_id<CMap,Info_,Tag,OnMerge,OnSplit>`
- `CGAL::Generic_map_min_items`

\cgalCRPSubsection{IO Functions for CMap}
- \link PkgCombinatorialMapsRefIO `std::ostream& operator<< (std::ostream& os, const GenericMap& amap)` \endlink
- \link PkgCombinatorialMapsRefIO `std::ifstream& operator>> (std::ifstream& is, GenericMap& amap)` \endlink

*/

---

### Combinatorial Map Doc Combinatorial Map Examples (`Combinatorial_map/doc/Combinatorial_map/examples.txt`)

/*!
\example Combinatorial_map/map_3_marks.cpp
\example Combinatorial_map/map_3_simple_example.cpp
\example Combinatorial_map/map_3_operations.cpp
\example Combinatorial_map/map_4_simple_example.cpp
\example Combinatorial_map/map_3_with_colored_facets.cpp
\example Combinatorial_map/map_3_dynamic_onmerge.cpp
\example Combinatorial_map/map_3_index.cpp
\example Combinatorial_map/map_3_insert.cpp
*/

---

### Cone Spanners 2 Doc Cone Spanners 2 Cone Spanners 2 (`Cone_spanners_2/doc/Cone_spanners_2/Cone_spanners_2.txt`)

namespace CGAL {

/*!
\mainpage User Manual
\anchor Chapter_ConeBasedSpanners

\cgalAutoToc
\author Weisheng Si, Quincy Tse and Frédérik Paradis

\section sec_CBS_Introduction Introduction

This chapter describes the package for constructing two kinds of cone-based spanners:
<i>Yao graph</i> and <i>Theta graph</i>, given a set of vertices on the plane and the directions of cone boundaries.
Both exact and inexact constructions are supported.
In exact construction, the cone boundaries are calculated using roots of polynomials,
which achieves the exactness by avoiding using \f$ \pi \f$ in the computation.
In inexact construction, the cone boundaries are calculated with a floating point
approximation of \f$ \pi \f$ value and is still accurate
enough for most applications.
Moreover, for visualization purpose, this chapter describes a global function
that, given a constructed graph as input, can generate the data and script files for \gnuplot
to plot that graph.

\section sec_CBS_mydefinitions Definitions

This section gives detailed definitions of Yao graph and Theta graph, which are followed
in our implementation. In particular, because this package supports constructing Yao graph
and Theta graph exactly, we need to be clear on which cone a cone boundary belongs to.
The definitions presented here clarify on this.

Given a set \f$V\f$ of vertices on the plane, the directed Yao Graph with an integer
parameter \f$k (k > 1)\f$ on \f$V\f$ is obtained as follows. For each vertex \f$u \in V\f$,
starting from a given direction (e.g., the direction of positive \f$x\f$-axis),
draw \f$k\f$ equally-spaced rays \f$l_0\f$, \f$l_1\f$, ..., \f$l_{k-1}\f$ originating
from \f$u\f$ in counterclockwise order (see \cgalFigureRef{f-y5} (a)).
These rays divide the plane into \f$k\f$ cones of angle \f$2\pi/k\f$,
denoted by \f$ c(u, 0), c(u, 1), ..., c(u, k-1)\f$ respectively in counterclockwise order.
To avoid overlapping at boundaries, it is stipulated here that the area of \f$ c(u, i)\f$,
where \f$ i=0, \ldots, k-1\f$,  includes the ray \f$l_{i}\f$ but excludes the ray \f$l_{(i+1)\% k}\f$.
In each cone of \f$u\f$, draw a directed edge from \f$u\f$ to its closest vertex by
Euclidean distance in that cone. Ties are broken arbitrarily. These directed edges will form the
edge set of the directed Yao graph on \f$V\f$. The undirected Yao Graph on \f$V\f$ is obtained by
ignoring the directions of the edges. Note that if both edge \f$uv\f$ and \f$vu\f$ are in the
directed Yao graph, only one edge \f$uv\f$ exists in the undirected Yao graph.
\cgalFigureRef{f-y5} (b) gives an example of Yao graph with \f$k=5\f$.

\cgalFigureBegin{f-y5, Example-Y5.jpg}
Cones and an example of Yao Graph with \f$k=5\f$.
\cgalFigureEnd

Similar to Yao graph, the directed or undirected Theta Graph is also obtained by letting each
vertex \f$u \in V\f$ select a <i>closest</i> vertex in each of its cones to have an edge.
The only difference is that <i>closest</i> in Theta Graph means the smallest projection distance
onto the bisector of that cone, not the direct Euclidean distance. For instance,
in \cgalFigureRef{f-theta}, vertex \f$u\f$'s <i>closest</i> vertex will be vertex \f$b\f$.

\cgalFigureBegin{f-theta, BisectorInThetaGraph.jpg}
The bisector in a cone of a Theta Graph.
\cgalFigureEnd

Variants of Yao graph and Theta graph are Half Yao graph and Half Theta graph. The difference
is that only the edges in the even or odd cones are drawn. For instance, in the even case of
the Theta graph with \f$k=6\f$, only the edges in the cones \f$c(u, 0)\f$, \f$c(u, 2)\f$, and
\f$c(u, 4)\f$ are drawn.

\section sec_CBS_design Software Design
This package provides the following template functors:

- `Compute_cone_boundaries_2`: The functor for computing the directions of cone boundaries
  given a cone number and an initial direction.
- `Construct_theta_graph_2`: The functor for constructing Theta graphs given a set of vertices
  on the plane.
- `Construct_yao_graph_2`: The functor for constructing Yao graphs given a set of vertices
  on the plane.

In addition to these functors, for visualizing the constructed graphs, this package provides a global function
called `CGAL::gnuplot_output_2()` to output a `boost::adjacency_list` data structure to \gnuplot data and script files.
Below, we detail the design and the usage of the above functors and function.

\subsection subsec_CBS_cone Computing Cone Boundaries

The functor `Compute_cone_boundaries_2` has the following definition.

\code{.cpp}
    template <typename Traits>
    class Compute_cone_boundaries_2;
\endcode

The template parameter `Traits` determines whether the cone boundaries are computed
exactly or inexactly. If this parameter is `Exact_predicates_exact_constructions_kernel_with_root_of`,
the computation will be done exactly; if this parameter is
`Exact_predicates_inexact_constructions_kernel`, the computation will be done inexactly.
The exact computation is implemented based on the fact that
when the cone angle \f$ \theta \f$ is in the form of \f$ 2\pi / n \f$,
where \f$ n \f$ is a positive integer, \f$ \sin(\theta) \f$ and \f$ \cos(\theta) \f$
can be represented exactly by roots of polynomials, thus avoiding using \f$ \pi \f$
in the computation. The exact computation requires the number type of either `CORE::Expr`
or `leda_real`.
In inexact computation, the cone angle \f$ \theta \f$ is
simply calculated as \f$ 2\pi/k \f$, where \f$ k \f$ is the number of cones and
\f$ \pi \f$ takes the value of the constant `CGAL_PI=3.14159265358979323846`.
Then, the \f$ \sin(\theta) \f$ and \f$ \cos(\theta) \f$ are calculated.
While the inexact computation is done by the general functor
definition, the exact computation is done by a specialization of this functor.



This functor is currently used by the functors
`Construct_theta_graph_2` and `Construct_yao_graph_2`
in constructing Theta and Yao graphs. This functor can also be used in other applications where the plane needs to be
divided into equally-angled cones. For how to use this functor to compute cone boundaries in writing an application,
please refer to Section \ref sec_CBS_examples.

\subsection subsec_CBS_theta Constructing a Theta Graph

The functor `Construct_theta_graph_2` has the following definition

\code{.cpp}
    template <typename Traits, typename Graph>
    class Construct_theta_graph_2;
\endcode

Similar to the functor `Compute_cone_boundaries_2`, the template parameter `Traits`
determines whether the Theta graph will constructed exactly or inexactly.
The template parameter `Graph` specifies the graph type used to store the constructed graph.
Our package requires it to be
<a href="https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/graph_classes/adjacency_list.html">boost::adjacency_list</a>
from the Boost Graph Library (BGL).
The advantage of using `boost::adjacency_list` is that it provides convenience
to the further processing of the constructed graphs, since BGL includes most common graph algorithms.
Note that BGL altogether provides two template classes for representing graphs:
`boost::adjacency_list` and `boost::adjacency_matrix`, with the former suitable for
sparse graphs and the latter suitable for dense graphs. While cone-based spanners
are sparse graphs and the interfaces provided by `boost::adjacency_list` and `boost::adjacency_matrix`
are different, our package only supports `boost::adjacency_list`.

Note that there are seven template parameters for `boost::adjacency_list` in BGL: `OutEdgeList`, `VertexList`,
`Directed`, `VertexProperties`, `EdgeProperties`, `GraphProperties`, `EdgeList`,
of which we require `VertexProperties` to be `Traits::Point_2`,
and other parameters can be chosen freely.
Also note that, here we pass `Point_2` directly as
<a href="https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/property_maps/bundled.html"><i>bundled properties</i></a>
to `boost::adjacency_list`, because this makes our implementation more straightforward than using a property map.
If you want more properties other than `Point_2` for vertices, you can still
construct external properties by using property maps.

In constructing Theta graphs, this functor uses the algorithm from
Chapter 4 of the book by Narasimhan and Smid \cgalCite{cgal:ns-gsn-07}.
Basically, it is a sweep line algorithm and uses a
balanced search tree to store the vertices that have already been scanned.
It has the complexity of \cgalBigO{n \log n}, where \f$n\f$ is the number of vertices in the plane.
This complexity has been proved to be optimal.

For more details on how to use this `Construct_theta_graph_2` functor to write an application to build Theta graphs,
please refer to Section \ref sec_CBS_examples.

\subsection subsec_CBS_yao Constructing a Yao Graph

The functor `Construct_yao_graph_2` has a similar definition as `Construct_theta_graph_2`.


\code{.cpp}
    template <typename Traits, typename Graph>
    class Construct_yao_graph_2;
\endcode

The way of using these two template parameters is the same as that of `Construct_theta_graph_2`,
so please refer to the previous subsection for the details. We note here that construction algorithm for Yao graph
is a slight adaptation of the algorithm for constructing Theta graph, having a complexity of \cgalBigO{n^2}.
The increase of complexity in this adaptation is because in constructing Theta graph,
the searching of the 'closest' node by projection distance can be done by a balanced search tree,
but in constructing Yao graph, the searching of the 'closest' node by Euclidean distance cannot be
done by a balanced search tree.

Note that an optimal algorithm for constructing Yao graph with a complexity of \cgalBigO{n \log n} is
described in \cgalCite{cgal:cht-oacov-90}. However, this algorithm is much more complex to implement than
the current algorithm implemented, and it can hardly reuse the codes for constructing Theta graphs,
so it is not implemented in this package right now.

\subsection subsec_CBS_gnuplot Gnuplot Output

This package also implements a template function `CGAL::gnuplot_output_2()`, which reads a
`boost::adjacency_list` object and generate two files used by \gnuplot to visualize the graph stored
in the `boost::adjacency_list` object. This template function has the following definition:

\code{.cpp}
    template <typename Graph_>
    void gnuplot_output_2(const Graph_& g, const std::string& prefix);
\endcode

The template parameter `Graph_` specifies the type of the graph to be plotted. For this function to work,
the graph type must be `boost::adjacency_list` with `Point_2` as the `VertexProperties`.
As for the two arguments to the function, `g` gives the graph to be plotted, and `prefix` gives the
prefix for the names of the files generated by the function. Specifically, this function will
generate the following two files:
- A data file named `prefix.v` that contains the \f$(x, y)\f$-coordinates
  of each vertex. To be read by \gnuplot,
  the \f$(x, y)\f$-coordinates are written into the data file with decimal format,
  no matter which number type is used in the \cgal kernel.
  This is achieved by calling `to_double()` on \f$x\f$ or \f$y\f$ coordinate before outputting them.
- A \gnuplot script file named `prefix.plt` to be loaded by \gnuplot to plot the set of vertices and the set of edges.
  The set of vertices is read from the above data file and the set of edges are included in the script file
  with the syntax `set arrow from x1, y1 to x2, y2`.

For details on how to use this function to generate \gnuplot files, please refer to Section \ref sec_CBS_examples.

\section sec_CBS_examples Examples

\subsection CBS_coneboundaries Computing Cone Boundaries Exactly or Inexactly

The following example shows how to compute the directions of the cone boundaries
exactly given the cone number and the initial direction. This example basically consists of the following steps:

1. Define `Exact_predicates_exact_constructions_kernel_with_root_of` as the kernel type
   to compute the cone boundaries exactly.
2. Construct a `Compute_cone_boundaries_2` object named  `cones` with the above kernel
   as the template parameter. Note that since the functor `Compute_cone_boundaries_2` has no
   member variables but member types and functions, its constructor needs no arguments.
3. Initialize a vector of `Direction_2` named `rays` to store the computed results.
4. Use `cones` to compute the cone boundaries by passing the cone number, the initial direction
   and the beginning iterator of `rays` to it.
5. Output the computed results.

\cgalExample{Cone_spanners_2/compute_cones.cpp}

Note that, in this example, for any k<=28, the computation can be done successfully; for any k>28, the computation
cannot be completed because `CORE::Expr`, which we use as the number type for the exact kernel,
exceeds its limit. It seems that k<=28 will suffice for most applications. Also, if inexact computation
is used, the computation will be successful for any k>1, and much quicker than exact computation.
We also note here that we don't experiment with `leda_real`.

As a final note, to compute the cone boundaries inexactly, just define the `Kernel` to be
`Exact_predicates_inexact_constructions_kernel` in the above example.

\subsection CBS_construction Constructing Graphs Exactly or Inexactly and Generating Gnuplot Files

The following example shows how to construct Theta graphs exactly and generate \gnuplot files.
This example basically consists of the following steps:
1. Define `Exact_predicates_exact_constructions_kernel_with_root_of` as the kernel type
   to construct the graph exactly.
2. Define the graph type to store the constructed graph.
3. Construct a `Construct_theta_graph_2` object named `theta` with the number of cones and the initial direction
   as constructor arguments.
4. Construct a graph object `g` to store the constructed graph.
5. Use `theta` to construct the Theta graph by passing the input vertices and `g` to it.
6. Generate \gnuplot files for plotting the construct graph.

\cgalExample{Cone_spanners_2/theta_io.cpp}

To construct Theta graphs inexactly, just define the `Kernel` to be
`Exact_predicates_inexact_constructions_kernel` in the above example. And the way of
constructing Yao graphs exactly or inexactly is the same as that of constructing
Theta graphs, just replacing the functor `Construct_theta_graph_2` by the functor
`Construct_yao_graph_2`.

Note that, for Theta graph, the `Kernel` defined must support the `CGAL::sqrt()` operation.
This is required by the `bisector()` function, which is used to calculate the angle
bisector of a cone. For instance, the compiler will complain if
`Exact_predicates_exact_constructions_kernel` (not supporting `CGAL::sqrt()`)
is defined as the kernel, but `Exact_predicates_inexact_constructions_kernel` will be fine
since it supports `CAL::sqrt()`. For Yao graph, there is no such restriction, since its construction
does not need `CGAL::sqrt()`.

Also note that when using g++ or clang++ compilers with the c++11 standard,
using a directed graph will cause a compilation error due to a
<a href="https://lists.boost.org/Archives/boost/2016/05/229458.php">bug</a> in the boost library.
As a workaround you can use a undirected graph instead.

After compiling `theta_io.cpp`, execute the executable `theta_io` to construct a Theta graph with 4 cones
on a set of 20 vertices (which is given in the file `data/n20.cin`):

\code{.txt}
      $ ./theta_io  4  data/n20.cin
\endcode

The following two files will be generated for \gnuplot:
- `t4n20.v`:  This file contains the \f$(x, y)\f$-coordinates of the 20 vertices.
- `t4n20.plt`: This is the script to be loaded by \gnuplot. It will read
          `t4n20.v` to plot the vertices. It will also plot all the edges,
          which are included in this script itself.

\cgalFigureRef{f-t4} shows the Theta graph plotted when the above `t4n20.plt` is loaded by \gnuplot.

\cgalFigureBegin{f-t4, t4n20.jpg}
A directed Theta graph of 20 vertices with \f$k=4\f$.
\cgalFigureEnd

\subsection CBS_half Constructing Half Theta or Yao Graphs

By default, the functors `Construct_theta_graph_2`
and `Construct_yao_graph_2` construct full Theta and Yao graphs. They also provide a way
to compute Half Theta and Yao graphs. As mentioned in Section \ref sec_CBS_mydefinitions,
only the edges for the odd or even cones are added to the graph in an Half Theta and Yao
graph. To do so, the constructor of the functors provides a parameter of type
`Cones_selected` which is an enumeration that contains the following possible values:
`ALL_CONES`, `EVEN_CONES` and `ODD_CONES`. Users should include the
`CGAL/Cone_spanners_enum_2.h` header file to use these enum values. The following are the
examples on the functor constructions for Half Theta and Yao Graphs.


\code{.cpp}
// Construct an Half Theta graph with the edges only in the even cones.
CGAL::Construct_theta_graph_2<Kernel, Graph> theta(k, Direction_2(1,0), CGAL::EVEN_CONES);

// Construct an Half Theta graph with the edges only in the odd cones.
CGAL::Construct_theta_graph_2<Kernel, Graph> theta(k, Direction_2(1,0), CGAL::ODD_CONES);

// Construct an Half Yao graph with the edges only in the even cones.
CGAL::Construct_yao_graph_2<Kernel, Graph> yao(k, Direction_2(1,0), CGAL::EVEN_CONES);

// Construct an Half Yao graph with the edges only in the odd cones.
CGAL::Construct_yao_graph_2<Kernel, Graph> yao(k, Direction_2(1,0), CGAL::ODD_CONES);
\endcode

\subsection CBS_diff_exact Exact Construction Can Make a Difference

This subsection gives an example vertex set on which the exact construction provided
in this package can produce the correct Theta graph while the inexact construction cannot.

This vertex set, given in the file `examples/data/n9.cin`, consists of 9 vertices
with the following \f$(x, y)\f$-coordinates:
\code{.txt}
0.000000  0.000000
0.000000  1.000000
0.000000  2.000000
1.000000  0.000000
1.000000  1.000000
1.000000  2.000000
2.000000  0.000000
2.000000  1.000000
2.000000  2.000000
\endcode

If we construct the directed Theta graph on this vertex set with \f$k=4\f$ and its cone boundaries
on the \f$x\f$ and \f$y\f$ axis, the exact construction will produce the Theta graph shown in
\cgalFigureRef{f-t4n9exact}. Based on our definition on Theta graph presented in the
Section \ref sec_CBS_mydefinitions, we can verify that the Theta graph in \cgalFigureRef{f-t4n9exact}
is correctly constructed.

\cgalFigureBegin{f-t4n9exact, t4n9exact.jpg}
The correct Theta graph produced by the exact construction.
\cgalFigureEnd

On the other hand, the inexact construction will produce the Theta graph
depicted in \cgalFigureRef{f-t4n9inexact}. We can see that this Theta graph is not constructed
correctly, since the inexact construction will make wrong decisions on whether
those vertices on the cone boundaries belong to a certain cone.

\cgalFigureBegin{f-t4n9inexact, t4n9inexact.jpg}
The incorrect Theta graph produced by the inexact construction.
\cgalFigureEnd

This example demonstrates that the exact construction capability
provided by this package can be very
valuable if it is a strict requirement that graphs be constructed correctly.

\subsection CBS_using_BGL Using BGL Algorithms

The following example, 'dijkstra_theta.cpp', shows how to call algorithms from BGL to do further processing
after the graphs are constructed. Since the constructed Theta or Yao graphs are stored in the class
`boost::adjacency_list`, it is convenient to apply BGL algorithms into the constructed graphs.
Specifically, this example constructs a Theta graph first and then calculates
the shortest paths on this graph by calling the Dijkstra's algorithm from BGL.
It mainly consists of the following steps:

1. Define `Exact_predicates_inexact_constructions_kernel` as the kernel type
   to construct the graph inexactly.
2. Define a structure named `Edge_property` for storing the Euclidean length of each edge,
   which is needed by the Dijkstra's algorithm.
3. Define the graph type to store the constructed graph, passing `Edge_property` as a template
   parameter to the graph type `boost::adjacency_list`.
4. Construct a `Construct_theta_graph_2` object named `theta`.
5. Construct a graph object `g` to store the constructed graph.
6. Use `theta` to construct the Theta graph by passing the input vertices and `g` to it.
7. After `g` is constructed, calculate the Euclidean length of each edge in `g`.
8. Calculate the shortest distances from `v0` to other vertices by calling the function
   `dijkstra_shortest_paths()` from BGL.

\cgalExample{Cone_spanners_2/dijkstra_theta.cpp}

*/
} /* namespace CGAL */

---

### Cone Spanners 2 Doc Cone Spanners 2 PackageDescription (`Cone_spanners_2/doc/Cone_spanners_2/PackageDescription.txt`)

/// \defgroup PkgConeSpanners2Ref Reference Manual

/*!
\addtogroup PkgConeSpanners2Ref

\cgalPkgDescriptionBegin{Cone-Based Spanners,PkgConeSpanners2}
\cgalPkgPicture{Logo-ConeSpanners.png}

\cgalPkgSummaryBegin
\cgalPkgAuthors{Weisheng Si, Quincy Tse, and Frédérik Paradis}
\cgalPkgDesc{This package provides functors for constructing two kinds of cone-based spanners:
Yao graph and Theta graph, given a set of vertices on the plane and the directions of cone boundaries.
Both exact and inexact constructions are supported.
In exact construction, the cone boundaries are calculated using the roots of polynomials,
thus avoiding the use of \f$ \pi \f$, which cannot be represented exactly.
In inexact construction, the cone boundaries are calculated using the approximate \f$ \pi \f$
value defined in \cgal, which is still accurate enough for most applications.
Moreover, for visualization purpose, this package provides a global function to
generate the data and script files used by Gnuplot to plot the constructed graphs.
This package also provides options for the Half Yao graph and the Half Theta graph.}
\cgalPkgManuals{Chapter_ConeBasedSpanners,PkgConeSpanners2Ref}
\cgalPkgSummaryEnd

\cgalPkgShortInfoBegin
\cgalPkgSince{4.9}
\cgalPkgBib{cgal:st-cbs}
\cgalPkgLicense{\ref licensesGPL "GPL"}
\cgalPkgShortInfoEnd

\cgalPkgDescriptionEnd

\cgalClassifedRefPages


\cgalCRPSection{Functors}
- `CGAL::Compute_cone_boundaries_2`
- `CGAL::Construct_yao_graph_2`
- `CGAL::Construct_theta_graph_2`

\cgalCRPSection{Functions}
- `CGAL::gnuplot_output_2()`

\cgalCRPSection{Enumerations}
- `CGAL::Cones_selected`

*/

---

### Cone Spanners 2 Doc Cone Spanners 2 Examples (`Cone_spanners_2/doc/Cone_spanners_2/examples.txt`)

/*!
\example Cone_spanners_2/compute_cones.cpp
\example Cone_spanners_2/theta_io.cpp
\example Cone_spanners_2/dijkstra_theta.cpp
*/

---

### Constrained Triangulation 3 Doc Constrained Triangulation 3 Constrained Triangulation 3 (`Constrained_triangulation_3/doc/Constrained_triangulation_3/Constrained_triangulation_3.txt`)

namespace CGAL {
/*!

\mainpage User Manual
\anchor Chapter_CT_3
\anchor userchapterct3

\cgalAutoToc
\author Laurent Rineau and Jane Tournois

\cgalFigureAnchor{CT_3_pyramid_fig}
<img src="cdt_title_pyramid.png" style="max-width:60%;min-width=20%"/>
<BR>

\section CT_3_CCDT_3 Constrained Triangulations in 3D

3D triangulations partition space and are useful in many applications. In some cases, it is
important to ensure that specific faces, such as those representing the sharp features of an object, appear in the output.
When a triangulation exactly respects these constraints, it is called a _constrained_ triangulation.
However, it is sometimes only possible to preserve the geometry of the constraints, but not their exact
combinatorics. In such cases, additional points, called _Steiner_ _points_, must be inserted. This process
results in a _conforming_ triangulation.

This package implements an algorithm for constructing conforming triangulations of 3D polygonal
constraints. Specifically, it requires that these piecewise linear constraints are provided as a
_piecewise linear complex_&nbsp;(PLC). The resulting triangulations are of type `Triangulation_3`,
as described in the chapter \ref PkgTriangulation3.

The article by Cohen-Steiner et al. \cgalCite{cgal:cohen2002conforming} discusses the problem of
constructing conforming Delaunay triangulations and proposes an algorithm to address it.
Si et al.'s work \cgalCite{si2005meshing}, \cgalCite{cgal:si2008cdt3}, \cgalCite{si2015tetgen},
 presents an algorithm for computing conforming constrained
Delaunay triangulations in 3D.

\section CT_3_definitions Definitions

This section introduces the key concepts necessary to understand and use this package effectively.

\subsection CT_3_PLC Piecewise Linear Complex

A _piecewise linear complex_&nbsp;(PLC) is the three-dimensional generalization of a
planar straight-line graph. It consists of a finite set of vertices, edges, and polygonal faces
that satisfy the following properties:

- The vertices and edges of the PLC form a simplicial complex: two edges may intersect only at a
  shared vertex.
- The boundary of each polygonal face in the PLC is an ordered list of vertices from the PLC, forming
  one closed loop.
- Each polygonal face must be a simple polygon, i.e., its edges don't intersect,
  except consecutive edges, which intersect at their common vertex.
- Each polygonal face must be planar, meaning all its vertices lie on the same plane.
- Each polygonal face may be non-convex.
- Each polygonal face may have one or more holes, each of them also represented by an ordered list of vertices
  from the PLC, forming a closed loop.
- Polygonal holes may be non-convex.
- If two polygonal faces in the PLC intersect, their intersection is a union of edges and vertices from the
  PLC. In particular, the interiors of two polygonal faces cannot overlap.


\cgalFigureAnchor{CT_3_plc_fig}
<center>
<img src="plc.png" style="max-width:60%;"/>
</center>
\cgalFigureCaptionBegin{CT_3_plc_fig}
A piecewise linear complex, composed of planar faces connected by edges and vertices.
\cgalFigureCaptionEnd


\subsection CT_3_CDT Conforming Constrained Delaunay Triangulation

The algorithms developed in this package are designed to compute a constrained Delaunay
triangulation that contains a given set of polygonal constraints in 3D as a subcomplex.

A triangulation is a _Delaunay triangulation_ if the circumscribing sphere of any simplex
in the triangulation contains no vertex in its interior (see chapter \ref PkgTriangulation3
for more details on Delaunay triangulations).

A _constrained Delaunay triangulation_ of a PLC is a constrained triangulation that is as close as
possible to being Delaunay, given that some faces are marked as _constrained_. More precisely, a
triangulation is _constrained Delaunay_ if, for any simplex \f$s\f$ of the triangulation, the
interior of its circumscribing sphere contains no vertex of the triangulation that is _visible_ from
any point in the interior of the simplex \f$s\f$. Two points are _visible_ if the open line segment
joining them does not intersect any polygonal face of the PLC, except for polygonal faces that are coplanar with
the segment.

In 3D, constrained triangulations do not always exist. This can be demonstrated using the example of
Sch&ouml;nhardt polyhedra \cgalCite{s-udzvd-28} (see \cgalFigureRef{CT_3_schonhardt_fig}),
\cgalCite{b-ip-48a}. Shewchuk \cgalCite{cgal:shewchuk1998condition} demonstrated that for any PLC,
there exists a refined
version of the original PLC that admits a constrained Delaunay triangulation. This refinement is
achieved by adding Steiner vertices to the input edges and polygonal faces. The constrained triangulation
built on this refined PLC is known as a _conforming constrained Delaunay triangulation_ (CCDT for
short). \cgalFigureRef{CT_3_plc2cdt_fig} illustrates an example of a conforming constrained
Delaunay triangulation constructed from a PLC.


\cgalFigureAnchor{CT_3_schonhardt_fig}
<center>
<img src="schonhardt.png" style="max-width:25%;"/>
</center>
\cgalFigureCaptionBegin{CT_3_schonhardt_fig}
A Sch&ouml;nhardt polyhedron.
\cgalFigureCaptionEnd


\cgalFigureAnchor{CT_3_plc2cdt_fig}
<center>
<img src="plc_to_cdt.png" style="max-width:70%;"/>
</center>
\cgalFigureCaptionBegin{CT_3_plc2cdt_fig}
Left: PLC (360 vertices);
Right: CCDT (2452 vertices).
\cgalFigureCaptionEnd

The algorithm implemented in this package is based on the work of Hang Si et al., who developed particular
algorithms for constructing conforming constrained Delaunay triangulations from PLCs.
The corresponding implementation is designed to handle points whose coordinates
are floating-point numbers.
\cgalCite{si2005meshing}, \cgalCite{cgal:si2008cdt3}, \cgalCite{si2015tetgen}.


\section CT_3_design Software Design

\subsection CT_3_representation_of_PLCs Representation of Piecewise Linear Complexes

There is no universal or canonical way to represent all possible PLCs in \cgal.

Any polyhedral surface is a PLC, so any model of `FaceListGraph`, such as `CGAL::Surface_mesh`, can be
used to represent such a PLC.
In this representation, the geometric structure of the PLC is directly mapped to the elements
of the `CGAL::Surface_mesh`:
- vertices of the PLC geometrically correspond to vertices of the surface mesh,
- edges of the PLC correspond to edges of the surface mesh,
- and polygonal faces of the PLC correspond to faces of the surface mesh,
covering the surface of a geometric object.
However, PLCs represented in this way are limited to being
manifold (that is, each edge belongs to exactly two faces), and their faces cannot have holes.

A PLC can also be represented as a polygon soup: a collection of vertices and a set of polygons, where
each polygon is defined by an ordered list of vertices, without explicit connectivity information between
polygons. For a polygon soup to represent a valid PLC, its polygons must satisfy the
polygonal faces properties described
in the previous section. This approach allows for the representation of non-manifold geometries; however,
polygons in a polygon soup cannot have holes.

This package also provides a way to group polygonal faces into distinct surface patches using a property map,
named `plc_face_id`.
Each polygon can be assigned a _patch_ identifier, allowing multiple polygonal faces to form a continuous surface patch,
which may include holes. Some necessary conditions must be satisfied for these patches to be
used in the conforming constrained Delaunay triangulation construction:
- Each patch must be planar, meaning all polygonal faces in the patch lie on the same plane;
- The polygonal faces of the patch must not intersect except at their shared edges.

When this property map is provided, the input PLC is interpreted in terms of its polygonal faces,
edges and vertices as follows:
- Each polygonal face of the PLC is defined as the union of input polygons sharing the same patch identifier;
- The edges of the PLC are those from the surface mesh or polygon soup that satisfy one of the following conditions:
-- they are adjacent to only one polygonal face;
-- they are adjacent to two polygonal faces with different patch identifiers;
-- they are adjacent to more than two polygonal faces with differing patch identifiers, indicating non-manifold features of the PLC.
- The vertices of the PLC are the ones lying on the boundaries of surface patches in the original surface mesh or polygon soup.

\subsection CT_3_api API

This package provides a primary class, `CGAL::Conforming_constrained_Delaunay_triangulation_3`.
This class is templated by a
geometric traits class and an underlying triangulation class, allowing for flexibility and
customization.

In addition to the main class, the package includes several auxiliary classes that define the types
of vertices, cells, and associated metadata used within the triangulation. These supporting classes
enable users to extend or adapt the triangulation data structure to their specific needs.

Two overloads of the constructor function \link
PkgConstrainedTriangulation3FunctionsPolygonSoupOrMesh
`CGAL::make_conforming_constrained_Delaunay_triangulation_3()`\endlink are provided to facilitate the creation
of a `CGAL::Conforming_constrained_Delaunay_triangulation_3` object from either a surface mesh or a polygon soup.

\subsection CT_3_geomtraits Traits and Kernel Choice

The requirements for geometric objects and operations are specified by the traits class concept
`ConformingConstrainedDelaunayTriangulationTraits_3`. Any CGAL kernel is a model of this concept.
However, because this package builds upon the 3D Triangulation package, it inherits the requirement
that the traits class must provide exact predicates.

A key aspect of this algorithm is the creation of new points, known as Steiner points, which are
inserted on the segments and polygons forming the input PLC polygonal faces.
If a traits class with inexact constructions
is used, it cannot be guaranteed that these points will lie exactly on the intended segments or polygons.
As a result, the output will only approximate the input, with the accuracy limited by the rounding
of the computed Steiner points.

Furthermore, when using inexact constructions, the algorithm may fail if the input PLC contains
non-adjacent simplices that are too close to each other. In such cases, the triangulation process
will emit an error if the distance between simplices falls below an internally computed threshold.
An error message describing the involved simplices will be displayed on the standard output.
If the issue is caused by poorly shaped triangles, functions such as
`CGAL::Polygon_mesh_processing::remove_almost_degenerate_faces()` may help resolve the problem.

\section CT_3_examples Examples

\subsection CT_3_example_ccdt Build a Conforming Constrained Delaunay Triangulation

The following example illustrates how to use the helper function
`CGAL::make_conforming_constrained_Delaunay_triangulation_3()` to construct a conforming constrained
Delaunay triangulation from a given PLC.

The triangulation is saved in the MEDIT file format, using the
\link PkgCDT3IOFunctions `CGAL::IO::write_MEDIT()` \endlink function.

\cgalExample{Constrained_triangulation_3/conforming_constrained_Delaunay_triangulation_3.cpp }


\subsection CT_3_example_ccdt_soup Build a Conforming Constrained Delaunay Triangulation from a Polygon Soup

You can also construct a conforming constrained Delaunay triangulation from a polygon soup.
The following example demonstrates how to create such a triangulation from a collection of polygons
without explicit connectivity information.

\cgalExample{Constrained_triangulation_3/ccdt_3_from_soup.cpp }


\subsection CT_3_example_ccdt_fimap Build a Conforming Constrained Delaunay Triangulation with Known Polygon Identifiers

If the user already knows the set of polygonal face identifiers to associate with each PLC face, this information can be
provided and preserved throughout the construction of the conforming constrained Delaunay
triangulation.

The following example demonstrates how to detect planar surface patches and remesh them as coarsely
as possible using
\link CGAL::Polygon_mesh_processing::remesh_planar_patches(const TriangleMeshIn&,PolygonMeshOut&,const NamedParametersIn&,const NamedParametersOut&) `CGAL::Polygon_mesh_processing::remesh_planar_patches()` \endlink
from the \ref PkgPMPRemeshing package.
The resulting patches and segmentation are then used to build a conforming constrained Delaunay triangulation.

When the named parameter `plc_face_id` is specified, each constrained facet in the 3D triangulation
is assigned to the corresponding input PLC face, as identified by the provided property map.
If this parameter is not specified, each input polygonal face is assigned a unique face index.

Figure \cgalFigureRef{CT_3_ccdt_examples_fig} shows the benefit of using the `plc_face_id` property map.
On the last line of the figure, the input PLC is enriched with a segmentation of the planar faces,
provided via the `plc_face_id` property map. In the resulting conforming constrained Delaunay triangulation,
only the boundary edges of the PLC faces are constrained, while the other edges never get inserted as
edges of the 3D triangulation.

Without the `plc_face_id` property map, all edges of the PLC faces are constrained,
each PLC face is considered as a constraint,
possibly resulting in a 3D triangulation with surfaces that are more refined than necessary.

\cgalExample{Constrained_triangulation_3/conforming_constrained_Delaunay_triangulation_3_fimap.cpp}

\cgalFigureRef{CT_3_ccdt_examples_fig} shows the input and output of this triangulation construction example.


\subsection CT_3_example_ccdt_region_growing_fimap Build a Conforming Constrained Delaunay Triangulation with Detected Polygon Identifiers

If the user does not know the set of polygonal face identifiers to associate with each PLC face, this information can be
automatically detected using the
\link CGAL::Polygon_mesh_processing::region_growing_of_planes_on_faces(const PolygonMesh& mesh,RegionMap region_map,const NamedParameters& np) `CGAL::Polygon_mesh_processing::region_growing_of_planes_on_faces()`\endlink
function from the \ref PkgPolygonMeshProcessing package.

The following example demonstrates how to detect planar surface patches and build a conforming
constrained Delaunay triangulation using the detected segmentation. The named parameter `plc_face_id`
is used to associate each facet of the triangulation with the corresponding input PLC face.

\cgalExample{Constrained_triangulation_3/ccdt_3_fimap_region_growing.cpp}


\subsection CT_3_examples_preprocessing Preprocessing the Input for Conforming Constrained Delaunay Triangulations

Given a PLC, the algorithms in this package can construct a conforming constrained Delaunay triangulation, provided
the input surface can be represented as a valid surface mesh or a collection of surface meshes,
and does not contain self-intersections.
Several preprocessing functions are available in the \ref PkgPMPMeshRepair package to help ensure these
preconditions are met.

The following example demonstrates how to construct a conforming constrained Delaunay triangulation from
an input mesh that is not triangulated and may contain self-intersections,
using autorefinement.

\cgalExample{Constrained_triangulation_3/ccdt_3_after_autorefinement.cpp }

The function
\link CGAL::Polygon_mesh_processing::does_self_intersect(const FaceRange&, const TriangleMesh&, const NamedParameters&) `CGAL::Polygon_mesh_processing::does_self_intersect()` \endlink
is used to detect self-intersections,
but it requires the input mesh to be triangulated. Therefore, the input mesh must first be triangulated
using
\link CGAL::Polygon_mesh_processing::triangulate_faces(const FaceRange&,PolygonMesh&,const NamedParameters&) `CGAL::Polygon_mesh_processing::triangulate_faces()`\endlink
before performing the self-intersection check.

If self-intersections are found, the triangulated mesh is converted into a triangle soup, which is then
processed with
\link CGAL::Polygon_mesh_processing::autorefine_triangle_soup(PointRange&,TriangleRange&,const NamedParameters&) `CGAL::Polygon_mesh_processing::autorefine_triangle_soup()`\endlink
to resolve the self-intersections.


\subsection CT_3_example_remesh Remeshing a Conforming Constrained Delaunay Triangulation

After constructing the triangulation, you can improve its quality or adapt it to a specific sizing
field by applying the
\link CGAL::tetrahedral_isotropic_remeshing(CGAL::Triangulation_3<Traits, TDS, SLDS>&, const SizingFunction&, const NamedParameters&) `CGAL::tetrahedral_isotropic_remeshing()`\endlink
 function from the \ref PkgTetrahedralRemeshing package.

The following example demonstrates how to remesh a conforming constrained Delaunay triangulation.

\cgalExample{Constrained_triangulation_3/remesh_constrained_Delaunay_triangulation_3.cpp }


\subsection CT_3_examples_figure Figures

The following table of figures (\cgalFigureRef{CT_3_ccdt_examples_fig}) illustrates some results of the examples provided in this package.
The left column shows the input PLC, while the right column displays the resulting conforming
constrained Delaunay triangulation.

From top to bottom, the lines show different input PLC, from the same input triangulated surface and,
for each of them, the resulting conforming constrained Delaunay triangulation.
The input data are:
<ul>
<li> the input PLC with no preprocessing;
<li> the input PLC with a segmentation of the surface patches done with `CGAL::Polygon_mesh_processing::region_growing_of_planes_on_faces()` as done in example \ref CT_3_example_ccdt_region_growing_fimap;</li>
<li> the input PLC, remeshed and not triangulated, with a segmentation of the surface patches, done with `CGAL::Polygon_mesh_processing::remesh_planar_patches()` as in example \ref CT_3_example_ccdt_fimap;</li>
<li> the input PLC, isotropically remeshed, with a segmentation of the surface patches, done with `CGAL::Polygon_mesh_processing::region_growing_of_planes_on_faces()` as in example \ref CT_3_example_ccdt_region_growing_fimap.</li>
</ul>

On the fourth line, the input PLC is remeshed using `CGAL::Polygon_mesh_processing::isotropic_remeshing()`.
The resulting conforming constrained Delaunay triangulation contains fewer vertices than the input
remeshed and segmented input PLC. This reduction occurs because only the boundary edges of the PLC faces
are marked as constraints in the triangulation;
interior edges that do not lie on the boundaries of surface patches (as defined by `plc_face_id`) are ignored.
As a result, these non-boundary edges are omitted from the triangulation, leading to a coarser triangulation.

\cgalFigureAnchor{CT_3_ccdt_examples_fig}
<center>
<img src="ccdt_examples.png" style="max-width:50%;"/>
</center>
\cgalFigureCaptionBegin{CT_3_ccdt_examples_fig}
A collection of conforming constrained Delaunay triangulations built from different inputs.
The left column shows the input PLC, while the right column displays the resulting 3D triangulation.<br>
\cgalFigureCaptionEnd


\section CT_3_history Implementation History

The initial version of this package was implemented by Laurent Rineau and released in
\cgal&nbsp;6.1&nbsp;(2025). Jane Tournois contributed to the documentation and helped improve the API.
The package design and algorithms are grounded in the theoretical work of
Hang&nbsp;Si et al. on meshing algorithms&nbsp;\cgalCite{si2005meshing},&nbsp;\cgalCite{si2015tetgen}.

*/
} /* namespace CGAL */

---

### Constrained Triangulation 3 Doc Constrained Triangulation 3 PackageDescription (`Constrained_triangulation_3/doc/Constrained_triangulation_3/PackageDescription.txt`)

/*!
\defgroup PkgConstrainedTriangulation3Ref Reference Manual

\defgroup PkgConstrainedTriangulation3Concepts Concepts
\ingroup PkgConstrainedTriangulation3Ref

\defgroup PkgConstrainedTriangulation3Classes Classes and Class Templates
\ingroup PkgConstrainedTriangulation3Ref

\defgroup PkgConstrainedTriangulation3FunctionsPolygonSoupOrMesh  Free Functions for Creating Conforming Constrained Delaunay Triangulations
\ingroup PkgConstrainedTriangulation3Ref

\defgroup PkgCDT3IOFunctions Output Functions
\ingroup PkgConstrainedTriangulation3Ref

\defgroup PkgDrawCDT_3 Draw a 3D Constrained Triangulation
\ingroup PkgConstrainedTriangulation3Ref

\defgroup PkgConstrainedTriangulation3Functions Other Functions
\ingroup PkgConstrainedTriangulation3Ref

\addtogroup PkgConstrainedTriangulation3Ref
\cgalPkgDescriptionBegin{3D Constrained Triangulations,PkgConstrainedTriangulation3}
\cgalPkgPicture{small-pyramid.png}

\cgalPkgSummaryBegin
\cgalPkgAuthors{Laurent Rineau and Jane Tournois}
\cgalPkgDesc{This package implements the construction of a 3D Constrained Delaunay triangulation.
This triangulation is a generalization of a 3D Delaunay Triangulation which conforms to the set of faces
of a 3D _piecewise linear complex_ (PLC), ensuring that these faces are part of the triangulation.
As not all PLCs are tetrahedralizable,
the algorithm may insert Steiner points to construct the constrained triangulation.
}
\cgalPkgManuals{Chapter_CT_3,PkgConstrainedTriangulation3Ref}
\cgalPkgSummaryEnd

\cgalPkgShortInfoBegin
\cgalPkgSince{6.1}
\cgalPkgDependsOn{\ref PkgTriangulation3 "3D Triangulations"}
\cgalPkgBib{cgal:rt-cdt3}
\cgalPkgLicense{\ref licensesGPL "GPL"}
\cgalPkgDemo{CGAL Lab,CGALlab.zip}
\cgalPkgShortInfoEnd


\cgalPkgDescriptionEnd

\cgalClassifedRefPages

\cgalCRPSection{Concepts}

- `ConformingConstrainedDelaunayTriangulationTraits_3`
- `ConformingConstrainedDelaunayTriangulationVertexBase_3`
- `ConformingConstrainedDelaunayTriangulationCellBase_3`

\cgalCRPSection{Functions}

- \link PkgConstrainedTriangulation3FunctionsPolygonSoupOrMesh `CGAL::make_conforming_constrained_Delaunay_triangulation_3()` \endlink: the main function to create
a conforming constrained Delaunay triangulation in 3D, an instance of the class template
`CGAL::Conforming_constrained_Delaunay_triangulation_3`.
- `CGAL::Tetrahedral_remeshing::get_remeshing_triangulation()`

\cgalCRPSubsection{Classes}

- `CGAL::Conforming_constrained_Delaunay_triangulation_3<Traits, Triangulation>`
- `CGAL::Conforming_constrained_Delaunay_triangulation_vertex_base_3<Traits, Vertex_base>`
- `CGAL::Conforming_constrained_Delaunay_triangulation_cell_base_3<Traits, Cell_base>`

\cgalCRPSection{Draw a 3D Constrained Triangulation}

- \link PkgDrawCDT_3 `CGAL::draw()` \endlink

\cgalCRPSection{Output Functions}

- \link PkgCDT3IOFunctions `CGAL::IO::write_MEDIT()` \endlink

*/

---

### Constrained Triangulation 3 Doc Constrained Triangulation 3 Examples (`Constrained_triangulation_3/doc/Constrained_triangulation_3/examples.txt`)

/*!
\example Constrained_triangulation_3/conforming_constrained_Delaunay_triangulation_3.cpp
@brief

Simple example demonstrating the usage of the Constrained_triangulation_3 package.<br>

It constructs a 3D constrained Delaunay triangulation from a polygon mesh.
*/

/*!
\example Constrained_triangulation_3/ccdt_3_from_soup.cpp
@brief

Simple example demonstrating the usage of the Constrained_triangulation_3 package.<br>

It constructs a constrained Delaunay triangulation from a polygon soup.
*/

/*!
\example Constrained_triangulation_3/remesh_constrained_Delaunay_triangulation_3.cpp
@brief

How to use `CGAL::tetrahedral_isotropic_remeshing` with a constrained Delaunay triangulation.
*/


/*!
\example Constrained_triangulation_3/conforming_constrained_Delaunay_triangulation_3_fimap.cpp
@brief

From a non-manifold OFF file, construct the constrained Delaunay triangulation.
*/


/*!
\example Constrained_triangulation_3/ccdt_3_after_autorefinement.cpp
@brief

From a self-intersecting and non-triangulated surface in an OFF file,
construct the constrained Delaunay triangulation after preprocessing by autorefinement.
*/

/*!
\example Constrained_triangulation_3/ccdt_3_check_preconditions.cpp
\example Constrained_triangulation_3/ccdt_3_fimap_region_growing.cpp
\example Constrained_triangulation_3/ccdt_3_from_soup_fimap.cpp
\example Constrained_triangulation_3/ccdt_3_preprocessing.cpp
*/

---

### Convex Decomposition 3 Doc Convex Decomposition 3 Convex Decomposition 3 (`Convex_decomposition_3/doc/Convex_decomposition_3/Convex_decomposition_3.txt`)

namespace CGAL {
/*!

\mainpage User Manual
\anchor Chapter_Convex_Decomposition_of_Polyhedra
\anchor chapterConvexDecomposition3
\cgalAutoToc
\author Peter Hachenberger, Sven Oesau

\section Convex_decomposition_3Introduction Introduction

For many applications on non-convex polyhedra, there are efficient
solutions that first decompose the polyhedron into convex pieces. As
an example, the Minkowski sum of two polyhedra can be computed by
decomposing both polyhedra into convex pieces, compute pairwise
Minkowski sums of the convex pieces, and unite the pairwise sums.

While it is desirable to have a decomposition into a minimum number of
pieces, this problem is known to be NP-hard \cgalCite{c-cpplb-84}. This
package offers two methods for decomposing polyhedra. The
\ref Convex_decomposition_3Nef "Convex Decomposition of Nef Polyhedra"
splits polyhedra into convex pieces with an upper bound on their number.
The \ref Convex_decomposition_3ACD_Intro
"Approximate Convex Decomposition" method offers a fast
approximate decomposition of the convex hull into convex volumes. While
any number of convex volumes can be generated, these convex volumes
are more compact than the convex hull, but still include additional
empty space than just the input polyhedron.

\section Convex_decomposition_3Nef Convex Decomposition of Nef Polyhedra

The method decomposes a Nef polyhedron \f$ N\f$ into \cgalBigO{r^2} convex
pieces, where \f$ r\f$ is the number of edges that have two adjacent
facets that span an angle of more than 180 degrees with respect to the
interior of the polyhedron. Those edges are also called reflex edges.
The bound of \cgalBigO{r^2} convex pieces is worst-case
optimal \cgalCite{c-cpplb-84}.

\cgalFigureBegin{figverticalDecomposition,two_cubes_all_in_one.png}
Vertical decomposition based on the insertion of vertical facets (viewed from the top). Left: Non-convex polyhedron. Middle: Non-vertical reflex edges have been resolved. Right: Vertical reflex edges have been resolved. The sub-volumes are convex.
\cgalFigureEnd

The decomposition runs in two steps. In the first step, each
non-vertical reflex edge \f$ e\f$ is resolved by insertion of vertical
facets through \f$ e\f$. In the second step, the
vertical reflex edges are handled in the same way. \cgalFigureRef{figverticalDecomposition}
illustrates the two steps.

At the moment the implementation is restricted to the decomposition of
bounded polyhedra.

\subsection Convex_decomposition_3InterfaceandUsage Interface and Usage

An instance of `Nef_polyhedron_3` represents a subdivision of the
three-dimensional space into vertices, edges, facets, and
volumes. Some of these items form the polyhedron (selected), while
others represent the outer volume or holes within the polyhedron
(unselected). As an example, the unit cube is the point set
\f$ [0,1]^3\f$. The smallest subdivision that represents the unit cube has
8 vertices, 12 edges, 6 facets, and 2 volumes. The volumes enclosed by
the vertices, edges, and facets is the interior of the cube and
therefore selected. The volume outside the cube does not belong to it
and is therefore unselected. The vertices, edges, and facets - also
denoted as boundary items - are needed to separate the two volumes,
but are also useful for representing topological properties. In case
of the (closed) unit cube the boundary items are part of the
polyhedron and therefore selected, but in case of the open unit cube
\f$ [0,1)^3\f$ they are unselected. Each item has its own selection mark,
which allows the correct representation of Nef polyhedra, which are
closed under Boolean and topological operations. Details can be found
in Chapter \ref chapterNef3 "3D Boolean Operations on Nef Polyhedra".

Usually, an instance of `Nef_polyhedron_3` does not contain any
redundant items. However, the function `convex_decomposition_3()`
subdivides selected volumes of a given `Nef_polyhedron_3` by
selected facets. These additional facets are therefore redundant,
i.e., their insertion alters the representation of the polyhedron, but
not the polyhedron itself.

When `convex_decomposition_3()` resolved all reflex edges, the
selected sub-volumes have become convex. Each of them is represented
by a separate volume item and can therefore be traversed
separately as described in Section \ref subsectionNef_3ShellExploration. Another possibility
of accessing the convex pieces is to convert them into separate Nef
polyhedra, as illustrated by the example code given below.

Note that due to the restriction to bounded polyhedra, the use of
extended kernels is unnecessary and expensive. Therefore the use of
extended kernels in the convex decomposition is not supported.

\subsection Convex_decomposition_3Example Example

This example shows the usage of `CGAL::convex_decomposition_3(Nef_polyhedron_3&)` to decompose a Nef polyhedron into convex parts.

\cgalExample{Convex_decomposition_3/list_of_convex_parts.cpp}

\section Convex_decomposition_3ACD_Intro Approximate Convex Decomposition

\cgalFigureAnchor{Acd_topfig}
<center>
<img src="acd_top.jpg" style="max-width:70%;"/>
</center>
\cgalFigureCaptionBegin{Acd_topfig}
Approximate convex decomposition of the elephant.off model.\n From left to right: input mesh, 6, 9, and 12 convex volumes
\cgalFigureCaptionEnd

The H-VACD method \cgalCite{cgal:mamou2016volumetric}, "Hierarchical volumetric approximate convex decomposition", computes a set of convex volumes that fit the polyhedron. Contrary to the decomposition of the polyhedron into convex parts, the convex volumes cover the polyhedron, but also include additional volume outside of it.
A sufficiently tight enclosure of the polyhedron by several convex volumes allows fast intersection calculation and collision detection among polyhedra while offering a non-hierarchical approach and may thus be easier to use in a parallel setting.
The resulting set of convex volumes minimizes the volume between their union and the polyhedron while fully including the input polyhedron. While the optimal solution with `n` convex hulls that cover the polyhedron with the smallest additional volume remains NP-hard, this method provides a fast error-driven approximation.

\subsection Convex_decomposition_3ACD_Algorithm Algorithm
The algorithm computes a set of convex volumes \f$ C=\{C_i\f$ with \f$ i \in[0..n-1]\} \f$ that cover the input polyhedron while minimizing the additional covered volume:

\f{equation}{
\arg \min_C d(\bigcup_{C_i \in C} C_i, P) \\
\f}
<center>with</center>
\f{equation}{
d(A, B) = |A| - |B|
\f}

Where \f$|A|\f$ is the volume of A, P is the input polyhedron and \f$C_i\f$ are convex volumes. The convex volumes \f$C_i\f$ are may slightly overlap and their union contain the input polyhedron \f$ P \subset \bigcup_{C_i \in C} \f$.

\cgalFigureAnchor{Acd_pipelinefig}
<center>
<img src="acd_pipeline.jpg" style="max-width:90%;"/>
</center>
\cgalFigureCaptionBegin{Acd_pipelinefig}
Approximate convex decomposition pipeline.\n From left to right: 1. input mesh 2. voxel grid 3. convex volumes after error-driven splitting 4. final convex volumes after merging
\cgalFigureCaptionEnd

The method employs a top-down splitting phase followed by a bottom-up merging to achieve the target number of convex volumes. The splitting phase aims at decomposing the input mesh into smaller mostly convex parts. Each part of the input mesh is approximated with its convex hull. In a hierarchical manner, each part of the mesh is split into two parts when its convexity is low. The convexity is measured by the volume difference of the part and its convex hull. Splitting a part into two can be done by simply cutting the longest side of the bounding box in half. A better choice is often found by searching the longest side of the bounding box for a concave spot. However, it comes with a higher computational cost. The hierarchical splitting stops when either the convexity is sufficiently high or the maximum depth is reached.
The volume calculation, convex hull computation and the concavity search is accelerated by a voxel grid. The grid is prepared before the splitting phase and voxel cells overlapping with triangles are labeled as surface. The remaining voxels are labeled as outside or inside by flood fill, in case the input mesh is closed, or by axis-aligned ray shooting, i.e., along x, y and z-axes in positive and negative directions. A voxel is only labeled as inside if at least 3 faces facing away from the voxel have been hit and
no face facing towards the voxel. The convex hulls are calculated from voxel corners. Thus, a mesh with a high resolution is less penalized by its number of vertices.
The splitting phase typically results in a number of convex volumes larger than targeted.

To optionally improve the fit of the convex volumes, they can be refitted to the mesh before starting the second phase. The second phase employs a bottom-up merging that reduces the number of convex volumes to the targeted number while aiming at maintaining a low volume difference between convex volumes and the input mesh. The greedy merging maintains a priority queue to incrementally merge the pair of convex volumes with the smallest increase of volume difference.

The splitting phase is not limited by the chosen `maximum_number_of_convex_volumes`, because a splitting into a larger number of more convex parts with a subsequent merging leads to better results.

Due to the hierarchical splitting using planes, it is possible that a convex volume is degenerated. In the merging phase, these degenerated convex volumes are merged with a high priority. However, it is possible that the output of the method still contains degenerated convex volumes. This is especially the case, when a large `maximum_number_of_convex_volumes` is chosen while using a limited `maximum_depth`.

\subsection Convex_decomposition_3ACD_Parameters Parameters
Several parameters of the algorithm impact the quality of the result as well as the running time.
- `maximum_number_of_convex_volumes`: The maximum number of convex volumes output by the method. The actual number may be lower for mostly convex input meshes, e.g., a sphere. The impact on the running time is rather low. The default is 16.
- `maximum_depth`: The maximum depth for the hierarchical splitting phase. For complex meshes, a higher maximum depth is required to split small concavities into convex parts. The choice of  `maximum_depth` has a larger impact on the running time. The default is 10.
- `refitting`: The convex hulls can be refitted after the splitting phase to more tightly enclose the input mesh. It increases the running time, but significantly reduces the overhead volume included by the computed convex volumes. It is enabled by default.
- `maximum_number_of_voxels`: This parameter controls the resolution of the voxel grid used for speed-up. Larger numbers result in a higher memory footprint and a higher running time. A small number also limits the `maximum_depth`. The voxel grid is isotropic and the longest axis of the bounding box will be split into a number of voxels equal to the cubic root of `maximum_number_of_voxels`. The default value is 1.000.000.
- `volume_error`: The splitting of a convex volume into smaller parts is controlled by the `volume_error` which provides the tolerance for difference in volume. The difference is calculated by \f$ (|C_i| - |P_i|) / |P_i|\f$. The default value is 0.01. Thus, if a convex volume has 1 percent more volume that the part of the input mesh it approximates, it will be further divided.
- `split_at_concavity`: The splitting can be either performed after searching a concavity on the longest side of the bounding box or simply by splitting the longest side of the bounding box in half. The default value is true, i.e., splitting at the concavity.

\subsection Convex_decomposition_3ACD_Performance Performance
The method is demonstrated on a few models:

|  Data set                              | Faces |     Volume |    Convex hull volume |   Overhead |
| :---- | ----: | ----: | -: | -: |
|   Camel          | 19.536 | 0.0468 | 0.15541 | 2.32388 |
|   Elephant       | 5.558 | 0.0462 | 0.12987 | 1.81087 |
|   Triceratops    | 5.660 | 136.732 | 336.925 | 1.46412 |
|   Knot2    | 11.520 | 0.0488 | 0.19141 | 2.92334 |


The overhead is the convex hull volume divided by the volume of the mesh.
If not mentioned otherwise, all tests used a volume error of 0.01, a maximum depth of 10, 1 million voxels and split at the concavity.

Impact of varying the number of generated convex volumes with splitting at the concavity and refitting to the convex hull of the input mesh on volume overhead:


|  Data set  | Split location |     Refitting |    4 volumes |   6 volumes |   8 volumes |   10 volumes |   12 volumes | Running time |
| :---- | ----: | ----: | -: | -: | -: | -: | -: | -: |
|   Camel       | Concavity | + | 0.6951 | 0.4316 | 0.3016 | 0.2514 | 0.1955 | 2.22s |
|   Camel       | Concavity | - | 0.9932 | 0.7482 | 0.6174 | 0.5507 | 0.5261 | 1.20s |
|   Camel       | Mid | + | 0.7994 | 0.5589 | 0.3928 | 0.3211 | 0.2266 | 2.58s |
|   Camel       | Mid | - | 1.0875 | 0.9280 | 0.8394 | 0.6801 | 0.5529 | 1.29s |
|          |  | |  |  |  |  |  | |
|   Elephant    | Concavity | + | 0.7897 | 0.6505 | 0.4973 | 0.3986 | 0.3299 | 1.16s |
|   Elephant    | Concavity | - | 1.2140 | 1.0028 | 0.8071 | 0.7290 | 0.6870 | 0.98s |
|   Elephant    | Mid | + | 0.7448 | 0.5692 | 0.4453 | 0.3844 | 0.2912 | 1.99s |
|   Elephant    | Mid | - | 1.2075 | 1.0410 | 0.8247 | 0.6779 | 0.6263 | 1.45s |
|          |  | |  |  |  |  |  | |
|   Triceratops | Concavity | + | 0.5952 | 0.3978 | 0.3548 | 0.2385 | 0.2057 | 1.03s |
|   Triceratops | Concavity | - | 1.0073 | 0.7490 | 0.7035 | 0.5966 | 0.5429 | 0.59s |
|   Triceratops | Mid | + | 0.7149 | 0.4380 | 0.3984 | 0.2801 | 0.2303 | 1.53s |
|   Triceratops | Mid | - | 1.0470 | 0.8990 | 0.6749 | 0.5803 | 0.5237 | 0.91s |
|          |  | |  |  |  |  |  | |
|   Knot2       | Concavity | + | 1.2721 | 0.9538 | 0.6395 | 0.4748 | 0.4040 | 1.95s |
|   Knot2       | Concavity | - | 1.7901 | 1.4242 | 1.1538 | 0.9394 | 0.8496 | 1.49s |
|   Knot2       | Mid | + | 1.2451 | 0.9286 | 0.6178 | 0.4373 | 0.3558 | 2.08s |
|   Knot2       | Mid | - | 1.7143 | 1.3477 | 1.0436 | 0.9030 | 0.7910 | 1.78s |

The columns for the different number of volumes indicate the overhead of the union of the convex volumes compared to the volume of the mesh. Note that the convex volumes may overlap, thus the volume of their union may be lower than the sum of volumes.
Although searching the voxel grid for the concavity takes additional computational time, it is compensated by fewer splits.

\cgalFigureAnchor{Acd_resultsfig}
<center>
<img src="acd_results.jpg" style="max-width:90%;"/>
</center>
\cgalFigureCaptionBegin{Acd_resultsfig}
Approximate convex decomposition results.\n From left to right: input mesh, 4, 8, and 12 convex volumes
\cgalFigureCaptionEnd

\subsection Convex_decomposition_3ACD_Example Example

The example shows the approximate convex decomposition of the knot2.off mesh into 9 convex volumes that are saved as off files.

\cgalExample{Convex_decomposition_3/approximate_convex_decomposition.cpp }


\section Convex_decomposition_3_history Design and Implementation History

This package was created by Peter Hachenberger with the `CGAL::convex_decomposition_3()` method. In 2025, it has been extended by Sven Oesau with the `CGAL::approximate_convex_decomposition()` method.

*/
} /* namespace CGAL */

---

### Convex Decomposition 3 Doc Convex Decomposition 3 PackageDescription (`Convex_decomposition_3/doc/Convex_decomposition_3/PackageDescription.txt`)

/// \defgroup PkgConvexDecomposition3Ref Reference Manual

/*!
\addtogroup PkgConvexDecomposition3Ref
\cgalPkgDescriptionBegin{Convex Decomposition of Polyhedra,PkgConvexDecomposition3}
\cgalPkgPicture{Convex_decomposition_3/fig/Convex_decomposition_3-teaser.png}
\cgalPkgSummaryBegin
\cgalPkgAuthor{Peter Hachenberger, Sven Oesau}
\cgalPkgDesc{This packages provides two functions for computing a set of convex volumes that cover a bounded polyhedron. A convex decomposition of Nef Polyhedra into \cgalBigO{r^2} convex pieces, where \f$ r\f$ is the number of edges, whose adjacent facets form an angle of more than 180 degrees with respect to the polyhedron's interior. This bound is worst-case optimal.
A second method approximates the input mesh with convex volumes. While these convex volumes cover additional space outside of the polyhedron, the computation is fast for any chosen number of convex volumes.}
\cgalPkgManuals{Chapter_Convex_Decomposition_of_Polyhedra,PkgConvexDecomposition3Ref}
\cgalPkgSummaryEnd
\cgalPkgShortInfoBegin
\cgalPkgSince{3.5}
\cgalPkgBib{cgal:h-emspe}
\cgalPkgLicense{\ref licensesGPL  "GPL"}
\cgalPkgDemo{CGAL Lab,CGALlab.zip}
\cgalPkgShortInfoEnd
\cgalPkgDescriptionEnd

\cgalClassifedRefPages

\cgalCRPSection{Functions}
- \link CGAL::approximate_convex_decomposition() `CGAL::approximate_convex_decomposition(FaceGraph)` \endlink
- \link CGAL::convex_decomposition_3() `CGAL::convex_decomposition_3(NefPolyhedron_3)`  \endlink

*/

---

### Convex Decomposition 3 Doc Convex Decomposition 3 Examples (`Convex_decomposition_3/doc/Convex_decomposition_3/examples.txt`)

/*!
\example Convex_decomposition_3/approximate_convex_decomposition.cpp
\example Convex_decomposition_3/list_of_convex_parts.cpp
*/

---

### Convex Hull 2 Doc Convex Hull 2 Convex Hull 2 (`Convex_hull_2/doc/Convex_hull_2/Convex_hull_2.txt`)

namespace CGAL {
/*!

\mainpage User Manual
\anchor Chapter_2D_Convex_Hulls_and_Extreme_Points
\anchor chapconvexhull2
\cgalAutoToc
\authors Susan Hert and Stefan Schirra

\section Convex_hull_2Introduction Introduction

A subset \f$ S \subseteq \mathbb{R}^2\f$ is convex if for any two points \f$ p\f$ and \f$ q\f$
in the set the line segment with endpoints \f$ p\f$ and \f$ q\f$ is contained
in \f$ S\f$. The convex hull of a set \f$ S\f$
is the smallest convex set containing
\f$ S\f$. The convex hull of a set of points \f$ P\f$ is a convex
polygon with vertices in \f$ P\f$. A point in \f$ P\f$ is an extreme point
(with respect to \f$ P\f$) if it is a vertex of
the convex hull of \f$ P\f$. A set of points is said to be strongly convex
if it consists of only extreme points.

This chapter describes the functions provided in
\cgal for producing convex hulls in two dimensions as well as
functions for checking if sets of points are strongly convex are not.
There are also a number of functions described for computing particular
extreme points and subsequences of hull points, such as the lower and
upper hull of a set of points.

\image html saarhull.png
\image latex saarhull.png

\section secconvex_hull_2 Convex Hull

\cgal provides implementations of several classical algorithms for
computing the counterclockwise sequence of extreme points for a set of
points in two dimensions (<I>i.e.</I>, the counterclockwise sequence
of points on the convex hull). The algorithms have different asymptotic
running times and require slightly different sets of geometric primitives.
Thus you may choose the algorithm that best fits your setting.

Each of the convex hull functions presents the same interface to the
user. That is, the user provides a pair of iterators, `first`
and `beyond`, an output iterator `result`, and a traits class
`traits`. The points in the range [`first`, `beyond`) define
the input points whose convex hull is to be computed. The counterclockwise
sequence of extreme points is written to the sequence starting at position
`result`, and the past-the-end iterator for the resulting set of
points is returned. The traits classes for the functions specify the types
of the input points and the geometric primitives that are required by
the algorithms. All functions provide an interface in which this
class need not be specified and defaults to types and operations defined
in the kernel in which the input point type is defined.

Given a sequence of \f$ n\f$ input points with \f$ h\f$ extreme points,
the function `convex_hull_2()` uses either the output-sensitive \cgalBigO{n h} algorithm of Bykat \cgalCite{b-chfsp-78}
(a non-recursive version of the quickhull \cgalCite{bdh-qach-96} algorithm) or the algorithm of Akl and Toussaint, which requires \cgalBigO{n \log n} time
in the worst case. The algorithm chosen depends on the kind of
iterator used to specify the input points. These two algorithms are
also available via the functions `ch_bykat()` and `ch_akl_toussaint()`,
respectively. Also available are
the \cgalBigO{n \log n} Graham-Andrew scan algorithm \cgalCite{a-aeach-79}, \cgalCite{m-mdscg-84}
(`ch_graham_andrew()`),
the \cgalBigO{n h} Jarvis march algorithm \cgalCite{j-ichfs-73}
(`ch_jarvis()`),
and Eddy's \cgalBigO{n h} algorithm \cgalCite{e-nchap-77}
(`ch_eddy()`), which corresponds to the
two-dimensional version of the quickhull algorithm.
The linear-time algorithm of Melkman for producing the convex hull of
simple polygonal chains (or polygons) is available through the function
`ch_melkman()`.

\section Convex_hull_2Example Example using Graham-Andrew's Algorithm

In the following example a convex hull is constructed from point data read
from standard input using `Graham_Andrew` algorithm. The resulting convex
polygon is shown at the standard output console. The same results could be
achieved by substituting the function `ch_graham_andrew()` by other
functions such as `ch_bykat()`.

\cgalExample{Convex_hull_2/ch_from_cin_to_cout.cpp}


\section Convex_hull_2ExampleIndex  Example using a Property Map

In the following example we have as input a vector of points,
and we retrieve the indices of the points which are on the convex hull.
The convex hull function takes as fourth argument a traits class
that must be model of the concept `ConvexHullTraits_2`. It provides
predicates such as orientation tests.
The class `Convex_hull_traits_adapter_2` in combination with a
`Pointer_property_map`, is such a model. The indices `i` are then "points",
and the adapter performs the predicates on `points[i]`.

\cgalExample{Convex_hull_2/convex_hull_indices_2.cpp}


\section Convex_hull_2Extreme Extreme Points and Hull Subsequences

In addition to the functions for producing convex hulls, there are a
number of functions for computing sets and sequences of points related
to the convex hull.

The functions `lower_hull_points_2()` and `upper_hull_points_2()`
provide the computation of the counterclockwise
sequence of extreme points on the lower hull and upper hull,
respectively. The algorithm used in these functions is
Andrew's variant of Graham's scan algorithm \cgalCite{a-aeach-79}, \cgalCite{m-mdscg-84},
which has worst-case running time of \cgalBigO{n \log n}.

There are also functions available for computing certain subsequences
of the sequence of extreme points on the convex hull. The function
`ch_jarvis_march()` generates the counterclockwise ordered subsequence of
extreme points between a given pair of points and
`ch_graham_andrew_scan()` computes the sorted sequence of extreme points that are
not left of the line defined by the first and last input points.

Finally, a set of functions (`ch_nswe_point()`, `ch_ns_point()`,
`ch_we_point()`, `ch_n_point()`, `ch_s_point()`, `ch_w_point()`, `ch_e_point()`)
is provided for computing extreme points of a
2D point set in the coordinate directions.

\section Convex_hull_2Traits Traits Classes

Each of the functions used to compute convex hulls or extreme points
is parameterized by a traits class, which specifies the types and geometric
primitives to be used in the computation. There are several implementations
of 2D traits classes provided in the library. The class
`Convex_hull_traits_2` corresponds to the default traits class that provides the types and
predicates presented in the 2-dimensional \cgal kernel in which the input
points lie. The class `Convex_hull_constructive_traits_2` is a second traits class
 based on \cgal primitives but differs from `Convex_hull_traits_2` in that some of its primitives reuse
intermediate results to speed up computation.

In addition, the 2D and 3D Linear Geometric Kernel provides three projective traits classes
(`Projection_traits_xy_3`, `Projection_traits_xz_3`, and `Projection_traits_yz_3`),
which may be used to compute the convex hull of a set of three-dimensional
points projected into each of the three coordinate planes.

\section Convex_hull_2Convexity Convexity Checking

The functions `is_ccw_strongly_convex_2()` and `is_cw_strongly_convex_2()`
check whether a given sequence of 2D points forms a (counter)clockwise strongly
convex polygon. These are used in postcondition
testing of the two-dimensional convex hull functions.

In case you want to keep collinear points you can use the 2D Delaunay triangulation as
in the following example. This sequence is then <em>not</em> strongly convex.

\cgalExample{Convex_hull_2/ch_delaunay_2.cpp}

*/
} /* namespace CGAL */

---

### Convex Hull 2 Doc Convex Hull 2 PackageDescription (`Convex_hull_2/doc/Convex_hull_2/PackageDescription.txt`)

/// \defgroup PkgConvexHull2Ref Reference Manual

/// \defgroup PkgConvexHull2Concepts Concepts
/// \ingroup PkgConvexHull2Ref

/// \defgroup PkgConvexHull2Traits Traits Classes
/// \ingroup PkgConvexHull2Ref

/// \defgroup PkgConvexHull2Functions Convex Hull Functions
/// \ingroup PkgConvexHull2Ref

/// \defgroup PkgConvexHull2Convexity Convexity Checking
/// \ingroup PkgConvexHull2Ref

/// \defgroup PkgConvexHull2Subsequence Hull Subsequence Functions
/// \ingroup PkgConvexHull2Ref

/// \defgroup PkgConvexHull2Extreme Extreme Point Functions
/// \ingroup PkgConvexHull2Ref

/*!
\addtogroup PkgConvexHull2Ref

\cgalPkgDescriptionBegin{2D Convex Hulls and Extreme Points,PkgConvexHull2}
\cgalPkgPicture{Convex_hull_2/fig/convex_hull.png}
\cgalPkgSummaryBegin
\cgalPkgAuthors{Susan Hert and Stefan Schirra}
\cgalPkgDesc{This package provides functions for computing convex hulls in two dimensions as well as functions for checking if sets of points are strongly convex are not. There are also a number of functions described for computing particular extreme points and subsequences of hull points, such as the lower and upper hull of a set of points.}
\cgalPkgManuals{Chapter_2D_Convex_Hulls_and_Extreme_Points,PkgConvexHull2Ref}
\cgalPkgSummaryEnd
\cgalPkgShortInfoBegin
\cgalPkgSince{1.0}
\cgalPkgBib{cgal:hs-chep2}
\cgalPkgLicense{\ref licensesGPL  "GPL"}
\cgalPkgDemo{See Bounding Volumes,bounding_volumes_2.zip}
\cgalPkgShortInfoEnd
\cgalPkgDescriptionEnd

A subset \f$S \subseteq \mathbb{R}^2 \f$ is convex if for any two points `p` and `q`
in the set the line segment with endpoints `p` and `q` is contained in \f$ S \f$.
The convex hull of a set \f$ S \f$ is the smallest convex set containing \f$ S \f$.
The convex hull of a set of points `P` is a convex polygon with vertices in `P`.
A point in `P` is an extreme point (with respect to `P`) if it is a vertex
of the convex hull of `P`.

\cgal provides functions for computing convex hulls in two dimensions as well
as functions for testing if a given set of points is strongly convex or not.
There are also a number of functions available for computing particular extreme
points in 2D and subsequences of the hull points, such as the lower hull or
upper hull of a set of points.

\cgalClassifedRefPages

\cgalCRPSection{Assertions}

For the convex hull algorithms, the postcondition
check tests only convexity (if not disabled), but not containment of the
input points in the polygon or polyhedron defined by the output points.
The latter is considered an expensive checking and can be enabled by
defining `CGAL_CHECK_EXPENSIVE`.

\cgalCRPSection{Concepts}

- `ConvexHullTraits_2`

\cgalCRPSection{Traits Classes}

- `CGAL::Convex_hull_constructive_traits_2<R>`
- `CGAL::Convex_hull_traits_2<R>`
- `CGAL::Convex_hull_traits_adapter_2<R,P>`

\cgalCRPSection{Convex Hull Functions}

- `CGAL::ch_akl_toussaint()`
- `CGAL::ch_bykat()`
- `CGAL::ch_eddy()`
- `CGAL::ch_graham_andrew()`
- `CGAL::ch_jarvis()`
- `CGAL::ch_melkman()`
- `CGAL::convex_hull_2()`

\cgalCRPSection{Convexity Checking Functions}

- `CGAL::is_ccw_strongly_convex_2()`
- `CGAL::is_cw_strongly_convex_2()`

\cgalCRPSection{Hull Subsequence Functions}

- `CGAL::ch_graham_andrew_scan()`
- `CGAL::ch_jarvis_march()`
- `CGAL::lower_hull_points_2()`
- `CGAL::upper_hull_points_2()`

\cgalCRPSection{Extreme Point Functions}

- `CGAL::ch_e_point()`
- `CGAL::ch_nswe_point()`
- `CGAL::ch_n_point()`
- `CGAL::ch_ns_point()`
- `CGAL::ch_s_point()`
- `CGAL::ch_w_point()`
- `CGAL::ch_we_point()`


*/

---

### Convex Hull 2 Doc Convex Hull 2 Examples (`Convex_hull_2/doc/Convex_hull_2/examples.txt`)

/*!
\example Convex_hull_2/array_convex_hull_2.cpp
\example Convex_hull_2/convex_hull_indices_2.cpp
\example Convex_hull_2/ch_from_cin_to_cout.cpp
\example Convex_hull_2/ch_graham_anderson.cpp
\example Convex_hull_2/ch_timing.cpp
\example Convex_hull_2/iostream_convex_hull_2.cpp
\example Convex_hull_2/vector_convex_hull_2.cpp
\example Convex_hull_2/ch_delaunay_2.cpp
*/

---

### Convex Hull 3 Doc Convex Hull 3 Convex Hull 3 (`Convex_hull_3/doc/Convex_hull_3/Convex_hull_3.txt`)

namespace CGAL {
/*!

\mainpage User Manual
\anchor Chapter_3D_Convex_Hulls
\anchor chapconvexhull3
\cgalAutoToc
\authors Samuel Hornus, Susan Hert, Stefan Schirra, and Leo Valque

\cgalFigureBegin{figchbimba,chull_bimba.png}
The convex hull of a model made of 192135 points.
\cgalFigureEnd

\section Convex_hull_3Introduction Introduction

A subset \f$ S \subseteq \mathbb{R}^3\f$ is convex if for any two points \f$ p\f$ and \f$ q\f$
in the set the line segment with endpoints \f$ p\f$ and \f$ q\f$ is contained
in \f$ S\f$. The convex hull of a set \f$ S\f$
is the smallest convex set containing
\f$ S\f$. The convex hull of a set of points \f$ P \in \mathbb{R}^3\f$ is a convex
polytope with vertices in \f$ P\f$. A point in \f$ P\f$ is an extreme point
(with respect to \f$ P\f$) if it is a vertex of
the convex hull of \f$ P\f$. A set of points is said to be strongly convex if it consists of only extreme points.

This chapter describes the functions provided in
\cgal for producing convex hulls in three dimensions as well as
functions for checking if sets of points are strongly convex are not.
One can compute the convex hull of a set of points in three dimensions
in two ways in \cgal: using a static algorithm or using a
triangulation to get a fully dynamic computation.

\section secconvex_hull_3 Static Convex Hull Construction

The function
`convex_hull_3()` provides an
implementation of the quickhull algorithm \cgalCite{bdh-qach-96}.
There are two versions of this
function available, one that can be used when it is known that the output
will be a polyhedron (i.e., there are more than three points and
they are not all collinear) and one that handles all degenerate cases
and returns an `Object`, which may be a point, a segment, a
triangle, or a polyhedron. Both versions accept a range of input
iterators defining the set of points whose convex hull is to be computed
and a traits class defining the geometric types and predicates used in
computing the hull.

\subsection Convex_hull_3TraitsClass Traits Class

The function `convex_hull_3()` is parameterized by a traits class,
which specifies the types and geometric primitives to be used in the
computation.   As the function constructs 3D planes from three input
points, we cannot simply pass a kernel with inexact constructions as
optional argument for the traits class.

If input points from a kernel with exact predicates
and non-exact constructions are used, and a certified result is expected,
the class `Convex_hull_traits_3<R>` should be used
(`R` being the input kernel).
If the constructions from a kernel are exact this kernel can be used
directly as a traits class.

Note that the default traits class takes this into account, that is the
above considerations are only important for custom traits classes.

\subsubsection Convex_hull_3Example Example

The following program reads points from an input file and computes
their convex hull.  We assume that the points are
not all identical and not all collinear, thus we directly use a polyhedron
as output. In the example you see that the convex hull function can
write in any model of the concept `MutableFaceGraph`.


\cgalExample{Convex_hull_3/quickhull_3.cpp}


\subsubsection Convex_hull_3ExampleLower Example for Lower Dimensional Results

The following program reads points from an input file and computes
their convex hull. Depending on the dimension of the result, we will
get a point, a segment, a triangle, or a polyhedral surface.
Note that the latter may also be planar polygon with a border.

\cgalExample{Convex_hull_3/quickhull_any_dim_3.cpp}

\subsection Convex_hull_3ExtremePoints Extreme Points
In addition to the `convex_hull_3()` function, the function `extreme_points_3()` is also
provided in case only the points on the convex hull are required (without the connectivity
information). In addition the traits class adapter `CGAL::Extreme_points_traits_adapter_3`
is also provided in order to get the indices or more generally any given entity that
is associated a 3D point that is on the convex hull.

The following program reads a set of points from an OFF file and outputs the indices
of the points that are on the convex hull.
\cgalExample{Convex_hull_3/extreme_indices_3.cpp}

The following program reads and builds a mesh from an OFF file, and then collects the vertices
that are on the convex hull of the mesh.
\cgalExample{Convex_hull_3/extreme_points_3_sm.cpp}

\subsection Convex_hull_3HalfspaceIntersection Halfspace Intersection

The functions `halfspace_intersection_3()` and
`halfspace_intersection_with_constructions_3()`
uses the convex hull algorithm and the duality to compute the intersection
of a list of halfspaces. The first version does not explicitly compute
the dual points: the traits class handles this issue. The second one constructs
these points and hence is less robust but the computation is faster.

In order to compute the intersection an interior point is needed. It can be
either given by the user or computed using linear programming. Notice that the
second approach is slower due to the resolution of a linear program.

\subsubsection Convex_hull_3HalfspaceInntersectionExample Example

The following example computes the intersection of halfspaces defined by
tangent planes to a sphere.

\cgalExample{Convex_hull_3/halfspace_intersection_3.cpp}


\subsection Convex_hull_3ConvexityChecking Convexity Checking

The function `is_strongly_convex_3()`
implements the algorithm of Mehlhorn <I>et al.</I> \cgalCite{mnssssu-cgpvg-96}
to determine if the vertices of a given polytope constitute a strongly convex
point set or not. This function is used in postcondition testing for
`convex_hull_3()`.


\section Convex_hull_3Dynamic Dynamic Convex Hull Construction

Fully dynamic maintenance of a convex hull can be achieved by using the
class `Delaunay_triangulation_3`. This class supports insertion
and removal of points (i.e., vertices of the triangulation) and the
convex hull edges are simply the finite edges of infinite faces.
The following example illustrates the dynamic construction of a convex hull.
First, random points from a sphere of a certain radius are generated and are
inserted into a triangulation. Then the number of points of the convex hull
are obtained by counting the number of triangulation vertices incident to the
infinite vertex. Some of the points are removed and then the number of points
remaining on the hull are determined. Notice that the vertices incident to the
infinite vertex of the triangulation are on the convex hull but it may be that
not all of them are vertices of the hull.

\subsection Convex_hull_3Example_2 Example

The following example shows how to compute a convex hull with a triangulation.
The vertices incident to the infinite vertex are on the convex hull.

The function `convex_hull_3_to_face_graph()` can be used to obtain a polyhedral surface
that is model of the concept `MutableFaceGraph`, e.g. `Polyhedron_3` and `Surface_mesh`.

\cgalExample{Convex_hull_3/dynamic_hull_3.cpp}

\section Convex_hull_3Do_intersect Intersection Test of Convex Hulls

`CGAL::Convex_hull_3::do_intersect(ch1, ch2)` determines whether two convex hulls intersect or not.

Input hulls can be provided as a range of points or as a graph, and may be of different types.
Furthermore, when many intersection queries use the same object, one should wrap that input in the class `CGAL::Convex_hull_hierarchy_3` as to construct an optimized view of the convex hull and accelerate intersection tests.
This is especially true when the convex hull is made of a large number of vertices (see `CGAL::Convex_hull_hierarchy_3` for more details).

\subsection Do_intersectExample Example
The following program reads points from two input files, computes their convex hulls with `Convex_hull_hierarchy_3` and prints if they intersect or not.
\cgalExample{Convex_hull_3/do_intersect_ch3.cpp}

\section Convex_hull_3Performance Performance

In the following, we compare the running times of the two approaches to compute 3D convex hulls.
For the static version (using `convex_hull_3()`) and the dynamic version
(using `Delaunay_triangulation_3` and `convex_hull_3_to_face_graph()`), the kernel
used was `Exact_predicates_inexact_constructions_kernel`.

To compute the convex hull of a million of random points in a unit ball the static approach needed 1.63s, while
the dynamic approach needed 9.50s.
To compute the convex hull of the model of \cgalFigureRef{figchbimba} featuring 192135 points,
the static approach needed 0.18s, while the dynamic approach needed 1.90s.

The measurements have been performed using \cgal 3.9, using the \gnu \cpp compiler version 4.3.5, under Linux (Debian distribution),
with the compilation options <TT>-O3 -DCGAL_NDEBUG</TT>. The computer used was equipped with a 64bit Intel Xeon 2.27GHz processor and 12GB of RAM.


\section Convex_hull_3History Implementation History

The initial version of this package was implemented by Susan Hert and Stefan Schirra, and released in 2011.
The functions `do_intersect()`, `extreme_point_3()`, and the class `Convex_hull_hierarchy_3` were implemented in 2026 by Samuel Hornus and Leo Valque, under the supervision of Sébastien Loriot.


*/
} /* namespace CGAL */

---

### Convex Hull 3 Doc Convex Hull 3 PackageDescription (`Convex_hull_3/doc/Convex_hull_3/PackageDescription.txt`)

/// \defgroup PkgConvexHull3Ref Reference Manual

/// \defgroup PkgConvexHull3Concepts Concepts
/// \ingroup PkgConvexHull3Ref

/// \defgroup PkgConvexHull3Traits Traits Classes
/// \ingroup PkgConvexHull3Ref

/// \defgroup PkgConvexHull3Intersections Intersection Test Functions
/// \ingroup PkgConvexHull3Ref

/// \defgroup PkgConvexHull3Queries Directional Queries Functions
/// \ingroup PkgConvexHull3Ref

/*! \defgroup PkgConvexHull3Functions Convex Hull Functions
   \ingroup PkgConvexHull3Ref
The function `CGAL::convex_hull_3()` computes the convex hull of a given set of
three-dimensional points.

Two versions of this function are available. The first can be used when it
is known that the result will be a polyhedron and the second when a
degenerate hull may also be possible.
*/

/// \defgroup PkgConvexityChecking Convexity Checking
/// \ingroup PkgConvexHull3Ref

/*!
\addtogroup PkgConvexHull3Ref
\todo fix or keep the `Default_traits`

\cgalPkgDescriptionBegin{3D Convex Hulls,PkgConvexHull3}
\cgalPkgPicture{Convex_hull_3/fig/bunny.png}
\cgalPkgSummaryBegin
\cgalPkgAuthors{Susan Hert and Stefan Schirra}
\cgalPkgDesc{This package provides functions for computing convex hulls in three dimensions, as well as functions for checking if sets of points are strongly convex or not, and checking if two convex hulls intersect or not. One can compute the convex hull of a set of points in three dimensions in three ways: using a static algorithm, using a triangulation to get a fully dynamic computation, or using the specific data structure `Convex_hull_hierarchy_3` for optimal intersection testing.}
\cgalPkgManuals{Chapter_3D_Convex_Hulls,PkgConvexHull3Ref}
\cgalPkgSummaryEnd
\cgalPkgShortInfoBegin
\cgalPkgSince{1.1}
\cgalPkgDependsOn{The dynamic algorithms depend on \ref PkgTriangulation3 "3D Triangulations".}
\cgalPkgBib{cgal:hs-ch3}
\cgalPkgLicense{\ref licensesGPL  "GPL"}
\cgalPkgDemo{CGAL Lab,CGALlab.zip}
\cgalPkgShortInfoEnd
\cgalPkgDescriptionEnd

A subset \f$S \subseteq \mathbb{R}^3 \f$ is convex if for any two points `p` and `q`
in the set the line segment with endpoints `p` and `q` is contained
in \f$S\f$. The convex hull of a set \f$ S \f$ is the smallest convex set containing
\f$ S \f$. The convex hull of a set of points `P` is a convex
polytope with vertices in `P`.  A point in `P` is an extreme point
(with respect to `P`) if it is a vertex of the convex hull of `P`.

\cgal provides functions for computing convex hulls in two, three
and arbitrary dimensions as well as functions for testing if a given set of
points in is strongly convex or not and checking if two convex hulls intersect. This chapter describes the functions
available for three dimensions.

\cgalCRPSection{Assertions}
For the convex hull algorithms, the postcondition
check tests only convexity (if not disabled), but not containment of the
input points in the polygon or polyhedron defined by the output points.
The latter is considered an expensive checking and can be enabled by
defining `CGAL_CHECK_EXPENSIVE`.

\cgalClassifedRefPages

\cgalCRPSection{Concepts}

- `ConvexHullTraits_3`
- `IsStronglyConvexTraits_3`

\cgalCRPSection{Traits Classes}

- `CGAL::Convex_hull_traits_3<R>`
- `CGAL::Extreme_points_traits_adapter_3`
- `CGAL::make_extreme_points_traits_adapter()`

\cgalCRPSection{Convex Hull Functions}

- `CGAL::convex_hull_3()`
- `CGAL::extreme_points_3()`

\cgalCRPSection{Intersection and Directional Queries}

- `CGAL::extreme_point_3()`
- `CGAL::extreme_vertex_3()`
- `CGAL::Convex_hull_3::do_intersect()`
- `CGAL::Convex_hull_hierarchy_3`

\cgalCRPSection{Convexity Checking Function}

- `CGAL::is_strongly_convex_3`

\cgalCRPSection{Halfspace Intersection Functions}

- `CGAL::halfspace_intersection_3()`
- `CGAL::halfspace_intersection_with_constructions_3()`
- `CGAL::halfspace_intersection_interior_point_3()`

*/

---

### Convex Hull 3 Doc Convex Hull 3 Examples (`Convex_hull_3/doc/Convex_hull_3/examples.txt`)

/*!
\example Convex_hull_3/dynamic_hull_3.cpp
\example Convex_hull_3/dynamic_hull_OM_3.cpp
\example Convex_hull_3/quickhull_3.cpp
\example Convex_hull_3/quickhull_OM_3.cpp
\example Convex_hull_3/halfspace_intersection_3.cpp
\example Convex_hull_3/quickhull_any_dim_3.cpp
\example Convex_hull_3/extreme_points_3_sm.cpp
\example Convex_hull_3/extreme_indices_3.cpp
\example Convex_hull_3/quickhull_indexed_triangle_set_3.cpp
\example Convex_hull_3/do_intersect_ch3.cpp
*/

---

### Convex Hull D Doc Convex Hull D Convex Hull D (`Convex_hull_d/doc/Convex_hull_d/Convex_hull_d.txt`)

namespace CGAL {
/*!

\mainpage User Manual
\anchor Chapter_dD_Convex_Hulls_and_Delaunay_Triangulations
\anchor chapconvexhulld
\authors Susan Hert and Michael Seel

\deprecated This package is deprecated since the version 4.6 of \cgal. The package \ref PkgTriangulations should be used instead.

\section Convex_hull_dIntroduction Introduction

A subset \f$ S \subseteq \mathbb{R}^d\f$ is convex if for any two points \f$ p\f$ and \f$ q\f$
in the set the line segment with endpoints \f$ p\f$ and \f$ q\f$ is contained
in \f$ S\f$. The convex hull of a set \f$ S\f$
is the smallest convex set containing
\f$ S\f$. The convex hull of a set of points \f$ P\f$ is a convex
polytope with vertices in \f$ P\f$. A point in \f$ P\f$ is an extreme point
(with respect to \f$ P\f$) if it is a vertex of
the convex hull of \f$ P\f$. A set of points is said to be strongly convex if it consist of only extreme points.

This chapter describes the class provided in \cgal for producing convex
hull in arbitrary dimensions. There is an intimate relationship between
the Delaunay triangulation of a point set \f$ S\f$ and the convex hull of
`lift(S)`: The nearest site
Delaunay triangulation is the projection of the lower hull and the
furthest site Delaunay triangulation is the upper hull. Here we also
describe the companion class to the convex hull class that computes
nearest and furthest site Delaunay triangulations.

\section Convex_hull_ddD dD Convex Hull

The class `Convex_hull_d<R>` is used to represent the
convex hull of a set of points in \f$ d\f$-dimensional space. This class
supports incremental construction of hulls, and provides a rich
interface for exploration. There are also output routines for hulls
of dimension 2 and 3.

The convex hull class is parameterized by a traits class that provides
\f$ d\f$-dimensional data types and predicates. The class
`Convex_hull_d_traits_3` adapts any low-dimensional standard kernel
model <I>e.g.</I>, `Homogeneous<RT>` or `Cartesian<FT>` for use
with `Convex_hull_d`, where the dimension is fixed to three.
The validity of the computed convex hull can be checked using the
member function `Convex_hull_d::is_valid`, which implements the algorithm
of Mehlhorn <I>et al.</I>\cgalCite{mnssssu-cgpvg-96} to determine if
the vertices of a given polytope constitute a strongly convex point
set or not.

The implementation follows the papers \cgalCite{cms-frric-93} and
\cgalCite{bms-dgc-94}.

\section Convex_hull_dDelaunay Delaunay Triangulation

There is a class type with a thorough interface providing the
construction and exploration of closest and furthest site Delaunay
simplicial complexes in arbitrary higher dimension. The class
`Delaunay_d<R, Lifted_R>`C provides an
implementation via the lifting map to higher dimensional
convex hulls.lifting map, dD.
The class supports incremental construction of Delaunay triangulations
and various kind of query operations (in particular, nearest and furthest
neighbor queries and range queries with spheres and simplices).

*/
} /* namespace CGAL */

---

### Convex Hull D Doc Convex Hull D PackageDescription (`Convex_hull_d/doc/Convex_hull_d/PackageDescription.txt`)

/// \defgroup PkgConvexHullDRef Reference Manual
/// \defgroup PkgConvexHullDConcepts Concepts
/// \ingroup PkgConvexHullDRef
/*!
\addtogroup PkgConvexHullDRef
\cgalPkgDescriptionBegin{dD Convex Hulls and Delaunay Triangulations,PkgConvexHullD}
\cgalPkgPicture{convex_hull_d-teaser.png}
\cgalPkgSummaryBegin
\cgalPkgAuthors{Susan Hert and Michael Seel}
\cgalPkgDesc{This package provides functions for computing convex hulls and Delaunay triangulations in \f$ d\f$-dimensional Euclidean space.}
\cgalPkgManuals{Chapter_dD_Convex_Hulls_and_Delaunay_Triangulations,PkgConvexHullDRef}
\cgalPkgSummaryEnd
\cgalPkgShortInfoBegin
\cgalPkgSince{2.3}
\cgalPkgBib{cgal:hs-chdt3}
\cgalPkgLicense{\ref licensesGPL "GPL"}
\cgalPkgShortInfoEnd
\cgalPkgDescriptionEnd

\deprecated This package is deprecated since the version 4.6 of \cgal. The package \ref PkgTriangulations should be used instead.

A subset \f$ S \subseteq \mathbb{R}^d\f$ is convex if for any two points \f$ p\f$ and \f$ q\f$
in the set the line segment with endpoints \f$ p\f$ and \f$ q\f$ is contained
in \f$ S\f$. The convex hull of a set \f$ S\f$ is
the smallest convex set containing
\f$ S\f$. The convex hull of a set of points \f$ P\f$ is a convex
polytope with vertices in \f$ P\f$.A point in \f$ P\f$ is an extreme point
(with respect to \f$ P\f$) if it is a vertex
of the convex hull of \f$ P\f$.

\cgal provides functions for computing convex hulls in two, three
and arbitrary dimensions as well as functions for testing if a given set of
points in is strongly convex or not. This chapter describes the class
available for arbitrary dimensions and its companion class for
computing the nearest and furthest site Delaunay triangulation.

\cgalClassifedRefPages

\cgalCRPSection{Concepts}
- `ConvexHullTraits_d`
- `DelaunayLiftedTraits_d`
- `DelaunayTraits_d`

\cgalCRPSection{Classes}
- `CGAL::Convex_hull_d_traits_3<R>`
- `CGAL::Convex_hull_d<R>`
- `CGAL::Delaunay_d< R, Lifted_R > `

*/

---

### Documentation Doc Documentation Doxygen For CGAL (`Documentation/doc/Documentation/Doxygen_for_CGAL.md`)

\page Doxygen_for_CGAL Doxygen for CGAL

This is the documentation of doxygen hacks that are applied to make
the output of Doxygen more suitable to CGAL. It explains the general
structure of the build system, the ordinary customizations and the
hacks that create what you see.

## Overall structure ##

## Ordinary Customization ##

## Hacks ##

### Package Overview ###

The package overview is built by having a special command that is
filtered by the python script `pkglist_filter.py`.

A command has to be of the form `\package_listing{PKG_NAME}`, where
`PKG_NAME` cannot contain a closing `}`.

The command is replaced by the text between the two delimiters
`cgalPkgDescriptionBegin` and `cgalPkgDescriptionEnd` in the file `../PKG_NAME/doc/PKG_NAME/PackageDescription.txt`

If `PKG_NAME` is of the form `A/B` the selected file is
`../A/doc/B/PackageDescription.txt`. This is to support packages like
`TDS_2`, which don't reside in their own packages in the SCM.

### Footnotes ###

A JQuery footnotes plug-in jquery.footnotes is used to handle
footnotes. The special doxygen command `\cgalFootnote` expands to the
appropriate html marker. Some JavaScript in `header.html` is used to
append the `<ol div="autoFootnotes0">` to the current doc-content
div. It is not added to the footer because this would break when tree
views are enabled.

The plug-in code is part of `hacks.js` to minimize the amount of files
that have to be delivered.

### autotoc ###

TOCs in HTML are generated by the some JavaScript. This is necessary
to work around the fact that doxygen does not supported sections that
have no label in a TOC. This command simply becomes a normal toc in
LaTex.

### Reference Manual link in the tree view  ###

This hack fiddles with the internal structures and functions of the
treeview to remove the unnecessary intermediate top-level module part.

It assigns the first element of the module array (found in `module.js`)
to the Reference Manual entry. This makes the tree view link go to
that group directly instead of the intermediate link. It also removes
one level of nesting.

Unfortunately this changes the overall tree structure. To adjust for
that we hijack the `gotoNode` function of `navtree.js` and *augment* it
with an additional check for the specific tree level we borked and
redirect it.

All of it is in `header.html` and `hacks.js`.

# Things that would be nice to have #

## Search ##
The search function could be better:
- member functions could be removed
- global functions could be searchable
- package codenames could be supported

## Function Documentation ##

Automatic grouping of overloads or a switch to document functions in a
style more similar to classes, e.g. with their own page.

## Global Build Version ##

I have no idea how feasible that actually is, but it might be worth a
try.

## Package Overview ##

Build the Package Overview with the help of the Build System.

---

### Documentation Doc Documentation General (`Documentation/doc/Documentation/General.txt`)

/// \cgalConcept
/// Concept from the \cpp standard.
/// See https://en.cppreference.com/w/cpp/named_req/DefaultConstructible
class DefaultConstructible {};

/// \cgalConcept
/// Concept from the \cpp standard.
/// See https://en.cppreference.com/w/cpp/named_req/CopyConstructible
class CopyConstructible {};

/// \cgalConcept
/// Concept from the \cpp standard.
/// See https://en.cppreference.com/w/cpp/named_req/CopyAssignable
class CopyAssignable {};

///This concept refines both `CopyAssignable` and `CopyConstructible`.
class Assignable {};

/// \cgalConcept
/// Concept from the \cpp standard.
/// See https://en.cppreference.com/w/cpp/named_req/Callable
class Callable {};

/// \cgalConcept
/// Concept from the \cpp standard.
/// See https://en.cppreference.com/w/cpp/named_req/EqualityComparable
class EqualityComparable {};

/// \cgalConcept
/// Concept from the \cpp standard.
/// See https://en.cppreference.com/w/cpp/named_req/LessThanComparable
class LessThanComparable {};

/// \cgalConcept
/// The concept `AdaptableFunctor` defines an adaptable functor, that is, a functor that can be
/// used with function object adaptors such as binders and composers.
///
class AdaptableFunctor {};

/// \cgalConcept
/// Adaptable functor with one argument
/// \cgalRefines{AdaptableFunctor}
class AdaptableUnaryFunction
{
public:
  /// result_type
  typedef unspecified_type result_type;
  /// argument_type
  typedef unspecified_type argument_type;
  /// operator type
  result_type operator()(argument_type);
};

/// \cgalConcept
/// Adaptable functor with two arguments
/// \cgalRefines{AdaptableFunctor}
class AdaptableBinaryFunction
{
public:
  /// result_type
  typedef unspecified_type result_type;
  /// first argument_type
  typedef unspecified_type first_argument_type;
  /// second argument_type
  typedef unspecified_type second_argument_type;
  /// operator type
  result_type operator()(first_argument_type, second_argument_type);
};

/// \cgalConcept
/// Adaptable functor with three arguments
/// \cgalRefines{AdaptableFunctor}
class AdaptableTernaryFunction
{
public:
  /// result_type
  typedef unspecified_type result_type;
  /// first argument_type
  typedef unspecified_type first_argument_type;
  /// second argument_type
  typedef unspecified_type second_argument_type;
  /// third argument_type
  typedef unspecified_type third_argument_type;
  /// operator type
  result_type operator()(first_argument_type, second_argument_type, third_argument_type);
};

/// \cgalConcept
/// Adaptable functor with four arguments
/// \cgalRefines{AdaptableFunctor}
class AdaptableQuaternaryFunction
{
public:
  /// result_type
  typedef unspecified_type result_type;
  /// first argument_type
  typedef unspecified_type first_argument_type;
  /// second argument_type
  typedef unspecified_type second_argument_type;
  /// third argument_type
  typedef unspecified_type third_argument_type;
  /// fourth argument_type
  typedef unspecified_type fourth_argument_type;
  /// operator type
  result_type operator()(first_argument_type, second_argument_type, third_argument_type, fourth_argument_type);
};

/// \cgalConcept
/// Adaptable functor with five arguments
/// \cgalRefines{AdaptableFunctor}
class AdaptableQuinaryFunction
{
public:
  /// result_type
  typedef unspecified_type result_type;
  /// first argument_type
  typedef unspecified_type first_argument_type;
  /// second argument_type
  typedef unspecified_type second_argument_type;
  /// third argument_type
  typedef unspecified_type third_argument_type;
  /// fourth argument_type
  typedef unspecified_type fourth_argument_type;
  /// fifth argument_type
  typedef unspecified_type fifth_argument_type;
  /// operator type
  result_type operator()(first_argument_type, second_argument_type, third_argument_type, fourth_argument_type, fifth_argument_type);
};

/// \cgalConcept
/// Concept from the \cpp standard.
/// See https://en.cppreference.com/w/cpp/named_req/Iterator
class Iterator {};

/// \cgalConcept
/// Concept from the \cpp standard.
/// See https://en.cppreference.com/w/cpp/named_req/OutputIterator
class OutputIterator {};

/// \cgalConcept
/// Concept from the \cpp standard.
/// See https://en.cppreference.com/w/cpp/named_req/InputIterator
class InputIterator {};

/// \cgalConcept
/// Concept from the \cpp standard.
/// See https://en.cppreference.com/w/cpp/named_req/ForwardIterator
class ForwardIterator {};

/// \cgalConcept
/// Concept from the \cpp standard.
/// See https://en.cppreference.com/w/cpp/named_req/RandomAccessIterator
class RandomAccessIterator {};

/// \cgalConcept
/// Concept from the \cpp standard.
/// See https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator
class BidirectionalIterator {};

/// \cgalConcept
/// A regular type is a type similar to `int`: it is copyable, assignable, and equality comparable.
/// \cgalRefines{DefaultConstructible, CopyConstructible, CopyAssignable, EqualityComparable}
/// See also the C++ concept `std::regular` at https://en.cppreference.com/w/cpp/concepts/regular
class Regular {};

/// \cgalConcept
/// Concept from the \cpp standard.
/// See https://en.cppreference.com/w/cpp/named_req/Swappable
class Swappable {};

/// \cgalConcept
/// Concept from the \cpp standard.
/// See https://en.cppreference.com/w/cpp/named_req/Container
class Container {};

/// \cgalConcept
/// Concept from the \cpp standard.
/// See https://en.cppreference.com/w/cpp/named_req/ReversibleContainer
class ReversibleContainer {};

/// \cgalConcept
/// Concept from the \cpp standard.
/// See https://en.cppreference.com/w/cpp/named_req/AssociativeContainer
class AssociativeContainer {};

/// \cgalConcept
/// Concept from the \cpp standard.
/// See https://en.cppreference.com/w/cpp/named_req/SequenceContainer
class SequenceContainer {};

/// \cgalConcept
/// This container concept refines
/// <a href="https://en.cppreference.com/w/cpp/named_req/ReversibleContainer"><tt>ReversibleContainer</tt></a> and its iterator type is a model of
/// <a href="https://en.cppreference.com/w/cpp/named_req/RandomAccessIterator"><tt>RandomAccessIterator</tt></a>.
class RandomAccessContainer {};

/// \cgalConcept
/// This container concepts refines
/// <a href="https://en.cppreference.com/w/cpp/named_req/SequenceContainer"><tt>SequenceContainer</tt></a> and
/// has the ability to append elements at the end of the sequence and to access the last element, both in amortized constant time.
class BackInsertionSequence
{
public:
  /// returns the last inserted element.
  const value_type& back() const;
  /// removes the last inserted element if not empty.
  void pop_back()
  /// inserts an element
  void push_back(const value_type&)
};

/*!
See https://www.boost.org/doc/libs/latest/libs/property_map/doc/LvaluePropertyMap.html
\cgalConcept
*/
class LvaluePropertyMap {};

/*!
See https://www.boost.org/doc/libs/latest/libs/property_map/doc/ReadWritePropertyMap.html
\cgalConcept
*/
class ReadWritePropertyMap {};

/*!
See https://www.boost.org/doc/libs/latest/libs/property_map/doc/WritablePropertyMap.html
\cgalConcept
*/
class WritablePropertyMap {};

/*!
See https://www.boost.org/doc/libs/latest/libs/property_map/doc/ReadablePropertyMap.html
\cgalConcept
*/
class ReadablePropertyMap {};

/*!
See https://www.boost.org/doc/libs/latest/libs/range/doc/html/range/concepts/single_pass_range.html
\cgalConcept
*/
class SinglePassRange {};

/*!
See https://www.boost.org/doc/libs/latest/libs/range/doc/html/range/concepts/random_access_range.html
\cgalConcept
*/
class RandomAccessRange {};

/*!
See https://www.boost.org/doc/libs/latest/libs/range/doc/html/range/concepts/forward_range.html
\cgalConcept
*/
class ForwardRange {};

/*!
Concept from the Boost Graph Library.
See https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/concepts/IncidenceGraph.html
\cgalConcept
*/
class IncidenceGraph {};

/*!
Concept from the Boost Graph Library.
See https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/concepts/BidirectionalGraph.html
\cgalConcept
*/
class BidirectionalGraph {};

/*!
Concept from the Boost Graph Library.
See https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/concepts/VertexAndEdgeListGraph.html
\cgalConcept
*/
class VertexAndEdgeListGraph {};

/*!
Concept from the Boost Graph Library.
See https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/concepts/AdjacencyGraph.html
\cgalConcept
*/
class AdjacencyGraph {};

/*!
Concept from the Boost Graph Library.
See https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/concepts/AdjacencyMatrix.html
\cgalConcept
*/
class AdjacencyMatrix {};

/*!
Concept from the Boost Graph Library.
See https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/concepts/MutableGraph.html
\cgalConcept
*/
class MutableGraph {};

/*!
Concept from the Boost Graph Library.
See https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/concepts/PropertyGraph.html
\cgalConcept
*/
class PropertyGraph {};

/*!
Concept from the Boost Graph Library.
See https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/concepts/MutablePropertyGraph.html
\cgalConcept
*/
class MutablePropertyGraph {};

/*!
This indicates that the definition of a type nested in a class is not documented.
*/
class unspecified_type {};

---

### Documentation Doc Documentation Getting Started (`Documentation/doc/Documentation/Getting_started.txt`)

/*!
\page general_intro Getting Started with %CGAL

The following pages describe how to use \cgal on different environments:

- \subpage usage

- \subpage windows

- \subpage thirdparty gives information (supported versions, download links) of the required and optional third-party libraries.

- \subpage devman_create_and_use_a_cmakelist explains how to use CMake to link a program with \cgal.

The following pages cover advanced installation options:

- \subpage configurationvariables gives information about which CMake variables can be used to help
resolve missing dependencies while using the cmake command line tool.

- \subpage installation describes the process of configuring and installing \cgal.

The following pages cover the structure of the manual and general information about \cgal:

- \subpage manual gives an idea of where you should look for documentation.

- \subpage preliminaries lists how to control inlining, thread safety, code deprecation, checking
of pre- and postconditions, how to alter the failure behavior, and how to check the version of \cgal.

- \subpage license describes the different licenses used within \cgal, with which users must comply.

Once you are familiar with building your programs with \cgal and how the documentation is structured,
you can head over to the \ref tutorials for a gentle introduction to \cgal, or directly to the package(s)
that interest you the \ref packages. Each package contains simple examples of the various functionalities of the package.

*/

---

### Documentation Doc Documentation Preliminaries (`Documentation/doc/Documentation/Preliminaries.txt`)

/*!

\page preliminaries General Information
\cgalAutoToc

The chapter explains some basic features of \cgal such as thread safety, code deprecation,
checking of pre- and postconditions and altering the failure behavior, and how to control inlining.

These concepts are further developed in the \ref dev_manual.

\section Preliminaries_namespace Namespace CGAL

All names introduced by \cgal, especially those documented in these
manuals, are in a namespace called `CGAL`, which is in global
scope. A user can either qualify names from \cgal by adding
`CGAL::`, e.g., `CGAL::Point_2< CGAL::Exact_predicates_inexact_constructions_kernel >`,
make a single name from \cgal visible in a scope via a `using`
statement, e.g., `using CGAL::Point_2;`, and then use this name
unqualified in this scope, or even make all names from namespace
`CGAL` visible in a scope with `using namespace CGAL;`. The
latter, however, is likely to give raise to name conflicts and is
therefore not recommended.


\section Preliminaries_thread_safety Thread Safety

\cgal is progressively being made thread-safe.  The guidelines which are followed
are:

- it should be possible to use different objects in different threads at the same time (of the same type or not),
- it is not safe to access the same object from different threads at the same time, unless otherwise specified in the class documentation.

If the macro `CGAL_HAS_THREADS` is not defined, then \cgal assumes it can use
any thread-unsafe code (such as static variables).  By default, this macro is not
defined, unless `BOOST_HAS_THREADS` or `_OPENMP` is defined.  It is possible
to force its definition in the compiler options, and it is possible to prevent its
default definition by defining the macro `CGAL_HAS_NO_THREADS`.
If you are using CMake, then you can set the CMake option `CGAL_HAS_NO_THREADS` to
`TRUE`. In addition to defining the preprocessor macro `CGAL_HAS_NO_THREADS`, it will
also avoid CMake to link with the native threads support library on your system.

\section Preliminaries_cc0x C++17 Support

\cgal is based on the version C++17 of the C++ standard.

\section preliminaries_secconmod Concepts and Models

One of the core principles of \cgal is algorithmic <em>genericity</em>, enabling users to call
algorithms with custom data types, and to modify their behavior. To achieve this, and following
the examples of the C++ Standard Template Library (STL) and \boost libraries, \cgal makes heavy
use of C++ templates.

The traditional design pattern used to specify the requirements of these templates is
the <em>concept-model pattern</em>. In this context, a <em>concept</em> is an informal,
abstract set of requirements on a type. A type that satisfies these requirements is said to
<em>model the concept</em>. A concept's requirements are typically syntactic (the set of valid
expressions that a type must support, including member types, member functions, and operators)
and semantic (the expected behavior and invariants of the syntactic requirements) requirements.

For example, the concept `FaceGraph` describes the requirements for a graph data structure that
explicitly maintains faces defined by halfedges. It requires specific accessors, such as a function
to get an incident halfedge from a face, and a function to get an incident face from a halfedge.
Any class that provides these operations with the expected behavior, such as `CGAL::Surface_mesh`
or `CGAL::Polyhedron_3`, can be said to model the `FaceGraph` concept. This allows these different
data structures to be used interchangeably as arguments to many mesh processing algorithms of \cgal.

Concepts can also be <em>refined</em>. A refined concept builds upon an existing one by adding
further requirements. For instance, a `MutableFaceGraph` concept would inherit all the requirements
of `FaceGraph` but add new ones for operations that modify the graph structure, such as adding or
removing faces. Any type that models `MutableFaceGraph` also models `FaceGraph`.

It is important to note that these concepts from the concept-model design pattern should not be
confused with the <a href="https://en.cppreference.com/w/cpp/language/constraints.html">first-class concepts</a> language feature introduced in C++20.
The requirements described by the concept-model pattern are more akin to the pre-existing
<a href="https://en.cppreference.com/w/cpp/named_req.html">C++ Named Requirements</a>
found in the C++ standard, which serve as a formal description of the interface and behavior
required of template arguments. The concept-model pattern provides the philosophical framework
for designing generic libraries like \cgal.

\section preliminaries_secchecks Checks

Much of the \cgal code contains assert statements for preconditions, and postconditions of functions
as well as in the code.  These assertions can be switched on and off per package
and the user can change the error behavior. For details see Section \ref secchecks
of Chapter \ref Chapter_STL_Extensions_for_CGAL.

\section Preliminaries_flags Compile-time Flags to Control Inlining

Making functions inlined can, at times, improve the efficiency of your code.
However this is not always the case and it can differ for a single function
depending on the application in which it is used. Thus \cgal defines a set
of compile-time macros that can be used to control whether certain functions
are designated as inlined functions or not.  The following table lists the
macros and their default values, which are set in one of the \cgal include
files.

| Macro Name                   | Default |
| :---------                   | :------ |
| `CGAL_KERNEL_INLINE`         | inline  |
| `CGAL_KERNEL_MEDIUM_INLINE`  |         |
| `CGAL_KERNEL_LARGE_INLINE`   |         |
| `CGAL_MEDIUM_INLINE`         | inline  |
| `CGAL_LARGE_INLINE`          |         |
| `CGAL_HUGE_INLINE`           |         |

If you wish to change the value of one or more of these macros,
you can simply give it a new value when compiling.  For example, to make
functions that use the macro `CGAL_KERNEL_MEDIUM_INLINE` inline functions,
you should set the value of this macro to `inline` instead of the
default blank.

Note that setting inline manually is very fragile, especially in a template
context.  It is usually better to let the compiler select by himself which
functions should be inlined or not.

\section seccgal_version Identifying the Version of CGAL

Every release of \cgal defines the following preprocessor macros:

<DL>
<DT>`CGAL_VERSION_STR`</DT>
<DD>a textual description of the current release (e.g., or 3.3 or 3.2.1 or 3.2.1-I-15) as a string literal</DD>
<DT>`CGAL_VERSION_NR`</DT>
<DD>a numerical description of the current release such that more recent
releases have higher number.

More precisely, it is defined as `1MMmmbiiii`, where `MM` is
the major release number (e.g. 03), `mm` is the minor release
number (e.g. 02), `b` is the bug-fix release number (e.g. 0),
and `iiii` is the internal release number (e.g. 0001). For
public releases, the latter is defined as 1000.  Examples: for the
public release 3.2.4 this number is 1030241000; for internal release
3.2-I-1, it is 1030200001.  Note that this scheme was modified around
3.2-I-30.
</DD>
<DT>`CGAL_VERSION_NUMBER(M,m,b)`</DT>
<DD>
a function macro computing the version number macro from the
M.m.b release version. Note that the internal release number is
dropped here. Example: `CGAL_VERSION_NUMBER(3,2,4)` is equal to
1030241000.
</DD>
</DL>

The macro `CGAL_VERSION` is deprecated. It is the same as
`CGAL_VERSION_STR`, but not as a string literal.

*/

---

### Documentation Doc Documentation Third Party (`Documentation/doc/Documentation/Third_party.txt`)

/*!

\page thirdparty Compilers and Third Party Dependencies
\cgalAutoToc

\section seccompilers Supported Compilers

In order to build a program using \cgal, you need a \cpp compiler
supporting C++17 or later.
\cgal \cgalReleaseNumber is supported (continuously tested) for the following compilers/operating systems:

| Operating System | Compiler |
| :----------      | :--------------- |
| Linux            | \gnu `g++` 13.3.0 or later\cgalFootnote{<A HREF="https://gcc.gnu.org/">\cgalFootnoteCode{https://gcc.gnu.org/}</A>} |
|                  | `Clang` \cgalFootnote{<A HREF="https://clang.llvm.org/">\cgalFootnoteCode{https://clang.llvm.org/}</A>} compiler version 22.0.0 or later |
| \ms Windows      | \gnu `g++` 13.3.0 or later\cgalFootnote{<A HREF="https://gcc.gnu.org/">\cgalFootnoteCode{https://gcc.gnu.org/}</A>} |
|                  | \ms Visual `C++` 15.9, 16.10, 17.14, 18.0 (\visualstudio 2017, 2019, 2022, and 2026) or later \cgalFootnote{<A HREF="https://visualstudio.microsoft.com/">\cgalFootnoteCode{https://visualstudio.microsoft.com/}</A>} |
| macOS            | \gnu `g++` 13.3.0 or later\cgalFootnote{<A HREF="https://gcc.gnu.org/">\cgalFootnoteCode{https://gcc.gnu.org/}</A>} |
|                  | Apple `Clang` compiler versions 14.0.0 or later |



Older versions of the above listed compilers might work, but no guarantee is provided.

\section seccmake CMake
<b>Version 3.22 or later</b>

In order to configure and build the \cgal examples, demos, or libraries,
you need <a href="https://cmake.org/">CMake</a>, a cross-platform "makefile generator".

This manual explains only the features of CMake which are needed in order to use \cgal.
Please refer to the <a href="https://cmake.org/documentation/">CMake documentation</a>
for further details.

\attention Recent versions of CMake are needed for the most recent versions of MS Visual C++.
Please refer to CMake's documentation for further information.

\section secessential3rdpartysoftware Essential Third Party Libraries

The focus of \cgal is on geometry, and we rely on other
highly specialized libraries and software for non-geometric issues,
for instance for numeric solvers or visualization. We first list software
that is essential to most of \cgal, and must therefore be found during the configuration of \cgal.
The page \ref configurationvariables lists CMake and environment variables which can be used to specify
the location of third-party software during configuration.

\subsection thirdpartystl Standard Template Library (STL)

\cgal heavily uses the \stl, and in particular adopted many of its design ideas. You can find online
documentation for the \stl at various web sites, for instance,
<A HREF="https://en.cppreference.com/w/">`https://en.cppreference.com `</A>,
or <A HREF="https://msdn.microsoft.com/en-us/library/1fe2x6kt(v=vs.140).aspx">`https://msdn.microsoft.com`</A>.

The \stl comes with the compiler, and as such no installation is required.

\subsection thirdpartyBoost Boost
<b>Version 1.74 or later</b>

The \boost libraries are a set of portable C++ source libraries.
Most of \boost libraries are header-only, but a few of them need to be compiled or
installed as binaries.

\cgal only requires the headers of the \boost libraries, but some demos and examples
depend on the binary library `Boost.Program_options`.

In case the \boost libraries are not installed on your system already, you
can obtain them from <A HREF="https://www.boost.org">`https://www.boost.org/`</A>.
For Visual C++ you can download precompiled libraries
from <A HREF="https://sourceforge.net/projects/boost/files/boost-binaries/">`https://sourceforge.net/projects/boost/files/boost-binaries/`</A>.

As there is no canonical directory for where to find \boost on Windows,
we recommend to use the config mode of CMake by defining the environment variable
`Boost_DIR` (case sensitive) to the path of the directory in your boost installation
containing the file `BoostConfig.cmake`, e.g.`C:/local/boost_1_80_0/lib64-msvc-14.3/cmake/Boost-1.80.0`.

\subsection thirdpartyMP Multi Precision Number Type Library

GNU Multiple Precision Arithmetic (GMP) and GNU Multiple Precision Floating-Point Reliably (MPFR) Libraries
are libraries for multi precision integers and rational numbers, and for multi precision floating point numbers.

These libraries can be obtained from <A HREF="https://gmplib.org/">`https://gmplib.org/`</A>
and <A HREF="https://www.mpfr.org/">`https://www.mpfr.org/`</A>.
Since Visual \cpp is not properly supported by the \gmp and \mpfr projects,
we provide precompiled versions of \gmp and \mpfr, which can be downloaded
from the <a href="https://github.com/CGAL/cgal/releases">assets of a release</a>.
Version supported are <b>GMP Version 5.0.1 or later, MPFR Version 3.0.0 or later</b>.

The \boost library also provides a module for multi precision integers and rational numbers:
<A HREF="https://www.boost.org/doc/libs/latest/libs/multiprecision/doc/html/index.html">\boost multiprecision</A>.

The components \cgal, and `CGAL_Qt6` require either \gmp and \mpfr, or \boost multiprecision
for multi precision numbers. `CGAL_Core` requires \boost multiprecision.

\cgal combines floating point arithmetic with exact arithmetic
in order to be efficient and reliable. \cgal has a built-in
number type for that, but previous alternatives are faster
solutions, and we recommend using one of them.

The CMake variable `CGAL_CMAKE_EXACT_NT_BACKEND` can be used to select
the library that will be used internally for multi precision number types.

\section secoptional3rdpartysoftware Optional Third Party Libraries

Optional 3rd party software can be used by \cgal for various reasons:
certain optional libraries might be required to build examples and
demos shipped with \cgal or to build your own project using \cgal;
another reason is to speed up basic tasks where specialized libraries can be faster than the default
version shipped with \cgal.
The page \ref configurationvariables lists CMake and environment variables which can be used to specify
the location of third-party software during configuration.

\subsection thirdpartyQt Qt6
<b>Version 6.4 or later</b>

Qt is a cross-platform application and UI framework.

The component `CGAL_Qt6` is essential to run the \cgal demos and basic viewers.
It requires \qt6 installed on your system.
In case \qt is not yet installed on your system, you can download
it from <A HREF="https://contribute.qt-project.org/">`https://contribute.qt-project.org/`</A>.

The exhaustive list of \qt6 components used in demos is:
`Core`, `Gui`, `Help`, `OpenGL`, `OpenGLWidgets`, `Qml`, `Svg`, `Widgets`,
`WebSockets`,  `Network`, and `qcollectiongenerator` (with `sqlite` driver plugin).

\subsection thirdpartyEigen Eigen
<b>Version 3.3.7 or later (including Eigen3 5.0.0)</b>

\eigen is a `C++` template library for linear algebra. \eigen supports all
matrix sizes, various matrix decomposition methods and sparse linear solvers.

In \cgal, \eigen is used in many packages such as \ref
PkgPoissonSurfaceReconstruction3 or \ref PkgJetFitting3, providing
sparse linear solvers and singular value decompositions.  A package
dependency over \eigen is marked on the <a
href="https://doc.cgal.org/latest/Manual/packages.html">Package
Overview</a> page. In order to use Eigen in \cgal programs, the
executables should be linked with the CMake imported target
`CGAL::Eigen3_support` provided in `CGAL_Eigen3_support.cmake`.

The \eigen web site is <A HREF="https://libeigen.gitlab.io/">`https://libeigen.gitlab.io/`</A>.

\subsection thirdpartyOpenGR OpenGR

\opengr is a set C++ libraries for 3D Global Registration released under the terms of the APACHE V2 license.

\cgal provides wrappers for the Super4PCS algorithm of \opengr in the \ref PkgPointSetProcessing3
packages. In order to use \opengr in \cgal programs, the executables should be linked with the CMake imported target `CGAL::OpenGR_support` provided in `CGAL_OpenGR_support.cmake`.

The \opengr web site is <A HREF="https://github.com/STORM-IRIT/OpenGR">`https://github.com/STORM-IRIT/OpenGR`</A>.

\subsection thirdpartylibpointmatcher PointMatcher

\libpointmatcher is a modular library implementing the Iterative Closest Point (ICP) algorithm for aligning point clouds, released under a permissive BSD license.

\cgal provides wrappers for the ICP algorithm of \libpointmatcher in the \ref PkgPointSetProcessing3
packages. In order to use \libpointmatcher in \cgal programs, the
executables should be linked with the CMake imported target
`CGAL::pointmatcher_support` provided in
`CGAL_pointmatcher_support.cmake`.

The \libpointmatcher web site is <A
HREF="https://github.com/ethz-asl/libpointmatcher">`https://github.com/ethz-asl/libpointmatcher`</A>.
\attention On Windows, \libpointmatcher needs to be compiled with the flag BOOST_TIMER_ENABLE_DEPRECATED set as it uses a deprecated module from \boost.
\attention On Windows, we support version 1.4.4 of \libpointmatcher with version 3.4.0 of Eigen.
Alternatively, version 1.3.1 of \libpointmatcher is supported with version 3.3.7 of Eigen, with some changes to the recipe at
`https://github.com/ethz-asl/libpointmatcher/blob/master/doc/Compilation.md`:`NABO_INCLUDE_DIR` becomes `libnabo_INCLUDE_DIRS`
and `NABO_LIBRARY` becomes `libnabo_LIBRARIES` in the "Build libpointmatcher" section.

\subsection thirdpartyMPFI Multiple Precision Floating-point Interval (MPFI)
<b>Version 1.4 or later</b>

\mpfi provides arbitrary precision interval arithmetic with intervals
represented using \mpfr reliable floating-point numbers.
It is based on the libraries \gmp and \mpfr.
In the setting of \cgal, this library is
optional: it is used by some models of the
\ref PkgAlgebraicKernelD "Algebraic Kernel".

\mpfi can be downloaded from <A HREF="https://gitlab.inria.fr/mpfi/mpfi">`https://gitlab.inria.fr/mpfi/mpfi`</A>.

\subsection thirdpartyESBTL ESBTL

The \esbtl (Easy Structural Biology Template Library) is a library that allows
the handling of \pdb data.

In \cgal, the \esbtl is used in an example of the \ref PkgSkinSurface3 package.

It can be downloaded from <A HREF="https://esbtl.sourceforge.net/">`https://esbtl.sourceforge.net/`</A>.

\subsection thirdpartyTBB Intel TBB

\tbb (Threading Building Blocks) is a library developed by Intel Corporation for writing software
programs that take advantage of multi-core processors.

In \cgal, \tbb is used by the packages that offer parallel
code. In order to use \tbb in \cgal programs, the executables
should be linked with the CMake imported target `CGAL::TBB_support`
provided in `CGAL_TBB_support.cmake`.

The \tbb web site is <A HREF="https://github.com/oneapi-src/oneTBB">`https://github.com/oneapi-src/oneTBB`</A>.

\subsection thirdpartyLASlib LASlib

\laslib is a `C++` library for handling LIDAR data sets stored in
the LAS format (or the compressed LAZ format).

In \cgal, \laslib is used to provide input and output functions in
the \ref PkgPointSetProcessing3 package. In order to use \laslib
in \cgal programs, the executables should be linked with the CMake
imported target `CGAL::LASLIB_support` provided in
`CGAL_LASLIB_support.cmake`.

\laslib information can be obtained from
<a href="https://lastools.github.io/">https://lastools.github.io/</a> and
<a href="https://rapidlasso.de/product-overview/">https://rapidlasso.de/product-overview/</a>.
\laslib is usually distributed along with LAStools. Current versions of \laslib provide CMake support.
BUILD_SHARED_LIBS needs to be set to true on windows to create a dynamic linked library.

\subsection thirdpartyOpenCV OpenCV

\opencv (Open Computer Vision) is a library designed for computer
vision, computer graphics and machine learning.

In \cgal, \opencv is used by the \ref PkgClassification
package. In order to use \opencv in \cgal programs, the
executables should be linked with the CMake imported target
`CGAL::OpenCV_support` provided in `CGAL_OpenCV_support.cmake`.

The \opencv web site is <A HREF="https://opencv.org/">`https://opencv.org/`</A>.

\subsection thirdpartySuiteSparse SuiteSparse
<b>Version 7.10.1 or later</b>

\suitesparse is a set of sparse-matrix-related packages written or co-authored by Tim Davis, available at <A HREF="https://github.com/DrTimothyAldenDavis/SuiteSparse">https://github.com/DrTimothyAldenDavis/SuiteSparse</A>.

\suitesparse is used by the Orbifold Tutte Embedding and ARAP parameterization, i.e., in the \ref PkgSurfaceMeshParameterization package.

\note SuiteSparse on Windows can easily be installed by \code
vcpkg install suitesparse
\endcode and it will be found automatically. When installed manually it is helpful to add the installation folder to the environment variable CMAKE_PREFIX_PATH for CMake to find the SuiteSparse libraries.

\subsection thirdpartyMETIS METIS
<b>Version 5.1 or later</b>

\metis is a library developed by the <A HREF="https://github.com/KarypisLab/">Karypis Lab</A>
and designed to partition graphs and produce fill-reducing matrix orderings.

\cgal offers wrappers around some of the methods of the \metis library
to allow the partitioning of graphs that are models of the concepts of the
<A HREF="https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/index.html">Boost Graph Library</A>,
and, by extension, of surface meshes (see Section \ref BGLPartitioning of the package \ref PkgBGL).

More information is available on the METIS library
at <A HREF="https://github.com/KarypisLab/METIS">`https://github.com/KarypisLab/METIS`</A>.

\subsection thirdpartyzlib zlib

\zlib is a data compression library, and is essential for the component libCGAL_ImageIO.

In \cgal, this library is used in the examples of the \ref PkgMesh3 package.

If it is not already on your system,
for instance, on Windows, you can download it from <A HREF="https://www.zlib.net/">`https://www.zlib.net/`</A>.

\subsection thirdpartyCeres Ceres Solver

\ceres is an open source C++ library for modeling and solving large, complicated optimization problems.

In \cgal, \ceres is used by the \ref PkgPMPRemeshing package for mesh smoothing, which
requires solving complex non-linear least squares problems.

Visit the official website of the library at <A HREF="http://ceres-solver.org/index.html">`ceres-solver.org`</A>
for more information.

\attention \ceres requires to be compiled with the exact same version of \eigen that is used for \cgal.

\attention \ceres indicates that `glog` is a recommended dependency. `glog` has `libunwind` as a recommended dependency.
On some platforms, linking with `libunwind` was responsible for an increase of the runtime of the final application.
If you experience such an issue, we recommend to compile \ceres without `glog` support.

\attention In the master branch of \ceres `glog` was dropped as a dependency and `abseil` was added instead. It is not compatible with \visualstudio 2017 or earlier versions.

\subsection thirdpartyGLPK GLPK

\glpk (GNU Linear Programming Kit) is a library for solving linear programming (LP), mixed integer programming (MIP), and other related problems.

In \cgal, \glpk provides an optional linear integer program solver in the \ref PkgPolygonalSurfaceReconstruction package.
In order to use \glpk in \cgal programs, the executables should be linked with the CMake imported target `CGAL::GLPK_support` provided in `CGAL_GLPK_support.cmake`.

The \glpk web site is <A HREF="https://www.gnu.org/software/glpk/">`https://www.gnu.org/software/glpk/`</A>.

\subsection thirdpartySCIP SCIP

\scip (Solving Constraint Integer Programs) is currently one of the fastest open source solvers for mixed integer programming (MIP) and mixed integer nonlinear programming (MINLP).

In \cgal, \scip provides an optional linear integer program solver in the \ref PkgPolygonalSurfaceReconstruction package.
In order to use \scip in \cgal programs, the executables should be linked with the CMake imported target `CGAL::SCIP_support` provided in `CGAL_SCIP_support.cmake`.

The \scip web site is <A HREF="https://www.scipopt.org/">`https://www.scipopt.org/`</A>.

\subsection thirdpartyOSQP OSQP

\osqp (Operator Splitting Quadratic Program) is currently one of the fastest open source solvers for convex Quadratic Programs (QP).

In \cgal, \osqp provides an optional solver for the quadratic programming used in the \ref PkgShapeRegularization package.
In order to use \osqp in \cgal programs, the executables should be linked with the CMake imported target `CGAL::OSQP_support` provided in `CGAL_OSQP_support.cmake`. \cgal is compatible with \osqp version 1.0.0.

The \osqp web site is <A HREF="https://osqp.org">`https://osqp.org`</A>.


\subsection thirdpartyVTK VTK

\vtk is the Visualization Toolkit.
In \cgal, this library is used in some examples of the \ref PkgMesh3 package.
The \vtk web site is <A HREF="https://vtk.org/">`https://vtk.org`</A>.

\subsection thirdpartyITK ITK

\itk is the Insight Toolkit.
In \cgal, this library is used in some examples of the \ref PkgMesh3 package.
The \itk web site is <A HREF="https://itk.org/">`https://itk.org`</A>.
*/

---

### Documentation Doc Documentation Usage (`Documentation/doc/Documentation/Usage.txt`)

/*!
\page usage Using %CGAL on Unix (Linux, macOS, ...)
\cgalAutoToc

Since \cgal version 5.0, \cgal is header-only by default, which means
that there is <b>no need to build \cgal before it can be used</b>.
However, some dependencies of \cgal might still need to be installed.

\section usage_introduction Quick Start: Compiling a Program using CGAL

Assuming that you have obtained \cgal through one of the package managers offering \cgal on your platform
(see Section \ref secgettingcgal), you can download \cgal examples (
<a href="https://github.com/CGAL/cgal/releases/download/v\cgalReleaseNumber/CGAL-\cgalReleaseNumber-examples.tar.xz">CGAL-\cgalReleaseNumber-examples.tar.xz</a>)
and the compilation of an example is as simple as:

    cd $HOME/CGAL-\cgalReleaseNumber/examples/Triangulation_2 # go to an example directory
    cmake -DCMAKE_BUILD_TYPE=Release . # configure the examples
    make # build the examples

Compiling your own program is similar:

    cd /path/to/your/program
    path/to/cgal/Scripts/scripts/cgal_create_CMakeLists -s your_program
    cmake -DCMAKE_BUILD_TYPE=Release .
    make

The script `cgal_create_CMakeLists` and its options are detailed in Section \ref devman_create_cgal_CMakeLists.

In a less ideal world, you might have to install some required tools and third-party libraries.
This is what this page is about.

\section secprerequisites Prerequisites

Using \cgal requires a few core components to be previously installed:
<ul>
<li> a supported compiler (see Section \ref seccompilers),</li>
<li> \ref seccmake,</li>
<li> \ref thirdpartyBoost,</li>
<li> a \ref thirdpartyMP.</li>
</ul>

Optional third-party software might be required to build examples and demos shipped with \cgal,
or to build your own project using \cgal, see Section \ref secoptional3rdpartysoftware.

\section secgettingcgal Downloading CGAL

\cgal can be obtained through different channels. We recommend using a package manager as
this will ensure that all essential third-party dependencies are present, and with the correct versions.
You may also download the sources of \cgal directly, but it is then your responsibility to independently
acquire these dependencies.

The examples and demos of \cgal are not included when you install \cgal with a package manager,
and must be downloaded
<a href="https://github.com/CGAL/cgal/releases/download/v\cgalReleaseNumber/CGAL-\cgalReleaseNumber-examples.tar.xz">here</a>.

\subsection secusingpkgman Using a Package Manager

On most operating systems, package managers offer \cgal and its essential third party dependencies.

On macOS, we recommend using of <a href="https://brew.sh/">Homebrew</a> in the following way:

    brew install cgal

On Linux distributions such as `Debian`/`Ubuntu`/`Mint`, use `apt-get` in the following way:

    sudo apt-get install libcgal-dev

For other distributions or package manager, please consult your respective documentation.

\subsection secusingwebsite Using CGAL Source Archive

You can also obtain the \cgal library sources directly from
<A HREF="https://www.cgal.org/download.html">https://www.cgal.org/download.html</A>.

Once you have downloaded the file `CGAL-\cgalReleaseNumber.tar.xz` containing the
\cgal sources, you have to unpack it. Under a Unix-like shell, use the
command:

    tar xf CGAL-\cgalReleaseNumber.tar.xz

The directory `CGAL-\cgalReleaseNumber` will be created. This directory
contains the following subdirectories:

| Directory                  | Contents   |
| :------------------------- | :----------|
| `auxiliary` (Windows only) | precompiled \gmp and \mpfr for Windows |
| `cmake/modules`            | modules for finding and using libraries |
| `demo`                     | demo programs (most of them need \qt, or other third-party products) |
| `doc_html`                 | documentation (HTML) |
| `examples`                 | example programs |
| `include`                  | header files |
| `scripts`                  | some useful scripts (e.g. for creating CMakeLists.txt files) |
| `src`                      | source files |

The directories `include/CGAL/CORE` and `src/CGALCore` contain a
distribution of the <a href="https://cs.nyu.edu/exact/">Core library</a> version 1.7 for
dealing with algebraic numbers. Note that \core is not part of \cgal and has its
own license.

The only documentation shipped within \cgal sources is the present manual.
The \cgal manual can also be accessed online at
<a href="https://doc.cgal.org/latest/Manual/index.html">`https://doc.cgal.org`</a>
or downloaded separately at
<a href="https://github.com/CGAL/cgal/releases">`https://github.com/CGAL/cgal/releases`</a>.

\section section_headeronly Header-only Usage

\cgal is a <a href="https://en.wikipedia.org/wiki/Header-only">header-only</a> library, and as such
there is no need to even configure it before using it. Programs using \cgal (examples, tests, demos, etc.)
are instead configured using CMake and \cgal will be configured at the same time.

There is one exception to the last paragraph: if you want to install \cgal header files to
a standard location (such as `/usr/local/include`):

    cmake .
    make install

For more advanced installations, we refer to Section \ref installation_configwithcmake.

Note that even though \cgal is a header-only library, not all its dependencies
are header-only. The libraries \gmp and \mpfr, for example, are not
header-only. As such, these dependencies must be built or installed independently.

\section usage_configuring Configuring your Program

Before building anything using \cgal you have to choose the compiler/linker, set compiler
and linker flags, specify which third-party libraries you want to use and where they can be found.
Gathering all this information is called <I>configuration</I>. The end of the process is marked
by the generation of a makefile or a Visual \cpp solution and project file that you can use
to build your program.

CMake maintains configuration parameters in so-called <I>Cmake variables</I>, like the `CMAKE_CXX_COMPILER`
in the example above. These variables <I>are not environment variables</I> but <I>CMake variables</I>.
Some of the CMake variables represent user choices, such as `CMAKE_BUILD_TYPE`,
whereas others indicate the details of a third-party library, such as `Boost_INCLUDE_DIR`
or the compiler flags to use, such as `CMAKE_CXX_FLAGS`.

The most important CMake variable is the variable `CGAL_DIR`, which will serve to configure \cgal
as you configure your program.

In a typical installation of dependencies, almost all CMake variables will be set automatically.
The variable `CGAL_DIR` is also generally found when \cgal has been obtained via a package manager.
In the rare event that it has not, the variable `CGAL_DIR` should be set manually to:

<ul>
<li>something like `/usr/local/opt/cgal/lib/cmake/CGAL`, for Brew.</li>
<li>something like `/usr/lib/x86_64-linux-gnu/cmake/CGAL`, for Linux distributions.</li>
</ul>

Note that you can also use `CMAKE_PREFIX_PATH` to point to a directory that contains all dependencies, like so:

    cmake -DCMAKE_PREFIX_PATH=/my/custom/brew/installation/dir -DCMAKE_BUILD_TYPE=Release .

If \cgal has been obtained via other means, `CGAL_DIR` must point to the root directory
of the \cgal source code (either the root of the unpacked release tarball or the root
of the Git working directory).

It is also strongly recommended to set the build type variable to `Release` for performance reasons
if no debugging is intended. Users should thus run:

    cd CGAL-\cgalReleaseNumber/examples/Triangulation_2
    cmake -DCGAL_DIR=$HOME/CGAL-\cgalReleaseNumber -DCMAKE_BUILD_TYPE=Release . # we are here using a release tarball

The package Qt6 on brew is "keg-only", which means it is not "linked" with brew.
In order to link against Qt6, you need to run:

    brew link qt@6

After that, you will have to specify the Qt6_DIR by hand to cmake, using something like

    -DQt6_DIR=/usr/local/opt/qt6/lib/cmake/Qt6

where `/usr/local/` is actually your current brew installation directory. Check this directory
to be sure where the Qt6 is placed on your machine.

\subsection usage_configuring_cmake_gui Specifying Missing Dependencies

The configuration process launched above might fail if CMake fails to find
all the required dependencies. This typically happens if you have installed dependencies
at non-standard locations.
Although the command line tool `cmake` accepts CMake variables as arguments of the form
`-D<VAR>:<TYPE>=<VALUE>`, this is only useful if you already know which variables
need to be explicitly defined. For this reason, the simplest way to manually set the missing variables
is to run the graphical user interface of CMake, `cmake-gui`.

    cd CGAL-\cgalReleaseNumber/examples/Triangulation_2
    cmake-gui .

After the `CMake` window opens, press 'Configure'. A dialog will pop up and you will have to choose
what shall be generated. After you have made your choice and pressed 'Finish', you will see
the output of configuration tests in the lower portion of the application.
Once these tests are done, you will see many red entries in the upper portion of the application.
Just ignore them, and press 'Configure' again. By now, CMake should have found most required
libraries and have initialized variables.
If red entries are still present, you must provide the necessary information (paths/values).
When all entries have been appropriately filled (and automatically filled values have been adjusted,
if desired) and lines are gray, you are now ready to press 'Generate',
and to exit `cmake-gui` afterwards.

\cgalAdvancedBegin
You may also decide to solve missing dependencies using the command line tool (which is not recommended).
If so, the page \ref configurationvariables lists variables which can be used to specify
the location of third-party software.
\cgalAdvancedEnd

If you do not need to debug, you should set the variable `CMAKE_BUILD_TYPE` to `Release`.

\subsection usage_configuring_external Configuring an External Program

Running `cmake` (or `cmake-gui`) requires a `CMakeLists.txt` file. This file is automatically provided
for all shipped examples and demos of \cgal. For other programs, CMake can also be used to configure
and build user programs, but one has to provide the corresponding `CMakeLists.txt`.
This script can be generated either manually, or with the help of a shell-script,
see Section \ref devman_create_cgal_CMakeLists. Using this shell-script,
the process of configuring a user's program called `your_program.cpp` amounts to:

    cd /path/to/your/program
    path/to/cgal/Scripts/scripts/cgal_create_CMakeLists -s your_program
    cmake -DCGAL_DIR=$HOME/CGAL-\cgalReleaseNumber -DCMAKE_BUILD_TYPE=Release .

Note that the script `cgal_create_CMakeLists` creates a very coarse `CMakeLists.txt` file which
might not properly encode the third party dependencies of your program. Users are advised to look
at the `CMakeLists.txt` files in the example folder(s) of the package that they are using to
learn how to specify their dependencies.

\subsection usage_configuring_advanced_cmake Advanced Configuration Options

CMake keeps the variables that a user can manipulate in a so-called CMake cache, a simple text file
named `CMakeCache.txt`, whose entries are of the form `VARIABLE:TYPE=VALUE`. Advanced users can manually
edit this file, instead of going through the interactive configuration session.

\section usage_building_program Building your Program

The results of a successful configuration are build files that control the build step.
The nature of the build files depends on the generator used during configuration, but in most cases
they contain several <I>targets</I>, such as all the examples of the Triangulation_2 package.

In a \unix-like environment the default generator produces makefiles.
You can use the `make` command-line tool for the succeeding build step as follows:

    cd CGAL-\cgalReleaseNumber/examples/Triangulation_2
    make # build all the examples of the Triangulation_2 package

\cgalAdvancedBegin
The build files produced by CMake are autoconfigured. That is, if you change any of the dependencies,
the build step automatically goes all the way back to the configuration step. This way, once the target
has been configured the very first time by invoking cmake, you don't necessarily need to invoke `cmake`
again. Rebuilding will call itself `cmake` and re-generate the build file whenever needed.
\cgalAdvancedEnd

*/

---

### Documentation Doc Documentation Deprecated (`Documentation/doc/Documentation/deprecated.txt`)

/*!

\page deprecated Deprecation Notice

In \cgal, we are trying as much as possible not to break the backward compatibility. If we have to do it, it will be announced in the <a href="https://www.cgal.org/releases.html">release notes</a>,
and a solution will always be provided. When possible, we keep the deprecated API for two releases before removing it.
If you reached this page after clicking on a link, it must probably mean that the documentation page you were trying to reach
is now deprecated. Have a look at the <a href="https://www.cgal.org/releases.html">release notes</a> for more information.


*/

---

### Documentation Doc Documentation Main (`Documentation/doc/Documentation/main.txt`)

/*!

\mainpage

The Computational Geometry Algorithms Library (\cgal) is a software project
that provides easy access to efficient and reliable geometric algorithms
in the form of a C++ library.

<h2>Package Overview</h2>

\cgal offers data structures and algorithms like \ref PartTriangulationsAndDelaunayTriangulations "triangulations",
\ref PartVoronoiDiagrams "Voronoi diagrams", \ref PartPolygons, \ref PartPolyhedra,
\ref PartArrangements "arrangements of curves", \ref PartMeshing "mesh generation",
\ref PartPolygonMeshProcessing "geometry processing (polygon meshes)", \ref PartPointSetProcessing "geometry processing (point sets)", \ref PartConvexHullAlgorithms "convex hull algorithms",
to name just a few.

All these data structures and algorithms operate on geometric objects
like points and segments, and perform geometric tests on them. These
objects and predicates are regrouped in \ref PartKernels "CGAL Kernels".

Finally, the \ref PartSupportLibrary "Support Library" offers geometric object generators and
spatial sorting functions, as well as a matrix search framework and a
solver for linear and quadratic programs. It further offers interfaces
to third party software such as the GUI libraries Qt, and
the Boost Graph Library.

The complete list of packages is available on the page \ref packages.

<h2>Getting Started</h2>

Head over to \ref general_intro to learn how to obtain, install, and use \cgal.

<h2>License</h2>

\cgal is distributed under a dual-license scheme. \cgal can be used
together with Open Source software free of charge. Using \cgal in
other contexts can be done by obtaining a commercial license from
[GeometryFactory](https://www.geometryfactory.com). For more details
see the \ref license "License" page.

<h2>Acknowledgment</h2>

We provide bibtex entries for each package so that you can cite \cgal correctly in your publications,
see the page \ref how_to_cite_cgal.

<h2>Manuals for the Previous Releases</h2>

For releases >= 4.2, visit [https://doc.cgal.org/X.Y](https://doc.cgal.org/4.2)

For releases X.Y, with 3.1 <= X.Y <= 4.1 visit
[https://doc.cgal.org/Manual/X.Y/doc_html/cgal_manual/packages.html](https://doc.cgal.org/Manual/3.1/doc_html/cgal_manual/packages.html)

<div style="display:none">

\subpage general_intro
\subpage tutorials
\subpage packages
\subpage dev_manual
\subpage license

</div>

*/

---

### Documentation Doc Documentation Manual (`Documentation/doc/Documentation/manual.txt`)

/*!

\page manual Organization of the Manual
\cgalAutoToc
\author %CGAL Editorial Board

\section secorganization Organization of the Manual

This manual is organized in several parts covering the many domains
of computational geometry.
Each part consists of several chapters,
and each chapter is split into a *User Manual*  and a *Reference
Manual*. The User Manual gives the general idea and comes with examples.
The Reference Manual presents the \api of the various classes
and functions.

The manual has a \ref packages  with a short paragraph explaining
what each package is about, what license
it has, and on which other packages it depends. It further provides
links to precompiled demo programs for the Windows platform.

The manual further has a class index, as well as a search box in the upper right of
each page.
The scope of the search box is the package you currently look at and the
packages it depends on, or  it is the whole manual when you are in
a top level page such as the package overview.

\section secorganizationref Organization of the Reference Manual

The \cgal library is a library of class templates. Consequently, we express
the requirements on template arguments by specifying \em concepts
and by providing \em models for concepts. See \ref intro_concept "here"
for an explanation of concept/model.

The reference manual has pages for concepts and for models,
and just as classes can be derived from other classes, concepts
can \em refine other concepts, by adding requirements.

When a class is a model of a concept, its reference manual
page has a link to the concept, and the API is mainly documented
on the reference manual page of the concept.  As a concept
may refine another concept, the full API of a class is sometimes
distributed over the pages of base classes and over the pages
of several concepts.

Let's have a look at the vertex type of 3D triangulations.

\cgalFigureBegin{Manual_Fig_concept_model,ConceptModel.svg}
Models and concepts.
\cgalFigureEnd

The class `CGAL::Triangulation_vertex_base_3` derives from
the class `CGAL::Triangulation_ds_vertex_base_3`.
The two classes are models of the concepts `TriangulationVertexBase_3`
and `TriangulationDSVertexBase_3`, respectively.
The former concept refines the latter.

In the reference manual pages of these concepts and models
only the methods and types which are not greyed in
\cgalFigureRef{Manual_Fig_concept_model} are documented.
Inherited methods are only documented in the base class.
And methods that must be implemented in order to be a
model of a concept are only documented in the concept.

As pointed out in Section \ref intro_concept "Concepts and Models"
the notion of a \em concept is about requirements,
and it can be a required global function or a required traits class.

\section markingSpecialFunctionality Marking of Special Functionality

In this manual, you will encounter sections marked as follows.

\subsection advanced_features Advanced Features

Some functionality is considered more advanced, for example because it is
relatively low-level, or requires special care to be properly used.

\cgalAdvancedBegin
Such functionality is identified this way in the manual.
\cgalAdvancedEnd

\subsection debugging_support Debugging Support Features

Usually related to advanced features that for example may not guarantee
class invariants, some functionality is provided that helps debugging,
for example by performing invariants checks on demand.

\cgalDebugBegin
Such functionality is identified this way in the manual.
\cgalDebugEnd

\subsection deprecated_code Deprecated Code

Sometimes, the \cgal project decides that a feature is <em>deprecated</em>. This means
that it still works in the current release, but it will be removed in the next,
or a subsequent release.  This can happen when we have found a better way to do
something, and we would like to reduce the maintenance cost of \cgal at some
point in the future.  There is a trade-off between maintaining backward
compatibility and implementing new features more easily.

In order to help users manage the changes to apply to their code, we attempt
to make \cgal code emit warnings when deprecated code is used.  This can be
done using some compiler specific features.  Those warnings can be disabled
by defining the macro `CGAL_NO_DEPRECATION_WARNINGS`.  On top of this, we
also provide a macro, `CGAL_NO_DEPRECATED_CODE`, which, when defined,
disables all deprecated features.  This allows users to easily test if their
code relies on deprecated features.

\deprecated Such functionality is identified this way in the manual.

*/

---

### Documentation Doc Documentation Packages (`Documentation/doc/Documentation/packages.txt`)

/*!

\page packages Package Overview

\cgalPackageSection{PartAlgebraicFoundations,Arithmetic and Algebra}

\package_listing{Algebraic_foundations}
\package_listing{Number_types}
\package_listing{Modular_arithmetic}
\package_listing{Polynomial}
\package_listing{Algebraic_kernel_d}

\cgalPackageSection{PartCombinatorialAlgorithms,Combinatorial Algorithms}

\package_listing{Matrix_search}
\package_listing{QP_solver}

\cgalPackageSection{PartKernels,Geometry Kernels}

\package_listing{Kernel_23}
\package_listing{Kernel_d}
\package_listing{Circular_kernel_2}
\package_listing{Circular_kernel_3}

\cgalPackageSection{PartConvexHullAlgorithms,Convex Hull Algorithms}

\package_listing{Convex_hull_2}
\package_listing{Convex_hull_3}
\package_listing{Convex_hull_d}

\cgalPackageSection{PartPolygons,Polygons}

\package_listing{Polygon}
\package_listing{Polygon_repair}
\package_listing{Boolean_set_operations_2}
\package_listing{Nef_2}
\package_listing{Nef_S2}
\package_listing{Partition_2}
\package_listing{Straight_skeleton_2}
\package_listing{Minkowski_sum_2}
\package_listing{Polyline_simplification_2}
\package_listing{Frechet_distance}
\package_listing{Visibility_2}
\package_listing{Set_movable_separability_2}


\cgalPackageSection{PartPolyhedra,Cell Complexes and Polyhedra}

\package_listing{Polyhedron}
\package_listing{HalfedgeDS}
\package_listing{Surface_mesh}
\package_listing{Combinatorial_map}
\package_listing{Generalized_map}
\package_listing{Linear_cell_complex}
\package_listing{Nef_3}
\package_listing{Convex_decomposition_3}
\package_listing{Minkowski_sum_3}


\cgalPackageSection{PartArrangements,Arrangements}

\package_listing{Arrangement_on_surface_2}
\package_listing{Surface_sweep_2}
\package_listing{Snap_rounding_2}
\package_listing{Envelope_2}
\package_listing{Envelope_3}

\cgalPackageSection{PartTriangulationsAndDelaunayTriangulations,Triangulations and Delaunay Triangulations}

\package_listing{Triangulation_2}
\package_listing{TDS_2}
\package_listing{Triangulation_on_sphere_2}
\package_listing{Periodic_2_triangulation_2}
\package_listing{Hyperbolic_triangulation_2}
\package_listing{Triangulation_on_hyperbolic_surface_2}
\package_listing{Periodic_4_hyperbolic_triangulation_2}
\package_listing{Triangulation_3}
\package_listing{TDS_3}
\package_listing{Constrained_triangulation_3}
\package_listing{Periodic_3_triangulation_3}
\package_listing{Triangulation}
\package_listing{Alpha_shapes_2}
\package_listing{Alpha_shapes_3}

\cgalPackageSection{PartVoronoiDiagrams,Voronoi Diagrams}

\package_listing{Segment_Delaunay_graph_2}
\package_listing{Segment_Delaunay_graph_Linf_2}
\package_listing{Apollonius_graph_2}
\package_listing{Voronoi_diagram_2}

\cgalPackageSection{PartMeshing,Mesh Generation}

\package_listing{Mesh_2}
\package_listing{Alpha_wrap_2}
\package_listing{Surface_mesher}
\package_listing{Skin_surface_3}
\package_listing{SMDS_3}
\package_listing{Mesh_3}
\package_listing{Isosurfacing_3}
\package_listing{Tetrahedral_remeshing}
\package_listing{Periodic_3_mesh_3}
\package_listing{Alpha_wrap_3}
\package_listing{Mesh_smoothing_3}

\cgalPackageSection{PartReconstruction,Shape Reconstruction}

\package_listing{Poisson_surface_reconstruction_3}
\package_listing{Scale_space_reconstruction_3}
\package_listing{Advancing_front_surface_reconstruction}
\package_listing{Polygonal_surface_reconstruction}
\package_listing{Kinetic_space_partition}
\package_listing{Kinetic_surface_reconstruction}
\package_listing{Optimal_transportation_reconstruction_2}

\cgalPackageSection{PartPolygonMeshProcessing,Polygon Mesh Processing}

\package_listing{Polygon_mesh_processing}
\package_listing{PMP_Boolean_operations}
\package_listing{PMP_Remeshing}
\package_listing{PMP_Mesh_repair}
\package_listing{Subdivision_method_3}
\package_listing{Surface_mesh_segmentation}
\package_listing{Surface_mesh_simplification}
\package_listing{Surface_mesh_deformation}
\package_listing{Surface_mesh_parameterization}
\package_listing{Surface_mesh_shortest_path}
\package_listing{Surface_mesh_skeletonization}
\package_listing{Surface_mesh_approximation}
\package_listing{Heat_method_3}
\package_listing{Surface_mesh_topology}

\cgalPackageSection{PartPointSetProcessing,Point Set Processing}

\package_listing{Ridges_3}
\package_listing{Jet_fitting_3}
\package_listing{Point_set_3}
\package_listing{Point_set_processing_3}
\package_listing{Shape_detection}
\package_listing{Shape_regularization}
\package_listing{Stream_lines_2}
\package_listing{Classification}

\cgalPackageSection{PartSearchStructures,Spatial Searching and Sorting}

\package_listing{Point_set_2}
\package_listing{Interval_skip_list}
\package_listing{Spatial_searching}
\package_listing{SearchStructures}
\package_listing{Box_intersection_d}
\package_listing{AABB_tree}
\package_listing{Orthtree}
\package_listing{Spatial_sorting}

\cgalPackageSection{PartGeometricOptimization,Geometric Optimization}

\package_listing{Bounding_volumes}
\package_listing{Inscribed_areas}
\package_listing{Polytope_distance_d}
\package_listing{Principal_component_analysis}
\package_listing{Optimal_bounding_box}

\cgalPackageSection{PartInterpolation,Interpolation}

\package_listing{Interpolation}
\package_listing{Barycentric_coordinates_2}
\package_listing{Barycentric_coordinates_3}

\cgalPackageSection{PartSupportLibrary,Support Library}

\package_listing{STL_Extension}
\package_listing{BGL}
\package_listing{Solver_interface}
\package_listing{Property_map}
\package_listing{Weights}
\package_listing{Cone_spanners_2}
\package_listing{Circulator}
\package_listing{Generator}
\package_listing{Miscellany}
\package_listing{Stream_support}

\cgalPackageSection{PartVisualization,Visualization}

\package_listing{GraphicsView}
\package_listing{CGAL_ipelets}
\package_listing{Basic_viewer}

*/

---

--- METRICS ---
- Files Extracted: 99
- Estimated Token Budget: ~300825 tokens
- Canonical Reference: https://codewiki.google/github.com/CGAL/cgal
