mirror of
https://github.com/TwilitRealm/dusklight
synced 2026-07-10 12:54:50 -04:00
Compare commits
74 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c509ff7647 | |||
| 6849baac06 | |||
| f3ca94b338 | |||
| 9b3b827054 | |||
| 4de3c20431 | |||
| 2840843e3c | |||
| 312195920a | |||
| bc11bf3563 | |||
| 36635f8c62 | |||
| 6136d9bbf7 | |||
| 16c573a170 | |||
| e9e16a8ac1 | |||
| 4339e60ba6 | |||
| af5635dd42 | |||
| c876ea558f | |||
| 9b75dc5fd2 | |||
| 5c9c76cc0b | |||
| b474aafe9d | |||
| 84c5729c4e | |||
| e0ab36b7d9 | |||
| d40a30ee13 | |||
| 074b43a089 | |||
| 8e8dc305e6 | |||
| 41389f4a8e | |||
| 8145dec2a1 | |||
| 4089a80a17 | |||
| b772b6d952 | |||
| 42910ab2fd | |||
| f54892b2c2 | |||
| f32e069c4b | |||
| 09f087656a | |||
| fe15366912 | |||
| cfadf7607a | |||
| f81d25b425 | |||
| ebf6f31719 | |||
| 590d209f76 | |||
| ed21cd4fd0 | |||
| 277538bb81 | |||
| 5418b1831d | |||
| 2d4e69466b | |||
| 427dcfab82 | |||
| f5642f3073 | |||
| cc9c15de54 | |||
| 1fd8a2ca3c | |||
| 0c9c8795ce | |||
| 9eb9acfa11 | |||
| facbf35343 | |||
| 7a34830dc7 | |||
| e4557efb23 | |||
| 42e12eb5ab | |||
| 16cc37ca10 | |||
| 44cb2c84ba | |||
| 8e9d4d624a | |||
| db87b91954 | |||
| ad53af5c78 | |||
| a6e5160c71 | |||
| 38a0a7be0b | |||
| 02fdde3768 | |||
| 33e13d508b | |||
| afc3376aec | |||
| b07fb50128 | |||
| d0894853d7 | |||
| cacb768725 | |||
| 00707024bb | |||
| 7c5ed6a0e1 | |||
| 131a09f317 | |||
| a58f9c7b43 | |||
| 7290649bb8 | |||
| 34e1e740ab | |||
| a58f64ed80 | |||
| 28a37f6b4f | |||
| 285691cd19 | |||
| 93e33ecf1a | |||
| e26fab71d6 |
+1
-1
@@ -1,6 +1,6 @@
|
||||
---
|
||||
Language: Cpp
|
||||
Standard: C++03
|
||||
Standard: c++20
|
||||
AccessModifierOffset: -4
|
||||
AlignAfterOpenBracket: DontAlign
|
||||
AlignConsecutiveAssignments: false
|
||||
|
||||
+191
-143
@@ -5,96 +5,8 @@ if (NOT CMAKE_BUILD_TYPE)
|
||||
"Build type options: Debug Release RelWithDebInfo MinSizeRel" FORCE)
|
||||
endif ()
|
||||
|
||||
set(DUSK_VERSION_OVERRIDE "" CACHE STRING "Override version string (skips git detection and format validation)")
|
||||
|
||||
if (DUSK_VERSION_OVERRIDE)
|
||||
set(DUSK_WC_DESCRIBE "${DUSK_VERSION_OVERRIDE}")
|
||||
set(DUSK_VERSION_STRING "0.0.0.0")
|
||||
set(DUSK_SHORT_VERSION_STRING "0.0.0")
|
||||
set(DUSK_VERSION_CODE "1")
|
||||
set(DUSK_WC_REVISION "")
|
||||
set(DUSK_WC_BRANCH "")
|
||||
set(DUSK_WC_DATE "")
|
||||
message(STATUS "Dusklight version overridden to ${DUSK_WC_DESCRIBE}")
|
||||
else ()
|
||||
# obtain revision info from git
|
||||
find_package(Git)
|
||||
if (GIT_FOUND)
|
||||
# make sure version information gets re-run when the current Git HEAD changes
|
||||
execute_process(WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} COMMAND ${GIT_EXECUTABLE} rev-parse --git-path HEAD
|
||||
OUTPUT_VARIABLE dusk_git_head_filename
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${dusk_git_head_filename}")
|
||||
|
||||
execute_process(WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} COMMAND ${GIT_EXECUTABLE} rev-parse --symbolic-full-name HEAD
|
||||
OUTPUT_VARIABLE dusk_git_head_symbolic
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
execute_process(WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
|
||||
COMMAND ${GIT_EXECUTABLE} rev-parse --git-path ${dusk_git_head_symbolic}
|
||||
OUTPUT_VARIABLE dusk_git_head_symbolic_filename
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${dusk_git_head_symbolic_filename}")
|
||||
|
||||
# defines DUSK_WC_REVISION
|
||||
execute_process(WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} COMMAND ${GIT_EXECUTABLE} rev-parse HEAD
|
||||
OUTPUT_VARIABLE DUSK_WC_REVISION
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
# defines DUSK_WC_DESCRIBE
|
||||
execute_process(WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} COMMAND ${GIT_EXECUTABLE} describe --tags --long --dirty --match "v*"
|
||||
OUTPUT_VARIABLE DUSK_WC_DESCRIBE
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
|
||||
# remove the git hash, then collapse a clean "-0" suffix only
|
||||
string(REGEX REPLACE "-[^-]+(-dirty|)$" "\\1" DUSK_WC_DESCRIBE "${DUSK_WC_DESCRIBE}")
|
||||
string(REGEX REPLACE "-0$" "" DUSK_WC_DESCRIBE "${DUSK_WC_DESCRIBE}")
|
||||
|
||||
# defines DUSK_WC_BRANCH
|
||||
execute_process(WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} COMMAND ${GIT_EXECUTABLE} rev-parse --abbrev-ref HEAD
|
||||
OUTPUT_VARIABLE DUSK_WC_BRANCH
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
# defines DUSK_WC_DATE
|
||||
execute_process(WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} COMMAND ${GIT_EXECUTABLE} log -1 --format=%ad
|
||||
OUTPUT_VARIABLE DUSK_WC_DATE
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
else ()
|
||||
message(STATUS "Unable to find git, commit information will not be available")
|
||||
endif ()
|
||||
|
||||
if (DUSK_WC_DESCRIBE MATCHES "^v([0-9]+)\\.([0-9]+)\\.([0-9]+)([-+].*)?$")
|
||||
set(DUSK_SHORT_VERSION_STRING "${CMAKE_MATCH_1}.${CMAKE_MATCH_2}.${CMAKE_MATCH_3}")
|
||||
set(_ver_major ${CMAKE_MATCH_1})
|
||||
set(_ver_minor ${CMAKE_MATCH_2})
|
||||
set(_ver_patch ${CMAKE_MATCH_3})
|
||||
set(DUSK_VERSION_TWEAK "0")
|
||||
if (DUSK_WC_DESCRIBE MATCHES "^v[0-9]+\\.[0-9]+\\.[0-9]+-([0-9]+)(-dirty)?$")
|
||||
set(DUSK_VERSION_TWEAK "${CMAKE_MATCH_1}")
|
||||
elseif (DUSK_WC_DESCRIBE MATCHES "^v[0-9]+\\.[0-9]+\\.[0-9]+-[0-9A-Za-z.-]+-([0-9]+)(-dirty)?$")
|
||||
set(DUSK_VERSION_TWEAK "${CMAKE_MATCH_1}")
|
||||
endif ()
|
||||
set(DUSK_VERSION_STRING "${DUSK_SHORT_VERSION_STRING}.${DUSK_VERSION_TWEAK}")
|
||||
if(DUSK_VERSION_TWEAK GREATER 999)
|
||||
set(_tweak 999)
|
||||
else()
|
||||
set(_tweak ${DUSK_VERSION_TWEAK})
|
||||
endif()
|
||||
# encoding: major*1e7 + minor*1e5 + patch*1e3 + tweak; collision-free for major<210, minor<100, patch<100, tweak<=999
|
||||
math(EXPR DUSK_VERSION_CODE
|
||||
"${_ver_major} * 10000000 + ${_ver_minor} * 100000 + ${_ver_patch} * 1000 + ${_tweak}")
|
||||
else ()
|
||||
set(DUSK_WC_DESCRIBE "UNKNOWN-VERSION")
|
||||
set(DUSK_VERSION_STRING "0.0.0.0")
|
||||
set(DUSK_SHORT_VERSION_STRING "0.0.0")
|
||||
set(DUSK_VERSION_CODE "1")
|
||||
endif ()
|
||||
|
||||
endif ()
|
||||
|
||||
# Add version information to CI environment variables
|
||||
if(DEFINED ENV{GITHUB_ENV})
|
||||
file(APPEND "$ENV{GITHUB_ENV}" "DUSK_VERSION=${DUSK_WC_DESCRIBE}\n")
|
||||
file(APPEND "$ENV{GITHUB_ENV}" "DUSK_VERSION_CODE=${DUSK_VERSION_CODE}\n")
|
||||
endif()
|
||||
message(STATUS "Dusklight version set to ${DUSK_WC_DESCRIBE}")
|
||||
include(cmake/DetectVersion.cmake)
|
||||
detect_version()
|
||||
message(STATUS "Build type: ${CMAKE_BUILD_TYPE}")
|
||||
project(dusklight LANGUAGES C CXX VERSION ${DUSK_VERSION_STRING})
|
||||
if (APPLE)
|
||||
@@ -126,6 +38,33 @@ set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
|
||||
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
|
||||
set_property(GLOBAL PROPERTY PREDEFINED_TARGETS_FOLDER "_cmake")
|
||||
|
||||
option(ENABLE_ASAN "Enable AddressSanitizer" OFF)
|
||||
if (ENABLE_ASAN)
|
||||
if (CMAKE_C_COMPILER_FRONTEND_VARIANT STREQUAL "MSVC" AND
|
||||
CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "MSVC")
|
||||
add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:/fsanitize=address>)
|
||||
add_link_options(/fsanitize=address /INCREMENTAL:NO)
|
||||
set(CMAKE_MSVC_DEBUG_INFORMATION_FORMAT "ProgramDatabase")
|
||||
foreach (_lang C CXX)
|
||||
foreach (_rtc_flag /RTC1 /RTCc /RTCs /RTCu)
|
||||
string(REPLACE "${_rtc_flag}" "" CMAKE_${_lang}_FLAGS_DEBUG "${CMAKE_${_lang}_FLAGS_DEBUG}")
|
||||
endforeach ()
|
||||
endforeach ()
|
||||
elseif (CMAKE_C_COMPILER_FRONTEND_VARIANT STREQUAL "GNU" AND
|
||||
CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "GNU")
|
||||
add_compile_options(
|
||||
$<$<COMPILE_LANGUAGE:C,CXX,OBJC,OBJCXX>:-fsanitize=address>
|
||||
$<$<COMPILE_LANGUAGE:C,CXX,OBJC,OBJCXX>:-fno-omit-frame-pointer>
|
||||
)
|
||||
add_link_options(-fsanitize=address)
|
||||
else ()
|
||||
message(FATAL_ERROR "ENABLE_ASAN requires GNU-like or MSVC-like C/C++ compiler frontends")
|
||||
endif ()
|
||||
|
||||
add_compile_definitions(NDEBUG_SANITIZER) # Avoids absl issue with SwissTable debug code
|
||||
message(STATUS "dusklight: Enabled AddressSanitizer")
|
||||
endif ()
|
||||
|
||||
if (CMAKE_SYSTEM_NAME STREQUAL Linux)
|
||||
set(DAWN_USE_WAYLAND ON CACHE BOOL "Enable support for Wayland surface" FORCE)
|
||||
endif ()
|
||||
@@ -148,13 +87,14 @@ option(DUSK_SELECTED_OPT "If on, selected parts of the project will be compiled
|
||||
option(DUSK_MOVIE_SUPPORT "If on, compile against libjpeg-turbo to enable THP file decoding" ON)
|
||||
option(DUSK_ENABLE_UPDATE_CHECKER "Enable update checking support" ON)
|
||||
option(DUSK_ENABLE_SENTRY_NATIVE "Enable sentry-native crash reporting support" OFF)
|
||||
option(DUSK_PACKAGE_INSTALL "Install Dusklight with a Linux-native file structure" OFF)
|
||||
option(DUSK_GFX_DEBUG_GROUPS "Report debug groups to the native graphics API" ${DUSK_GFX_DEBUG_GROUPS_DEFAULT})
|
||||
set(DUSK_SENTRY_DSN "" CACHE STRING "Sentry DSN")
|
||||
set(DUSK_SENTRY_ENVIRONMENT "development" CACHE STRING "Sentry environment")
|
||||
option(DUSK_ENABLE_CODE_MODS "Enable code mods" OFF)
|
||||
|
||||
# Edit & Continue
|
||||
if (MSVC)
|
||||
if ("${CMAKE_MSVC_DEBUG_INFORMATION_FORMAT}" STREQUAL "" AND CMAKE_BUILD_TYPE STREQUAL "Debug")
|
||||
if ("${CMAKE_MSVC_DEBUG_INFORMATION_FORMAT}" STREQUAL "" AND CMAKE_BUILD_TYPE STREQUAL "Debug"
|
||||
AND CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
|
||||
set(CMAKE_MSVC_DEBUG_INFORMATION_FORMAT "EditAndContinue")
|
||||
endif ()
|
||||
if (CMAKE_MSVC_DEBUG_INFORMATION_FORMAT STREQUAL "EditAndContinue")
|
||||
@@ -256,7 +196,6 @@ elseif (MSVC)
|
||||
add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:/utf-8>)
|
||||
endif ()
|
||||
|
||||
|
||||
include(FetchContent)
|
||||
|
||||
# Declare all dependencies first so CMake can download them in parallel
|
||||
@@ -264,15 +203,55 @@ message(STATUS "dusklight: Fetching cxxopts")
|
||||
FetchContent_Declare(cxxopts
|
||||
URL https://github.com/jarro2783/cxxopts/archive/refs/tags/v3.3.1.tar.gz
|
||||
URL_HASH SHA256=3bfc70542c521d4b55a46429d808178916a579b28d048bd8c727ee76c39e2072
|
||||
DOWNLOAD_EXTRACT_TIMESTAMP TRUE
|
||||
DOWNLOAD_EXTRACT_TIMESTAMP FALSE
|
||||
)
|
||||
message(STATUS "dusklight: Fetching nlohmann/json")
|
||||
FetchContent_Declare(json
|
||||
URL https://github.com/nlohmann/json/releases/download/v3.12.0/json.tar.xz
|
||||
URL_HASH SHA256=42f6e95cad6ec532fd372391373363b62a14af6d771056dbfc86160e6dfff7aa
|
||||
DOWNLOAD_EXTRACT_TIMESTAMP TRUE
|
||||
DOWNLOAD_EXTRACT_TIMESTAMP FALSE
|
||||
)
|
||||
FetchContent_MakeAvailable(cxxopts json)
|
||||
message(STATUS "dusklight: Fetching miniz")
|
||||
FetchContent_Declare(miniz
|
||||
URL https://github.com/richgel999/miniz/releases/download/3.0.2/miniz-3.0.2.zip
|
||||
DOWNLOAD_EXTRACT_TIMESTAMP TRUE
|
||||
EXCLUDE_FROM_ALL
|
||||
)
|
||||
|
||||
set(_fetch_content_deps cxxopts json miniz)
|
||||
if (DUSK_ENABLE_CODE_MODS)
|
||||
message(STATUS "dusklight: Fetching funchook")
|
||||
# cmake/PatchFunchook.cmake patches funchook's cmake/capstone.cmake.in to inject a
|
||||
# PATCH_COMMAND into capstone's inner ExternalProject. That PATCH_COMMAND runs
|
||||
# cmake/PatchCapstone.cmake after capstone is cloned, which removes the
|
||||
# cmake_policy(SET CMP0048 OLD) line that CMake >= 3.27 rejects.
|
||||
# This is incredibly scuffed and we should probably think of a better way to do this
|
||||
set(CAPSTONE_FIX_SCRIPT "${CMAKE_CURRENT_SOURCE_DIR}/cmake/PatchCapstone.cmake")
|
||||
FetchContent_Declare(funchook
|
||||
GIT_REPOSITORY https://github.com/kubo/funchook.git
|
||||
GIT_TAG v1.1.3
|
||||
GIT_SHALLOW TRUE
|
||||
GIT_PROGRESS TRUE
|
||||
PATCH_COMMAND ${CMAKE_COMMAND} -DSOURCE_DIR=<SOURCE_DIR> -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/PatchFunchook.cmake
|
||||
EXCLUDE_FROM_ALL
|
||||
)
|
||||
set(FUNCHOOK_BUILD_TESTS OFF CACHE BOOL "" FORCE)
|
||||
set(FUNCHOOK_BUILD_SHARED OFF CACHE BOOL "" FORCE)
|
||||
set(FUNCHOOK_INSTALL OFF CACHE BOOL "" FORCE)
|
||||
if (APPLE AND CMAKE_OSX_ARCHITECTURES)
|
||||
list(LENGTH CMAKE_OSX_ARCHITECTURES _osx_arch_count)
|
||||
if (_osx_arch_count EQUAL 1)
|
||||
list(GET CMAKE_OSX_ARCHITECTURES 0 _osx_arch)
|
||||
if (_osx_arch MATCHES "^(arm64|aarch64|ARM64)$")
|
||||
set(FUNCHOOK_CPU arm64 CACHE STRING "" FORCE)
|
||||
elseif (_osx_arch MATCHES "^(x86_64|AMD64|amd64|i[3-6]86|x86)$")
|
||||
set(FUNCHOOK_CPU x86 CACHE STRING "" FORCE)
|
||||
endif ()
|
||||
endif ()
|
||||
endif ()
|
||||
list(APPEND _fetch_content_deps funchook)
|
||||
endif ()
|
||||
FetchContent_MakeAvailable(${_fetch_content_deps})
|
||||
|
||||
if (DUSK_ENABLE_SENTRY_NATIVE)
|
||||
message(STATUS "dusklight: Fetching sentry-native")
|
||||
@@ -306,21 +285,7 @@ if(_arch MATCHES "^(arm|aarch64)" AND CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQU
|
||||
add_compile_options(-fsigned-char)
|
||||
endif()
|
||||
|
||||
if (CMAKE_SYSTEM_NAME STREQUAL Windows)
|
||||
set(PLATFORM_NAME win32)
|
||||
elseif (CMAKE_SYSTEM_NAME STREQUAL Darwin)
|
||||
if (IOS)
|
||||
set(PLATFORM_NAME ios)
|
||||
elseif (TVOS)
|
||||
set(PLATFORM_NAME tvos)
|
||||
else ()
|
||||
set(PLATFORM_NAME macos)
|
||||
endif ()
|
||||
else ()
|
||||
string(TOLOWER CMAKE_SYSTEM_NAME PLATFORM_NAME)
|
||||
endif ()
|
||||
|
||||
configure_file(${CMAKE_SOURCE_DIR}/version.h.in ${CMAKE_BINARY_DIR}/version.h)
|
||||
configure_version_header()
|
||||
|
||||
include(files.cmake)
|
||||
|
||||
@@ -336,24 +301,15 @@ set(DUSK_COPYRIGHT "Copyright (C) Twilit Realm contributors")
|
||||
source_group("dolzel" FILES ${DOLZEL_FILES} ${Z2AUDIOLIB_FILES} ${REL_FILES})
|
||||
source_group("dusklight" FILES ${DUSK_FILES} ${DUSK_HTTP_BACKEND_FILES})
|
||||
|
||||
set(GAME_COMPILE_DEFS TARGET_PC WIDESCREEN_SUPPORT=1 AVOID_UB=1 VERSION=0 MTX_USE_PS=1)
|
||||
|
||||
set(GAME_INCLUDE_DIRS
|
||||
include
|
||||
src
|
||||
assets/GZ2E01 # TODO: make this dynamic if needed?
|
||||
libs/JSystem/include
|
||||
libs
|
||||
extern/aurora/include/dolphin
|
||||
extern
|
||||
${CMAKE_BINARY_DIR})
|
||||
include(cmake/GameABIConfig.cmake)
|
||||
|
||||
find_package(Threads REQUIRED)
|
||||
set(GAME_LIBS aurora::core aurora::gx aurora::gd aurora::si aurora::vi aurora::pad aurora::mtx aurora::os aurora::dvd
|
||||
aurora::card freeverb cxxopts::cxxopts absl::flat_hash_map nlohmann_json::nlohmann_json TracyClient fmt::fmt
|
||||
Threads::Threads)
|
||||
|
||||
list(APPEND GAME_LIBS zstd::libzstd)
|
||||
Threads::Threads zstd::libzstd dusklight_game_headers)
|
||||
if (DUSK_ENABLE_CODE_MODS)
|
||||
list(APPEND GAME_LIBS funchook-static)
|
||||
endif ()
|
||||
|
||||
if (DUSK_ENABLE_SENTRY_NATIVE)
|
||||
list(APPEND GAME_LIBS sentry)
|
||||
@@ -421,8 +377,13 @@ if (DUSK_ENABLE_DISCORD AND NOT ANDROID AND NOT IOS AND NOT TVOS)
|
||||
list(APPEND GAME_COMPILE_DEFS DUSK_DISCORD=1)
|
||||
endif ()
|
||||
|
||||
if(ANDROID)
|
||||
list(APPEND GAME_COMPILE_DEFS TARGET_ANDROID=1)
|
||||
if (DUSK_ENABLE_CODE_MODS)
|
||||
list(APPEND GAME_COMPILE_DEFS DUSK_CODE_MODS=1)
|
||||
endif ()
|
||||
|
||||
if (DUSK_PACKAGE_INSTALL)
|
||||
include(GNUInstallDirs)
|
||||
list(APPEND GAME_COMPILE_DEFS DUSK_ASSET_DIR="${CMAKE_INSTALL_FULL_DATADIR}/dusklight/")
|
||||
endif ()
|
||||
|
||||
if (DUSK_GFX_DEBUG_GROUPS)
|
||||
@@ -444,7 +405,7 @@ set(GAME_DEBUG_FILES
|
||||
set_source_files_properties(
|
||||
${GAME_DEBUG_FILES}
|
||||
PROPERTIES
|
||||
COMPILE_DEFINITIONS "$<$<CONFIG:Debug>:DEBUG=1>;$<$<CONFIG:Debug>:PARTIAL_DEBUG=1>"
|
||||
COMPILE_DEFINITIONS "$<$<CONFIG:Debug>:DEBUG=1>"
|
||||
)
|
||||
|
||||
# game_base is for all other game code files
|
||||
@@ -458,16 +419,11 @@ set(GAME_BASE_FILES
|
||||
set_source_files_properties(
|
||||
${GAME_BASE_FILES}
|
||||
PROPERTIES
|
||||
COMPILE_DEFINITIONS "NDEBUG=1;NDEBUG_DEFINED=1;DEBUG_DEFINED=0;$<$<CONFIG:Debug>:PARTIAL_DEBUG=1>"
|
||||
COMPILE_DEFINITIONS "NDEBUG=1;NDEBUG_DEFINED=1;DEBUG_DEFINED=0"
|
||||
)
|
||||
|
||||
foreach(jsystem_lib IN LISTS JSYSTEM_LIBRARIES)
|
||||
target_compile_definitions(${jsystem_lib} PRIVATE
|
||||
${GAME_COMPILE_DEFS}
|
||||
$<$<CONFIG:Debug>:DEBUG=1>
|
||||
$<$<CONFIG:Debug>:PARTIAL_DEBUG=1>
|
||||
)
|
||||
target_include_directories(${jsystem_lib} PRIVATE ${GAME_INCLUDE_DIRS})
|
||||
target_compile_definitions(${jsystem_lib} PRIVATE ${GAME_COMPILE_DEFS} $<$<CONFIG:Debug>:DEBUG=1>)
|
||||
target_link_libraries(${jsystem_lib} PRIVATE ${GAME_LIBS})
|
||||
set_target_properties(${jsystem_lib} PROPERTIES FOLDER "JSystem")
|
||||
endforeach()
|
||||
@@ -479,18 +435,67 @@ if (CMAKE_CXX_LINK_GROUP_USING_RESCAN_SUPPORTED OR CMAKE_LINK_GROUP_USING_RESCAN
|
||||
set(JSYSTEM_LINK_LIBRARIES "$<LINK_GROUP:RESCAN,${JSYSTEM_LIBRARIES}>")
|
||||
endif ()
|
||||
|
||||
set(DUSK_FILES src/dusk/main.cpp ${GAME_BASE_FILES} ${GAME_DEBUG_FILES})
|
||||
set(DUSK_FILES src/dusk/main.cpp ${GAME_BASE_FILES} ${GAME_DEBUG_FILES} ${miniz_SOURCE_DIR}/miniz.c)
|
||||
if(ANDROID)
|
||||
add_library(dusklight SHARED ${DUSK_FILES})
|
||||
set_target_properties(dusklight PROPERTIES OUTPUT_NAME main)
|
||||
else ()
|
||||
add_executable(dusklight ${DUSK_FILES})
|
||||
endif ()
|
||||
if (ENABLE_ASAN)
|
||||
target_sources(dusklight PRIVATE src/dusk/asan_options.c)
|
||||
endif ()
|
||||
|
||||
target_compile_definitions(dusklight PRIVATE ${GAME_COMPILE_DEFS})
|
||||
target_include_directories(dusklight PRIVATE ${GAME_INCLUDE_DIRS})
|
||||
target_include_directories(dusklight PRIVATE ${miniz_SOURCE_DIR})
|
||||
target_link_libraries(dusklight PRIVATE aurora::main ${GAME_LIBS} ${JSYSTEM_LINK_LIBRARIES})
|
||||
target_precompile_headers(dusklight PRIVATE "$<$<COMPILE_LANGUAGE:CXX>:${CMAKE_SOURCE_DIR}/include/dusk_pch.hpp>")
|
||||
|
||||
if (DUSK_ENABLE_CODE_MODS)
|
||||
include(cmake/SymbolManifest.cmake)
|
||||
if (WIN32)
|
||||
# Game ABI exports & import library for mod linking
|
||||
include(cmake/WindowsExports.cmake)
|
||||
setup_windows_exports(dusklight)
|
||||
endif ()
|
||||
# Post-link symbol manifest: hookable-surface name->address map keyed to the build.
|
||||
setup_symbol_manifest(dusklight)
|
||||
endif ()
|
||||
|
||||
# Hook reliability: guaranteed patchable entries on the game ABI surface, and no identical-code folding.
|
||||
if (MSVC)
|
||||
if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
|
||||
set(DUSK_PATCHABLE_ENTRY_FLAG $<$<COMPILE_LANGUAGE:C,CXX>:/hotpatch>)
|
||||
endif ()
|
||||
if (CMAKE_SYSTEM_PROCESSOR STREQUAL "ARM64")
|
||||
target_link_options(dusklight PRIVATE /FUNCTIONPADMIN:16 /OPT:NOICF)
|
||||
else ()
|
||||
target_link_options(dusklight PRIVATE /FUNCTIONPADMIN /OPT:NOICF)
|
||||
endif ()
|
||||
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
|
||||
if (CMAKE_SYSTEM_PROCESSOR STREQUAL "arm64" OR CMAKE_OSX_ARCHITECTURES MATCHES "arm64")
|
||||
set(DUSK_PATCHABLE_ENTRY_FLAG $<$<COMPILE_LANGUAGE:C,CXX>:-fpatchable-function-entry=2,1>)
|
||||
else ()
|
||||
set(DUSK_PATCHABLE_ENTRY_FLAG $<$<COMPILE_LANGUAGE:C,CXX>:-fpatchable-function-entry=10,5>)
|
||||
endif ()
|
||||
endif ()
|
||||
if (DEFINED DUSK_PATCHABLE_ENTRY_FLAG)
|
||||
target_compile_options(dusklight PRIVATE ${DUSK_PATCHABLE_ENTRY_FLAG})
|
||||
foreach(jsystem_lib IN LISTS JSYSTEM_LIBRARIES)
|
||||
target_compile_options(${jsystem_lib} PRIVATE ${DUSK_PATCHABLE_ENTRY_FLAG})
|
||||
endforeach()
|
||||
endif ()
|
||||
|
||||
if (WIN32)
|
||||
target_link_libraries(dusklight PRIVATE Psapi)
|
||||
endif ()
|
||||
if (APPLE)
|
||||
# Mods resolve game symbols from the executable at dlopen time.
|
||||
target_link_options(dusklight PRIVATE -Wl,-export_dynamic)
|
||||
elseif (UNIX AND NOT ANDROID)
|
||||
target_link_options(dusklight PRIVATE -rdynamic)
|
||||
endif ()
|
||||
|
||||
if (TARGET crashpad_handler)
|
||||
add_dependencies(dusklight crashpad_handler)
|
||||
add_custom_command(TARGET dusklight POST_BUILD
|
||||
@@ -509,6 +514,7 @@ endif ()
|
||||
|
||||
if (CMAKE_SYSTEM_NAME STREQUAL Linux)
|
||||
target_link_options(dusklight PRIVATE "-Wl,--build-id=sha1")
|
||||
target_link_libraries(dusklight PRIVATE dl)
|
||||
endif ()
|
||||
|
||||
if (NOT APPLE)
|
||||
@@ -549,6 +555,13 @@ if (WIN32)
|
||||
endif ()
|
||||
endif ()
|
||||
|
||||
include(cmake/ModSDK.cmake)
|
||||
|
||||
if (DUSK_ENABLE_CODE_MODS AND CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
|
||||
add_custom_target(dusklight_mods) # Aggregate target for all in-tree mods
|
||||
add_subdirectory(tools/mod_template)
|
||||
endif ()
|
||||
|
||||
if (APPLE)
|
||||
if (IOS)
|
||||
set(DUSK_RESOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/platforms/ios)
|
||||
@@ -556,6 +569,7 @@ if (APPLE)
|
||||
set(DUSK_RESOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/platforms/tvos)
|
||||
else ()
|
||||
set(DUSK_RESOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/platforms/macos)
|
||||
set(DUSK_ENTITLEMENTS ${DUSK_RESOURCE_DIR}/Dusklight.entitlements)
|
||||
endif ()
|
||||
set(DUSK_INFO_PLIST ${DUSK_RESOURCE_DIR}/Info.plist.in)
|
||||
file(GLOB_RECURSE DUSK_RESOURCE_FILES
|
||||
@@ -575,8 +589,7 @@ if (APPLE)
|
||||
get_filename_component(NEW_FILE_PATH ${NEW_FILE} DIRECTORY)
|
||||
set_property(SOURCE ${FILE} PROPERTY MACOSX_PACKAGE_LOCATION "Resources/${NEW_FILE_PATH}")
|
||||
endforeach ()
|
||||
set_target_properties(
|
||||
dusklight PROPERTIES
|
||||
set(_apple_bundle_properties
|
||||
MACOSX_BUNDLE TRUE
|
||||
MACOSX_BUNDLE_BUNDLE_NAME ${DUSK_BUNDLE_NAME}
|
||||
MACOSX_BUNDLE_GUI_IDENTIFIER ${DUSK_BUNDLE_IDENTIFIER}
|
||||
@@ -587,6 +600,31 @@ if (APPLE)
|
||||
XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED "YES"
|
||||
XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED "YES"
|
||||
)
|
||||
if (DUSK_ENTITLEMENTS)
|
||||
list(APPEND _apple_bundle_properties
|
||||
XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS ${DUSK_ENTITLEMENTS})
|
||||
endif ()
|
||||
if (NOT IOS AND NOT TVOS)
|
||||
list(APPEND _apple_bundle_properties
|
||||
XCODE_ATTRIBUTE_ENABLE_HARDENED_RUNTIME "YES")
|
||||
endif ()
|
||||
set_target_properties(dusklight PROPERTIES ${_apple_bundle_properties})
|
||||
|
||||
if (NOT IOS AND NOT TVOS AND NOT "${CMAKE_GENERATOR}" STREQUAL "Xcode")
|
||||
set(_sign_nested_commands)
|
||||
if (TARGET crashpad_handler)
|
||||
list(APPEND _sign_nested_commands
|
||||
COMMAND /usr/bin/codesign --force --sign -
|
||||
"$<TARGET_FILE_DIR:dusklight>/crashpad_handler")
|
||||
endif ()
|
||||
add_custom_command(TARGET dusklight POST_BUILD
|
||||
${_sign_nested_commands}
|
||||
COMMAND /usr/bin/codesign --force --sign - --entitlements
|
||||
"${DUSK_ENTITLEMENTS}" "$<TARGET_BUNDLE_DIR:dusklight>"
|
||||
COMMENT "Signing Dusklight.app with entitlements"
|
||||
VERBATIM
|
||||
)
|
||||
endif ()
|
||||
endif ()
|
||||
|
||||
if (APPLE AND NOT IOS AND NOT TVOS)
|
||||
@@ -648,12 +686,20 @@ set(EXTRA_TARGETS "")
|
||||
if (TARGET crashpad_handler)
|
||||
list(APPEND EXTRA_TARGETS crashpad_handler)
|
||||
endif ()
|
||||
install(TARGETS ${BINARY_TARGETS} ${EXTRA_TARGETS} DESTINATION ${CMAKE_INSTALL_PREFIX})
|
||||
if (DUSK_PACKAGE_INSTALL)
|
||||
install(TARGETS ${BINARY_TARGETS} ${EXTRA_TARGETS} DESTINATION ${CMAKE_INSTALL_BINDIR})
|
||||
else()
|
||||
install(TARGETS ${BINARY_TARGETS} ${EXTRA_TARGETS} DESTINATION ${CMAKE_INSTALL_PREFIX})
|
||||
endif()
|
||||
aurora_install_runtime_dlls(dusklight ${CMAKE_INSTALL_PREFIX})
|
||||
if (NOT APPLE)
|
||||
install(DIRECTORY ${CMAKE_SOURCE_DIR}/res DESTINATION ${CMAKE_INSTALL_PREFIX})
|
||||
if (DUSK_PACKAGE_INSTALL)
|
||||
install(DIRECTORY ${CMAKE_SOURCE_DIR}/res DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/dusklight)
|
||||
else()
|
||||
install(DIRECTORY ${CMAKE_SOURCE_DIR}/res DESTINATION ${CMAKE_INSTALL_PREFIX})
|
||||
endif()
|
||||
endif ()
|
||||
if (CMAKE_BUILD_TYPE STREQUAL Debug OR CMAKE_BUILD_TYPE STREQUAL RelWithDebInfo)
|
||||
if (CMAKE_BUILD_TYPE STREQUAL Debug OR CMAKE_BUILD_TYPE STREQUAL RelWithDebInfo AND NOT DUSK_PACKAGE_INSTALL)
|
||||
set(DEBUG_FILES_LIST "")
|
||||
foreach (target IN LISTS BINARY_TARGETS EXTRA_TARGETS)
|
||||
get_target_output_name(${target} output_name)
|
||||
@@ -702,3 +748,5 @@ foreach (target IN LISTS BINARY_TARGETS)
|
||||
endif ()
|
||||
endforeach ()
|
||||
endforeach ()
|
||||
|
||||
install_bundled_mods()
|
||||
|
||||
+93
-3
@@ -52,6 +52,16 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "asan",
|
||||
"hidden": true,
|
||||
"cacheVariables": {
|
||||
"ENABLE_ASAN": {
|
||||
"type": "BOOL",
|
||||
"value": true
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "linux-default",
|
||||
"displayName": "Linux (default)",
|
||||
@@ -62,7 +72,11 @@
|
||||
"type": "BOOL",
|
||||
"value": false
|
||||
},
|
||||
"CMAKE_INSTALL_PREFIX": "${sourceDir}/build/install"
|
||||
"CMAKE_INSTALL_PREFIX": "${sourceDir}/build/install",
|
||||
"DUSK_ENABLE_CODE_MODS": {
|
||||
"type": "BOOL",
|
||||
"value": true
|
||||
}
|
||||
},
|
||||
"vendor": {
|
||||
"microsoft.com/VisualStudioSettings/CMake/1.0": {
|
||||
@@ -83,6 +97,15 @@
|
||||
"linux-default"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "linux-default-debug-asan",
|
||||
"displayName": "Linux (default) Debug ASan",
|
||||
"inherits": [
|
||||
"debug",
|
||||
"linux-default",
|
||||
"asan"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "linux-default-relwithdebinfo",
|
||||
"displayName": "Linux (default) RelWithDebInfo",
|
||||
@@ -110,6 +133,15 @@
|
||||
"linux-clang"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "linux-clang-debug-asan",
|
||||
"displayName": "Linux (Clang) Debug ASan",
|
||||
"inherits": [
|
||||
"debug",
|
||||
"linux-clang",
|
||||
"asan"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "linux-clang-relwithdebinfo",
|
||||
"displayName": "Linux (Clang) RelWithDebInfo",
|
||||
@@ -130,7 +162,15 @@
|
||||
"cacheVariables": {
|
||||
"CMAKE_C_COMPILER": "cl",
|
||||
"CMAKE_CXX_COMPILER": "cl",
|
||||
"CMAKE_INSTALL_PREFIX": "${sourceDir}/build/install"
|
||||
"CMAKE_INSTALL_PREFIX": "${sourceDir}/build/install",
|
||||
"DUSK_ENABLE_CODE_MODS": {
|
||||
"type": "BOOL",
|
||||
"value": true
|
||||
},
|
||||
"CMAKE_DISABLE_FIND_PACKAGE_PkgConfig": {
|
||||
"type": "BOOL",
|
||||
"value": true
|
||||
}
|
||||
},
|
||||
"vendor": {
|
||||
"microsoft.com/VisualStudioSettings/CMake/1.0": {
|
||||
@@ -148,6 +188,15 @@
|
||||
"windows-msvc"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "windows-msvc-debug-asan",
|
||||
"displayName": "Windows (MSVC) Debug ASan",
|
||||
"inherits": [
|
||||
"debug",
|
||||
"windows-msvc",
|
||||
"asan"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "windows-msvc-relwithdebinfo",
|
||||
"displayName": "Windows (MSVC) RelWithDebInfo",
|
||||
@@ -221,7 +270,11 @@
|
||||
"type": "BOOL",
|
||||
"value": false
|
||||
},
|
||||
"CMAKE_INSTALL_PREFIX": "${sourceDir}/build/install"
|
||||
"CMAKE_INSTALL_PREFIX": "${sourceDir}/build/install",
|
||||
"DUSK_ENABLE_CODE_MODS": {
|
||||
"type": "BOOL",
|
||||
"value": true
|
||||
}
|
||||
},
|
||||
"vendor": {
|
||||
"microsoft.com/VisualStudioSettings/CMake/1.0": {
|
||||
@@ -239,6 +292,15 @@
|
||||
"macos-default"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "macos-default-debug-asan",
|
||||
"displayName": "macOS (default) Debug ASan",
|
||||
"inherits": [
|
||||
"debug",
|
||||
"macos-default",
|
||||
"asan"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "macos-default-relwithdebinfo",
|
||||
"displayName": "macOS (default) RelWithDebInfo",
|
||||
@@ -344,6 +406,10 @@
|
||||
"type": "BOOL",
|
||||
"value": false
|
||||
},
|
||||
"DUSK_ENABLE_CODE_MODS": {
|
||||
"type": "BOOL",
|
||||
"value": true
|
||||
},
|
||||
"CMAKE_DISABLE_FIND_PACKAGE_PkgConfig": {
|
||||
"type": "BOOL",
|
||||
"value": true
|
||||
@@ -529,6 +595,12 @@
|
||||
"description": "Linux (default) debug build",
|
||||
"displayName": "Linux (default) Debug"
|
||||
},
|
||||
{
|
||||
"name": "linux-default-debug-asan",
|
||||
"configurePreset": "linux-default-debug-asan",
|
||||
"description": "Linux (default) debug build with AddressSanitizer",
|
||||
"displayName": "Linux (default) Debug ASan"
|
||||
},
|
||||
{
|
||||
"name": "linux-default-relwithdebinfo",
|
||||
"configurePreset": "linux-default-relwithdebinfo",
|
||||
@@ -541,6 +613,12 @@
|
||||
"description": "Linux (Clang) debug build",
|
||||
"displayName": "Linux (Clang) Debug"
|
||||
},
|
||||
{
|
||||
"name": "linux-clang-debug-asan",
|
||||
"configurePreset": "linux-clang-debug-asan",
|
||||
"description": "Linux (Clang) debug build with AddressSanitizer",
|
||||
"displayName": "Linux (Clang) Debug ASan"
|
||||
},
|
||||
{
|
||||
"name": "linux-clang-relwithdebinfo",
|
||||
"configurePreset": "linux-clang-relwithdebinfo",
|
||||
@@ -553,6 +631,12 @@
|
||||
"description": "macOS debug build",
|
||||
"displayName": "macOS Debug"
|
||||
},
|
||||
{
|
||||
"name": "macos-default-debug-asan",
|
||||
"configurePreset": "macos-default-debug-asan",
|
||||
"description": "macOS debug build with AddressSanitizer",
|
||||
"displayName": "macOS Debug ASan"
|
||||
},
|
||||
{
|
||||
"name": "macos-default-relwithdebinfo",
|
||||
"configurePreset": "macos-default-relwithdebinfo",
|
||||
@@ -610,6 +694,12 @@
|
||||
"description": "Windows (MSVC) debug build",
|
||||
"displayName": "Windows (MSVC) Debug"
|
||||
},
|
||||
{
|
||||
"name": "windows-msvc-debug-asan",
|
||||
"configurePreset": "windows-msvc-debug-asan",
|
||||
"description": "Windows (MSVC) debug build with AddressSanitizer",
|
||||
"displayName": "Windows (MSVC) Debug ASan"
|
||||
},
|
||||
{
|
||||
"name": "windows-msvc-relwithdebinfo",
|
||||
"configurePreset": "windows-msvc-relwithdebinfo",
|
||||
|
||||
@@ -20,31 +20,17 @@ It aims to be as accurate as possible to the original while also providing new o
|
||||
> Dusklight does *not* provide any copyrighted assets. You must provide your own copy of the original game.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> At a minimum, Dusklight requires a GPU with support for either D3D12, Vulkan, or Metal. Your experience with specific hardware, operating systems, and drivers may vary. In particular, older Intel iGPUs have a high likelihood of incompatibility. We are also aware of a number of issues on devices with Adreno GPUs and are working to resolve them.
|
||||
> At a minimum, Dusklight requires a GPU with support for D3D12, Vulkan 1.1+, or Metal. For older devices, best-effort support is provided for D3D11 and OpenGL ES (Android), but will not achieve full accuracy or performance. Your experience with specific hardware, operating systems, and drivers may vary.
|
||||
|
||||
### 1. Dump your game
|
||||
|
||||
You must dump your own copy of the game, please see [this article](https://wiki.dolphin-emu.org/index.php?title=Ripping_Games) for instructions. After dumping, you can use a program like [Dolphin](https://dolphin-emu.org/) or [nodtool](https://github.com/encounter/nod/releases) to convert the `.iso` to a `.rvz` to save space.
|
||||
You must dump your own copy of the game. Please see [this article](https://wiki.dolphin-emu.org/index.php?title=Ripping_Games) for instructions. After dumping, you can use a program like [Dolphin](https://dolphin-emu.org/) or [nodtool](https://github.com/encounter/nod/releases) to convert the `.iso` to `.rvz` to save space.
|
||||
|
||||
Currently, only the GameCube USA and EUR releases are supported. Support for other versions of the game is planned in the future.
|
||||
|
||||
### 2. Download [Dusklight](https://github.com/TwilitRealm/dusklight/releases)
|
||||
### 2. Install Dusklight
|
||||
|
||||
### 3. Setup the game
|
||||
**Windows / macOS / Linux**
|
||||
- Extract the .zip file
|
||||
- Launch Dusklight
|
||||
- Press **Select Disc Image** and provide the path to your supported game dump
|
||||
- Press **Play**!
|
||||
|
||||
**iOS**
|
||||
- Follow the [iOS setup guide](docs/ios-install-altstore.md)
|
||||
|
||||
**Android**
|
||||
- Install the Dusklight APK
|
||||
- Launch Dusklight
|
||||
- Press **Select Disc Image** and provide the path to your supported game dump
|
||||
- Press **Play**!
|
||||
Visit the [official installation guide](https://twilitrealm.dev/install/) for full instructions.
|
||||
|
||||
# Building
|
||||
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
# Version detection shared by the main build and the mod SDK (sdk/CMakeLists.txt)
|
||||
include_guard(GLOBAL)
|
||||
|
||||
get_filename_component(_DUSK_VERSION_ROOT "${CMAKE_CURRENT_LIST_DIR}/.." ABSOLUTE)
|
||||
|
||||
set(DUSK_SENTRY_DSN "" CACHE STRING "Sentry DSN")
|
||||
set(DUSK_SENTRY_ENVIRONMENT "development" CACHE STRING "Sentry environment")
|
||||
|
||||
set(DUSK_VERSION_OVERRIDE "" CACHE STRING "Override version string (skips git detection and format validation)")
|
||||
|
||||
macro(detect_version)
|
||||
if (DUSK_VERSION_OVERRIDE)
|
||||
set(DUSK_WC_DESCRIBE "${DUSK_VERSION_OVERRIDE}")
|
||||
set(DUSK_VERSION_STRING "0.0.0.0")
|
||||
set(DUSK_SHORT_VERSION_STRING "0.0.0")
|
||||
set(DUSK_VERSION_CODE "1")
|
||||
set(DUSK_WC_REVISION "")
|
||||
set(DUSK_WC_BRANCH "")
|
||||
set(DUSK_WC_DATE "")
|
||||
message(STATUS "Dusklight version overridden to ${DUSK_WC_DESCRIBE}")
|
||||
else ()
|
||||
# obtain revision info from git
|
||||
find_package(Git)
|
||||
if (GIT_FOUND)
|
||||
# make sure version information gets re-run when the current Git HEAD changes
|
||||
execute_process(WORKING_DIRECTORY ${_DUSK_VERSION_ROOT} COMMAND ${GIT_EXECUTABLE} rev-parse --git-path HEAD
|
||||
OUTPUT_VARIABLE dusk_git_head_filename
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
get_filename_component(dusk_git_head_filename "${dusk_git_head_filename}" ABSOLUTE BASE_DIR "${_DUSK_VERSION_ROOT}")
|
||||
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${dusk_git_head_filename}")
|
||||
|
||||
execute_process(WORKING_DIRECTORY ${_DUSK_VERSION_ROOT} COMMAND ${GIT_EXECUTABLE} rev-parse --symbolic-full-name HEAD
|
||||
OUTPUT_VARIABLE dusk_git_head_symbolic
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
execute_process(WORKING_DIRECTORY ${_DUSK_VERSION_ROOT}
|
||||
COMMAND ${GIT_EXECUTABLE} rev-parse --git-path ${dusk_git_head_symbolic}
|
||||
OUTPUT_VARIABLE dusk_git_head_symbolic_filename
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
get_filename_component(dusk_git_head_symbolic_filename "${dusk_git_head_symbolic_filename}" ABSOLUTE BASE_DIR "${_DUSK_VERSION_ROOT}")
|
||||
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${dusk_git_head_symbolic_filename}")
|
||||
|
||||
# defines DUSK_WC_REVISION
|
||||
execute_process(WORKING_DIRECTORY ${_DUSK_VERSION_ROOT} COMMAND ${GIT_EXECUTABLE} rev-parse HEAD
|
||||
OUTPUT_VARIABLE DUSK_WC_REVISION
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
# defines DUSK_WC_DESCRIBE
|
||||
execute_process(WORKING_DIRECTORY ${_DUSK_VERSION_ROOT} COMMAND ${GIT_EXECUTABLE} describe --tags --long --dirty --match "v*"
|
||||
OUTPUT_VARIABLE DUSK_WC_DESCRIBE
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
|
||||
# remove the git hash, then collapse a clean "-0" suffix only
|
||||
string(REGEX REPLACE "-[^-]+(-dirty|)$" "\\1" DUSK_WC_DESCRIBE "${DUSK_WC_DESCRIBE}")
|
||||
string(REGEX REPLACE "-0$" "" DUSK_WC_DESCRIBE "${DUSK_WC_DESCRIBE}")
|
||||
|
||||
# defines DUSK_WC_BRANCH
|
||||
execute_process(WORKING_DIRECTORY ${_DUSK_VERSION_ROOT} COMMAND ${GIT_EXECUTABLE} rev-parse --abbrev-ref HEAD
|
||||
OUTPUT_VARIABLE DUSK_WC_BRANCH
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
# defines DUSK_WC_DATE
|
||||
execute_process(WORKING_DIRECTORY ${_DUSK_VERSION_ROOT} COMMAND ${GIT_EXECUTABLE} log -1 --format=%ad
|
||||
OUTPUT_VARIABLE DUSK_WC_DATE
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
else ()
|
||||
message(STATUS "Unable to find git, commit information will not be available")
|
||||
endif ()
|
||||
|
||||
if (DUSK_WC_DESCRIBE MATCHES "^v([0-9]+)\\.([0-9]+)\\.([0-9]+)([-+].*)?$")
|
||||
set(DUSK_SHORT_VERSION_STRING "${CMAKE_MATCH_1}.${CMAKE_MATCH_2}.${CMAKE_MATCH_3}")
|
||||
set(_ver_major ${CMAKE_MATCH_1})
|
||||
set(_ver_minor ${CMAKE_MATCH_2})
|
||||
set(_ver_patch ${CMAKE_MATCH_3})
|
||||
set(DUSK_VERSION_TWEAK "0")
|
||||
if (DUSK_WC_DESCRIBE MATCHES "^v[0-9]+\\.[0-9]+\\.[0-9]+-([0-9]+)(-dirty)?$")
|
||||
set(DUSK_VERSION_TWEAK "${CMAKE_MATCH_1}")
|
||||
elseif (DUSK_WC_DESCRIBE MATCHES "^v[0-9]+\\.[0-9]+\\.[0-9]+-[0-9A-Za-z.-]+-([0-9]+)(-dirty)?$")
|
||||
set(DUSK_VERSION_TWEAK "${CMAKE_MATCH_1}")
|
||||
endif ()
|
||||
set(DUSK_VERSION_STRING "${DUSK_SHORT_VERSION_STRING}.${DUSK_VERSION_TWEAK}")
|
||||
if (DUSK_VERSION_TWEAK GREATER 999)
|
||||
set(_tweak 999)
|
||||
else ()
|
||||
set(_tweak ${DUSK_VERSION_TWEAK})
|
||||
endif ()
|
||||
# encoding: major*1e7 + minor*1e5 + patch*1e3 + tweak; collision-free for major<210, minor<100, patch<100, tweak<=999
|
||||
math(EXPR DUSK_VERSION_CODE
|
||||
"${_ver_major} * 10000000 + ${_ver_minor} * 100000 + ${_ver_patch} * 1000 + ${_tweak}")
|
||||
else ()
|
||||
set(DUSK_WC_DESCRIBE "UNKNOWN-VERSION")
|
||||
set(DUSK_VERSION_STRING "0.0.0.0")
|
||||
set(DUSK_SHORT_VERSION_STRING "0.0.0")
|
||||
set(DUSK_VERSION_CODE "1")
|
||||
endif ()
|
||||
|
||||
endif ()
|
||||
|
||||
# Add version information to CI environment variables
|
||||
if (DEFINED ENV{GITHUB_ENV})
|
||||
file(APPEND "$ENV{GITHUB_ENV}" "DUSK_VERSION=${DUSK_WC_DESCRIBE}\n")
|
||||
file(APPEND "$ENV{GITHUB_ENV}" "DUSK_VERSION_CODE=${DUSK_VERSION_CODE}\n")
|
||||
endif ()
|
||||
message(STATUS "Dusklight version set to ${DUSK_WC_DESCRIBE}")
|
||||
endmacro()
|
||||
|
||||
# Sets PLATFORM_NAME and configures version.h into the caller's binary dir.
|
||||
macro(configure_version_header)
|
||||
if (CMAKE_SYSTEM_NAME STREQUAL Windows)
|
||||
set(PLATFORM_NAME win32)
|
||||
elseif (CMAKE_SYSTEM_NAME STREQUAL Darwin)
|
||||
if (IOS)
|
||||
set(PLATFORM_NAME ios)
|
||||
elseif (TVOS)
|
||||
set(PLATFORM_NAME tvos)
|
||||
else ()
|
||||
set(PLATFORM_NAME macos)
|
||||
endif ()
|
||||
else ()
|
||||
string(TOLOWER CMAKE_SYSTEM_NAME PLATFORM_NAME)
|
||||
endif ()
|
||||
|
||||
configure_file(${_DUSK_VERSION_ROOT}/version.h.in ${CMAKE_CURRENT_BINARY_DIR}/version.h)
|
||||
endmacro()
|
||||
@@ -0,0 +1,27 @@
|
||||
# The game ABI surface shared by the main build and the mod SDK (sdk/CMakeLists.txt)
|
||||
include_guard(GLOBAL)
|
||||
|
||||
get_filename_component(_game_root "${CMAKE_CURRENT_LIST_DIR}/.." ABSOLUTE)
|
||||
|
||||
# PARTIAL_DEBUG makes debug and release share one struct/vtable ABI so a mod binary loads into either
|
||||
set(_game_compile_defs TARGET_PC=1 WIDESCREEN_SUPPORT=1 AVOID_UB=1 VERSION=0 MTX_USE_PS=1 PARTIAL_DEBUG=1)
|
||||
if (ANDROID)
|
||||
list(APPEND _game_compile_defs TARGET_ANDROID=1)
|
||||
endif ()
|
||||
|
||||
set(_game_include_dirs
|
||||
${_game_root}/include
|
||||
${_game_root}/src
|
||||
${_game_root}/assets/GZ2E01 # TODO: make this dynamic if needed?
|
||||
${_game_root}/libs/JSystem/include
|
||||
${_game_root}/libs
|
||||
${_game_root}/extern/aurora/include/dolphin
|
||||
${_game_root}/extern/aurora/include
|
||||
${_game_root}/extern
|
||||
${CMAKE_CURRENT_BINARY_DIR}
|
||||
)
|
||||
|
||||
# Interface target for mods and sub-projects to inherit game headers/defines.
|
||||
add_library(dusklight_game_headers INTERFACE)
|
||||
target_include_directories(dusklight_game_headers INTERFACE ${_game_include_dirs})
|
||||
target_compile_definitions(dusklight_game_headers INTERFACE ${_game_compile_defs})
|
||||
@@ -0,0 +1,279 @@
|
||||
# add_mod(<target> SOURCES <file>... MOD_JSON <mod.json> [RES_DIR <res>] [OVERLAY_DIR <overlay>]
|
||||
# [TEXTURES_DIR <textures>] [OUTPUT_DIR <dir>] [BUNDLE])
|
||||
set(DUSK_MODS_OUTPUT_DIR "${CMAKE_BINARY_DIR}/mods" CACHE PATH "Directory to write mod packages into")
|
||||
|
||||
function(_mod_lib_name out_var)
|
||||
set(_arch "${CMAKE_SYSTEM_PROCESSOR}")
|
||||
if (APPLE AND CMAKE_OSX_ARCHITECTURES)
|
||||
list(LENGTH CMAKE_OSX_ARCHITECTURES _count)
|
||||
if (_count GREATER 1)
|
||||
message(FATAL_ERROR "add_mod: universal binaries are not supported")
|
||||
endif ()
|
||||
set(_arch "${CMAKE_OSX_ARCHITECTURES}")
|
||||
endif ()
|
||||
string(TOLOWER "${CMAKE_SYSTEM_NAME}" _platform)
|
||||
string(TOLOWER "${_arch}" _arch)
|
||||
if (_arch MATCHES "^(i[3-6]86|x86)$")
|
||||
set(_arch "x86")
|
||||
endif ()
|
||||
if (WIN32)
|
||||
set(_ext ".dll")
|
||||
elseif (APPLE)
|
||||
set(_ext ".dylib")
|
||||
else ()
|
||||
set(_ext ".so")
|
||||
endif ()
|
||||
set(${out_var} "${_platform}-${_arch}${_ext}" PARENT_SCOPE)
|
||||
endfunction()
|
||||
|
||||
function(_mod_resolve_source_path out_var path)
|
||||
if (IS_ABSOLUTE "${path}")
|
||||
set(_path "${path}")
|
||||
else ()
|
||||
set(_path "${CMAKE_CURRENT_SOURCE_DIR}/${path}")
|
||||
endif ()
|
||||
set(${out_var} "${_path}" PARENT_SCOPE)
|
||||
endfunction()
|
||||
|
||||
function(_mod_collect_assets out_var dir)
|
||||
if (NOT IS_DIRECTORY "${dir}")
|
||||
message(FATAL_ERROR "add_mod: asset directory does not exist: ${dir}")
|
||||
endif ()
|
||||
|
||||
file(GLOB_RECURSE _files CONFIGURE_DEPENDS LIST_DIRECTORIES false "${dir}/*")
|
||||
set(${out_var} ${_files} PARENT_SCOPE)
|
||||
endfunction()
|
||||
|
||||
function(add_mod target_name)
|
||||
cmake_parse_arguments(ARG "BUNDLE" "MOD_JSON;RES_DIR;OVERLAY_DIR;TEXTURES_DIR;OUTPUT_DIR" "SOURCES" ${ARGN})
|
||||
if (NOT ARG_MOD_JSON)
|
||||
message(FATAL_ERROR "add_mod: MOD_JSON is required")
|
||||
endif ()
|
||||
_mod_resolve_source_path(_mod_json "${ARG_MOD_JSON}")
|
||||
if (NOT EXISTS "${_mod_json}")
|
||||
message(FATAL_ERROR "add_mod: MOD_JSON does not exist: ${_mod_json}")
|
||||
endif ()
|
||||
|
||||
add_library(${target_name} SHARED ${ARG_SOURCES})
|
||||
_mod_lib_name(_lib_name)
|
||||
set_target_properties(${target_name} PROPERTIES
|
||||
PREFIX ""
|
||||
C_VISIBILITY_PRESET hidden
|
||||
CXX_VISIBILITY_PRESET hidden
|
||||
VISIBILITY_INLINES_HIDDEN ON
|
||||
WINDOWS_EXPORT_ALL_SYMBOLS OFF)
|
||||
target_compile_features(${target_name} PRIVATE cxx_std_20)
|
||||
target_link_libraries(${target_name} PRIVATE dusklight_game_headers)
|
||||
|
||||
if (NOT TARGET dusklight)
|
||||
# Apply global compile options for out-of-tree mod builds
|
||||
if (CMAKE_SYSTEM_NAME STREQUAL Linux)
|
||||
target_compile_options(${target_name} PRIVATE
|
||||
-Wno-multichar -Wno-trigraphs -Wno-deprecated-declarations)
|
||||
elseif (APPLE)
|
||||
target_compile_options(${target_name} PRIVATE
|
||||
-Wno-declaration-after-statement -Wno-non-pod-varargs)
|
||||
elseif (MSVC)
|
||||
target_compile_options(${target_name} PRIVATE
|
||||
"$<$<COMPILE_LANGUAGE:C,CXX>:/bigobj>"
|
||||
"$<$<COMPILE_LANGUAGE:C,CXX>:/utf-8>")
|
||||
endif ()
|
||||
# Use signed char on ARM to match the original game (and x86)
|
||||
string(TOLOWER "${CMAKE_SYSTEM_PROCESSOR}" _mod_arch)
|
||||
if (_mod_arch MATCHES "^(arm|aarch64)" AND CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "GNU")
|
||||
target_compile_options(${target_name} PRIVATE -fsigned-char)
|
||||
endif ()
|
||||
endif ()
|
||||
|
||||
if (APPLE)
|
||||
# Game symbols resolve against the host executable at dlopen time.
|
||||
target_link_options(${target_name} PRIVATE -undefined dynamic_lookup)
|
||||
elseif (ANDROID)
|
||||
if (TARGET dusklight)
|
||||
target_link_libraries(${target_name} PRIVATE dusklight)
|
||||
elseif (DUSK_GAME_SOLIB)
|
||||
target_link_libraries(${target_name} PRIVATE "${DUSK_GAME_SOLIB}")
|
||||
else ()
|
||||
message(FATAL_ERROR "add_mod: DUSK_GAME_SOLIB is not set (libmain.so)")
|
||||
endif ()
|
||||
elseif (UNIX)
|
||||
target_link_options(${target_name} PRIVATE -Wl,--allow-shlib-undefined)
|
||||
elseif (WIN32)
|
||||
# Link against the generated import library (game ABI surface). Function calls
|
||||
# resolve through import thunks. Data is toolchain dependent:
|
||||
# - clang-cl: lld's mingw mode auto-imports data references, fixed up at load by
|
||||
# the mod SDK's pseudo-relocation runtime (pseudo_reloc.cpp).
|
||||
# - cl (MSVC): only DUSK_GAME_DATA-annotated data is reachable. Un-annotated
|
||||
# references fail to link.
|
||||
if (NOT DUSK_GAME_IMPLIB)
|
||||
message(FATAL_ERROR "add_mod: DUSK_GAME_IMPLIB is not set.")
|
||||
endif ()
|
||||
target_link_libraries(${target_name} PRIVATE "${DUSK_GAME_IMPLIB}")
|
||||
set_target_properties(${target_name} PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreadedDLL")
|
||||
target_compile_definitions(${target_name} PRIVATE _ITERATOR_DEBUG_LEVEL=0)
|
||||
if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
|
||||
target_compile_options(${target_name} PRIVATE "$<$<COMPILE_LANGUAGE:C,CXX>:/clang:-mcmodel=large>")
|
||||
target_sources(${target_name} PRIVATE "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../sdk/pseudo_reloc.cpp")
|
||||
# lld mingw mode rewrites /DEFAULTLIB directives to -l style and skips %LIB%, so
|
||||
# the CRT libraries and search paths are spelled out explicitly.
|
||||
target_link_options(${target_name} PRIVATE -lldmingw /nodefaultlib /INCREMENTAL:NO)
|
||||
target_link_libraries(${target_name} PRIVATE
|
||||
msvcrt.lib msvcprt.lib vcruntime.lib ucrt.lib
|
||||
oldnames.lib uuid.lib kernel32.lib user32.lib)
|
||||
set(_lib_dirs "$ENV{LIB}")
|
||||
if ("${_lib_dirs}" STREQUAL "")
|
||||
message(FATAL_ERROR "add_mod: %LIB% is empty; configure from a VS dev shell")
|
||||
endif ()
|
||||
foreach (_libdir IN LISTS _lib_dirs)
|
||||
target_link_options(${target_name} PRIVATE "/libpath:${_libdir}")
|
||||
endforeach ()
|
||||
endif ()
|
||||
endif ()
|
||||
|
||||
set(_output_dir "${DUSK_MODS_OUTPUT_DIR}")
|
||||
if (ARG_OUTPUT_DIR)
|
||||
set(_output_dir "${ARG_OUTPUT_DIR}")
|
||||
endif ()
|
||||
set(_stage "${CMAKE_CURRENT_BINARY_DIR}/${target_name}_stage")
|
||||
set(_out "${_output_dir}/${target_name}.dusk")
|
||||
|
||||
set(_zip_args "${_lib_name}" mod.json)
|
||||
set(_package_deps "${_mod_json}")
|
||||
set(_package_inputs "${_mod_json}")
|
||||
set(_extra_cmds "")
|
||||
if (ARG_RES_DIR)
|
||||
_mod_resolve_source_path(_res_dir "${ARG_RES_DIR}")
|
||||
_mod_collect_assets(_res_deps "${_res_dir}")
|
||||
list(APPEND _package_deps ${_res_deps})
|
||||
list(APPEND _package_inputs "${_res_dir}" ${_res_deps})
|
||||
list(APPEND _zip_args res)
|
||||
list(APPEND _extra_cmds COMMAND ${CMAKE_COMMAND} -E copy_directory
|
||||
"${_res_dir}" "${_stage}/res")
|
||||
endif ()
|
||||
if (ARG_OVERLAY_DIR)
|
||||
_mod_resolve_source_path(_overlay_dir "${ARG_OVERLAY_DIR}")
|
||||
_mod_collect_assets(_overlay_deps "${_overlay_dir}")
|
||||
list(APPEND _package_deps ${_overlay_deps})
|
||||
list(APPEND _package_inputs "${_overlay_dir}" ${_overlay_deps})
|
||||
list(APPEND _zip_args overlay)
|
||||
list(APPEND _extra_cmds COMMAND ${CMAKE_COMMAND} -E copy_directory
|
||||
"${_overlay_dir}" "${_stage}/overlay")
|
||||
endif ()
|
||||
if (ARG_TEXTURES_DIR)
|
||||
_mod_resolve_source_path(_textures_dir "${ARG_TEXTURES_DIR}")
|
||||
_mod_collect_assets(_textures_deps "${_textures_dir}")
|
||||
list(APPEND _package_deps ${_textures_deps})
|
||||
list(APPEND _package_inputs "${_textures_dir}" ${_textures_deps})
|
||||
list(APPEND _zip_args textures)
|
||||
list(APPEND _extra_cmds COMMAND ${CMAKE_COMMAND} -E copy_directory
|
||||
"${_textures_dir}" "${_stage}/textures")
|
||||
endif ()
|
||||
|
||||
set(_bundle_cmds "")
|
||||
if (ARG_BUNDLE AND TARGET dusklight)
|
||||
file(READ "${_mod_json}" _mod_json_text)
|
||||
string(JSON _mod_id GET "${_mod_json_text}" id)
|
||||
set_property(GLOBAL APPEND PROPERTY DUSK_BUNDLED_MOD_TARGETS "${target_name}")
|
||||
set_property(GLOBAL APPEND PROPERTY DUSK_BUNDLED_MOD_IDS "${_mod_id}")
|
||||
set_property(GLOBAL APPEND PROPERTY DUSK_BUNDLED_MOD_STAGES "${_stage}")
|
||||
set_property(GLOBAL APPEND PROPERTY DUSK_BUNDLED_MOD_PACKAGES "${_out}")
|
||||
set_property(GLOBAL APPEND PROPERTY DUSK_BUNDLED_MOD_LIB_NAMES "${_lib_name}")
|
||||
set(_bundle_cmds
|
||||
COMMAND ${CMAKE_COMMAND} -E make_directory "${CMAKE_BINARY_DIR}/bundled_mods"
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_if_different "${_out}" "${CMAKE_BINARY_DIR}/bundled_mods/${target_name}.dusk")
|
||||
endif ()
|
||||
|
||||
set(_package_target "${target_name}_package")
|
||||
set(_package_inputs_file "${CMAKE_CURRENT_BINARY_DIR}/${target_name}_package_inputs.txt")
|
||||
list(SORT _package_inputs)
|
||||
set(_package_inputs_text "")
|
||||
foreach (_package_input IN LISTS _package_inputs)
|
||||
string(APPEND _package_inputs_text "${_package_input}\n")
|
||||
endforeach ()
|
||||
file(GENERATE OUTPUT "${_package_inputs_file}" CONTENT "${_package_inputs_text}")
|
||||
add_custom_command(OUTPUT "${_out}"
|
||||
COMMAND ${CMAKE_COMMAND} -E rm -rf "${_stage}"
|
||||
COMMAND ${CMAKE_COMMAND} -E make_directory "${_stage}" "${_output_dir}"
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_if_different "$<TARGET_FILE:${target_name}>" "${_stage}/${_lib_name}"
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_if_different "${_mod_json}" "${_stage}/mod.json"
|
||||
${_extra_cmds}
|
||||
COMMAND ${CMAKE_COMMAND} -E chdir "${_stage}" ${CMAKE_COMMAND} -E tar cvf "${_out}" --format=zip ${_zip_args}
|
||||
${_bundle_cmds}
|
||||
DEPENDS ${target_name} ${_package_deps} "${_package_inputs_file}"
|
||||
COMMENT "Packaging ${target_name} -> ${_out}"
|
||||
COMMAND_EXPAND_LISTS
|
||||
VERBATIM
|
||||
)
|
||||
add_custom_target(${_package_target} ALL DEPENDS "${_out}")
|
||||
if (TARGET dusklight_mods)
|
||||
add_dependencies(dusklight_mods ${_package_target})
|
||||
endif ()
|
||||
endfunction()
|
||||
|
||||
# Install rules for BUNDLE mods.
|
||||
# - Windows: the .dusk archives into <install>/mods (the loader extracts native libs to the
|
||||
# user cache).
|
||||
# - Linux: pre-extracted stage dirs into <install>/mods so native libs dlopen in place from
|
||||
# read-only installs.
|
||||
# - macOS: pre-extracted stage dirs into the installed app's Contents/Resources/mods, dylibs
|
||||
# ad-hoc signed in place, then the whole bundle re-signed.
|
||||
# - iOS/tvOS: assets into <app>/mods/<id> and the dylib into Frameworks/<id>.dylib.
|
||||
# - Android: nothing here; gradle packs ${CMAKE_BINARY_DIR}/bundled_mods into APK assets.
|
||||
function(install_bundled_mods)
|
||||
get_property(_targets GLOBAL PROPERTY DUSK_BUNDLED_MOD_TARGETS)
|
||||
if (NOT _targets OR ANDROID)
|
||||
return ()
|
||||
endif ()
|
||||
get_property(_ids GLOBAL PROPERTY DUSK_BUNDLED_MOD_IDS)
|
||||
get_property(_stages GLOBAL PROPERTY DUSK_BUNDLED_MOD_STAGES)
|
||||
get_property(_lib_names GLOBAL PROPERTY DUSK_BUNDLED_MOD_LIB_NAMES)
|
||||
list(LENGTH _targets _count)
|
||||
math(EXPR _last "${_count} - 1")
|
||||
|
||||
if (APPLE)
|
||||
get_target_property(_app_name dusklight OUTPUT_NAME)
|
||||
if (NOT _app_name)
|
||||
set(_app_name dusklight)
|
||||
endif ()
|
||||
set(_bundle_dir "${CMAKE_INSTALL_PREFIX}/${_app_name}.app")
|
||||
if (IOS OR TVOS)
|
||||
foreach (_i RANGE ${_last})
|
||||
list(GET _targets ${_i} _target)
|
||||
list(GET _ids ${_i} _id)
|
||||
list(GET _stages ${_i} _stage)
|
||||
list(GET _lib_names ${_i} _lib_name)
|
||||
install(DIRECTORY "${_stage}/" DESTINATION "${_bundle_dir}/mods/${_id}"
|
||||
PATTERN "${_lib_name}" EXCLUDE)
|
||||
install(PROGRAMS "$<TARGET_FILE:${_target}>"
|
||||
DESTINATION "${_bundle_dir}/Frameworks" RENAME "${_id}.dylib")
|
||||
endforeach ()
|
||||
else ()
|
||||
foreach (_i RANGE ${_last})
|
||||
list(GET _ids ${_i} _id)
|
||||
list(GET _stages ${_i} _stage)
|
||||
list(GET _lib_names ${_i} _lib_name)
|
||||
install(DIRECTORY "${_stage}/" DESTINATION "${_bundle_dir}/Contents/Resources/mods/${_id}")
|
||||
install(CODE "execute_process(COMMAND /usr/bin/codesign --force --sign - \"${_bundle_dir}/Contents/Resources/mods/${_id}/${_lib_name}\" COMMAND_ERROR_IS_FATAL ANY)")
|
||||
endforeach ()
|
||||
install(CODE "execute_process(COMMAND /usr/bin/codesign --force --sign - --entitlements \"${DUSK_ENTITLEMENTS}\" \"${_bundle_dir}\" COMMAND_ERROR_IS_FATAL ANY)")
|
||||
endif ()
|
||||
return ()
|
||||
endif ()
|
||||
|
||||
if (DUSK_PACKAGE_INSTALL)
|
||||
set(_mods_dest "${CMAKE_INSTALL_DATAROOTDIR}/dusklight/mods")
|
||||
else ()
|
||||
set(_mods_dest "${CMAKE_INSTALL_PREFIX}/mods")
|
||||
endif ()
|
||||
if (WIN32)
|
||||
foreach (_target IN LISTS _targets)
|
||||
install(FILES "${CMAKE_BINARY_DIR}/bundled_mods/${_target}.dusk" DESTINATION "${_mods_dest}")
|
||||
endforeach ()
|
||||
else ()
|
||||
foreach (_i RANGE ${_last})
|
||||
list(GET _ids ${_i} _id)
|
||||
list(GET _stages ${_i} _stage)
|
||||
install(DIRECTORY "${_stage}/" DESTINATION "${_mods_dest}/${_id}")
|
||||
endforeach ()
|
||||
endif ()
|
||||
endfunction()
|
||||
@@ -0,0 +1,13 @@
|
||||
# Patches capstone's CMakeLists.txt for compatibility with CMake >= 4.0:
|
||||
# - Bumps cmake_minimum_required to 3.10 (CMake >= 4.0 dropped < 3.5 support; < 3.10 warns)
|
||||
# - Removes cmake_policy(SET CMP0048 OLD) (rejected by CMake >= 3.27)
|
||||
file(READ "${DIR}/CMakeLists.txt" _content)
|
||||
string(REGEX REPLACE
|
||||
"cmake_minimum_required[ \t]*\\([ \t]*VERSION[ \t]+[0-9]+\\.[0-9]+(\\.[0-9]+)?[ \t]*\\)"
|
||||
"cmake_minimum_required(VERSION 3.10)"
|
||||
_content "${_content}")
|
||||
string(REGEX REPLACE
|
||||
"cmake_policy[ \t]*\\([ \t]*SET[ \t]+CMP0048[ \t]+OLD[ \t]*\\)"
|
||||
"# cmake_policy(SET CMP0048 OLD)"
|
||||
_content "${_content}")
|
||||
file(WRITE "${DIR}/CMakeLists.txt" "${_content}")
|
||||
@@ -0,0 +1,60 @@
|
||||
file(READ "${SOURCE_DIR}/cmake/capstone.cmake.in" _content)
|
||||
|
||||
# Insert PATCH_COMMAND before CONFIGURE_COMMAND in the ExternalProject_Add.
|
||||
# Bracket args prevent cmake from substituting ${...} while writing this file.
|
||||
string(REPLACE
|
||||
" CONFIGURE_COMMAND \"\""
|
||||
[=[ PATCH_COMMAND "${CMAKE_COMMAND}" -DDIR=${CMAKE_CURRENT_BINARY_DIR}/capstone-src -P "${CAPSTONE_FIX_SCRIPT}"
|
||||
CONFIGURE_COMMAND ""]=]
|
||||
_content "${_content}")
|
||||
|
||||
file(WRITE "${SOURCE_DIR}/cmake/capstone.cmake.in" "${_content}")
|
||||
|
||||
file(READ "${SOURCE_DIR}/src/funchook_unix.c" _unix_content)
|
||||
|
||||
# macOS rejects the POSIX mprotect RWX/RW transition for executable image pages on arm64.
|
||||
# Use Mach VM_PROT_COPY for the short patch window, then restore RX permissions.
|
||||
if (NOT _unix_content MATCHES "VM_PROT_READ \\| VM_PROT_WRITE \\| VM_PROT_COPY")
|
||||
string(REPLACE
|
||||
[=[ rv = mprotect(mstate->addr, mstate->size, prot);]=]
|
||||
[=[#ifdef __APPLE__
|
||||
kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)mstate->addr,
|
||||
(vm_size_t)mstate->size, FALSE,
|
||||
VM_PROT_READ | VM_PROT_WRITE | VM_PROT_COPY);
|
||||
if (kr == KERN_SUCCESS) {
|
||||
funchook_log(funchook, " unprotect memory %p (size=%"PRIuPTR", prot=read,write,copy) <- %p (size=%"PRIuPTR")\n",
|
||||
mstate->addr, mstate->size, start, len);
|
||||
return 0;
|
||||
}
|
||||
funchook_set_error_message(funchook, "Failed to unprotect memory %p (size=%"PRIuPTR", prot=read,write,copy) <- %p (size=%"PRIuPTR", error=%s)",
|
||||
mstate->addr, mstate->size, start, len,
|
||||
mach_error_string(kr));
|
||||
return FUNCHOOK_ERROR_MEMORY_FUNCTION;
|
||||
#endif
|
||||
rv = mprotect(mstate->addr, mstate->size, prot);]=]
|
||||
_unix_content "${_unix_content}")
|
||||
|
||||
string(REPLACE
|
||||
[=[ char errbuf[128];
|
||||
int rv = mprotect(mstate->addr, mstate->size, PROT_READ | PROT_EXEC);]=]
|
||||
[=[ char errbuf[128];
|
||||
#ifdef __APPLE__
|
||||
kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)mstate->addr,
|
||||
(vm_size_t)mstate->size, FALSE,
|
||||
VM_PROT_READ | VM_PROT_EXECUTE);
|
||||
|
||||
if (kr == KERN_SUCCESS) {
|
||||
funchook_log(funchook, " protect memory %p (size=%"PRIuPTR", prot=read,exec)\n",
|
||||
mstate->addr, mstate->size);
|
||||
return 0;
|
||||
}
|
||||
funchook_set_error_message(funchook, "Failed to protect memory %p (size=%"PRIuPTR", prot=read,exec, error=%s)",
|
||||
mstate->addr, mstate->size,
|
||||
mach_error_string(kr));
|
||||
return FUNCHOOK_ERROR_MEMORY_FUNCTION;
|
||||
#endif
|
||||
int rv = mprotect(mstate->addr, mstate->size, PROT_READ | PROT_EXEC);]=]
|
||||
_unix_content "${_unix_content}")
|
||||
endif ()
|
||||
|
||||
file(WRITE "${SOURCE_DIR}/src/funchook_unix.c" "${_unix_content}")
|
||||
@@ -0,0 +1,125 @@
|
||||
include_guard(GLOBAL)
|
||||
|
||||
get_filename_component(_SYMBOL_MANIFEST_CMAKE_DIR "${CMAKE_CURRENT_LIST_FILE}" DIRECTORY)
|
||||
|
||||
set(_SYMGEN_VERSION "1.1.0")
|
||||
set(_SYMGEN_RELEASE_BASE_URL "https://github.com/encounter/symgen/releases/download/v${_SYMGEN_VERSION}")
|
||||
set(SYMGEN_PATH "" CACHE FILEPATH "Path to a symgen executable; empty downloads the pinned release")
|
||||
mark_as_advanced(SYMGEN_PATH)
|
||||
|
||||
function(symgen_host_asset out_name)
|
||||
string(TOLOWER "${CMAKE_HOST_SYSTEM_PROCESSOR}" _host_processor)
|
||||
set(_asset "")
|
||||
|
||||
if (CMAKE_HOST_SYSTEM_NAME STREQUAL "Darwin")
|
||||
if (_host_processor MATCHES "^(arm64|aarch64)$")
|
||||
set(_asset "symgen-macos-arm64")
|
||||
elseif (_host_processor MATCHES "^(x86_64|amd64)$")
|
||||
set(_asset "symgen-macos-x86_64")
|
||||
endif ()
|
||||
elseif (CMAKE_HOST_SYSTEM_NAME STREQUAL "Linux")
|
||||
if (_host_processor MATCHES "^(aarch64|arm64)$")
|
||||
set(_asset "symgen-linux-aarch64")
|
||||
elseif (_host_processor MATCHES "^(x86_64|amd64)$")
|
||||
set(_asset "symgen-linux-x86_64")
|
||||
elseif (_host_processor MATCHES "^(i[3-6]86|x86)$")
|
||||
set(_asset "symgen-linux-i686")
|
||||
endif ()
|
||||
elseif (CMAKE_HOST_WIN32)
|
||||
if (_host_processor MATCHES "^(arm64|aarch64)$")
|
||||
set(_asset "symgen-windows-arm64.exe")
|
||||
elseif (_host_processor MATCHES "^(x86_64|amd64)$")
|
||||
set(_asset "symgen-windows-x86_64.exe")
|
||||
elseif (_host_processor MATCHES "^(i[3-6]86|x86)$")
|
||||
set(_asset "symgen-windows-x86.exe")
|
||||
endif ()
|
||||
endif ()
|
||||
|
||||
set(${out_name} "${_asset}" PARENT_SCOPE)
|
||||
endfunction()
|
||||
|
||||
function(ensure_symgen required)
|
||||
if (TARGET symgen)
|
||||
return()
|
||||
endif ()
|
||||
|
||||
if (SYMGEN_PATH)
|
||||
get_filename_component(_symgen "${SYMGEN_PATH}" ABSOLUTE)
|
||||
if (NOT EXISTS "${_symgen}")
|
||||
if (required)
|
||||
message(FATAL_ERROR "symgen: SYMGEN_PATH does not exist: ${_symgen}")
|
||||
endif ()
|
||||
message(STATUS "symgen: SYMGEN_PATH does not exist, symbol manifest generation "
|
||||
"skipped (by-name hook resolution will be unavailable)")
|
||||
return()
|
||||
endif ()
|
||||
else ()
|
||||
symgen_host_asset(_asset)
|
||||
if (_asset STREQUAL "")
|
||||
if (required)
|
||||
message(FATAL_ERROR "symgen: no prebuilt binary for host "
|
||||
"${CMAKE_HOST_SYSTEM_NAME}/${CMAKE_HOST_SYSTEM_PROCESSOR} "
|
||||
"(configure with -DDUSK_ENABLE_CODE_MODS=OFF)")
|
||||
endif ()
|
||||
message(STATUS "symgen: no prebuilt binary for host "
|
||||
"${CMAKE_HOST_SYSTEM_NAME}/${CMAKE_HOST_SYSTEM_PROCESSOR}; "
|
||||
"symbol manifest generation skipped (by-name hook resolution will be unavailable)")
|
||||
return()
|
||||
endif ()
|
||||
|
||||
set(_symgen_dir "${CMAKE_BINARY_DIR}/_deps/symgen")
|
||||
set(_symgen "${_symgen_dir}/${_asset}")
|
||||
set(_url "${_SYMGEN_RELEASE_BASE_URL}/${_asset}")
|
||||
message(STATUS "dusklight: Fetching symgen ${_SYMGEN_VERSION} (${_asset})")
|
||||
file(MAKE_DIRECTORY "${_symgen_dir}")
|
||||
file(DOWNLOAD "${_url}" "${_symgen}"
|
||||
TLS_VERIFY ON
|
||||
STATUS _download_status
|
||||
SHOW_PROGRESS)
|
||||
list(GET _download_status 0 _download_code)
|
||||
if (NOT _download_code EQUAL 0)
|
||||
list(GET _download_status 1 _download_message)
|
||||
file(REMOVE "${_symgen}")
|
||||
if (required)
|
||||
message(FATAL_ERROR "symgen: failed to download ${_url}: ${_download_message}")
|
||||
endif ()
|
||||
message(STATUS "symgen: failed to download ${_url}: ${_download_message}; "
|
||||
"symbol manifest generation skipped (by-name hook resolution will be unavailable)")
|
||||
return()
|
||||
endif ()
|
||||
if (NOT CMAKE_HOST_WIN32)
|
||||
file(CHMOD "${_symgen}" PERMISSIONS
|
||||
OWNER_READ OWNER_WRITE OWNER_EXECUTE
|
||||
GROUP_READ GROUP_EXECUTE
|
||||
WORLD_READ WORLD_EXECUTE)
|
||||
endif ()
|
||||
endif ()
|
||||
|
||||
add_custom_target(symgen DEPENDS "${_symgen}")
|
||||
set(SYMGEN_EXE "${_symgen}" CACHE INTERNAL "symgen executable" FORCE)
|
||||
endfunction()
|
||||
|
||||
function(setup_symbol_manifest target)
|
||||
ensure_symgen(TRUE)
|
||||
if (NOT TARGET symgen)
|
||||
return()
|
||||
endif ()
|
||||
add_dependencies(${target} symgen)
|
||||
|
||||
if (WIN32)
|
||||
set(_input --pdb "$<TARGET_PDB_FILE:${target}>")
|
||||
set(_out "$<TARGET_FILE_DIR:${target}>/dusklight.symdb")
|
||||
else ()
|
||||
set(_input --binary "$<TARGET_FILE:${target}>")
|
||||
if (APPLE)
|
||||
set(_out "$<TARGET_BUNDLE_CONTENT_DIR:${target}>/Resources/dusklight.symdb")
|
||||
else ()
|
||||
set(_out "$<TARGET_FILE_DIR:${target}>/dusklight.symdb")
|
||||
endif ()
|
||||
endif ()
|
||||
|
||||
add_custom_command(TARGET ${target} POST_BUILD
|
||||
COMMAND "${SYMGEN_EXE}" manifest ${_input} --out "${_out}"
|
||||
COMMENT "Generating symbol manifest"
|
||||
VERBATIM)
|
||||
endfunction()
|
||||
@@ -0,0 +1,79 @@
|
||||
include_guard(GLOBAL)
|
||||
|
||||
get_filename_component(_DUSK_WINDOWS_EXPORTS_CMAKE_DIR "${CMAKE_CURRENT_LIST_FILE}" DIRECTORY)
|
||||
|
||||
# Windows mod linking: generate the curated export surface for the game executable and the
|
||||
# import library mods link against. symgen scans the built objects, filters by source, and
|
||||
# writes a .def used by the main link and import library generation.
|
||||
function(setup_windows_exports target)
|
||||
if (NOT CMAKE_SIZEOF_VOID_P EQUAL 8)
|
||||
message(WARNING "dusklight: Windows code-mod exports are x64-only for now; skipping")
|
||||
return()
|
||||
endif ()
|
||||
|
||||
include("${_DUSK_WINDOWS_EXPORTS_CMAKE_DIR}/SymbolManifest.cmake")
|
||||
ensure_symgen(TRUE)
|
||||
set(_symgen "${SYMGEN_EXE}")
|
||||
add_dependencies(${target} symgen)
|
||||
|
||||
set(_config_subdir "")
|
||||
if (CMAKE_CONFIGURATION_TYPES)
|
||||
set(_config_subdir "$<CONFIG>/")
|
||||
endif ()
|
||||
|
||||
set(_rsp_lines "$<TARGET_OBJECTS:${target}>")
|
||||
foreach (_lib IN LISTS JSYSTEM_LIBRARIES)
|
||||
list(APPEND _rsp_lines "$<TARGET_FILE:${_lib}>")
|
||||
endforeach ()
|
||||
list(JOIN _rsp_lines "\n" _rsp_content)
|
||||
set(_rsp "${CMAKE_BINARY_DIR}/${_config_subdir}dusklight_exports_input.rsp")
|
||||
file(GENERATE OUTPUT "${_rsp}" CONTENT "${_rsp_content}")
|
||||
|
||||
set(_sdk_args)
|
||||
foreach (_lib aurora_card aurora_core aurora_dvd aurora_gd aurora_gx aurora_mtx
|
||||
aurora_os aurora_pad aurora_si aurora_vi)
|
||||
if (TARGET ${_lib})
|
||||
list(APPEND _sdk_args --sdk-lib "$<TARGET_FILE:${_lib}>")
|
||||
endif ()
|
||||
endforeach ()
|
||||
|
||||
# Generate curated exports list from the main binary
|
||||
set(_def "${CMAKE_BINARY_DIR}/${_config_subdir}dusklight_exports.def")
|
||||
add_custom_command(TARGET ${target} PRE_LINK
|
||||
# TODO: src/dusk/ is NOT excluded: inline code in game headers
|
||||
# currently call into it (e.g. dusk::frame_interp::lookup_replacement).
|
||||
COMMAND "${_symgen}" def
|
||||
--rsp "${_rsp}"
|
||||
--out "${_def}"
|
||||
--exclude cmake_pch
|
||||
--exclude miniz
|
||||
--exclude asan_options
|
||||
--max-exports 58000
|
||||
${_sdk_args}
|
||||
COMMENT "Generating dusklight exports"
|
||||
VERBATIM)
|
||||
target_link_options(${target} PRIVATE "/DEF:${_def}")
|
||||
|
||||
# Generate import library for mods to link against.
|
||||
set(_implib "${CMAKE_BINARY_DIR}/${_config_subdir}dusklight_imports.lib")
|
||||
get_filename_component(_compiler_dir "${CMAKE_CXX_COMPILER}" DIRECTORY)
|
||||
find_program(DUSK_LLVM_DLLTOOL llvm-dlltool HINTS "${_compiler_dir}")
|
||||
if (DUSK_LLVM_DLLTOOL)
|
||||
set(_implib_cmd "${DUSK_LLVM_DLLTOOL}" -d "${_def}" -D dusklight.exe -m i386:x86-64
|
||||
-l "${_implib}")
|
||||
else ()
|
||||
set(_implib_cmd "${CMAKE_AR}" /nologo "/def:${_def}" /machine:x64 /name:dusklight.exe
|
||||
"/out:${_implib}")
|
||||
endif ()
|
||||
add_custom_command(TARGET ${target} POST_BUILD
|
||||
COMMAND ${_implib_cmd}
|
||||
BYPRODUCTS "${_implib}"
|
||||
COMMENT "Generating dusklight import library"
|
||||
VERBATIM)
|
||||
set(DUSK_GAME_IMPLIB "${_implib}" CACHE INTERNAL "Import library for Windows mod linking")
|
||||
set(DUSK_GAME_DEF "${_def}" CACHE INTERNAL "Curated export .def for the game executable")
|
||||
|
||||
# Ship the import library as sdk/dusklight.lib in the install tree: mods may use it to
|
||||
# compile against Dusklight without having to build the whole game. (See DUSK_GAME_IMPLIB)
|
||||
install(FILES "${_implib}" DESTINATION sdk RENAME dusklight.lib)
|
||||
endfunction()
|
||||
@@ -180,6 +180,7 @@ cmake --build --preset macos-default-relwithdebinfo
|
||||
Alternate presets available:
|
||||
|
||||
* `macos-default-debug`: Clang, Debug
|
||||
* `macos-default-debug-asan`: Clang, Debug, AddressSanitizer
|
||||
|
||||
**ninja (Linux)**
|
||||
|
||||
@@ -191,8 +192,10 @@ cmake --build --preset linux-default-relwithdebinfo
|
||||
Alternate presets available:
|
||||
|
||||
* `linux-default-debug`: GCC, Debug
|
||||
* `linux-default-debug-asan`: GCC, Debug, AddressSanitizer
|
||||
* `linux-clang-relwithdebinfo`: Clang, RelWithDebInfo
|
||||
* `linux-clang-debug`: Clang, Debug
|
||||
* `linux-clang-debug-asan`: Clang, Debug, AddressSanitizer
|
||||
|
||||
**ninja (Windows)**
|
||||
|
||||
@@ -204,6 +207,7 @@ cmake --build --preset windows-msvc-relwithdebinfo
|
||||
Alternate presets available:
|
||||
|
||||
* `windows-msvc-debug`: MSVC, Debug
|
||||
* `windows-msvc-debug-asan`: MSVC, Debug, AddressSanitizer
|
||||
* `windows-clang-relwithdebinfo`: Clang-cl, RelWithDebInfo
|
||||
* `windows-clang-debug`: Clang-cl, Debug
|
||||
|
||||
|
||||
+716
@@ -0,0 +1,716 @@
|
||||
# Dusklight Mod API
|
||||
|
||||
Mods are `.dusk` bundles: zip archives that can contain code (in the form of native libraries), resources, DVD overlay
|
||||
files, and texture replacements. Mods may be enabled, disabled and reloaded at runtime.
|
||||
|
||||
When code mods are loaded, they get dynamically linked by the operating system to the running game process. The mod
|
||||
exports lifecycle functions that Dusklight calls into (`mod_initialize`, `mod_update`, `mod_shutdown`), and the mod
|
||||
communicates with the host via **services**: plain C APIs, individually versioned. Dusklight exports several built-in
|
||||
services, and mods may export services of their own, permitting framework mods and cross-mod integration.
|
||||
|
||||
Beyond services, mods have full access to the original game's code: include game headers, call directly into any public
|
||||
function, read and write data fields, and hook the vast majority of game functions.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Getting Started](#getting-started)
|
||||
2. [mod.json](#modjson)
|
||||
3. [Anatomy of a Code Mod](#anatomy-of-a-code-mod)
|
||||
4. [Services](#services)
|
||||
5. [Built-in Services](#built-in-services)
|
||||
6. [Hooking Game Functions](#hooking-game-functions)
|
||||
7. [Asset Overlays](#asset-overlays)
|
||||
8. [Runtime Lifecycle](#runtime-lifecycle)
|
||||
9. [Error Handling](#error-handling)
|
||||
10. [Advanced: Exporting Services](#advanced-exporting-services)
|
||||
|
||||
---
|
||||
|
||||
## Getting Started
|
||||
|
||||
Fork the [mod template](../tools/mod_template/), a self-contained CMake project that uses the Dusklight mod SDK.
|
||||
|
||||
```
|
||||
my_mod/
|
||||
├── CMakeLists.txt
|
||||
├── mod.json
|
||||
├── src/mod.cpp
|
||||
├── res/ (optional bundled resources)
|
||||
├── overlay/ (optional game file overrides)
|
||||
└── textures/ (optional texture replacements)
|
||||
```
|
||||
|
||||
**CMakeLists.txt:**
|
||||
|
||||
```cmake
|
||||
cmake_minimum_required(VERSION 3.25)
|
||||
project(my_mod CXX)
|
||||
|
||||
set(DUSKLIGHT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/dusklight" CACHE PATH "Path to dusklight source root")
|
||||
add_subdirectory("${DUSKLIGHT_DIR}/sdk" dusklight-sdk EXCLUDE_FROM_ALL)
|
||||
|
||||
add_mod(my_mod
|
||||
SOURCES src/mod.cpp
|
||||
MOD_JSON mod.json
|
||||
RES_DIR res # optional
|
||||
OVERLAY_DIR overlay # optional
|
||||
TEXTURES_DIR textures # optional
|
||||
)
|
||||
```
|
||||
|
||||
Building produces `my_mod.dusk` in `build/<preset>/mods/` (configurable via the `DUSK_MODS_OUTPUT_DIR` cache variable).
|
||||
Dusklight searches a `mods/` directory next to the app in addition to the user directory, so a dev build launched from
|
||||
`build/<preset>/` picks these up automatically: rebuild, relaunch (or click Reload), done.
|
||||
|
||||
For a regular game install, copy the `.dusk` into the user mods folder:
|
||||
|
||||
- Windows: `%APPDATA%\TwilitRealm\Dusklight\mods`
|
||||
- Linux: `~/.local/share/TwilitRealm/Dusklight/mods`
|
||||
- macOS: `~/Library/Application Support/TwilitRealm/Dusklight/mods`
|
||||
|
||||
Passing `--mods <dir>` on the command line replaces the user directory with one of your choosing.
|
||||
|
||||
---
|
||||
|
||||
## mod.json
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "com.example.my_mod",
|
||||
"name": "My Mod",
|
||||
"version": "1.0.0",
|
||||
"author": "Your Name",
|
||||
"description": "A short description shown in the mod manager.",
|
||||
"icon": "res/my_icon.png",
|
||||
"banner": "res/my_banner.png"
|
||||
}
|
||||
```
|
||||
|
||||
`id` is required: a unique, stable identifier (reverse-DNS style; periods, underscores, and alphanumerics). Everything
|
||||
else is optional but recommended.
|
||||
|
||||
`icon` and `banner` are bundle-relative paths to PNG images for the in-game mod manager: the square icon (e.g.
|
||||
512x512), the banner (~3.5:1). If omitted, `res/icon.png` and `res/banner.png` are used automatically when present.
|
||||
|
||||
---
|
||||
|
||||
## Anatomy of a Code Mod
|
||||
|
||||
```cpp
|
||||
#include "mods/service.hpp"
|
||||
#include "mods/svc/log.h"
|
||||
|
||||
DEFINE_MOD(); // once, in exactly one translation unit
|
||||
IMPORT_SERVICE(LogService, svc_log); // resolved by the loader before mod_initialize
|
||||
|
||||
extern "C" {
|
||||
|
||||
MOD_EXPORT ModResult mod_initialize(ModError* error) {
|
||||
svc_log->info(mod_ctx, "hello from my_mod");
|
||||
return MOD_OK;
|
||||
}
|
||||
|
||||
MOD_EXPORT ModResult mod_update(ModError* error) { // called every frame
|
||||
return MOD_OK;
|
||||
}
|
||||
|
||||
MOD_EXPORT ModResult mod_shutdown(ModError* error) {
|
||||
return MOD_OK;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
All three lifecycle exports are required. `mod_ctx` is your mod's identity token, set by the loader before
|
||||
`mod_initialize` runs. Pass it as the first argument to every service call.
|
||||
|
||||
---
|
||||
|
||||
## Services
|
||||
|
||||
A service is a struct of C function pointers with a version header. You declare what you use at file scope, and the
|
||||
loader resolves it before your mod initializes:
|
||||
|
||||
```cpp
|
||||
IMPORT_SERVICE(LogService, svc_log); // required, any minor version
|
||||
IMPORT_SERVICE_VERSION(LogService, svc_log, 2); // required, minor version >= 2
|
||||
IMPORT_OPTIONAL_SERVICE(SomeService, svc_maybe); // may be null
|
||||
```
|
||||
|
||||
Each service is individually versioned, and there may be multiple major versions of a service provided at once,
|
||||
allowing backwards compatibility with older mods while still changing services fundamentally if necessary. A **major**
|
||||
bump is a breaking change, treated as a different service entirely. For **additive** changes, a service appends new
|
||||
functions to the end of the struct without breaking existing callers and simply bumps the minor version. Mods that
|
||||
want the newer functions may use `IMPORT_SERVICE_VERSION` to require that minor at **load time**, or `SERVICE_HAS` to
|
||||
check at **runtime** whether a specific function is available.
|
||||
|
||||
The contract (see `include/mods/api.h` for the full version):
|
||||
|
||||
- **A required import is guaranteed valid.** If the service is missing or too old, the mod fails to load with a clear
|
||||
error. No need to null check at call sites.
|
||||
- **Anything at or below the minor version you imported can be called unconditionally.**
|
||||
- Optional imports may be null; check once in `mod_initialize`.
|
||||
- Fields newer than your imported minor must be gated behind `SERVICE_HAS(service, ServiceType, field)` plus a null
|
||||
check.
|
||||
|
||||
---
|
||||
|
||||
## Built-in Services
|
||||
|
||||
### LogService (`mods/svc/log.h`)
|
||||
|
||||
```cpp
|
||||
IMPORT_SERVICE(LogService, svc_log);
|
||||
|
||||
svc_log->info(mod_ctx, "spawned the thing");
|
||||
svc_log->warn(mod_ctx, "that looks wrong");
|
||||
svc_log->error(mod_ctx, "very bad");
|
||||
svc_log->write(mod_ctx, LOG_LEVEL_DEBUG, "verbose details");
|
||||
```
|
||||
|
||||
Messages appear in the console prefixed with your mod ID. Messages are plain UTF-8 strings and are copied before the
|
||||
call returns; use `snprintf` or `fmt::format` for formatting.
|
||||
|
||||
### ResourceService (`mods/svc/resource.h`)
|
||||
|
||||
Loads files from the `res/` tree of your `.dusk` archive. Paths are relative to `res/` (pass `"config.txt"`, not
|
||||
`"res/config.txt"`); absolute paths and `..` are rejected.
|
||||
|
||||
```cpp
|
||||
IMPORT_SERVICE(ResourceService, svc_resource);
|
||||
|
||||
ResourceBuffer buf = RESOURCE_BUFFER_INIT;
|
||||
if (svc_resource->load(mod_ctx, "config.txt", &buf) == MOD_OK) {
|
||||
// buf.data / buf.size
|
||||
svc_resource->free(mod_ctx, &buf);
|
||||
}
|
||||
```
|
||||
|
||||
Missing files return `MOD_UNAVAILABLE`. Always `free` what you `load`. Note that the bundle is read-only; for writable
|
||||
storage, use the directory from `svc_host->mod_dir(mod_ctx)`.
|
||||
|
||||
### HostService (`mods/svc/host.h`)
|
||||
|
||||
Mod metadata and runtime interaction with the loader:
|
||||
|
||||
```cpp
|
||||
IMPORT_SERVICE(HostService, svc_host);
|
||||
|
||||
const char* id = svc_host->mod_id(mod_ctx);
|
||||
const char* dir = svc_host->mod_dir(mod_ctx); // writable per-mod directory
|
||||
svc_host->fail(mod_ctx, MOD_ERROR, "something unrecoverable happened"); // disables the mod
|
||||
```
|
||||
|
||||
`get_service`/`publish_service` provide dynamic service lookup; see [Advanced](#advanced-exporting-services).
|
||||
|
||||
**Lifecycle watches.** If your mod provides a service that hands out per-caller state (registrations, callbacks,
|
||||
handles), watch other mods' lifecycle and drop what you hold for a mod when it detaches.
|
||||
|
||||
```cpp
|
||||
IMPORT_SERVICE_VERSION(HostService, svc_host, 1);
|
||||
|
||||
void on_mod_lifecycle(ModContext* ctx, ModContext* subject, const char* subject_id,
|
||||
ModLifecycleEvent event, void* user_data) {
|
||||
if (event == MOD_LIFECYCLE_DETACHED) {
|
||||
drop_state_for(subject); // same ModContext* the subject passed into your service
|
||||
}
|
||||
}
|
||||
|
||||
uint64_t watch = 0;
|
||||
svc_host->watch_mod_lifecycle(mod_ctx, on_mod_lifecycle, nullptr, &watch);
|
||||
```
|
||||
|
||||
`MOD_LIFECYCLE_DETACHED` fires on the game thread at a lifecycle safe point, after the subject's `mod_shutdown` ran and
|
||||
every service dropped its state. For your own mod's teardown, use `mod_shutdown` instead.
|
||||
|
||||
### HookService (`mods/svc/hook.h`)
|
||||
|
||||
Installs hooks on game functions and resolves symbols by name. You'll rarely call it directly; use the typed helpers in
|
||||
`mods/hook.hpp` described in [Hooking Game Functions](#hooking-game-functions).
|
||||
|
||||
### OverlayService (`mods/svc/overlay.h`)
|
||||
|
||||
Registers DVD file overlays at runtime: the dynamic counterpart to the static `overlay/` directory (see
|
||||
[Asset Overlays](#asset-overlays)). Overlay a disc path with a file from your bundle, or with a caller-owned buffer
|
||||
(copied on registration):
|
||||
|
||||
```cpp
|
||||
IMPORT_SERVICE(OverlayService, svc_overlay);
|
||||
|
||||
OverlayHandle handle = 0;
|
||||
svc_overlay->add_file(mod_ctx, "/res/Msgus.arc", "res/replacement.arc", &handle);
|
||||
svc_overlay->add_buffer(mod_ctx, "/generated.txt", data, size, nullptr);
|
||||
svc_overlay->remove(mod_ctx, handle);
|
||||
```
|
||||
|
||||
`disc_path` must be absolute (leading `/`) and is matched against the disc case-insensitively. Paths that don't exist
|
||||
on the disc are added as new files. Changes are applied at the next frame boundary, and data the game already read
|
||||
stays in memory until the file is re-read: sometimes a scene reload, and in the worst case, a full restart.
|
||||
|
||||
See [Asset Overlays](#asset-overlays) for priority and conflict handling.
|
||||
|
||||
### TextureService (`mods/svc/texture.h`)
|
||||
|
||||
Registers texture replacements at runtime: the dynamic counterpart to the static `textures/` directory (see
|
||||
[Asset Overlays](#asset-overlays)). Two forms: raw texel data with an explicit key, or an encoded `.dds`/`.png` from
|
||||
your bundle whose filename encodes the key:
|
||||
|
||||
```cpp
|
||||
IMPORT_SERVICE(TextureService, svc_texture);
|
||||
|
||||
// Encoded file; filename follows the replacement naming convention.
|
||||
TextureReplacementHandle handle = 0;
|
||||
svc_texture->register_file(mod_ctx, "res/tex1_32x32_$_6.png", &handle);
|
||||
|
||||
// Raw data: match by texel-data pointer or by content hash (TEXTURE_KEY_SOURCE).
|
||||
TextureKey key = TEXTURE_KEY_INIT;
|
||||
key.kind = TEXTURE_KEY_POINTER;
|
||||
key.pointer = someTexObj.data;
|
||||
TextureData data = TEXTURE_DATA_INIT;
|
||||
data.data = pixels; data.size = pixelsSize;
|
||||
data.width = 32; data.height = 32; data.gx_format = GX_TF_RGBA8_PC;
|
||||
svc_texture->register_data(mod_ctx, &key, &data, nullptr);
|
||||
|
||||
svc_texture->unregister(mod_ctx, handle);
|
||||
```
|
||||
|
||||
Filenames use the same Dolphin-style convention as the user's `texture_replacements` directory:
|
||||
`tex1_{w}x{h}_{texhash}[_{tluthash}]_{fmt}.dds|.png`, where hashes may be `$` (wildcard). `_mipN` sidecar files next to
|
||||
a registered file are picked up automatically. Files are decoded lazily on first use by the renderer; raw data is copied
|
||||
at registration. Registrations follow your mod's lifecycle.
|
||||
|
||||
See [Asset Overlays](#asset-overlays) for priority and conflict handling.
|
||||
|
||||
### ConfigService (`mods/svc/config.h`)
|
||||
|
||||
Persistent, mod-scoped configuration variables. Each var is stored in the user's `config.json` under
|
||||
`mod.<escaped mod id>.<name>` (escaping: `.` → `_`, `_` → `__`, so `com.example.my_mod` becomes `com_example_my__mod`),
|
||||
next to the host's own settings:
|
||||
|
||||
```cpp
|
||||
IMPORT_SERVICE(ConfigService, svc_config);
|
||||
|
||||
ConfigVarDesc desc = CONFIG_VAR_DESC_INIT;
|
||||
desc.name = "speedMultiplier"; // 1-64 chars from [A-Za-z0-9_-]; "enabled" is reserved
|
||||
desc.type = CONFIG_VAR_FLOAT;
|
||||
desc.default_float = 1.0;
|
||||
ConfigVarHandle var = 0;
|
||||
svc_config->register_var(mod_ctx, &desc, &var);
|
||||
|
||||
double speed = 1.0;
|
||||
svc_config->get_float(mod_ctx, var, &speed);
|
||||
svc_config->set_float(mod_ctx, var, 2.0);
|
||||
|
||||
// Optional: get notified when the value changes.
|
||||
void on_speed_changed(ModContext* ctx, ConfigVarHandle var, const ConfigVarValue* value,
|
||||
const ConfigVarValue* previous, void* user_data) {
|
||||
/* value->float_value is the new value, previous->float_value the old one */
|
||||
}
|
||||
svc_config->subscribe(mod_ctx, var, on_speed_changed, nullptr, nullptr);
|
||||
```
|
||||
|
||||
Types: `CONFIG_VAR_BOOL` (`bool`), `CONFIG_VAR_INT` (`int64_t`), `CONFIG_VAR_FLOAT` (`double`), `CONFIG_VAR_STRING`
|
||||
(UTF-8; `get_string` copies into a caller buffer, pass a `NULL` buffer with size 0 to query the length). Accessors are
|
||||
typed and must match the registration.
|
||||
|
||||
Change callbacks fire on the game thread whenever the value changes at runtime (your own `set_*` calls included).
|
||||
Writes that store the same value are silent. Values applied from `config.json` or `--cvar` at registration do
|
||||
**not** fire callbacks; read the value after `register_var` for the starting state.
|
||||
|
||||
### UiService (`mods/svc/ui.h`)
|
||||
|
||||
Integrate seamlessly with Dusklight's UI system: add controls and buttons to your mod's detail pane in the Mods window,
|
||||
create custom windows and modal dialogs, apply custom RCSS stylesheets (anywhere!), and add menu bar tabs.
|
||||
|
||||
**Mod panel:** Registers or replaces the panel rendered in your mod's detail pane; `build` runs every time the detail
|
||||
content is rebuilt, and `update` runs every frame while that mod is selected. While your mod is selected, the detail
|
||||
pane carries your mod's id as a `mod-id` attribute (like custom window roots), so scoped RCSS can target it (e.g.
|
||||
`[mod-id="com.example.mod"]`).
|
||||
|
||||
```cpp
|
||||
IMPORT_SERVICE(UiService, svc_ui);
|
||||
|
||||
UiElementHandle statusText = 0;
|
||||
|
||||
ModResult build(ModContext*, UiElementHandle panel, void*, ModError*) {
|
||||
svc_ui->pane_add_section(mod_ctx, panel, "Status");
|
||||
svc_ui->pane_add_text(mod_ctx, panel, "starting...", &statusText);
|
||||
svc_ui->pane_add_progress(mod_ctx, panel, 0.5f, nullptr);
|
||||
return MOD_OK;
|
||||
}
|
||||
|
||||
ModResult update(ModContext*, void*, ModError*) {
|
||||
svc_ui->elem_set_text(mod_ctx, statusText, "running");
|
||||
return MOD_OK;
|
||||
}
|
||||
|
||||
UiModsPanelDesc panel = UI_MODS_PANEL_DESC_INIT;
|
||||
panel.build = build;
|
||||
panel.update = update;
|
||||
svc_ui->register_mods_panel(mod_ctx, &panel);
|
||||
```
|
||||
|
||||
Element setters must match the element kind: `elem_set_text`/`elem_set_rml` on text rows, and `elem_set_progress` on
|
||||
progress bars. `elem_set_class` sets or clears an RCSS class on any element handle, for styling via scoped or
|
||||
per-window RCSS. A non-`MOD_OK` result from `build`/`update` fails your mod, as do exceptions thrown from any UI
|
||||
callback.
|
||||
|
||||
**Controls:** `pane_add_control` adds an input row described by a `UiControlDesc`: `UI_CONTROL_BUTTON`,
|
||||
`UI_CONTROL_TOGGLE`, `UI_CONTROL_NUMBER`, `UI_CONTROL_STRING`, or `UI_CONTROL_SELECT`. Values bind with callbacks or
|
||||
directly to a config var.
|
||||
|
||||
```cpp
|
||||
UiControlDesc control = UI_CONTROL_DESC_INIT;
|
||||
control.kind = UI_CONTROL_TOGGLE;
|
||||
control.label = "Enable rainbows";
|
||||
control.help_rml = "Shown in the help pane while focused.";
|
||||
control.binding = UI_BINDING_CONFIG_VAR;
|
||||
control.config_var = myBoolVar; // from svc_config->register_var
|
||||
svc_ui->pane_add_control(mod_ctx, leftPane, &control, nullptr);
|
||||
```
|
||||
|
||||
`UI_BINDING_CONFIG_VAR` wires persistence, change notifications, and the modified indicator automatically. The var
|
||||
type must match the control: `TOGGLE` = bool, `NUMBER` and `SELECT` = int, `STRING` = string. Float vars are not
|
||||
bindable; use callbacks and convert. `help_rml` and `SELECT` option lists render in a help pane, so `SELECT` controls
|
||||
are only available inside window tabs.
|
||||
|
||||
**Windows:** `window_push` pushes a tabbed two-pane window onto the document stack and shows it. Each tab's `build`
|
||||
receives the window handle plus fresh left and right pane handles on every activation. The optional per-tab `update`
|
||||
runs each frame while that tab is active. `on_closed` fires when the window is destroyed. `desc.rcss` optionally styles
|
||||
that window's document only; custom windows carry the owning mod's id as a `mod-id` attribute on the window root, so
|
||||
scoped RCSS can target your specific mod's windows (e.g. `window[mod-id="com.example.mod"]`).
|
||||
|
||||
```cpp
|
||||
UiTabDesc tabs[1] = {UI_TAB_DESC_INIT};
|
||||
tabs[0].title = "Options";
|
||||
tabs[0].build = build_options_tab;
|
||||
|
||||
UiWindowDesc desc = UI_WINDOW_DESC_INIT;
|
||||
desc.tabs = tabs;
|
||||
desc.tab_count = 1;
|
||||
desc.on_closed = options_window_closed;
|
||||
UiWindowHandle window = 0;
|
||||
svc_ui->window_push(mod_ctx, &desc, &window);
|
||||
```
|
||||
|
||||
**Dialogs:** `dialog_push` shows a modal dialog. `variant` picks the style, `icon` optionally overrides the variant's
|
||||
default icon, and actions become buttons. After an action's `on_pressed` returns, the dialog closes unless the action
|
||||
sets `keep_open`. A `keep_open` action can close it later (or immediately) with `dialog_close`. Cancel fires
|
||||
`on_dismiss` if present and always closes. `dialog_set_body`, `dialog_set_icon`, and `dialog_add_action` mutate a live
|
||||
dialog.
|
||||
|
||||
**Menu bar tabs:** `register_menu_tab` adds a tab to the in-game menu bar. `on_selected` fires when the user activates
|
||||
the tab: typically you'd push a window from it. The tab is removed by `unregister_menu_tab`, or automatically when the
|
||||
mod is disabled.
|
||||
|
||||
**Custom styles:** `register_styles(scope, rcss, &handle)` applies an RCSS stylesheet to every document of a scope:
|
||||
existing documents restyle immediately, and future ones pick it up when created. `register_styles_file(scope, path,
|
||||
&handle)` reads the sheet from your bundle's `res/` directory. Scopes are `UI_SCOPE_PRELAUNCH`, `UI_SCOPE_WINDOW`,
|
||||
`UI_SCOPE_MENU_BAR`, `UI_SCOPE_OVERLAY`, `UI_SCOPE_TOUCH_CONTROLS`, and `UI_SCOPE_GRAPHICS_TUNER`. Sheets apply after
|
||||
host styles and may override them. Scope selectors tightly (use `[mod-id="..."]`!), especially for `UI_SCOPE_WINDOW`,
|
||||
unless changing host UI is intentional.
|
||||
|
||||
---
|
||||
|
||||
## Hooking Game Functions
|
||||
|
||||
Mods may hook the vast majority of game functions, including file-local static, private and virtual functions.
|
||||
`mods/hook.hpp` provides typed helpers over the hook service:
|
||||
|
||||
```cpp
|
||||
#include "mods/hook.hpp"
|
||||
#include "mods/svc/hook.h"
|
||||
|
||||
IMPORT_SERVICE(HookService, svc_hook);
|
||||
```
|
||||
|
||||
### Pre-hooks
|
||||
|
||||
Run before the original. Return `HOOK_SKIP_ORIGINAL` to cancel it (post-hooks still run).
|
||||
|
||||
```cpp
|
||||
HookAction on_pos_move_pre(ModContext*, void* args, void* retval, void* userdata) {
|
||||
daAlink_c* link = dusk::mods::arg<daAlink_c*>(args, 0); // arg 0 is `this`
|
||||
if (link->shape_angle.y > 10000) {
|
||||
return HOOK_SKIP_ORIGINAL;
|
||||
}
|
||||
return HOOK_CONTINUE;
|
||||
}
|
||||
|
||||
dusk::mods::hook_add_pre<&daAlink_c::posMove>(svc_hook, on_pos_move_pre);
|
||||
```
|
||||
|
||||
### Post-hooks
|
||||
|
||||
Run after the original (or after a replace-hook, or after a cancelled original). `retval` points to the return value,
|
||||
if any.
|
||||
|
||||
```cpp
|
||||
void on_pos_move_post(ModContext*, void* args, void* retval, void* userdata) { ... }
|
||||
|
||||
dusk::mods::hook_add_post<&daAlink_c::posMove>(svc_hook, on_pos_move_post);
|
||||
```
|
||||
|
||||
### Replace-hooks
|
||||
|
||||
Substitute the original entirely. Call through to it via `Hook<...>::g_orig` if needed:
|
||||
|
||||
```cpp
|
||||
using ExecuteEntry = dusk::mods::Hook<&daAlink_c::execute>;
|
||||
|
||||
void on_execute_replace(ModContext*, void* args, void* retval, void*) {
|
||||
int result = ExecuteEntry::g_orig(dusk::mods::arg<daAlink_c*>(args, 0));
|
||||
if (retval != nullptr) {
|
||||
*static_cast<int*>(retval) = result;
|
||||
}
|
||||
}
|
||||
|
||||
dusk::mods::hook_replace<&daAlink_c::execute>(svc_hook, on_execute_replace);
|
||||
```
|
||||
|
||||
By default a second replace-hook on the same function is a conflict; `HookOptions` (`replace_policy`, `priority`,
|
||||
`userdata`) controls this and callback ordering. Multiple mods can attach pre/post hooks to the same function
|
||||
independently.
|
||||
|
||||
### Hooking by name
|
||||
|
||||
Functions you can't name in C++ (file-local statics, private class members, anything not in a header) can be hooked by
|
||||
symbol name instead. You must supply the signature along with the name.
|
||||
|
||||
```cpp
|
||||
// static callback used by Link's hookshot collider in d_a_alink_hook.inc
|
||||
using HookshotHit = dusk::mods::NamedHook<
|
||||
"daAlink_hookshotAtHitCallBack",
|
||||
void(fopAc_ac_c*, dCcD_GObjInf*, fopAc_ac_c*, dCcD_GObjInf*)>;
|
||||
|
||||
dusk::mods::hook_add_pre<HookshotHit>(svc_hook, on_hookshot_hit_pre);
|
||||
...
|
||||
HookshotHit::g_orig(link, atObjInf, target, tgObjInf); // call through to the original
|
||||
```
|
||||
|
||||
Class member functions must include `Class*` as the first argument.
|
||||
|
||||
The install fails with the resolve error when the name is missing (`MOD_UNAVAILABLE`), ambiguous (`MOD_CONFLICT`),
|
||||
or the manifest is absent (`MOD_UNSUPPORTED`). Unlike `Hook<&Class::method>`, the signature is **not**
|
||||
compiler-checked: a mismatched signature will corrupt the call.
|
||||
|
||||
### Reading and writing arguments
|
||||
|
||||
`args` is an array of pointers to the arguments. For member functions, index 0 is `this`; parameters follow in
|
||||
declaration order.
|
||||
|
||||
```cpp
|
||||
T value = dusk::mods::arg<T>(args, n); // copy
|
||||
T& ref = dusk::mods::arg_ref<T>(args, n); // read/write reference
|
||||
```
|
||||
|
||||
```cpp
|
||||
// fpc_ProcID fopAcM_createItem(..., int itemNo, ...): turn heart drops into green rupees
|
||||
HookAction on_create_item_pre(ModContext*, void* args, void*, void*) {
|
||||
int& itemNo = dusk::mods::arg_ref<int>(args, 1);
|
||||
if (itemNo == dItemNo_HEART_e) {
|
||||
itemNo = dItemNo_GREEN_RUPEE_e;
|
||||
}
|
||||
return HOOK_CONTINUE;
|
||||
}
|
||||
|
||||
dusk::mods::hook_add_pre<&fopAcM_createItem>(svc_hook, on_create_item_pre);
|
||||
```
|
||||
|
||||
For reference parameters (e.g. `const cXyz& pos`), `arg_ref<cXyz>` yields a direct reference.
|
||||
|
||||
### Resolving symbols by name
|
||||
|
||||
`resolve` looks a symbol up in the **symbol manifest**: a name→address map generated alongside every game build and
|
||||
keyed to that exact binary. It covers the whole image, including functions that aren't exported (file-local statics),
|
||||
which makes them hookable:
|
||||
|
||||
```cpp
|
||||
IMPORT_SERVICE(HookService, svc_hook);
|
||||
|
||||
void* addr = nullptr;
|
||||
uint32_t flags = 0;
|
||||
if (svc_hook->resolve(mod_ctx, "GXSetProjection", &addr, &flags) == MOD_OK) {
|
||||
// addr is the function's real address in the running game; hook or call it.
|
||||
}
|
||||
```
|
||||
|
||||
Two spellings work on every platform:
|
||||
|
||||
- **Display names** (`daAlink_c::posMove`, `fapGm_Before`): the qualified name with no parameter list. They carry no
|
||||
signature, so overload sets (and file-local statics sharing a name) return `MOD_CONFLICT`.
|
||||
- **Decorated names** (`_ZN9daAlink_c7posMoveEv` / `?posMove@daAlink_c@@...`): the platform's mangled spelling in
|
||||
dlsym convention (no Mach-O leading underscore). The escape hatch for overloads.
|
||||
|
||||
`MOD_UNSUPPORTED` means the manifest is missing or was built for a different game binary.
|
||||
|
||||
### Game code ABI contract
|
||||
|
||||
A primary consideration when letting mods link against the game is maintaining ABI stability across Dusklight
|
||||
versions. If your mod calls or hooks game code directly (anything beyond the service APIs), import `GameService`
|
||||
(`mods/svc/game.h`):
|
||||
|
||||
```cpp
|
||||
IMPORT_SERVICE(GameService, svc_game);
|
||||
```
|
||||
|
||||
Its major version is the game code ABI epoch: it's bumped when game struct or vtable layouts change incompatibly, and
|
||||
the ordinary service version check then rejects your mod with a clear error instead of letting it corrupt memory in a
|
||||
version it wasn't built for. Service-only and asset-only mods should *not* import it and will continue to work across
|
||||
game ABI changes.
|
||||
|
||||
The more you can do through services, the better: a mod that avoids touching game code directly sidesteps future ABI
|
||||
breaks entirely and plays nicer with other enabled mods.
|
||||
|
||||
---
|
||||
|
||||
## Asset Overlays
|
||||
|
||||
Files placed under `overlay/` in the `.dusk` archive override game files at the corresponding path, equivalent to
|
||||
replacing files in the .iso. This requires no code: an archive with just `mod.json` and `overlay/` is a complete mod.
|
||||
|
||||
Files placed under `textures/` register as texture replacements, and act just like the user's general
|
||||
`texture_replacements/` directory: Dolphin-style naming, matched by texture hash
|
||||
(`tex1_{w}x{h}_{texhash}[_{tluthash}]_{fmt}.dds|.png`, `$` as a hash wildcard). Subdirectories are scanned recursively;
|
||||
only the filename needs to match.
|
||||
|
||||
Both mechanisms are tied to the mod's lifecycle: disabling the mod removes its overrides (files revert to the disc
|
||||
contents on their next open; added files stop existing), and reloading serves the new bundle's content. However, game
|
||||
data the engine already read stays as-is until it is loaded again, which may require a scene change or, in the worst
|
||||
case, a full restart. Texture replacements usually take effect immediately.
|
||||
|
||||
If multiple sources replace the same file or texture, the last one wins: runtime registrations override static
|
||||
`textures/` or `overlay/` files, and later-loaded mods override earlier ones. Cross-mod conflicts log warnings.
|
||||
**All** mod-provided texture replacements override the user's `texture_replacements/`.
|
||||
|
||||
To configure overlays and texture replacements at runtime instead, see [OverlayService](#overlayservice-modssvcoverlayh)
|
||||
and [TextureService](#textureservice-modssvctextureh).
|
||||
|
||||
---
|
||||
|
||||
## Runtime Lifecycle
|
||||
|
||||
Mods can be disabled, re-enabled, and reloaded at runtime without restarting the game (the enabled state persists as the
|
||||
`mod.<escaped id>.enabled` config var). Write your mod assuming this happens:
|
||||
|
||||
- **Disable** calls `mod_shutdown`, removes your hooks, services, overlays, and texture replacements (both static and
|
||||
runtime-registered), and unloads your library.
|
||||
- **Enable** and **Reload** load a *fresh copy* of your library, imports are re-resolved, and `mod_initialize` runs
|
||||
again. You never see a second `mod_initialize` on the same image, so just make `mod_shutdown` release anything the
|
||||
loader doesn't manage for you (threads, files, game-side state you mutated).
|
||||
- **Reload** additionally re-reads the `.dusk` from disk, picking up a rebuilt library and changed assets. This is the
|
||||
fast iteration loop during development: rebuild, click Reload.
|
||||
|
||||
**Dependents restart too.** Disabling or reloading a mod that exports services shuts down the mods importing them
|
||||
first (in reverse dependency order) and brings them back afterward. A mod whose *required* provider is disabled stays
|
||||
suspended and resumes automatically when the provider returns. Mods with an *optional* import of a disabled provider
|
||||
restart with that import null.
|
||||
|
||||
**One caution for hooks:** lifecycle changes are applied between frames, which is safe for hooks on functions
|
||||
that return every frame (effectively everything you'd normally hook). Avoid hooking a function that stays on
|
||||
the stack for the whole session (e.g. the outermost main loop); a mod that does cannot be safely unloaded.
|
||||
|
||||
---
|
||||
|
||||
## Error Handling
|
||||
|
||||
Service calls report failure through `ModResult` return values (`MOD_OK`, `MOD_UNAVAILABLE`,
|
||||
`MOD_INVALID_ARGUMENT`, ...). Lifecycle exports additionally receive a `ModError*`: fill it (e.g. with
|
||||
`dusk::mods::set_error(error, code, "message")`) and return the code, and the loader disables the mod and shows the
|
||||
message to the user.
|
||||
|
||||
```cpp
|
||||
MOD_EXPORT ModResult mod_initialize(ModError* error) {
|
||||
if (!load_my_data()) {
|
||||
return dusk::mods::set_error(error, MOD_ERROR, "failed to load data");
|
||||
}
|
||||
return MOD_OK;
|
||||
}
|
||||
```
|
||||
|
||||
Throwing exceptions out of lifecycle functions also disables the mod (they are caught by the loader), but prefer
|
||||
explicit results.
|
||||
|
||||
---
|
||||
|
||||
## Advanced: Exporting Services
|
||||
|
||||
Mods may export services of their own, permitting framework mods and cross-mod integration. Define the interface in a
|
||||
header both mods share:
|
||||
|
||||
```cpp
|
||||
// my_mod_api.h
|
||||
#include "mods/api.h"
|
||||
|
||||
#define MY_MOD_SERVICE_ID "com.example.my_mod.api"
|
||||
#define MY_MOD_SERVICE_MAJOR 1u
|
||||
#define MY_MOD_SERVICE_MINOR 0u
|
||||
|
||||
typedef struct MyModService {
|
||||
ServiceHeader header;
|
||||
ModResult (*do_thing)(ModContext* ctx, int value);
|
||||
} MyModService;
|
||||
|
||||
#ifdef __cplusplus
|
||||
#include "mods/service.hpp"
|
||||
template <>
|
||||
struct dusk::mods::ServiceTraits<MyModService> {
|
||||
static constexpr const char* id = MY_MOD_SERVICE_ID;
|
||||
static constexpr uint16_t major_version = MY_MOD_SERVICE_MAJOR;
|
||||
};
|
||||
#endif
|
||||
```
|
||||
|
||||
**Provider:**
|
||||
|
||||
```cpp
|
||||
ModResult do_thing(ModContext* ctx, int value) { ... }
|
||||
|
||||
constexpr MyModService g_service{
|
||||
.header = SERVICE_HEADER(MyModService, MY_MOD_SERVICE_MAJOR, MY_MOD_SERVICE_MINOR),
|
||||
.do_thing = do_thing,
|
||||
};
|
||||
EXPORT_SERVICE(g_service);
|
||||
```
|
||||
|
||||
**Consumer:**
|
||||
|
||||
```cpp
|
||||
IMPORT_SERVICE(MyModService, svc_my_mod);
|
||||
// or IMPORT_OPTIONAL_SERVICE if the dependency is optional
|
||||
|
||||
svc_my_mod->do_thing(mod_ctx, 42);
|
||||
```
|
||||
|
||||
The loader registers all exports before resolving any imports, so declaration order between mods doesn't matter. Note
|
||||
that the `ctx` a provider receives identifies the *calling* mod.
|
||||
|
||||
### Dependencies between mods
|
||||
|
||||
Service imports are also dependency declarations: the loader initializes mods in dependency order, so by the time your
|
||||
`mod_initialize` runs, every mod you import services from (required *or* optional) has already finished its own
|
||||
`mod_initialize`. This includes deferred services: a service the provider publishes during its initialization resolves
|
||||
into your import slot just like a static export.
|
||||
|
||||
Consequences of that contract:
|
||||
|
||||
- If a provider fails to load, every mod that *requires* one of its services is disabled too, with an error naming the
|
||||
provider. Optional imports of a failed provider simply resolve to `NULL`.
|
||||
- Mods whose **required** imports form a cycle all fail to load. If the cycle runs through an **optional** import, the
|
||||
loader breaks it there: the optional import still resolves, but its provider may not be initialized yet when you run.
|
||||
- `svc_host->get_service(...)` is outside this system. It sees whatever is published at call time and gives no
|
||||
initialization-order guarantee, which also makes it the escape hatch for intentionally cyclic designs.
|
||||
|
||||
Mods shut down in reverse initialization order, so services you import remain safe to call from `mod_shutdown`.
|
||||
|
||||
Rules for providers:
|
||||
|
||||
- Service IDs are global and use reverse-DNS names (e.g. `com.mydomain.mod.service`)
|
||||
- Every function pointer covered by your declared minor version must be populated.
|
||||
- Within a major version, only append fields; never reorder, remove, or repurpose them. Breaking changes require a major
|
||||
bump (which is, in effect, a new service).
|
||||
- Only one provider per `(id, major)` pair may be registered; duplicates are load errors.
|
||||
|
||||
For services whose construction can't happen at static-init time, declare the export with `EXPORT_DEFERRED_SERVICE(...)`
|
||||
and publish the pointer later via `svc_host->publish_service(...)`. Consumers can fetch services dynamically with
|
||||
`svc_host->get_service(...)`; prefer manifest imports whenever possible, since they give the loader dependency
|
||||
information and fail fast with good errors.
|
||||
Vendored
+1
-1
Submodule extern/aurora updated: 19479a53e4...0a5a5d90ef
+50
@@ -1418,7 +1418,11 @@ set(DUSK_FILES
|
||||
include/dusk/scope_guard.hpp
|
||||
src/dusk/dvd_asset.cpp
|
||||
src/d/actor/d_a_alink_dusk.cpp
|
||||
src/dusk/android_frame_rate.hpp
|
||||
src/dusk/android_frame_rate.cpp
|
||||
src/dusk/asserts.cpp
|
||||
src/dusk/batch.cpp
|
||||
src/dusk/batch.hpp
|
||||
src/dusk/config.cpp
|
||||
src/dusk/crash_handler.cpp
|
||||
src/dusk/crash_reporting.cpp
|
||||
@@ -1432,6 +1436,8 @@ set(DUSK_FILES
|
||||
src/dusk/game_clock.cpp
|
||||
src/dusk/globals.cpp
|
||||
src/dusk/gyro.cpp
|
||||
include/dusk/menu_pointer.h
|
||||
src/dusk/menu_pointer.cpp
|
||||
src/dusk/mouse.cpp
|
||||
src/dusk/gamepad_color.cpp
|
||||
src/dusk/autosave.cpp
|
||||
@@ -1445,6 +1451,7 @@ set(DUSK_FILES
|
||||
src/dusk/stubs.cpp
|
||||
include/dusk/texture_replacements.hpp
|
||||
src/dusk/texture_replacements.cpp
|
||||
src/dusk/touch_camera.cpp
|
||||
src/dusk/update_check.cpp
|
||||
src/dusk/update_check.hpp
|
||||
#src/dusk/m_Do_ext_dusk.cpp
|
||||
@@ -1474,6 +1481,7 @@ set(DUSK_FILES
|
||||
src/dusk/ui/button.hpp
|
||||
src/dusk/ui/component.cpp
|
||||
src/dusk/ui/component.hpp
|
||||
src/dusk/ui/controls.hpp
|
||||
src/dusk/ui/controller_config.cpp
|
||||
src/dusk/ui/controller_config.hpp
|
||||
src/dusk/ui/document.cpp
|
||||
@@ -1486,6 +1494,14 @@ set(DUSK_FILES
|
||||
src/dusk/ui/graphics_tuner.hpp
|
||||
src/dusk/ui/input.cpp
|
||||
src/dusk/ui/input.hpp
|
||||
src/dusk/ui/icon_provider.cpp
|
||||
src/dusk/ui/icon_provider.hpp
|
||||
src/dusk/ui/logs_window.cpp
|
||||
src/dusk/ui/logs_window.hpp
|
||||
src/dusk/ui/mod_texture_provider.cpp
|
||||
src/dusk/ui/mod_texture_provider.hpp
|
||||
src/dusk/ui/mod_window.cpp
|
||||
src/dusk/ui/mod_window.hpp
|
||||
src/dusk/ui/modal.cpp
|
||||
src/dusk/ui/modal.hpp
|
||||
src/dusk/ui/nav_types.hpp
|
||||
@@ -1497,6 +1513,8 @@ set(DUSK_FILES
|
||||
src/dusk/ui/pane.hpp
|
||||
src/dusk/ui/menu_bar.cpp
|
||||
src/dusk/ui/menu_bar.hpp
|
||||
src/dusk/ui/mods_window.cpp
|
||||
src/dusk/ui/mods_window.hpp
|
||||
src/dusk/ui/prelaunch.cpp
|
||||
src/dusk/ui/prelaunch.hpp
|
||||
src/dusk/ui/preset.cpp
|
||||
@@ -1511,6 +1529,12 @@ set(DUSK_FILES
|
||||
src/dusk/ui/string_button.hpp
|
||||
src/dusk/ui/tab_bar.cpp
|
||||
src/dusk/ui/tab_bar.hpp
|
||||
src/dusk/ui/touch_controls_common.cpp
|
||||
src/dusk/ui/touch_controls_common.hpp
|
||||
src/dusk/ui/touch_controls.cpp
|
||||
src/dusk/ui/touch_controls.hpp
|
||||
src/dusk/ui/touch_controls_editor.cpp
|
||||
src/dusk/ui/touch_controls_editor.hpp
|
||||
src/dusk/ui/ui.cpp
|
||||
src/dusk/ui/ui.hpp
|
||||
src/dusk/ui/warp.cpp
|
||||
@@ -1525,6 +1549,32 @@ set(DUSK_FILES
|
||||
src/dusk/OSReport.cpp
|
||||
src/dusk/OSThread.cpp
|
||||
src/dusk/OSMutex.cpp
|
||||
src/dusk/mods/log_buffer.cpp
|
||||
src/dusk/mods/log_buffer.hpp
|
||||
src/dusk/mods/manifest.cpp
|
||||
src/dusk/mods/manifest.hpp
|
||||
src/dusk/mods/loader/bundle_disk.cpp
|
||||
src/dusk/mods/loader/bundle_zip.cpp
|
||||
src/dusk/mods/loader/context.cpp
|
||||
src/dusk/mods/loader/depgraph.cpp
|
||||
src/dusk/mods/loader/depgraph.hpp
|
||||
src/dusk/mods/loader/loader.cpp
|
||||
src/dusk/mods/loader/loader.hpp
|
||||
src/dusk/mods/loader/native_module.cpp
|
||||
src/dusk/mods/loader/native_module.hpp
|
||||
src/dusk/mods/svc/config.cpp
|
||||
src/dusk/mods/svc/config.hpp
|
||||
src/dusk/mods/svc/game.cpp
|
||||
src/dusk/mods/svc/hook.cpp
|
||||
src/dusk/mods/svc/host.cpp
|
||||
src/dusk/mods/svc/log.cpp
|
||||
src/dusk/mods/svc/overlay.cpp
|
||||
src/dusk/mods/svc/resource.cpp
|
||||
src/dusk/mods/svc/texture.cpp
|
||||
src/dusk/mods/svc/ui.cpp
|
||||
src/dusk/mods/svc/ui.hpp
|
||||
src/dusk/mods/svc/registry.cpp
|
||||
src/dusk/mods/svc/registry.hpp
|
||||
src/dusk/discord.cpp
|
||||
src/dusk/discord.hpp
|
||||
src/dusk/discord_presence.cpp
|
||||
|
||||
@@ -16,37 +16,37 @@
|
||||
];
|
||||
forAllSystems = lib.genAttrs supportedSystems;
|
||||
|
||||
dawnVersion = "v20260423.175430";
|
||||
nodVersion = "v2.0.0-alpha.8";
|
||||
dawnVersion = "v20260618.032059";
|
||||
nodVersion = "v2.0.0-alpha.10";
|
||||
versionSuffix = "nix-" + (self.shortRev or self.dirtyShortRev or "dirty");
|
||||
|
||||
dawnInfo = {
|
||||
"x86_64-linux" = {
|
||||
triple = "linux-x86_64";
|
||||
hash = "sha256-HXfKTLHtMPwupnFnaflCARtXVPuS/0PoCePXidjE5xs=";
|
||||
hash = "sha256-GFSd573b+VQx/VmFdNQgWDd0V9ayQlcw0Zuopke12ak=";
|
||||
};
|
||||
"aarch64-linux" = {
|
||||
triple = "linux-aarch64";
|
||||
hash = "sha256-34yyFpfqBZUwoFXQ41F0AwAU78FaNihOSY0oriwn6B0=";
|
||||
hash = "sha256-ZaoP7BAjBMnfAv2/AMRi3FNH2ZtyqASCSFyU/oB2Mzg=";
|
||||
};
|
||||
"aarch64-darwin" = {
|
||||
triple = "darwin-arm64";
|
||||
hash = "sha256-eQnzrBp6gjiBek1VYQ9A5W13ClYWrDDKjIqv/7eNTR4=";
|
||||
hash = "sha256-HT+qtlLaSHyoXPrUcXgcTGa877X5YfzbxRD4bJb7i1Y=";
|
||||
};
|
||||
"x86_64-darwin" = {
|
||||
triple = "darwin-x86_64";
|
||||
hash = "sha256-QGWiGdxiI9kci3NPXH6QFFirxn16851zB/w3jqhIBJ4=";
|
||||
hash = "sha256-cUNaCbA7rlKSukDVKGaVEVw0Zt1+mSbaHbmUCMvMVWc=";
|
||||
};
|
||||
};
|
||||
|
||||
nodPrebuiltInfo = {
|
||||
"x86_64-linux" = {
|
||||
triple = "linux-x86_64";
|
||||
hash = "sha256-mUqvLsbsqaZ+HAjMmHYPYO+MgtanGRTw7Gzn5uXR5rE=";
|
||||
hash = "sha256-FVQWECVA2gWdc+n5OQ/Tvwn8z0qdgjSd1WlFt5HKOec=";
|
||||
};
|
||||
"aarch64-darwin" = {
|
||||
triple = "macos-arm64";
|
||||
hash = "sha256-UPy1ywCcv0K6VJOU3uUelJuUdBh3UNaPRlyP5LOBeDw=";
|
||||
hash = "sha256-8ZEejxksVgShNKUVRCBYaLOp9x/qOC9pAeVrElQUGUk=";
|
||||
};
|
||||
};
|
||||
|
||||
@@ -75,7 +75,7 @@
|
||||
'';
|
||||
|
||||
dawn = pkgs.fetchzip {
|
||||
url = "https://github.com/encounter/dawn-build/releases/download/${dawnVersion}/dawn-${dawnInfo.${system}.triple}.tar.gz";
|
||||
url = "https://github.com/encounter/dawn/releases/download/${dawnVersion}/dawn-${dawnInfo.${system}.triple}.tar.gz";
|
||||
hash = dawnInfo.${system}.hash;
|
||||
stripRoot = false;
|
||||
};
|
||||
@@ -94,7 +94,7 @@
|
||||
owner = "encounter";
|
||||
repo = "nod";
|
||||
rev = nodVersion;
|
||||
hash = "sha256-+zrtVzjo0+X/6uMcNUn1+FaSR+jOhrcQSDNBFjw0NDs=";
|
||||
hash = "sha256-r8qDlOVxv5iKiFjJQrcBuL9HVoOM3yEjRVnQIMqaICs=";
|
||||
};
|
||||
patches = [ ./fix-cmake-paths.patch ];
|
||||
cargoDeps = pkgs.rustPlatform.importCargoLock {
|
||||
@@ -138,15 +138,15 @@
|
||||
NOD_PREBUILT = nod;
|
||||
CXXOPTS = pkgs.cxxopts.src;
|
||||
JSON = pkgs.nlohmann_json.src;
|
||||
XXHASH = pkgs.xxHash.src;
|
||||
XXHASH = pkgs.xxhash.src;
|
||||
ZSTD = pkgs.zstd.src;
|
||||
FMT = pkgs.fetchzip {
|
||||
url = "https://github.com/fmtlib/fmt/archive/refs/tags/11.1.4.tar.gz";
|
||||
hash = "sha256-sUbxlYi/Aupaox3JjWFqXIjcaQa0LFjclQAOleT+FRA=";
|
||||
url = "https://github.com/fmtlib/fmt/archive/refs/tags/12.1.0.tar.gz";
|
||||
hash = "sha256-ZmI1Dv0ZabPlxa02OpERI47jp7zFfjpeWCy1WyuPYZ0=";
|
||||
};
|
||||
TRACY = pkgs.fetchzip {
|
||||
url = "https://github.com/wolfpld/tracy/archive/a64b9a20294d59421a2f57aeca3c6383d8c48169.tar.gz";
|
||||
hash = "sha256-hbNGOsGeyGSvCJ2No8RkwOib1lX2on3vNZSzyVkZdXw=";
|
||||
url = "https://github.com/wolfpld/tracy/archive/6789e7d6f9a65ec98926b602097a33a9676d2606.tar.gz";
|
||||
hash = "sha256-Xxyd7G/mnXEPpN+ehmwl0AkAhS3CwObpJNDgcqbdUJg=";
|
||||
};
|
||||
IMGUI = pkgs.fetchFromGitHub {
|
||||
owner = "ocornut";
|
||||
@@ -194,7 +194,7 @@
|
||||
pkgs.zstd
|
||||
pkgs.cxxopts
|
||||
pkgs.nlohmann_json
|
||||
pkgs.xxHash
|
||||
pkgs.xxhash
|
||||
pkgs.abseil-cpp
|
||||
pkgs.zlib
|
||||
pkgs.libpng
|
||||
@@ -269,6 +269,12 @@
|
||||
runHook postInstall
|
||||
'';
|
||||
|
||||
postFixup = lib.optionalString (!isDarwin) ''
|
||||
patchelf \
|
||||
--add-needed "${pkgs.vulkan-loader}/lib/libvulkan.so" \
|
||||
$out/bin/dusklight
|
||||
'';
|
||||
|
||||
dontStrip = true;
|
||||
|
||||
meta = {
|
||||
|
||||
@@ -20,7 +20,7 @@ public:
|
||||
|
||||
/* 0x14 */ cM3dGAab mM3dGAab;
|
||||
/* 0x30 */ cBgS_ShdwDraw_Callback mCallbackFun;
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
/* 0x34 */ int field_0x34;
|
||||
#endif
|
||||
};
|
||||
|
||||
@@ -48,6 +48,8 @@ public:
|
||||
/* 0x1370 */ Z2FxLineMgr mFxLineMgr;
|
||||
#if DEBUG
|
||||
/* 0x13BC */ Z2DebugSys mDebugSys;
|
||||
#elif PARTIAL_DEBUG
|
||||
alignas(Z2DebugSys) u8 mDebugSys[sizeof(Z2DebugSys)];
|
||||
#endif
|
||||
}; // Size: 0x138C
|
||||
|
||||
|
||||
@@ -194,7 +194,7 @@ public:
|
||||
JAISoundHandle* getMainBgmHandle() { return &mMainBgmHandle; }
|
||||
JAISoundHandle* getSubBgmHandle() { return &mSubBgmHandle; }
|
||||
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
f32 field_0x00_debug;
|
||||
u8 field_0x04_debug;
|
||||
#endif
|
||||
|
||||
@@ -100,13 +100,13 @@ public:
|
||||
bool isForceBattle() { return forceBattle_; }
|
||||
JSUList<Z2CreatureEnemy>* getEnemyList() { return &field_0x0; }
|
||||
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
JSUList<Z2SoundObjBase>* getAllList() { return &allList_; }
|
||||
#endif
|
||||
|
||||
private:
|
||||
/* 0x00 */ JSUList<Z2CreatureEnemy> field_0x0;
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
/* 0x0C */ JSUList<Z2SoundObjBase> allList_;
|
||||
#endif
|
||||
/* 0x0C */ Z2EnemyArea enemyArea_;
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
struct Z2SoundStarter;
|
||||
|
||||
class Z2SoundObjBase : public Z2SoundHandles
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
, public JSULink<Z2SoundObjBase>
|
||||
#endif
|
||||
{
|
||||
|
||||
@@ -4556,6 +4556,7 @@ public:
|
||||
void handleWolfHowl();
|
||||
void handleQuickTransform();
|
||||
bool checkAimContext();
|
||||
bool checkAimInputContext();
|
||||
|
||||
void onIronBallChainInterpCallback();
|
||||
|
||||
|
||||
@@ -88,9 +88,14 @@ public:
|
||||
/* 0x396A */ u8 field_0x396A[0x399E - 0x396A];
|
||||
/* 0x399E */ s16 field_0x399e;
|
||||
/* 0x39A0 */ u8 field_0x39A0[0x39A4 - 0x39A0];
|
||||
|
||||
#if TARGET_PC
|
||||
/* 0x39A4 */ cM_rnd_c mMantRng;
|
||||
#endif
|
||||
};
|
||||
|
||||
#if TARGET_PC
|
||||
STATIC_ASSERT(sizeof(mant_class) == 0x39ac);
|
||||
#else
|
||||
STATIC_ASSERT(sizeof(mant_class) == 0x39a4);
|
||||
#endif
|
||||
|
||||
#endif /* D_A_MANT_H */
|
||||
|
||||
@@ -4,6 +4,10 @@
|
||||
#include "JSystem/J3DGraphBase/J3DPacket.h"
|
||||
#include "SSystem/SComponent/c_xyz.h"
|
||||
|
||||
#if TARGET_PC
|
||||
#include "dusk/batch.hpp"
|
||||
#endif
|
||||
|
||||
class cCcD_Obj;
|
||||
class dCcMassS_HitInf;
|
||||
class fopAc_ac_c;
|
||||
@@ -107,6 +111,12 @@ public:
|
||||
#if TARGET_PC
|
||||
TGXTexObj mTexObj_l_J_Ohana00_64TEX;
|
||||
TGXTexObj mTexObj_l_J_Ohana01_64128_0419TEX;
|
||||
|
||||
dusk::batch::LeafTemplate mTplHana00; // l_J_hana00DL
|
||||
dusk::batch::LeafTemplate mTplHana00Cut; // l_J_hana00_cDL
|
||||
dusk::batch::LeafTemplate mTplHana01; // l_J_hana01DL
|
||||
dusk::batch::LeafTemplate mTplHana01Cut00; // l_J_hana01_c_00DL
|
||||
dusk::batch::LeafTemplate mTplHana01Cut; // l_J_hana01_c_01DL
|
||||
#endif
|
||||
}; // Size: 0x12A54
|
||||
|
||||
|
||||
@@ -4,6 +4,10 @@
|
||||
#include "JSystem/J3DGraphBase/J3DPacket.h"
|
||||
#include "SSystem/SComponent/c_xyz.h"
|
||||
|
||||
#if TARGET_PC
|
||||
#include "../../../src/dusk/batch.hpp"
|
||||
#endif
|
||||
|
||||
class cCcD_Obj;
|
||||
class csXyz;
|
||||
class dCcMassS_HitInf;
|
||||
@@ -110,6 +114,10 @@ public:
|
||||
#if TARGET_PC
|
||||
TGXTexObj mTexObj_l_M_Hijiki00TEX;
|
||||
TGXTexObj mTexObj_l_M_kusa05_RGBATEX;
|
||||
|
||||
dusk::batch::LeafTemplate mTplKusa9q; // l_M_Kusa_9qDL
|
||||
dusk::batch::LeafTemplate mTplKusa9qCut; // l_M_Kusa_9q_cDL
|
||||
dusk::batch::LeafTemplate mTplTengusa; // l_M_TenGusaDL
|
||||
#endif
|
||||
}; // Size: 0x1D718
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ private:
|
||||
|
||||
class dAttParam_c : public JORReflexible {
|
||||
public:
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
/* 0x04 */ s8 mHIOChildNo;
|
||||
#endif
|
||||
|
||||
@@ -66,7 +66,7 @@ public:
|
||||
/* 0x35 */ u8 mAttnCursorDisappearFrames;
|
||||
/* 0x38 */ f32 field_0x38;
|
||||
/* 0x3C */ f32 field_0x3c;
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
/* 0x44 */ s32 mDebugDispPosX;
|
||||
/* 0x48 */ s32 mDebugDispPosY;
|
||||
#endif
|
||||
|
||||
@@ -201,7 +201,7 @@ private:
|
||||
/* 0x02C */ u32 m_flags;
|
||||
/* 0x030 */ cXyz* pm_pos;
|
||||
/* 0x034 */ cXyz* pm_old_pos;
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
/* 0x038 */ cXyz unk_0x38;
|
||||
#endif
|
||||
/* 0x038 */ cXyz* pm_speed;
|
||||
@@ -229,7 +229,7 @@ private:
|
||||
/* 0x0CC */ f32 field_0xcc;
|
||||
/* 0x0D0 */ f32 m_wtr_chk_offset;
|
||||
/* 0x0D4 */ cBgS_PolyInfo* pm_out_poly_info;
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
/* 0x0E4 */ cXyz unk_0xe4;
|
||||
#endif
|
||||
/* 0x0D8 */ f32 field_0xd8;
|
||||
|
||||
@@ -1037,7 +1037,7 @@ public:
|
||||
bool test1Camera(s32);
|
||||
bool test2Camera(s32);
|
||||
#if TARGET_PC
|
||||
static bool canUseFreeCam();
|
||||
static bool isAimActive();
|
||||
bool freeCamera();
|
||||
bool executeDebugFlyCam();
|
||||
void deactivateDebugFlyCam();
|
||||
|
||||
+1
-1
@@ -79,7 +79,7 @@ public:
|
||||
|
||||
// /* 0x0000 */ cCcS mCCcS;
|
||||
/* 0x284C */ dCcMassS_Mng mMass_Mng;
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
/* 0x2AD0 */ u8 m_is_mass_all_timer;
|
||||
#endif
|
||||
}; // Size = 0x2AC4
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
#include "m_Do/m_Do_graphic.h"
|
||||
#include <cstring>
|
||||
|
||||
#include "tracy/Tracy.hpp"
|
||||
#include "dusk/profiling.hpp"
|
||||
|
||||
enum dComIfG_ButtonStatus {
|
||||
/* 0x00 */ BUTTON_STATUS_NONE,
|
||||
@@ -1037,7 +1037,7 @@ public:
|
||||
/* 0x1DE09 */ u8 field_0x1de09;
|
||||
/* 0x1DE0A */ u8 field_0x1de0a;
|
||||
/* 0x1DE0B */ u8 mIsDebugMode;
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
/* 0x1DE0C */ OSStopwatch mStopwatch;
|
||||
#endif
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@ public:
|
||||
BASE_ROOM5,
|
||||
BASE_DEMO,
|
||||
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
BASE_DEBUG,
|
||||
#endif
|
||||
|
||||
|
||||
@@ -287,6 +287,11 @@ public:
|
||||
MEMCARDCHECKPROC_ERR_YESNO_CURSOR_MOVE_ANM,
|
||||
MEMCARDCHECKPROC_SAVEDATA_CLEAR,
|
||||
|
||||
#if TARGET_PC
|
||||
MEMCARDCHECKPROC_AUTO_MAKE_GAMEFILE,
|
||||
MEMCARDCHECKPROC_AUTO_MAKE_GAMEFILE_ERR_WAIT,
|
||||
#endif
|
||||
|
||||
#if PLATFORM_WII || PLATFORM_SHIELD
|
||||
MEMCARDCHECKPROC_NAND_STAT_CHECK,
|
||||
MEMCARDCHECKPROC_GAMEFILE_INIT_SEL,
|
||||
@@ -411,6 +416,10 @@ public:
|
||||
bool yesnoWakuAlpahAnm(u8);
|
||||
#if TARGET_PC
|
||||
void fileSelectWide();
|
||||
bool pointerDataSelect();
|
||||
bool pointerMenuSelect();
|
||||
bool pointerCopyDataToSelect();
|
||||
bool pointerYesNoSelect(bool errorSelect);
|
||||
#endif
|
||||
void _draw();
|
||||
void errorMoveAnmInitSet(int, int);
|
||||
@@ -445,6 +454,10 @@ public:
|
||||
void MemCardMakeGameFile();
|
||||
void MemCardMakeGameFileWait();
|
||||
void MemCardMakeGameFileCheck();
|
||||
#if TARGET_PC
|
||||
void MemCardAutoMakeGameFile();
|
||||
void MemCardAutoMakeGameFileErrWait();
|
||||
#endif
|
||||
void MemCardMsgWindowInitOpen();
|
||||
void MemCardMsgWindowOpen();
|
||||
void MemCardMsgWindowClose();
|
||||
|
||||
@@ -259,7 +259,7 @@ public:
|
||||
/* 0x09B8 */ DUNGEON_LIGHT dungeonlight[8];
|
||||
/* 0x0C18 */ BOSS_LIGHT field_0x0c18[8];
|
||||
/* 0x0D58 */ BOSS_LIGHT field_0x0d58[6];
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
/* 0x0E48 */ NAVYCHAN navy;
|
||||
/* 0x0E58 */ u8 field_0xe58[0xE68 - 0xE58]; // part of NAVYCHAN?
|
||||
#endif
|
||||
|
||||
@@ -157,6 +157,9 @@ public:
|
||||
int getDispType() const;
|
||||
void _move(f32, f32, int, f32);
|
||||
void _draw();
|
||||
#if TARGET_PC
|
||||
bool refreshTextureSize();
|
||||
#endif
|
||||
|
||||
virtual ~dMap_c() {
|
||||
#if DEBUG
|
||||
|
||||
@@ -74,6 +74,8 @@ public:
|
||||
|
||||
#if TARGET_PC
|
||||
void menuCollectWide();
|
||||
bool pointerWait();
|
||||
void pointerActivateCurrent();
|
||||
#endif
|
||||
|
||||
void _create();
|
||||
|
||||
@@ -51,6 +51,10 @@ public:
|
||||
void setBButtonString(u16);
|
||||
void setHIO(bool);
|
||||
|
||||
#if TARGET_PC
|
||||
bool pointerWait();
|
||||
#endif
|
||||
|
||||
virtual void draw() { _draw(); }
|
||||
virtual ~dMenu_Insect_c();
|
||||
|
||||
|
||||
@@ -55,6 +55,10 @@ public:
|
||||
u8 getLetterNum();
|
||||
void setHIO(bool);
|
||||
|
||||
#if TARGET_PC
|
||||
bool pointerWait();
|
||||
#endif
|
||||
|
||||
virtual void draw() { _draw(); }
|
||||
virtual ~dMenu_Letter_c();
|
||||
|
||||
|
||||
@@ -80,6 +80,9 @@ public:
|
||||
void setBButtonString(u16);
|
||||
bool isRumbleSupported();
|
||||
bool dpdMenuMove();
|
||||
#if TARGET_PC
|
||||
bool pointerConfirmSelect();
|
||||
#endif
|
||||
void paneResize(u64);
|
||||
void initialize();
|
||||
void yesnoMenuMoveAnmInitSet(int, int);
|
||||
|
||||
@@ -74,6 +74,9 @@ public:
|
||||
void clacEllipsePlotAverage(int, f32, f32);
|
||||
bool dpdMove();
|
||||
u8 openExplain(u8);
|
||||
#if TARGET_PC
|
||||
bool pointerMove();
|
||||
#endif
|
||||
|
||||
virtual void draw() { _draw(); }
|
||||
virtual ~dMenu_Ring_c();
|
||||
@@ -215,6 +218,7 @@ private:
|
||||
bool mCursorInterpPrevAngular;
|
||||
bool mCursorInterpCurrAngular;
|
||||
bool mCursorInterpInit;
|
||||
bool mPointerTouchPressHoveredCurrent;
|
||||
#endif
|
||||
};
|
||||
|
||||
|
||||
@@ -266,6 +266,8 @@ public:
|
||||
|
||||
#if TARGET_PC
|
||||
void menuSaveWide();
|
||||
bool pointerSaveSelect();
|
||||
bool pointerYesNoSelect(bool errorSelect, u8 errParam = 0, u8 soundParam = 0);
|
||||
#endif
|
||||
|
||||
void _draw2();
|
||||
|
||||
@@ -49,6 +49,10 @@ public:
|
||||
u8 getSkillNum();
|
||||
void setHIO(bool);
|
||||
|
||||
#if TARGET_PC
|
||||
bool pointerWait();
|
||||
#endif
|
||||
|
||||
virtual void draw() { _draw(); }
|
||||
virtual ~dMenu_Skill_c();
|
||||
|
||||
|
||||
@@ -360,7 +360,12 @@ inline void dMsgObject_demoMessageGroup() {
|
||||
}
|
||||
|
||||
inline bool dMsgObject_isTalkNowCheck() {
|
||||
#if TARGET_PC
|
||||
dMsgObject_c* msgObject = dMsgObject_getMsgObjectClass();
|
||||
return msgObject != NULL && msgObject->getStatus() != 1;
|
||||
#else
|
||||
return dMsgObject_getMsgObjectClass()->getStatus() == 1 ? false : true;
|
||||
#endif
|
||||
}
|
||||
|
||||
inline bool dMsgObject_isKillMessageFlag() {
|
||||
@@ -497,7 +502,12 @@ inline void dMsgObject_onMsgSend() {
|
||||
}
|
||||
|
||||
inline bool dMsgObject_isFukidashiCheck() {
|
||||
#if TARGET_PC
|
||||
dMsgObject_c* msgObject = dMsgObject_getMsgObjectClass();
|
||||
return msgObject != NULL && msgObject->getScrnDrawPtr() != NULL;
|
||||
#else
|
||||
return dMsgObject_getMsgObjectClass()->getScrnDrawPtr() == NULL ? false : true;
|
||||
#endif
|
||||
}
|
||||
|
||||
inline void* dMsgObject_getTalkHeap() {
|
||||
|
||||
@@ -49,6 +49,10 @@ public:
|
||||
void selectScale();
|
||||
void selectTrans();
|
||||
void selectAnimeTransform(int);
|
||||
#if TARGET_PC
|
||||
bool pointerMove();
|
||||
bool consumePointerClick();
|
||||
#endif
|
||||
|
||||
void setOffsetX(f32 i_offsetX) { mOffsetX = i_offsetX; }
|
||||
bool isAnimeUpdate(int param_0) { return (field_0x114 & (u8)(1 << param_0)) ? TRUE : FALSE; }
|
||||
|
||||
@@ -521,13 +521,13 @@ private:
|
||||
/* 0x019 */ u8 field_0x19;
|
||||
/* 0x01A */ u8 field_0x1a;
|
||||
/* 0x01B */ u8 field_0x1b;
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
/* 0x01C */ dPa_simpleEcallBack field_0x1c[48];
|
||||
#else
|
||||
/* 0x01C */ dPa_simpleEcallBack field_0x1c[25];
|
||||
#endif
|
||||
/* 0x210 */ level_c field_0x210;
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
u8 mSceneCount;
|
||||
#endif
|
||||
};
|
||||
|
||||
@@ -59,7 +59,7 @@ private:
|
||||
/* 0x18 */ JKRHeap* heap;
|
||||
/* 0x1C */ JKRSolidHeap* mDataHeap;
|
||||
/* 0x20 */ void** mRes;
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
/* 0x24 */ int mSize;
|
||||
#endif
|
||||
}; // Size: 0x24
|
||||
|
||||
+4
-1
@@ -1008,7 +1008,7 @@ public:
|
||||
|
||||
static const int ZONE_MAX = 0x20;
|
||||
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
/* 0x000 */ u8 unk_0x0;
|
||||
/* 0x001 */ char unk_0x1;
|
||||
/* 0x000 */ u8 unk_0x2[0x48 - 0x2];
|
||||
@@ -1029,6 +1029,9 @@ public:
|
||||
/* 0xF30 */ s64 mSaveTotalTime;
|
||||
#if DEBUG
|
||||
/* 0xF80 */ flagFile_c mFlagFile;
|
||||
#elif PARTIAL_DEBUG
|
||||
// flagFile_c's ctor/virtuals are only defined under #if DEBUG (d_save.cpp)
|
||||
alignas(flagFile_c) u8 mFlagFile[sizeof(flagFile_c)];
|
||||
#endif
|
||||
}; // Size: 0xF38
|
||||
|
||||
|
||||
+4
-4
@@ -538,7 +538,7 @@ public:
|
||||
/* vt[86] */ virtual stage_tgsc_class* getDrTg(void) const = 0;
|
||||
/* vt[87] */ virtual void setDoor(stage_tgsc_class*) = 0;
|
||||
/* vt[88] */ virtual stage_tgsc_class* getDoor(void) const = 0;
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
virtual void setUnit(void*) = 0;
|
||||
virtual void* getUnit() = 0;
|
||||
#endif
|
||||
@@ -796,7 +796,7 @@ public:
|
||||
virtual stage_tgsc_class* getDrTg(void) const { return mDrTg; }
|
||||
virtual void setDoor(stage_tgsc_class* i_Door) { mDoor = i_Door; }
|
||||
virtual stage_tgsc_class* getDoor(void) const { return mDoor; }
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
virtual void setUnit(void* i_Unit) { mUnit = i_Unit; }
|
||||
virtual void* getUnit() { return mUnit; }
|
||||
#endif
|
||||
@@ -845,7 +845,7 @@ public:
|
||||
/* 0x54 */ stage_tgsc_class* mDrTg;
|
||||
/* 0x58 */ stage_tgsc_class* mDoor;
|
||||
/* 0x5C */ dStage_FloorInfo_c* mFloorInfo;
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
/* 0x60 */ void* mUnit;
|
||||
#endif
|
||||
/* 0x60 */ u16 mPlayerNum;
|
||||
@@ -990,7 +990,7 @@ public:
|
||||
/* vt[86] */ virtual stage_tgsc_class* getDrTg(void) const { return mDrTg; }
|
||||
/* vt[87] */ virtual void setDoor(stage_tgsc_class* i_Door) { mDoor = i_Door; }
|
||||
/* vt[88] */ virtual stage_tgsc_class* getDoor(void) const { return mDoor; }
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
virtual void setUnit(void* i_Unit) {
|
||||
UNUSED(i_Unit);
|
||||
OSReport("stage non unit list data !!\n");
|
||||
|
||||
@@ -97,6 +97,9 @@ public:
|
||||
private:
|
||||
#if DEBUG
|
||||
/* 0x00 */ dVibTest_c mVibTest;
|
||||
#elif PARTIAL_DEBUG
|
||||
// dVibTest_c's ctor/virtuals are only defined under #if DEBUG (d_vibration.cpp)
|
||||
alignas(dVibTest_c) u8 mVibTest[sizeof(dVibTest_c)];
|
||||
#endif
|
||||
|
||||
class {
|
||||
|
||||
@@ -9,6 +9,8 @@ namespace dusk {
|
||||
enum class ActionBinds {
|
||||
FIRST_PERSON_CAMERA,
|
||||
CALL_MIDNA,
|
||||
OPEN_MAP_SCREEN,
|
||||
TOGGLE_MINIMAP,
|
||||
OPEN_DUSKLIGHT_MENU,
|
||||
TURBO_SPEED_BUTTON,
|
||||
COUNT,
|
||||
@@ -32,6 +34,12 @@ bool isActionBound(ActionBinds action, u32 port);
|
||||
|
||||
void updateActionBindings();
|
||||
|
||||
void setVirtualActionBind(ActionBinds action, u32 port, bool pressed, bool available = true);
|
||||
|
||||
void clearVirtualActionBind(ActionBinds action, u32 port);
|
||||
|
||||
void clearAllVirtualActionBinds();
|
||||
|
||||
bool getActionBindTrig(ActionBinds action, u32 port);
|
||||
|
||||
bool getActionBindHold(ActionBinds action, u32 port);
|
||||
|
||||
+69
-7
@@ -1,9 +1,11 @@
|
||||
#ifndef DUSK_CONFIG_HPP
|
||||
#define DUSK_CONFIG_HPP
|
||||
|
||||
#include <concepts>
|
||||
#include <functional>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <stdexcept>
|
||||
#include "nlohmann/json.hpp"
|
||||
|
||||
#include "config_var.hpp"
|
||||
|
||||
namespace dusk::config {
|
||||
@@ -40,7 +42,7 @@ public:
|
||||
[[nodiscard]] virtual nlohmann::json dumpToJson(const ConfigVarBase& cVar) const = 0;
|
||||
};
|
||||
|
||||
template<ConfigValue T>
|
||||
template <ConfigValue T>
|
||||
class ConfigImpl : public ConfigImplBase {
|
||||
// Just downcasting the references...
|
||||
void loadFromJson(ConfigVarBase& cVar, const nlohmann::json& jsonValue) const final {
|
||||
@@ -90,20 +92,28 @@ public:
|
||||
void Register(ConfigVarBase& configVar);
|
||||
|
||||
/**
|
||||
* \brief Indicate that all registrations have happened and everything should lock in.
|
||||
* \brief Unregister a CVar, detaching it from the config system.
|
||||
*
|
||||
* If the CVar carries a user-set value (Value or Speedrun layer), it is stashed as an
|
||||
* unregistered key: Save() keeps writing it, and a later Register() of the same name restores
|
||||
* it through the normal back-fill path. The CVar may be destroyed after this returns.
|
||||
*/
|
||||
void FinishRegistration();
|
||||
void unregister(ConfigVarBase& configVar);
|
||||
|
||||
/**
|
||||
* \brief Load config from the standard user preferences location.
|
||||
*/
|
||||
void LoadFromUserPreferences();
|
||||
void LoadFromFileName(const char* path);
|
||||
void load_from_user_preferences();
|
||||
void load_from_file_name(const char* path);
|
||||
|
||||
void load_arg_override(std::string_view name, std::string_view value);
|
||||
|
||||
void shutdown();
|
||||
|
||||
/**
|
||||
* \brief Save the config to file.
|
||||
*/
|
||||
void Save();
|
||||
void save();
|
||||
|
||||
/**
|
||||
* \brief Get a registered CVar by name.
|
||||
@@ -124,6 +134,58 @@ void ClearAllActionBindings(int port);
|
||||
*/
|
||||
void EnumerateRegistered(std::function<void(ConfigVarBase&)> callback);
|
||||
|
||||
/**
|
||||
* \brief Type-erased change callback. previousValue points at the value before the mutation
|
||||
* (a `const T*` for a `ConfigVar<T>`) and is valid only for the duration of the call.
|
||||
*/
|
||||
using ChangeCallback = std::function<void(ConfigVarBase& cVar, const void* previousValue)>;
|
||||
|
||||
/**
|
||||
* \brief Token identifying a change subscription. 0 is never a valid token.
|
||||
*/
|
||||
using Subscription = u64;
|
||||
|
||||
/**
|
||||
* \brief Subscribe to changes of the named CVar (registered or not yet registered).
|
||||
*
|
||||
* Fired synchronously on the mutating thread (in practice the game thread) whenever the CVar's
|
||||
* effective value changes at runtime: setValue, override/speedrun setters and clears. Values
|
||||
* applied by config load or launch arguments do *not* notify: loads happen during startup
|
||||
* before the subsystems callbacks push values into are initialized, and each subsystem reads
|
||||
* its initial value itself at its own init. Callbacks may mutate other CVars; a nested
|
||||
* mutation of the same CVar applies but does not re-notify.
|
||||
*/
|
||||
Subscription subscribe(std::string_view name, ChangeCallback callback);
|
||||
|
||||
/**
|
||||
* \brief Typed convenience overload: the callback receives the current and previous values.
|
||||
*/
|
||||
template <ConfigValue T, typename Callback>
|
||||
requires std::invocable<Callback, const T&, const T&> Subscription subscribe(
|
||||
ConfigVar<T>& cVar, Callback&& callback) {
|
||||
return subscribe(cVar.getName(),
|
||||
[&cVar, cb = std::forward<Callback>(callback)](ConfigVarBase&, const void* previousValue) {
|
||||
cb(cVar.getValue(), *static_cast<const T*>(previousValue));
|
||||
});
|
||||
}
|
||||
|
||||
void unsubscribe(Subscription token);
|
||||
|
||||
/**
|
||||
* \brief Register a CVar and attach a change callback in one step.
|
||||
*
|
||||
* Useful for pushing settings into external systems (e.g. aurora) from one place instead of
|
||||
* every UI setter. The callback fires only for runtime changes (see subscribe); not when
|
||||
* loaded from config or launch arguments.
|
||||
*/
|
||||
template <ConfigValue T, typename Callback>
|
||||
requires std::invocable<Callback, const T&, const T&> Subscription Register(
|
||||
ConfigVar<T>& cVar, Callback&& onChange) {
|
||||
auto subscription = subscribe(cVar, std::forward<Callback>(onChange));
|
||||
Register(static_cast<ConfigVarBase&>(cVar));
|
||||
return subscription;
|
||||
}
|
||||
|
||||
template <ConfigValue T>
|
||||
const ConfigImplBase* GetConfigImpl() {
|
||||
static ConfigImpl<T> config;
|
||||
|
||||
@@ -2,9 +2,12 @@
|
||||
#define DUSK_CONFIG_VAR_HPP
|
||||
|
||||
#include "dolphin/types.h"
|
||||
#include <type_traits>
|
||||
#include <concepts>
|
||||
#include <cstdlib>
|
||||
#include <limits>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
|
||||
/**
|
||||
* The configuration system.
|
||||
@@ -68,7 +71,7 @@ protected:
|
||||
/**
|
||||
* The name of this CVar, used in the configuration file.
|
||||
*/
|
||||
const char* name;
|
||||
std::string name;
|
||||
|
||||
/**
|
||||
* Whether this CVar has been registered with the global managing logic.
|
||||
@@ -86,8 +89,8 @@ protected:
|
||||
*/
|
||||
const ConfigImplBase* impl;
|
||||
|
||||
ConfigVarBase(const char* name, const ConfigImplBase* impl);
|
||||
virtual ~ConfigVarBase() = default;
|
||||
ConfigVarBase(const ConfigVarBase&) = delete;
|
||||
ConfigVarBase(std::string name, const ConfigImplBase* impl);
|
||||
|
||||
/**
|
||||
* Check that the CVar is registered, aborting if this is not the case.
|
||||
@@ -97,7 +100,22 @@ protected:
|
||||
abort();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether any change subscriber (see config::subscribe) is attached to this CVar's name.
|
||||
*/
|
||||
[[nodiscard]] bool has_subscribers() const;
|
||||
|
||||
/**
|
||||
* Notify change subscribers (see config::subscribe) that the effective value of this CVar
|
||||
* changed. Called by mutators after the change has been applied; previousValue points at
|
||||
* the old value (a `const T*` for a `ConfigVar<T>`), valid only for the duration of the
|
||||
* call.
|
||||
*/
|
||||
void notify_changed(const void* previousValue);
|
||||
|
||||
public:
|
||||
virtual ~ConfigVarBase();
|
||||
|
||||
/**
|
||||
* Get the name of this CVar, used in the configuration file.
|
||||
*/
|
||||
@@ -120,6 +138,7 @@ public:
|
||||
* This is necessary to make it legal to access.
|
||||
*/
|
||||
void markRegistered();
|
||||
void unmarkRegistered();
|
||||
|
||||
/**
|
||||
* Clear a speedrun-mode override if one is active on this CVar.
|
||||
@@ -139,26 +158,36 @@ concept ConfigValueInteger =
|
||||
|| std::is_same_v<T, s64>
|
||||
|| std::is_same_v<T, u64>;
|
||||
|
||||
template <typename T>
|
||||
struct ConfigValueTraits {
|
||||
static constexpr bool enabled = false;
|
||||
};
|
||||
|
||||
/**
|
||||
* \brief Concept that defines the legal set of types that can be used for CVar values.
|
||||
*
|
||||
* Valid types cannot be cv-qualified and must be basic primitive types (int, float, bool),
|
||||
* strings, or enums of the basic primitives.
|
||||
* strings, enums of the basic primitives, or explicitly-enabled structured settings.
|
||||
*/
|
||||
template <typename T>
|
||||
concept ConfigValue =
|
||||
!std::is_const_v<T>
|
||||
&& !std::is_volatile_v<T>
|
||||
&& std::equality_comparable<T>
|
||||
&& (std::is_same_v<T, bool>
|
||||
|| ConfigValueInteger<T>
|
||||
|| std::is_same_v<T, f32>
|
||||
|| std::is_same_v<T, f64>
|
||||
|| std::is_same_v<T, std::string>
|
||||
|| (std::is_enum_v<T> && ConfigValueInteger<std::underlying_type_t<T>>));
|
||||
|| (std::is_enum_v<T> && ConfigValueInteger<std::underlying_type_t<T>>)
|
||||
|| ConfigValueTraits<T>::enabled);
|
||||
|
||||
template <ConfigValue T>
|
||||
const ConfigImplBase* GetConfigImpl();
|
||||
|
||||
template <ConfigValue T>
|
||||
class ConfigImpl;
|
||||
|
||||
template <typename T>
|
||||
struct ConfigEnumRange {
|
||||
static constexpr auto min = std::numeric_limits<std::underlying_type_t<T>>::min();
|
||||
@@ -185,10 +214,12 @@ public:
|
||||
* @param arg Arguments to forward to construct the default value.
|
||||
*/
|
||||
template <typename... Args>
|
||||
ConfigVar(const char* name, Args&&... arg)
|
||||
: ConfigVarBase(name, GetConfigImpl<T>()), defaultValue(std::forward<Args>(arg)...),
|
||||
ConfigVar(std::string name, Args&&... arg)
|
||||
: ConfigVarBase(std::move(name), GetConfigImpl<T>()), defaultValue(std::forward<Args>(arg)...),
|
||||
value(), overrideValue() {}
|
||||
|
||||
ConfigVar(ConfigVar const&) = delete;
|
||||
|
||||
/**
|
||||
* \brief Get the current value of the CVar.
|
||||
*
|
||||
@@ -227,6 +258,7 @@ public:
|
||||
*/
|
||||
void setValue(T newValue, bool replaceOverride = true) {
|
||||
checkRegistered();
|
||||
const auto previous = previous_for_notify();
|
||||
value = std::move(newValue);
|
||||
|
||||
if (replaceOverride) {
|
||||
@@ -235,6 +267,7 @@ public:
|
||||
} else if (layer != ConfigVarLayer::Override) {
|
||||
layer = ConfigVarLayer::Value;
|
||||
}
|
||||
notify_if_changed(previous);
|
||||
}
|
||||
|
||||
operator const T&() {
|
||||
@@ -251,8 +284,10 @@ public:
|
||||
*/
|
||||
void setOverrideValue(T newValue) {
|
||||
checkRegistered();
|
||||
const auto previous = previous_for_notify();
|
||||
overrideValue = std::move(newValue);
|
||||
layer = ConfigVarLayer::Override;
|
||||
notify_if_changed(previous);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -266,25 +301,31 @@ public:
|
||||
void setSpeedrunValue(T newValue) {
|
||||
checkRegistered();
|
||||
if (layer != ConfigVarLayer::Override) {
|
||||
const auto previous = previous_for_notify();
|
||||
priorLayer = layer;
|
||||
overrideValue = std::move(newValue);
|
||||
layer = ConfigVarLayer::Speedrun;
|
||||
notify_if_changed(previous);
|
||||
}
|
||||
}
|
||||
|
||||
void clearOverride() {
|
||||
checkRegistered();
|
||||
if (layer == ConfigVarLayer::Override) {
|
||||
const auto previous = previous_for_notify();
|
||||
overrideValue = {};
|
||||
layer = ConfigVarLayer::Value;
|
||||
notify_if_changed(previous);
|
||||
}
|
||||
}
|
||||
|
||||
void clearSpeedrunOverride() override {
|
||||
checkRegistered();
|
||||
if (layer == ConfigVarLayer::Speedrun) {
|
||||
const auto previous = previous_for_notify();
|
||||
overrideValue = {};
|
||||
layer = priorLayer;
|
||||
notify_if_changed(previous);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -298,6 +339,48 @@ public:
|
||||
const ConfigVarLayer effectiveLayer = (layer == ConfigVarLayer::Speedrun) ? priorLayer : layer;
|
||||
return effectiveLayer == ConfigVarLayer::Default ? defaultValue : value;
|
||||
}
|
||||
|
||||
private:
|
||||
// The config loader applies values through the silent load_* methods below.
|
||||
friend class ConfigImpl<T>;
|
||||
|
||||
/**
|
||||
* Copy of the effective value before a mutation, taken only when someone is subscribed.
|
||||
*/
|
||||
[[nodiscard]] std::optional<T> previous_for_notify() const {
|
||||
return has_subscribers() ? std::optional<T>{getValue()} : std::nullopt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify subscribers if the effective value actually changed across a mutation.
|
||||
*/
|
||||
void notify_if_changed(const std::optional<T>& previous) {
|
||||
if (previous.has_value() && !(getValue() == *previous)) {
|
||||
notify_changed(&*previous);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* setValue(newValue, false) without notifying change subscribers. Used when loading config:
|
||||
* loads happen during startup before the subsystems change callbacks push values into are
|
||||
* initialized, and each subsystem applies the loaded value itself at its own init.
|
||||
*/
|
||||
void load_value(T newValue) {
|
||||
checkRegistered();
|
||||
value = std::move(newValue);
|
||||
if (layer != ConfigVarLayer::Override) {
|
||||
layer = ConfigVarLayer::Value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* setOverrideValue without notifying change subscribers (see load_value).
|
||||
*/
|
||||
void load_override_value(T newValue) {
|
||||
checkRegistered();
|
||||
overrideValue = std::move(newValue);
|
||||
layer = ConfigVarLayer::Override;
|
||||
}
|
||||
};
|
||||
|
||||
using ActionBindConfigVar = ConfigVar<int>;
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
|
||||
#include <dolphin/gx/GXAurora.h>
|
||||
#include <dolphin/gx/GXExtra.h>
|
||||
#include "tracy/Tracy.hpp"
|
||||
|
||||
#include "profiling.hpp"
|
||||
|
||||
#if DUSK_GFX_DEBUG_GROUPS
|
||||
#define GX_DEBUG_GROUP(name, ...) \
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
#pragma once
|
||||
|
||||
#include "dolphin/types.h"
|
||||
|
||||
class CPaneMgr;
|
||||
|
||||
namespace dusk::menu_pointer {
|
||||
|
||||
using TargetId = u16;
|
||||
constexpr TargetId InvalidTarget = 0xffff;
|
||||
|
||||
enum class Context {
|
||||
None,
|
||||
FileSelect,
|
||||
Save,
|
||||
ItemWheel,
|
||||
Collection,
|
||||
Options,
|
||||
Dialog,
|
||||
};
|
||||
|
||||
enum class Phase {
|
||||
Move,
|
||||
Press,
|
||||
Release,
|
||||
Cancel,
|
||||
};
|
||||
|
||||
struct State {
|
||||
f32 x = 0.0f;
|
||||
f32 y = 0.0f;
|
||||
bool valid = false;
|
||||
bool down = false;
|
||||
bool pressed = false;
|
||||
bool released = false;
|
||||
bool clicked = false;
|
||||
bool touch = false;
|
||||
};
|
||||
|
||||
void begin_game_frame() noexcept;
|
||||
void end_game_frame() noexcept;
|
||||
void begin_context(Context context) noexcept;
|
||||
bool handle_fallthrough_pointer(f32 x, f32 y, Phase phase, bool touch, s32 mouseButton = -1) noexcept;
|
||||
|
||||
bool active() noexcept;
|
||||
bool enabled() noexcept;
|
||||
bool mouse_capture_active() noexcept;
|
||||
const State& state() noexcept;
|
||||
void set_hover_target(TargetId target) noexcept;
|
||||
bool consume_click() noexcept;
|
||||
bool peek_click() noexcept;
|
||||
void set_dialog_choice(u8 choice, bool clicked) noexcept;
|
||||
bool get_dialog_choice(u8& choice) noexcept;
|
||||
bool consume_dialog_click(u8& choice) noexcept;
|
||||
void defer_activation(Context context, TargetId target) noexcept;
|
||||
bool consume_deferred_activation(Context context, TargetId target) noexcept;
|
||||
void clear_deferred_activation(Context context) noexcept;
|
||||
u32 suppressed_pad_buttons(u32 port) noexcept;
|
||||
void finish_pad_suppression_read(u32 port) noexcept;
|
||||
|
||||
bool hit_rect(f32 left, f32 top, f32 right, f32 bottom, f32 padding = 0.0f) noexcept;
|
||||
bool hit_pane(CPaneMgr* pane, f32 padding = 0.0f) noexcept;
|
||||
bool hit_pane(J2DPane* pane, f32 padding = 0.0f) noexcept;
|
||||
|
||||
} // namespace dusk::menu_pointer
|
||||
@@ -0,0 +1,245 @@
|
||||
#pragma once
|
||||
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <ranges>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
#include "dusk/config.hpp"
|
||||
#include "dusk/config_var.hpp"
|
||||
#include "mods/api.h"
|
||||
|
||||
namespace dusk::mods {
|
||||
struct LoadedMod;
|
||||
class ModBundle;
|
||||
} // namespace dusk::mods
|
||||
|
||||
struct ModContext {
|
||||
dusk::mods::LoadedMod* mod = nullptr;
|
||||
};
|
||||
|
||||
namespace dusk::mods::loader {
|
||||
class NativeModule;
|
||||
} // namespace dusk::mods::loader
|
||||
|
||||
namespace dusk::mods {
|
||||
|
||||
struct ModDependencyEdge {
|
||||
LoadedMod* mod = nullptr;
|
||||
bool required = false;
|
||||
};
|
||||
|
||||
struct ModManifestInfo {
|
||||
struct Import {
|
||||
std::string id;
|
||||
uint16_t major = 0;
|
||||
bool required = false;
|
||||
bool operator==(const Import&) const = default;
|
||||
};
|
||||
struct Export {
|
||||
std::string id;
|
||||
uint16_t major = 0;
|
||||
bool operator==(const Export&) const = default;
|
||||
};
|
||||
std::vector<Import> imports;
|
||||
std::vector<Export> exports;
|
||||
bool operator==(const ModManifestInfo&) const = default;
|
||||
};
|
||||
|
||||
struct ModMetadata {
|
||||
std::string id;
|
||||
std::string name;
|
||||
std::string version;
|
||||
std::string author;
|
||||
std::string description;
|
||||
std::string iconPath;
|
||||
std::string bannerPath;
|
||||
};
|
||||
|
||||
struct ModSearchDir {
|
||||
std::filesystem::path path;
|
||||
// Directory bundles dlopen their native lib in place instead of extracting it to the cache.
|
||||
// Required where extracted code cannot run (iOS), desirable for signed/read-only installs.
|
||||
bool inPlaceNative = false;
|
||||
// Native library location for platforms that restrict placement (e.g. iOS/tvOS Frameworks/)
|
||||
std::filesystem::path nativeLibDir;
|
||||
};
|
||||
|
||||
struct NativeMod {
|
||||
std::unique_ptr<loader::NativeModule> handle;
|
||||
const ModManifest* manifest = nullptr;
|
||||
ModContext** contextSymbol = nullptr;
|
||||
|
||||
ModInitializeFn fn_initialize = nullptr;
|
||||
ModUpdateFn fn_update = nullptr;
|
||||
ModShutdownFn fn_shutdown = nullptr;
|
||||
};
|
||||
|
||||
enum class NativeModStatus : u8 {
|
||||
/**
|
||||
* Mod does not have native code included.
|
||||
*/
|
||||
None,
|
||||
|
||||
/**
|
||||
* Native code mod loaded successfully.
|
||||
*
|
||||
* Note that this only indicates load status of the native library. If the native lib throws in
|
||||
* its init function, it will still be disabled!
|
||||
*/
|
||||
Loaded,
|
||||
|
||||
/**
|
||||
* This build was compiled without native mod support!
|
||||
*/
|
||||
BuildDisabled,
|
||||
|
||||
/**
|
||||
* Mod ships native libraries, but none matches this build's platform and architecture.
|
||||
*/
|
||||
ModMissingPlatform,
|
||||
|
||||
/**
|
||||
* Mod is built for a different ABI version than this build of the game.
|
||||
*/
|
||||
ApiVersionMismatch,
|
||||
|
||||
/**
|
||||
* Mod is missing a required native API export.
|
||||
*/
|
||||
MissingExport,
|
||||
|
||||
/**
|
||||
* Unknown error loading the native mod.
|
||||
*/
|
||||
Unknown,
|
||||
};
|
||||
|
||||
struct LoadedMod {
|
||||
ModMetadata metadata;
|
||||
std::string modPath;
|
||||
std::string dir;
|
||||
|
||||
uint32_t searchDirIndex = 0;
|
||||
// Native lib is dlopen'd in place and stays resident for the session. Reload is unsupported.
|
||||
bool inPlace = false;
|
||||
|
||||
std::unique_ptr<ConfigVar<bool> > cvarIsEnabled;
|
||||
config::Subscription enabledSubscription = 0;
|
||||
|
||||
bool active = false;
|
||||
bool loadFailed = false;
|
||||
std::string failureReason;
|
||||
|
||||
// mod_initialize succeeded; a mod_shutdown is owed on deactivation.
|
||||
bool initialized = false;
|
||||
// Static service exports are currently present in the registry.
|
||||
bool servicesRegistered = false;
|
||||
// Lifecycle state last applied by the loader; diffed against cvarIsEnabled to pick up
|
||||
// runtime enable/disable requests.
|
||||
bool enabledApplied = false;
|
||||
// Deactivated because a provider it imports from was disabled, not by its own cvar.
|
||||
bool suspendedByProvider = false;
|
||||
// Bumped per native lib extraction so every dlopen sees a fresh path (and thus a fresh
|
||||
// image with fresh statics; a previous dlclose may not fully unmap). Also bumped by
|
||||
// asset-only reloads, so it doubles as a generation for anything caching per-mod content.
|
||||
uint32_t cacheGeneration = 0;
|
||||
// Currently extracted native library, empty if none.
|
||||
std::string nativePath;
|
||||
|
||||
NativeModStatus nativeStatus = NativeModStatus::None;
|
||||
std::unique_ptr<NativeMod> native;
|
||||
std::unique_ptr<ModContext> context;
|
||||
|
||||
// Shared with overlay file registrations so in-flight DVD reads survive disable/reload.
|
||||
std::shared_ptr<ModBundle> bundle;
|
||||
|
||||
ModManifestInfo manifestInfo;
|
||||
|
||||
// Mods this mod imports services from, and mods importing services from this mod.
|
||||
std::vector<ModDependencyEdge> dependencies;
|
||||
std::vector<ModDependencyEdge> dependents;
|
||||
};
|
||||
|
||||
class ModLoader {
|
||||
public:
|
||||
static ModLoader& instance();
|
||||
|
||||
void set_search_dirs(std::vector<ModSearchDir> dirs) { m_searchDirs = std::move(dirs); }
|
||||
void set_cache_dir(std::filesystem::path dir) { m_cacheDir = std::move(dir); }
|
||||
void init();
|
||||
void tick();
|
||||
void shutdown();
|
||||
|
||||
void request_enable(std::string_view id);
|
||||
void request_disable(std::string_view id);
|
||||
void request_reload(std::string_view id);
|
||||
void notify_mod_failure(LoadedMod& mod, bool firstFailure);
|
||||
|
||||
[[nodiscard]] auto mods() const {
|
||||
return m_mods | std::views::transform([](const auto& m) -> LoadedMod& { return *m; });
|
||||
}
|
||||
|
||||
[[nodiscard]] auto active_mods() const {
|
||||
return mods() | std::views::filter([](const auto& m) { return m.active; });
|
||||
}
|
||||
|
||||
private:
|
||||
enum class RequestKind : u8 { Enable, Disable, Reload };
|
||||
struct Request {
|
||||
std::string modId;
|
||||
RequestKind kind;
|
||||
};
|
||||
// ModLoader::tick runs inside fapGm_Execute, so code from an unloading mod can still be
|
||||
// live on the stack (its frame unwinds after the tick). dlclose is therefore deferred to
|
||||
// the next tick, by which point every per-frame entry into the mod should have returned.
|
||||
struct RetiredNative {
|
||||
std::unique_ptr<NativeMod> native;
|
||||
std::string path;
|
||||
};
|
||||
|
||||
std::vector<std::unique_ptr<LoadedMod> > m_mods;
|
||||
std::vector<ModSearchDir> m_searchDirs;
|
||||
std::filesystem::path m_cacheDir;
|
||||
std::vector<Request> m_pendingRequests;
|
||||
std::vector<std::string> m_pendingFailures;
|
||||
std::vector<RetiredNative> m_retiredNatives;
|
||||
bool m_initialized = false;
|
||||
bool m_startupComplete = false;
|
||||
|
||||
void try_load_mod(const std::filesystem::path& modPath, bool fromDir, uint32_t searchDirIndex);
|
||||
void load_native(LoadedMod& mod, const std::string& dllEntry);
|
||||
// Resolved <nativeLibDir>/<mod id><ext> if it exists on disk, empty otherwise.
|
||||
[[nodiscard]] std::filesystem::path external_native_lib_path(const LoadedMod& mod) const;
|
||||
void unload_native(LoadedMod& mod);
|
||||
// Registers exports (if needed), resolves imports and runs mod_initialize.
|
||||
// Returns whether the mod ended up active; failures go through fail_mod.
|
||||
bool activate_mod(LoadedMod& mod);
|
||||
// Runs mod_shutdown (if needed), detaches the mod from every service, and unloads the
|
||||
// native lib. Must only run with no mod code on the stack (startup, shutdown, or top of tick).
|
||||
void deactivate_mod(LoadedMod& mod);
|
||||
void init_services();
|
||||
bool register_static_service_exports(LoadedMod& mod);
|
||||
bool resolve_service_imports(LoadedMod& mod);
|
||||
[[nodiscard]] std::string describe_missing_import(
|
||||
const char* serviceId, uint16_t majorVersion, uint16_t minMinorVersion) const;
|
||||
|
||||
LoadedMod* find_mod(std::string_view id) const;
|
||||
void drain_retired_natives();
|
||||
void apply_pending_requests();
|
||||
void flush_toasts();
|
||||
void on_enabled_changed(LoadedMod& mod);
|
||||
// Deactivates `target` (if needed) and its transitive dependents, optionally re-reads the
|
||||
// bundle from disk, then reactivates whatever the current cvar/provider state allows.
|
||||
void apply_lifecycle_change(LoadedMod& target, bool reload);
|
||||
// `target` plus transitive active/suspended dependents, in m_mods (init) order.
|
||||
std::vector<LoadedMod*> collect_lifecycle_set(LoadedMod& target);
|
||||
bool reload_bundle(LoadedMod& mod);
|
||||
bool ensure_native_loaded(LoadedMod& mod);
|
||||
};
|
||||
|
||||
using ModIndex = std::ranges::range_difference_t<decltype(std::declval<ModLoader>().mods())>;
|
||||
|
||||
} // namespace dusk::mods
|
||||
@@ -4,9 +4,9 @@
|
||||
|
||||
namespace dusk::mouse {
|
||||
void read();
|
||||
void getAimDeltas(float& out_yaw, float& out_pitch);
|
||||
void getCameraDeltas(float& out_yaw, float& out_pitch);
|
||||
void get_aim_deltas(float& out_yaw, float& out_pitch);
|
||||
void get_camera_deltas(float& out_yaw, float& out_pitch);
|
||||
void handle_event(const SDL_Event& event) noexcept;
|
||||
void onFocusLost();
|
||||
void onFocusGained();
|
||||
void on_focus_lost();
|
||||
void on_focus_gained();
|
||||
} // namespace dusk::mouse
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
#pragma once
|
||||
|
||||
#if defined(__has_include)
|
||||
#if __has_include(<tracy/Tracy.hpp>)
|
||||
#include <tracy/Tracy.hpp>
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifndef ZoneScoped
|
||||
#define ZoneScoped
|
||||
#define ZoneScopedN(name)
|
||||
#endif
|
||||
+34
-18
@@ -1,13 +1,14 @@
|
||||
#ifndef DUSK_CONFIG_H
|
||||
#define DUSK_CONFIG_H
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
|
||||
#include "dusk/config_var.hpp"
|
||||
#include "dusk/ui/controls.hpp"
|
||||
|
||||
namespace dusk {
|
||||
|
||||
using namespace config;
|
||||
using config::ConfigVar;
|
||||
using config::ActionBindConfigVar;
|
||||
|
||||
enum class BloomMode : int {
|
||||
Off = 0,
|
||||
@@ -40,17 +41,18 @@ enum class DiscVerificationState : u8 {
|
||||
HashMismatch,
|
||||
};
|
||||
|
||||
enum class GyroMode : u8 {
|
||||
Sensor = 0,
|
||||
Mouse = 1,
|
||||
};
|
||||
|
||||
enum class FrameInterpMode : u8 {
|
||||
Off = 0,
|
||||
Capped = 1,
|
||||
Unlimited = 2,
|
||||
};
|
||||
|
||||
enum class TouchTargeting : u8 {
|
||||
Hybrid = 0,
|
||||
Hold = 1,
|
||||
Switch = 2,
|
||||
};
|
||||
|
||||
enum class MenuScaling : u8 {
|
||||
GameCube = 0,
|
||||
Wii = 1,
|
||||
@@ -96,18 +98,18 @@ struct ConfigEnumRange<DiscVerificationState> {
|
||||
static constexpr auto max = DiscVerificationState::HashMismatch;
|
||||
};
|
||||
|
||||
template <>
|
||||
struct ConfigEnumRange<GyroMode> {
|
||||
static constexpr auto min = GyroMode::Sensor;
|
||||
static constexpr auto max = GyroMode::Mouse;
|
||||
};
|
||||
|
||||
template <>
|
||||
struct ConfigEnumRange<FrameInterpMode> {
|
||||
static constexpr auto min = FrameInterpMode::Off;
|
||||
static constexpr auto max = FrameInterpMode::Unlimited;
|
||||
};
|
||||
|
||||
template <>
|
||||
struct ConfigEnumRange<TouchTargeting> {
|
||||
static constexpr auto min = TouchTargeting::Hybrid;
|
||||
static constexpr auto max = TouchTargeting::Switch;
|
||||
};
|
||||
|
||||
template <>
|
||||
struct ConfigEnumRange<MenuScaling> {
|
||||
static constexpr auto min = MenuScaling::GameCube;
|
||||
@@ -119,6 +121,11 @@ struct ConfigEnumRange<MagicArmorMode> {
|
||||
static constexpr auto min = MagicArmorMode::NORMAL;
|
||||
static constexpr auto max = MagicArmorMode::COSMETIC;
|
||||
};
|
||||
|
||||
template <>
|
||||
struct ConfigValueTraits<ui::ControlLayout> {
|
||||
static constexpr bool enabled = true;
|
||||
};
|
||||
} // namespace config
|
||||
|
||||
// Persistent user settings
|
||||
@@ -134,6 +141,9 @@ struct UserSettings {
|
||||
ConfigVar<bool> enableFpsOverlay;
|
||||
ConfigVar<int> fpsOverlayCorner;
|
||||
ConfigVar<int> maxFrameRate;
|
||||
ConfigVar<bool> rememberWindowSize;
|
||||
ConfigVar<int> lastWindowWidth;
|
||||
ConfigVar<int> lastWindowHeight;
|
||||
} video;
|
||||
|
||||
struct {
|
||||
@@ -218,6 +228,10 @@ struct UserSettings {
|
||||
ConfigVar<float> mouseCameraSensitivity;
|
||||
ConfigVar<bool> invertMouseY;
|
||||
ConfigVar<bool> freeCamera;
|
||||
ConfigVar<bool> enableTouchControls;
|
||||
ConfigVar<TouchTargeting> touchTargeting;
|
||||
ConfigVar<bool> enableMenuPointer;
|
||||
ConfigVar<ui::ControlLayout> touchControlsLayout;
|
||||
ConfigVar<bool> invertCameraXAxis;
|
||||
ConfigVar<bool> invertCameraYAxis;
|
||||
ConfigVar<bool> invertFirstPersonXAxis;
|
||||
@@ -226,6 +240,8 @@ struct UserSettings {
|
||||
ConfigVar<bool> invertAirSwimY;
|
||||
ConfigVar<float> freeCameraXSensitivity;
|
||||
ConfigVar<float> freeCameraYSensitivity;
|
||||
ConfigVar<float> touchCameraXSensitivity;
|
||||
ConfigVar<float> touchCameraYSensitivity;
|
||||
ConfigVar<bool> debugFlyCam;
|
||||
ConfigVar<bool> debugFlyCamLockEvents;
|
||||
ConfigVar<bool> allowBackgroundInput;
|
||||
@@ -250,6 +266,7 @@ struct UserSettings {
|
||||
ConfigVar<bool> fastSpinner;
|
||||
ConfigVar<MagicArmorMode> armorRupeeDrain;
|
||||
ConfigVar<bool> invincibleEnemies;
|
||||
ConfigVar<bool> easyQuickSpin;
|
||||
|
||||
// Technical
|
||||
ConfigVar<bool> restoreWiiGlitches;
|
||||
@@ -273,7 +290,6 @@ struct UserSettings {
|
||||
ConfigVar<DiscVerificationState> isoVerification;
|
||||
ConfigVar<std::string> graphicsBackend;
|
||||
ConfigVar<bool> skipPreLaunchUI;
|
||||
ConfigVar<bool> showPipelineCompilation;
|
||||
ConfigVar<bool> wasPresetChosen;
|
||||
ConfigVar<bool> checkForUpdates;
|
||||
ConfigVar<int> cardFileType;
|
||||
@@ -284,6 +300,8 @@ struct UserSettings {
|
||||
struct {
|
||||
std::array<ActionBindConfigVar, 4> firstPersonCamera;
|
||||
std::array<ActionBindConfigVar, 4> callMidna;
|
||||
std::array<ActionBindConfigVar, 4> openMapScreen;
|
||||
std::array<ActionBindConfigVar, 4> toggleMinimap;
|
||||
std::array<ActionBindConfigVar, 4> openDusklightMenu;
|
||||
std::array<ActionBindConfigVar, 4> turboSpeedButton;
|
||||
} actionBindings;
|
||||
@@ -315,6 +333,4 @@ struct TransientSettings {
|
||||
|
||||
TransientSettings& getTransientSettings();
|
||||
|
||||
}
|
||||
|
||||
#endif // DUSK_CONFIG_H
|
||||
} // namespace dusk
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
#ifndef DUSK_TEXTURE_REPLACEMENTS_HPP
|
||||
#define DUSK_TEXTURE_REPLACEMENTS_HPP
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace dusk::texture_replacements {
|
||||
|
||||
// Mod replacements are prioritized *over* user replacements (<data folder>/texture_replacements/)
|
||||
inline constexpr int32_t kUserTextureReplacementPriority = -1'000'000;
|
||||
|
||||
void reload();
|
||||
void set_enabled(bool enabled);
|
||||
void shutdown();
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
#pragma once
|
||||
|
||||
namespace dusk::touch_camera {
|
||||
|
||||
constexpr float YAW_DEGREES_PER_DP = 0.34f;
|
||||
constexpr float PITCH_DEGREES_PER_DP = 0.22f;
|
||||
|
||||
void add_delta(float yaw_dp, float pitch_dp) noexcept;
|
||||
bool consume_delta(float& yaw_dp, float& pitch_dp) noexcept;
|
||||
void clear() noexcept;
|
||||
|
||||
} // namespace dusk::touch_camera
|
||||
@@ -36,7 +36,7 @@ typedef struct node_create_request {
|
||||
/* 0x58 */ s16 name;
|
||||
/* 0x5C */ void* data;
|
||||
/* 0x60 */ s16 unk_0x60;
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
/* 0x64 */ int unk_0x64;
|
||||
/* 0x68 */ int unk_0x68;
|
||||
#endif
|
||||
|
||||
@@ -114,6 +114,19 @@ inline int __builtin_clz(unsigned int v) {
|
||||
|
||||
#endif
|
||||
|
||||
// Data symbols exported from the main exe need dllimport on the mod side.
|
||||
// DUSK_BUILDING_GAME is defined for the game build so the same headers work in both.
|
||||
#if defined(TARGET_PC) && defined(_WIN32) && !defined(DUSK_BUILDING_GAME)
|
||||
#define DUSK_GAME_EXTERN extern __declspec(dllimport)
|
||||
#define DUSK_GAME_DATA __declspec(dllimport)
|
||||
#elif defined(TARGET_PC) && defined(_WIN32) && defined(DUSK_BUILDING_GAME)
|
||||
#define DUSK_GAME_EXTERN extern __declspec(dllexport)
|
||||
#define DUSK_GAME_DATA __declspec(dllexport)
|
||||
#else
|
||||
#define DUSK_GAME_EXTERN extern
|
||||
#define DUSK_GAME_DATA
|
||||
#endif
|
||||
|
||||
#define FAST_DIV(x, n) (x >> (n / 2))
|
||||
|
||||
#define SQUARE(x) ((x) * (x))
|
||||
|
||||
@@ -11,13 +11,13 @@ class mDoAud_zelAudio_c : public Z2AudioMgr {
|
||||
public:
|
||||
void reset();
|
||||
mDoAud_zelAudio_c() {
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
setMode(2);
|
||||
#endif
|
||||
}
|
||||
~mDoAud_zelAudio_c() {}
|
||||
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
u8 getMode() { return field_0x13bd; }
|
||||
void setMode(u8 mode) { field_0x13bd = mode; }
|
||||
|
||||
|
||||
@@ -35,6 +35,11 @@ public:
|
||||
/* 0x4 */ s8 mNo;
|
||||
/* 0x5 */ u8 mCount;
|
||||
#else
|
||||
#if PARTIAL_DEBUG
|
||||
// Initialized here since the DEBUG ctor doesn't run.
|
||||
/* 0x4 */ s8 mNo = -1;
|
||||
/* 0x5 */ u8 mCount = 0;
|
||||
#endif
|
||||
virtual ~mDoHIO_entry_c() {}
|
||||
#endif
|
||||
};
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
#pragma once
|
||||
|
||||
#ifdef __cplusplus
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
extern "C" {
|
||||
#else
|
||||
#include <assert.h>
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#endif
|
||||
|
||||
#if defined(_WIN32)
|
||||
#define MOD_EXPORT __declspec(dllexport)
|
||||
#else
|
||||
#define MOD_EXPORT __attribute__((visibility("default")))
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
#define MOD_EXTERN_C extern "C"
|
||||
#else
|
||||
#define MOD_EXTERN_C
|
||||
#endif
|
||||
|
||||
#define MOD_ABI_VERSION 5u
|
||||
#define MOD_ERROR_MESSAGE_SIZE 512u
|
||||
|
||||
typedef struct ModContext ModContext;
|
||||
|
||||
typedef enum ModResult {
|
||||
MOD_OK = 0,
|
||||
MOD_ERROR = 1,
|
||||
MOD_UNAVAILABLE = 2,
|
||||
MOD_UNSUPPORTED = 3,
|
||||
MOD_CONFLICT = 4,
|
||||
MOD_INVALID_ARGUMENT = 5,
|
||||
} ModResult;
|
||||
|
||||
static_assert(sizeof(ModResult) == 4, "mod SDK enums must be int-sized; do not build mods with -fshort-enums");
|
||||
|
||||
typedef struct ModError {
|
||||
uint32_t struct_size;
|
||||
ModResult code;
|
||||
char message[MOD_ERROR_MESSAGE_SIZE];
|
||||
} ModError;
|
||||
|
||||
#define MOD_ERROR_INIT {sizeof(ModError), MOD_OK, {0}}
|
||||
|
||||
/*
|
||||
* Opaque per-mod context, populated by the host before mod_initialize is called.
|
||||
* Pass it as the first argument to every service call; it identifies the calling
|
||||
* mod for attribution (logging, resource lookup, hook ownership, etc.).
|
||||
*/
|
||||
MOD_EXPORT extern ModContext* mod_ctx;
|
||||
|
||||
/*
|
||||
* Service versioning contract:
|
||||
*
|
||||
* A service is a struct of function pointers, beginning with a ServiceHeader.
|
||||
* Compatibility is tracked with a major/minor version pair:
|
||||
*
|
||||
* - A major version bump is a breaking change. Different majors are distinct
|
||||
* services; the registry never matches an import against a different major.
|
||||
* - A minor version bump may only append fields to the end of the struct.
|
||||
* Existing fields must keep their offsets and semantics.
|
||||
*
|
||||
* Providers: exporting minor N means every function pointer introduced at or
|
||||
* below N is populated (non-NULL). struct_size reflects the compiled struct.
|
||||
*
|
||||
* Importers: importing with min_minor_version N guarantees (enforced at load
|
||||
* time) that the resolved service is at least minor N, so any field introduced
|
||||
* at or below N may be used unconditionally, with no availability checks.
|
||||
* Fields newer than the declared min_minor_version must be gated behind
|
||||
* SERVICE_HAS plus a NULL check on the pointer itself.
|
||||
*
|
||||
* Load ordering: a manifest import of another mod's service (required or
|
||||
* optional) guarantees that the provider's mod_initialize completed before the
|
||||
* importer's runs, and deferred services published during the provider's
|
||||
* initialization resolve into import slots just like static exports. If a
|
||||
* provider fails to load, mods that required its services fail in turn. Mods
|
||||
* whose required imports form a cycle all fail to load; a cycle involving an
|
||||
* optional import is broken by dropping the ordering guarantee (not the
|
||||
* resolution) of that optional import. Dynamic lookups via
|
||||
* HostService::get_service carry no ordering guarantee: they see whatever has
|
||||
* been published at call time.
|
||||
*/
|
||||
typedef struct ServiceHeader {
|
||||
uint32_t struct_size;
|
||||
uint16_t major_version;
|
||||
uint16_t minor_version;
|
||||
} ServiceHeader;
|
||||
|
||||
#define SERVICE_HEADER(service_type, major, minor) {sizeof(service_type), (major), (minor)}
|
||||
|
||||
#define SERVICE_HAS(service, service_type, field) \
|
||||
((service) != NULL && \
|
||||
(service)->header.struct_size >= \
|
||||
(uint32_t)(offsetof(service_type, field) + sizeof(((service_type*)0)->field)))
|
||||
|
||||
typedef enum ServiceImportFlags {
|
||||
SERVICE_IMPORT_REQUIRED = 0u,
|
||||
SERVICE_IMPORT_OPTIONAL = 1u << 0u,
|
||||
} ServiceImportFlags;
|
||||
|
||||
typedef enum ServiceExportFlags {
|
||||
SERVICE_EXPORT_STATIC = 0u,
|
||||
SERVICE_EXPORT_DEFERRED = 1u << 0u,
|
||||
} ServiceExportFlags;
|
||||
|
||||
typedef struct ServiceImport {
|
||||
uint32_t struct_size;
|
||||
const char* service_id;
|
||||
uint16_t major_version;
|
||||
uint16_t min_minor_version;
|
||||
uint32_t flags;
|
||||
void* slot;
|
||||
} ServiceImport;
|
||||
|
||||
typedef struct ServiceExport {
|
||||
uint32_t struct_size;
|
||||
const char* service_id;
|
||||
uint16_t major_version;
|
||||
uint16_t minor_version;
|
||||
uint32_t flags;
|
||||
const void* service;
|
||||
} ServiceExport;
|
||||
|
||||
typedef struct ModManifest {
|
||||
uint32_t struct_size;
|
||||
uint32_t abi_version;
|
||||
const ServiceImport* imports;
|
||||
size_t import_count;
|
||||
const ServiceExport* exports;
|
||||
size_t export_count;
|
||||
} ModManifest;
|
||||
|
||||
typedef const ModManifest* (*ModGetManifestFn)(void);
|
||||
|
||||
typedef ModResult (*ModInitializeFn)(ModError* out_error);
|
||||
typedef ModResult (*ModUpdateFn)(ModError* out_error);
|
||||
typedef ModResult (*ModShutdownFn)(ModError* out_error);
|
||||
|
||||
MOD_EXPORT const ModManifest* mod_get_manifest(void);
|
||||
|
||||
MOD_EXPORT ModResult mod_initialize(ModError* out_error);
|
||||
MOD_EXPORT ModResult mod_update(ModError* out_error);
|
||||
MOD_EXPORT ModResult mod_shutdown(ModError* out_error);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,464 @@
|
||||
#pragma once
|
||||
|
||||
#include "mods/svc/hook.h"
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
|
||||
namespace dusk::mods {
|
||||
|
||||
template <class T>
|
||||
T arg(void* argsRaw, int n) noexcept {
|
||||
void** args = static_cast<void**>(argsRaw);
|
||||
return *static_cast<std::add_pointer_t<std::remove_reference_t<T> > >(args[n]);
|
||||
}
|
||||
|
||||
template <class T>
|
||||
std::remove_reference_t<T>& arg_ref(void* argsRaw, int n) noexcept {
|
||||
void** args = static_cast<void**>(argsRaw);
|
||||
return *static_cast<std::add_pointer_t<std::remove_reference_t<T> > >(args[n]);
|
||||
}
|
||||
|
||||
template <class F>
|
||||
void* mfp_addr(F fn) noexcept {
|
||||
void* p = nullptr;
|
||||
static_assert(sizeof(fn) >= sizeof(void*), "unexpected function pointer size");
|
||||
std::memcpy(&p, &fn, sizeof(void*));
|
||||
return p;
|
||||
}
|
||||
|
||||
/* A string usable as a template argument: carries the hook target's symbol name and
|
||||
* makes each NamedHook instantiation's static state unique. */
|
||||
template <size_t N>
|
||||
struct FixedString {
|
||||
char chars[N]{};
|
||||
constexpr FixedString(const char (&s)[N]) noexcept {
|
||||
for (size_t i = 0; i < N; ++i) {
|
||||
chars[i] = s[i];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
namespace detail {
|
||||
|
||||
template <class T>
|
||||
constexpr std::string_view class_name() {
|
||||
#if defined(__clang__) || defined(__GNUC__)
|
||||
// "... class_name() [T = daAlink_c]" / "... [with T = daAlink_c; ...]"
|
||||
constexpr std::string_view fn = __PRETTY_FUNCTION__;
|
||||
constexpr size_t start = fn.find("T = ") + 4;
|
||||
return fn.substr(start, fn.find_first_of(";]", start) - start);
|
||||
#elif defined(_MSC_VER)
|
||||
// "... class_name<class daAlink_c>(void)"
|
||||
constexpr std::string_view fn = __FUNCSIG__;
|
||||
constexpr size_t start = fn.find("class_name<") + 11;
|
||||
constexpr std::string_view name = fn.substr(start, fn.rfind(">(") - start);
|
||||
if constexpr (name.starts_with("class ")) {
|
||||
return name.substr(6);
|
||||
} else if constexpr (name.starts_with("struct ")) {
|
||||
return name.substr(7);
|
||||
} else {
|
||||
return name;
|
||||
}
|
||||
#else
|
||||
#error "unsupported compiler"
|
||||
#endif
|
||||
}
|
||||
|
||||
/* The manifest name of C's vtable. Only unscoped, non-template class names are
|
||||
* supported (an empty result fails resolution and the install reports it). */
|
||||
template <class C>
|
||||
constexpr auto vtable_symbol() {
|
||||
constexpr std::string_view name = class_name<C>();
|
||||
constexpr bool simple = name.find_first_of(":<> ") == std::string_view::npos;
|
||||
// "_ZTV" + decimal length + name / "??_7" + name + "@@6B@", NUL-terminated
|
||||
std::array<char, name.size() + 12> out{};
|
||||
if constexpr (!simple) {
|
||||
return out;
|
||||
}
|
||||
size_t n = 0;
|
||||
#if defined(_WIN32)
|
||||
for (char c : {'?', '?', '_', '7'}) {
|
||||
out[n++] = c;
|
||||
}
|
||||
for (char c : name) {
|
||||
out[n++] = c;
|
||||
}
|
||||
for (char c : {'@', '@', '6', 'B', '@'}) {
|
||||
out[n++] = c;
|
||||
}
|
||||
#else
|
||||
for (char c : {'_', 'Z', 'T', 'V'}) {
|
||||
out[n++] = c;
|
||||
}
|
||||
size_t len = name.size();
|
||||
char digits[8]{};
|
||||
size_t d = 0;
|
||||
while (len != 0) {
|
||||
digits[d++] = static_cast<char>('0' + len % 10);
|
||||
len /= 10;
|
||||
}
|
||||
while (d != 0) {
|
||||
out[n++] = digits[--d];
|
||||
}
|
||||
for (char c : name) {
|
||||
out[n++] = c;
|
||||
}
|
||||
#endif
|
||||
return out;
|
||||
}
|
||||
|
||||
#if defined(_WIN32)
|
||||
/* Follow jump stubs, then match the MSVC vcall thunk a virtual mfp points at.
|
||||
* Returns the vtable slot's byte offset, or npos when fn is not a vcall thunk. */
|
||||
inline size_t vcall_slot_offset(const void*& fn) noexcept {
|
||||
constexpr size_t npos = static_cast<size_t>(-1);
|
||||
#if defined(_M_X64) || defined(__x86_64__)
|
||||
const auto* p = static_cast<const uint8_t*>(fn);
|
||||
for (int i = 0; i < 8 && p[0] == 0xE9; ++i) { // incremental-link stubs
|
||||
int32_t rel;
|
||||
std::memcpy(&rel, p + 1, 4);
|
||||
p += 5 + rel;
|
||||
}
|
||||
fn = p;
|
||||
// The vptr load. Unoptimized clang-cl thunks spill/reload rcx first
|
||||
// (push rax; mov [rsp], rcx; mov rcx, [rsp]), so scan a short window.
|
||||
const uint8_t* q = nullptr;
|
||||
for (int i = 0; i <= 12; ++i) {
|
||||
if (p[i] == 0x48 && p[i + 1] == 0x8B && p[i + 2] == 0x01) { // mov rax, [rcx]
|
||||
q = p + i + 3;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (q == nullptr) {
|
||||
return npos;
|
||||
}
|
||||
if (q[0] == 0xFF && q[1] == 0x20) { // jmp [rax] (MSVC)
|
||||
return 0;
|
||||
}
|
||||
if (q[0] == 0xFF && q[1] == 0x60) { // jmp [rax + imm8]
|
||||
return static_cast<int8_t>(q[2]);
|
||||
}
|
||||
if (q[0] == 0xFF && q[1] == 0xA0) { // jmp [rax + imm32]
|
||||
int32_t off;
|
||||
std::memcpy(&off, q + 2, 4);
|
||||
return off;
|
||||
}
|
||||
// clang-cl: mov rax, [rax + off]; (pop r10;) jmp rax. Requiring the jmp rax
|
||||
// distinguishes the thunk from an ordinary getter that begins the same way.
|
||||
if (q[0] == 0x48 && q[1] == 0x8B && (q[2] == 0x00 || q[2] == 0x40 || q[2] == 0x80)) {
|
||||
size_t off = 0;
|
||||
const uint8_t* r = q + 3;
|
||||
if (q[2] == 0x40) {
|
||||
off = static_cast<int8_t>(q[3]);
|
||||
r = q + 4;
|
||||
} else if (q[2] == 0x80) {
|
||||
int32_t off32;
|
||||
std::memcpy(&off32, q + 3, 4);
|
||||
off = off32;
|
||||
r = q + 7;
|
||||
}
|
||||
for (int i = 0; i <= 8; ++i) {
|
||||
if (r[i] == 0xFF && r[i + 1] == 0xE0) { // jmp rax (48 REX optional)
|
||||
return off;
|
||||
}
|
||||
}
|
||||
}
|
||||
return npos;
|
||||
#elif defined(_M_ARM64) || defined(__aarch64__)
|
||||
const auto* p = static_cast<const uint8_t*>(fn);
|
||||
uint32_t insn[3];
|
||||
for (int i = 0; i < 8; ++i) { // incremental-link `b` stubs
|
||||
std::memcpy(insn, p, 4);
|
||||
if ((insn[0] & 0xFC000000u) != 0x14000000u) {
|
||||
break;
|
||||
}
|
||||
const auto imm26 = static_cast<int32_t>(insn[0] << 6) >> 6;
|
||||
p += static_cast<intptr_t>(imm26) * 4;
|
||||
}
|
||||
fn = p;
|
||||
std::memcpy(insn, p, 12);
|
||||
// ldr Xt, [x0]; ldr Xs, [Xt, #imm12*8]; br Xs
|
||||
if ((insn[0] & 0xFFFFFFE0u) != 0xF9400000u) {
|
||||
return npos;
|
||||
}
|
||||
const uint32_t t = insn[0] & 0x1Fu;
|
||||
if ((insn[1] & 0xFFC003E0u) != (0xF9400000u | (t << 5))) {
|
||||
return npos;
|
||||
}
|
||||
const uint32_t s = insn[1] & 0x1Fu;
|
||||
if (insn[2] != (0xD61F0000u | (s << 5))) {
|
||||
return npos;
|
||||
}
|
||||
return ((insn[1] >> 10) & 0xFFFu) * 8;
|
||||
#else
|
||||
(void)fn;
|
||||
return npos;
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
/* Code address of the member function a mfp designates. Virtual mfps don't carry
|
||||
* one; recover it from the class's vtable (resolved from the symbol manifest), so
|
||||
* Hook works uniformly on virtual and non-virtual members. */
|
||||
template <class C, class F>
|
||||
ModResult member_target(const HookService* hooks, F mfp, void** out) {
|
||||
*out = nullptr;
|
||||
uintptr_t words[sizeof(F) > sizeof(uintptr_t) ? 2 : 1] = {};
|
||||
std::memcpy(words, &mfp, sizeof(words) < sizeof(F) ? sizeof(words) : sizeof(F));
|
||||
|
||||
#if defined(_WIN32)
|
||||
const void* fn = reinterpret_cast<const void*>(words[0]);
|
||||
const size_t slot = vcall_slot_offset(fn);
|
||||
if (slot == static_cast<size_t>(-1)) { // not a vcall thunk: direct address
|
||||
*out = const_cast<void*>(fn);
|
||||
return MOD_OK;
|
||||
}
|
||||
void* vtable = nullptr;
|
||||
const ModResult resolved = hooks->resolve(mod_ctx, vtable_symbol<C>().data(), &vtable, nullptr);
|
||||
if (resolved != MOD_OK) {
|
||||
return resolved;
|
||||
}
|
||||
// ??_7 points at the first slot.
|
||||
*out = *reinterpret_cast<void**>(static_cast<char*>(vtable) + slot);
|
||||
#else
|
||||
#if defined(__aarch64__) || defined(__arm__)
|
||||
// AAPCS C++ ABI: the virtual flag is bit 0 of the adjustment word (function
|
||||
// addresses can't spare their low bit), and ptr holds the slot offset directly.
|
||||
const bool isVirtual = (words[1] & 1) != 0;
|
||||
const uintptr_t thisAdjust = words[1] >> 1;
|
||||
const uintptr_t slotOffset = words[0];
|
||||
#else
|
||||
// Itanium C++ ABI: virtual mfps set bit 0 of ptr; the slot offset is ptr - 1.
|
||||
const bool isVirtual = (words[0] & 1) != 0;
|
||||
const uintptr_t thisAdjust = words[1];
|
||||
const uintptr_t slotOffset = words[0] - 1;
|
||||
#endif
|
||||
if (!isVirtual) { // non-virtual: the address itself
|
||||
*out = reinterpret_cast<void*>(words[0]);
|
||||
return MOD_OK;
|
||||
}
|
||||
if (thisAdjust != 0) {
|
||||
// this-adjusting mfp (member of a secondary base): the slot offset is
|
||||
// relative to a vtable we can't locate. Hook the overrider by name instead.
|
||||
return MOD_UNSUPPORTED;
|
||||
}
|
||||
void* vtable = nullptr;
|
||||
const ModResult resolved = hooks->resolve(mod_ctx, vtable_symbol<C>().data(), &vtable, nullptr);
|
||||
if (resolved != MOD_OK) {
|
||||
return resolved;
|
||||
}
|
||||
// _ZTV points at the offset-to-top slot; the address point mfps index from is
|
||||
// two pointers in (past offset-to-top and the typeinfo pointer).
|
||||
*out = *reinterpret_cast<void**>(static_cast<char*>(vtable) + 2 * sizeof(void*) + slotOffset);
|
||||
#endif
|
||||
return *out != nullptr ? MOD_OK : MOD_UNAVAILABLE;
|
||||
}
|
||||
|
||||
} // namespace detail
|
||||
|
||||
/* Trampoline generator + per-target state shared by Hook and NamedHook. Tag makes
|
||||
* each hooked target's statics distinct; the target address is filled in at install. */
|
||||
template <class Tag, class R, class... A>
|
||||
struct HookImpl {
|
||||
static inline R (*g_orig)(A...) = nullptr;
|
||||
static inline const HookService* hooks = nullptr;
|
||||
static inline void* target = nullptr;
|
||||
|
||||
static bool dispatch_pre(void* args, void* retval) {
|
||||
if (hooks == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
int skipOriginal = 0;
|
||||
const ModResult result = hooks->dispatch_pre(mod_ctx, target, args, retval, &skipOriginal);
|
||||
return result == MOD_OK && skipOriginal != 0;
|
||||
}
|
||||
|
||||
static void dispatch_post(void* args, void* retval) {
|
||||
if (hooks != nullptr) {
|
||||
hooks->dispatch_post(mod_ctx, target, args, retval);
|
||||
}
|
||||
}
|
||||
|
||||
static R trampoline(A... args) {
|
||||
if constexpr (sizeof...(A) == 0) {
|
||||
if constexpr (std::is_void_v<R>) {
|
||||
const bool skipOriginal = dispatch_pre(nullptr, nullptr);
|
||||
if (!skipOriginal) {
|
||||
g_orig(args...);
|
||||
}
|
||||
dispatch_post(nullptr, nullptr);
|
||||
} else {
|
||||
R result{};
|
||||
const bool skipOriginal =
|
||||
dispatch_pre(nullptr, static_cast<void*>(std::addressof(result)));
|
||||
if (!skipOriginal) {
|
||||
result = g_orig(args...);
|
||||
}
|
||||
dispatch_post(nullptr, static_cast<void*>(std::addressof(result)));
|
||||
return result;
|
||||
}
|
||||
} else {
|
||||
void* ptrs[] = {static_cast<void*>(std::addressof(args))...};
|
||||
if constexpr (std::is_void_v<R>) {
|
||||
const bool skipOriginal = dispatch_pre(static_cast<void*>(ptrs), nullptr);
|
||||
if (!skipOriginal) {
|
||||
g_orig(args...);
|
||||
}
|
||||
dispatch_post(static_cast<void*>(ptrs), nullptr);
|
||||
} else {
|
||||
R result{};
|
||||
const bool skipOriginal = dispatch_pre(
|
||||
static_cast<void*>(ptrs), static_cast<void*>(std::addressof(result)));
|
||||
if (!skipOriginal) {
|
||||
result = g_orig(args...);
|
||||
}
|
||||
dispatch_post(static_cast<void*>(ptrs), static_cast<void*>(std::addressof(result)));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
namespace detail {
|
||||
template <auto Target>
|
||||
using TargetTag = std::integral_constant<decltype(Target), Target>;
|
||||
template <FixedString Name>
|
||||
struct NameTag {};
|
||||
} // namespace detail
|
||||
|
||||
/*
|
||||
* Typed hook on a function named at compile time (&daAlink_c::execute, &free_fn).
|
||||
* Member functions may be virtual: the install decodes the member function pointer and hooks the
|
||||
* class's own overrider.
|
||||
*/
|
||||
template <auto Target>
|
||||
struct Hook;
|
||||
|
||||
template <class C, class R, class... A, R (C::*Target)(A...)>
|
||||
struct Hook<Target> : HookImpl<detail::TargetTag<Target>, R, C*, A...> {
|
||||
static ModResult resolve_target(const HookService* hooks, void** out) {
|
||||
return detail::member_target<C>(hooks, Target, out);
|
||||
}
|
||||
};
|
||||
|
||||
template <class C, class R, class... A, R (C::*Target)(A...) const>
|
||||
struct Hook<Target> : HookImpl<detail::TargetTag<Target>, R, const C*, A...> {
|
||||
static ModResult resolve_target(const HookService* hooks, void** out) {
|
||||
return detail::member_target<C>(hooks, Target, out);
|
||||
}
|
||||
};
|
||||
|
||||
template <class R, class... A, R (*Target)(A...)>
|
||||
struct Hook<Target> : HookImpl<detail::TargetTag<Target>, R, A...> {
|
||||
static ModResult resolve_target(const HookService*, void** out) {
|
||||
*out = mfp_addr(Target);
|
||||
return MOD_OK;
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
* Typed hook on a function by its symbol name, for targets you can't name in C++: file-local
|
||||
* statics, private members, or symbols without a header. The signature is written free-style with
|
||||
* the receiver first and is *not* compiler-checked.
|
||||
*
|
||||
* using HookshotHit = dusk::mods::NamedHook<
|
||||
* "daAlink_hookshotAtHitCallBack",
|
||||
* void(fopAc_ac_c*, dCcD_GObjInf*, fopAc_ac_c*, dCcD_GObjInf*)>;
|
||||
* dusk::mods::hook_add_pre<HookshotHit>(svc_hook, on_hookshot_hit);
|
||||
*/
|
||||
template <FixedString Name, class Sig>
|
||||
struct NamedHook;
|
||||
|
||||
template <FixedString Name, class R, class... A>
|
||||
struct NamedHook<Name, R(A...)> : HookImpl<detail::NameTag<Name>, R, A...> {
|
||||
static ModResult resolve_target(const HookService* hooks, void** out) {
|
||||
HookSymbolFlags flags{};
|
||||
const ModResult resolved = hooks->resolve(mod_ctx, Name.chars, out, &flags);
|
||||
if (resolved == MOD_OK && (flags & HOOK_SYMBOL_CODE) == 0) {
|
||||
*out = nullptr;
|
||||
return MOD_INVALID_ARGUMENT;
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
};
|
||||
|
||||
template <class Entry>
|
||||
ModResult hook_install(const HookService* hooks) {
|
||||
if (hooks == nullptr) {
|
||||
return MOD_UNAVAILABLE;
|
||||
}
|
||||
|
||||
Entry::hooks = hooks;
|
||||
if (Entry::target == nullptr) {
|
||||
const ModResult resolved = Entry::resolve_target(hooks, &Entry::target);
|
||||
if (resolved != MOD_OK) {
|
||||
return resolved;
|
||||
}
|
||||
}
|
||||
return hooks->install(mod_ctx, Entry::target, reinterpret_cast<void*>(Entry::trampoline),
|
||||
reinterpret_cast<void**>(&Entry::g_orig));
|
||||
}
|
||||
|
||||
template <auto Target>
|
||||
ModResult hook_install(const HookService* hooks) {
|
||||
return hook_install<Hook<Target> >(hooks);
|
||||
}
|
||||
|
||||
template <class Entry>
|
||||
ModResult hook_add_pre(
|
||||
const HookService* hooks, HookPreFn callback, const HookOptions* options = nullptr) {
|
||||
const ModResult installed = hook_install<Entry>(hooks);
|
||||
if (installed != MOD_OK) {
|
||||
return installed;
|
||||
}
|
||||
|
||||
return hooks->add_pre(mod_ctx, Entry::target, callback, options);
|
||||
}
|
||||
|
||||
template <auto Target>
|
||||
ModResult hook_add_pre(
|
||||
const HookService* hooks, HookPreFn callback, const HookOptions* options = nullptr) {
|
||||
return hook_add_pre<Hook<Target> >(hooks, callback, options);
|
||||
}
|
||||
|
||||
template <class Entry>
|
||||
ModResult hook_add_post(
|
||||
const HookService* hooks, HookPostFn callback, const HookOptions* options = nullptr) {
|
||||
const ModResult installed = hook_install<Entry>(hooks);
|
||||
if (installed != MOD_OK) {
|
||||
return installed;
|
||||
}
|
||||
|
||||
return hooks->add_post(mod_ctx, Entry::target, callback, options);
|
||||
}
|
||||
|
||||
template <auto Target>
|
||||
ModResult hook_add_post(
|
||||
const HookService* hooks, HookPostFn callback, const HookOptions* options = nullptr) {
|
||||
return hook_add_post<Hook<Target> >(hooks, callback, options);
|
||||
}
|
||||
|
||||
template <class Entry>
|
||||
ModResult hook_replace(
|
||||
const HookService* hooks, HookReplaceFn callback, const HookOptions* options = nullptr) {
|
||||
const ModResult installed = hook_install<Entry>(hooks);
|
||||
if (installed != MOD_OK) {
|
||||
return installed;
|
||||
}
|
||||
|
||||
return hooks->replace(mod_ctx, Entry::target, callback, options);
|
||||
}
|
||||
|
||||
template <auto Target>
|
||||
ModResult hook_replace(
|
||||
const HookService* hooks, HookReplaceFn callback, const HookOptions* options = nullptr) {
|
||||
return hook_replace<Hook<Target> >(hooks, callback, options);
|
||||
}
|
||||
|
||||
} // namespace dusk::mods
|
||||
@@ -0,0 +1,138 @@
|
||||
#pragma once
|
||||
|
||||
#include "mods/api.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <type_traits>
|
||||
#include <vector>
|
||||
|
||||
namespace dusk::mods {
|
||||
|
||||
template <class Service>
|
||||
struct ServiceTraits;
|
||||
|
||||
namespace detail {
|
||||
|
||||
inline std::vector<ServiceImport>& imports() {
|
||||
static std::vector<ServiceImport> entries;
|
||||
return entries;
|
||||
}
|
||||
|
||||
inline std::vector<ServiceExport>& exports() {
|
||||
static std::vector<ServiceExport> entries;
|
||||
return entries;
|
||||
}
|
||||
|
||||
inline int register_import(ServiceImport entry) {
|
||||
imports().push_back(entry);
|
||||
return 0;
|
||||
}
|
||||
|
||||
inline int register_export(ServiceExport entry) {
|
||||
exports().push_back(entry);
|
||||
return 0;
|
||||
}
|
||||
|
||||
inline const ModManifest* manifest() {
|
||||
static ModManifest manifest{
|
||||
sizeof(ModManifest),
|
||||
MOD_ABI_VERSION,
|
||||
nullptr,
|
||||
0,
|
||||
nullptr,
|
||||
0,
|
||||
};
|
||||
|
||||
auto& importEntries = imports();
|
||||
auto& exportEntries = exports();
|
||||
manifest.imports = importEntries.data();
|
||||
manifest.import_count = importEntries.size();
|
||||
manifest.exports = exportEntries.data();
|
||||
manifest.export_count = exportEntries.size();
|
||||
return &manifest;
|
||||
}
|
||||
|
||||
} // namespace detail
|
||||
|
||||
inline ModResult set_error(ModError* outError, ModResult code, const char* message) {
|
||||
if (outError != nullptr && outError->struct_size >= sizeof(ModError)) {
|
||||
outError->code = code;
|
||||
outError->message[0] = '\0';
|
||||
if (message != nullptr) {
|
||||
std::snprintf(outError->message, sizeof(outError->message), "%s", message);
|
||||
}
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
} // namespace dusk::mods
|
||||
|
||||
#define DEFINE_MOD() \
|
||||
extern "C" { \
|
||||
MOD_EXPORT ModContext* mod_ctx = nullptr; \
|
||||
MOD_EXPORT const ModManifest* mod_get_manifest(void) { \
|
||||
return ::dusk::mods::detail::manifest(); \
|
||||
} \
|
||||
}
|
||||
|
||||
// Declares `static const service_type* variable`, filled in by the host before mod_initialize.
|
||||
// Required imports are guaranteed non-null (the mod fails to load otherwise); optional imports
|
||||
// must be checked against nullptr before use.
|
||||
#define IMPORT_SERVICE_EX( \
|
||||
service_type, variable, service_id_value, major_value, min_minor_value, flags_value) \
|
||||
static const service_type* variable = nullptr; \
|
||||
[[maybe_unused]] static const int mod_import_registration_##variable = \
|
||||
::dusk::mods::detail::register_import(ServiceImport{ \
|
||||
sizeof(ServiceImport), \
|
||||
(service_id_value), \
|
||||
static_cast<uint16_t>(major_value), \
|
||||
static_cast<uint16_t>(min_minor_value), \
|
||||
static_cast<uint32_t>(flags_value), \
|
||||
&(variable), \
|
||||
})
|
||||
|
||||
#define IMPORT_SERVICE_VERSION(service_type, variable, min_minor_value) \
|
||||
IMPORT_SERVICE_EX(service_type, variable, ::dusk::mods::ServiceTraits<service_type>::id, \
|
||||
::dusk::mods::ServiceTraits<service_type>::major_version, min_minor_value, \
|
||||
SERVICE_IMPORT_REQUIRED)
|
||||
|
||||
#define IMPORT_SERVICE(service_type, variable) IMPORT_SERVICE_VERSION(service_type, variable, 0)
|
||||
|
||||
#define IMPORT_OPTIONAL_SERVICE_VERSION(service_type, variable, min_minor_value) \
|
||||
IMPORT_SERVICE_EX(service_type, variable, ::dusk::mods::ServiceTraits<service_type>::id, \
|
||||
::dusk::mods::ServiceTraits<service_type>::major_version, min_minor_value, \
|
||||
SERVICE_IMPORT_OPTIONAL)
|
||||
|
||||
#define IMPORT_OPTIONAL_SERVICE(service_type, variable) \
|
||||
IMPORT_OPTIONAL_SERVICE_VERSION(service_type, variable, 0)
|
||||
|
||||
#define EXPORT_SERVICE_AS(instance, service_id_value) \
|
||||
namespace { \
|
||||
const int mod_export_registration_##instance = \
|
||||
::dusk::mods::detail::register_export(ServiceExport{ \
|
||||
sizeof(ServiceExport), \
|
||||
(service_id_value), \
|
||||
(instance).header.major_version, \
|
||||
(instance).header.minor_version, \
|
||||
SERVICE_EXPORT_STATIC, \
|
||||
&(instance), \
|
||||
}); \
|
||||
}
|
||||
|
||||
#define EXPORT_SERVICE(instance) \
|
||||
EXPORT_SERVICE_AS( \
|
||||
instance, ::dusk::mods::ServiceTraits<std::remove_cv_t<decltype(instance)> >::id)
|
||||
|
||||
#define EXPORT_DEFERRED_SERVICE(token, service_id_value, major_value, minor_value) \
|
||||
namespace { \
|
||||
const int mod_deferred_export_registration_##token = \
|
||||
::dusk::mods::detail::register_export(ServiceExport{ \
|
||||
sizeof(ServiceExport), \
|
||||
(service_id_value), \
|
||||
static_cast<uint16_t>(major_value), \
|
||||
static_cast<uint16_t>(minor_value), \
|
||||
SERVICE_EXPORT_DEFERRED, \
|
||||
nullptr, \
|
||||
}); \
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
#pragma once
|
||||
|
||||
#include "mods/api.h"
|
||||
|
||||
#define CONFIG_SERVICE_ID "dev.twilitrealm.dusklight.config"
|
||||
#define CONFIG_SERVICE_MAJOR 1u
|
||||
#define CONFIG_SERVICE_MINOR 0u
|
||||
|
||||
/* Handle for a config var registered by the calling mod. 0 is never a valid handle. */
|
||||
typedef uint64_t ConfigVarHandle;
|
||||
/* Handle for a change subscription. 0 is never a valid handle. */
|
||||
typedef uint64_t ConfigSubscriptionHandle;
|
||||
|
||||
typedef enum ConfigVarType {
|
||||
CONFIG_VAR_BOOL = 0, /* bool */
|
||||
CONFIG_VAR_INT = 1, /* int64_t */
|
||||
CONFIG_VAR_FLOAT = 2, /* double */
|
||||
CONFIG_VAR_STRING = 3, /* UTF-8 */
|
||||
} ConfigVarType;
|
||||
|
||||
typedef struct ConfigVarDesc {
|
||||
uint32_t struct_size;
|
||||
/* Name fragment: 1-64 characters from [A-Za-z0-9_-]. The full config key is
|
||||
* "mod.<escaped mod id>.<name>", persisted in config.json alongside host settings.
|
||||
* "enabled" is reserved by the loader. */
|
||||
const char* name;
|
||||
ConfigVarType type;
|
||||
/* Default value; only the field matching `type` is read. */
|
||||
bool default_bool;
|
||||
int64_t default_int;
|
||||
double default_float;
|
||||
const char* default_string; /* NULL means "" */
|
||||
} ConfigVarDesc;
|
||||
|
||||
#define CONFIG_VAR_DESC_INIT {sizeof(ConfigVarDesc), NULL, CONFIG_VAR_BOOL, false, 0, 0.0, NULL}
|
||||
|
||||
/* Snapshot of a var's value; only the field matching `type` is meaningful. */
|
||||
typedef struct ConfigVarValue {
|
||||
uint32_t struct_size;
|
||||
ConfigVarType type;
|
||||
bool bool_value;
|
||||
int64_t int_value;
|
||||
double float_value;
|
||||
const char* string_value; /* NUL-terminated; NULL for non-string vars */
|
||||
size_t string_length; /* excludes the NUL */
|
||||
} ConfigVarValue;
|
||||
|
||||
/*
|
||||
* Fired on the game thread whenever the var's effective value changes at runtime: the calling mod's
|
||||
* own set_* calls and any other runtime writer. Writes that leave the value unchanged do not fire,
|
||||
* and neither do values applied from config.json or --cvar during registration. `value` holds the
|
||||
* new (current) value and `previous` the one it replaced; both snapshots are valid only for the
|
||||
* duration of the call (copy string_value if you need to keep it). Setting the same var from inside
|
||||
* its own callback applies the write but is not re-notified.
|
||||
*/
|
||||
typedef void (*ConfigChangedFn)(ModContext* ctx, ConfigVarHandle var, const ConfigVarValue* value,
|
||||
const ConfigVarValue* previous, void* user_data);
|
||||
|
||||
/*
|
||||
* Scoped configuration variables.
|
||||
*
|
||||
* Registrations are owned by the calling mod and removed automatically (subscriptions included)
|
||||
* when it is disabled, reloaded, or fails. Values are saved to config.json. Writes are debounced,
|
||||
* not flushed per set.
|
||||
*/
|
||||
typedef struct ConfigService {
|
||||
ServiceHeader header;
|
||||
|
||||
/* Register a config var. If a value for the full key was saved earlier (or set via --cvar),
|
||||
* it takes effect immediately; otherwise the var starts at the default. Registering a name
|
||||
* that is already live is MOD_CONFLICT. */
|
||||
ModResult (*register_var)(
|
||||
ModContext* ctx, const ConfigVarDesc* desc, ConfigVarHandle* out_handle);
|
||||
/* Unregister a var previously registered by the calling mod. Its persisted value is kept. */
|
||||
ModResult (*unregister_var)(ModContext* ctx, ConfigVarHandle var);
|
||||
|
||||
/* Typed accessors; the type must match the registration (MOD_INVALID_ARGUMENT otherwise). */
|
||||
ModResult (*get_bool)(ModContext* ctx, ConfigVarHandle var, bool* out_value);
|
||||
ModResult (*set_bool)(ModContext* ctx, ConfigVarHandle var, bool value);
|
||||
ModResult (*get_int)(ModContext* ctx, ConfigVarHandle var, int64_t* out_value);
|
||||
ModResult (*set_int)(ModContext* ctx, ConfigVarHandle var, int64_t value);
|
||||
ModResult (*get_float)(ModContext* ctx, ConfigVarHandle var, double* out_value);
|
||||
ModResult (*set_float)(ModContext* ctx, ConfigVarHandle var, double value);
|
||||
/* Copies the NUL-terminated value into buffer. out_length (optional) receives the full
|
||||
* length excluding the NUL regardless of buffer size; call with buffer == NULL and
|
||||
* buffer_size == 0 to query the length. A non-NULL buffer that is too small fails with
|
||||
* MOD_INVALID_ARGUMENT and writes nothing. */
|
||||
ModResult (*get_string)(
|
||||
ModContext* ctx, ConfigVarHandle var, char* buffer, size_t buffer_size, size_t* out_length);
|
||||
ModResult (*set_string)(ModContext* ctx, ConfigVarHandle var, const char* value);
|
||||
|
||||
/* Subscribe to changes of a var registered by the calling mod. out_handle may be NULL if
|
||||
* the subscription is never removed manually (cleanup on mod teardown is automatic). */
|
||||
ModResult (*subscribe)(ModContext* ctx, ConfigVarHandle var, ConfigChangedFn callback,
|
||||
void* user_data, ConfigSubscriptionHandle* out_handle);
|
||||
ModResult (*unsubscribe)(ModContext* ctx, ConfigSubscriptionHandle handle);
|
||||
} ConfigService;
|
||||
|
||||
#ifdef __cplusplus
|
||||
#include "mods/service.hpp"
|
||||
|
||||
template <>
|
||||
struct dusk::mods::ServiceTraits<ConfigService> {
|
||||
static constexpr const char* id = CONFIG_SERVICE_ID;
|
||||
static constexpr uint16_t major_version = CONFIG_SERVICE_MAJOR;
|
||||
};
|
||||
#endif
|
||||
@@ -0,0 +1,30 @@
|
||||
#pragma once
|
||||
|
||||
#include "mods/api.h"
|
||||
|
||||
/*
|
||||
* Mods that link or hook game code directly must import this service; service-only and asset-only
|
||||
* mods must not.
|
||||
*
|
||||
* Major version is the game-code ABI epoch: it is bumped when game-visible struct or vtable layouts
|
||||
* change incompatibly (e.g. a TARGET_PC field added to an existing game struct). The loader's
|
||||
* ordinary version check then fails mods built against the old epoch with a clear message instead
|
||||
* of letting them corrupt memory.
|
||||
*/
|
||||
#define GAME_SERVICE_ID "dev.twilitrealm.dusklight.game"
|
||||
#define GAME_SERVICE_MAJOR 1u
|
||||
#define GAME_SERVICE_MINOR 0u
|
||||
|
||||
typedef struct GameService {
|
||||
ServiceHeader header;
|
||||
} GameService;
|
||||
|
||||
#ifdef __cplusplus
|
||||
#include "mods/service.hpp"
|
||||
|
||||
template <>
|
||||
struct dusk::mods::ServiceTraits<GameService> {
|
||||
static constexpr const char* id = GAME_SERVICE_ID;
|
||||
static constexpr uint16_t major_version = GAME_SERVICE_MAJOR;
|
||||
};
|
||||
#endif
|
||||
@@ -0,0 +1,125 @@
|
||||
#pragma once
|
||||
|
||||
#include "mods/api.h"
|
||||
|
||||
/*
|
||||
* Intercept game functions by address. Prefer the typed helpers in mods/hook.hpp
|
||||
* (hook_add_pre/hook_add_post/hook_replace over a &Class::method): they generate the
|
||||
* trampoline and hide install/dispatch, which are the low-level primitives those helpers
|
||||
* build. resolve() maps a symbol name to an address for targets you can't name at compile time
|
||||
* (file-local statics included).
|
||||
*
|
||||
* Every call is game-thread-only. Install and removal must run with no hooked function on the
|
||||
* stack; the loader guarantees this by applying mod lifecycle changes between frames, which is
|
||||
* why hooking a function that never returns (the outermost loop) makes a mod un-unloadable.
|
||||
*/
|
||||
|
||||
#define HOOK_SERVICE_ID "dev.twilitrealm.dusklight.hook"
|
||||
#define HOOK_SERVICE_MAJOR 1u
|
||||
#define HOOK_SERVICE_MINOR 0u
|
||||
|
||||
/* Symbol flags reported by resolve() */
|
||||
typedef enum HookSymbolFlags {
|
||||
HOOK_SYMBOL_CODE = 1u << 0u,
|
||||
HOOK_SYMBOL_DATA = 1u << 1u,
|
||||
/* Not exported/dynamically visible: hookable, but never linkable. */
|
||||
HOOK_SYMBOL_LOCAL = 1u << 2u,
|
||||
/* Other names share this address (ICF fold/alias): a hook intercepts them all. */
|
||||
HOOK_SYMBOL_MULTI_NAME = 1u << 3u,
|
||||
/* Resolved through a demangled display-name alias rather than the real symbol. */
|
||||
HOOK_SYMBOL_DISPLAY = 1u << 6u,
|
||||
} HookSymbolFlags;
|
||||
|
||||
/* A pre-hook's return value: whether to run the original function. */
|
||||
typedef enum HookAction {
|
||||
HOOK_CONTINUE = 0, /* run the original (and any lower-priority pre-hooks) */
|
||||
HOOK_SKIP_ORIGINAL = 1, /* cancel the original and remaining pre-hooks; post-hooks still run */
|
||||
} HookAction;
|
||||
|
||||
/* How replace resolves a second replace-hook on a target that already has one. */
|
||||
typedef enum HookReplacePolicy {
|
||||
HOOK_REPLACE_CONFLICT = 0, /* refuse with MOD_CONFLICT (the default) */
|
||||
HOOK_REPLACE_PRIORITY = 1, /* take over only if this options.priority is strictly higher */
|
||||
HOOK_REPLACE_OVERRIDE = 2, /* take over unconditionally */
|
||||
} HookReplacePolicy;
|
||||
|
||||
/*
|
||||
* Hook callbacks. `args` is an array of pointers to the call's arguments (index 0 is `this`
|
||||
* for member functions); `retval` points at the return slot (NULL for void). Read and write
|
||||
* them through dusk::mods::arg<T> / arg_ref<T> from mods/hook.hpp. `userdata` is the pointer
|
||||
* from HookOptions. All run on the game thread, in the hooked call's own stack frame.
|
||||
*/
|
||||
typedef HookAction (*HookPreFn)(ModContext* ctx, void* args, void* retval, void* userdata);
|
||||
typedef void (*HookPostFn)(ModContext* ctx, void* args, void* retval, void* userdata);
|
||||
typedef void (*HookReplaceFn)(ModContext* ctx, void* args, void* retval, void* userdata);
|
||||
|
||||
typedef struct HookOptions {
|
||||
uint32_t struct_size;
|
||||
/* Higher runs first; ties break by registration order. Applies to pre/post ordering and,
|
||||
* with HOOK_REPLACE_PRIORITY, to replace-hook takeover. */
|
||||
int32_t priority;
|
||||
HookReplacePolicy replace_policy;
|
||||
void* userdata; /* passed back to the callback */
|
||||
} HookOptions;
|
||||
|
||||
#define HOOK_OPTIONS_INIT {sizeof(HookOptions), 0, HOOK_REPLACE_CONFLICT, NULL}
|
||||
|
||||
typedef struct HookService {
|
||||
ServiceHeader header;
|
||||
|
||||
/*
|
||||
* Install a trampoline detour on fn_addr and return the address to call the original through in
|
||||
* *out_original_fn. The typed helpers generate the trampoline and call this; mods normally
|
||||
* don't. The first mod to install a given target owns the live detour; later mods register as
|
||||
* candidates so a hook survives the owner unloading (the detour is handed off and every
|
||||
* original pointer is rewritten). Idempotent per (mod, out slot).
|
||||
*/
|
||||
ModResult (*install)(
|
||||
ModContext* ctx, void* fn_addr, void* trampoline_fn, void** out_original_fn);
|
||||
|
||||
/*
|
||||
* Register a callback on an already-installed target. Pre runs before the original (and can
|
||||
* cancel it), post runs after (even if cancelled). Any number of mods may add pre/post to the
|
||||
* same target; they run in priority then registration order. replace installs a single
|
||||
* substitute for the original, managed by options.replace_policy, MOD_CONFLICT if refused.
|
||||
*/
|
||||
ModResult (*add_pre)(
|
||||
ModContext* ctx, void* fn_addr, HookPreFn callback, const HookOptions* options);
|
||||
ModResult (*add_post)(
|
||||
ModContext* ctx, void* fn_addr, HookPostFn callback, const HookOptions* options);
|
||||
ModResult (*replace)(
|
||||
ModContext* ctx, void* fn_addr, HookReplaceFn callback, const HookOptions* options);
|
||||
|
||||
/*
|
||||
* Run the registered callbacks for a target. The generated trampoline calls these; they
|
||||
* are not a mod-facing entry point. dispatch_pre reports through *out_skip_original
|
||||
* whether the original should be skipped (a pre-hook returned HOOK_SKIP_ORIGINAL, or a
|
||||
* replace-hook ran).
|
||||
*/
|
||||
ModResult (*dispatch_pre)(
|
||||
ModContext* ctx, void* fn_addr, void* args, void* retval, int* out_skip_original);
|
||||
ModResult (*dispatch_post)(ModContext* ctx, void* fn_addr, void* args, void* retval);
|
||||
|
||||
/*
|
||||
* Resolve a game symbol by name from the symbol manifest, including non-exported (static)
|
||||
* functions. Names can be either the platform's mangled name (i.e. the name passed to dlopen;
|
||||
* no Mach-O leading underscore) or the qualified function name without parameters (e.g.
|
||||
* "daAlink_c::execute"). out_flags (optional) receives HookSymbolFlags.
|
||||
*
|
||||
* Results: MOD_OK; MOD_UNSUPPORTED (no manifest for this build, missing or stale);
|
||||
* MOD_UNAVAILABLE (symbol not found); MOD_CONFLICT (name maps to more than one address: C++
|
||||
* overloads or per-TU statics; use the mangled name).
|
||||
*/
|
||||
ModResult (*resolve)(
|
||||
ModContext* ctx, const char* symbol, void** out_addr, HookSymbolFlags* out_flags);
|
||||
} HookService;
|
||||
|
||||
#ifdef __cplusplus
|
||||
#include "mods/service.hpp"
|
||||
|
||||
template <>
|
||||
struct dusk::mods::ServiceTraits<HookService> {
|
||||
static constexpr const char* id = HOOK_SERVICE_ID;
|
||||
static constexpr uint16_t major_version = HOOK_SERVICE_MAJOR;
|
||||
};
|
||||
#endif
|
||||
@@ -0,0 +1,104 @@
|
||||
#pragma once
|
||||
|
||||
#include "mods/api.h"
|
||||
|
||||
/*
|
||||
* The host service: the calling mod's identity and its runtime interface to the loader.
|
||||
* Always available; every other service can be reached from it.
|
||||
*/
|
||||
|
||||
#define HOST_SERVICE_ID "dev.twilitrealm.dusklight.host"
|
||||
#define HOST_SERVICE_MAJOR 2u
|
||||
#define HOST_SERVICE_MINOR 0u
|
||||
|
||||
/*
|
||||
* Ignore unknown values: later service minors may add events.
|
||||
*/
|
||||
typedef enum ModLifecycleEvent {
|
||||
/*
|
||||
* The subject mod is gone: its mod_shutdown has run (when it initialized at all) and
|
||||
* every service has already dropped the state it held for it. The subject's library is
|
||||
* still mapped, so pointers into it are valid to compare against, but they must not be
|
||||
* called or dereferenced after the callback returns. Drop everything keyed to the
|
||||
* mod: callbacks it registered, its ModContext*, state indexed by it.
|
||||
*/
|
||||
MOD_LIFECYCLE_DETACHED = 0,
|
||||
} ModLifecycleEvent;
|
||||
|
||||
/*
|
||||
* ctx is the watching mod's own context; subject identifies the mod the event is about.
|
||||
* subject_id is valid only for the duration of the call.
|
||||
*/
|
||||
typedef void (*ModLifecycleFn)(ModContext* ctx, ModContext* subject, const char* subject_id,
|
||||
ModLifecycleEvent event, void* user_data);
|
||||
|
||||
typedef struct HostService {
|
||||
ServiceHeader header;
|
||||
|
||||
/* Version string of the current Dusklight build. (e.g. "1.4.2") */
|
||||
const char* version;
|
||||
|
||||
/* Build id of the running game binary: PDB GUID+age on Windows, LC_UUID on macOS, GNU build-id
|
||||
* on Linux. May be empty (len 0) if the identity could not be determined. */
|
||||
const uint8_t* build_id;
|
||||
uint32_t build_id_len;
|
||||
|
||||
/*
|
||||
* Look up a service by id at call time. Unlike a manifest import, this sees whatever is
|
||||
* currently published and carries no initialization-order guarantee (see mods/api.h).
|
||||
* MOD_UNAVAILABLE if no matching service is published; *out_service is null on failure.
|
||||
*/
|
||||
ModResult (*get_service)(ModContext* ctx, const char* service_id, uint16_t major_version,
|
||||
uint16_t min_minor_version, const void** out_service);
|
||||
|
||||
/*
|
||||
* Publish a service the calling mod declared as a deferred export in its manifest.
|
||||
* Must happen during mod_initialize so importers can resolve it; `service` must stay
|
||||
* valid until the mod shuts down.
|
||||
*/
|
||||
ModResult (*publish_service)(
|
||||
ModContext* ctx, const char* service_id, uint16_t major_version, const void* service);
|
||||
|
||||
/*
|
||||
* Report an unrecoverable failure. The calling mod's services stop resolving immediately
|
||||
* and the loader fully disables it at the next safe point; `message` is shown to the user.
|
||||
* Safe to call from any mod callback.
|
||||
*/
|
||||
void (*fail)(ModContext* ctx, ModResult code, const char* message);
|
||||
|
||||
/*
|
||||
* The calling mod's manifest metadata. Returned strings remain valid while the mod is
|
||||
* loaded.
|
||||
*/
|
||||
const char* (*mod_id)(ModContext* ctx);
|
||||
const char* (*mod_name)(ModContext* ctx);
|
||||
const char* (*mod_version)(ModContext* ctx);
|
||||
|
||||
/*
|
||||
* A writable scratch directory reserved for the calling mod. Contents survive disable
|
||||
* and reload within a session, but the directory is wiped at game startup.
|
||||
*/
|
||||
const char* (*mod_dir)(ModContext* ctx);
|
||||
|
||||
/*
|
||||
* Observe other mods' lifecycle events. Any mod whose service hands out per-caller state
|
||||
* (registrations, callbacks, handles) should watch for MOD_LIFECYCLE_DETACHED and drop what it
|
||||
* holds for the subject.
|
||||
*
|
||||
* Callbacks fire on the game thread at a lifecycle safe point (never mid-frame), for
|
||||
* every mod but the watcher itself (use mod_shutdown for self-cleanup).
|
||||
*/
|
||||
ModResult (*watch_mod_lifecycle)(
|
||||
ModContext* ctx, ModLifecycleFn fn, void* user_data, uint64_t* out_handle);
|
||||
ModResult (*unwatch_mod_lifecycle)(ModContext* ctx, uint64_t handle);
|
||||
} HostService;
|
||||
|
||||
#ifdef __cplusplus
|
||||
#include "mods/service.hpp"
|
||||
|
||||
template <>
|
||||
struct dusk::mods::ServiceTraits<HostService> {
|
||||
static constexpr const char* id = HOST_SERVICE_ID;
|
||||
static constexpr uint16_t major_version = HOST_SERVICE_MAJOR;
|
||||
};
|
||||
#endif
|
||||
@@ -0,0 +1,47 @@
|
||||
#pragma once
|
||||
|
||||
#include "mods/api.h"
|
||||
|
||||
/*
|
||||
* Logging into the game's console and log files. Messages are attributed to the calling mod
|
||||
* (prefixed with its ID).
|
||||
*/
|
||||
|
||||
#define LOG_SERVICE_ID "dev.twilitrealm.dusklight.log"
|
||||
#define LOG_SERVICE_MAJOR 1u
|
||||
#define LOG_SERVICE_MINOR 0u
|
||||
|
||||
typedef enum LogLevel {
|
||||
LOG_LEVEL_TRACE = 0,
|
||||
LOG_LEVEL_DEBUG = 1,
|
||||
LOG_LEVEL_INFO = 2,
|
||||
LOG_LEVEL_WARN = 3,
|
||||
LOG_LEVEL_ERROR = 4,
|
||||
} LogLevel;
|
||||
|
||||
typedef struct LogService {
|
||||
ServiceHeader header;
|
||||
|
||||
/*
|
||||
* Write a log message at the given level.
|
||||
* `message` is a plain UTF-8 string and is copied before returning.
|
||||
*/
|
||||
void (*write)(ModContext* ctx, LogLevel level, const char* message);
|
||||
|
||||
/* Per-level shorthands for write. */
|
||||
void (*trace)(ModContext* ctx, const char* message);
|
||||
void (*debug)(ModContext* ctx, const char* message);
|
||||
void (*info)(ModContext* ctx, const char* message);
|
||||
void (*warn)(ModContext* ctx, const char* message);
|
||||
void (*error)(ModContext* ctx, const char* message);
|
||||
} LogService;
|
||||
|
||||
#ifdef __cplusplus
|
||||
#include "mods/service.hpp"
|
||||
|
||||
template <>
|
||||
struct dusk::mods::ServiceTraits<LogService> {
|
||||
static constexpr const char* id = LOG_SERVICE_ID;
|
||||
static constexpr uint16_t major_version = LOG_SERVICE_MAJOR;
|
||||
};
|
||||
#endif
|
||||
@@ -0,0 +1,57 @@
|
||||
#pragma once
|
||||
|
||||
#include "mods/api.h"
|
||||
|
||||
#define OVERLAY_SERVICE_ID "dev.twilitrealm.dusklight.overlay"
|
||||
#define OVERLAY_SERVICE_MAJOR 1u
|
||||
#define OVERLAY_SERVICE_MINOR 0u
|
||||
|
||||
/* Handle for a runtime overlay registration. 0 is never a valid handle. */
|
||||
typedef uint64_t OverlayHandle;
|
||||
|
||||
/*
|
||||
* Runtime DVD file overlays.
|
||||
*
|
||||
* Registrations are owned by the calling mod and removed automatically when it is disabled,
|
||||
* reloaded, or fails. Changes are applied at the next frame boundary; data the game has already
|
||||
* read stays in memory until it re-reads the file (sometimes on scene reload, sometimes on
|
||||
* restart).
|
||||
*
|
||||
* disc_path names the file to overlay: absolute with a leading '/', matched against the disc
|
||||
* case-insensitively (e.g. "/res/Stage/R04_00.arc"). Paths that do not exist on the disc are added
|
||||
* as new files.
|
||||
*
|
||||
* If multiple sources overlay the same path, the last one wins: a mod's runtime registrations beat
|
||||
* its static overlay/ files, and later-loaded mods beat earlier ones.
|
||||
*/
|
||||
typedef struct OverlayService {
|
||||
ServiceHeader header;
|
||||
|
||||
/*
|
||||
* Overlay disc_path with a file from the calling mod's bundle (bundle-relative path, e.g.
|
||||
* "res/replacement.arc"). The file's contents are read lazily on each open, so the bundle
|
||||
* file must not change size while registered.
|
||||
*/
|
||||
ModResult (*add_file)(
|
||||
ModContext* ctx, const char* disc_path, const char* bundle_path, OverlayHandle* out_handle);
|
||||
|
||||
/*
|
||||
* Overlay disc_path with a caller-owned buffer. The data is copied; the caller may free it
|
||||
* as soon as this returns.
|
||||
*/
|
||||
ModResult (*add_buffer)(ModContext* ctx, const char* disc_path, const void* data, size_t size,
|
||||
OverlayHandle* out_handle);
|
||||
|
||||
/* Remove a runtime overlay previously added by the calling mod. */
|
||||
ModResult (*remove)(ModContext* ctx, OverlayHandle handle);
|
||||
} OverlayService;
|
||||
|
||||
#ifdef __cplusplus
|
||||
#include "mods/service.hpp"
|
||||
|
||||
template <>
|
||||
struct dusk::mods::ServiceTraits<OverlayService> {
|
||||
static constexpr const char* id = OVERLAY_SERVICE_ID;
|
||||
static constexpr uint16_t major_version = OVERLAY_SERVICE_MAJOR;
|
||||
};
|
||||
#endif
|
||||
@@ -0,0 +1,52 @@
|
||||
#pragma once
|
||||
|
||||
#include "mods/api.h"
|
||||
|
||||
/*
|
||||
* Read-only access to the res/ tree of the calling mod's own bundle. Reload serves the new
|
||||
* bundle's contents. For writable storage, use HostService::mod_dir.
|
||||
*/
|
||||
|
||||
#define RESOURCE_SERVICE_ID "dev.twilitrealm.dusklight.resource"
|
||||
#define RESOURCE_SERVICE_MAJOR 1u
|
||||
#define RESOURCE_SERVICE_MINOR 0u
|
||||
|
||||
/*
|
||||
* A loaded resource, allocated by the service. Return every successful load with free;
|
||||
* buffers still live when the mod is disabled or reloaded are reclaimed with a warning.
|
||||
*/
|
||||
typedef struct ResourceBuffer {
|
||||
uint32_t struct_size;
|
||||
void* data;
|
||||
size_t size;
|
||||
} ResourceBuffer;
|
||||
|
||||
#define RESOURCE_BUFFER_INIT {sizeof(ResourceBuffer), NULL, 0u}
|
||||
|
||||
typedef struct ResourceService {
|
||||
ServiceHeader header;
|
||||
|
||||
/*
|
||||
* Load a file into a fresh allocation. `relative_path` is resolved against the bundle's
|
||||
* res/ directory. Absolute paths and ".." are rejected. MOD_UNAVAILABLE if the file does not
|
||||
* exist. An empty file loads as data == NULL with size 0. Previous contents of `out_buffer` are
|
||||
* overwritten, not freed.
|
||||
*/
|
||||
ModResult (*load)(ModContext* ctx, const char* relative_path, ResourceBuffer* out_buffer);
|
||||
|
||||
/*
|
||||
* Release a loaded buffer and reset it to the empty state. Safe to call on an empty or
|
||||
* already-freed buffer.
|
||||
*/
|
||||
void (*free)(ModContext* ctx, ResourceBuffer* buffer);
|
||||
} ResourceService;
|
||||
|
||||
#ifdef __cplusplus
|
||||
#include "mods/service.hpp"
|
||||
|
||||
template <>
|
||||
struct dusk::mods::ServiceTraits<ResourceService> {
|
||||
static constexpr const char* id = RESOURCE_SERVICE_ID;
|
||||
static constexpr uint16_t major_version = RESOURCE_SERVICE_MAJOR;
|
||||
};
|
||||
#endif
|
||||
@@ -0,0 +1,88 @@
|
||||
#pragma once
|
||||
|
||||
#include "mods/api.h"
|
||||
|
||||
#define TEXTURE_SERVICE_ID "dev.twilitrealm.dusklight.texture"
|
||||
#define TEXTURE_SERVICE_MAJOR 1u
|
||||
#define TEXTURE_SERVICE_MINOR 0u
|
||||
|
||||
/* Handle for a runtime texture replacement registration. 0 is never a valid handle. */
|
||||
typedef uint64_t TextureReplacementHandle;
|
||||
|
||||
typedef enum TextureKeyKind {
|
||||
/* Match a texture by the address of its in-memory GX texel data. */
|
||||
TEXTURE_KEY_POINTER = 0,
|
||||
/* Match by content: XXH64 of the base mip level (and of the referenced TLUT range for
|
||||
* palette formats), as encoded in replacement filenames / texture dumps. */
|
||||
TEXTURE_KEY_SOURCE = 1,
|
||||
} TextureKeyKind;
|
||||
|
||||
/* Wildcard values for TEXTURE_KEY_SOURCE hashes ("$" in the filename convention). */
|
||||
#define TEXTURE_HASH_WILDCARD UINT64_C(0xFFFFFFFFFFFFFFFF)
|
||||
#define TEXTURE_TLUT_WILDCARD UINT64_C(0xFFFFFFFFFFFFFFFE)
|
||||
|
||||
typedef struct TextureKey {
|
||||
uint32_t struct_size;
|
||||
TextureKeyKind kind;
|
||||
const void* pointer; /* TEXTURE_KEY_POINTER only */
|
||||
uint64_t texture_hash; /* TEXTURE_KEY_SOURCE */
|
||||
uint64_t tlut_hash; /* TEXTURE_KEY_SOURCE, palette formats only */
|
||||
uint32_t width;
|
||||
uint32_t height;
|
||||
uint32_t gx_format;
|
||||
bool has_tlut;
|
||||
} TextureKey;
|
||||
|
||||
#define TEXTURE_KEY_INIT {sizeof(TextureKey), TEXTURE_KEY_POINTER, NULL, 0u, 0u, 0u, 0u, 0u, false}
|
||||
|
||||
typedef struct TextureData {
|
||||
uint32_t struct_size;
|
||||
const void* data; /* texel data laid out in gx_format; copied by the service */
|
||||
size_t size;
|
||||
uint32_t width;
|
||||
uint32_t height;
|
||||
uint32_t mip_count;
|
||||
uint32_t gx_format; /* any GX texture format supported by Aurora's converter */
|
||||
} TextureData;
|
||||
|
||||
#define TEXTURE_DATA_INIT {sizeof(TextureData), NULL, 0u, 0u, 0u, 1u, 0u}
|
||||
|
||||
/*
|
||||
* Runtime texture replacements.
|
||||
*
|
||||
* Registrations are owned by the calling mod and removed automatically when it is disabled,
|
||||
* reloaded, or fails. When multiple sources replace the same texture, the highest priority wins:
|
||||
* later-loaded mods beat earlier ones, and any mod beats the user's texture_replacements config
|
||||
* directory. Files shipped in a mod's textures/ directory register automatically with the same
|
||||
* ownership and priority; this service is for replacements decided at runtime.
|
||||
*/
|
||||
typedef struct TextureService {
|
||||
ServiceHeader header;
|
||||
|
||||
/* Register a replacement from raw texel data. The data is copied; the caller may free it as
|
||||
* soon as this returns. */
|
||||
ModResult (*register_data)(ModContext* ctx, const TextureKey* key, const TextureData* data,
|
||||
TextureReplacementHandle* out_handle);
|
||||
|
||||
/*
|
||||
* Register a replacement from an encoded .dds/.png inside the calling mod's bundle. The
|
||||
* filename encodes the key (same convention as the texture_replacements directory, e.g.
|
||||
* "tex1_{w}x{h}_{hash}_{fmt}.dds"); "_mipN" sidecars next to it are picked up automatically.
|
||||
* The file is decoded lazily on first use by the renderer.
|
||||
*/
|
||||
ModResult (*register_file)(ModContext* ctx, const char* bundle_path,
|
||||
TextureReplacementHandle* out_handle);
|
||||
|
||||
/* Remove a replacement previously registered by the calling mod. */
|
||||
ModResult (*unregister)(ModContext* ctx, TextureReplacementHandle handle);
|
||||
} TextureService;
|
||||
|
||||
#ifdef __cplusplus
|
||||
#include "mods/service.hpp"
|
||||
|
||||
template <>
|
||||
struct dusk::mods::ServiceTraits<TextureService> {
|
||||
static constexpr const char* id = TEXTURE_SERVICE_ID;
|
||||
static constexpr uint16_t major_version = TEXTURE_SERVICE_MAJOR;
|
||||
};
|
||||
#endif
|
||||
@@ -0,0 +1,284 @@
|
||||
#pragma once
|
||||
|
||||
#include "mods/api.h"
|
||||
#include "mods/svc/config.h"
|
||||
|
||||
#define UI_SERVICE_ID "dev.twilitrealm.dusklight.ui"
|
||||
#define UI_SERVICE_MAJOR 1u
|
||||
#define UI_SERVICE_MINOR 0u
|
||||
|
||||
/*
|
||||
* UI primitives: a panel inside the host Mods window, mod-owned windows, dialogs, scoped
|
||||
* RCSS stylesheets and menu bar tabs.
|
||||
*
|
||||
* All calls must be made on the game thread from mod callbacks (initialize, update, hooks, or UI
|
||||
* callbacks). Handles are opaque, generation-checked ids; a stale or unknown handle fails with
|
||||
* MOD_INVALID_ARGUMENT. Element handles die with the content that owns them: a panel or tab rebuild
|
||||
* destroys the previous build's elements, so re-acquire handles inside the build callback rather
|
||||
* than caching them. Strings are UTF-8 and, in both directions, only valid for the duration of the
|
||||
* call.
|
||||
*/
|
||||
|
||||
/* 0 is never a valid handle. */
|
||||
typedef uint64_t UiWindowHandle;
|
||||
typedef uint64_t UiDialogHandle;
|
||||
typedef uint64_t UiElementHandle;
|
||||
typedef uint64_t UiStyleHandle;
|
||||
typedef uint64_t UiMenuTabHandle;
|
||||
|
||||
typedef enum UiStyleScope {
|
||||
UI_SCOPE_PRELAUNCH = 0, /* the pre-launch menu */
|
||||
UI_SCOPE_WINDOW = 1, /* every tabbed/small window, host and mod alike */
|
||||
UI_SCOPE_MENU_BAR = 2, /* the in-game menu bar */
|
||||
UI_SCOPE_OVERLAY = 3, /* the passive overlay (toasts, FPS counter, timers) */
|
||||
UI_SCOPE_TOUCH_CONTROLS = 4, /* touch controls and their editor */
|
||||
UI_SCOPE_GRAPHICS_TUNER = 5, /* the graphics tuner overlay window */
|
||||
} UiStyleScope;
|
||||
|
||||
typedef enum UiDialogVariant {
|
||||
UI_DIALOG_NORMAL = 0,
|
||||
UI_DIALOG_WARNING = 1, /* warning icon by default */
|
||||
UI_DIALOG_DANGER = 2, /* red styling, error icon by default */
|
||||
} UiDialogVariant;
|
||||
|
||||
typedef enum UiControlKind {
|
||||
UI_CONTROL_BUTTON = 0, /* action button (on_pressed) */
|
||||
UI_CONTROL_TOGGLE = 1, /* boolean on/off */
|
||||
UI_CONTROL_NUMBER = 2, /* integer stepper with min/max/step */
|
||||
UI_CONTROL_STRING = 3, /* text input */
|
||||
UI_CONTROL_SELECT = 4, /* one of `options`; the value is the option index */
|
||||
} UiControlKind;
|
||||
|
||||
typedef enum UiControlBinding {
|
||||
/* Values flow through the `get`/`set` callbacks. Getters are polled every frame while the
|
||||
control is visible and must be cheap. */
|
||||
UI_BINDING_CALLBACKS = 0,
|
||||
/* The control reads and writes `config_var` (a ConfigService handle owned by the calling mod)
|
||||
* directly: persistence, change notifications and the modified indicator (value != default) are
|
||||
* wired automatically. The var type must match the control kind: TOGGLE = bool, NUMBER and
|
||||
* SELECT = int, STRING = string. Float vars are not bindable; use callbacks. */
|
||||
UI_BINDING_CONFIG_VAR = 1,
|
||||
} UiControlBinding;
|
||||
|
||||
/* Tagged by the control's kind: TOGGLE reads bool_value, NUMBER and SELECT read int_value, STRING
|
||||
* reads string_value. string_value passed to a setter is only valid during the call; a getter
|
||||
* should point it at storage owned by the mod (e.g. a static buffer) that stays valid until the
|
||||
* next call into the mod — the host copies it right after the getter returns. */
|
||||
typedef struct UiControlValue {
|
||||
uint32_t struct_size;
|
||||
bool bool_value;
|
||||
int64_t int_value;
|
||||
const char* string_value;
|
||||
} UiControlValue;
|
||||
|
||||
#define UI_CONTROL_VALUE_INIT {sizeof(UiControlValue), false, 0, NULL}
|
||||
|
||||
typedef void (*UiControlGetFn)(ModContext* ctx, void* user_data, UiControlValue* out_value);
|
||||
typedef void (*UiControlSetFn)(ModContext* ctx, void* user_data, const UiControlValue* value);
|
||||
/* Polled every frame while the control is visible. */
|
||||
typedef bool (*UiPredicateFn)(ModContext* ctx, void* user_data);
|
||||
typedef void (*UiPressedFn)(ModContext* ctx, void* user_data);
|
||||
|
||||
typedef struct UiControlDesc {
|
||||
uint32_t struct_size;
|
||||
UiControlKind kind;
|
||||
/* Row label (plain text). Required. */
|
||||
const char* label;
|
||||
/* Optional RML shown as contextual help when the control is focused or hovered. Only rendered
|
||||
* where a help pane exists (mod window tabs). */
|
||||
const char* help_rml;
|
||||
UiControlBinding binding; /* ignored for BUTTON */
|
||||
ConfigVarHandle config_var; /* UI_BINDING_CONFIG_VAR */
|
||||
UiControlGetFn get; /* UI_BINDING_CALLBACKS (all kinds but BUTTON) */
|
||||
UiControlSetFn set; /* UI_BINDING_CALLBACKS (all kinds but BUTTON) */
|
||||
UiPressedFn on_pressed; /* BUTTON only. Required for BUTTON. */
|
||||
UiPredicateFn is_disabled; /* optional */
|
||||
/* Optional override for the modified indicator. CONFIG_VAR controls derive it from value !=
|
||||
* default when this is NULL. */
|
||||
UiPredicateFn is_modified;
|
||||
/* Passed to every callback above. */
|
||||
void* user_data;
|
||||
/* NUMBER: inclusive clamp range and step. min == max means the defaults (0 .. INT32_MAX); step
|
||||
* < 1 means 1. */
|
||||
int64_t min;
|
||||
int64_t max;
|
||||
int64_t step;
|
||||
const char* prefix; /* NUMBER: optional text before the value */
|
||||
const char* suffix; /* NUMBER: optional text after the value */
|
||||
/* SELECT: option labels (plain text). Required for SELECT. SELECT controls
|
||||
* present their options in the help pane, so they are only available where
|
||||
* one exists (mod window tabs); MOD_UNSUPPORTED elsewhere. */
|
||||
const char* const* options;
|
||||
size_t option_count;
|
||||
int32_t max_length; /* STRING: maximum input length; < 1 means unlimited */
|
||||
} UiControlDesc;
|
||||
|
||||
#define UI_CONTROL_DESC_INIT \
|
||||
{sizeof(UiControlDesc), UI_CONTROL_BUTTON, NULL, NULL, UI_BINDING_CALLBACKS, 0u, NULL, NULL, \
|
||||
NULL, NULL, NULL, NULL, 0, 0, 1, NULL, NULL, NULL, 0u, 0}
|
||||
|
||||
/* Build the panel contents. `panel` accepts the pane_add_* functions; it and
|
||||
* every element created in it are destroyed (handles invalidated) whenever the
|
||||
* panel is rebuilt, e.g. on tab switches. A non-MOD_OK result fails the mod. */
|
||||
typedef ModResult (*UiPanelBuildFn)(
|
||||
ModContext* ctx, UiElementHandle panel, void* user_data, ModError* out_error);
|
||||
/* Called every frame while the panel is the visible tab. */
|
||||
typedef ModResult (*UiPanelUpdateFn)(ModContext* ctx, void* user_data, ModError* out_error);
|
||||
|
||||
/* A panel rendered inside the calling mod's tab of the host Mods window. */
|
||||
typedef struct UiModsPanelDesc {
|
||||
uint32_t struct_size;
|
||||
UiPanelBuildFn build; /* required */
|
||||
UiPanelUpdateFn update;
|
||||
void* user_data;
|
||||
} UiModsPanelDesc;
|
||||
|
||||
#define UI_MODS_PANEL_DESC_INIT {sizeof(UiModsPanelDesc), NULL, NULL, NULL}
|
||||
|
||||
/* Build one tab of a mod window. `left_pane` is the interactive column,
|
||||
* `right_pane` shows contextual help (controls' help_rml and SELECT options
|
||||
* render there). Rebuilt on every tab activation. */
|
||||
typedef ModResult (*UiTabBuildFn)(ModContext* ctx, UiWindowHandle window, UiElementHandle left_pane,
|
||||
UiElementHandle right_pane, void* user_data, ModError* out_error);
|
||||
|
||||
typedef struct UiTabDesc {
|
||||
uint32_t struct_size;
|
||||
const char* title; /* required */
|
||||
UiTabBuildFn build; /* required */
|
||||
UiPanelUpdateFn update;
|
||||
void* user_data;
|
||||
} UiTabDesc;
|
||||
|
||||
#define UI_TAB_DESC_INIT {sizeof(UiTabDesc), NULL, NULL, NULL, NULL}
|
||||
|
||||
typedef void (*UiWindowClosedFn)(ModContext* ctx, UiWindowHandle window, void* user_data);
|
||||
|
||||
typedef struct UiWindowDesc {
|
||||
uint32_t struct_size;
|
||||
const UiTabDesc* tabs; /* at least one */
|
||||
size_t tab_count;
|
||||
/* Optional RCSS applied to this window's document only (on top of any
|
||||
* UI_SCOPE_WINDOW sheets, which apply automatically). */
|
||||
const char* rcss;
|
||||
/* Fired when the window is destroyed by user close or window_close. Not
|
||||
* fired during owning-mod teardown/shutdown. The handle is already invalid. */
|
||||
UiWindowClosedFn on_closed;
|
||||
void* user_data;
|
||||
} UiWindowDesc;
|
||||
|
||||
#define UI_WINDOW_DESC_INIT {sizeof(UiWindowDesc), NULL, 0u, NULL, NULL, NULL}
|
||||
|
||||
typedef void (*UiDialogActionFn)(ModContext* ctx, UiDialogHandle dialog, void* user_data);
|
||||
|
||||
/* Note: array element without struct_size; a future change requires appending
|
||||
* a v2 desc struct rather than growing this one. */
|
||||
typedef struct UiDialogAction {
|
||||
const char* label; /* required */
|
||||
UiDialogActionFn on_pressed;
|
||||
void* user_data;
|
||||
bool keep_open; /* false = the dialog closes after on_pressed returns */
|
||||
} UiDialogAction;
|
||||
|
||||
typedef struct UiDialogDesc {
|
||||
uint32_t struct_size;
|
||||
const char* title; /* plain text; required */
|
||||
const char* body_rml; /* RML body; required */
|
||||
UiDialogVariant variant;
|
||||
/* Optional icon name overriding the variant default: "warning", "error",
|
||||
* "question-mark", "verifying", "celebration". */
|
||||
const char* icon;
|
||||
const UiDialogAction* actions; /* at least one */
|
||||
size_t action_count;
|
||||
/* Fired on cancel (B/Escape) before the dialog closes; the dialog always
|
||||
* closes on dismiss. */
|
||||
UiDialogActionFn on_dismiss;
|
||||
void* user_data; /* passed to on_dismiss */
|
||||
} UiDialogDesc;
|
||||
|
||||
#define UI_DIALOG_DESC_INIT \
|
||||
{sizeof(UiDialogDesc), NULL, NULL, UI_DIALOG_NORMAL, NULL, NULL, 0u, NULL, NULL}
|
||||
|
||||
/* A tab added to the in-game menu bar. */
|
||||
typedef struct UiMenuTabDesc {
|
||||
uint32_t struct_size;
|
||||
const char* label; /* plain text; required */
|
||||
UiPressedFn on_selected; /* fired when the user activates the tab; required */
|
||||
void* user_data;
|
||||
} UiMenuTabDesc;
|
||||
|
||||
#define UI_MENU_TAB_DESC_INIT {sizeof(UiMenuTabDesc), NULL, NULL, NULL}
|
||||
|
||||
typedef struct UiService {
|
||||
ServiceHeader header;
|
||||
|
||||
/* Register or replace the panel shown in the calling mod's Mods-window tab. */
|
||||
ModResult (*register_mods_panel)(ModContext* ctx, const UiModsPanelDesc* desc);
|
||||
|
||||
/* Content builders. `pane` is a panel or tab pane handle; out_elem (where
|
||||
* present, optional) receives a handle for later elem_set_* updates. */
|
||||
ModResult (*pane_add_section)(ModContext* ctx, UiElementHandle pane, const char* title);
|
||||
ModResult (*pane_add_text)(
|
||||
ModContext* ctx, UiElementHandle pane, const char* text, UiElementHandle* out_elem);
|
||||
ModResult (*pane_add_rml)(
|
||||
ModContext* ctx, UiElementHandle pane, const char* rml, UiElementHandle* out_elem);
|
||||
ModResult (*pane_add_progress)(
|
||||
ModContext* ctx, UiElementHandle pane, float value, UiElementHandle* out_elem);
|
||||
ModResult (*pane_add_control)(ModContext* ctx, UiElementHandle pane, const UiControlDesc* desc,
|
||||
UiElementHandle* out_elem);
|
||||
|
||||
/* Element updates. The handle kind must match the setter (text/rml on text
|
||||
* rows, progress on progress bars). */
|
||||
ModResult (*elem_set_text)(ModContext* ctx, UiElementHandle elem, const char* text);
|
||||
ModResult (*elem_set_rml)(ModContext* ctx, UiElementHandle elem, const char* rml);
|
||||
ModResult (*elem_set_progress)(ModContext* ctx, UiElementHandle elem, float value);
|
||||
/* Set or clear an RCSS class on any element handle (rows, progress bars,
|
||||
* controls, panes), for styling via scoped or window RCSS. */
|
||||
ModResult (*elem_set_class)(
|
||||
ModContext* ctx, UiElementHandle elem, const char* name, bool active);
|
||||
|
||||
/* Push a tabbed two-pane window onto the document stack and show it. */
|
||||
ModResult (*window_push)(ModContext* ctx, const UiWindowDesc* desc, UiWindowHandle* out_window);
|
||||
ModResult (*window_close)(ModContext* ctx, UiWindowHandle window);
|
||||
|
||||
/* Push a modal dialog onto the document stack and show it. */
|
||||
ModResult (*dialog_push)(ModContext* ctx, const UiDialogDesc* desc, UiDialogHandle* out_dialog);
|
||||
ModResult (*dialog_close)(ModContext* ctx, UiDialogHandle dialog);
|
||||
ModResult (*dialog_set_body)(ModContext* ctx, UiDialogHandle dialog, const char* body_rml);
|
||||
/* Replace the dialog icon ("" removes it; names as in UiDialogDesc.icon). */
|
||||
ModResult (*dialog_set_icon)(ModContext* ctx, UiDialogHandle dialog, const char* icon);
|
||||
/* Append one action button (same callback rules as at push). */
|
||||
ModResult (*dialog_add_action)(
|
||||
ModContext* ctx, UiDialogHandle dialog, const UiDialogAction* action);
|
||||
|
||||
/* Whether any focus-stack document is currently visible (visible documents block gamepad
|
||||
* input). */
|
||||
ModResult (*is_any_document_visible)(ModContext* ctx, bool* out_visible);
|
||||
|
||||
/* Register an RCSS sheet applied to every document of `scope`, now and in the future, until
|
||||
* unregistered or the calling mod is torn down. Sheets apply in registration order after the
|
||||
* host styles. Fails with MOD_INVALID_ARGUMENT if the RCSS does not parse. */
|
||||
ModResult (*register_styles)(
|
||||
ModContext* ctx, UiStyleScope scope, const char* rcss, UiStyleHandle* out_style);
|
||||
/* Like register_styles, but reads the RCSS from the mod bundle's res/ directory (same path
|
||||
* rules as ResourceService::load). MOD_UNAVAILABLE if the file does not exist. */
|
||||
ModResult (*register_styles_file)(
|
||||
ModContext* ctx, UiStyleScope scope, const char* path, UiStyleHandle* out_style);
|
||||
ModResult (*unregister_styles)(ModContext* ctx, UiStyleHandle style);
|
||||
|
||||
/* Add a tab to the in-game menu bar, on_selected runs with the menu open; pushing a window from
|
||||
* it stacks the window over the menu like the host tabs do. The tab is removed when
|
||||
* unregistered or the mod is torn down. */
|
||||
ModResult (*register_menu_tab)(
|
||||
ModContext* ctx, const UiMenuTabDesc* desc, UiMenuTabHandle* out_tab);
|
||||
ModResult (*unregister_menu_tab)(ModContext* ctx, UiMenuTabHandle tab);
|
||||
} UiService;
|
||||
|
||||
#ifdef __cplusplus
|
||||
#include "mods/service.hpp"
|
||||
|
||||
template <>
|
||||
struct dusk::mods::ServiceTraits<UiService> {
|
||||
static constexpr const char* id = UI_SERVICE_ID;
|
||||
static constexpr uint16_t major_version = UI_SERVICE_MAJOR;
|
||||
};
|
||||
#endif
|
||||
@@ -212,6 +212,9 @@ public:
|
||||
void setCornerColor(JUtility::TColor c0) {
|
||||
setCornerColor(c0, c0, c0, c0);
|
||||
}
|
||||
#if TARGET_PC
|
||||
JUtility::TColor corner(size_t index) const { return mCornerColor[index]; }
|
||||
#endif
|
||||
|
||||
protected:
|
||||
/* 0x100 */ JUTTexture* mTexture[2];
|
||||
|
||||
@@ -12,12 +12,23 @@ struct JORNodeEvent;
|
||||
class JORMContext;
|
||||
class JORServer;
|
||||
|
||||
// NOTE (stable game ABI): these classes stay non-polymorphic outside DEBUG
|
||||
// on purpose. Making them polymorphic under PARTIAL_DEBUG would give every one of the ~250
|
||||
// derived HIO classes a vptr and turn their plain `void genMessage(JORMContext*);`
|
||||
// declarations into implicit virtual overrides whose definitions are #if DEBUG-gated; every
|
||||
// instantiated one then fails to link (missing vtable). Closure types shared with DEBUG TUs
|
||||
// either declare their own unconditional virtuals (vptr in all TUs anyway) or add a
|
||||
// PARTIAL_DEBUG-only virtual dtor for vptr parity (see dAttParam_c).
|
||||
class JOREventListener {
|
||||
public:
|
||||
#if DEBUG
|
||||
JOREventListener() {}
|
||||
#if TARGET_PC
|
||||
virtual void listenPropertyEvent(const JORPropertyEvent*) {}
|
||||
#else
|
||||
virtual void listenPropertyEvent(const JORPropertyEvent*) = 0;
|
||||
#endif
|
||||
#endif
|
||||
};
|
||||
|
||||
class JORReflexible : public JOREventListener {
|
||||
@@ -30,7 +41,11 @@ public:
|
||||
virtual void listenPropertyEvent(const JORPropertyEvent*);
|
||||
virtual void listen(u32, const JOREvent*);
|
||||
virtual void genObjectInfo(const JORGenEvent*);
|
||||
#if TARGET_PC
|
||||
virtual void genMessage(JORMContext*) {}
|
||||
#else
|
||||
virtual void genMessage(JORMContext*) = 0;
|
||||
#endif
|
||||
virtual void listenNodeEvent(const JORNodeEvent*);
|
||||
#endif
|
||||
};
|
||||
|
||||
@@ -3,6 +3,20 @@
|
||||
|
||||
#include <gx.h>
|
||||
|
||||
#if TARGET_PC
|
||||
#include <mtx.h>
|
||||
|
||||
struct ParticleDrawCtx {
|
||||
bool batch; // off = immediate mode
|
||||
bool useTexMtx; // UVs transformed by texMtx
|
||||
bool useClr0; // prm color in GX_VA_CLR0
|
||||
bool useClr1; // env color in GX_VA_CLR1
|
||||
Mtx texMtx;
|
||||
GXColor clr0;
|
||||
GXColor clr1;
|
||||
};
|
||||
#endif
|
||||
|
||||
struct JPAEmitterWorkData;
|
||||
class JPABaseParticle;
|
||||
class JKRHeap;
|
||||
@@ -75,6 +89,9 @@ public:
|
||||
|
||||
const GXTevColorArg* getTevColorArg() const { return st_ca[(pBsd->mFlags >> 0x0F) & 0x07]; }
|
||||
const GXTevAlphaArg* getTevAlphaArg() const { return st_aa[(pBsd->mFlags >> 0x12) & 0x01]; }
|
||||
#if TARGET_PC
|
||||
u32 getTevColorArgSel() const { return (pBsd->mFlags >> 0x0F) & 0x07; }
|
||||
#endif
|
||||
|
||||
u32 getType() const { return (pBsd->mFlags >> 0) & 0x0F; }
|
||||
u32 getDirType() const { return (pBsd->mFlags >> 4) & 0x07; }
|
||||
@@ -186,26 +203,34 @@ void JPARegistPrm(JPAEmitterWorkData*);
|
||||
void JPARegistEnv(JPAEmitterWorkData*);
|
||||
void JPARegistPrmEnv(JPAEmitterWorkData*);
|
||||
|
||||
void JPADrawPoint(JPAEmitterWorkData*, JPABaseParticle*);
|
||||
void JPADrawLine(JPAEmitterWorkData*, JPABaseParticle*);
|
||||
void JPADrawRotBillboard(JPAEmitterWorkData*, JPABaseParticle*);
|
||||
void JPADrawBillboard(JPAEmitterWorkData*, JPABaseParticle*);
|
||||
void JPADrawRotDirection(JPAEmitterWorkData*, JPABaseParticle*);
|
||||
void JPADrawDirection(JPAEmitterWorkData*, JPABaseParticle*);
|
||||
void JPADrawRotation(JPAEmitterWorkData*, JPABaseParticle*);
|
||||
void JPADrawDBillboard(JPAEmitterWorkData*, JPABaseParticle*);
|
||||
void JPADrawRotYBillboard(JPAEmitterWorkData*, JPABaseParticle*);
|
||||
void JPADrawYBillboard(JPAEmitterWorkData*, JPABaseParticle*);
|
||||
void JPADrawParticleCallBack(JPAEmitterWorkData*, JPABaseParticle*);
|
||||
void JPALoadTexAnm(JPAEmitterWorkData*, JPABaseParticle*);
|
||||
void JPASetPointSize(JPAEmitterWorkData*, JPABaseParticle*);
|
||||
void JPASetLineWidth(JPAEmitterWorkData*, JPABaseParticle*);
|
||||
void JPALoadCalcTexCrdMtxAnm(JPAEmitterWorkData*, JPABaseParticle*);
|
||||
void JPARegistAlpha(JPAEmitterWorkData*, JPABaseParticle*);
|
||||
void JPARegistEnv(JPAEmitterWorkData*, JPABaseParticle*);
|
||||
void JPARegistAlphaEnv(JPAEmitterWorkData*, JPABaseParticle*);
|
||||
void JPARegistPrmAlpha(JPAEmitterWorkData*, JPABaseParticle*);
|
||||
void JPARegistPrmAlphaEnv(JPAEmitterWorkData*, JPABaseParticle*);
|
||||
#if TARGET_PC
|
||||
#define JPA_DRAW_PARTICLE_ARGS JPAEmitterWorkData*, JPABaseParticle*, ParticleDrawCtx*
|
||||
#else
|
||||
#define JPA_DRAW_PARTICLE_ARGS JPAEmitterWorkData*, JPABaseParticle*
|
||||
#endif
|
||||
|
||||
void JPADrawPoint(JPA_DRAW_PARTICLE_ARGS);
|
||||
void JPADrawLine(JPA_DRAW_PARTICLE_ARGS);
|
||||
void JPADrawRotBillboard(JPA_DRAW_PARTICLE_ARGS);
|
||||
void JPADrawBillboard(JPA_DRAW_PARTICLE_ARGS);
|
||||
void JPADrawRotDirection(JPA_DRAW_PARTICLE_ARGS);
|
||||
void JPADrawDirection(JPA_DRAW_PARTICLE_ARGS);
|
||||
void JPADrawRotation(JPA_DRAW_PARTICLE_ARGS);
|
||||
void JPADrawDBillboard(JPA_DRAW_PARTICLE_ARGS);
|
||||
void JPADrawRotYBillboard(JPA_DRAW_PARTICLE_ARGS);
|
||||
void JPADrawYBillboard(JPA_DRAW_PARTICLE_ARGS);
|
||||
void JPADrawParticleCallBack(JPA_DRAW_PARTICLE_ARGS);
|
||||
void JPALoadTexAnm(JPA_DRAW_PARTICLE_ARGS);
|
||||
void JPASetPointSize(JPA_DRAW_PARTICLE_ARGS);
|
||||
void JPASetLineWidth(JPA_DRAW_PARTICLE_ARGS);
|
||||
void JPALoadCalcTexCrdMtxAnm(JPA_DRAW_PARTICLE_ARGS);
|
||||
void JPARegistAlpha(JPA_DRAW_PARTICLE_ARGS);
|
||||
void JPARegistEnv(JPA_DRAW_PARTICLE_ARGS);
|
||||
void JPARegistAlphaEnv(JPA_DRAW_PARTICLE_ARGS);
|
||||
void JPARegistPrmAlpha(JPA_DRAW_PARTICLE_ARGS);
|
||||
void JPARegistPrmAlphaEnv(JPA_DRAW_PARTICLE_ARGS);
|
||||
|
||||
#undef JPA_DRAW_PARTICLE_ARGS
|
||||
|
||||
#if TARGET_PC
|
||||
void JPAInterpBillboard(JPAEmitterWorkData*, JPABaseParticle*);
|
||||
|
||||
@@ -17,6 +17,10 @@ class JPADynamicsBlock;
|
||||
class JPAFieldBlock;
|
||||
class JPAKeyBlock;
|
||||
|
||||
#if TARGET_PC
|
||||
struct ParticleDrawCtx;
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @ingroup jsystem-jparticle
|
||||
*
|
||||
@@ -50,13 +54,19 @@ public:
|
||||
public:
|
||||
typedef void (*EmitterFunc)(JPAEmitterWorkData*);
|
||||
typedef void (*ParticleFunc)(JPAEmitterWorkData*, JPABaseParticle*);
|
||||
#if TARGET_PC
|
||||
typedef void (*DrawParticleFunc)(JPAEmitterWorkData*, JPABaseParticle*,
|
||||
ParticleDrawCtx*);
|
||||
#else
|
||||
typedef ParticleFunc DrawParticleFunc;
|
||||
#endif
|
||||
/* 0x00 */ EmitterFunc* mpCalcEmitterFuncList;
|
||||
/* 0x04 */ EmitterFunc* mpDrawEmitterFuncList;
|
||||
/* 0x08 */ EmitterFunc* mpDrawEmitterChildFuncList;
|
||||
/* 0x0C */ ParticleFunc* mpCalcParticleFuncList;
|
||||
/* 0x10 */ ParticleFunc* mpDrawParticleFuncList;
|
||||
/* 0x10 */ DrawParticleFunc* mpDrawParticleFuncList;
|
||||
/* 0x14 */ ParticleFunc* mpCalcParticleChildFuncList;
|
||||
/* 0x18 */ ParticleFunc* mpDrawParticleChildFuncList;
|
||||
/* 0x18 */ DrawParticleFunc* mpDrawParticleChildFuncList;
|
||||
|
||||
/* 0x1C */ JPABaseShape* pBsp;
|
||||
/* 0x20 */ JPAExtraShape* pEsp;
|
||||
@@ -77,6 +87,20 @@ public:
|
||||
/* 0x45 */ u8 mpDrawParticleFuncListNum;
|
||||
/* 0x46 */ u8 mpCalcParticleChildFuncListNum;
|
||||
/* 0x47 */ u8 mpDrawParticleChildFuncListNum;
|
||||
|
||||
#if TARGET_PC
|
||||
struct BatchInfo {
|
||||
f32 vtxPos[8][3];
|
||||
f32 vtxUv[8][2];
|
||||
u8 vtxCount; // 4 (quad) or 8 (cross)
|
||||
bool supported; // draw func list contains only batchable funcs
|
||||
bool hasPtclColor; // per-particle JPARegist* func is present
|
||||
bool hasPtclTexMtx; // JPALoadCalcTexCrdMtxAnm is present
|
||||
};
|
||||
BatchInfo mBatchInfo;
|
||||
|
||||
void initBatchInfo();
|
||||
#endif
|
||||
};
|
||||
|
||||
#endif /* JPARESOURCE_H */
|
||||
|
||||
@@ -314,7 +314,7 @@ public:
|
||||
>
|
||||
{
|
||||
TIterator_data_(const TFunctionValue_list_parameter& rParent, const f32* value) {
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
pOwn_ = &rParent;
|
||||
#endif
|
||||
pf_ = value;
|
||||
@@ -372,7 +372,7 @@ public:
|
||||
return (r1.pf_ - r2.pf_) / suData_size;
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
/* 0x00 */ const TFunctionValue_list_parameter* pOwn_;
|
||||
#endif
|
||||
/* 0x00 */ const f32* pf_;
|
||||
@@ -425,7 +425,7 @@ public:
|
||||
>
|
||||
{
|
||||
TIterator_data_(const TFunctionValue_hermite& rParent, const f32* value) {
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
pOwn_ = &rParent;
|
||||
#endif
|
||||
pf_ = value;
|
||||
@@ -491,7 +491,7 @@ public:
|
||||
return (r1.pf_ - r2.pf_) / r1.uSize_;
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
#if PARTIAL_DEBUG || DEBUG
|
||||
/* 0x00 */ const TFunctionValue_hermite* pOwn_;
|
||||
/* 0x04 */ const f32* pf_;
|
||||
/* 0x08 */ u32 uSize_;
|
||||
|
||||
@@ -542,8 +542,11 @@ void J3DModel::viewCalc() {
|
||||
}
|
||||
|
||||
#ifdef TARGET_PC
|
||||
for (u16 i = 0; i < mModelData->getDrawMtxNum(); ++i) {
|
||||
dusk::frame_interp::record_final_mtx(getDrawMtxPtr()[i]);
|
||||
Mtx* drawMtx = getDrawMtxPtr();
|
||||
if (drawMtx != J3DMtxBuffer::sNoUseDrawMtxPtr) {
|
||||
for (u16 i = 0; i < mModelData->getDrawMtxNum(); ++i) {
|
||||
dusk::frame_interp::record_final_mtx(drawMtx[i]);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
@@ -136,8 +136,8 @@ void J3DLoadCPCmd(u8 addr, u32 val) {
|
||||
#if TARGET_PC
|
||||
static void J3DLoadArrayBasePtr(GXAttr attr, void* data, u32 size, bool le) {
|
||||
u32 idx = (attr == GX_VA_NBT) ? 1 : (attr - GX_VA_POS);
|
||||
GXCmd1u8(GX_LOAD_AURORA);
|
||||
GXCmd1u16(GX_LOAD_AURORA_ARRAYBASE | idx);
|
||||
GXCmd1u8(GX_AURORA);
|
||||
GXCmd1u16(GX_AURORA_LOAD_ARRAYBASE | idx);
|
||||
GXCmd1u64((u64)data);
|
||||
GXCmd1u32(size);
|
||||
GXCmd1u8(le ? 1 : 0);
|
||||
|
||||
@@ -7,265 +7,11 @@
|
||||
#include "JSystem/JKernel/JKRHeap.h"
|
||||
|
||||
#if TARGET_PC
|
||||
#include <algorithm>
|
||||
#include <aurora/dl.hpp>
|
||||
#include <tracy/Tracy.hpp>
|
||||
#include <vector>
|
||||
#include "dusk/logging.h"
|
||||
|
||||
namespace {
|
||||
|
||||
u16 read_be16(const u8* data) {
|
||||
return (u16(data[0]) << 8) | data[1];
|
||||
}
|
||||
|
||||
void append_be16(std::vector<u8>& out, u16 value) {
|
||||
out.push_back(value >> 8);
|
||||
out.push_back(value & 0xFF);
|
||||
}
|
||||
|
||||
void append_bytes(std::vector<u8>& out, const u8* data, u32 size) {
|
||||
out.insert(out.end(), data, data + size);
|
||||
}
|
||||
|
||||
bool is_matrix_idx_attr(GXAttr attr) {
|
||||
return attr >= GX_VA_PNMTXIDX && attr <= GX_VA_TEX7MTXIDX;
|
||||
}
|
||||
|
||||
bool is_draw_opcode(u8 opcode) {
|
||||
return opcode == GX_QUADS || opcode == GX_TRIANGLES || opcode == GX_TRIANGLESTRIP ||
|
||||
opcode == GX_TRIANGLEFAN || opcode == GX_LINES || opcode == GX_LINESTRIP ||
|
||||
opcode == GX_POINTS;
|
||||
}
|
||||
|
||||
bool is_mergeable_draw_opcode(u8 opcode) {
|
||||
return opcode == GX_QUADS || opcode == GX_TRIANGLES || opcode == GX_TRIANGLESTRIP ||
|
||||
opcode == GX_TRIANGLEFAN;
|
||||
}
|
||||
|
||||
bool calc_vtx_stride(const GXVtxDescList* vtxDesc, u32& stride) {
|
||||
stride = 0;
|
||||
for (; vtxDesc->attr != GX_VA_NULL; vtxDesc++) {
|
||||
switch (vtxDesc->type) {
|
||||
case GX_NONE:
|
||||
break;
|
||||
case GX_DIRECT:
|
||||
if (!is_matrix_idx_attr(vtxDesc->attr)) {
|
||||
return false;
|
||||
}
|
||||
stride += 1;
|
||||
break;
|
||||
case GX_INDEX8:
|
||||
stride += 1;
|
||||
break;
|
||||
case GX_INDEX16:
|
||||
stride += 2;
|
||||
break;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return stride != 0;
|
||||
}
|
||||
|
||||
bool get_command_size(const u8* dlStart, u32 dlSize, u32 offset, u32 stride, u32& cmdSize) {
|
||||
if (offset >= dlSize) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const u8 cmd = dlStart[offset];
|
||||
const u8 opcode = cmd & GX_OPCODE_MASK;
|
||||
switch (opcode) {
|
||||
case GX_NOP:
|
||||
case GX_CMD_INVL_VC:
|
||||
cmdSize = 1;
|
||||
return true;
|
||||
case (GX_LOAD_BP_REG & GX_OPCODE_MASK):
|
||||
cmdSize = 5;
|
||||
return offset + cmdSize <= dlSize;
|
||||
case GX_LOAD_CP_REG:
|
||||
cmdSize = 6;
|
||||
return offset + cmdSize <= dlSize;
|
||||
case GX_LOAD_XF_REG: {
|
||||
if (offset + 5 > dlSize) {
|
||||
return false;
|
||||
}
|
||||
const u16 count = read_be16(dlStart + offset + 1) + 1;
|
||||
cmdSize = 5 + count * 4;
|
||||
return offset + cmdSize <= dlSize;
|
||||
}
|
||||
case GX_LOAD_INDX_A:
|
||||
case GX_LOAD_INDX_B:
|
||||
case GX_LOAD_INDX_C:
|
||||
case GX_LOAD_INDX_D:
|
||||
cmdSize = 5;
|
||||
return offset + cmdSize <= dlSize;
|
||||
case GX_CMD_CALL_DL:
|
||||
cmdSize = 9;
|
||||
return offset + cmdSize <= dlSize;
|
||||
default:
|
||||
if (is_draw_opcode(opcode)) {
|
||||
if (offset + 3 > dlSize) {
|
||||
return false;
|
||||
}
|
||||
const u16 vtxCount = read_be16(dlStart + offset + 1);
|
||||
cmdSize = 3 + vtxCount * stride;
|
||||
return offset + cmdSize <= dlSize;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
struct MergeRun {
|
||||
u8 cmd = 0;
|
||||
u16 vtxCount = 0;
|
||||
std::vector<u8> vertices;
|
||||
};
|
||||
|
||||
void flush_merge_run(std::vector<u8>& out, MergeRun& run) {
|
||||
if (run.vtxCount == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
out.push_back(run.cmd);
|
||||
append_be16(out, run.vtxCount);
|
||||
append_bytes(out, run.vertices.data(), run.vertices.size());
|
||||
run.vertices.clear();
|
||||
run.vtxCount = 0;
|
||||
}
|
||||
|
||||
void append_vertex(std::vector<u8>& out, const u8* vertices, u32 stride, u16 idx) {
|
||||
append_bytes(out, vertices + idx * stride, stride);
|
||||
}
|
||||
|
||||
bool triangulate_draw(
|
||||
std::vector<u8>& out, u8 opcode, const u8* vertices, u32 stride, u16 vtxCount) {
|
||||
switch (opcode) {
|
||||
case GX_TRIANGLES:
|
||||
append_bytes(out, vertices, vtxCount * stride);
|
||||
return true;
|
||||
case GX_TRIANGLEFAN:
|
||||
if (vtxCount < 3) {
|
||||
return false;
|
||||
}
|
||||
for (u16 v = 2; v < vtxCount; v++) {
|
||||
append_vertex(out, vertices, stride, 0);
|
||||
append_vertex(out, vertices, stride, v - 1);
|
||||
append_vertex(out, vertices, stride, v);
|
||||
}
|
||||
return true;
|
||||
case GX_TRIANGLESTRIP:
|
||||
if (vtxCount < 3) {
|
||||
return false;
|
||||
}
|
||||
for (u16 v = 2; v < vtxCount; v++) {
|
||||
if ((v & 1) == 0) {
|
||||
append_vertex(out, vertices, stride, v - 2);
|
||||
append_vertex(out, vertices, stride, v - 1);
|
||||
} else {
|
||||
append_vertex(out, vertices, stride, v - 1);
|
||||
append_vertex(out, vertices, stride, v - 2);
|
||||
}
|
||||
append_vertex(out, vertices, stride, v);
|
||||
}
|
||||
return true;
|
||||
case GX_QUADS:
|
||||
if ((vtxCount & 3) != 0) {
|
||||
return false;
|
||||
}
|
||||
for (u16 v = 0; v < vtxCount; v += 4) {
|
||||
append_vertex(out, vertices, stride, v);
|
||||
append_vertex(out, vertices, stride, v + 1);
|
||||
append_vertex(out, vertices, stride, v + 2);
|
||||
append_vertex(out, vertices, stride, v + 2);
|
||||
append_vertex(out, vertices, stride, v + 3);
|
||||
append_vertex(out, vertices, stride, v);
|
||||
}
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void append_triangles_to_run(
|
||||
std::vector<u8>& out, MergeRun& run, u8 cmd, const std::vector<u8>& vertices, u32 stride) {
|
||||
u32 offset = 0;
|
||||
u32 remaining = vertices.size() / stride;
|
||||
while (remaining != 0) {
|
||||
if (run.vtxCount != 0 && run.cmd != cmd) {
|
||||
flush_merge_run(out, run);
|
||||
}
|
||||
|
||||
if (run.vtxCount == 0) {
|
||||
run.cmd = cmd;
|
||||
}
|
||||
|
||||
u32 available = 0xFFFF - run.vtxCount;
|
||||
if (available == 0) {
|
||||
flush_merge_run(out, run);
|
||||
continue;
|
||||
}
|
||||
|
||||
u32 toCopy = std::min(remaining, available);
|
||||
append_bytes(run.vertices, vertices.data() + offset * stride, toCopy * stride);
|
||||
run.vtxCount += toCopy;
|
||||
offset += toCopy;
|
||||
remaining -= toCopy;
|
||||
|
||||
if (run.vtxCount == 0xFFFF) {
|
||||
flush_merge_run(out, run);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool optimize_display_list(const u8* dlStart, u32 dlSize, u32 stride, std::vector<u8>& out) {
|
||||
MergeRun run;
|
||||
out.reserve(dlSize);
|
||||
|
||||
for (u32 offset = 0; offset < dlSize;) {
|
||||
u32 cmdSize = 0;
|
||||
if (!get_command_size(dlStart, dlSize, offset, stride, cmdSize)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const u8 cmd = dlStart[offset];
|
||||
const u8 opcode = cmd & GX_OPCODE_MASK;
|
||||
if (opcode == GX_NOP) {
|
||||
offset += cmdSize;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!is_draw_opcode(opcode)) {
|
||||
flush_merge_run(out, run);
|
||||
append_bytes(out, dlStart + offset, cmdSize);
|
||||
offset += cmdSize;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!is_mergeable_draw_opcode(opcode)) {
|
||||
flush_merge_run(out, run);
|
||||
append_bytes(out, dlStart + offset, cmdSize);
|
||||
offset += cmdSize;
|
||||
continue;
|
||||
}
|
||||
|
||||
const u16 vtxCount = read_be16(dlStart + offset + 1);
|
||||
const u8* vertices = dlStart + offset + 3;
|
||||
std::vector<u8> triangles;
|
||||
if (!triangulate_draw(triangles, opcode, vertices, stride, vtxCount)) {
|
||||
flush_merge_run(out, run);
|
||||
append_bytes(out, dlStart + offset, cmdSize);
|
||||
offset += cmdSize;
|
||||
continue;
|
||||
}
|
||||
|
||||
append_triangles_to_run(out, run, (GX_TRIANGLES | (cmd & GX_VAT_MASK)), triangles, stride);
|
||||
offset += cmdSize;
|
||||
}
|
||||
|
||||
flush_merge_run(out, run);
|
||||
return true;
|
||||
}
|
||||
|
||||
void set_display_list_copy(void*& displayList, u32& displayListSize, const u8* data, u32 size) {
|
||||
const u32 alignedSize = ALIGN_NEXT(size, 0x20);
|
||||
u8* newDL = JKR_NEW_ARRAY_ARGS(u8, alignedSize, 0x20);
|
||||
@@ -289,20 +35,11 @@ u32 J3DShapeDraw::countVertex(u32 stride) {
|
||||
u8* dlStart = (u8*)getDisplayList();
|
||||
|
||||
#if TARGET_PC
|
||||
for (u32 offset = 0; offset < getDisplayListSize();) {
|
||||
u8 cmd = dlStart[offset];
|
||||
u8 opcode = cmd & GX_OPCODE_MASK;
|
||||
u32 cmdSize = 0;
|
||||
if (!get_command_size(dlStart, getDisplayListSize(), offset, stride, cmdSize)) {
|
||||
break;
|
||||
aurora::gx::dl::Reader reader{dlStart, getDisplayListSize(), static_cast<u8>(stride)};
|
||||
while (const auto cmd = reader.next()) {
|
||||
if (cmd->kind != aurora::gx::dl::Command::Kind::Passthrough) {
|
||||
count += cmd->draw.vtxCount;
|
||||
}
|
||||
if (!is_draw_opcode(opcode)) {
|
||||
offset += cmdSize;
|
||||
continue;
|
||||
}
|
||||
int vtxNum = be16(*reinterpret_cast<u16*>(dlStart + offset + 1));
|
||||
count += vtxNum;
|
||||
offset += 3 + stride * vtxNum;
|
||||
}
|
||||
#else
|
||||
for (u8* dl = dlStart; (dl - dlStart) < getDisplayListSize();) {
|
||||
@@ -320,6 +57,53 @@ u32 J3DShapeDraw::countVertex(u32 stride) {
|
||||
return count;
|
||||
}
|
||||
|
||||
#if TARGET_PC
|
||||
void J3DShapeDraw::addTexMtxIndexInDL(u32 stride, u32 attrOffs, u32 valueBase) {
|
||||
u32 byteNum = countVertex(stride);
|
||||
u32 oldSize = mDisplayListSize;
|
||||
u32 newSize = ALIGN_NEXT(oldSize + byteNum, 0x20);
|
||||
u8* newDLStart = JKR_NEW_ARRAY_ARGS(u8, newSize, 0x20);
|
||||
u8* oldDLStart = (u8*)mDisplayList;
|
||||
u8* newDL = newDLStart;
|
||||
|
||||
aurora::gx::dl::Reader reader{oldDLStart, mDisplayListSize, static_cast<u8>(stride)};
|
||||
while (const auto cmd = reader.next()) {
|
||||
if (cmd->kind == aurora::gx::dl::Command::Kind::Passthrough) {
|
||||
std::memcpy(newDL, cmd->data, cmd->size);
|
||||
newDL += cmd->size;
|
||||
continue;
|
||||
}
|
||||
|
||||
const auto& draw = cmd->draw;
|
||||
const u32 headerSize = draw.vertices - cmd->data;
|
||||
std::memcpy(newDL, cmd->data, headerSize);
|
||||
newDL += headerSize;
|
||||
|
||||
for (u32 i = 0; i < draw.vtxCount; i++) {
|
||||
const u8* oldVtx = draw.vertices + stride * i;
|
||||
u8 pnmtxidx = oldVtx[0];
|
||||
std::memcpy(newDL, oldVtx, attrOffs);
|
||||
newDL += attrOffs;
|
||||
*newDL++ = valueBase + pnmtxidx;
|
||||
std::memcpy(newDL, oldVtx + attrOffs, stride - attrOffs);
|
||||
newDL += stride - attrOffs;
|
||||
}
|
||||
}
|
||||
if (reader.failed()) {
|
||||
// preserve the remainder untouched
|
||||
std::memcpy(newDL, oldDLStart + reader.pos(), mDisplayListSize - reader.pos());
|
||||
newDL += mDisplayListSize - reader.pos();
|
||||
}
|
||||
|
||||
u32 realSize = ALIGN_NEXT((uintptr_t)newDL - (uintptr_t)newDLStart, 0x20);
|
||||
for (; (newDL - newDLStart) < newSize; newDL++)
|
||||
*newDL = 0;
|
||||
|
||||
mDisplayListSize = realSize;
|
||||
mDisplayList = newDLStart;
|
||||
DCStoreRange(newDLStart, mDisplayListSize);
|
||||
}
|
||||
#else
|
||||
void J3DShapeDraw::addTexMtxIndexInDL(u32 stride, u32 attrOffs, u32 valueBase) {
|
||||
u32 byteNum = countVertex(stride);
|
||||
u32 oldSize = mDisplayListSize;
|
||||
@@ -330,32 +114,13 @@ void J3DShapeDraw::addTexMtxIndexInDL(u32 stride, u32 attrOffs, u32 valueBase) {
|
||||
u8* newDL = newDLStart;
|
||||
|
||||
for (; (oldDL - oldDLStart) < mDisplayListSize;) {
|
||||
#if TARGET_PC
|
||||
u32 oldOffset = oldDL - oldDLStart;
|
||||
u32 cmdSize = 0;
|
||||
if (!get_command_size(oldDLStart, mDisplayListSize, oldOffset, stride, cmdSize)) {
|
||||
memcpy(newDL, oldDL, mDisplayListSize - oldOffset);
|
||||
newDL += mDisplayListSize - oldOffset;
|
||||
break;
|
||||
}
|
||||
#endif
|
||||
// Copy command
|
||||
u8 cmd = *(u8*)oldDL;
|
||||
oldDL++;
|
||||
*newDL++ = cmd;
|
||||
|
||||
#if TARGET_PC
|
||||
u8 opcode = cmd & GX_OPCODE_MASK;
|
||||
if (!is_draw_opcode(opcode)) {
|
||||
memcpy(newDL, oldDL, cmdSize - 1);
|
||||
oldDL += cmdSize - 1;
|
||||
newDL += cmdSize - 1;
|
||||
continue;
|
||||
}
|
||||
#else
|
||||
if (cmd != GX_TRIANGLEFAN && cmd != GX_TRIANGLESTRIP)
|
||||
break;
|
||||
#endif
|
||||
|
||||
// Copy count
|
||||
int vtxNum = *(u16*)oldDL;
|
||||
@@ -384,6 +149,7 @@ void J3DShapeDraw::addTexMtxIndexInDL(u32 stride, u32 attrOffs, u32 valueBase) {
|
||||
mDisplayList = newDLStart;
|
||||
DCStoreRange(newDLStart, mDisplayListSize);
|
||||
}
|
||||
#endif
|
||||
|
||||
J3DShapeDraw::J3DShapeDraw(const u8* displayList, u32 displayListSize) {
|
||||
#if TARGET_PC
|
||||
@@ -397,12 +163,8 @@ J3DShapeDraw::J3DShapeDraw(const u8* displayList, u32 displayListSize) {
|
||||
#if TARGET_PC
|
||||
J3DShapeDraw::J3DShapeDraw(
|
||||
const u8* displayList, u32 displayListSize, const GXVtxDescList* vtxDesc) {
|
||||
u32 stride = 0;
|
||||
std::vector<u8> optimized;
|
||||
if (calc_vtx_stride(vtxDesc, stride) &&
|
||||
optimize_display_list(displayList, displayListSize, stride, optimized))
|
||||
{
|
||||
set_display_list_copy(mDisplayList, mDisplayListSize, optimized.data(), optimized.size());
|
||||
if (const auto optimized = aurora::gx::dl::optimize(displayList, displayListSize, vtxDesc)) {
|
||||
set_display_list_copy(mDisplayList, mDisplayListSize, optimized->data(), optimized->size());
|
||||
} else {
|
||||
set_display_list_copy(mDisplayList, mDisplayListSize, displayList, displayListSize);
|
||||
}
|
||||
|
||||
@@ -14,6 +14,33 @@
|
||||
#endif
|
||||
#include "tracy/Tracy.hpp"
|
||||
|
||||
#if TARGET_PC
|
||||
#define JPA_DRAW_CTX_PARAM , ParticleDrawCtx* ctx
|
||||
|
||||
namespace {
|
||||
GXColor emitter_prm_color(JPAEmitterWorkData* work) {
|
||||
JPABaseEmitter* emtr = work->mpEmtr;
|
||||
GXColor prm = emtr->mPrmClr;
|
||||
prm.r = COLOR_MULTI(prm.r, emtr->mGlobalPrmClr.r);
|
||||
prm.g = COLOR_MULTI(prm.g, emtr->mGlobalPrmClr.g);
|
||||
prm.b = COLOR_MULTI(prm.b, emtr->mGlobalPrmClr.b);
|
||||
prm.a = COLOR_MULTI(prm.a, emtr->mGlobalPrmClr.a);
|
||||
return prm;
|
||||
}
|
||||
|
||||
GXColor emitter_env_color(JPAEmitterWorkData* work) {
|
||||
JPABaseEmitter* emtr = work->mpEmtr;
|
||||
GXColor env = emtr->mEnvClr;
|
||||
env.r = COLOR_MULTI(env.r, emtr->mGlobalEnvClr.r);
|
||||
env.g = COLOR_MULTI(env.g, emtr->mGlobalEnvClr.g);
|
||||
env.b = COLOR_MULTI(env.b, emtr->mGlobalEnvClr.b);
|
||||
return env;
|
||||
}
|
||||
} // namespace
|
||||
#else
|
||||
#define JPA_DRAW_CTX_PARAM
|
||||
#endif
|
||||
|
||||
void JPASetPointSize(JPAEmitterWorkData* work) {
|
||||
GXSetPointSize((u8)(25.0f * work->mGlobalPtclScl.x), GX_TO_ONE);
|
||||
}
|
||||
@@ -22,15 +49,16 @@ void JPASetLineWidth(JPAEmitterWorkData* work) {
|
||||
GXSetLineWidth((u8)(25.0f * work->mGlobalPtclScl.x), GX_TO_ONE);
|
||||
}
|
||||
|
||||
void JPASetPointSize(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
void JPASetPointSize(JPAEmitterWorkData* work, JPABaseParticle* ptcl JPA_DRAW_CTX_PARAM) {
|
||||
GXSetPointSize((u8)(ptcl->mParticleScaleX * (25.0f * work->mGlobalPtclScl.x)), GX_TO_ONE);
|
||||
}
|
||||
|
||||
void JPASetLineWidth(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
void JPASetLineWidth(JPAEmitterWorkData* work, JPABaseParticle* ptcl JPA_DRAW_CTX_PARAM) {
|
||||
GXSetLineWidth((u8)(ptcl->mParticleScaleX * (25.0f * work->mGlobalPtclScl.x)), GX_TO_ONE);
|
||||
}
|
||||
|
||||
void JPARegistPrm(JPAEmitterWorkData* work) {
|
||||
ZoneScoped;
|
||||
JPABaseEmitter* emtr = work->mpEmtr;
|
||||
GXColor prm = emtr->mPrmClr;
|
||||
prm.r = COLOR_MULTI(prm.r, emtr->mGlobalPrmClr.r);
|
||||
@@ -41,6 +69,7 @@ void JPARegistPrm(JPAEmitterWorkData* work) {
|
||||
}
|
||||
|
||||
void JPARegistEnv(JPAEmitterWorkData* work) {
|
||||
ZoneScoped;
|
||||
JPABaseEmitter* emtr = work->mpEmtr;
|
||||
GXColor env = emtr->mEnvClr;
|
||||
env.r = COLOR_MULTI(env.r, emtr->mGlobalEnvClr.r);
|
||||
@@ -50,6 +79,7 @@ void JPARegistEnv(JPAEmitterWorkData* work) {
|
||||
}
|
||||
|
||||
void JPARegistPrmEnv(JPAEmitterWorkData* work) {
|
||||
ZoneScoped;
|
||||
JPABaseEmitter* emtr = work->mpEmtr;
|
||||
GXColor prm = emtr->mPrmClr;
|
||||
GXColor env = emtr->mEnvClr;
|
||||
@@ -64,7 +94,8 @@ void JPARegistPrmEnv(JPAEmitterWorkData* work) {
|
||||
GXSetTevColor(GX_TEVREG1, env);
|
||||
}
|
||||
|
||||
void JPARegistAlpha(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
void JPARegistAlpha(JPAEmitterWorkData* work, JPABaseParticle* ptcl JPA_DRAW_CTX_PARAM) {
|
||||
ZoneScoped;
|
||||
JPABaseEmitter* emtr = work->mpEmtr;
|
||||
GXColor prm = emtr->mPrmClr;
|
||||
prm.r = COLOR_MULTI(prm.r, emtr->mGlobalPrmClr.r);
|
||||
@@ -72,10 +103,19 @@ void JPARegistAlpha(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
prm.b = COLOR_MULTI(prm.b, emtr->mGlobalPrmClr.b);
|
||||
prm.a = COLOR_MULTI(prm.a, emtr->mGlobalPrmClr.a);
|
||||
prm.a = COLOR_MULTI(prm.a, ptcl->mPrmColorAlphaAnm);
|
||||
#if TARGET_PC
|
||||
if (ctx->batch) {
|
||||
ctx->clr0 = prm;
|
||||
if (ctx->useClr1) {
|
||||
ctx->clr1 = emitter_env_color(work);
|
||||
}
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
GXSetTevColor(GX_TEVREG0, prm);
|
||||
}
|
||||
|
||||
void JPARegistPrmAlpha(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
void JPARegistPrmAlpha(JPAEmitterWorkData* work, JPABaseParticle* ptcl JPA_DRAW_CTX_PARAM) {
|
||||
ZoneScoped;
|
||||
JPABaseEmitter* emtr = work->mpEmtr;
|
||||
GXColor prm = ptcl->mPrmClr;
|
||||
@@ -84,10 +124,19 @@ void JPARegistPrmAlpha(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
prm.b = COLOR_MULTI(prm.b, emtr->mGlobalPrmClr.b);
|
||||
prm.a = COLOR_MULTI(prm.a, emtr->mGlobalPrmClr.a);
|
||||
prm.a = COLOR_MULTI(prm.a, ptcl->mPrmColorAlphaAnm);
|
||||
#if TARGET_PC
|
||||
if (ctx->batch) {
|
||||
ctx->clr0 = prm;
|
||||
if (ctx->useClr1) {
|
||||
ctx->clr1 = emitter_env_color(work);
|
||||
}
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
GXSetTevColor(GX_TEVREG0, prm);
|
||||
}
|
||||
|
||||
void JPARegistPrmAlphaEnv(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
void JPARegistPrmAlphaEnv(JPAEmitterWorkData* work, JPABaseParticle* ptcl JPA_DRAW_CTX_PARAM) {
|
||||
ZoneScoped;
|
||||
JPABaseEmitter* emtr = work->mpEmtr;
|
||||
GXColor prm = ptcl->mPrmClr;
|
||||
@@ -100,11 +149,19 @@ void JPARegistPrmAlphaEnv(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
env.r = COLOR_MULTI(env.r, emtr->mGlobalEnvClr.r);
|
||||
env.g = COLOR_MULTI(env.g, emtr->mGlobalEnvClr.g);
|
||||
env.b = COLOR_MULTI(env.b, emtr->mGlobalEnvClr.b);
|
||||
#if TARGET_PC
|
||||
if (ctx->batch) {
|
||||
ctx->clr0 = prm;
|
||||
ctx->clr1 = env;
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
GXSetTevColor(GX_TEVREG0, prm);
|
||||
GXSetTevColor(GX_TEVREG1, env);
|
||||
}
|
||||
|
||||
void JPARegistAlphaEnv(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
void JPARegistAlphaEnv(JPAEmitterWorkData* work, JPABaseParticle* ptcl JPA_DRAW_CTX_PARAM) {
|
||||
ZoneScoped;
|
||||
JPABaseEmitter* emtr = work->mpEmtr;
|
||||
GXColor prm = emtr->mPrmClr;
|
||||
GXColor env = ptcl->mEnvClr;
|
||||
@@ -116,16 +173,31 @@ void JPARegistAlphaEnv(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
env.r = COLOR_MULTI(env.r, emtr->mGlobalEnvClr.r);
|
||||
env.g = COLOR_MULTI(env.g, emtr->mGlobalEnvClr.g);
|
||||
env.b = COLOR_MULTI(env.b, emtr->mGlobalEnvClr.b);
|
||||
#if TARGET_PC
|
||||
if (ctx->batch) {
|
||||
ctx->clr0 = prm;
|
||||
ctx->clr1 = env;
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
GXSetTevColor(GX_TEVREG0, prm);
|
||||
GXSetTevColor(GX_TEVREG1, env);
|
||||
}
|
||||
|
||||
void JPARegistEnv(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
void JPARegistEnv(JPAEmitterWorkData* work, JPABaseParticle* ptcl JPA_DRAW_CTX_PARAM) {
|
||||
ZoneScoped;
|
||||
JPABaseEmitter* emtr = work->mpEmtr;
|
||||
GXColor env = ptcl->mEnvClr;
|
||||
env.r = COLOR_MULTI(env.r, emtr->mGlobalEnvClr.r);
|
||||
env.g = COLOR_MULTI(env.g, emtr->mGlobalEnvClr.g);
|
||||
env.b = COLOR_MULTI(env.b, emtr->mGlobalEnvClr.b);
|
||||
#if TARGET_PC
|
||||
if (ctx->batch) {
|
||||
ctx->clr0 = emitter_prm_color(work);
|
||||
ctx->clr1 = env;
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
GXSetTevColor(GX_TEVREG1, env);
|
||||
}
|
||||
|
||||
@@ -258,7 +330,7 @@ void JPAGenCalcTexCrdMtxAnm(JPAEmitterWorkData* work) {
|
||||
GXSetTexCoordGen(GX_TEXCOORD0, GX_TG_MTX2x4, GX_TG_TEX0, GX_TEXMTX0);
|
||||
}
|
||||
|
||||
void JPALoadCalcTexCrdMtxAnm(JPAEmitterWorkData* work, JPABaseParticle* param_1) {
|
||||
void JPALoadCalcTexCrdMtxAnm(JPAEmitterWorkData* work, JPABaseParticle* param_1 JPA_DRAW_CTX_PARAM) {
|
||||
ZoneScoped;
|
||||
JPABaseShape* shape = work->mpRes->getBsp();
|
||||
f32 dVar16 = param_1->mAge;
|
||||
@@ -286,6 +358,12 @@ void JPALoadCalcTexCrdMtxAnm(JPAEmitterWorkData* work, JPABaseParticle* param_1)
|
||||
local_108[2][1] = 0.0f;
|
||||
local_108[2][2] = 1.0f;
|
||||
local_108[2][3] = 0.0f;
|
||||
#if TARGET_PC
|
||||
if (ctx->batch) {
|
||||
MTXCopy(local_108, ctx->texMtx);
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
GXLoadTexMtxImm(local_108, 0x1e, GX_MTX2x4);
|
||||
}
|
||||
|
||||
@@ -299,7 +377,7 @@ void JPALoadTexAnm(JPAEmitterWorkData* work) {
|
||||
work->mpResMgr->load(work->mpRes->getTexIdx(work->mpEmtr->mTexAnmIdx), GX_TEXMAP0);
|
||||
}
|
||||
|
||||
void JPALoadTexAnm(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
void JPALoadTexAnm(JPAEmitterWorkData* work, JPABaseParticle* ptcl JPA_DRAW_CTX_PARAM) {
|
||||
ZoneScoped;
|
||||
work->mpResMgr->load(work->mpRes->getTexIdx(ptcl->mTexAnmIdx), GX_TEXMAP0);
|
||||
}
|
||||
@@ -429,6 +507,47 @@ static projectionFunc p_prj[3] = {
|
||||
};
|
||||
|
||||
#if TARGET_PC
|
||||
static void emit_batch_quad(JPAEmitterWorkData* work, const ParticleDrawCtx* ctx,
|
||||
const Mtx posMtx) {
|
||||
const JPAResource::BatchInfo& info = work->mpRes->mBatchInfo;
|
||||
|
||||
for (int i = 0; i < info.vtxCount; i++) {
|
||||
Vec localPos = {info.vtxPos[i][0], info.vtxPos[i][1], info.vtxPos[i][2]};
|
||||
Vec drawPos;
|
||||
MTXMultVec(posMtx, &localPos, &drawPos);
|
||||
|
||||
f32 texS = info.vtxUv[i][0];
|
||||
f32 texT = info.vtxUv[i][1];
|
||||
if (ctx->useTexMtx) {
|
||||
f32 srcS = texS;
|
||||
f32 srcT = texT;
|
||||
texS = ctx->texMtx[0][0] * srcS + ctx->texMtx[0][1] * srcT + ctx->texMtx[0][3];
|
||||
texT = ctx->texMtx[1][0] * srcS + ctx->texMtx[1][1] * srcT + ctx->texMtx[1][3];
|
||||
}
|
||||
|
||||
GXPosition3f32(drawPos.x, drawPos.y, drawPos.z);
|
||||
if (ctx->useClr0) {
|
||||
GXColor4u8(ctx->clr0.r, ctx->clr0.g, ctx->clr0.b, ctx->clr0.a);
|
||||
}
|
||||
if (ctx->useClr1) {
|
||||
GXColor4u8(ctx->clr1.r, ctx->clr1.g, ctx->clr1.b, ctx->clr1.a);
|
||||
}
|
||||
GXTexCoord2f32(texS, texT);
|
||||
}
|
||||
}
|
||||
|
||||
static void submit_particle_quad(
|
||||
JPAEmitterWorkData* work, ParticleDrawCtx* ctx, const Mtx posMtx, const u8* dl, u32 dlSize) {
|
||||
if (ctx->batch) {
|
||||
emit_batch_quad(work, ctx, posMtx);
|
||||
return;
|
||||
}
|
||||
|
||||
GXLoadPosMtxImm(posMtx, GX_PNMTX0);
|
||||
p_prj[work->mPrjType](work, posMtx);
|
||||
GXCallDisplayList(dl, dlSize);
|
||||
}
|
||||
|
||||
void JPAInterpBillboard(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
Mtx ptclPosMtx;
|
||||
MTXTrans(ptclPosMtx, ptcl->mPosition.x, ptcl->mPosition.y, ptcl->mPosition.z);
|
||||
@@ -448,7 +567,7 @@ void JPAInterpRotBillboard(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
}
|
||||
#endif
|
||||
|
||||
void JPADrawBillboard(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
void JPADrawBillboard(JPAEmitterWorkData* work, JPABaseParticle* ptcl JPA_DRAW_CTX_PARAM) {
|
||||
if (ptcl->checkStatus(JPAPtclStts_Invisible)) {
|
||||
return;
|
||||
}
|
||||
@@ -473,12 +592,16 @@ void JPADrawBillboard(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
posMtx[2][2] = 1.0f;
|
||||
posMtx[2][3] = pos.z;
|
||||
posMtx[0][1] = posMtx[0][2] = posMtx[1][0] = posMtx[1][2] = posMtx[2][0] = posMtx[2][1] = 0.0f;
|
||||
#if TARGET_PC
|
||||
submit_particle_quad(work, ctx, posMtx, jpa_dl, sizeof(jpa_dl));
|
||||
#else
|
||||
GXLoadPosMtxImm(posMtx, GX_PNMTX0);
|
||||
p_prj[work->mPrjType](work, posMtx);
|
||||
GXCallDisplayList(jpa_dl, sizeof(jpa_dl));
|
||||
#endif
|
||||
}
|
||||
|
||||
void JPADrawRotBillboard(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
void JPADrawRotBillboard(JPAEmitterWorkData* work, JPABaseParticle* ptcl JPA_DRAW_CTX_PARAM) {
|
||||
if (ptcl->checkStatus(JPAPtclStts_Invisible)) {
|
||||
return;
|
||||
}
|
||||
@@ -517,12 +640,16 @@ void JPADrawRotBillboard(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
posMtx[2][2] = 1.0f;
|
||||
posMtx[2][3] = pos.z;
|
||||
posMtx[0][2] = posMtx[1][2] = posMtx[2][0] = posMtx[2][1] = 0.0f;
|
||||
#if TARGET_PC
|
||||
submit_particle_quad(work, ctx, posMtx, jpa_dl, sizeof(jpa_dl));
|
||||
#else
|
||||
GXLoadPosMtxImm(posMtx, GX_PNMTX0);
|
||||
p_prj[work->mPrjType](work, posMtx);
|
||||
GXCallDisplayList(jpa_dl, sizeof(jpa_dl));
|
||||
#endif
|
||||
}
|
||||
|
||||
void JPADrawYBillboard(JPAEmitterWorkData* work, JPABaseParticle* param_1) {
|
||||
void JPADrawYBillboard(JPAEmitterWorkData* work, JPABaseParticle* param_1 JPA_DRAW_CTX_PARAM) {
|
||||
if (param_1->checkStatus(JPAPtclStts_Invisible)) {
|
||||
return;
|
||||
}
|
||||
@@ -542,12 +669,16 @@ void JPADrawYBillboard(JPAEmitterWorkData* work, JPABaseParticle* param_1) {
|
||||
local_38[2][2] = work->mYBBCamMtx[2][2];
|
||||
local_38[2][3] = local_48.z;
|
||||
local_38[0][1] = local_38[0][2] = local_38[1][0] = local_38[2][0] = 0.0f;
|
||||
#if TARGET_PC
|
||||
submit_particle_quad(work, ctx, local_38, jpa_dl, sizeof(jpa_dl));
|
||||
#else
|
||||
GXLoadPosMtxImm(local_38, GX_PNMTX0);
|
||||
p_prj[work->mPrjType](work, local_38);
|
||||
GXCallDisplayList(jpa_dl, sizeof(jpa_dl));
|
||||
#endif
|
||||
}
|
||||
|
||||
void JPADrawRotYBillboard(JPAEmitterWorkData* work, JPABaseParticle* param_1) {
|
||||
void JPADrawRotYBillboard(JPAEmitterWorkData* work, JPABaseParticle* param_1 JPA_DRAW_CTX_PARAM) {
|
||||
if (param_1->checkStatus(JPAPtclStts_Invisible)) {
|
||||
return;
|
||||
}
|
||||
@@ -576,9 +707,13 @@ void JPADrawRotYBillboard(JPAEmitterWorkData* work, JPABaseParticle* param_1) {
|
||||
local_38[2][1] = local_94 * fVar1;
|
||||
local_38[2][2] = local_90;
|
||||
local_38[2][3] = local_48.z;
|
||||
#if TARGET_PC
|
||||
submit_particle_quad(work, ctx, local_38, jpa_dl, sizeof(jpa_dl));
|
||||
#else
|
||||
GXLoadPosMtxImm(local_38, GX_PNMTX0);
|
||||
p_prj[work->mPrjType](work, local_38);
|
||||
GXCallDisplayList(jpa_dl, sizeof(jpa_dl));
|
||||
#endif
|
||||
}
|
||||
|
||||
void dirTypeVel(JPAEmitterWorkData const* work, JPABaseParticle const* param_1,
|
||||
@@ -741,6 +876,88 @@ static u8* p_dl[2] = {
|
||||
};
|
||||
|
||||
#if TARGET_PC
|
||||
static bool make_direction_mtx(JPAEmitterWorkData* work, JPABaseParticle* ptcl, Mtx posMtx) {
|
||||
JGeometry::TVec3<f32> axisY;
|
||||
JGeometry::TVec3<f32> axisZ;
|
||||
JGeometry::TVec3<f32> baseAxis(ptcl->mBaseAxis);
|
||||
p_direction[work->mDirType](work, ptcl, &axisY);
|
||||
if (axisY.isZero()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
axisY.normalize();
|
||||
axisZ.cross(baseAxis, axisY);
|
||||
if (axisZ.isZero()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
axisZ.normalize();
|
||||
baseAxis.cross(axisY, axisZ);
|
||||
baseAxis.normalize();
|
||||
ptcl->mBaseAxis.set(baseAxis);
|
||||
|
||||
f32 scaleX = work->mGlobalPtclScl.x * ptcl->mParticleScaleX;
|
||||
f32 scaleY = work->mGlobalPtclScl.y * ptcl->mParticleScaleY;
|
||||
posMtx[0][0] = baseAxis.x;
|
||||
posMtx[0][1] = axisY.x;
|
||||
posMtx[0][2] = axisZ.x;
|
||||
posMtx[0][3] = ptcl->mPosition.x;
|
||||
posMtx[1][0] = baseAxis.y;
|
||||
posMtx[1][1] = axisY.y;
|
||||
posMtx[1][2] = axisZ.y;
|
||||
posMtx[1][3] = ptcl->mPosition.y;
|
||||
posMtx[2][0] = baseAxis.z;
|
||||
posMtx[2][1] = axisY.z;
|
||||
posMtx[2][2] = axisZ.z;
|
||||
posMtx[2][3] = ptcl->mPosition.z;
|
||||
p_plane[work->mPlaneType](posMtx, scaleX, scaleY);
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool make_rot_direction_mtx(JPAEmitterWorkData* work, JPABaseParticle* ptcl, Mtx posMtx) {
|
||||
f32 sinRot = JMASSin(ptcl->mRotateAngle);
|
||||
f32 cosRot = JMASCos(ptcl->mRotateAngle);
|
||||
JGeometry::TVec3<f32> axisY;
|
||||
JGeometry::TVec3<f32> axisZ;
|
||||
JGeometry::TVec3<f32> baseAxis(ptcl->mBaseAxis);
|
||||
p_direction[work->mDirType](work, ptcl, &axisY);
|
||||
if (axisY.isZero()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
axisY.normalize();
|
||||
axisZ.cross(baseAxis, axisY);
|
||||
if (axisZ.isZero()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
axisZ.normalize();
|
||||
baseAxis.cross(axisY, axisZ);
|
||||
baseAxis.normalize();
|
||||
ptcl->mBaseAxis.set(baseAxis);
|
||||
|
||||
f32 scaleX = work->mGlobalPtclScl.x * ptcl->mParticleScaleX;
|
||||
f32 scaleY = work->mGlobalPtclScl.y * ptcl->mParticleScaleY;
|
||||
Mtx rotMtx;
|
||||
Mtx dirMtx;
|
||||
p_rot[work->mRotType](sinRot, cosRot, rotMtx);
|
||||
p_plane[work->mPlaneType](rotMtx, scaleX, scaleY);
|
||||
dirMtx[0][0] = baseAxis.x;
|
||||
dirMtx[0][1] = axisY.x;
|
||||
dirMtx[0][2] = axisZ.x;
|
||||
dirMtx[0][3] = ptcl->mPosition.x;
|
||||
dirMtx[1][0] = baseAxis.y;
|
||||
dirMtx[1][1] = axisY.y;
|
||||
dirMtx[1][2] = axisZ.y;
|
||||
dirMtx[1][3] = ptcl->mPosition.y;
|
||||
dirMtx[2][0] = baseAxis.z;
|
||||
dirMtx[2][1] = axisY.z;
|
||||
dirMtx[2][2] = axisZ.z;
|
||||
dirMtx[2][3] = ptcl->mPosition.z;
|
||||
MTXConcat(dirMtx, rotMtx, posMtx);
|
||||
return true;
|
||||
}
|
||||
|
||||
void JPAInterpDirection(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
JGeometry::TVec3<f32> axisY;
|
||||
JGeometry::TVec3<f32> axisZ;
|
||||
@@ -823,7 +1040,7 @@ void JPAInterpRotDirection(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
}
|
||||
#endif
|
||||
|
||||
void JPADrawDirection(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
void JPADrawDirection(JPAEmitterWorkData* work, JPABaseParticle* ptcl JPA_DRAW_CTX_PARAM) {
|
||||
if (ptcl->checkStatus(JPAPtclStts_Invisible)) {
|
||||
return;
|
||||
}
|
||||
@@ -832,8 +1049,12 @@ void JPADrawDirection(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
|
||||
Mtx posMtx;
|
||||
#if TARGET_PC
|
||||
if (!dusk::frame_interp::lookup_replacement(ptcl, posMtx))
|
||||
#endif
|
||||
if (!dusk::frame_interp::lookup_replacement(ptcl, posMtx) &&
|
||||
!make_direction_mtx(work, ptcl, posMtx))
|
||||
{
|
||||
return;
|
||||
}
|
||||
#else
|
||||
{
|
||||
JGeometry::TVec3<f32> axisY;
|
||||
JGeometry::TVec3<f32> axisZ;
|
||||
@@ -869,14 +1090,19 @@ void JPADrawDirection(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
posMtx[2][3] = ptcl->mPosition.z;
|
||||
p_plane[work->mPlaneType](posMtx, scaleX, scaleY);
|
||||
}
|
||||
#endif
|
||||
|
||||
MTXConcat(work->mPosCamMtx, posMtx, posMtx);
|
||||
#if TARGET_PC
|
||||
submit_particle_quad(work, ctx, posMtx, p_dl[work->mDLType], sizeof(jpa_dl));
|
||||
#else
|
||||
GXLoadPosMtxImm(posMtx, GX_PNMTX0);
|
||||
p_prj[work->mPrjType](work, posMtx);
|
||||
GXCallDisplayList(p_dl[work->mDLType], sizeof(jpa_dl));
|
||||
#endif
|
||||
}
|
||||
|
||||
void JPADrawRotDirection(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
void JPADrawRotDirection(JPAEmitterWorkData* work, JPABaseParticle* ptcl JPA_DRAW_CTX_PARAM) {
|
||||
if (ptcl->checkStatus(JPAPtclStts_Invisible)) {
|
||||
return;
|
||||
}
|
||||
@@ -886,8 +1112,12 @@ void JPADrawRotDirection(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
Mtx mtx1;
|
||||
Mtx mtx2;
|
||||
#if TARGET_PC
|
||||
if (!dusk::frame_interp::lookup_replacement(ptcl, mtx1))
|
||||
#endif
|
||||
if (!dusk::frame_interp::lookup_replacement(ptcl, mtx1) &&
|
||||
!make_rot_direction_mtx(work, ptcl, mtx1))
|
||||
{
|
||||
return;
|
||||
}
|
||||
#else
|
||||
{
|
||||
f32 sinRot = JMASSin(ptcl->mRotateAngle);
|
||||
f32 cosRot = JMASCos(ptcl->mRotateAngle);
|
||||
@@ -927,13 +1157,18 @@ void JPADrawRotDirection(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
mtx2[2][3] = ptcl->mPosition.z;
|
||||
MTXConcat(mtx2, mtx1, mtx1);
|
||||
}
|
||||
#endif
|
||||
MTXConcat(work->mPosCamMtx, mtx1, mtx2);
|
||||
#if TARGET_PC
|
||||
submit_particle_quad(work, ctx, mtx2, p_dl[work->mDLType], sizeof(jpa_dl));
|
||||
#else
|
||||
GXLoadPosMtxImm(mtx2, GX_PNMTX0);
|
||||
p_prj[work->mPrjType](work, mtx2);
|
||||
GXCallDisplayList(p_dl[work->mDLType], sizeof(jpa_dl));
|
||||
#endif
|
||||
}
|
||||
|
||||
void JPADrawDBillboard(JPAEmitterWorkData* param_0, JPABaseParticle* param_1) {
|
||||
void JPADrawDBillboard(JPAEmitterWorkData* param_0, JPABaseParticle* param_1 JPA_DRAW_CTX_PARAM) {
|
||||
if (param_1->checkStatus(JPAPtclStts_Invisible)) {
|
||||
return;
|
||||
}
|
||||
@@ -970,7 +1205,7 @@ void JPADrawDBillboard(JPAEmitterWorkData* param_0, JPABaseParticle* param_1) {
|
||||
GXCallDisplayList(jpa_dl, sizeof(jpa_dl));
|
||||
}
|
||||
|
||||
void JPADrawRotation(JPAEmitterWorkData* param_0, JPABaseParticle* param_1) {
|
||||
void JPADrawRotation(JPAEmitterWorkData* param_0, JPABaseParticle* param_1 JPA_DRAW_CTX_PARAM) {
|
||||
if (param_1->checkStatus(JPAPtclStts_Invisible)) {
|
||||
return;
|
||||
}
|
||||
@@ -988,12 +1223,16 @@ void JPADrawRotation(JPAEmitterWorkData* param_0, JPABaseParticle* param_1) {
|
||||
auStack_88[1][3] = param_1->mPosition.y;
|
||||
auStack_88[2][3] = param_1->mPosition.z;
|
||||
MTXConcat(param_0->mPosCamMtx, auStack_88, auStack_88);
|
||||
#if TARGET_PC
|
||||
submit_particle_quad(param_0, ctx, auStack_88, p_dl[param_0->mDLType], sizeof(jpa_dl));
|
||||
#else
|
||||
GXLoadPosMtxImm(auStack_88, 0);
|
||||
p_prj[param_0->mPrjType](param_0, auStack_88);
|
||||
GXCallDisplayList(p_dl[param_0->mDLType], sizeof(jpa_dl));
|
||||
#endif
|
||||
}
|
||||
|
||||
void JPADrawPoint(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
void JPADrawPoint(JPAEmitterWorkData* work, JPABaseParticle* ptcl JPA_DRAW_CTX_PARAM) {
|
||||
if (ptcl->checkStatus(JPAPtclStts_Invisible)) {
|
||||
return;
|
||||
}
|
||||
@@ -1010,7 +1249,7 @@ void JPADrawPoint(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
GXSetVtxDesc(GX_VA_TEX0, GX_INDEX8);
|
||||
}
|
||||
|
||||
void JPADrawLine(JPAEmitterWorkData* param_0, JPABaseParticle* param_1) {
|
||||
void JPADrawLine(JPAEmitterWorkData* param_0, JPABaseParticle* param_1 JPA_DRAW_CTX_PARAM) {
|
||||
if (param_1->checkStatus(JPAPtclStts_Invisible)) {
|
||||
return;
|
||||
}
|
||||
@@ -1086,7 +1325,7 @@ void JPADrawStripe(JPAEmitterWorkData* param_0) {
|
||||
GXSetVtxDesc(GX_VA_POS, GX_DIRECT);
|
||||
GXSetVtxDesc(GX_VA_TEX0, GX_DIRECT);
|
||||
GXBegin(GX_TRIANGLESTRIP, GX_VTXFMT1, ptcl_num << 1);
|
||||
for (JPANode<JPABaseParticle>* node = startNode; node != param_0->mpAlivePtcl->getEnd();
|
||||
for (JPANode<JPABaseParticle>* node = startNode; node != param_0->mpAlivePtcl->getEnd();
|
||||
node = node_func(node), coord += step) {
|
||||
param_0->mpCurNode = node;
|
||||
JPABaseParticle* particle = node->getObject();
|
||||
@@ -1111,7 +1350,7 @@ void JPADrawStripe(JPAEmitterWorkData* param_0) {
|
||||
}
|
||||
particle->mBaseAxis.cross(local_f8, local_104);
|
||||
particle->mBaseAxis.normalize();
|
||||
|
||||
|
||||
local_c8[0][0] = local_104.x;
|
||||
local_c8[0][1] = local_f8.x;
|
||||
local_c8[0][2] = particle->mBaseAxis.x;
|
||||
@@ -1177,7 +1416,7 @@ void JPADrawStripeX(JPAEmitterWorkData* param_0) {
|
||||
GXSetVtxDesc(GX_VA_POS, GX_DIRECT);
|
||||
GXSetVtxDesc(GX_VA_TEX0, GX_DIRECT);
|
||||
GXBegin(GX_TRIANGLESTRIP, GX_VTXFMT1, ptcl_num << 1);
|
||||
for (JPANode<JPABaseParticle>* node = startNode; node != param_0->mpAlivePtcl->getEnd();
|
||||
for (JPANode<JPABaseParticle>* node = startNode; node != param_0->mpAlivePtcl->getEnd();
|
||||
node = node_func(node), coord += step) {
|
||||
param_0->mpCurNode = node;
|
||||
JPABaseParticle* particle = node->getObject();
|
||||
@@ -1202,7 +1441,7 @@ void JPADrawStripeX(JPAEmitterWorkData* param_0) {
|
||||
}
|
||||
particle->mBaseAxis.cross(local_c0, local_cc);
|
||||
particle->mBaseAxis.normalize();
|
||||
|
||||
|
||||
local_90[0][0] = local_cc.x;
|
||||
local_90[0][1] = local_c0.x;
|
||||
local_90[0][2] = particle->mBaseAxis.x;
|
||||
@@ -1227,7 +1466,7 @@ void JPADrawStripeX(JPAEmitterWorkData* param_0) {
|
||||
|
||||
coord = start_coord;
|
||||
GXBegin(GX_TRIANGLESTRIP, GX_VTXFMT1, ptcl_num << 1);
|
||||
for (JPANode<JPABaseParticle>* node = startNode; node != param_0->mpAlivePtcl->getEnd();
|
||||
for (JPANode<JPABaseParticle>* node = startNode; node != param_0->mpAlivePtcl->getEnd();
|
||||
node = node_func(node), coord += step) {
|
||||
param_0->mpCurNode = node;
|
||||
JPABaseParticle* particle = node->getObject();
|
||||
@@ -1252,7 +1491,7 @@ void JPADrawStripeX(JPAEmitterWorkData* param_0) {
|
||||
}
|
||||
particle->mBaseAxis.cross(local_c0, local_cc);
|
||||
particle->mBaseAxis.normalize();
|
||||
|
||||
|
||||
local_90[0][0] = local_cc.x;
|
||||
local_90[0][1] = local_c0.x;
|
||||
local_90[0][2] = particle->mBaseAxis.x;
|
||||
@@ -1289,7 +1528,7 @@ void JPADrawEmitterCallBackB(JPAEmitterWorkData* work) {
|
||||
emtr->mpEmtrCallBack->draw(emtr);
|
||||
}
|
||||
|
||||
void JPADrawParticleCallBack(JPAEmitterWorkData* work, JPABaseParticle* ptcl) {
|
||||
void JPADrawParticleCallBack(JPAEmitterWorkData* work, JPABaseParticle* ptcl JPA_DRAW_CTX_PARAM) {
|
||||
JPABaseEmitter* emtr = work->mpEmtr;
|
||||
if (emtr->mpPtclCallBack == NULL) {
|
||||
return;
|
||||
|
||||
@@ -18,9 +18,21 @@
|
||||
#include "global.h"
|
||||
#include "tracy/Tracy.hpp"
|
||||
|
||||
#if TARGET_PC
|
||||
#define JPA_DRAW_CTX_ARG , &ctx
|
||||
#else
|
||||
#define JPA_DRAW_CTX_ARG
|
||||
#endif
|
||||
|
||||
JPAResource::JPAResource() {
|
||||
mpCalcEmitterFuncList = mpDrawEmitterFuncList = mpDrawEmitterChildFuncList = NULL;
|
||||
#if TARGET_PC
|
||||
mpCalcParticleFuncList = mpCalcParticleChildFuncList = NULL;
|
||||
mpDrawParticleFuncList = mpDrawParticleChildFuncList = NULL;
|
||||
mBatchInfo = {};
|
||||
#else
|
||||
mpCalcParticleFuncList = mpDrawParticleFuncList = mpCalcParticleChildFuncList = mpDrawParticleChildFuncList = NULL;
|
||||
#endif
|
||||
pBsp = NULL;
|
||||
pEsp = NULL;
|
||||
pCsp = NULL;
|
||||
@@ -61,6 +73,60 @@ static u8 jpa_crd[32] ATTRIBUTE_ALIGN(32) = {
|
||||
0x00, 0x00, 0x01, 0x00, 0x01, 0x02, 0x00, 0x02, 0x00, 0x00, 0x02, 0x00, 0x02, 0x02, 0x00, 0x02,
|
||||
};
|
||||
|
||||
#if TARGET_PC
|
||||
void JPAResource::initBatchInfo() {
|
||||
mBatchInfo = {};
|
||||
|
||||
bool hasDrawFunc = false;
|
||||
for (int i = 0; i < mpDrawParticleFuncListNum; i++) {
|
||||
DrawParticleFunc func = mpDrawParticleFuncList[i];
|
||||
if (func == JPADrawBillboard || func == JPADrawRotBillboard ||
|
||||
func == JPADrawYBillboard || func == JPADrawRotYBillboard ||
|
||||
func == JPADrawDirection || func == JPADrawRotDirection || func == JPADrawRotation)
|
||||
{
|
||||
hasDrawFunc = true;
|
||||
} else if (func == JPADrawParticleCallBack) {
|
||||
// Batchable only for emitters without a particle callback; checked per draw
|
||||
} else if (func == JPALoadCalcTexCrdMtxAnm) {
|
||||
mBatchInfo.hasPtclTexMtx = true;
|
||||
} else if (func == JPARegistAlpha || func == JPARegistPrmAlpha ||
|
||||
func == JPARegistPrmAlphaEnv || func == JPARegistAlphaEnv ||
|
||||
func == static_cast<DrawParticleFunc>(JPARegistEnv)) // overloaded
|
||||
{
|
||||
mBatchInfo.hasPtclColor = true;
|
||||
} else {
|
||||
// JPADrawPoint, JPADrawLine, JPADrawDBillboard, JPALoadTexAnm,
|
||||
// JPASetPointSize, JPASetLineWidth
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!hasDrawFunc) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Template array offsets, same math as setPTev
|
||||
int base_plane_type = (pBsp->getType() == 3 || pBsp->getType() == 7) ?
|
||||
pBsp->getBasePlaneType() : 0;
|
||||
int center_offset = pEsp != nullptr ? (pEsp->getScaleCenterX() + 3 * pEsp->getScaleCenterY()) * 0xC : 0x30;
|
||||
const s8* pos = reinterpret_cast<const s8*>(jpa_pos) + center_offset + base_plane_type * 0x6C;
|
||||
const s8* crd = reinterpret_cast<const s8*>(jpa_crd) + (pBsp->getTilingS() + 2 * pBsp->getTilingT()) * 8;
|
||||
|
||||
bool cross = pBsp->getType() == 4 || pBsp->getType() == 8;
|
||||
mBatchInfo.vtxCount = cross ? 8 : 4;
|
||||
for (int i = 0; i < mBatchInfo.vtxCount; i++) {
|
||||
int posIdx = i < 4 ? i : 72 + (i - 4);
|
||||
int crdIdx = i & 3;
|
||||
mBatchInfo.vtxPos[i][0] = pos[posIdx * 3 + 0];
|
||||
mBatchInfo.vtxPos[i][1] = pos[posIdx * 3 + 1];
|
||||
mBatchInfo.vtxPos[i][2] = pos[posIdx * 3 + 2];
|
||||
mBatchInfo.vtxUv[i][0] = crd[crdIdx * 2 + 0];
|
||||
mBatchInfo.vtxUv[i][1] = crd[crdIdx * 2 + 1];
|
||||
}
|
||||
|
||||
mBatchInfo.supported = true;
|
||||
}
|
||||
#endif
|
||||
|
||||
void JPAResource::init(JKRHeap* heap) {
|
||||
BOOL is_glbl_clr_anm = pBsp->isGlblClrAnm();
|
||||
BOOL is_glbl_tex_anm = pBsp->isGlblTexAnm();
|
||||
@@ -525,7 +591,10 @@ void JPAResource::init(JKRHeap* heap) {
|
||||
|
||||
if (mpDrawParticleFuncListNum != 0) {
|
||||
mpDrawParticleFuncList =
|
||||
(ParticleFunc*)JKRAllocFromHeap(heap, mpDrawParticleFuncListNum * sizeof(ParticleFunc), alignof(ParticleFunc));
|
||||
(DrawParticleFunc*)JKRAllocFromHeap(
|
||||
heap,
|
||||
mpDrawParticleFuncListNum * sizeof(DrawParticleFunc),
|
||||
alignof(DrawParticleFunc));
|
||||
}
|
||||
|
||||
func_no = 0;
|
||||
@@ -635,7 +704,10 @@ void JPAResource::init(JKRHeap* heap) {
|
||||
|
||||
if (mpDrawParticleChildFuncListNum != 0) {
|
||||
mpDrawParticleChildFuncList =
|
||||
(ParticleFunc*)JKRAllocFromHeap(heap, mpDrawParticleChildFuncListNum * sizeof(ParticleFunc), sizeof(EmitterFunc));
|
||||
(DrawParticleFunc*)JKRAllocFromHeap(
|
||||
heap,
|
||||
mpDrawParticleChildFuncListNum * sizeof(DrawParticleFunc),
|
||||
alignof(DrawParticleFunc));
|
||||
}
|
||||
|
||||
func_no = 0;
|
||||
@@ -699,6 +771,10 @@ void JPAResource::init(JKRHeap* heap) {
|
||||
mpDrawParticleChildFuncList[func_no] = &JPARegistPrmAlphaEnv;
|
||||
func_no++;
|
||||
}
|
||||
|
||||
#if TARGET_PC
|
||||
initBatchInfo();
|
||||
#endif
|
||||
}
|
||||
|
||||
bool JPAResource::calc(JPAEmitterWorkData* work, JPABaseEmitter* emtr) {
|
||||
@@ -808,6 +884,183 @@ void JPAResource::draw(JPAEmitterWorkData* work, JPABaseEmitter* emtr) {
|
||||
}
|
||||
}
|
||||
|
||||
#if TARGET_PC
|
||||
static GXTevAlphaArg to_vtx_alpha_arg(GXTevAlphaArg arg) {
|
||||
return arg == GX_CA_A0 ? GX_CA_RASA : arg;
|
||||
}
|
||||
|
||||
static void batch_set_tev_op(GXTevStageID stage) {
|
||||
GXSetTevColorOp(stage, GX_TEV_ADD, GX_TB_ZERO, GX_CS_SCALE_1, GX_TRUE, GX_TEVPREV);
|
||||
GXSetTevAlphaOp(stage, GX_TEV_ADD, GX_TB_ZERO, GX_CS_SCALE_1, GX_TRUE, GX_TEVPREV);
|
||||
}
|
||||
|
||||
static void batch_setup_tev(JPAEmitterWorkData* work, bool useClr1) {
|
||||
JPABaseShape* shape = work->mpRes->getBsp();
|
||||
JPAExTexShape* ets = work->mpRes->getEts();
|
||||
bool useIndirect = ets != nullptr && ets->isUseIndirect();
|
||||
|
||||
// JPAEmitterManager::draw configures both channels to pass vertex color through
|
||||
GXSetNumChans(useClr1 ? 2 : 1);
|
||||
|
||||
const GXTevAlphaArg* alphaArg = shape->getTevAlphaArg();
|
||||
GXSetTevOrder(GX_TEVSTAGE0, GX_TEXCOORD0, GX_TEXMAP0, GX_COLOR0A0);
|
||||
GXSetTevAlphaIn(GX_TEVSTAGE0, to_vtx_alpha_arg(alphaArg[0]), to_vtx_alpha_arg(alphaArg[1]),
|
||||
to_vtx_alpha_arg(alphaArg[2]), to_vtx_alpha_arg(alphaArg[3]));
|
||||
batch_set_tev_op(GX_TEVSTAGE0);
|
||||
if (!useIndirect) {
|
||||
GXSetTevDirect(GX_TEVSTAGE0);
|
||||
}
|
||||
GXTevStageID nextStage = GX_TEVSTAGE1;
|
||||
|
||||
switch (shape->getTevColorArgSel()) {
|
||||
case 0: // TEXC
|
||||
GXSetTevColorIn(GX_TEVSTAGE0, GX_CC_ZERO, GX_CC_TEXC, GX_CC_ONE, GX_CC_ZERO);
|
||||
break;
|
||||
case 1: // C0 * TEXC
|
||||
GXSetTevColorIn(GX_TEVSTAGE0, GX_CC_ZERO, GX_CC_RASC, GX_CC_TEXC, GX_CC_ZERO);
|
||||
break;
|
||||
case 2: // lerp(C0, 1, TEXC)
|
||||
GXSetTevColorIn(GX_TEVSTAGE0, GX_CC_RASC, GX_CC_ONE, GX_CC_TEXC, GX_CC_ZERO);
|
||||
break;
|
||||
case 3: // lerp(C1, C0, TEXC) = C0 * TEXC (stage 0) + C1 * (1 - TEXC) (stage 1)
|
||||
GXSetTevColorIn(GX_TEVSTAGE0, GX_CC_ZERO, GX_CC_RASC, GX_CC_TEXC, GX_CC_ZERO);
|
||||
GXSetTevOrder(nextStage, GX_TEXCOORD0, GX_TEXMAP0, GX_COLOR1A1);
|
||||
GXSetTevColorIn(nextStage, GX_CC_RASC, GX_CC_ZERO, GX_CC_TEXC, GX_CC_CPREV);
|
||||
GXSetTevAlphaIn(nextStage, GX_CA_ZERO, GX_CA_ZERO, GX_CA_ZERO, GX_CA_APREV);
|
||||
batch_set_tev_op(nextStage);
|
||||
GXSetTevDirect(nextStage);
|
||||
nextStage = static_cast<GXTevStageID>(nextStage + 1);
|
||||
break;
|
||||
case 4: // TEXC * C0 + C1: C0 * TEXC (stage 0), + C1 (stage 1)
|
||||
GXSetTevColorIn(GX_TEVSTAGE0, GX_CC_ZERO, GX_CC_RASC, GX_CC_TEXC, GX_CC_ZERO);
|
||||
GXSetTevOrder(nextStage, GX_TEXCOORD0, GX_TEXMAP0, GX_COLOR1A1);
|
||||
GXSetTevColorIn(nextStage, GX_CC_CPREV, GX_CC_ZERO, GX_CC_ZERO, GX_CC_RASC);
|
||||
GXSetTevAlphaIn(nextStage, GX_CA_ZERO, GX_CA_ZERO, GX_CA_ZERO, GX_CA_APREV);
|
||||
batch_set_tev_op(nextStage);
|
||||
GXSetTevDirect(nextStage);
|
||||
nextStage = static_cast<GXTevStageID>(nextStage + 1);
|
||||
break;
|
||||
case 5: // C0
|
||||
GXSetTevColorIn(GX_TEVSTAGE0, GX_CC_ZERO, GX_CC_ZERO, GX_CC_ZERO, GX_CC_RASC);
|
||||
break;
|
||||
}
|
||||
|
||||
if (ets != nullptr && ets->isUseSecTex()) {
|
||||
// Mirrors setPTev's secondary texture stage, at the next free stage
|
||||
GXTexCoordID texCoord = useIndirect ? GX_TEXCOORD2 : GX_TEXCOORD1;
|
||||
GXSetTevOrder(nextStage, texCoord, GX_TEXMAP3, GX_COLOR_NULL);
|
||||
GXSetTevColorIn(nextStage, GX_CC_ZERO, GX_CC_TEXC, GX_CC_CPREV, GX_CC_ZERO);
|
||||
GXSetTevAlphaIn(nextStage, GX_CA_ZERO, GX_CA_TEXA, GX_CA_APREV, GX_CA_ZERO);
|
||||
batch_set_tev_op(nextStage);
|
||||
GXSetTevDirect(nextStage);
|
||||
nextStage = static_cast<GXTevStageID>(nextStage + 1);
|
||||
}
|
||||
|
||||
GXSetNumTevStages(nextStage);
|
||||
}
|
||||
|
||||
static void batch_setup_vtx_desc(bool useClr0, bool useClr1) {
|
||||
static Mtx identityMtx = {
|
||||
{1.0f, 0.0f, 0.0f, 0.0f},
|
||||
{0.0f, 1.0f, 0.0f, 0.0f},
|
||||
{0.0f, 0.0f, 1.0f, 0.0f},
|
||||
};
|
||||
|
||||
GXLoadPosMtxImm(identityMtx, GX_PNMTX0);
|
||||
GXSetCurrentMtx(GX_PNMTX0);
|
||||
GXClearVtxDesc();
|
||||
GXSetVtxDesc(GX_VA_POS, GX_DIRECT);
|
||||
if (useClr0) {
|
||||
GXSetVtxDesc(GX_VA_CLR0, GX_DIRECT);
|
||||
}
|
||||
if (useClr1) {
|
||||
GXSetVtxDesc(GX_VA_CLR1, GX_DIRECT);
|
||||
}
|
||||
GXSetVtxDesc(GX_VA_TEX0, GX_DIRECT);
|
||||
GXSetVtxAttrFmt(GX_VTXFMT1, GX_VA_POS, GX_POS_XYZ, GX_F32, 0);
|
||||
if (useClr0) {
|
||||
GXSetVtxAttrFmt(GX_VTXFMT1, GX_VA_CLR0, GX_CLR_RGBA, GX_RGBA8, 0);
|
||||
}
|
||||
if (useClr1) {
|
||||
GXSetVtxAttrFmt(GX_VTXFMT1, GX_VA_CLR1, GX_CLR_RGBA, GX_RGBA8, 0);
|
||||
}
|
||||
GXSetVtxAttrFmt(GX_VTXFMT1, GX_VA_TEX0, GX_TEX_ST, GX_F32, 0);
|
||||
}
|
||||
|
||||
static void batch_restore_gx(JPAEmitterWorkData* work, bool changedTev, bool changedTexMtx) {
|
||||
GXClearVtxDesc();
|
||||
GXSetVtxDesc(GX_VA_POS, GX_INDEX8);
|
||||
GXSetVtxDesc(GX_VA_TEX0, GX_INDEX8);
|
||||
GXSetVtxAttrFmt(GX_VTXFMT0, GX_VA_POS, GX_POS_XYZ, GX_S8, 0);
|
||||
GXSetVtxAttrFmt(GX_VTXFMT0, GX_VA_TEX0, GX_TEX_ST, GX_S8, 0);
|
||||
GXSetVtxAttrFmt(GX_VTXFMT1, GX_VA_POS, GX_POS_XYZ, GX_F32, 0);
|
||||
GXSetVtxAttrFmt(GX_VTXFMT1, GX_VA_TEX0, GX_TEX_ST, GX_F32, 0);
|
||||
GXSetCurrentMtx(GX_PNMTX0);
|
||||
|
||||
if (changedTexMtx) {
|
||||
GXSetTexCoordGen(GX_TEXCOORD0, GX_TG_MTX2x4, GX_TG_TEX0, GX_TEXMTX0);
|
||||
}
|
||||
|
||||
if (changedTev) {
|
||||
GXSetNumChans(0);
|
||||
work->mpRes->getBsp()->setGX(work);
|
||||
work->mpRes->setPTev();
|
||||
}
|
||||
}
|
||||
|
||||
static bool draw_particle_batch(JPAEmitterWorkData* work) {
|
||||
ZoneScoped;
|
||||
|
||||
JPAResource* res = work->mpRes;
|
||||
const JPAResource::BatchInfo& info = res->mBatchInfo;
|
||||
if (!info.supported || work->mPrjType != 0 || work->mpEmtr->mpPtclCallBack != nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool useClr0 = false;
|
||||
bool useClr1 = false;
|
||||
if (info.hasPtclColor) {
|
||||
u32 colorSel = res->getBsp()->getTevColorArgSel();
|
||||
if (colorSel >= 6) {
|
||||
return false;
|
||||
}
|
||||
useClr0 = true;
|
||||
useClr1 = colorSel == 3 || colorSel == 4;
|
||||
batch_setup_tev(work, useClr1);
|
||||
}
|
||||
|
||||
if (info.hasPtclTexMtx) {
|
||||
// UVs are CPU-transformed; drop the texgen
|
||||
GXSetTexCoordGen(GX_TEXCOORD0, GX_TG_MTX2x4, GX_TG_TEX0, GX_IDENTITY);
|
||||
}
|
||||
|
||||
batch_setup_vtx_desc(useClr0, useClr1);
|
||||
|
||||
ParticleDrawCtx ctx{};
|
||||
ctx.batch = true;
|
||||
ctx.useTexMtx = info.hasPtclTexMtx;
|
||||
ctx.useClr0 = useClr0;
|
||||
ctx.useClr1 = useClr1;
|
||||
|
||||
bool fwdAhead = res->getBsp()->isDrawFwdAhead();
|
||||
JPANode<JPABaseParticle>* node = fwdAhead ? work->mpEmtr->mAlivePtclBase.getLast() :
|
||||
work->mpEmtr->mAlivePtclBase.getFirst();
|
||||
|
||||
GXBegin(GX_QUADS, GX_VTXFMT1, GX_AUTO);
|
||||
while (node != work->mpEmtr->mAlivePtclBase.getEnd()) {
|
||||
work->mpCurNode = node;
|
||||
for (int i = res->mpDrawParticleFuncListNum - 1; i >= 0; i--) {
|
||||
(*res->mpDrawParticleFuncList[i])(work, node->getObject(), &ctx);
|
||||
}
|
||||
node = fwdAhead ? node->getPrev() : node->getNext();
|
||||
}
|
||||
GXEnd();
|
||||
|
||||
batch_restore_gx(work, useClr0, info.hasPtclTexMtx);
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
|
||||
void JPAResource::drawP(JPAEmitterWorkData* work) {
|
||||
ZoneScoped;
|
||||
work->mpEmtr->clearStatus(0x80);
|
||||
@@ -842,13 +1095,25 @@ void JPAResource::drawP(JPAEmitterWorkData* work) {
|
||||
(*mpDrawEmitterFuncList[i])(work);
|
||||
}
|
||||
|
||||
#if TARGET_PC
|
||||
if (draw_particle_batch(work)) {
|
||||
GXSetMisc(GX_MT_XF_FLUSH, 0);
|
||||
if (work->mpEmtr->mpEmtrCallBack != nullptr) {
|
||||
work->mpEmtr->mpEmtrCallBack->drawAfter(work->mpEmtr);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
ParticleDrawCtx ctx{}; // immediate mode
|
||||
#endif
|
||||
|
||||
if (pBsp->isDrawFwdAhead()) {
|
||||
JPANode<JPABaseParticle>* node = work->mpEmtr->mAlivePtclBase.getLast();
|
||||
for (; node != work->mpEmtr->mAlivePtclBase.getEnd(); node = node->getPrev()) {
|
||||
work->mpCurNode = node;
|
||||
if (mpDrawParticleFuncList != NULL) {
|
||||
for (int i = mpDrawParticleFuncListNum - 1; i >= 0; i--) {
|
||||
(*mpDrawParticleFuncList[i])(work, node->getObject());
|
||||
(*mpDrawParticleFuncList[i])(work, node->getObject() JPA_DRAW_CTX_ARG);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -858,7 +1123,7 @@ void JPAResource::drawP(JPAEmitterWorkData* work) {
|
||||
work->mpCurNode = node;
|
||||
if (mpDrawParticleFuncList != NULL) {
|
||||
for (int i = mpDrawParticleFuncListNum - 1; i >= 0; i--) {
|
||||
(*mpDrawParticleFuncList[i])(work, node->getObject());
|
||||
(*mpDrawParticleFuncList[i])(work, node->getObject() JPA_DRAW_CTX_ARG);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -905,13 +1170,17 @@ void JPAResource::drawC(JPAEmitterWorkData* work) {
|
||||
(*mpDrawEmitterChildFuncList[i])(work);
|
||||
}
|
||||
|
||||
#if TARGET_PC
|
||||
ParticleDrawCtx ctx{}; // immediate mode
|
||||
#endif
|
||||
|
||||
if (pBsp->isDrawFwdAhead()) {
|
||||
JPANode<JPABaseParticle>* node = work->mpEmtr->mAlivePtclChld.getLast();
|
||||
for (; node != work->mpEmtr->mAlivePtclChld.getEnd(); node = node->getPrev()) {
|
||||
work->mpCurNode = node;
|
||||
if (mpDrawParticleChildFuncList != NULL) {
|
||||
for (int i = mpDrawParticleChildFuncListNum - 1; i >= 0; i--) {
|
||||
(*mpDrawParticleChildFuncList[i])(work, node->getObject());
|
||||
(*mpDrawParticleChildFuncList[i])(work, node->getObject() JPA_DRAW_CTX_ARG);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -921,7 +1190,7 @@ void JPAResource::drawC(JPAEmitterWorkData* work) {
|
||||
work->mpCurNode = node;
|
||||
if (mpDrawParticleChildFuncList != NULL) {
|
||||
for (int i = mpDrawParticleChildFuncListNum - 1; i >= 0; i--) {
|
||||
(*mpDrawParticleChildFuncList[i])(work, node->getObject());
|
||||
(*mpDrawParticleChildFuncList[i])(work, node->getObject() JPA_DRAW_CTX_ARG);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import android.app.ActionBar;
|
||||
import android.app.Activity;
|
||||
import android.content.ActivityNotFoundException;
|
||||
import android.content.ClipData;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.database.Cursor;
|
||||
import android.net.Uri;
|
||||
@@ -14,12 +15,16 @@ import android.provider.DocumentsContract;
|
||||
import android.provider.OpenableColumns;
|
||||
import android.provider.Settings;
|
||||
import android.util.Log;
|
||||
import android.view.Display;
|
||||
import android.view.Surface;
|
||||
import android.view.SurfaceHolder;
|
||||
import android.view.View;
|
||||
import android.view.Window;
|
||||
import android.view.WindowInsets;
|
||||
import android.view.WindowInsetsController;
|
||||
|
||||
import org.libsdl.app.SDLActivity;
|
||||
import org.libsdl.app.SDLSurface;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
@@ -27,6 +32,7 @@ import java.util.List;
|
||||
|
||||
public class DuskActivity extends SDLActivity {
|
||||
private static final String TAG = "DuskActivity";
|
||||
private static final float DEFAULT_SURFACE_FRAME_RATE = 60.0f;
|
||||
private static final int FOLDER_DIALOG_REQUEST_CODE = 0x4455;
|
||||
private static final int MANAGE_STORAGE_REQUEST_CODE = 0x4456;
|
||||
private static final String EXTERNAL_STORAGE_AUTHORITY =
|
||||
@@ -88,6 +94,11 @@ public class DuskActivity extends SDLActivity {
|
||||
hideSystemBars();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected SDLSurface createSDLSurface(Context context) {
|
||||
return new DuskSurface(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResume() {
|
||||
super.onResume();
|
||||
@@ -139,6 +150,77 @@ public class DuskActivity extends SDLActivity {
|
||||
};
|
||||
}
|
||||
|
||||
public void setPreferredSurfaceFrameRate(float frameRate) {
|
||||
runOnUiThread(() -> {
|
||||
if (mSurface instanceof DuskSurface) {
|
||||
((DuskSurface)mSurface).setPreferredFrameRate(frameRate);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static final class DuskSurface extends SDLSurface {
|
||||
private float preferredFrameRate = DEFAULT_SURFACE_FRAME_RATE;
|
||||
|
||||
DuskSurface(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
|
||||
super.surfaceChanged(holder, format, width, height);
|
||||
setTargetFrameRate(holder);
|
||||
}
|
||||
|
||||
void setPreferredFrameRate(float frameRate) {
|
||||
preferredFrameRate = frameRate;
|
||||
setTargetFrameRate(getHolder());
|
||||
}
|
||||
|
||||
private void setTargetFrameRate(SurfaceHolder holder) {
|
||||
if (!mIsSurfaceReady || Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
|
||||
return;
|
||||
}
|
||||
|
||||
Surface surface = holder != null ? holder.getSurface() : getHolder().getSurface();
|
||||
if (surface == null || !surface.isValid()) {
|
||||
return;
|
||||
}
|
||||
|
||||
float targetFrameRate = getMaxSupportedFrameRate();
|
||||
if (preferredFrameRate > 0.0f) {
|
||||
targetFrameRate = preferredFrameRate;
|
||||
}
|
||||
if (targetFrameRate <= 0.0f) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
surface.setFrameRate(
|
||||
targetFrameRate, Surface.FRAME_RATE_COMPATIBILITY_DEFAULT);
|
||||
Log.v(TAG, "Requested surface frame rate " + targetFrameRate + " fps");
|
||||
} catch (RuntimeException e) {
|
||||
Log.w(TAG, "Failed to request surface frame rate", e);
|
||||
}
|
||||
}
|
||||
|
||||
private float getMaxSupportedFrameRate() {
|
||||
if (mDisplay == null) {
|
||||
return 0.0f;
|
||||
}
|
||||
|
||||
float maxFrameRate = mDisplay.getRefreshRate();
|
||||
Display.Mode[] modes = mDisplay.getSupportedModes();
|
||||
if (modes == null) {
|
||||
return maxFrameRate;
|
||||
}
|
||||
|
||||
for (Display.Mode mode : modes) {
|
||||
maxFrameRate = Math.max(maxFrameRate, mode.getRefreshRate());
|
||||
}
|
||||
return maxFrameRate;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String[] getArguments() {
|
||||
Intent intent = getIntent();
|
||||
|
||||
+209
-35
@@ -19,9 +19,13 @@ import android.os.*;
|
||||
|
||||
import java.lang.Runnable;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.UUID;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.regex.Matcher;
|
||||
|
||||
class HIDDeviceBLESteamController extends BluetoothGattCallback implements HIDDevice {
|
||||
|
||||
private static final String TAG = "hidapi";
|
||||
@@ -33,10 +37,19 @@ class HIDDeviceBLESteamController extends BluetoothGattCallback implements HIDDe
|
||||
private boolean mIsConnected = false;
|
||||
private boolean mIsChromebook = false;
|
||||
private boolean mIsReconnecting = false;
|
||||
private boolean mHasEnabledNotifications = false;
|
||||
private boolean mHasSeenInputUpdate = false;
|
||||
private boolean mFrozen = false;
|
||||
private LinkedList<GattOperation> mOperations;
|
||||
GattOperation mCurrentOperation = null;
|
||||
private Handler mHandler;
|
||||
private int mProductId = -1;
|
||||
private int mReportId = 0;
|
||||
private UUID mInputCharacteristic;
|
||||
|
||||
private static final int D0G_BLE2_PID = 0x1106;
|
||||
private static final int TRITON_BLE_PID = 0x1303;
|
||||
|
||||
|
||||
private static final int TRANSPORT_AUTO = 0;
|
||||
private static final int TRANSPORT_BREDR = 1;
|
||||
@@ -45,10 +58,14 @@ class HIDDeviceBLESteamController extends BluetoothGattCallback implements HIDDe
|
||||
private static final int CHROMEBOOK_CONNECTION_CHECK_INTERVAL = 10000;
|
||||
|
||||
static final UUID steamControllerService = UUID.fromString("100F6C32-1735-4313-B402-38567131E5F3");
|
||||
static final UUID inputCharacteristic = UUID.fromString("100F6C33-1735-4313-B402-38567131E5F3");
|
||||
static final UUID inputCharacteristicD0G = UUID.fromString("100F6C33-1735-4313-B402-38567131E5F3");
|
||||
static final UUID inputCharacteristicTriton_0x45 = UUID.fromString("100F6C7A-1735-4313-B402-38567131E5F3");
|
||||
static final UUID inputCharacteristicTriton_0x47 = UUID.fromString("100F6C7C-1735-4313-B402-38567131E5F3");
|
||||
static final UUID reportCharacteristic = UUID.fromString("100F6C34-1735-4313-B402-38567131E5F3");
|
||||
static private final byte[] enterValveMode = new byte[] { (byte)0xC0, (byte)0x87, 0x03, 0x08, 0x07, 0x00 };
|
||||
|
||||
private HashMap<Integer, BluetoothGattCharacteristic> mOutputReportChars = new HashMap<Integer, BluetoothGattCharacteristic>();
|
||||
|
||||
static class GattOperation {
|
||||
private enum Operation {
|
||||
CHR_READ,
|
||||
@@ -61,6 +78,7 @@ class HIDDeviceBLESteamController extends BluetoothGattCallback implements HIDDe
|
||||
byte[] mValue;
|
||||
BluetoothGatt mGatt;
|
||||
boolean mResult = true;
|
||||
int mDelayMs = 0;
|
||||
|
||||
private GattOperation(BluetoothGatt gatt, GattOperation.Operation operation, UUID uuid) {
|
||||
mGatt = gatt;
|
||||
@@ -68,6 +86,13 @@ class HIDDeviceBLESteamController extends BluetoothGattCallback implements HIDDe
|
||||
mUuid = uuid;
|
||||
}
|
||||
|
||||
private GattOperation(BluetoothGatt gatt, GattOperation.Operation operation, UUID uuid, int delayMs) {
|
||||
mGatt = gatt;
|
||||
mOp = operation;
|
||||
mUuid = uuid;
|
||||
mDelayMs = delayMs;
|
||||
}
|
||||
|
||||
private GattOperation(BluetoothGatt gatt, GattOperation.Operation operation, UUID uuid, byte[] value) {
|
||||
mGatt = gatt;
|
||||
mOp = operation;
|
||||
@@ -75,6 +100,14 @@ class HIDDeviceBLESteamController extends BluetoothGattCallback implements HIDDe
|
||||
mValue = value;
|
||||
}
|
||||
|
||||
private GattOperation(BluetoothGatt gatt, GattOperation.Operation operation, UUID uuid, byte[] value, int delayMs) {
|
||||
mGatt = gatt;
|
||||
mOp = operation;
|
||||
mUuid = uuid;
|
||||
mValue = value;
|
||||
mDelayMs = delayMs;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
// This is executed in main thread
|
||||
BluetoothGattCharacteristic chr;
|
||||
@@ -136,6 +169,8 @@ class HIDDeviceBLESteamController extends BluetoothGattCallback implements HIDDe
|
||||
return mResult;
|
||||
}
|
||||
|
||||
public int getDelayMs() { return mDelayMs; }
|
||||
|
||||
private BluetoothGattCharacteristic getCharacteristic(UUID uuid) {
|
||||
BluetoothGattService valveService = mGatt.getService(steamControllerService);
|
||||
if (valveService == null)
|
||||
@@ -154,6 +189,10 @@ class HIDDeviceBLESteamController extends BluetoothGattCallback implements HIDDe
|
||||
static public GattOperation enableNotification(BluetoothGatt gatt, UUID uuid) {
|
||||
return new GattOperation(gatt, Operation.ENABLE_NOTIFICATION, uuid);
|
||||
}
|
||||
|
||||
static public GattOperation enableNotification(BluetoothGatt gatt, UUID uuid, int delayMs) {
|
||||
return new GattOperation(gatt, Operation.ENABLE_NOTIFICATION, uuid, delayMs);
|
||||
}
|
||||
}
|
||||
|
||||
HIDDeviceBLESteamController(HIDDeviceManager manager, BluetoothDevice device) {
|
||||
@@ -166,6 +205,8 @@ class HIDDeviceBLESteamController extends BluetoothGattCallback implements HIDDe
|
||||
mHandler = new Handler(Looper.getMainLooper());
|
||||
|
||||
mGatt = connectGatt();
|
||||
mHasEnabledNotifications = false;
|
||||
mHasSeenInputUpdate = false;
|
||||
// final HIDDeviceBLESteamController finalThis = this;
|
||||
// mHandler.postDelayed(new Runnable() {
|
||||
// @Override
|
||||
@@ -314,8 +355,45 @@ class HIDDeviceBLESteamController extends BluetoothGattCallback implements HIDDe
|
||||
Log.v(TAG, "Found Valve steam controller service " + service.getUuid());
|
||||
|
||||
for (BluetoothGattCharacteristic chr : service.getCharacteristics()) {
|
||||
if (chr.getUuid().equals(inputCharacteristic)) {
|
||||
Log.v(TAG, "Found input characteristic");
|
||||
if (chr.getUuid().equals(inputCharacteristicTriton_0x45)) {
|
||||
Log.v(TAG, "Found Triton input characteristic 0x45");
|
||||
mProductId = TRITON_BLE_PID;
|
||||
mReportId = 0x45;
|
||||
mInputCharacteristic = chr.getUuid();
|
||||
} else if (chr.getUuid().equals(inputCharacteristicTriton_0x47)) {
|
||||
Log.v(TAG, "Found Triton input characteristic 0x47");
|
||||
mProductId = TRITON_BLE_PID;
|
||||
mReportId = 0x47;
|
||||
mInputCharacteristic = chr.getUuid();
|
||||
} else if (chr.getUuid().equals(inputCharacteristicD0G)) {
|
||||
Log.v(TAG, "Found D0G input characteristic");
|
||||
mProductId = D0G_BLE2_PID;
|
||||
mReportId = 0x03;
|
||||
mInputCharacteristic = chr.getUuid();
|
||||
} else {
|
||||
Pattern reportPattern = Pattern.compile("100F6C([0-9A-Z]{2})", Pattern.CASE_INSENSITIVE);
|
||||
Matcher matcher = reportPattern.matcher(chr.getUuid().toString());
|
||||
|
||||
if (matcher.find()) {
|
||||
try {
|
||||
int reportId = Integer.parseInt(matcher.group(1), 16);
|
||||
|
||||
reportId -= 0x35;
|
||||
if (reportId >= 0x80) {
|
||||
// This is a Triton output report characteristic that we need to care about.
|
||||
Log.v(TAG, "Found Triton output report 0x" + Integer.toString(reportId, 16));
|
||||
mOutputReportChars.put(reportId, chr);
|
||||
}
|
||||
}
|
||||
catch (NumberFormatException nfe) {
|
||||
Log.w(TAG, "Could not parse report characteristic " + chr.getUuid().toString() + ": " + nfe.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (BluetoothGattCharacteristic chr : service.getCharacteristics()) {
|
||||
if (chr.getUuid().equals(mInputCharacteristic)) {
|
||||
// Start notifications
|
||||
BluetoothGattDescriptor cccd = chr.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
|
||||
if (cccd != null) {
|
||||
@@ -372,21 +450,30 @@ class HIDDeviceBLESteamController extends BluetoothGattCallback implements HIDDe
|
||||
mCurrentOperation = mOperations.removeFirst();
|
||||
}
|
||||
|
||||
// Run in main thread
|
||||
mHandler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
synchronized (mOperations) {
|
||||
if (mCurrentOperation == null) {
|
||||
Log.e(TAG, "Current operation null in executor?");
|
||||
return;
|
||||
}
|
||||
Runnable gattOperationRunnable = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
synchronized (mOperations) {
|
||||
if (mCurrentOperation == null) {
|
||||
Log.e(TAG, "Current operation null in executor?");
|
||||
return;
|
||||
}
|
||||
|
||||
mCurrentOperation.run();
|
||||
// now wait for the GATT callback and when it comes, finish this operation
|
||||
mCurrentOperation.run();
|
||||
// now wait for the GATT callback and when it comes, finish this operation
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
if (mCurrentOperation.getDelayMs() == 0) {
|
||||
// Run in main thread
|
||||
mHandler.post(gattOperationRunnable);
|
||||
}
|
||||
else {
|
||||
// If we have a delay on this operation, wait before we post it.
|
||||
mHandler.postDelayed(gattOperationRunnable, mCurrentOperation.getDelayMs());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void queueGattOperation(GattOperation op) {
|
||||
@@ -397,8 +484,39 @@ class HIDDeviceBLESteamController extends BluetoothGattCallback implements HIDDe
|
||||
}
|
||||
|
||||
private void enableNotification(UUID chrUuid) {
|
||||
GattOperation op = HIDDeviceBLESteamController.GattOperation.enableNotification(mGatt, chrUuid);
|
||||
// Add a 500ms delay to notification write for Amazon Fire TV devices, as otherwise if we do this too quickly after connecting
|
||||
// it will return success and then silently drop the operation on the floor.
|
||||
GattOperation op = HIDDeviceBLESteamController.GattOperation.enableNotification(mGatt, chrUuid, 500);
|
||||
queueGattOperation(op);
|
||||
|
||||
// Amazon Fire devices can also silently timeout on writeDescriptor, so
|
||||
// set up a little delayed check that will attempt to write a second time.
|
||||
//
|
||||
// While this only seems to be needed on Amazon Fire TV devices at present, it
|
||||
// doesn't hurt to have a retry on other devices as well.
|
||||
//
|
||||
final HIDDeviceBLESteamController finalThis = this;
|
||||
final UUID finalUuid = chrUuid;
|
||||
mHandler.postDelayed(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (!finalThis.mHasEnabledNotifications) {
|
||||
|
||||
if (finalThis.mHasSeenInputUpdate) {
|
||||
// Amazon Five devices may have enabled notifications on the input characteristic and not given us a callback. If we've seen
|
||||
// input reports, though, somewhat by definition notifications are enabled.
|
||||
Log.w(TAG, "WriteDescriptor has never returned, but we've seen input reports. Moving on with controller initialization.");
|
||||
finalThis.mHasEnabledNotifications = true;
|
||||
finalThis.enableValveMode();
|
||||
return;
|
||||
}
|
||||
|
||||
// Give one more try.
|
||||
GattOperation retry = HIDDeviceBLESteamController.GattOperation.enableNotification(finalThis.mGatt, finalUuid, 500);
|
||||
finalThis.queueGattOperation(retry);
|
||||
}
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
void writeCharacteristic(UUID uuid, byte[] value) {
|
||||
@@ -448,8 +566,16 @@ class HIDDeviceBLESteamController extends BluetoothGattCallback implements HIDDe
|
||||
mIsConnected = false;
|
||||
gatt.disconnect();
|
||||
mGatt = connectGatt(false);
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
if (getProductId() == TRITON_BLE_PID) {
|
||||
// Android will not properly play well with Data Length Extensions without manually requesting a large MTU,
|
||||
// and Triton controllers require DLE support.
|
||||
//
|
||||
// 517 is basically a "magic number" as far as Android's bluetooth code is concerned, so do not change
|
||||
// this value. It is functionally "please enable data length extensions" on some Android builds.
|
||||
mGatt.requestMtu(517);
|
||||
}
|
||||
|
||||
probeService(this);
|
||||
}
|
||||
}
|
||||
@@ -474,7 +600,7 @@ class HIDDeviceBLESteamController extends BluetoothGattCallback implements HIDDe
|
||||
// Only register controller with the native side once it has been fully configured
|
||||
if (!isRegistered()) {
|
||||
Log.v(TAG, "Registering Steam Controller with ID: " + getId());
|
||||
mManager.HIDDeviceConnected(getId(), getIdentifier(), getVendorId(), getProductId(), getSerialNumber(), getVersion(), getManufacturerName(), getProductName(), 0, 0, 0, 0, true);
|
||||
mManager.HIDDeviceConnected(getId(), getIdentifier(), getVendorId(), getProductId(), getSerialNumber(), getVersion(), getManufacturerName(), getProductName(), 0, 0, 0, 0, true, mReportId);
|
||||
setRegistered();
|
||||
}
|
||||
}
|
||||
@@ -487,7 +613,8 @@ class HIDDeviceBLESteamController extends BluetoothGattCallback implements HIDDe
|
||||
// Enable this for verbose logging of controller input reports
|
||||
//Log.v(TAG, "onCharacteristicChanged uuid=" + characteristic.getUuid() + " data=" + HexDump.dumpHexString(characteristic.getValue()));
|
||||
|
||||
if (characteristic.getUuid().equals(inputCharacteristic) && !mFrozen) {
|
||||
if (characteristic.getUuid().equals(mInputCharacteristic) && !mFrozen) {
|
||||
mHasSeenInputUpdate = true;
|
||||
mManager.HIDDeviceInputReport(getId(), characteristic.getValue());
|
||||
}
|
||||
}
|
||||
@@ -497,19 +624,36 @@ class HIDDeviceBLESteamController extends BluetoothGattCallback implements HIDDe
|
||||
//Log.v(TAG, "onDescriptorRead status=" + status);
|
||||
}
|
||||
|
||||
private void enableValveMode()
|
||||
{
|
||||
BluetoothGattService valveService = mGatt.getService(steamControllerService);
|
||||
if (valveService == null)
|
||||
return;
|
||||
|
||||
BluetoothGattCharacteristic reportChr = valveService.getCharacteristic(reportCharacteristic);
|
||||
if (reportChr != null) {
|
||||
if (getProductId() == TRITON_BLE_PID) {
|
||||
// For Triton we just mark things registered.
|
||||
Log.v(TAG, "Registering Triton Steam Controller with ID: " + getId());
|
||||
mManager.HIDDeviceConnected(getId(), getIdentifier(), getVendorId(), getProductId(), getSerialNumber(), getVersion(), getManufacturerName(), getProductName(), 0, 0, 0, 0, true, mReportId);
|
||||
setRegistered();
|
||||
} else {
|
||||
// For the original controller, we need to manually enter Valve mode.
|
||||
Log.v(TAG, "Writing report characteristic to enter valve mode");
|
||||
reportChr.setValue(enterValveMode);
|
||||
mGatt.writeCharacteristic(reportChr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
|
||||
BluetoothGattCharacteristic chr = descriptor.getCharacteristic();
|
||||
//Log.v(TAG, "onDescriptorWrite status=" + status + " uuid=" + chr.getUuid() + " descriptor=" + descriptor.getUuid());
|
||||
|
||||
if (chr.getUuid().equals(inputCharacteristic)) {
|
||||
boolean hasWrittenInputDescriptor = true;
|
||||
BluetoothGattCharacteristic reportChr = chr.getService().getCharacteristic(reportCharacteristic);
|
||||
if (reportChr != null) {
|
||||
Log.v(TAG, "Writing report characteristic to enter valve mode");
|
||||
reportChr.setValue(enterValveMode);
|
||||
gatt.writeCharacteristic(reportChr);
|
||||
}
|
||||
if (chr.getUuid().equals(mInputCharacteristic)) {
|
||||
mHasEnabledNotifications = true;
|
||||
enableValveMode();
|
||||
}
|
||||
|
||||
finishCurrentGattOperation();
|
||||
@@ -548,9 +692,20 @@ class HIDDeviceBLESteamController extends BluetoothGattCallback implements HIDDe
|
||||
|
||||
@Override
|
||||
public int getProductId() {
|
||||
// We don't have an easy way to query from the Bluetooth device, but we know what it is
|
||||
final int D0G_BLE2_PID = 0x1106;
|
||||
return D0G_BLE2_PID;
|
||||
if (mProductId > 0) {
|
||||
// We've already set a product ID.
|
||||
return mProductId;
|
||||
}
|
||||
|
||||
if (mDevice.getName().startsWith("Steam Ctrl")) {
|
||||
// We're a newer Triton device
|
||||
mProductId = TRITON_BLE_PID;
|
||||
} else {
|
||||
// We're an OG Steam Controller
|
||||
mProductId = D0G_BLE2_PID;
|
||||
}
|
||||
|
||||
return mProductId;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -601,10 +756,29 @@ class HIDDeviceBLESteamController extends BluetoothGattCallback implements HIDDe
|
||||
writeCharacteristic(reportCharacteristic, actual_report);
|
||||
return report.length;
|
||||
} else {
|
||||
//Log.v(TAG, "writeOutputReport " + HexDump.dumpHexString(report));
|
||||
writeCharacteristic(reportCharacteristic, report);
|
||||
return report.length;
|
||||
// If we're an original-recipe Steam Controller we just write to the characteristic directly.
|
||||
if (getProductId() == D0G_BLE2_PID) {
|
||||
//Log.v(TAG, "writeOutputReport " + HexDump.dumpHexString(report));
|
||||
writeCharacteristic(reportCharacteristic, report);
|
||||
return report.length;
|
||||
}
|
||||
|
||||
// If we're a Triton, we need to find the correct report characteristic.
|
||||
if (report.length > 0) {
|
||||
int reportId = report[0] & 0xFF;
|
||||
BluetoothGattCharacteristic targetedReportCharacteristic = mOutputReportChars.get(reportId);
|
||||
if (targetedReportCharacteristic != null) {
|
||||
byte[] actual_report = Arrays.copyOfRange(report, 1, report.length - 1);
|
||||
//Log.v(TAG, "writeOutputReport 0x" + Integer.toString(reportId, 16) + " " + HexDump.dumpHexString(report));
|
||||
writeCharacteristic(targetedReportCharacteristic.getUuid(), actual_report);
|
||||
return report.length;
|
||||
} else {
|
||||
Log.w(TAG, "Got report write request for unknown report type 0x" + Integer.toString(reportId, 16));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -256,6 +256,7 @@ public class HIDDeviceManager {
|
||||
0x24c6, // PowerA
|
||||
0x2c22, // Qanba
|
||||
0x2dc8, // 8BitDo
|
||||
0x3537, // GameSir
|
||||
0x37d7, // Flydigi
|
||||
0x9886, // ASTRO Gaming
|
||||
};
|
||||
@@ -360,7 +361,7 @@ public class HIDDeviceManager {
|
||||
HIDDeviceUSB device = new HIDDeviceUSB(this, usbDevice, interface_index);
|
||||
int id = device.getId();
|
||||
mDevicesById.put(id, device);
|
||||
HIDDeviceConnected(id, device.getIdentifier(), device.getVendorId(), device.getProductId(), device.getSerialNumber(), device.getVersion(), device.getManufacturerName(), device.getProductName(), usbInterface.getId(), usbInterface.getInterfaceClass(), usbInterface.getInterfaceSubclass(), usbInterface.getInterfaceProtocol(), false);
|
||||
HIDDeviceConnected(id, device.getIdentifier(), device.getVendorId(), device.getProductId(), device.getSerialNumber(), device.getVersion(), device.getManufacturerName(), device.getProductName(), usbInterface.getId(), usbInterface.getInterfaceClass(), usbInterface.getInterfaceSubclass(), usbInterface.getInterfaceProtocol(), false, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -529,7 +530,13 @@ public class HIDDeviceManager {
|
||||
return false;
|
||||
}
|
||||
|
||||
return bluetoothDevice.getName().equals("SteamController") && ((bluetoothDevice.getType() & BluetoothDevice.DEVICE_TYPE_LE) != 0);
|
||||
// Steam Controllers will always support Bluetooth Low Energy
|
||||
if ((bluetoothDevice.getType() & BluetoothDevice.DEVICE_TYPE_LE) == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Match on the name either the original Steam Controller or the new second-generation one advertise with.
|
||||
return bluetoothDevice.getName().equals("SteamController") || bluetoothDevice.getName().startsWith("Steam Ctrl");
|
||||
}
|
||||
|
||||
private void close() {
|
||||
@@ -681,7 +688,7 @@ public class HIDDeviceManager {
|
||||
private native void HIDDeviceRegisterCallback();
|
||||
private native void HIDDeviceReleaseCallback();
|
||||
|
||||
native void HIDDeviceConnected(int deviceID, String identifier, int vendorId, int productId, String serial_number, int release_number, String manufacturer_string, String product_string, int interface_number, int interface_class, int interface_subclass, int interface_protocol, boolean bBluetooth);
|
||||
native void HIDDeviceConnected(int deviceID, String identifier, int vendorId, int productId, String serial_number, int release_number, String manufacturer_string, String product_string, int interface_number, int interface_class, int interface_subclass, int interface_protocol, boolean bBluetooth, int reportID);
|
||||
native void HIDDeviceOpenPending(int deviceID);
|
||||
native void HIDDeviceOpenResult(int deviceID, boolean opened);
|
||||
native void HIDDeviceDisconnected(int deviceID);
|
||||
|
||||
@@ -21,6 +21,7 @@ class HIDDeviceUSB implements HIDDevice {
|
||||
protected InputThread mInputThread;
|
||||
protected boolean mRunning;
|
||||
protected boolean mFrozen;
|
||||
protected boolean mClaimed;
|
||||
|
||||
public HIDDeviceUSB(HIDDeviceManager manager, UsbDevice usbDevice, int interface_index) {
|
||||
mManager = manager;
|
||||
@@ -29,6 +30,7 @@ class HIDDeviceUSB implements HIDDevice {
|
||||
mInterface = mDevice.getInterface(mInterfaceIndex).getId();
|
||||
mDeviceId = manager.getDeviceIDForIdentifier(getIdentifier());
|
||||
mRunning = false;
|
||||
mClaimed = false;
|
||||
}
|
||||
|
||||
String getIdentifier() {
|
||||
@@ -114,6 +116,7 @@ class HIDDeviceUSB implements HIDDevice {
|
||||
close();
|
||||
return false;
|
||||
}
|
||||
mClaimed = true;
|
||||
|
||||
// Find the endpoints
|
||||
for (int j = 0; j < iface.getEndpointCount(); j++) {
|
||||
@@ -132,9 +135,12 @@ class HIDDeviceUSB implements HIDDevice {
|
||||
}
|
||||
}
|
||||
|
||||
// Make sure the required endpoints were present
|
||||
if (mInputEndpoint == null || mOutputEndpoint == null) {
|
||||
// Make sure the required endpoints were present. The original Steam Controller and the wireless dongle for it do NOT
|
||||
// actually have -- or require -- output endpoints, so we need to accept only an input one for them or else we'll fall
|
||||
// back to the Android system gamepad functionality (and lose our paddles et al).
|
||||
if (mInputEndpoint == null) {
|
||||
Log.w(TAG, "Missing required endpoint on USB device " + getDeviceName());
|
||||
mConnection.releaseInterface(iface);
|
||||
close();
|
||||
return false;
|
||||
}
|
||||
@@ -154,6 +160,11 @@ class HIDDeviceUSB implements HIDDevice {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (!mClaimed) {
|
||||
Log.w(TAG, "writeReport() called but some other process currently owns the USB device");
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (feature) {
|
||||
int res = -1;
|
||||
int offset = 0;
|
||||
@@ -185,6 +196,11 @@ class HIDDeviceUSB implements HIDDevice {
|
||||
}
|
||||
return length;
|
||||
} else {
|
||||
if (mOutputEndpoint == null)
|
||||
{
|
||||
Log.e(TAG, "Tried to write an output report to an interface with no output endpoint!");
|
||||
return -1;
|
||||
}
|
||||
int res = mConnection.bulkTransfer(mOutputEndpoint, report, report.length, 1000);
|
||||
if (res != report.length) {
|
||||
Log.w(TAG, "writeOutputReport() returned " + res + " on device " + getDeviceName());
|
||||
@@ -205,6 +221,12 @@ class HIDDeviceUSB implements HIDDevice {
|
||||
Log.w(TAG, "readReport() called with no device connection");
|
||||
return false;
|
||||
}
|
||||
if (!mClaimed) {
|
||||
if (feature) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (report_number == 0x0) {
|
||||
/* Offset the return buffer by 1, so that the report ID
|
||||
@@ -258,10 +280,13 @@ class HIDDeviceUSB implements HIDDevice {
|
||||
mInputThread = null;
|
||||
}
|
||||
if (mConnection != null) {
|
||||
UsbInterface iface = mDevice.getInterface(mInterfaceIndex);
|
||||
mConnection.releaseInterface(iface);
|
||||
if (mClaimed) {
|
||||
UsbInterface iface = mDevice.getInterface(mInterfaceIndex);
|
||||
mConnection.releaseInterface(iface);
|
||||
}
|
||||
mConnection.close();
|
||||
mConnection = null;
|
||||
mClaimed = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -274,6 +299,22 @@ class HIDDeviceUSB implements HIDDevice {
|
||||
@Override
|
||||
public void setFrozen(boolean frozen) {
|
||||
mFrozen = frozen;
|
||||
|
||||
/* If we have a valid device connection and the claim state doesn't match what we want, try to correct that. */
|
||||
if (mConnection != null && mClaimed == mFrozen) {
|
||||
UsbInterface iface = mDevice.getInterface(mInterfaceIndex);
|
||||
if (frozen) {
|
||||
mClaimed = !mConnection.releaseInterface(iface);
|
||||
if (mClaimed) {
|
||||
Log.e(TAG, "Tried to release claim on USB device, but failed!");
|
||||
}
|
||||
} else {
|
||||
mClaimed = mConnection.claimInterface(iface, true);
|
||||
if (!mClaimed) {
|
||||
Log.e(TAG, "Tried to regain claim on USB device, but failed!");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected class InputThread extends Thread {
|
||||
|
||||
@@ -61,7 +61,7 @@ public class SDLActivity extends Activity implements View.OnSystemUiVisibilityCh
|
||||
private static final String TAG = "SDL";
|
||||
private static final int SDL_MAJOR_VERSION = 3;
|
||||
private static final int SDL_MINOR_VERSION = 4;
|
||||
private static final int SDL_MICRO_VERSION = 8;
|
||||
private static final int SDL_MICRO_VERSION = 10;
|
||||
/*
|
||||
// Display InputType.SOURCE/CLASS of events and devices
|
||||
//
|
||||
@@ -530,7 +530,8 @@ public class SDLActivity extends Activity implements View.OnSystemUiVisibilityCh
|
||||
|
||||
if (mHIDDeviceManager != null) {
|
||||
mHIDDeviceManager.setFrozen(true);
|
||||
}
|
||||
}
|
||||
|
||||
if (!mHasMultiWindow) {
|
||||
pauseNativeThread();
|
||||
}
|
||||
@@ -543,7 +544,8 @@ public class SDLActivity extends Activity implements View.OnSystemUiVisibilityCh
|
||||
|
||||
if (mHIDDeviceManager != null) {
|
||||
mHIDDeviceManager.setFrozen(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (!mHasMultiWindow) {
|
||||
resumeNativeThread();
|
||||
}
|
||||
@@ -616,6 +618,14 @@ public class SDLActivity extends Activity implements View.OnSystemUiVisibilityCh
|
||||
super.onWindowFocusChanged(hasFocus);
|
||||
Log.v(TAG, "onWindowFocusChanged(): " + hasFocus);
|
||||
|
||||
// If we are gaining focus, we can always try to restore our USB devices. If we are losing focus,
|
||||
// only try to relinquish them if we don't have background events allowed (for multi-window Android setups).
|
||||
if (hasFocus || !SDLActivity.nativeGetHintBoolean("SDL_JOYSTICK_ALLOW_BACKGROUND_EVENTS", false)) {
|
||||
if (mHIDDeviceManager != null) {
|
||||
mHIDDeviceManager.setFrozen(!hasFocus);
|
||||
}
|
||||
}
|
||||
|
||||
if (SDLActivity.mBrokenLibraries) {
|
||||
return;
|
||||
}
|
||||
@@ -1481,11 +1491,11 @@ public class SDLActivity extends Activity implements View.OnSystemUiVisibilityCh
|
||||
if (SDLControllerManager.isDeviceSDLJoystick(deviceId)) {
|
||||
// Note that we process events with specific key codes here
|
||||
if (event.getAction() == KeyEvent.ACTION_DOWN) {
|
||||
if (SDLControllerManager.onNativePadDown(deviceId, keyCode)) {
|
||||
if (SDLControllerManager.onNativePadDown(deviceId, keyCode, event.getScanCode())) {
|
||||
return true;
|
||||
}
|
||||
} else if (event.getAction() == KeyEvent.ACTION_UP) {
|
||||
if (SDLControllerManager.onNativePadUp(deviceId, keyCode)) {
|
||||
if (SDLControllerManager.onNativePadUp(deviceId, keyCode, event.getScanCode())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1963,7 +1973,7 @@ public class SDLActivity extends Activity implements View.OnSystemUiVisibilityCh
|
||||
Intent i = new Intent(Intent.ACTION_VIEW);
|
||||
i.setData(Uri.parse(url));
|
||||
|
||||
int flags = Intent.FLAG_ACTIVITY_NO_HISTORY
|
||||
int flags = Intent.FLAG_ACTIVITY_NO_HISTORY
|
||||
| Intent.FLAG_ACTIVITY_MULTIPLE_TASK
|
||||
| Intent.FLAG_ACTIVITY_NEW_DOCUMENT;
|
||||
i.addFlags(flags);
|
||||
@@ -2227,3 +2237,4 @@ class SDLClipboardHandler implements
|
||||
SDLActivity.onNativeClipboardChanged();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,10 @@ import android.hardware.lights.Light;
|
||||
import android.hardware.lights.LightsRequest;
|
||||
import android.hardware.lights.LightsManager;
|
||||
import android.hardware.lights.LightState;
|
||||
import android.hardware.Sensor;
|
||||
import android.hardware.SensorEvent;
|
||||
import android.hardware.SensorEventListener;
|
||||
import android.hardware.SensorManager;
|
||||
import android.graphics.Color;
|
||||
import android.os.Build;
|
||||
import android.os.VibrationEffect;
|
||||
@@ -30,16 +34,18 @@ public class SDLControllerManager
|
||||
static native void nativeAddJoystick(int device_id, String name, String desc,
|
||||
int vendor_id, int product_id,
|
||||
int button_mask,
|
||||
int naxes, int axis_mask, int nhats, boolean can_rumble, boolean has_rgb_led);
|
||||
int naxes, int axis_mask, int nhats, boolean can_rumble, boolean has_rgb_led,
|
||||
boolean has_accelerometer, boolean has_gyroscope);
|
||||
static native void nativeRemoveJoystick(int device_id);
|
||||
static native void nativeAddHaptic(int device_id, String name);
|
||||
static native void nativeRemoveHaptic(int device_id);
|
||||
static public native boolean onNativePadDown(int device_id, int keycode);
|
||||
static public native boolean onNativePadUp(int device_id, int keycode);
|
||||
static public native boolean onNativePadDown(int device_id, int keycode, int scancode);
|
||||
static public native boolean onNativePadUp(int device_id, int keycode, int scancode);
|
||||
static native void onNativeJoy(int device_id, int axis,
|
||||
float value);
|
||||
static native void onNativeHat(int device_id, int hat_id,
|
||||
int x, int y);
|
||||
static native void onNativeJoySensor(int device_id, int sensor_type, long sensor_timestamp, float x, float y, float z);
|
||||
|
||||
protected static SDLJoystickHandler mJoystickHandler;
|
||||
protected static SDLHapticHandler mHapticHandler;
|
||||
@@ -81,6 +87,13 @@ public class SDLControllerManager
|
||||
mJoystickHandler.setLED(device_id, red, green, blue);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is called by SDL using JNI.
|
||||
*/
|
||||
static void joystickSetSensorsEnabled(int device_id, boolean enabled) {
|
||||
mJoystickHandler.setSensorsEnabled(device_id, enabled);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is called by SDL using JNI.
|
||||
*/
|
||||
@@ -153,6 +166,10 @@ class SDLJoystickHandler {
|
||||
ArrayList<InputDevice.MotionRange> hats;
|
||||
ArrayList<Light> lights;
|
||||
LightsManager.LightsSession lightsSession;
|
||||
SensorManager sensorManager;
|
||||
SDLJoySensorListener sensorListener;
|
||||
Sensor accelerometerSensor;
|
||||
Sensor gyroscopeSensor;
|
||||
}
|
||||
static class RangeComparator implements Comparator<InputDevice.MotionRange> {
|
||||
@Override
|
||||
@@ -225,12 +242,13 @@ class SDLJoystickHandler {
|
||||
joystick.desc = getJoystickDescriptor(joystickDevice);
|
||||
joystick.axes = new ArrayList<InputDevice.MotionRange>();
|
||||
joystick.hats = new ArrayList<InputDevice.MotionRange>();
|
||||
java.util.Set<Integer> axisStrsSet = new java.util.HashSet<Integer>();
|
||||
joystick.lights = new ArrayList<Light>();
|
||||
|
||||
List<InputDevice.MotionRange> ranges = joystickDevice.getMotionRanges();
|
||||
Collections.sort(ranges, new RangeComparator());
|
||||
for (InputDevice.MotionRange range : ranges) {
|
||||
if ((range.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
|
||||
if (((range.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) && axisStrsSet.add(range.getAxis())) {
|
||||
if (range.getAxis() == MotionEvent.AXIS_HAT_X || range.getAxis() == MotionEvent.AXIS_HAT_Y) {
|
||||
joystick.hats.add(range);
|
||||
} else {
|
||||
@@ -241,6 +259,8 @@ class SDLJoystickHandler {
|
||||
|
||||
boolean can_rumble = false;
|
||||
boolean has_rgb_led = false;
|
||||
boolean has_accelerometer = false;
|
||||
boolean has_gyroscope = false;
|
||||
if (Build.VERSION.SDK_INT >= 31 /* Android 12.0 (S) */) {
|
||||
VibratorManager vibratorManager = joystickDevice.getVibratorManager();
|
||||
int[] vibrators = vibratorManager.getVibratorIds();
|
||||
@@ -258,12 +278,26 @@ class SDLJoystickHandler {
|
||||
joystick.lightsSession = lightsManager.openSession();
|
||||
has_rgb_led = true;
|
||||
}
|
||||
SensorManager sensorManager = joystickDevice.getSensorManager();
|
||||
if (sensorManager != null) {
|
||||
joystick.sensorManager = sensorManager;
|
||||
joystick.sensorListener = new SDLJoySensorListener(joystick.device_id);
|
||||
joystick.accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
|
||||
if (joystick.accelerometerSensor != null) {
|
||||
has_accelerometer = true;
|
||||
}
|
||||
joystick.gyroscopeSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
|
||||
if (joystick.gyroscopeSensor != null) {
|
||||
has_gyroscope = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mJoysticks.add(joystick);
|
||||
SDLControllerManager.nativeAddJoystick(joystick.device_id, joystick.name, joystick.desc,
|
||||
getVendorId(joystickDevice), getProductId(joystickDevice),
|
||||
getButtonMask(joystickDevice), joystick.axes.size(), getAxisMask(joystick.axes), joystick.hats.size()/2, can_rumble, has_rgb_led);
|
||||
getButtonMask(joystickDevice), joystick.axes.size(), getAxisMask(joystick.axes), joystick.hats.size()/2, can_rumble, has_rgb_led,
|
||||
has_accelerometer, has_gyroscope);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -508,6 +542,31 @@ class SDLJoystickHandler {
|
||||
}
|
||||
joystick.lightsSession.requestLights(lightsRequest.build());
|
||||
}
|
||||
|
||||
void setSensorsEnabled(int device_id, boolean enabled) {
|
||||
if (Build.VERSION.SDK_INT < 31 /* Android 12.0 (S) */) {
|
||||
return;
|
||||
}
|
||||
SDLJoystick joystick = getJoystick(device_id);
|
||||
if (joystick == null || joystick.sensorManager == null) {
|
||||
return;
|
||||
}
|
||||
if (enabled) {
|
||||
if (joystick.accelerometerSensor != null) {
|
||||
SDLSensorManager.registerListener(joystick.sensorManager, joystick.sensorListener, joystick.accelerometerSensor, SensorManager.SENSOR_DELAY_GAME);
|
||||
}
|
||||
if (joystick.gyroscopeSensor != null) {
|
||||
SDLSensorManager.registerListener(joystick.sensorManager, joystick.sensorListener, joystick.gyroscopeSensor, SensorManager.SENSOR_DELAY_GAME);
|
||||
}
|
||||
} else {
|
||||
if (joystick.accelerometerSensor != null) {
|
||||
SDLSensorManager.unregisterListener(joystick.sensorManager, joystick.sensorListener, joystick.accelerometerSensor);
|
||||
}
|
||||
if (joystick.gyroscopeSensor != null) {
|
||||
SDLSensorManager.unregisterListener(joystick.sensorManager, joystick.sensorListener, joystick.gyroscopeSensor);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class SDLHapticHandler_API31 extends SDLHapticHandler {
|
||||
@@ -933,3 +992,19 @@ class SDLGenericMotionListener_API29 extends SDLGenericMotionListener_API26 {
|
||||
return penDevice.isExternal() ? SDL_PEN_DEVICE_TYPE_INDIRECT : SDL_PEN_DEVICE_TYPE_DIRECT;
|
||||
}
|
||||
}
|
||||
|
||||
class SDLJoySensorListener implements SensorEventListener {
|
||||
int device_id;
|
||||
|
||||
public SDLJoySensorListener(int device_id) {
|
||||
this.device_id = device_id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
|
||||
|
||||
@Override
|
||||
public void onSensorChanged(SensorEvent event) {
|
||||
SDLControllerManager.onNativeJoySensor(device_id, event.sensor.getType(), event.timestamp, event.values[0], event.values[1], event.values[2]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package org.libsdl.app;
|
||||
|
||||
import android.hardware.Sensor;
|
||||
import android.hardware.SensorEventListener;
|
||||
import android.hardware.SensorManager;
|
||||
|
||||
// This class coordinates synchronized access to sensor manager registration
|
||||
//
|
||||
// This prevents a java.util.ConcurrentModificationException exception on
|
||||
// Android 16, specifically on the Samsung Tab S9 Ultra.
|
||||
|
||||
class SDLSensorManager
|
||||
{
|
||||
static private SDLSensorManager mManager = new SDLSensorManager();
|
||||
|
||||
public static void registerListener(SensorManager manager, SensorEventListener listener, Sensor sensor, int samplingPeriodUs) {
|
||||
mManager.RegisterListener(manager, listener, sensor, samplingPeriodUs);
|
||||
}
|
||||
|
||||
public static void unregisterListener(SensorManager manager, SensorEventListener listener, Sensor sensor) {
|
||||
mManager.UnregisterListener(manager, listener, sensor);
|
||||
}
|
||||
|
||||
private synchronized void RegisterListener(SensorManager manager, SensorEventListener listener, Sensor sensor, int samplingPeriodUs) {
|
||||
manager.registerListener(listener, sensor, samplingPeriodUs, null);
|
||||
}
|
||||
|
||||
private synchronized void UnregisterListener(SensorManager manager, SensorEventListener listener, Sensor sensor) {
|
||||
manager.unregisterListener(listener, sensor);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,6 +47,9 @@ public class SDLSurface extends SurfaceView implements SurfaceHolder.Callback,
|
||||
// Is SurfaceView ready for rendering
|
||||
protected boolean mIsSurfaceReady;
|
||||
|
||||
// Is on-screen keyboard visible
|
||||
protected boolean mKeyboardVisible;
|
||||
|
||||
// Pinch events
|
||||
private final ScaleGestureDetector scaleGestureDetector;
|
||||
|
||||
@@ -213,6 +216,18 @@ public class SDLSurface extends SurfaceView implements SurfaceHolder.Callback,
|
||||
WindowInsets.Type.displayCutout());
|
||||
|
||||
SDLActivity.onNativeInsetsChanged(combined.left, combined.right, combined.top, combined.bottom);
|
||||
|
||||
if (insets.isVisible(WindowInsets.Type.ime())) {
|
||||
if (!mKeyboardVisible) {
|
||||
mKeyboardVisible = true;
|
||||
SDLActivity.onNativeScreenKeyboardShown();
|
||||
}
|
||||
} else {
|
||||
if (mKeyboardVisible) {
|
||||
mKeyboardVisible = false;
|
||||
SDLActivity.onNativeScreenKeyboardHidden();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Pass these to any child views in case they need them
|
||||
@@ -318,11 +333,11 @@ public class SDLSurface extends SurfaceView implements SurfaceHolder.Callback,
|
||||
protected void enableSensor(int sensortype, boolean enabled) {
|
||||
// TODO: This uses getDefaultSensor - what if we have >1 accels?
|
||||
if (enabled) {
|
||||
mSensorManager.registerListener(this,
|
||||
SDLSensorManager.registerListener(mSensorManager, this,
|
||||
mSensorManager.getDefaultSensor(sensortype),
|
||||
SensorManager.SENSOR_DELAY_GAME, null);
|
||||
SensorManager.SENSOR_DELAY_GAME);
|
||||
} else {
|
||||
mSensorManager.unregisterListener(this,
|
||||
SDLSensorManager.unregisterListener(mSensorManager, this,
|
||||
mSensorManager.getDefaultSensor(sensortype));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.cs.disable-library-validation</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,97 @@
|
||||
window.logs content {
|
||||
flex-flow: column;
|
||||
}
|
||||
|
||||
window.logs .log-toolbar {
|
||||
display: flex;
|
||||
flex-flow: row;
|
||||
flex: 0 0 64dp;
|
||||
height: 64dp;
|
||||
align-items: center;
|
||||
gap: 8dp;
|
||||
padding-right: 72dp;
|
||||
background-color: rgba(217, 217, 217, 10%);
|
||||
border-bottom: 2dp #92875B;
|
||||
font-family: "Fira Sans Condensed";
|
||||
font-weight: bold;
|
||||
font-size: 18dp;
|
||||
}
|
||||
|
||||
window.logs > close {
|
||||
top: 8dp;
|
||||
right: 8dp;
|
||||
}
|
||||
|
||||
window.logs .log-title {
|
||||
align-self: stretch;
|
||||
flex: 0 0 auto;
|
||||
padding: 0 24dp;
|
||||
line-height: 64dp;
|
||||
text-transform: uppercase;
|
||||
border-bottom: 4dp #C2A42D;
|
||||
font-effect: glow(0dp 4dp 0dp 4dp black);
|
||||
}
|
||||
|
||||
window.logs .log-title-mod {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
font-family: "Fira Sans";
|
||||
font-weight: normal;
|
||||
font-size: 15dp;
|
||||
color: rgba(224, 219, 200, 55%);
|
||||
}
|
||||
|
||||
.log-toolbar-spacer {
|
||||
flex: 1 1 0;
|
||||
}
|
||||
|
||||
.log-toolbar button {
|
||||
flex: 0 0 auto;
|
||||
font-family: "Fira Sans";
|
||||
font-weight: normal;
|
||||
font-size: 15dp;
|
||||
padding: 5dp 12dp;
|
||||
}
|
||||
|
||||
window.logs content pane.log-view {
|
||||
flex: 1 1 0;
|
||||
padding: 12dp 16dp;
|
||||
padding-bottom: 0dp;
|
||||
gap: 0dp;
|
||||
}
|
||||
|
||||
.log-lines {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.log-line {
|
||||
display: block;
|
||||
font-family: "Noto Mono";
|
||||
font-size: 13dp;
|
||||
line-height: 1.5;
|
||||
word-break: break-word;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.log-line .log-time {
|
||||
color: rgba(224, 219, 200, 45%);
|
||||
}
|
||||
|
||||
.log-line .log-mod {
|
||||
color: rgba(194, 164, 45, 80%);
|
||||
}
|
||||
|
||||
.log-line.lvl-trace,
|
||||
.log-line.lvl-debug {
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
.log-line.lvl-warn .log-msg {
|
||||
color: #ffa826;
|
||||
}
|
||||
|
||||
.log-line.lvl-error .log-msg {
|
||||
color: #cc4444;
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
window.mods content pane.mod-list {
|
||||
flex: 0 0 360dp;
|
||||
padding: 16dp;
|
||||
padding-bottom: 0dp;
|
||||
gap: 4dp;
|
||||
}
|
||||
|
||||
@media (max-height: 640dp) {
|
||||
window.mods content pane.mod-list {
|
||||
flex: 1 1 0;
|
||||
}
|
||||
}
|
||||
|
||||
window.mods content pane.mod-detail {
|
||||
gap: 12dp;
|
||||
}
|
||||
|
||||
.mod-info-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12dp;
|
||||
padding: 4dp 0;
|
||||
}
|
||||
|
||||
.mod-info-label {
|
||||
font-family: "Fira Sans Condensed";
|
||||
font-weight: bold;
|
||||
opacity: 0.55;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.mod-info-value {
|
||||
flex: 1 1 0;
|
||||
}
|
||||
|
||||
.mod-path {
|
||||
font-size: 14dp;
|
||||
word-break: break-all;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
mod-entry {
|
||||
display: flex;
|
||||
flex-flow: row;
|
||||
gap: 12dp;
|
||||
padding: 10dp;
|
||||
border-radius: 10dp;
|
||||
decorator: vertical-gradient(#c2a42d00 #c2a42d00);
|
||||
transition: decorator 0.1s linear-in-out;
|
||||
cursor: pointer;
|
||||
focus: auto;
|
||||
}
|
||||
|
||||
mod-entry.current {
|
||||
box-shadow: rgba(146, 135, 91, 40%) 0 0 0 1dp;
|
||||
}
|
||||
|
||||
mod-entry:hover,
|
||||
mod-entry:focus-visible {
|
||||
decorator: vertical-gradient(#c2a42d00 #c2a42d26);
|
||||
}
|
||||
|
||||
mod-entry:selected {
|
||||
decorator: vertical-gradient(#c2a42d10 #c2a42d40);
|
||||
}
|
||||
|
||||
mod-entry .mod-icon {
|
||||
flex: 0 0 auto;
|
||||
width: 56dp;
|
||||
height: 56dp;
|
||||
border-radius: 8dp;
|
||||
}
|
||||
|
||||
mod-entry icon.mod-icon {
|
||||
font-size: 36dp;
|
||||
background-color: rgba(17, 16, 10, 20%);
|
||||
color: rgba(224, 219, 200, 45%);
|
||||
decorator: text("" center center);
|
||||
}
|
||||
|
||||
mod-entry .mod-entry-info {
|
||||
display: flex;
|
||||
flex-flow: column;
|
||||
flex: 1 1 0;
|
||||
min-width: 0;
|
||||
gap: 2dp;
|
||||
}
|
||||
|
||||
mod-entry .mod-entry-name {
|
||||
display: flex;
|
||||
flex-flow: row;
|
||||
align-items: baseline;
|
||||
gap: 6dp;
|
||||
}
|
||||
|
||||
mod-entry .mod-entry-name-text {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
font-weight: bold;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
mod-entry .mod-entry-version {
|
||||
flex: 0 0 auto;
|
||||
font-size: 13dp;
|
||||
color: rgba(224, 219, 200, 50%);
|
||||
}
|
||||
|
||||
mod-entry .mod-entry-status.active {
|
||||
color: #44cc55;
|
||||
}
|
||||
|
||||
mod-entry .mod-entry-status.failed {
|
||||
color: #cc4444;
|
||||
}
|
||||
|
||||
mod-entry .mod-entry-desc {
|
||||
font-size: 14dp;
|
||||
line-height: 1.3;
|
||||
color: rgba(224, 219, 200, 65%);
|
||||
max-height: 2.6em;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
mod-entry .mod-entry-sub {
|
||||
font-size: 13dp;
|
||||
color: rgba(224, 219, 200, 50%);
|
||||
}
|
||||
|
||||
mod-entry.inactive .mod-icon {
|
||||
filter: grayscale(1);
|
||||
}
|
||||
|
||||
mod-entry.inactive .mod-entry-info {
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
mod-header {
|
||||
position: relative;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
mod-header.has-banner {
|
||||
height: 180dp;
|
||||
margin: -24dp -24dp 0dp -24dp;
|
||||
}
|
||||
|
||||
mod-header .mod-actions {
|
||||
position: absolute;
|
||||
top: 24dp;
|
||||
left: 24dp;
|
||||
display: flex;
|
||||
flex-flow: row;
|
||||
gap: 8dp;
|
||||
}
|
||||
|
||||
mod-header .mod-actions button {
|
||||
font-size: 16dp;
|
||||
padding: 6dp 14dp;
|
||||
background-color: rgba(21, 22, 16, 80%);
|
||||
box-shadow: rgba(146, 135, 91, 60%) 0 0 0 1dp;
|
||||
}
|
||||
|
||||
mod-header.no-banner {
|
||||
display: flex;
|
||||
flex-flow: row;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
mod-header.no-banner .mod-actions {
|
||||
position: static;
|
||||
}
|
||||
|
||||
window.mods .mod-title {
|
||||
display: block;
|
||||
font-size: 28dp;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
window.mods .mod-title .mod-title-version {
|
||||
font-weight: normal;
|
||||
font-size: 16dp;
|
||||
color: rgba(224, 219, 200, 55%);
|
||||
}
|
||||
|
||||
window.mods .mod-author {
|
||||
display: block;
|
||||
font-size: 15dp;
|
||||
color: rgba(224, 219, 200, 55%);
|
||||
}
|
||||
|
||||
window.mods .mod-restart-note {
|
||||
font-size: 15dp;
|
||||
color: #ffa826;
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
window.mods .mod-description {
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.status-badge {
|
||||
font-size: 14dp;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.status-badge.active,
|
||||
.mod-info-label.active {
|
||||
color: #44cc55;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.status-badge.failed,
|
||||
.mod-info-label.failed {
|
||||
color: #cc4444;
|
||||
opacity: 1;
|
||||
}
|
||||
+61
-3
@@ -16,11 +16,12 @@ body {
|
||||
flex-direction: column;
|
||||
justify-content: flex-end;
|
||||
align-items: stretch;
|
||||
z-index: 1;
|
||||
z-index: 2;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
fps,
|
||||
pipeline-progress,
|
||||
toast {
|
||||
position: absolute;
|
||||
border: 1dp #92875B;
|
||||
@@ -98,7 +99,7 @@ toast message row.muted {
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
toast progress {
|
||||
progress {
|
||||
height: 4dp;
|
||||
position: absolute;
|
||||
left: 0;
|
||||
@@ -106,10 +107,50 @@ toast progress {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
toast progress fill {
|
||||
progress fill {
|
||||
background-color: rgba(194, 164, 45, 80%);
|
||||
}
|
||||
|
||||
pipeline-progress {
|
||||
left: 12dp;
|
||||
bottom: 12dp;
|
||||
display: flex;
|
||||
flex-flow: column;
|
||||
z-index: 100;
|
||||
min-width: 260dp;
|
||||
max-width: 90%;
|
||||
padding: 10dp 16dp 12dp;
|
||||
border-radius: 7dp;
|
||||
overflow: hidden;
|
||||
filter: opacity(0);
|
||||
transition: filter 0.2s linear-in-out;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
pipeline-progress[open] {
|
||||
filter: opacity(1);
|
||||
}
|
||||
|
||||
pipeline-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8dp;
|
||||
font-size: 18dp;
|
||||
font-weight: normal;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
icon.pipeline-spinner {
|
||||
width: 1.2em;
|
||||
height: 1.2em;
|
||||
line-height: 1.2em;
|
||||
font-size: 1.2em;
|
||||
color: #C2A42D;
|
||||
text-align: center;
|
||||
transform-origin: center;
|
||||
animation: 1s linear infinite pipeline-spinner-spin;
|
||||
}
|
||||
|
||||
toast.achievement {
|
||||
border: 1dp #C2A42D;
|
||||
}
|
||||
@@ -118,6 +159,14 @@ toast.achievement heading {
|
||||
color: #C2A42D;
|
||||
}
|
||||
|
||||
toast.warning {
|
||||
border: 1dp #C2A42D;
|
||||
}
|
||||
|
||||
toast.warning heading {
|
||||
color: #C2A42D;
|
||||
}
|
||||
|
||||
toast.controller-warning {
|
||||
top: auto;
|
||||
right: auto;
|
||||
@@ -310,6 +359,15 @@ logo img.outer {
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes pipeline-spinner-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-height: 640dp) {
|
||||
toast {
|
||||
top: 20dp;
|
||||
|
||||
@@ -362,6 +362,10 @@ body.animate-in .intro-item {
|
||||
transition: opacity transform 0.3s 0.6s cubic-in-out;
|
||||
}
|
||||
|
||||
.delay-6 {
|
||||
transition: opacity transform 0.3s 0.7s cubic-in-out;
|
||||
}
|
||||
|
||||
/* Mobile layout */
|
||||
@media (max-height: 640dp) {
|
||||
.gradient {
|
||||
|
||||
+12
-3
@@ -50,7 +50,8 @@ tab-bar[closable] tab-end-spacer {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
tab-bar[closable] close {
|
||||
tab-bar[closable] close,
|
||||
window > close {
|
||||
display: block;
|
||||
position: fixed;
|
||||
top: 8dp;
|
||||
@@ -70,12 +71,20 @@ tab-bar[closable] close {
|
||||
}
|
||||
|
||||
tab-bar[closable] close:hover,
|
||||
tab-bar[closable] close:focus-visible {
|
||||
tab-bar[closable] close:focus-visible,
|
||||
window > close:hover,
|
||||
window > close:focus-visible {
|
||||
color: #fff;
|
||||
background-color: rgba(194, 164, 45, 24%);
|
||||
}
|
||||
|
||||
tab-bar[closable] close:active {
|
||||
window > close {
|
||||
top: 16dp;
|
||||
right: 16dp;
|
||||
}
|
||||
|
||||
tab-bar[closable] close:active,
|
||||
window > close:active {
|
||||
color: #fff;
|
||||
background-color: rgba(194, 164, 45, 40%);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
*, *:before, *:after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
font-family: "Fira Sans Condensed";
|
||||
font-weight: bold;
|
||||
color: rgba(248, 244, 232, 90%);
|
||||
z-index: 1;
|
||||
filter: opacity(0);
|
||||
transition: filter 0.2s linear-in-out;
|
||||
}
|
||||
|
||||
body[open] {
|
||||
filter: opacity(1);
|
||||
}
|
||||
|
||||
body:not([open]) {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
decorator: none;
|
||||
padding: 0;
|
||||
border: 1dp rgba(255, 255, 255, 22%);
|
||||
background-color: rgba(22, 24, 28, 48%);
|
||||
color: rgba(248, 244, 232, 90%);
|
||||
text-align: center;
|
||||
/* backdrop-filter: blur(7dp); */
|
||||
/* box-shadow: 0 6dp 18dp rgba(0, 0, 0, 28%); */
|
||||
transform-origin: center;
|
||||
transition: background-color border-color filter transform 0.08s linear-in-out,
|
||||
opacity 0.2s linear-in-out;
|
||||
}
|
||||
|
||||
button.pressed,
|
||||
button.active {
|
||||
background-color: rgba(63, 78, 90, 68%);
|
||||
border-color: rgba(255, 255, 255, 48%);
|
||||
filter: brightness(1.18);
|
||||
}
|
||||
|
||||
button:hidden {
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
button span {
|
||||
display: block;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
button icon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
button icon glyph {
|
||||
display: block;
|
||||
font-family: "Material Symbols Rounded";
|
||||
font-weight: normal;
|
||||
font-size: 24dp;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.midna-icon,
|
||||
.item-icon,
|
||||
.item-count,
|
||||
.oil-meter {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.midna-icon.visible,
|
||||
.item-icon.visible,
|
||||
.item-count.visible,
|
||||
.oil-meter.visible {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.control {
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
.trigger-l.active {
|
||||
background-color: rgba(57, 116, 133, 74%);
|
||||
border-color: rgba(128, 222, 234, 72%);
|
||||
}
|
||||
|
||||
.trigger,
|
||||
.skip {
|
||||
border-radius: 23dp;
|
||||
}
|
||||
|
||||
.trigger {
|
||||
font-size: 22dp;
|
||||
}
|
||||
|
||||
.button-z {
|
||||
background-color: rgba(118, 79, 158, 58%);
|
||||
border-color: rgba(203, 170, 255, 36%);
|
||||
}
|
||||
|
||||
.midna-icon {
|
||||
position: absolute;
|
||||
left: 9dp;
|
||||
top: -1dp;
|
||||
height: 48dp;
|
||||
}
|
||||
|
||||
.button-z.has-icon span,
|
||||
.face.has-item span {
|
||||
position: absolute;
|
||||
font-size: 13dp;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.button-z.has-icon span {
|
||||
right: 9dp;
|
||||
bottom: 7dp;
|
||||
}
|
||||
|
||||
.button-z.pressed {
|
||||
background-color: rgba(139, 91, 187, 82%);
|
||||
border-color: rgba(220, 194, 255, 70%);
|
||||
}
|
||||
|
||||
action-bar {
|
||||
position: absolute;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
border: 1dp rgba(255, 255, 255, 22%);
|
||||
border-radius: 23dp;
|
||||
background-color: rgba(22, 24, 28, 48%);
|
||||
/* backdrop-filter: blur(7dp); */
|
||||
/* box-shadow: 0 -6dp 18dp rgba(0, 0, 0, 28%); */
|
||||
overflow: hidden;
|
||||
opacity: 1;
|
||||
transform-origin: center;
|
||||
transition: opacity 0.2s linear-in-out;
|
||||
}
|
||||
|
||||
action-bar:hidden,
|
||||
action-bar:hidden button,
|
||||
action-bar:hidden separator {
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.utility {
|
||||
position: relative;
|
||||
flex: 1 1 auto;
|
||||
width: 56dp;
|
||||
height: 44dp;
|
||||
margin: 0;
|
||||
border-width: 0dp;
|
||||
border-radius: 0;
|
||||
background-color: transparent;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.utility,
|
||||
.skip {
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
.utility.pressed {
|
||||
background-color: rgba(63, 78, 90, 68%);
|
||||
}
|
||||
|
||||
.utility.pressed,
|
||||
.skip.pressed {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.skip {
|
||||
z-index: 1;
|
||||
border-color: rgba(255, 255, 255, 36%);
|
||||
}
|
||||
|
||||
separator {
|
||||
display: block;
|
||||
flex: 0 0 1dp;
|
||||
width: 1dp;
|
||||
height: 24dp;
|
||||
background-color: rgba(255, 255, 255, 18%);
|
||||
opacity: 1;
|
||||
transition: opacity 0.2s linear-in-out;
|
||||
}
|
||||
|
||||
.face {
|
||||
position: absolute;
|
||||
border-radius: 29dp;
|
||||
font-size: 24dp;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.item-icon {
|
||||
width: auto;
|
||||
height: auto;
|
||||
max-width: 76%;
|
||||
max-height: 76%;
|
||||
}
|
||||
|
||||
.item-count {
|
||||
position: absolute;
|
||||
left: 6dp;
|
||||
bottom: 5dp;
|
||||
min-width: 17dp;
|
||||
height: 15dp;
|
||||
padding: 1dp 3dp;
|
||||
border-radius: 7dp;
|
||||
background-color: rgba(0, 0, 0, 52%);
|
||||
color: rgba(255, 255, 255, 92%);
|
||||
font-size: 12dp;
|
||||
line-height: 13dp;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.oil-meter {
|
||||
position: absolute;
|
||||
left: 12dp;
|
||||
bottom: -5dp;
|
||||
width: 34dp;
|
||||
height: 8dp;
|
||||
padding: 2dp;
|
||||
border: 1dp rgba(42, 32, 18, 82%);
|
||||
border-radius: 4dp;
|
||||
background-color: rgba(18, 14, 10, 70%);
|
||||
/* box-shadow: 0 2dp 6dp rgba(0, 0, 0, 35%); */
|
||||
}
|
||||
|
||||
oil-fill {
|
||||
display: block;
|
||||
width: 0%;
|
||||
height: 100%;
|
||||
border-radius: 2dp;
|
||||
background-color: rgb(255, 232, 74);
|
||||
}
|
||||
|
||||
.face.has-item span {
|
||||
right: 6dp;
|
||||
bottom: 6dp;
|
||||
color: rgba(255, 255, 255, 88%);
|
||||
}
|
||||
|
||||
.face.a {
|
||||
border-radius: 37dp;
|
||||
font-size: 31dp;
|
||||
background-color: rgba(34, 112, 123, 62%);
|
||||
}
|
||||
|
||||
.face.b {
|
||||
background-color: rgba(161, 61, 66, 58%);
|
||||
}
|
||||
|
||||
.face.x {
|
||||
background-color: rgba(83, 115, 151, 56%);
|
||||
}
|
||||
|
||||
.face.y {
|
||||
background-color: rgba(113, 91, 150, 54%);
|
||||
}
|
||||
|
||||
button.control.docked-top,
|
||||
action-bar.docked-top {
|
||||
border-top-width: 0dp;
|
||||
border-top-left-radius: 0dp;
|
||||
border-top-right-radius: 0dp;
|
||||
}
|
||||
|
||||
button.control.docked-bottom,
|
||||
action-bar.docked-bottom {
|
||||
border-bottom-width: 0dp;
|
||||
border-bottom-left-radius: 0dp;
|
||||
border-bottom-right-radius: 0dp;
|
||||
}
|
||||
|
||||
button.control.docked-left,
|
||||
action-bar.docked-left {
|
||||
border-left-width: 0dp;
|
||||
border-top-left-radius: 0dp;
|
||||
border-bottom-left-radius: 0dp;
|
||||
}
|
||||
|
||||
button.control.docked-right,
|
||||
action-bar.docked-right {
|
||||
border-right-width: 0dp;
|
||||
border-top-right-radius: 0dp;
|
||||
border-bottom-right-radius: 0dp;
|
||||
}
|
||||
|
||||
touch-stick {
|
||||
display: block;
|
||||
position: absolute;
|
||||
width: 124dp;
|
||||
height: 124dp;
|
||||
border-radius: 62dp;
|
||||
background-color: rgba(18, 20, 24, 35%);
|
||||
border: 1dp rgba(255, 255, 255, 20%);
|
||||
/* backdrop-filter: blur(7dp); */
|
||||
/* box-shadow: 0 8dp 24dp rgba(0, 0, 0, 24%); */
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity 0.18s linear-in-out;
|
||||
}
|
||||
|
||||
touch-stick.active {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
stick-ring {
|
||||
position: absolute;
|
||||
left: 18dp;
|
||||
top: 18dp;
|
||||
width: 88dp;
|
||||
height: 88dp;
|
||||
border-radius: 44dp;
|
||||
border: 1dp rgba(255, 255, 255, 18%);
|
||||
}
|
||||
|
||||
stick-knob {
|
||||
position: absolute;
|
||||
width: 48dp;
|
||||
height: 48dp;
|
||||
border-radius: 24dp;
|
||||
background-color: rgba(238, 236, 226, 55%);
|
||||
border: 1dp rgba(255, 255, 255, 45%);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user