# OBOE web build (Emscripten). From the repo root:
#   source ~/.emsdk/emsdk_env.sh
#   emcmake cmake -S build-web -B build-web/build -DCMAKE_BUILD_TYPE=Release
#   cmake --build build-web/build -j8
cmake_minimum_required(VERSION 3.22)
project(oboe-web CXX)

set(OBOE   ${CMAKE_CURRENT_SOURCE_DIR}/../oboe)
set(PREFIX ${CMAKE_CURRENT_SOURCE_DIR}/prefix)
set(GEN    ${CMAKE_CURRENT_BINARY_DIR}/gen)
# Toggle to isolate asyncify-related crashes: -DOBOE_ASYNCIFY=0
set(OBOE_ASYNCIFY 1 CACHE STRING "1 = enable -sASYNCIFY (default), 0 = disable")
set(OBOE_ASYNCIFY_IGNORE_INDIRECT 0 CACHE STRING "0 = instrument indirect calls (REQUIRED: OBOE reaches emscripten_sleep via call_indirect + EH invoke_* thunks; 1 aborts at runtime with asyncify 'invalid state'); 1 = -sASYNCIFY_IGNORE_INDIRECT (smaller/faster wasm, debugging only)")
set(OBOE_ASYNCIFY_DEBUG 0 CACHE STRING "ASYNCIFY_DEBUG level (0 off, 1, 2 verbose)")
set(OBOE_STACK_CHECK 0 CACHE STRING "STACK_OVERFLOW_CHECK level (0 off, 1, 2 full)")
set(OBOE_ASAN 0 CACHE STRING "1 = build with -fsanitize=address (memory-corruption diagnosis)")

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)   # strict -std=c++14, as in SConstruct

# --- include dirs (mirrors SConstruct CPPPATH: all src subdirs + deps) -------
file(GLOB_RECURSE SRC_DIRS LIST_DIRECTORIES true ${OBOE}/src/*)
set(INC_DIRS
  ${GEN}
  ${OBOE}/src
  ${OBOE}/src/fileio/gzstream
  ${OBOE}/src/fileio/xml-parser
  ${OBOE}/deps
  ${OBOE}/deps/Catch2/include/external   # Clara
  ${OBOE}/deps/cppcodec                  # replay.cpp base64 (SConstruct:412)
  ${OBOE}/deps/fmtlib/include
  ${PREFIX}/include)
foreach(d ${SRC_DIRS})
  if(IS_DIRECTORY ${d})
    list(APPEND INC_DIRS ${d})
  endif()
endforeach()

# --- gitrev.hpp (generated by scons natively; regenerate for web) ------------
file(MAKE_DIRECTORY ${GEN}/tools)
file(WRITE ${GEN}/tools/gitrev.hpp [==[
#define GIT_REVISION "web"
#define GIT_TAG ""
#define GIT_TAG_REVISION ""
#define GIT_STATUS ""
#define GIT_REPO "web"
]==])

# --- sources (mirror the SConscripts; web deltas are marked) ------------------
# SConstruct: game = game_sources + party_classes + common_sources, where
# common_sources = dlog_util + tools (tools' SConscript pulls in the
# top-level src/*.cpp game-support files via ../).
file(GLOB SRCTOP  ${OBOE}/src/*.cpp)
# oldstructs.cpp is dead (compiled by no SConscript); view_dialogs.cpp is
# listed explicitly in the game section below.
list(REMOVE_ITEM SRCTOP
  ${OBOE}/src/oldstructs.cpp
  ${OBOE}/src/view_dialogs.cpp)
file(GLOB TOOLS     ${OBOE}/src/tools/*.cpp)
# web delta: the SConscript compiles ONLY *.linux.cpp on posix (replaced by
# the web stubs, task 10) — so the win/mac platform files never build here
# either.
list(REMOVE_ITEM TOOLS
  ${OBOE}/src/tools/winutil.linux.cpp
  ${OBOE}/src/tools/cursors.linux.cpp
  ${OBOE}/src/tools/winutil.win.cpp
  ${OBOE}/src/tools/cursors.win.cpp
  ${OBOE}/src/tools/menu_accel.win.cpp)
file(GLOB RESMGR    ${OBOE}/src/fileio/resmgr/*.cpp)
file(GLOB GFX       ${OBOE}/src/gfx/*.cpp)
list(REMOVE_ITEM GFX ${OBOE}/src/gfx/qdpict.mac.cpp)
file(GLOB SCEN      ${OBOE}/src/scenario/*.cpp)
file(GLOB UNIV      ${OBOE}/src/universe/*.cpp)   # party_classes
file(GLOB DLOGXML   ${OBOE}/src/dialogxml/*.cpp ${OBOE}/src/dialogxml/dialogs/*.cpp ${OBOE}/src/dialogxml/widgets/*.cpp)
file(GLOB XMLPARSER ${OBOE}/src/fileio/xml-parser/*.cpp)

add_executable(oboe
  ${SRCTOP}
  # tools core + web stubs
  ${TOOLS}
  ${CMAKE_CURRENT_SOURCE_DIR}/winutil.web.cpp
  ${CMAKE_CURRENT_SOURCE_DIR}/cursors.web.cpp
  # fileio
  ${RESMGR}
  ${OBOE}/src/fileio/estreams.cpp
  ${OBOE}/src/fileio/fileio.cpp
  ${OBOE}/src/fileio/fileio_scen.cpp
  ${OBOE}/src/fileio/map_parse.cpp
  ${OBOE}/src/fileio/special_parse.cpp
  ${OBOE}/src/fileio/tarball.cpp
  ${OBOE}/src/fileio/tagfile.cpp
  ${OBOE}/src/fileio/gzstream/gzstream.cpp
  # gfx + scenario + universe
  ${GFX}
  ${SCEN}
  ${UNIV}
  # dialogxml (compiled with -fpermissive, as in its SConscript)
  ${DLOGXML}
  ${XMLPARSER}
  # game
  ${OBOE}/src/game/boe.actions.cpp
  ${OBOE}/src/game/boe.combat.cpp
  ${OBOE}/src/game/boe.dlgutil.cpp
  ${OBOE}/src/game/boe.fileio.cpp
  ${OBOE}/src/game/boe.graphics.cpp
  ${OBOE}/src/game/boe.graphutil.cpp
  ${OBOE}/src/game/boe.infodlg.cpp
  ${OBOE}/src/game/boe.items.cpp
  ${OBOE}/src/game/boe.locutils.cpp
  ${OBOE}/src/game/boe.main.cpp
  ${OBOE}/src/game/boe.monster.cpp
  ${OBOE}/src/game/boe.newgraph.cpp
  ${OBOE}/src/game/boe.party.cpp
  ${OBOE}/src/game/boe.specials.cpp
  ${OBOE}/src/game/boe.startup.cpp
  ${OBOE}/src/game/boe.text.cpp
  ${OBOE}/src/game/boe.town.cpp
  ${OBOE}/src/game/boe.townspec.cpp
  ${OBOE}/src/game/boe.ui.cpp
  ${OBOE}/src/game/boe.menu.cpp
  ${OBOE}/src/game/boe.menus.linux.cpp   # pure SFML in-canvas menu bar; no X11
  ${OBOE}/src/pcedit/pc.editors.cpp
  ${OBOE}/src/fileio/fileio_party.cpp
  ${OBOE}/src/view_dialogs.cpp
  ${OBOE}/deps/fmtlib/src/format.cc
  ${OBOE}/deps/fmtlib/src/os.cc)

target_include_directories(oboe PRIVATE ${INC_DIRS})
target_compile_definitions(oboe PRIVATE TIXML_USE_TICPP)
set_source_files_properties(${DLOGXML} ${XMLPARSER} PROPERTIES COMPILE_OPTIONS -fpermissive)
# POSIX parity from SConstruct: -std=c++14 -include global.hpp
target_compile_options(oboe PRIVATE --include=${OBOE}/src/global.hpp
  # emcc 6.x: wasm-ld requires the atomics/bulk-memory features in EVERY
  # input object when linking -sUSE_PTHREADS (shared memory), so -pthread is
  # a compile flag too (the plan's "compile single-threaded, link pthread"
  # assumption does not hold on this toolchain — the fork's own CMake bakes
  # -pthread into compile as well). OBOE's code stays single-threaded.
  # -fexceptions: OBOE is built around C++ exceptions (fs::canonical throws,
  # bad_lexical_cast, …); emcc 6.x defaults to exceptions OFF.
  -pthread -fexceptions
  # TEMP: detect stack overflow (compile flag)
  -sSTACK_OVERFLOW_CHECK=${OBOE_STACK_CHECK})
if(OBOE_ASAN)
  # TEMP: AddressSanitizer (memory-corruption diagnosis)
  target_compile_options(oboe PRIVATE -fsanitize=address)
endif()

# --- link: our static libs + emscripten built-ins/ports -----------------------
# SFML/TGUI/Boost all install into ${PREFIX} (tasks 3/4/8; SFML via
# `cmake --install build-web/sfml-build --prefix ...` in task 3's flow).
target_link_libraries(oboe PRIVATE
  # -s = SFML's static-build postfix: SFML must be configured with
  # -DBUILD_SHARED_LIBS=FALSE (never rely on the cmake version to force
  # static — cmake >= 4.2 does, cmake 3.x builds unusable shared libs).
  ${PREFIX}/lib/libsfml-graphics-s.a
  ${PREFIX}/lib/libsfml-audio-s.a
  ${PREFIX}/lib/libsfml-window-s.a
  ${PREFIX}/lib/libsfml-system-s.a
  ${PREFIX}/lib/libtgui.a
  ${PREFIX}/lib/libboost_filesystem.a
  -lopenal)   # emscripten's built-in OpenAL (Web Audio backend)

target_link_options(oboe PRIVATE
  # -fexceptions at link selects the exception libraries (libc++abi's
  # __cpp_exception et al.); emcc 6.x defaults to exceptions OFF
  -fexceptions
  # mirrors the fork's baked options (cmake/Config.cmake) so the statically
  # linked SFML code stays ABI-consistent; full rationale in task 3
  -sWASM -sMODULARIZE -sEXPORT_NAME=Oboe
  # OBOE's game loop yields to the browser via emscripten_sleep (asyncify
  # unwind-to-top). noExitRuntime keeps the runtime (and its globals) alive
  # across those suspends; otherwise callMain's post-main exitJS() runs the
  # global destructors (freeing SFML's GlContextImpl::mutex) while the loop is
  # still live, and the resumed loop reads the freed global (heap-UAF).
  -sALLOW_MEMORY_GROWTH=1 -sEXIT_RUNTIME=0
  -sFETCH=1 -sFORCE_FILESYSTEM=1
  -sFULL_ES2=1 -sMAX_WEBGL_VERSION=1 -sMIN_WEBGL_VERSION=1
  -sSTACK_SIZE=4mb -sUSE_PTHREADS=1 -pthread
  # Asyncify: OBOE is exception-heavy and reaches emscripten_sleep via
  # call_indirect, so ASYNCIFY_IGNORE_INDIRECT must be 0 (instrument indirect
  # calls; treat invoke_* EH thunks as suspension points).
  -sASYNCIFY=${OBOE_ASYNCIFY} -sASYNCIFY_IGNORE_INDIRECT=${OBOE_ASYNCIFY_IGNORE_INDIRECT}
  -sASYNCIFY_DEBUG=${OBOE_ASYNCIFY_DEBUG}
  -sGL_EXPLICIT_UNIFORM_LOCATION=1 -sGL_EXPLICIT_UNIFORM_BINDING=1
  --use-port=freetype --use-port=ogg --use-port=vorbis --use-port=zlib
  # IDBFS: cross-reload save persistence — boot.js mounts it on the manifest
  # "persist" dirs (spec 2026-08-22 §3).
  -lidbfs.js
  -sEXPORTED_RUNTIME_METHODS=FS)
if(OBOE_ASAN)
  target_link_options(oboe PRIVATE -fsanitize=address)
endif()

# Output straight into the served dir (alongside data/, scenarios/, bases/)
set_target_properties(oboe PROPERTIES
  RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/../web/assets)
