cmake_minimum_required(VERSION 3.15)
project(seamsh VERSION 0.1 LANGUAGES C CXX)

# --- hxt2d: robust 2D Delaunay, downloaded and built as an external project ---
# Consumed as a source dependency: its static libraries are linked (PIC) into
# libseamsh, so the wheel stays self-contained with no extra runtime .so.
include(FetchContent)

set(HXT2D_GIT_REPOSITORY "https://git.immc.ucl.ac.be/hextreme/hxt-delaunay.git"
    CACHE STRING "hxt2d git repository (use a local path for offline builds)")
set(HXT2D_GIT_TAG "api"
    CACHE STRING "hxt2d git tag, branch or commit to build")

# We only want the library, not its tests or CLI (both already default OFF when
# hxt2d is not the top-level project; set here to be explicit and robust).
set(HXT2D_BUILD_TESTS       OFF CACHE BOOL "" FORCE)
set(HXT2D_TRIMESH_BUILD_CLI OFF CACHE BOOL "" FORCE)

# Portability first: no OpenMP (removes the libgomp runtime dependency and forces
# hxt2d's single-thread path, which is fast enough for the size-field Delaunay).
set(HXT2D_ENABLE_OPENMP OFF CACHE BOOL "" FORCE)

FetchContent_Declare(hxt2d
    GIT_REPOSITORY "${HXT2D_GIT_REPOSITORY}"
    GIT_TAG        "${HXT2D_GIT_TAG}"
    GIT_SHALLOW    TRUE)

# EXCLUDE_FROM_ALL: build hxt2d only because libseamsh links it, and drop its
# own install() rules so its archives/cmake config do not end up in the wheel.
FetchContent_GetProperties(hxt2d)
if(NOT hxt2d_POPULATED)
    FetchContent_Populate(hxt2d)
    add_subdirectory("${hxt2d_SOURCE_DIR}" "${hxt2d_BINARY_DIR}" EXCLUDE_FROM_ALL)
endif()

# hxt2d builds hxt2d_triMesh with -march=native, which bakes in the build host's
# instruction set and would SIGILL on older CPUs running the wheel. Strip it for
# a portable binary; HXT2D_MARCH lets you opt back into a safe baseline such as
# "x86-64-v2" to recover the Morton-code speed without losing portability.
set(HXT2D_MARCH "" CACHE STRING "Optional -march= value for hxt2d (empty: none)")
get_target_property(_hxt2d_opts hxt2d_triMesh COMPILE_OPTIONS)
if(_hxt2d_opts)
    list(REMOVE_ITEM _hxt2d_opts "-march=native")
    set_target_properties(hxt2d_triMesh PROPERTIES COMPILE_OPTIONS "${_hxt2d_opts}")
endif()
if(HXT2D_MARCH)
    target_compile_options(hxt2d_triMesh PRIVATE "-march=${HXT2D_MARCH}")
endif()

add_library(seamsh SHARED
    seamshlib/seamsh.cpp
    seamshlib/topology.cpp
    seamshlib/sizefield.cpp
)

target_link_libraries(seamsh PRIVATE hxt2d_triMesh)

install(TARGETS seamsh DESTINATION seamsh)
