cmake_minimum_required(VERSION 3.16)
project(rhino3dm)

set (CMAKE_CXX_STANDARD 17)

if (EMSCRIPTEN)
  set(RHINO3DM_JS "YES")
else()
  set(RHINO3DM_PY "YES")
endif()

if (${RHINO3DM_JS})
  message("Web Assembly Compile")
endif()

if (${RHINO3DM_PY})
  message("Python Compile")
  # Python is nanobind (M2, docs/vnext/nanobind-port.md)
  if (CMAKE_VERSION VERSION_LESS 3.18)
    set(DEV_MODULE Development)
  else()
    set(DEV_MODULE Development.Module)
  endif()
  # Development.SABIModule (CMake 3.26+): what nanobind's STABLE_ABI needs to build an abi3 module
  # on Python 3.12+; OPTIONAL, so 3.10 / 3.11 (no abi3 for them) still configure
  if (NOT CMAKE_VERSION VERSION_LESS 3.26)
    set(SABI_MODULE OPTIONAL_COMPONENTS Development.SABIModule)
  endif()
  find_package(Python 3.10 COMPONENTS Interpreter ${DEV_MODULE} ${SABI_MODULE} REQUIRED)

  if (NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
    set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build." FORCE)
    set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo")
  endif()
  
  add_subdirectory(lib/nanobind)
endif()

if (NODE)
  message("NODE=${NODE}")
  message("NODE evaluates to True")
endif()

if (MODULE)
  message("MODULE=${MODULE}")
  message("MODULE evaluates to True")
endif()

# Draco: only the mesh / point-cloud encode-decode subset (bnd_draco.cpp and RhinoCommon's c/draco.cpp
# use nothing else), listed by tools/dev/draco_subset.py; lib/draco_config supplies draco_features.h
# (Draco's own CMake would generate it). The src/lib/draco submodule stays as the source.
include("${CMAKE_CURRENT_SOURCE_DIR}/draco_sources.cmake")
include_directories(${draco_subset_INCLUDE})
add_library(draco_subset STATIC ${draco_subset_SRC})
set_target_properties(draco_subset PROPERTIES POSITION_INDEPENDENT_CODE ON
  CXX_VISIBILITY_PRESET hidden VISIBILITY_INLINES_HIDDEN ON)

# the bindings (M3 layout): per class, bnd_<class>_gen.* (tools/generate/bnd_gen.py) beside the
# hand-maintained bnd_<class>.*, plus the core (bindings.*, bnd_common.*, ...)
file(GLOB bindings_SRC "bindings/*.h" "bindings/*.cpp")
file(GLOB zlib_SRC "lib/opennurbs/zlib/*.h" "lib/opennurbs/zlib/*.c")

# temporarily rename the 3 cpp files that we don't want to compile on OSX
file(RENAME "lib/opennurbs/opennurbs_gl.cpp" "lib/opennurbs/opennurbs_gl.skip")
file(RENAME "lib/opennurbs/opennurbs_unicode_cp932.cpp" "lib/opennurbs/opennurbs_unicode_cp932.skip")
file(RENAME "lib/opennurbs/opennurbs_unicode_cp949.cpp" "lib/opennurbs/opennurbs_unicode_cp949.skip")
file(GLOB opennurbs_SRC "lib/opennurbs/*.h" "lib/opennurbs/*.cpp")
file(RENAME "lib/opennurbs/opennurbs_gl.skip" "lib/opennurbs/opennurbs_gl.cpp")
file(RENAME "lib/opennurbs/opennurbs_unicode_cp932.skip" "lib/opennurbs/opennurbs_unicode_cp932.cpp")
file(RENAME "lib/opennurbs/opennurbs_unicode_cp949.skip" "lib/opennurbs/opennurbs_unicode_cp949.cpp")

file(RENAME "lib/opennurbs/android_uuid/gen_uuid_nt.c" "lib/opennurbs/android_uuid/gen_uuid_nt.skip")
file(GLOB uuid_SRC "lib/opennurbs/android_uuid/*.h" "lib/opennurbs/android_uuid/*.c")
file(RENAME "lib/opennurbs/android_uuid/gen_uuid_nt.skip" "lib/opennurbs/android_uuid/gen_uuid_nt.c")

if(${RHINO3DM_JS})
  # we will eventually want the following warning flags on both compiles
  # for now, just WASM
  set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wno-overloaded-virtual -Wno-switch -Wno-unknown-pragmas -Wno-unused-private-field")
  if(CMAKE_BUILD_TYPE STREQUAL "Debug")
    message("debug mode")
    set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g")
  else()
    set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Oz")
    # -Oz is for opennurbs and the bindings (download size). The compression code is small and
    # its loops are where the time goes: the C sources (zlib, uuid) had no -O flag at all, and
    # Draco, built as its own Release project until 9.x, had -O3. The last -O on the line wins.
    set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O3")
    target_compile_options(draco_subset PRIVATE -O3)
    # every string the bindings return goes through these two UTF conversions, one unit at a time
    set_source_files_properties("${CMAKE_CURRENT_SOURCE_DIR}/lib/opennurbs/opennurbs_unicode.cpp"
      "${CMAKE_CURRENT_SOURCE_DIR}/librhino3dm_native/stringholder.cpp" PROPERTIES COMPILE_OPTIONS "-O3")
  endif()
  # WASM64 (wasm memory64) is its own build dimension, independent of NODE.
  # It produces a 64-bit-memory binary that breaks the 4GB limit. Support
  # (MDN browser-compat-data, checked 2026-10-07): Chrome 133, Firefox 134,
  # Node 24; Safari still Technology Preview only.
  #
  # wasm32 is the DEFAULT again since 9.2, as in 8.x (script/setup.py passes
  # -D WASM64=TRUE only with --wasm64): it runs in every browser and on Node 22,
  # and it is faster than memory64. The release ships memory64 in the package's
  # wasm64/ folder. opennurbs supports wasm32 since RH-100167 (RH3DM-215).
  if(WASM64)
    message("WASM64 (memory64) build")
    # -sMEMORY64 is a codegen/target flag (wasm32 -> wasm64): it must be applied
    # at compile time to C sources (zlib, uuid) as well as C++, and to the draco
    # sub-build (see script/setup.py), or the objects link as mixed
    # wasm32/wasm64 and fail. (It also reaches the link line via CXX flags.)
    set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -sMEMORY64=1")
    set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -sMEMORY64=1")
    # -sMEMORY64 only lifts the address width; the heap cap still defaults to
    # 2GB when ALLOW_MEMORY_GROWTH is on and MAXIMUM_MEMORY is unset. Without
    # this the wasm64 binary is still capped at 2GB (memory.grow fails past it,
    # malloc returns null), defeating the point of the build. Raise it past 4GB
    # (link-only flag; only valid with MEMORY64, hence gated here).
    set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -sMAXIMUM_MEMORY=16GB")
  endif()
  # The remaining -s settings and -lembind are link-only; keep them out of the
  # compile flags so every object doesn't emit a "linker setting ignored during
  # compilation" / "linker input unused" warning.
  set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -sMODULARIZE=1 -sEXPORT_NAME=rhino3dm -sALLOW_MEMORY_GROWTH=1 -lembind")
  # C++ exceptions as JS errors (Luis, 2026-10-17): without exception support a C++ throw -- every
  # RhinoCommon guard (an index out of range), a dispatcher's "no overload matches" -- ABORTED the
  # whole module. WebAssembly exception handling (Chrome 95, Firefox 100, Safari 15.2, Node 17)
  # raises a catchable error instead; the helpers let JS read its message (getExceptionMessage).
  set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fwasm-exceptions")
  set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fwasm-exceptions")
  set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fwasm-exceptions -sEXPORTED_RUNTIME_METHODS=getExceptionMessage,incrementExceptionRefcount,decrementExceptionRefcount")
  if(MODULE)
    # the ES module is the browser build (package.json "browser"/"import" exports; Node gets
    # rhino3dm.js): without Node support it has no `node:` or `ws` imports, which bundlers
    # (webpack 5) cannot resolve for the web. Its .wasm is byte-identical to rhino3dm.js's.
    set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -sEXPORT_ES6=1 -sENVIRONMENT=web,worker")
  endif()
endif()

if (${RHINO3DM_PY})
  # Set default symbol visibility to hidden to prevent conflicts with other libraries
  if(NOT MSVC)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden")
    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fvisibility=hidden")
  endif()
endif()

if(MSVC)
  # Faster MSVC builds: parallelize the solution over projects (/MP), and each
  # project over files via the multi-tool task scheduler; use incremental linking.
  add_compile_options("/MP")
  set (CMAKE_VS_GLOBALS "${CMAKE_VS_GLOBALS};UseMultiToolTask=true;EnforceProcessCountAcrossBuilds=true")
  add_compile_options("/openmp")     # OpenNURBS can use OpenMP; no need to force the single-threaded variant
  add_link_options("/INCREMENTAL")
endif()

add_definitions(-D_GNU_SOURCE)
add_definitions(-DON_COMPILING_OPENNURBS)
# NOTE: OPENNURBS_FREETYPE_INC_ is opennurbs_freetype.h's OWN include guard.
# Pre-defining it makes that header a no-op, hiding every ON_FreeType*
# declaration. opennurbs 9.x defines OPENNURBS_FREETYPE_SUPPORT whenever
# ON_RUNTIME_LINUX is set, so on Linux the .cpp files call functions this
# would hide. Skip it there; same fix as src/librhino3dm_native/CMakeLists.txt.
# (EMSCRIPTEN is unaffected either way: it gets ON_RUNTIME_WASM, no freetype.)
if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux")
  add_definitions(-DOPENNURBS_FREETYPE_INC_)
endif()
add_definitions(-DMY_ZCALLOC -DZ_PREFIX)
add_definitions(-DOPENNURBS_ZLIB_LIB_DIR)
# RH3DM-179: we link zlib via CMake, not the MSVC #pragma comment(lib,...) path, so tell
# opennurbs to skip that pragma block (otherwise OPENNURBS_ZLIB_LIB_DIR being valueless
# yields a malformed string -> MSVC C4081). The native librhino3dm_native build already
# defines this; mirror it here for the JS/Python build.
add_definitions(-DON_CMAKE_BUILD)
# No fused multiply-add contraction: the bindings must reproduce RhinoCommon's (.NET) results
# bit for bit (tests/parity), and a contracted a*b+c rounds once instead of twice. GCC on aarch64
# and Apple clang contract by default; MSVC does not unless /fp:contract
if(NOT MSVC)
  add_compile_options(-ffp-contract=off)
endif()
add_definitions(-DUNICODE)
add_definitions(-DON_INCLUDE_DRACO)
# The generated bindings call the flat C layer (RhinoCommon's c/), so those C
# translation units compile INTO the module. RHINO3DM_BUILD is per-source: the
# C layer needs it, nothing else does.
# The C-layer files the generated code needs are listed by the generator
# (bindings/clayer_sources_gen.cmake): the files DEFINING every flat C function
# it calls, plus the transitive closure of free-function helpers those call
# (struct converters etc.). Only CLASS-based helpers, which a source scan
# cannot follow, are listed here.
include("${CMAKE_CURRENT_SOURCE_DIR}/bindings/clayer_sources_gen.cmake")
set(pilot_clayer_SRC ${generated_clayer_SRC}
  "${CMAKE_CURRENT_SOURCE_DIR}/librhino3dm_native/stringholder.cpp"
  "${CMAKE_CURRENT_SOURCE_DIR}/librhino3dm_native/on_progress_reporter.cpp")
list(REMOVE_DUPLICATES pilot_clayer_SRC)
# base64.cpp: the C layer's copy (reached through draco.cpp, G107) and the hand bindings' copy
# (bindings/base64.cpp) define the same functions -- the module links the hand bindings' one
list(REMOVE_ITEM pilot_clayer_SRC "${CMAKE_CURRENT_SOURCE_DIR}/librhino3dm_native/base64.cpp")
# RhinoCommon's c/draco.cpp (synced verbatim but for include paths) defines classes named BND_Draco and
# BND_DracoCompressionOptions; the second is also the generated binding of RhinoCommon's
# DracoCompressionOptions. Compile the C layer's under other names (its exports are extern "C"; callers
# hold opaque pointers) -- the generator reads the C signatures with the same names
# (tools/generate/gen_registry.py C_CLASS_RENAMES).
set_property(SOURCE "${CMAKE_CURRENT_SOURCE_DIR}/librhino3dm_native/draco.cpp" APPEND PROPERTY COMPILE_DEFINITIONS
  BND_Draco=RH3DM_CL_Draco BND_DracoCompressionOptions=RH3DM_CL_DracoCompressionOptions)

if(${RHINO3DM_JS})
  # opennurbs (>= 8.32) is emscripten-aware: it auto-defines ON_RUNTIME_WASM,
  # ON_LITTLE_ENDIAN, and selects ON_64BIT_RUNTIME / ON_32BIT_RUNTIME from the
  # actual wasm pointer size. So a WASM64 build only needs -sMEMORY64=1 (set
  # above) and opennurbs derives the 64-bit runtime itself. No manual defines.

  set(CMAKE_EXECUTABLE_SUFFIX ".js")

  set_property(SOURCE ${pilot_clayer_SRC} APPEND PROPERTY COMPILE_DEFINITIONS RHINO3DM_BUILD)

  add_executable(rhino3dm ${bindings_SRC} ${zlib_SRC} ${opennurbs_SRC} ${uuid_SRC} ${pilot_clayer_SRC})
  # what embind cannot express (G101: views hold their parent, static properties, for...of)
  target_link_options(rhino3dm PRIVATE "--pre-js=${CMAKE_CURRENT_SOURCE_DIR}/bindings/bnd_pre_gen.js"
                                       "--post-js=${CMAKE_CURRENT_SOURCE_DIR}/bindings/bnd_post_gen.js")
  set_property(TARGET rhino3dm APPEND PROPERTY LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/bindings/bnd_pre_gen.js")
  set_property(TARGET rhino3dm APPEND PROPERTY LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/bindings/bnd_post_gen.js")
  target_link_libraries(rhino3dm draco_subset)
endif()

if (${RHINO3DM_PY})
  if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
    add_definitions(-DON_RUNTIME_LINUX)
    add_definitions(-DON_CLANG_CONSTRUCTOR_BUG)
    set_property(SOURCE ${pilot_clayer_SRC} APPEND PROPERTY COMPILE_DEFINITIONS RHINO3DM_BUILD)
    # M2 (Luis 2026-11-03): one abi3 wheel for Python 3.12+ (nanobind applies STABLE_ABI only from
    # 3.12). No FREE_THREADED (Luis 2026-11-10): opennurbs is not safe for parallel use (const SubD
    # members write scratch ids), so on a free-threaded interpreter the import turns the GIL back on
    nanobind_add_module(_rhino3dm NB_STATIC STABLE_ABI ${bindings_SRC} ${opennurbs_SRC} ${zlib_SRC} ${uuid_SRC} ${pilot_clayer_SRC})
    # (nanobind_add_module links its own library: nanobind-static, or its abi3 variant)
    # Hide all symbols by default to prevent conflicts with other libraries (e.g., OpenVDB's zlib)
    set_target_properties(_rhino3dm PROPERTIES
      CXX_VISIBILITY_PRESET hidden
      C_VISIBILITY_PRESET hidden
      VISIBILITY_INLINES_HIDDEN ON
    )
    # opennurbs 9.x defines OPENNURBS_FREETYPE_SUPPORT whenever ON_RUNTIME_LINUX is
    # set (opennurbs_system.h); in 8.x that was Android only. The vendored FreeType
    # is therefore required to build opennurbs on Linux. Mirrors opennurbs' own
    # CMakeLists (freetype263 + include dir + link; it already sets
    # POSITION_INDEPENDENT_CODE so the static lib links into this shared module).
    # CMAKE_DL_LIBS is for dladdr(), used by Internal_GetLinuxInstalledFonts.
    add_subdirectory(lib/opennurbs/freetype263 freetype263)
    target_include_directories(_rhino3dm PRIVATE lib/opennurbs/freetype263/include)
    target_link_libraries(_rhino3dm PRIVATE opennurbs_public_freetype ${CMAKE_DL_LIBS})
  else()
    add_library(zlib_static STATIC ${zlib_SRC})
    set_target_properties(zlib_static PROPERTIES 
      CXX_VISIBILITY_PRESET hidden
      C_VISIBILITY_PRESET hidden
      VISIBILITY_INLINES_HIDDEN ON
    )
    add_library(opennurbs_static STATIC ${opennurbs_SRC})
    set_target_properties(opennurbs_static PROPERTIES
      CXX_VISIBILITY_PRESET hidden
      C_VISIBILITY_PRESET hidden
      VISIBILITY_INLINES_HIDDEN ON
    )
    # the C layer the generated bindings call (M3: these targets had built only the old bindings;
    # not yet built on macOS / Windows -- M4)
    set_property(SOURCE ${pilot_clayer_SRC} APPEND PROPERTY COMPILE_DEFINITIONS RHINO3DM_BUILD)
    # M2 (Luis 2026-11-03): one abi3 wheel for Python 3.12+ (nanobind applies STABLE_ABI only from
    # 3.12). No FREE_THREADED (Luis 2026-11-10): opennurbs is not safe for parallel use (const SubD
    # members write scratch ids), so on a free-threaded interpreter the import turns the GIL back on
    nanobind_add_module(_rhino3dm NB_STATIC STABLE_ABI ${bindings_SRC} ${pilot_clayer_SRC})
    # (nanobind_add_module links its own library: nanobind-static, or its abi3 variant)
    
    target_link_libraries(_rhino3dm PRIVATE zlib_static)
    target_link_libraries(_rhino3dm PRIVATE opennurbs_static)
    # Hide all symbols by default to prevent conflicts with other libraries
    set_target_properties(_rhino3dm PROPERTIES
      CXX_VISIBILITY_PRESET hidden
      C_VISIBILITY_PRESET hidden
      VISIBILITY_INLINES_HIDDEN ON
    )
  endif()

  target_link_libraries(_rhino3dm PRIVATE draco_subset)
endif()

if (MSVC)
  # Build the rhino3dm code with warnings on. TODO: raise to /W4 (and eventually
  # /WX) once OpenNURBS builds clean at that level.
  if (TARGET _rhino3dm)
    target_compile_options(_rhino3dm PRIVATE "/W3")
  endif()
  if (TARGET opennurbs_static)
    target_compile_options(opennurbs_static PRIVATE "/W3")
  endif()
endif()
