diff --git a/CMakeLists.txt b/CMakeLists.txt index b7d280190..fddeeddfd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,14 +1,49 @@ cmake_minimum_required(VERSION 3.5) -# DO NOT CHANGE THIS SRB2 STRING! Some variable names depend on this string. -# Version change is fine. -project(SRB2 - VERSION 1.6 - LANGUAGES C) + +# needed for lto to work for some reason +cmake_policy(SET CMP0069 NEW) if(${PROJECT_SOURCE_DIR} MATCHES ${PROJECT_BINARY_DIR}) message(FATAL_ERROR "In-source builds will bring you a world of pain. Please make a separate directory to invoke CMake from.") endif() +# DO NOT CHANGE THIS SRB2 STRING! Some variable names depend on this string. +# Version change is fine. +project(SRB2 + VERSION 1.6 + LANGUAGES C CXX) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +#set(CMAKE_CXX_EXTENSIONS OFF) # optional but recommended: disables GNU extensions, forces pure ISO C++ +set(CMAKE_CXX_EXTENSIONS ON) +set(CMAKE_C_EXTENSIONS ON) + +##### PACKAGE CONFIGURATION ##### + +set(SRB2_CPACK_GENERATOR "" CACHE STRING "Generator to use for making a package. E.g., ZIP, TGZ, DragNDrop (OSX only). Leave blank for default generator.") + +if("${SRB2_CPACK_GENERATOR}" STREQUAL "") + if("${CMAKE_SYSTEM_NAME}" MATCHES "Windows") + set(SRB2_CPACK_GENERATOR "ZIP") + elseif("${CMAKE_SYSTEM_NAME}" MATCHES "Linux") + set(SRB2_CPACK_GENERATOR "TGZ") + elseif("${CMAKE_SYSTEM_NAME}" MATCHES "Darwin") + set(SRB2_CPACK_GENERATOR "TGZ") + endif() +endif() + +set(CPACK_GENERATOR ${SRB2_CPACK_GENERATOR}) +set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Sonic Robo Blast 2 Kart Saturn" CACHE STRING "Program name for display purposes") +set(CPACK_PACKAGE_VENDOR "Kart Krew" CACHE STRING "Vendor name for display purposes") +#set(CPACK_PACKAGE_DESCRIPTION_FILE ) +set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE") +set(CPACK_PACKAGE_VERSION_MAJOR ${SRB2_VERSION_MAJOR}) +set(CPACK_PACKAGE_VERSION_MINOR ${SRB2_VERSION_MINOR}) +set(CPACK_PACKAGE_VERSION_PATCH ${SRB2_VERSION_PATCH}) +set(CPACK_PACKAGE_INSTALL_DIRECTORY "CMake ${CMAKE_VERSION_MAJOR}.${CMAKE_VERSION_MINOR}") +include(CPack) + # Set up CMAKE path set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/Modules/") @@ -73,6 +108,7 @@ endif() # OS macros if (UNIX) add_definitions(-DUNIXCOMMON) + add_link_options(-rdynamic) # Use -rdynamic so a backtrace log shows function names endif() if(CMAKE_COMPILER_IS_GNUCC) @@ -95,14 +131,12 @@ set(CMAKE_PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin") # Set EXE names so the assets CMakeLists can refer to its target set(SRB2_SDL2_EXE_NAME srb2kart CACHE STRING "Executable binary output name") -set(SRB2_WIN_EXE_NAME srb2kartdd CACHE STRING "Executable binary output name for DirectDraw build") include_directories(${CMAKE_CURRENT_BINARY_DIR}/src) add_subdirectory(src) add_subdirectory(assets) - ## config.h generation set(GIT_EXECUTABLE "git" CACHE FILEPATH "Path to git binary") include(GitUtilities) @@ -111,25 +145,3 @@ git_current_branch(SRB2_GIT_BRANCH "${CMAKE_SOURCE_DIR}") set(SRB2_COMP_BRANCH "${SRB2_GIT_BRANCH}") set(SRB2_COMP_REVISION "${SRB2_COMP_COMMIT}") configure_file(${CMAKE_CURRENT_SOURCE_DIR}/src/config.h.in ${CMAKE_CURRENT_BINARY_DIR}/src/config.h) - -##### PACKAGE CONFIGURATION ##### - -if(${CMAKE_SYSTEM} MATCHES "Windows") - set(CPACK_GENERATOR "ZIP") -endif() -if(${CMAKE_SYSTEM} MATCHES "Linux") - set(CPACK_GENERATOR "TGZ") -endif() -if(${CMAKE_SYSTEM} MATCHES "Darwin") - set(CPACK_GENERATOR "DragNDrop") -endif() - -set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Sonic Robo Blast 2 Kart" CACHE STRING "Program name for display purposes") -set(CPACK_PACKAGE_VENDOR "Kart Krew" CACHE STRING "Vendor name for display purposes") -#set(CPACK_PACKAGE_DESCRIPTION_FILE ) -set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE") -set(CPACK_PACKAGE_VERSION_MAJOR ${SRB2_VERSION_MAJOR}) -set(CPACK_PACKAGE_VERSION_MINOR ${SRB2_VERSION_MINOR}) -set(CPACK_PACKAGE_VERSION_PATCH ${SRB2_VERSION_PATCH}) -set(CPACK_PACKAGE_INSTALL_DIRECTORY "CMake ${CMAKE_VERSION_MAJOR}.${CMAKE_VERSION_MINOR}") -include(CPack) diff --git a/README.md b/README.md index d538288bb..698f55a9c 100644 --- a/README.md +++ b/README.md @@ -22,14 +22,14 @@ We also have a Flatpak available on [Flathub](https://flathub.org/en/apps/org.sr See [SRB2 Wiki/Source code compiling](http://wiki.srb2.org/wiki/Source_code_compiling). The compiling process for SRB2Kart is largely identical to SRB2. -Currently only the Makefile build system with GCC or Clang compiler is supported. -CMake is NOT supported at the moment, but will be availible again soon. - +For Windows only the Makefile build system with GCC or Clang compiler is supported. Visual C++ (MSVC) is unsupported. 64-bit Windows builds are supported and recommended over 32-bit builds, they will build automatically when using the MSYS2 MinGW 64-bit executable (requires the mingw-w64-x86_64-gcc package), no extra flags needed! The specific DLLs can be found under /libs/dll-binaries/(i686 for 32bit/x86_64 for 64-bit)/ or in the Release packages +MacOS and Linux can be build with CMake, but it is recommended to use the Makefile for Linux over CMake + Alternatively the [srb2bld](https://github.com/Bijman/srb2bld) script by Bijman can be used aswell! ## Disclaimer diff --git a/assets/CMakeLists.txt b/assets/CMakeLists.txt index 12be1c470..a34cf2dfc 100644 --- a/assets/CMakeLists.txt +++ b/assets/CMakeLists.txt @@ -1,5 +1,10 @@ ## Assets Target Configuration ## +if(${CMAKE_SYSTEM} MATCHES Linux) + # Asset installation isn't part of the Linux target + return() +endif() + # For prepending the current source path, later FUNCTION(PREPEND var prefix) SET(listVar "") diff --git a/cmake/Modules/FindGME.cmake b/cmake/Modules/FindGME.cmake index ea80af454..7e9087247 100644 --- a/cmake/Modules/FindGME.cmake +++ b/cmake/Modules/FindGME.cmake @@ -1,6 +1,6 @@ include(LibFindMacros) -libfind_pkg_check_modules(GME_PKGCONF GME) +libfind_pkg_check_modules(GME_PKGCONF LIBGME) find_path(GME_INCLUDE_DIR NAMES gme.h @@ -8,6 +8,7 @@ find_path(GME_INCLUDE_DIR ${GME_PKGCONF_INCLUDE_DIRS} "/usr/include/gme" "/usr/local/include/gme" + PATH_SUFFIXES gme ) find_library(GME_LIBRARY @@ -20,4 +21,4 @@ find_library(GME_LIBRARY set(GME_PROCESS_INCLUDES GME_INCLUDE_DIR) set(GME_PROCESS_LIBS GME_LIBRARY) -libfind_process(GME) \ No newline at end of file +libfind_process(GME) diff --git a/cmake/Modules/FindOPENMPT.cmake b/cmake/Modules/FindOPENMPT.cmake index 2d334b6f0..305a55ee1 100644 --- a/cmake/Modules/FindOPENMPT.cmake +++ b/cmake/Modules/FindOPENMPT.cmake @@ -1,6 +1,6 @@ include(LibFindMacros) -libfind_pkg_check_modules(OPENMPT_PKGCONF OPENMPT) +libfind_pkg_check_modules(OPENMPT_PKGCONF LIBOPENMPT) find_path(OPENMPT_INCLUDE_DIR NAMES libopenmpt.h @@ -8,6 +8,7 @@ find_path(OPENMPT_INCLUDE_DIR ${OPENMPT_PKGCONF_INCLUDE_DIRS} "/usr/include/libopenmpt" "/usr/local/include/libopenmpt" + PATH_SUFFIXES libopenmpt ) find_library(OPENMPT_LIBRARY @@ -20,4 +21,4 @@ find_library(OPENMPT_LIBRARY set(OPENMPT_PROCESS_INCLUDES OPENMPT_INCLUDE_DIR) set(OPENMPT_PROCESS_LIBS OPENMPT_LIBRARY) -libfind_process(OPENMPT) \ No newline at end of file +libfind_process(OPENMPT) diff --git a/cmake/Modules/Findlibbacktrace.cmake b/cmake/Modules/Findlibbacktrace.cmake new file mode 100644 index 000000000..81ebeb9dc --- /dev/null +++ b/cmake/Modules/Findlibbacktrace.cmake @@ -0,0 +1,33 @@ +include(LibFindMacros) + +libfind_pkg_check_modules(LIBBACKTRACE_PKGCONF LIBBACKTRACE) + +find_path(LIBBACKTRACE_INCLUDE_DIR + NAMES backtrace.h + PATHS + ${LIBBACKTRACE_PKGCONF_INCLUDE_DIRS} + "/usr/include" + "/usr/local/include" +) + +find_library(LIBBACKTRACE_LIBRARY + NAMES backtrace + PATHS + ${LIBBACKTRACE_PKGCONF_LIBRARY_DIRS} + "/usr/lib" + "/usr/local/lib" +) + +set(LIBBACKTRACE_PROCESS_INCLUDES LIBBACKTRACE_INCLUDE_DIR) +set(LIBBACKTRACE_PROCESS_LIBS LIBBACKTRACE_LIBRARY) +libfind_process(LIBBACKTRACE) + +if(LIBBACKTRACE_FOUND AND NOT TARGET libbacktrace) + add_library(libbacktrace UNKNOWN IMPORTED) + set_target_properties( + libbacktrace + PROPERTIES + IMPORTED_LOCATION "${LIBBACKTRACE_LIBRARY}" + INTERFACE_INCLUDE_DIRECTORIES "${LIBBACKTRACE_INCLUDE_DIR}" + ) +endif() diff --git a/cmake/Modules/LibFindMacros.cmake b/cmake/Modules/LibFindMacros.cmake index 81fef7d8e..0e29dea5e 100644 --- a/cmake/Modules/LibFindMacros.cmake +++ b/cmake/Modules/LibFindMacros.cmake @@ -1,4 +1,4 @@ -# Version 2.2 +# Version 2.4 # Public Domain, originally written by Lasse Kärkkäinen # Maintained at https://github.com/Tronic/cmake-modules # Please send your improvements as pull requests on Github. @@ -52,6 +52,10 @@ function (libfind_pkg_detect PREFIX) if (libraryargs) find_library(${PREFIX}_LIBRARY NAMES ${libraryargs} HINTS ${${PREFIX}_PKGCONF_LIBRARY_DIRS}) endif() + # Read pkg-config version + if (${PREFIX}_PKGCONF_VERSION) + set(${PREFIX}_VERSION ${${PREFIX}_PKGCONF_VERSION} PARENT_SCOPE) + endif() endfunction() # Extracts a version #define from a version.h file, output stored to _VERSION. @@ -125,24 +129,39 @@ function (libfind_process PREFIX) # Process deps to add to foreach (i ${PREFIX} ${${PREFIX}_DEPENDENCIES}) - if (DEFINED ${i}_INCLUDE_OPTS OR DEFINED ${i}_LIBRARY_OPTS) + if (DEFINED ${i}_INCLUDE_OPTS) # The package seems to export option lists that we can use, woohoo! list(APPEND includeopts ${${i}_INCLUDE_OPTS}) + else() + if (DEFINED ${i}_INCLUDE_DIR) + # Singular forms can be used + list(APPEND includeopts ${i}_INCLUDE_DIR) + else() + if (DEFINED ${i}_INCLUDE_DIRS) + # Plural forms can be used + list(APPEND includeopts ${i}_INCLUDE_DIRS) + else() + # Oh no, we don't know the option names + message(FATAL_ERROR "We couldn't determine config variable names for ${i} includes. Aieeh!") + endif() + endif() + endif() + + if (DEFINED ${i}_LIBRARY_OPTS) + # The package seems to export option lists that we can use, woohoo! list(APPEND libraryopts ${${i}_LIBRARY_OPTS}) else() - # If plural forms don't exist or they equal singular forms - if ((NOT DEFINED ${i}_INCLUDE_DIRS AND NOT DEFINED ${i}_LIBRARIES) OR - ({i}_INCLUDE_DIR STREQUAL ${i}_INCLUDE_DIRS AND ${i}_LIBRARY STREQUAL ${i}_LIBRARIES)) + if (DEFINED ${i}_LIBRARY) # Singular forms can be used - if (DEFINED ${i}_INCLUDE_DIR) - list(APPEND includeopts ${i}_INCLUDE_DIR) - endif() - if (DEFINED ${i}_LIBRARY) - list(APPEND libraryopts ${i}_LIBRARY) - endif() + list(APPEND libraryopts ${i}_LIBRARY) else() - # Oh no, we don't know the option names - message(FATAL_ERROR "We couldn't determine config variable names for ${i} includes and libs. Aieeh!") + if (DEFINED ${i}_LIBRARIES) + # Plural forms can be used + list(APPEND libraryopts ${i}_LIBRARIES) + else() + # Oh no, we don't know the option names + message(FATAL_ERROR "We couldn't determine config variable names for ${i} libraries. Aieeh!") + endif() endif() endif() endforeach() @@ -209,12 +228,12 @@ function (libfind_process PREFIX) message(STATUS " ${PREFIX}_LIBRARY_OPTS=${libraryopts}") message(STATUS " ${PREFIX}_LIBRARIES=${libs}") endif() - set (${PREFIX}_INCLUDE_OPTS ${includeopts} PARENT_SCOPE) - set (${PREFIX}_LIBRARY_OPTS ${libraryopts} PARENT_SCOPE) - set (${PREFIX}_INCLUDE_DIRS ${includes} PARENT_SCOPE) - set (${PREFIX}_LIBRARIES ${libs} PARENT_SCOPE) - set (${PREFIX}_FOUND TRUE PARENT_SCOPE) endif() + set (${PREFIX}_INCLUDE_OPTS ${includeopts} PARENT_SCOPE) + set (${PREFIX}_LIBRARY_OPTS ${libraryopts} PARENT_SCOPE) + set (${PREFIX}_INCLUDE_DIRS ${includes} PARENT_SCOPE) + set (${PREFIX}_LIBRARIES ${libs} PARENT_SCOPE) + set (${PREFIX}_FOUND TRUE PARENT_SCOPE) return() endif() diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 361386622..c763ab3b8 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -2,6 +2,8 @@ # Core sources set(SRB2_CORE_SOURCES + core/memory.cpp + core/thread_pool.cpp am_map.c b_bot.c command.c @@ -18,17 +20,21 @@ set(SRB2_CORE_SOURCES f_wipe.c filesrch.c g_game.c + g_demo.c g_input.c hu_stuff.c i_tcp.c info.c + k_hud.c lzf.c m_aatree.c m_anigif.c m_argv.c m_bbox.c m_cheat.c + m_curl.c m_cond.c + m_emotes.cpp m_fixed.c m_menu.c m_textinput.c @@ -40,19 +46,25 @@ set(SRB2_CORE_SOURCES mserv.c http-mserv.c qs22j.c + r_skins.c s_sound.c screen.c sounds.c st_stuff.c - #string.c + string.c tables.c v_video.c w_wad.c y_inter.c - z_zone.c + z_zone.cpp ) set(SRB2_CORE_HEADERS + core/memory.h + core/thread_pool.h + m_curl.h + m_emotes.h + k_hud.h am_map.h b_bot.h byteptr.h @@ -78,6 +90,7 @@ set(SRB2_CORE_HEADERS fastcmp.h filesrch.h g_game.h + g_demo.h g_input.h g_state.h hu_stuff.h @@ -109,6 +122,7 @@ set(SRB2_CORE_HEADERS md5.h mserv.h qs22j.h + r_skins.h s_sound.h screen.h sounds.h @@ -123,18 +137,18 @@ set(SRB2_CORE_HEADERS ) set(SRB2_CORE_RENDER_SOURCES - r_bsp.c + r_bsp.cpp r_data.c - r_draw.c - r_fps.c - r_main.c - r_patch.c - r_patchrotation.c - r_plane.c - r_segs.c + r_draw.cpp + r_fps.cpp + r_main.cpp + r_patch.cpp + r_patchrotation.cpp + r_plane.cpp + r_segs.cpp r_sky.c r_splats.c - r_things.c + r_things.cpp r_portal.c r_bsp.h @@ -162,7 +176,7 @@ set(SRB2_CORE_GAME_SOURCES p_inter.c p_lights.c p_map.c - p_maputl.c + p_maputl.cpp p_mobj.c p_polyobj.c p_saveg.c @@ -193,10 +207,6 @@ set(SRB2_CORE_GAME_SOURCES k_stats.h ) -if(NOT (CMAKE_CXX_COMPILER_ID MATCHES "Clang")) - set(SRB2_CORE_SOURCES ${SRB2_CORE_SOURCES} string.c) -endif() - prepend_sources(SRB2_CORE_SOURCES) prepend_sources(SRB2_CORE_HEADERS) prepend_sources(SRB2_CORE_RENDER_SOURCES) @@ -226,10 +236,29 @@ set(SRB2_CONFIG_HWRENDER ON CACHE BOOL "Enable hardware rendering through OpenGL.") set(SRB2_CONFIG_STATIC_OPENGL OFF CACHE BOOL "Use statically linked OpenGL. NOT RECOMMENDED.") -set(SRB2_CONFIG_USE_FBO_OGL ON CACHE BOOL - "Enable OpenGL FBO Downsampling support.") set(SRB2_CONFIG_DEDICATED OFF CACHE BOOL "Build a dedicated server.") +set(SRB2_CONFIG_LIBBACKTRACE ON CACHE BOOL + "Enable using libbacktrace for crashlogs.") +set(SRB2_CONFIG_LTO ON CACHE BOOL + "Enable link time optimizations, improves performance at the cost of longer link times.") +set(SRB2_CONFIG_ASAN OFF CACHE BOOL + "Compile with AddressSanitizer (libasan).") +set(SRB2_CONFIG_UBSAN OFF CACHE BOOL + "Compile with UndefinedBehaviorSanitizer (libubsan).") + +set(SRB2_CONFIG_MUMBLE ON CACHE BOOL + "Enable Mumble support") + +set(SRB2_CONFIG_SATURNPAK ON CACHE BOOL + "Enable Saturn specific special packet. Required for using the newer resynch system") +set(SRB2_CONFIG_SATURNJOIN ON CACHE BOOL + "Enable Saturn specific allowjoin toggle.") +set(SRB2_CONFIG_SCREENFBO ON CACHE BOOL + "Enable hardware renderer (OpenGL) FBO downsampling support") + +set(SRB2_CONFIG_PHOBOS ON CACHE BOOL + " Compile the Phobos client. Which contains things not compatible with vanilla, such as raised skinlimits, 32 player support, bugfixes, etc.") if(${SRB2_CONFIG_DEDICATED}) set(SRB2_CONFIG_HAVE_GME NO) @@ -252,6 +281,7 @@ if(${SRB2_CONFIG_HAVE_BLUA}) lua_hooklib.c lua_hudlib.c lua_hudlib_drawlist.c + lua_profile.cpp lua_infolib.c lua_maplib.c lua_mathlib.c @@ -267,6 +297,7 @@ if(${SRB2_CONFIG_HAVE_BLUA}) lua_hook.h lua_hud.h lua_hudlib_drawlist.h + lua_profile.h lua_libs.h lua_script.h lua_udatalib.h @@ -469,6 +500,26 @@ if(${SRB2_CONFIG_HAVE_CURL}) endif() endif() +if(${SRB2_CONFIG_LIBBACKTRACE}) + if(${SRB2_CONFIG_USE_INTERNAL_LIBRARIES}) + if(${SRB2_SYSTEM_BITS} EQUAL 64) + set(LIBBACKTRACE_FOUND ON) + set(LIBBACKTRACE_INCLUDE_DIRS ${CMAKE_SOURCE_DIR}/libs/libbacktrace/include) + set(LIBBACKTRACE_LIBRARIES "-L${CMAKE_SOURCE_DIR}/libs/libbacktrace/lib/x86_64 -lbacktrace") + else() # 32-bit + message(WARNING "libbacktrace is unsupported on 32-bit builds.") + endif() + else() + find_package(libbacktrace) + endif() + if(${LIBBACKTRACE_FOUND}) + set(SRB2_HAVE_LIBBACKTRACE ON) + add_definitions(-DHAVE_LIBBACKTRACE) + else() + message(WARNING "You have specified that libbacktrace is available but it was not found.") + endif() +endif() + if(${SRB2_CONFIG_HWRENDER}) add_definitions(-DHWRENDER) set(SRB2_HWRENDER_SOURCES @@ -478,7 +529,7 @@ if(${SRB2_CONFIG_HWRENDER}) ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_cache.c ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_clip.c ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_draw.c - ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_main.c + ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_main.cpp ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_portal.c ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_md2.c ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_md2load.c @@ -493,7 +544,6 @@ if(${SRB2_CONFIG_HWRENDER}) ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_clip.h ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_data.h ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_defs.h - ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_dll.h ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_gl.h ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_glob.h ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_main.h @@ -512,7 +562,6 @@ if(${SRB2_CONFIG_HWRENDER}) set(SRB2_R_OPENGL_HEADERS ${CMAKE_CURRENT_SOURCE_DIR}/hardware/r_opengl/r_opengl.h ) - endif() if(${SRB2_CONFIG_HWRENDER} AND ${SRB2_CONFIG_STATIC_OPENGL}) @@ -525,25 +574,44 @@ if(${SRB2_CONFIG_HWRENDER} AND ${SRB2_CONFIG_STATIC_OPENGL}) endif() endif() -if(${SRB2_CONFIG_HWRENDER}) - if(${SRB2_CONFIG_USE_FBO_OGL}) - set(SRB2_USE_FBO_OGL ON) - add_definitions(-DUSE_FBO_OGL) - endif() +if(${SRB2_CONFIG_HWRENDER} AND ${SRB2_CONFIG_SCREENFBO}) + add_definitions(-DUSE_FBO_OGL) +endif() + +if(${SRB2_CONFIG_SATURNPAK}) + add_definitions(-DDOSATURNPAK) +endif() + +if(${SRB2_CONFIG_SATURNJOIN}) + add_definitions(-DDOSATURNJOIN) +endif() + +if(${SRB2_CONFIG_HWRENDER} AND ${SRB2_CONFIG_SCREENFBO}) + add_definitions(-DPHOBOS_BUILD) endif() # Targets # Compatibility flag with later versions of GCC # We should really fix our code to not need this -if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") - set(CMAKE_C_FLAGS ${CMAKE_C_FLAGS} -mno-ms-bitfields) +if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" OR "${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") + if (CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|x64|amd64|AMD64|em64t|EM64T)") + add_compile_options(-mno-ms-bitfields) + endif() + add_compile_options(-Wno-trigraphs) endif() -if (CMAKE_CXX_COMPILER_ID MATCHES "Clang") - set(CMAKE_C_FLAGS ${CMAKE_C_FLAGS} -Wno-absolute-value) +# TODO: fix prng and P_CreateBlockmap overflow at some point +add_compile_options(-fwrapv) + +if (${CMAKE_BUILD_TYPE} MATCHES Debug) + add_compile_options(-O0) +else() + add_compile_options(-O3) endif() +add_compile_options(-g) + add_definitions(-DCMAKECONFIG) #add_library(SRB2Core STATIC diff --git a/src/Makefile b/src/Makefile index 0456990f3..27831946a 100644 --- a/src/Makefile +++ b/src/Makefile @@ -65,6 +65,10 @@ # DEBUGMODE=1 - Enable various debugging capabilities. # Also disables optimizations. # +# PHOBOS_BUILD=1 - Compile the Phobos client. +# Contains things not compatible with vanilla. +# such as raised skinlimits, 32 player support, bugfixes, etc. +# # Development flags: # # VALGRIND=1 - Enable Valgrind memory debugging support. @@ -93,7 +97,8 @@ # NOLDWARNING=1 - ? # NOSDLMAIN=1 - ? # SDLMAIN=1 - ? -# USELTO=1 - Enable building with LTO. +# NOLTO=1 - Disable link time optimizations +# USEJEMALLOC=1 Enable building with jemalloc Allocator to replace GLibc malloc, might improve performance # # Library configuration flags: # Everything here is an override. @@ -245,10 +250,6 @@ ifdef STATIC libs+=-static endif -ifneq (,$(filter $(CC) $(CXX),gcc g++)) - opts+=-mno-ms-bitfields -endif - # build with profiling information ifdef PROFILEMODE opts+=-pg @@ -260,7 +261,7 @@ debug_opts=-D_DEBUG else # build a normal optimized version debug_opts=-DNDEBUG opts+=-O3 -ifdef USELTO +ifndef NOLTO # compile with LTO opts+=-flto=auto libs+=-flto=auto @@ -269,16 +270,20 @@ endif ifdef USEASAN # compile with asan -opts+=-fsanitize=address +opts+=-O1 -fsanitize=address -fno-omit-frame-pointer -fno-common libs+=-fsanitize=address endif ifdef USEUBSAN -# compile with asan -opts+=-fsanitize=undefined +# compile with ubsan +opts+=-O1 -fsanitize=undefined -fno-omit-frame-pointer libs+=-fsanitize=undefined endif +ifdef USEJEMALLOC +libs+=-ljemalloc +endif + ifneq (,$(filter $(CC) $(CXX),clang clang++)) libs+=-fuse-ld=lld endif @@ -295,6 +300,7 @@ opts+=$(debug_opts) opts+=$(foreach v,$(passthru_opts),$(if $($(v)),-D$(v))) +CWFLAGS+=-std=gnu17 CXXFLAGS+=-std=c++17 # force c17 for c++ since most vpss run older ubuntu versions with old compilers opts+=$(WFLAGS) $(CFLAGS) diff --git a/src/Makefile.d/detect.mk b/src/Makefile.d/detect.mk index dd31d2f3e..766b497c3 100644 --- a/src/Makefile.d/detect.mk +++ b/src/Makefile.d/detect.mk @@ -64,9 +64,10 @@ endif # This must have high to low order. gcc_versions:=\ - 151 150 15\ + 161 160 16\ + 152 151 150 15\ 142 141 140 14\ - 132 131 130 13\ + 133 132 131 130 13\ 123 122 121 120 12\ 114 113 112 111 110 11\ 105 104 103 102 101 100 10\ @@ -77,7 +78,7 @@ gcc_versions:=\ 55 54 53 52 51 50\ 49 48 47 46 45 44 43 42 41 40 -latest_gcc_version:=15.1.1 +latest_gcc_version:=16.1 # Automatically set version flag, but not if one was # manually set. And don't bother if this is a clean only diff --git a/src/Makefile.d/features.mk b/src/Makefile.d/features.mk index b191ae2c1..6a63c9972 100644 --- a/src/Makefile.d/features.mk +++ b/src/Makefile.d/features.mk @@ -8,6 +8,8 @@ passthru_opts+=\ HAVE_MINIUPNPC\ HAVE_DISCORDRPC DEVELOP\ NOHOLEPUNCH\ + HAVE_IPV6\ + PHOBOS_BUILD\ # build with debugging information ifdef DEBUGMODE @@ -85,7 +87,7 @@ ifdef VALGRIND VALGRIND_PKGCONFIG?=valgrind VALGRIND_LDFLAGS= $(eval $(call Use_pkg_config,VALGRIND)) -ZDEBUG=1 +#ZDEBUG=1 we enable this by default opts+=-DHAVE_VALGRIND endif diff --git a/src/Makefile.d/platform.mk b/src/Makefile.d/platform.mk index d5423a397..12c3220d7 100644 --- a/src/Makefile.d/platform.mk +++ b/src/Makefile.d/platform.mk @@ -42,8 +42,6 @@ include Makefile.d/haiku.mk else ifdef SOLARIS # FIXME: UNTESTED UNIX=1 platform=solaris -else ifdef CYGWIN32 # FIXME: UNTESTED -platform=cygwin else ifdef MINGW ifdef MINGW64 NONX86=1 diff --git a/src/Makefile.d/sdl.mk b/src/Makefile.d/sdl.mk index 36f87fe30..aa4d4a7ee 100644 --- a/src/Makefile.d/sdl.mk +++ b/src/Makefile.d/sdl.mk @@ -15,16 +15,6 @@ sources+=$(call List,sdl/Sourcefile) NOUPNP=1 -# FIXME: UNTESTED -#ifdef PANDORA -#include sdl/SRB2Pandora/Makefile.cfg -#endif #ifdef PANDORA - -# FIXME: UNTESTED -#ifdef CYGWIN32 -#include sdl/MakeCYG.cfg -#endif #ifdef CYGWIN32 - ifndef NOHW sources+=sdl/ogl_sdl.c endif diff --git a/src/Makefile.d/versions.mk b/src/Makefile.d/versions.mk index 451ff72e7..cb13c286c 100644 --- a/src/Makefile.d/versions.mk +++ b/src/Makefile.d/versions.mk @@ -20,7 +20,11 @@ $(foreach v,$(join $(wordlist 2,$(_n),- $(gcc_versions)),\ CXXFLAGS+= -Wno-aggregate-return # -W -Wno-unused -WFLAGS:=-Wall -Wno-trigraphs +WFLAGS:=-Wall -Wnull-dereference +#WFLAGS+=-Wno-trigraphs +ifdef GCC152 +WFLAGS+=-Wzero-as-null-pointer-constant +endif ifndef GCC295 #WFLAGS+=-Wno-packed endif @@ -28,7 +32,7 @@ ifndef RELAXWARNINGS WFLAGS+=-W #WFLAGS+=-Wno-sign-compare ifndef GCC295 - WFLAGS+=-Wno-div-by-zero +# WFLAGS+=-Wno-div-by-zero endif #WFLAGS+=-Wsystem-headers WFLAGS+=-Wfloat-equal @@ -59,7 +63,7 @@ endif endif WFLAGS+=-Wsign-compare ifdef GCC91 - WFLAGS+=-Wno-error=address-of-packed-member +# WFLAGS+=-Wno-error=address-of-packed-member endif ifdef GCC45 WFLAGS+=-Wlogical-op @@ -102,14 +106,14 @@ endif endif WFLAGS+=-Wformat-y2k ifdef GCC71 -WFLAGS+=-Wno-error=format-overflow=2 +#WFLAGS+=-Wno-error=format-overflow=2 endif WFLAGS+=-Wformat-security ifndef GCC29 #WFLAGS+=-Winit-self endif ifdef GCC46 -WFLAGS+=-Wno-suggest-attribute=noreturn +#WFLAGS+=-Wno-suggest-attribute=noreturn endif ifdef NOLDWARNING @@ -127,21 +131,21 @@ ifdef GCC44 #WFLAGS+=-Wno-error=array-bounds endif ifdef GCC46 - WFLAGS+=-Wno-error=suggest-attribute=noreturn +# WFLAGS+=-Wno-error=suggest-attribute=noreturn endif ifdef GCC54 - WFLAGS+=-Wno-logical-op -Wno-error=logical-op +# WFLAGS+=-Wno-logical-op -Wno-error=logical-op endif ifdef GCC61 - WFLAGS+=-Wno-tautological-compare -Wno-error=tautological-compare +# WFLAGS+=-Wno-tautological-compare -Wno-error=tautological-compare endif ifdef GCC71 WFLAGS+=-Wimplicit-fallthrough=4 endif ifdef GCC81 - WFLAGS+=-Wno-error=format-overflow - WFLAGS+=-Wno-format-overflow - WFLAGS+=-Wno-error=multistatement-macros +# WFLAGS+=-Wno-error=format-overflow +# WFLAGS+=-Wno-format-overflow +# WFLAGS+=-Wno-error=multistatement-macros endif ifneq (,$(filter $(CC) $(CXX),clang clang++)) @@ -180,6 +184,6 @@ endif # Lua ifdef GCC43 ifndef GCC44 -WFLAGS+=-Wno-logical-op +#WFLAGS+=-Wno-logical-op endif endif diff --git a/src/Sourcefile b/src/Sourcefile index 08c18ebf0..f09a143bd 100644 --- a/src/Sourcefile +++ b/src/Sourcefile @@ -99,3 +99,4 @@ lua_skinlib.c lua_thinkerlib.c lua_udatalib.c lua_glib.c +lua_profile.cpp diff --git a/src/android/i_system.c b/src/android/i_system.c index 102bff461..c0f7cc11c 100644 --- a/src/android/i_system.c +++ b/src/android/i_system.c @@ -34,8 +34,8 @@ size_t I_GetFreeMem(size_t *total) /* return si.freeram; */ char buf[1024]; char *memTag; - UINT32 freeKBytes; - UINT32 totalKBytes; + size_t freeKBytes; + size_t totalKBytes; INT32 n; INT32 meminfo_fd = -1; @@ -46,7 +46,7 @@ size_t I_GetFreeMem(size_t *total) if (n < 0) { // Error - *total = 0L; + *total = 0; return 0; } @@ -54,7 +54,7 @@ size_t I_GetFreeMem(size_t *total) if (NULL == (memTag = strstr(buf, MEMTOTAL))) { // Error - *total = 0L; + *total = 0; return 0; } @@ -64,7 +64,7 @@ size_t I_GetFreeMem(size_t *total) if (NULL == (memTag = strstr(buf, MEMFREE))) { // Error - *total = 0L; + *total = 0; return 0; } @@ -226,10 +226,6 @@ const char *I_LocateWad(void) return "/sdcard/srb2"; } -void I_GetJoystickEvents(void){} - -void I_GetJoystick2Events(void){} - char *I_GetEnv(const char *name) { LOGW("I_GetEnv() called?!"); diff --git a/src/blua/lapi.c b/src/blua/lapi.c index 557896f43..6a33983fe 100644 --- a/src/blua/lapi.c +++ b/src/blua/lapi.c @@ -434,7 +434,7 @@ LUA_API void lua_pushnumber (lua_State *L, lua_Number n) { LUA_API void lua_pushlstring (lua_State *L, const char *s, size_t len) { lua_lock(L); luaC_checkGC(L); - setsvalue2s(L, L->top, (len == 0) ? luaS_new(L, "") : luaS_newlstr(L, s, len)); + setsvalue2s(L, L->top, (len == 0) ? luaS_newlstr(L, "", 0) : luaS_newlstr(L, s, len)); api_incr_top(L); lua_unlock(L); } diff --git a/src/blua/lauxlib.c b/src/blua/lauxlib.c index 5fb454d5e..05a115002 100644 --- a/src/blua/lauxlib.c +++ b/src/blua/lauxlib.c @@ -20,6 +20,7 @@ #define lauxlib_c #define LUA_LIB +#include "ldebug.h" #include "lua.h" #include "lauxlib.h" @@ -468,8 +469,19 @@ LUALIB_API char *luaL_prepbuffer (luaL_Buffer *B) { LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) { - while (l--) - luaL_addchar(B, *s++); + while (l) { + size_t space = bufffree(B); + if (space == 0) { + luaL_prepbuffer(B); + lua_assert(bufffree(B) == LUAL_BUFFERSIZE); + space = LUAL_BUFFERSIZE; + } + if (space > l) space = l; + memcpy(B->p, s, space); + B->p += space; + s += space; + l -= space; + } } @@ -686,6 +698,6 @@ static int panic (lua_State *L) { LUALIB_API lua_State *luaL_newstate (void) { lua_State *L = lua_newstate(l_alloc, NULL); - if (L) lua_atpanic(L, &panic); + if (l_likely(L)) lua_atpanic(L, &panic); return L; } diff --git a/src/blua/lcode.c b/src/blua/lcode.c index efb20e96b..567b88500 100644 --- a/src/blua/lcode.c +++ b/src/blua/lcode.c @@ -790,18 +790,19 @@ void luaK_posfix (FuncState *fs, BinOpr op, expdesc *e1, expdesc *e2) { case OPR_BXOR: codearith(fs, OP_BXOR, e1, e2); break; case OPR_BSHL: codearith(fs, OP_BSHL, e1, e2); break; case OPR_BSHR: codearith(fs, OP_BSHR, e1, e2); break; - case OPR_ADD: codearith(fs, OP_ADD, e1, e2); break; - case OPR_SUB: codearith(fs, OP_SUB, e1, e2); break; - case OPR_MUL: codearith(fs, OP_MUL, e1, e2); break; - case OPR_DIV: codearith(fs, OP_DIV, e1, e2); break; - case OPR_MOD: codearith(fs, OP_MOD, e1, e2); break; - case OPR_POW: codearith(fs, OP_POW, e1, e2); break; - case OPR_EQ: codecomp(fs, OP_EQ, 1, e1, e2); break; - case OPR_NE: codecomp(fs, OP_EQ, 0, e1, e2); break; - case OPR_LT: codecomp(fs, OP_LT, 1, e1, e2); break; - case OPR_LE: codecomp(fs, OP_LE, 1, e1, e2); break; - case OPR_GT: codecomp(fs, OP_LT, 0, e1, e2); break; - case OPR_GE: codecomp(fs, OP_LE, 0, e1, e2); break; + case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV: + case OPR_MOD: case OPR_POW: { + codearith(fs, op - OPR_ADD + OP_ADD, e1, e2); + break; + } + case OPR_EQ: case OPR_LT: case OPR_LE: { + codecomp(fs, op - OPR_EQ + OP_EQ, 1, e1, e2); + break; + } + case OPR_NE: case OPR_GT: case OPR_GE: { + codecomp(fs, op - OPR_NE + OP_EQ, 0, e1, e2); + break; + } default: lua_assert(0); } } diff --git a/src/blua/lcode.h b/src/blua/lcode.h index 5b8009472..b15c1bfeb 100644 --- a/src/blua/lcode.h +++ b/src/blua/lcode.h @@ -21,13 +21,13 @@ /* -** grep "ORDER OPR" if you change these enums +** grep "ORDER OPR" if you change these enums (ORDER OP) */ typedef enum BinOpr { OPR_ADD, OPR_SUB, OPR_MUL, OPR_DIV, OPR_MOD, OPR_POW, OPR_CONCAT, - OPR_NE, OPR_EQ, - OPR_LT, OPR_LE, OPR_GT, OPR_GE, + OPR_EQ, OPR_LT, OPR_LE, + OPR_NE, OPR_GT, OPR_GE, OPR_AND, OPR_OR, OPR_BAND, OPR_BOR, OPR_BXOR, OPR_BSHL, OPR_BSHR, diff --git a/src/blua/ldebug.c b/src/blua/ldebug.c index 542e209a1..e209fae5d 100644 --- a/src/blua/ldebug.c +++ b/src/blua/ldebug.c @@ -542,16 +542,39 @@ static const char *getobjname (lua_State *L, CallInfo *ci, int stackpos, static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) { + TMS tm = 0; Instruction i; if ((isLua(ci) && ci->tailcalls > 0) || !isLua(ci - 1)) return NULL; /* calling function is not Lua (or is unknown) */ ci--; /* calling function */ i = ci_func(ci)->l.p->code[currentpc(L, ci)]; - if (GET_OPCODE(i) == OP_CALL || GET_OPCODE(i) == OP_TAILCALL || - GET_OPCODE(i) == OP_TFORLOOP) - return getobjname(L, ci, GETARG_A(i), name); - else - return NULL; /* no useful name can be found */ + switch (GET_OPCODE(i)) { + case OP_CALL: + case OP_TAILCALL: + case OP_TFORLOOP: + return getobjname(L, ci, GETARG_A(i), name); + case OP_GETGLOBAL: + case OP_SELF: + case OP_GETTABLE: tm = TM_INDEX; break; + case OP_SETGLOBAL: + case OP_SETTABLE: tm = TM_NEWINDEX; break; + case OP_EQ: tm = TM_EQ; break; + case OP_ADD: tm = TM_ADD; break; + case OP_SUB: tm = TM_SUB; break; + case OP_MUL: tm = TM_MUL; break; + case OP_DIV: tm = TM_DIV; break; + case OP_MOD: tm = TM_MOD; break; + case OP_POW: tm = TM_POW; break; + case OP_UNM: tm = TM_UNM; break; + case OP_LEN: tm = TM_LEN; break; + case OP_LT: tm = TM_LT; break; + case OP_LE: tm = TM_LE; break; + case OP_CONCAT: tm = TM_CONCAT; break; + default: + return NULL; /* else no useful name can be found */ + } + *name = getstr(G(L)->tmname[tm]); + return "metamethod"; } diff --git a/src/blua/ldo.c b/src/blua/ldo.c index c573dab17..1bda07f11 100644 --- a/src/blua/ldo.c +++ b/src/blua/ldo.c @@ -164,7 +164,7 @@ void luaD_reallocCI (lua_State *L, int newsize) { void luaD_growstack (lua_State *L, int n) { - if (l_likely(n <= L->stacksize)) /* double size is enough? */ + if (n <= L->stacksize) /* double size is enough? */ luaD_reallocstack(L, 2*L->stacksize); else luaD_reallocstack(L, L->stacksize + n); @@ -318,7 +318,7 @@ int luaD_precall (lua_State *L, StkId func, int nresults) { ci->top = L->top + LUA_MINSTACK; lua_assert(ci->top <= L->stack_last); ci->nresults = nresults; - if (L->hookmask & LUA_MASKCALL) + if (l_unlikely(L->hookmask & LUA_MASKCALL)) luaD_callhook(L, LUA_HOOKCALL, -1); lua_unlock(L); n = (*curr_func(L)->c.f)(L); /* do the actual call */ diff --git a/src/blua/liolib.c b/src/blua/liolib.c index 2cd8dd481..2ef46c6a6 100644 --- a/src/blua/liolib.c +++ b/src/blua/liolib.c @@ -356,20 +356,21 @@ static int read_line (lua_State *L, FILE *f) { static int read_chars (lua_State *L, FILE *f, size_t n) { - size_t rlen; /* how much to read */ - size_t nr; /* number of chars actually read */ + size_t tbr = n; /* number of chars to be read */ + size_t rlen; /* how much to read in each cycle */ + size_t nr; /* number of chars actually read in each cycle */ luaL_Buffer b; luaL_buffinit(L, &b); rlen = LUAL_BUFFERSIZE; /* try to read that much each time */ do { char *p = luaL_prepbuffer(&b); - if (rlen > n) rlen = n; /* cannot read more than asked */ + if (rlen > tbr) rlen = tbr; /* cannot read more than asked */ nr = fread(p, sizeof(char), rlen, f); luaL_addsize(&b, nr); - n -= nr; /* still have to read `n' chars */ - } while (n > 0 && nr == rlen); /* until end of count or eof */ + tbr -= nr; /* still have to read 'tbr' chars */ + } while (tbr > 0 && nr == rlen); /* until end of count or eof */ luaL_pushresult(&b); /* close buffer */ - return (n == 0 || lua_objlen(L, -1) > 0); + return (tbr == 0 || tbr < n); /* true iff read something */ } @@ -432,13 +433,13 @@ static int f_read (lua_State *L) { static int io_readline (lua_State *L) { FILE *f = *(FILE **)lua_touserdata(L, lua_upvalueindex(1)); - int sucess; + int success; if (f == NULL) /* file is already closed? */ luaL_error(L, "file is already closed"); - sucess = read_line(L, f); + success = read_line(L, f); if (ferror(f)) return luaL_error(L, "%s", strerror(errno)); - if (sucess) return 1; + if (success) return 1; else { /* EOF */ if (lua_toboolean(L, lua_upvalueindex(2))) { /* generator created file? */ lua_settop(L, 0); diff --git a/src/blua/lobject.c b/src/blua/lobject.c index 0250de21d..c3cdd9eec 100644 --- a/src/blua/lobject.c +++ b/src/blua/lobject.c @@ -143,7 +143,7 @@ const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) { } case 'p': { char buff[4*sizeof(void *) + 8]; /* should be enough space for a `%p' */ - sprintf(buff, "%p", va_arg(argp, void *)); + snprintf(buff, sizeof(buff), "%p", va_arg(argp, void *)); pushstr(L, buff); break; } diff --git a/src/blua/lparser.c b/src/blua/lparser.c index 871c9730d..8046b0f1f 100644 --- a/src/blua/lparser.c +++ b/src/blua/lparser.c @@ -881,10 +881,10 @@ static const struct { lu_byte right; /* right priority */ } priority[] = { /* ORDER OPR */ {6, 6}, {6, 6}, {7, 7}, {7, 7}, {7, 7}, /* `+' `-' `/' `%' */ - {10, 9}, {5, 4}, /* power and concat (right associative) */ - {3, 3}, {3, 3}, /* equality and inequality */ - {3, 3}, {3, 3}, {3, 3}, {3, 3}, /* order */ - {2, 2}, {1, 1} /* logical (and/or) */ + {10, 9}, {5, 4}, /* ^, .. (right associative) */ + {3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */ + {3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */ + {2, 2}, {1, 1} /* and, or */ ,{6, 6}, {6, 6}, {6, 6}, /* bit-wise (band/bor/bxor) */ {7, 7}, {7, 7} /* shl/shr */ }; diff --git a/src/blua/lstring.c b/src/blua/lstring.c index 0bcc30877..b1249238b 100644 --- a/src/blua/lstring.c +++ b/src/blua/lstring.c @@ -51,7 +51,7 @@ static TString *newlstr (lua_State *L, const char *str, size_t l, unsigned int h) { TString *ts; stringtable *tb; - if (l+1 > (MAX_SIZET - sizeof(TString))/sizeof(char)) + if (l_unlikely(l+1 > (MAX_SIZET - sizeof(TString))/sizeof(char))) luaM_toobig(L); ts = cast(TString *, luaM_malloc(L, (l+1)*sizeof(char)+sizeof(TString))); ts->tsv.len = l; @@ -72,18 +72,72 @@ static TString *newlstr (lua_State *L, const char *str, size_t l, } -TString *luaS_newlstr (lua_State *L, const char *str, size_t l) { - GCObject *o; +// string hash taken from luaJIT + +/* Unaligned load of uint32_t. */ +static inline __attribute__((always_inline)) uint32_t getu32(const void* ptr) +{ + uint32_t result; + memcpy(&result, ptr, 4); + return result; +} + +// smol macro to look a little less messy lul +#define getu8(p) *cast(const uint8_t *, p) + +/* Keyed sparse ARX string hash. Constant time. */ +static unsigned hash_sparse(const char *str, size_t len) +{ + /* Constants taken from lookup3 hash by Bob Jenkins. */ + unsigned int a, b, h = cast(unsigned int, len); +#define rol(x, n) (((x)<<(n)) | ((x)>>(-cast(int, n)&(8*sizeof(x)-1)))) + if (len >= 4) { /* Caveat: unaligned access! */ + a = getu32(str); + h ^= getu32(str+len-4); + b = getu32(str+(len>>1)-2); + h ^= b; h -= rol(b, 14); + b += getu32(str+(len>>2)-1); + } else if (len > 0) { + a = getu8(str); + h ^= getu8(str+len-1); + b = getu8(str+(len>>1)); + h ^= b; h -= rol(b, 14); + } else { + return 0; + } + a ^= h; a -= rol(h, 11); + b ^= a; b -= rol(a, 25); + h ^= b; h -= rol(b, 16); +#undef rol + return h; +} + +#undef getu8 + + +static inline __attribute__((always_inline)) unsigned luaS_hash (const char *str, size_t l) { +#if 0 unsigned int h = cast(unsigned int, l); /* seed */ size_t step = (l>>5)+1; /* if string is too long, don't hash all its chars */ size_t l1; for (l1=l; l1>=step; l1-=step) /* compute hash */ h = h ^ ((h<<5)+(h>>2)+cast(unsigned char, str[l1-1])); + return h; +#else + return hash_sparse(str, l); +#endif +} + +TString *luaS_newlstr (lua_State *L, const char *str, size_t l) { + GCObject *o; + unsigned int h = luaS_hash(str, l); for (o = G(L)->strt.hash[lmod(h, G(L)->strt.size)]; o != NULL; o = o->gch.next) { TString *ts = rawgco2ts(o); - if (l_unlikely(ts->tsv.len == l && (memcmp(str, getstr(ts), l) == 0))) { + if (ts->tsv.hash == h && + ts->tsv.len == l && + (memcmp(str, getstr(ts), l) == 0)) { /* string may be dead */ if (isdead(G(L), o)) changewhite(o); return ts; diff --git a/src/blua/lstrlib.c b/src/blua/lstrlib.c index e2fd23604..5d3e4193c 100644 --- a/src/blua/lstrlib.c +++ b/src/blua/lstrlib.c @@ -527,7 +527,7 @@ static int str_find_aux (lua_State *L, int find) { if (find) { lua_pushinteger(L, s1-s+1); /* start */ lua_pushinteger(L, res-s); /* end */ - return push_captures(&ms, NULL, 0) + 2; + return push_captures(&ms, NULL, NULL) + 2; } else return push_captures(&ms, s1, res); @@ -776,23 +776,23 @@ static int str_format (lua_State *L) { strfrmt = scanformat(L, strfrmt, form); switch (*strfrmt++) { case 'c': { - sprintf(buff, form, (int)luaL_checknumber(L, arg)); + snprintf(buff, sizeof(buff), form, (int)luaL_checknumber(L, arg)); break; } case 'd': case 'i': { addintlen(form); - sprintf(buff, form, (LUA_INTFRM_T)luaL_checknumber(L, arg)); + snprintf(buff, sizeof(buff), form, (LUA_INTFRM_T)luaL_checknumber(L, arg)); break; } case 'o': case 'u': case 'x': case 'X': { addintlen(form); - sprintf(buff, form, (unsigned LUA_INTFRM_T)luaL_checknumber(L, arg)); + snprintf(buff, sizeof(buff), form, (unsigned LUA_INTFRM_T)luaL_checknumber(L, arg)); break; } case 'e': case 'E': case 'f': case 'g': case 'G': { - lua_Number n = luaL_checknumber(L, arg); - sprintf(buff, form, (double)n); + lua_Number n = luaL_checknumber(L, arg); + snprintf(buff, sizeof(buff), form, (double)n); break; } case 'q': { @@ -810,7 +810,7 @@ static int str_format (lua_State *L) { continue; /* skip the `addsize' at the end */ } else { - sprintf(buff, form, s); + snprintf(buff, sizeof(buff), form, s); break; } } diff --git a/src/blua/ltable.c b/src/blua/ltable.c index b21bc4bfa..dc4de9c62 100644 --- a/src/blua/ltable.c +++ b/src/blua/ltable.c @@ -81,6 +81,7 @@ static /*const*/ Node dummynode_ = { /* ** hash for lua_Numbers */ +#if 0 static Node *hashnum (const Table *t, lua_Number n) { unsigned int a[numints]; int i; @@ -90,6 +91,12 @@ static Node *hashnum (const Table *t, lua_Number n) { for (i = 1; i < numints; i++) a[0] += a[i]; return hashmod(t, a[0]); } +#else +// our lua_Number is just typedef´d int32 so no need to do any of the above +static inline Node *hashnum (const Table *t, lua_Number n) { + return hashmod(t, cast(unsigned int, n)); +} +#endif diff --git a/src/blua/luaconf.h b/src/blua/luaconf.h index 76a798751..76ade3bfd 100644 --- a/src/blua/luaconf.h +++ b/src/blua/luaconf.h @@ -536,7 +536,7 @@ #define LUA_NUMBER_SCAN "%d" #define LUA_NUMBER_FMT "%d" #endif -#define lua_number2str(s,n) sprintf((s), LUA_NUMBER_FMT, (n)) +#define lua_number2str(s,n) snprintf((s), LUAI_MAXNUMBER2STR, LUA_NUMBER_FMT, (n)) #define LUAI_MAXNUMBER2STR 12 /* 10 digits, sign, and \0 */ #define lua_str2number(s,p) ({ \ long nmr = strtol((s), (p), 10); \ @@ -772,10 +772,10 @@ union luai_Cast { double l_d; long l_l; }; #include #if defined(__GNUC__) -#define l_likely(x) (__builtin_expect(((x) != 0), 1)) -#define l_unlikely(x) (__builtin_expect(((x) != 0), 0)) +#define l_likely(x) (__builtin_expect(!!(x), 1)) +#define l_unlikely(x) (__builtin_expect(!!(x), 0)) #else -#define l_likely(x) (x) +#define l_likely(x) (x) #define l_unlikely(x) (x) #endif diff --git a/src/blua/lvm.c b/src/blua/lvm.c index 02d2265c1..7afbbd572 100644 --- a/src/blua/lvm.c +++ b/src/blua/lvm.c @@ -28,7 +28,7 @@ -/* limit for table tag-method chains (to avoid loops) */ +/* limit for table tag-method chains (to avoid infinite loops) */ #define MAXTAGLOOP 100 @@ -366,6 +366,7 @@ static void Arith (lua_State *L, StkId ra, TValue *rb, #define arith_op(op,tm) { \ + StkId ra = RA(i); \ TValue *rb = RKB(i); \ TValue *rc = RKC(i); \ if (ttisnumber(rb) && ttisnumber(rc)) { \ @@ -392,7 +393,6 @@ void luaV_execute (lua_State *L, int nexeccalls) { /* main loop of interpreter */ for (;;) { const Instruction i = *pc++; - StkId ra; if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) && (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) { traceexec(L, pc); @@ -402,26 +402,28 @@ void luaV_execute (lua_State *L, int nexeccalls) { } base = L->base; } - /* warning!! several calls may realloc the stack and invalidate `ra' */ - ra = RA(i); lua_assert(base == L->base && L->base == L->ci->base); lua_assert(base <= L->top && L->top <= L->stack + L->stacksize); lua_assert(L->top == L->ci->top || luaG_checkopenop(i)); switch (GET_OPCODE(i)) { case OP_MOVE: { + StkId ra = RA(i); setobjs2s(L, ra, RB(i)); continue; } case OP_LOADK: { + StkId ra = RA(i); setobj2s(L, ra, KBx(i)); continue; } case OP_LOADBOOL: { + StkId ra = RA(i); setbvalue(ra, GETARG_B(i)); if (GETARG_C(i)) pc++; /* skip next instruction (if C) */ continue; } case OP_LOADNIL: { + StkId ra = RA(i); TValue *rb = RB(i); do { setnilvalue(rb--); @@ -429,11 +431,13 @@ void luaV_execute (lua_State *L, int nexeccalls) { continue; } case OP_GETUPVAL: { + StkId ra = RA(i); int b = GETARG_B(i); setobj2s(L, ra, cl->upvals[b]->v); continue; } case OP_GETGLOBAL: { + StkId ra = RA(i); TValue g; TValue *rb = KBx(i); sethvalue(L, &g, cl->env); @@ -442,10 +446,14 @@ void luaV_execute (lua_State *L, int nexeccalls) { continue; } case OP_GETTABLE: { - Protect(luaV_gettable(L, RB(i), RKC(i), ra)); + StkId ra = RA(i); + StkId rb = RB(i); + TValue *rc = RKC(i); + Protect(luaV_gettable(L, rb, rc, ra)); continue; } case OP_SETGLOBAL: { + StkId ra = RA(i); TValue g; sethvalue(L, &g, cl->env); lua_assert(ttisstring(KBx(i))); @@ -453,16 +461,21 @@ void luaV_execute (lua_State *L, int nexeccalls) { continue; } case OP_SETUPVAL: { + StkId ra = RA(i); UpVal *uv = cl->upvals[GETARG_B(i)]; setobj(L, uv->v, ra); luaC_barrier(L, uv, ra); continue; } case OP_SETTABLE: { - Protect(luaV_settable(L, ra, RKB(i), RKC(i))); + StkId ra = RA(i); + TValue *rb = RKB(i); + TValue *rc = RKC(i); + Protect(luaV_settable(L, ra, rb, rc)); continue; } case OP_NEWTABLE: { + StkId ra = RA(i); int b = GETARG_B(i); int c = GETARG_C(i); sethvalue(L, ra, luaH_new(L, luaO_fb2int(b), luaO_fb2int(c))); @@ -470,6 +483,7 @@ void luaV_execute (lua_State *L, int nexeccalls) { continue; } case OP_SELF: { + StkId ra = RA(i); StkId rb = RB(i); setobjs2s(L, ra+1, rb); Protect(luaV_gettable(L, rb, RKC(i), ra)); @@ -488,6 +502,7 @@ void luaV_execute (lua_State *L, int nexeccalls) { continue; } case OP_DIV: { + StkId ra = RA(i); TValue *rb = RKB(i); TValue *rc = RKC(i); if (ttisnumber(rb) && ttisnumber(rc)) { @@ -503,6 +518,7 @@ void luaV_execute (lua_State *L, int nexeccalls) { continue; } case OP_MOD: { + StkId ra = RA(i); TValue *rb = RKB(i); TValue *rc = RKC(i); if (ttisnumber(rb) && ttisnumber(rc)) { @@ -522,26 +538,27 @@ void luaV_execute (lua_State *L, int nexeccalls) { continue; } case OP_BAND: { - arith_op(luai_numand, TM_AND); - continue; + arith_op(luai_numand, TM_AND); + continue; } case OP_BOR: { - arith_op(luai_numor, TM_OR); - continue; + arith_op(luai_numor, TM_OR); + continue; } case OP_BXOR: { - arith_op(luai_numxor, TM_XOR); - continue; + arith_op(luai_numxor, TM_XOR); + continue; } case OP_BSHL: { - arith_op(luai_numshl, TM_SHL); - continue; + arith_op(luai_numshl, TM_SHL); + continue; } case OP_BSHR: { - arith_op(luai_numshr, TM_SHR); - continue; + arith_op(luai_numshr, TM_SHR); + continue; } case OP_BNOT: { + StkId ra = RA(i); TValue *rb = RB(i); if (ttisnumber(rb)) { lua_Number nb = nvalue(rb); @@ -553,6 +570,7 @@ void luaV_execute (lua_State *L, int nexeccalls) { continue; } case OP_UNM: { + StkId ra = RA(i); TValue *rb = RB(i); if (ttisnumber(rb)) { lua_Number nb = nvalue(rb); @@ -564,11 +582,13 @@ void luaV_execute (lua_State *L, int nexeccalls) { continue; } case OP_NOT: { + StkId ra = RA(i); int res = l_isfalse(RB(i)); /* next assignment may change this value */ setbvalue(ra, res); continue; } case OP_LEN: { + StkId ra = RA(i); TValue *rb = RB(i); switch (ttype(rb)) { case LUA_TTABLE: { @@ -626,12 +646,14 @@ void luaV_execute (lua_State *L, int nexeccalls) { continue; } case OP_TEST: { + StkId ra = RA(i); if (l_isfalse(ra) != GETARG_C(i)) dojump(L, pc, GETARG_sBx(*pc)); pc++; continue; } case OP_TESTSET: { + StkId ra = RA(i); TValue *rb = RB(i); if (l_isfalse(rb) != GETARG_C(i)) { setobjs2s(L, ra, rb); @@ -641,6 +663,7 @@ void luaV_execute (lua_State *L, int nexeccalls) { continue; } case OP_CALL: { + StkId ra = RA(i); int b = GETARG_B(i); int nresults = GETARG_C(i) - 1; if (b != 0) L->top = ra+b; /* else previous instruction set top */ @@ -662,6 +685,7 @@ void luaV_execute (lua_State *L, int nexeccalls) { } } case OP_TAILCALL: { + StkId ra = RA(i); int b = GETARG_B(i); if (b != 0) L->top = ra+b; /* else previous instruction set top */ L->savedpc = pc; @@ -694,6 +718,7 @@ void luaV_execute (lua_State *L, int nexeccalls) { } } case OP_RETURN: { + StkId ra = RA(i); int b = GETARG_B(i); if (b != 0) L->top = ra+b-1; if (L->openupval) luaF_close(L, base); @@ -709,6 +734,7 @@ void luaV_execute (lua_State *L, int nexeccalls) { } } case OP_FORLOOP: { + StkId ra = RA(i); lua_Number step = nvalue(ra+2); lua_Number idx = luai_numadd(nvalue(ra), step); /* increment index */ lua_Number limit = nvalue(ra+1); @@ -721,6 +747,7 @@ void luaV_execute (lua_State *L, int nexeccalls) { continue; } case OP_FORPREP: { + StkId ra = RA(i); const TValue *init = ra; const TValue *plimit = ra+1; const TValue *pstep = ra+2; @@ -737,6 +764,7 @@ void luaV_execute (lua_State *L, int nexeccalls) { continue; } case OP_TFORLOOP: { + StkId ra = RA(i); StkId cb = ra + 3; /* call base */ setobjs2s(L, cb+2, ra+2); setobjs2s(L, cb+1, ra+1); @@ -753,6 +781,7 @@ void luaV_execute (lua_State *L, int nexeccalls) { continue; } case OP_SETLIST: { + StkId ra = RA(i); int n = GETARG_B(i); int c = GETARG_C(i); int last; @@ -775,10 +804,12 @@ void luaV_execute (lua_State *L, int nexeccalls) { continue; } case OP_CLOSE: { + StkId ra = RA(i); luaF_close(L, ra); continue; } case OP_CLOSURE: { + StkId ra = RA(i); Proto *p; Closure *ncl; int nup, j; @@ -799,6 +830,7 @@ void luaV_execute (lua_State *L, int nexeccalls) { continue; } case OP_VARARG: { + StkId ra = RA(i); int b = GETARG_B(i) - 1; int j; CallInfo *ci = L->ci; diff --git a/src/byteptr.h b/src/byteptr.h index 0c82e6f40..558235a44 100644 --- a/src/byteptr.h +++ b/src/byteptr.h @@ -206,6 +206,15 @@ FUNCINLINE static ATTRINLINE UINT32 readulong(void *ptr) p += n; \ } while (0) + +#ifdef PHOBOS_BUILD +#define WRITESKIN(p,b) WRITEUINT16(p,b) +#define READSKIN(p) READUINT16(p) +#else +#define WRITESKIN(p,b) WRITEUINT8(p,b) +#define READSKIN(p) READUINT8(p) +#endif + #ifdef __cplusplus } // extern "C" #endif diff --git a/src/command.c b/src/command.c index 0cf1c85ff..3ba7a2972 100644 --- a/src/command.c +++ b/src/command.c @@ -113,18 +113,29 @@ static vsbuf_t com_text; // variable sized buffer * \param ptext The text to add. * \sa COM_BufInsertText */ -void COM_BufAddText(const char *ptext) +void COM_BufAddTextEx(const char *ptext, size_t plen) { size_t l; + char *text; - l = strlen(ptext); + if (plen == 0) + plen = strlen(ptext); + + text = Z_Malloc(sizeof(char) * (plen+1), PU_STATIC, NULL); + memcpy(text, ptext, plen); + text[plen] = '\0'; + + l = strlen(text); if (com_text.cursize + l >= com_text.maxsize) { CONS_Alert(CONS_WARNING, M_GetText("Command buffer full!\n")); return; } - VS_Write(&com_text, ptext, l); + + VS_Write(&com_text, text, l); + + Z_Free(text); } /** Adds command text and executes it immediately. @@ -132,8 +143,10 @@ void COM_BufAddText(const char *ptext) * \param ptext The text to execute. A newline is automatically added. * \sa COM_BufAddText */ -void COM_BufInsertText(const char *ptext) +void COM_BufInsertTextEx(const char *ptext, size_t plen) { + const INT32 old_wait = com_wait; + char *temp = NULL; size_t templen; @@ -145,10 +158,14 @@ void COM_BufInsertText(const char *ptext) VS_Clear(&com_text); } + com_wait = 0; + // add the entire text of the file (or alias) - COM_BufAddText(ptext); + COM_BufAddTextEx(ptext, plen); COM_BufExecute(); // do it right away + com_wait += old_wait; + // add the copied off data if (templen) { @@ -159,8 +176,7 @@ void COM_BufInsertText(const char *ptext) /** Progress the wait timer and flush waiting console commands when ready. */ -void -COM_BufTicker(void) +void COM_BufTicker(void) { if (com_wait) { @@ -237,10 +253,13 @@ void COM_ImmedExecute(const char *ptext) char line[1024] = ""; INT32 quotes; - while (i < strlen(ptext)) + const size_t txtlength = strlen(ptext); + + while (i < txtlength) { quotes = 0; - for (j = 0; i < strlen(ptext); i++,j++) + + for (j = 0; i < txtlength; i++,j++) { if (ptext[i] == '\"' && !quotes && i > 0 && ptext[i-1] != ' ') // Malformed command return; @@ -652,7 +671,7 @@ static void COM_Alias_f(void) CONS_Printf(M_GetText("All aliases that start with \x87'%s'\x80 are:\n"), begin); int count = 0; - for (cmdalias_t *head = com_alias; head->next != NULL; head = head->next) + for (cmdalias_t *head = com_alias; head != NULL; head = head->next) { if (strncmp(begin, head->name, szBegin) == 0) { @@ -673,7 +692,7 @@ static void COM_Alias_f(void) /* Display alias subtext, show all aliases. */ CONS_Printf(M_GetText("alias : create a shortcut command that executes other command(s)\n")); - for (cmdalias_t *head = com_alias; head->next != NULL; head = head->next) + for (cmdalias_t *head = com_alias; head != NULL; head = head->next) { CONS_Printf(alias_format, head->name, head->value); } @@ -1162,6 +1181,39 @@ void VS_Print(vsbuf_t *buf, const char *data) // // ========================================================================= +#define NAME cvar_map_t +#define KEY_TY const char * +#define VAL_TY consvar_t * +#define HASH_FN FNV1a_HashLowercaseString +#define CMPR_FN vt_cmpr_casestring +#include "verstable.h" + +#define NAME netvar_map_t +#define KEY_TY UINT16 +#define VAL_TY consvar_t * +#define HASH_FN vt_hash_integer +#define CMPR_FN vt_cmpr_integer +#include "verstable.h" + +static cvar_map_t cvar_map; +static netvar_map_t netvar_map; + +CONSTRUCTOR static void CV_InitMap(void) +{ + // ensure the map is initialized + cvar_map_t_init(&cvar_map); + cvar_map_t_reserve(&cvar_map, 512); + + netvar_map_t_init(&netvar_map); + netvar_map_t_reserve(&netvar_map, 256); +} + +DESTRUCTOR static void CV_DestroyMap(void) +{ + cvar_map_t_cleanup(&cvar_map); + netvar_map_t_cleanup(&netvar_map); +} + static const char *cv_null_string = ""; /** Searches if a variable has been registered. @@ -1172,11 +1224,17 @@ static const char *cv_null_string = ""; */ consvar_t *CV_FindVar(const char *name) { - consvar_t *cvar; + cvar_map_t_itr it = cvar_map_t_get(&cvar_map, name); + if (!cvar_map_t_is_end(it)) + return it.data->val; + // fallback linear search + /* + consvar_t *cvar; for (cvar = consvar_vars; cvar; cvar = cvar->next) - if (fasticmp(name,cvar->name)) + if (fasticmp(name, cvar->name)) return cvar; + */ return NULL; } @@ -1191,7 +1249,7 @@ consvar_t *CV_FindVar(const char *name) static inline UINT16 CV_ComputeNetid(const char *s) { UINT16 ret = 0, i = 0; - static UINT16 premiers[16] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53}; + static const UINT16 premiers[16] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53}; while (*s) { @@ -1210,11 +1268,17 @@ static inline UINT16 CV_ComputeNetid(const char *s) */ static consvar_t *CV_FindNetVar(UINT16 netid) { + netvar_map_t_itr it = netvar_map_t_get(&netvar_map, netid); + if (!netvar_map_t_is_end(it)) + return it.data->val; + + /* consvar_t *cvar; for (cvar = consvar_vars; cvar; cvar = cvar->next) if (cvar->netid == netid) return cvar; + */ if (netid == 44542) // ouch this hack return &cv_karteliminatelast; @@ -1280,6 +1344,11 @@ void CV_RegisterVar(consvar_t *variable) // the SetValue will set this bit variable->flags &= ~CV_MODIFIED; + + cvar_map_t_insert(&cvar_map, variable->name, variable); + + if (variable->flags & CV_NETVAR) + netvar_map_t_insert(&netvar_map, variable->netid, variable); } /** Finds the string value of a console variable. @@ -1543,7 +1612,9 @@ void CV_SaveNetVars(UINT8 **p, boolean isdemorecording) // send only changed cvars ... // the client will reset all netvars to default before loading WRITEUINT16(*p, 0x0000); + for (cvar = consvar_vars; cvar; cvar = cvar->next) + { if (((cvar->flags & CV_NETVAR) && !CV_IsSetToDefault(cvar)) || (isdemorecording && cvar->netid == cv_numlaps.netid)) { WRITEUINT16(*p, cvar->netid); @@ -1561,7 +1632,7 @@ void CV_SaveNetVars(UINT8 **p, boolean isdemorecording) else { char buf[9]; - sprintf(buf, "%d", mapheaderinfo[gamemap - 1]->numlaps); + snprintf(buf, sizeof(buf), "%d", mapheaderinfo[gamemap - 1]->numlaps); WRITESTRING(*p, buf); } } @@ -1573,6 +1644,8 @@ void CV_SaveNetVars(UINT8 **p, boolean isdemorecording) WRITEUINT8(*p, false); ++count; } + } + WRITEUINT16(count_p, count); } @@ -1585,9 +1658,21 @@ size_t CV_LoadNetVars(const UINT8 *bufstart) // prevent "invalid command received" serverloading = true; + // we can use our netvar map instead of going through all cvars each time + netvar_map_t_itr it; + for (it = netvar_map_t_first(&netvar_map); + !netvar_map_t_is_end(it); + it = netvar_map_t_next(it)) + { + cvar = it.data->val; + Setvalue(cvar, cvar->defaultvalue, true); + } + + /* for (cvar = consvar_vars; cvar; cvar = cvar->next) if (cvar->flags & CV_NETVAR) Setvalue(cvar, cvar->defaultvalue, true); + */ count = READUINT16(p); while (count--) @@ -1717,8 +1802,7 @@ void CV_StealthSet(consvar_t *var, const char *value) void CV_StealthSetValue(consvar_t *var, INT32 value) { char val[32]; - - sprintf(val, "%d", value); + snprintf(val, sizeof(val), "%d", value); CV_SetCVar(var, val, true); } @@ -1738,8 +1822,7 @@ void CV_Set(consvar_t *var, const char *value) void CV_SetValue(consvar_t *var, INT32 value) { char val[32]; - - sprintf(val, "%d", value); + snprintf(val, sizeof(val), "%d", value); CV_SetCVar(var, val, false); } @@ -1790,7 +1873,7 @@ void CV_AddValue(consvar_t *var, INT32 increment) if (newvalue == oldvalue) break; // don't loop forever if there's none of a certain gametype - if (newvalue >= 0 && !mapheaderinfo[newvalue]) + if (newvalue >= 0 && newvalue < NUMMAPS && !mapheaderinfo[newvalue]) continue; // Don't allocate the header. That just makes memory usage skyrocket. } while (!M_CanShowLevelInList(newvalue, gt)); @@ -2137,6 +2220,7 @@ void CV_SaveVariables(FILE *f) consvar_t *cvar; for (cvar = consvar_vars; cvar; cvar = cvar->next) + { if (cvar->flags & CV_SAVE) { char stringtowrite[MAXTEXTCMD+1]; @@ -2145,15 +2229,23 @@ void CV_SaveVariables(FILE *f) if (fastcmp(cvar->string, "MAX") || fastcmp(cvar->string, "MIN")) { if (cvar->flags & CV_FLOAT) - sprintf(stringtowrite, "%f", FixedToFloat(cvar->value)); + { + snprintf(stringtowrite, sizeof(stringtowrite), "%f", FixedToFloat(cvar->value)); + } else - sprintf(stringtowrite, "%d", cvar->value); + { + snprintf(stringtowrite, sizeof(stringtowrite), "%d", cvar->value); + } } else - strcpy(stringtowrite, cvar->string); + { + strncpy(stringtowrite, cvar->string, sizeof(stringtowrite)-1); + stringtowrite[sizeof(stringtowrite)-1] = '\0'; + } fprintf(f, "%s \"%s\"\n", cvar->name, stringtowrite); } + } } //============================================================================ diff --git a/src/command.h b/src/command.h index 7074158e1..bfff2dd11 100644 --- a/src/command.h +++ b/src/command.h @@ -13,13 +13,13 @@ #ifndef __COMMAND_H__ #define __COMMAND_H__ +#include +#include "doomdef.h" + #ifdef __cplusplus extern "C" { #endif -#include -#include "doomdef.h" - //=================================== // Command buffer & command execution //=================================== @@ -52,10 +52,12 @@ size_t COM_FirstOption(void); const char *COM_CompleteCommand(const char *partial, INT32 skips); // insert at queu (at end of other command) -void COM_BufAddText(const char *btext); +#define COM_BufAddText(s) COM_BufAddTextEx(s, 0) +void COM_BufAddTextEx(const char *ptext, size_t plen); // insert in head (before other command) -void COM_BufInsertText(const char *btext); +#define COM_BufInsertText(s) COM_BufInsertTextEx(s, 0) +void COM_BufInsertTextEx(const char *ptext, size_t plen); // don't bother inserting, just do immediately void COM_ImmedExecute(const char *ptext); diff --git a/src/config.h.in b/src/config.h.in index 5225c8b0b..4028ef2f0 100644 --- a/src/config.h.in +++ b/src/config.h.in @@ -11,21 +11,6 @@ #ifdef CMAKECONFIG -// Base SRB2 hashes -#define ASSET_HASH_SRB2_SRB "${SRB2_ASSET_srb2.srb_HASH}" -#ifdef USE_PATCH_DTA -#define ASSET_HASH_PATCH_DTA "${SRB2_ASSET_patch.dta_HASH}" -#endif - -// SRB2Kart-specific hashes -#define ASSET_HASH_GFX_KART "${SRB2_ASSET_gfx.kart_HASH}" -#define ASSET_HASH_TEXTURES_KART "${SRB2_ASSET_textures.kart_HASH}" -#define ASSET_HASH_CHARS_KART "${SRB2_ASSET_chars.kart_HASH}" -#define ASSET_HASH_MAPS_KART "${SRB2_ASSET_maps.kart_HASH}" -#ifdef USE_PATCH_KART -#define ASSET_HASH_PATCH_KART "00000000000000000000000000000000" -#endif - #define SRB2_COMP_REVISION "${SRB2_COMP_REVISION}" #define SRB2_COMP_BRANCH "${SRB2_COMP_BRANCH}" @@ -33,30 +18,10 @@ #else -/* Manually defined asset hashes for non-CMake builds - * Last updated 2015 / 05 / 03 - SRB2 v2.1.15 - srb2.srb - * Last updated 2018 / 12 / 23 - SRB2 v2.1.22 - patch.dta - * Last updated 2019 / 01 / 18 - Kart v1.0.2 - Main assets - * Last updated 2020 / 08 / 30 - Kart v1.3 - patch.kart - * Last updated 2022 / 08 / 16 - Kart v1.4 - Main assets - * Last updated 2022 / 08 / 19 - Kart v1.5 - gfx.kart - * Last updated 2022 / 11 / 01 - Kart v1.6 - gfx.kart, maps.kart - */ +#define SRB2_COMP_REVISION "" +#define SRB2_COMP_BRANCH "" -// Base SRB2 hashes -#define ASSET_HASH_SRB2_SRB "c1b9577687f8a795104aef4600720ea7" -#ifdef USE_PATCH_DTA -#define ASSET_HASH_PATCH_DTA "b04fd9624bfd94dc96dcf4f400f7deb4" -#endif - -// SRB2Kart-specific hashes -#define ASSET_HASH_GFX_KART "06f86ee16136eb8a7043b15001797034" -#define ASSET_HASH_TEXTURES_KART "abb53d56aba47c3a8cb0f764da1c8b80" -#define ASSET_HASH_CHARS_KART "e2c428347dde52858a3dacd29fc5b964" -#define ASSET_HASH_MAPS_KART "d051e55141ba736582228c456953cd98" -#ifdef USE_PATCH_KART -#define ASSET_HASH_PATCH_KART "00000000000000000000000000000000" -#endif +#define CMAKE_ASSETS_DIR "" #endif #endif diff --git a/src/console.c b/src/console.c index 88fe25000..40a3d1700 100644 --- a/src/console.c +++ b/src/console.c @@ -46,23 +46,23 @@ #ifdef HAVE_THREADS I_mutex con_mutex; -// g_in_exiting_signal_handler is an evil hack +// I_In_Exiting_Signal_Handler is an evil hack // to avoid infinite SIGABRT recursion in the signal handler // due to poisoned locks or mach-o kernel not supporting locks in signals // or something like that. idk -# define Lock_state() if (!g_in_exiting_signal_handler) { I_lock_mutex(&con_mutex); } -# define Unlock_state() if (!g_in_exiting_signal_handler) { I_unlock_mutex(con_mutex); } -#else/*HAVE_THREADS*/ +# define Lock_state() if (!I_In_Exiting_Signal_Handler()) { I_lock_mutex(&con_mutex); } +# define Unlock_state() if (!I_In_Exiting_Signal_Handler()) { I_unlock_mutex(con_mutex); } +#else /*HAVE_THREADS*/ # define Lock_state() # define Unlock_state() -#endif/*HAVE_THREADS*/ +#endif /*HAVE_THREADS*/ static boolean con_started = false; // console has been initialised boolean con_startup = false; // true at game startup, screen need refreshing static boolean con_forcepic = true; // at startup toggle console translucency when first off boolean con_recalc = false; // set true when screen size has changed -static tic_t con_tick; // console ticker for anim or blinking prompt cursor +static tic_t con_tick; // console ticker for blinking prompt cursor // con_scrollup should use time (currenttime - lasttime).. static boolean consoletoggle; // true when console key pushed, ticker will handle @@ -103,6 +103,7 @@ static void CON_InputInit(void); static void CON_RecalcSize(void); static void CON_ChangeHeight(void); +static void CONS_height_Change(void); static void CONS_hudlines_Change(void); static void CONS_backcolor_Change(void); @@ -131,7 +132,7 @@ static CV_PossibleValue_t speed_cons_t[] = {{0, "MIN"}, {64, "MAX"}, {0, NULL}}; static consvar_t cons_speed = {"con_speed", "8", CV_SAVE, speed_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; // percentage of screen height to use for console -static consvar_t cons_height = {"con_height", "50", CV_SAVE, CV_Unsigned, NULL, 0, NULL, NULL, 0, 0, NULL}; +static consvar_t cons_height = {"con_height", "50", CV_CALL|CV_SAVE, CV_Unsigned, CONS_height_Change, 0, NULL, NULL, 0, 0, NULL}; static CV_PossibleValue_t backpic_cons_t[] = {{0, "translucent"}, {1, "picture"}, {0, NULL}}; // whether to use console background picture, or translucent mode @@ -173,6 +174,18 @@ consvar_t cons_consoleprintinmenu = {"consoleprintinmenu", "Off", CV_SAVE, CV_On static void CON_Print(char *msg); +// Change the console height on demand +// +static void CONS_height_Change(void) +{ + Lock_state(); + + if (con_destlines > 0 && !con_startup) // If the console is open (as in, not using "bind")... + CON_ChangeHeight(); // ...update its height now, not only when it's closed and re-opened + + Unlock_state(); +} + // // static void CONS_hudlines_Change(void) @@ -208,14 +221,6 @@ static void CONS_Clear_f(void) Unlock_state(); } -// Choose english keymap -// -/*static void CONS_English_f(void) -{ - shiftxform = english_shiftxform; - CONS_Printf(M_GetText("%s keymap.\n"), M_GetText("English")); -}*/ - static char *bindtable[NUMINPUTS]; static void CONS_Bind_f(void) @@ -633,72 +638,191 @@ void CON_MoveConsole(void) Unlock_state(); } +//====================================================================== +// KEYBOARD LAYOUTS FOR ENTERING TEXT +//====================================================================== + +static char english_shiftxform[] = +{ + 0, + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, + 31, + ' ', '!', '"', '#', '$', '%', '&', + '"', // shift-' + '(', ')', '*', '+', + '<', // shift-, + '_', // shift-- + '>', // shift-. + '?', // shift-/ + ')', // shift-0 + '!', // shift-1 + '@', // shift-2 + '#', // shift-3 + '$', // shift-4 + '%', // shift-5 + '^', // shift-6 + '&', // shift-7 + '*', // shift-8 + '(', // shift-9 + ':', + ':', // shift-; + '<', + '+', // shift-= + '>', '?', '@', + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', + 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', + '{', // shift-[ + '|', // shift-backslash - OH MY GOD DOES WATCOM SUCK + '}', // shift-] + '"', '_', + '~', // shift-` + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', + 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', + '{', '|', '}', '~', 127 +}; + +static char french_shiftxform[] = +{ + 0, + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, + 31, + ' ','$', //shift-! + '3', //shift-" + '#', '$', '%', + '1', //shift-& + '4', // shift-' + '5', // shift-( + ')', // shift-) + '*', '+', + '?', // shift-, + '6', // shift-- + '.', '/', + '0', '1', '2', '3', '4', '5', + '6', '7', '8', '9', + '/', // shitf-: + '.', // shift-; + '>', // shift-< + '+', // shift-= + '>', '?', '@', + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', + 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', + '[', '\\', ']', '^', + '8', //shift-_ + '`', + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', + 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', + '{', '|', '}', '~', 127, + 128, 129, + '2', + 131, 132, + '0', + 134, + '9', + 136, 137, + '7', + 139, 140, + '%' +}; + +static char french_altgrxform[] = +{ + 0, + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, + 31, + ' ', '!', + '#', //altgr-" + '#', '$', '%', '&', + '{', //altgr-' + '[', //altgr-( + ']', //altgr-) + '*', '+', ',', + '|', //altg-- + '.', '/', + '0', '1', '2', '3', '4', '5', + '6', '7', '8', '9', + ':', ';', '<', + '}', //altgr-= + '>', '?', '@', + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', + 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', + '[', '\\', ']', '^', + '\\', //altgr-backslash + '`', + 'a', 'b', 'c', 'd', 'E', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', + 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', + '{', '|', '}', '~', 127, + 128, 129, + '~', + 131, 132, + '@', + 134, + '^', + 136, 137, + '`', + 139, 140, + KEY_FR_U_GRAVE +}; + +// fallback for special letter non displayable in the game (i.e.: 'é','à',etc.) +static INT32 CON_FallBackFrSpecialLetter(INT32 key) +{ + switch (key) + { + case KEY_FR_E_AIGUE: return 'e'; + case KEY_FR_E_GRAVE: return 'e'; + case KEY_FR_C_CEDILLE: return 'c'; + case KEY_FR_A_GRAVE: return 'a'; + case KEY_FR_U_GRAVE: return 'u'; + default: return key; + } +} + +// goddang AZERTY +static size_t CON_GetShiftSize(void) +{ + return ((cv_keyboardlayout.value == 3) ? sizeof(french_shiftxform) : sizeof(english_shiftxform)); +} + +static char *CON_Shiftform(void) +{ + return (cv_keyboardlayout.value == 3) ? french_shiftxform : english_shiftxform; +} + INT32 CON_ShiftChar(INT32 ch) { - if (I_UseNativeKeyboard()) + if (I_UseNativeKeyboard() || ch >= (INT32)CON_GetShiftSize()) return ch; + // warning: shiftdown is NOT a boolean, it's 1 or 2 for lshift/rshift if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { - if (cv_keyboardlayout.value == 3) - { - if (shiftdown ^ capslock) - ch = shiftxform[ch]; - else if (altdown & 0x2) - ch = french_altgrxform[ch]; - else - ch = HU_FallBackFrSpecialLetter(ch); - } - else - { - if (shiftdown ^ capslock) - ch = shiftxform[ch]; - } + return !!shiftdown != capslock ? CON_Shiftform()[ch] : ch; } - else // if we're holding shift we should still shift non letter symbols + + // if we're holding shift we should still shift non letter symbols + if (shiftdown) { - if (cv_keyboardlayout.value == 3) - { - if (shiftdown) - ch = shiftxform[ch]; - else if (altdown & 0x2) - ch = french_altgrxform[ch]; - else - ch = HU_FallBackFrSpecialLetter(ch); - } - else - { - if (shiftdown) - ch = shiftxform[ch]; - } + return CON_Shiftform()[ch]; + } + + // AZERTY + if (cv_keyboardlayout.value == 3) + { + if (altdown & 0x2) + return french_altgrxform[ch]; + + return CON_FallBackFrSpecialLetter(ch); } return ch; } -INT32 CON_ShitAndAltGrChar(INT32 ch) -{ - if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) - { - if (shiftdown ^ capslock) - ch = shiftxform[ch]; - } - else // if we're holding shift we should still shift non letter symbols - { - if (shiftdown) - ch = shiftxform[ch]; - else if (altdown & 0x2) - { - ch = french_altgrxform[ch]; - } - else - { - ch = HU_FallBackFrSpecialLetter(ch); - } - } - - return ch; -} // Clear time of console heads up messages // @@ -892,7 +1016,7 @@ boolean CON_Responder(event_t *ev) return true; // ctrl modifier -- changes behavior, adds shortcuts - if ((cv_keyboardlayout.value != 3 && ctrldown) || (cv_keyboardlayout.value == 3 && ctrldown && !altdown)) + if (ctrldown && (cv_keyboardlayout.value != 3 || !altdown)) { // show all cvars/commands that match what we have inputted if (key == KEY_TAB) @@ -1222,19 +1346,10 @@ void CON_LogMessage(const char *msg) // Console print! Wahooo! Lots o fun! // -void CONS_Printf(const char *fmt, ...) +static inline void CONS_PrintMsg(char *txt) { - va_list argptr; - static char *txt = NULL; boolean startup; - if (txt == NULL) - txt = malloc(8192); - - va_start(argptr, fmt); - vsnprintf(txt, 8192, fmt, argptr); - va_end(argptr); - // echo console prints to log file DEBFILE(txt); @@ -1260,6 +1375,21 @@ void CONS_Printf(const char *fmt, ...) } } +void CONS_Printf(const char *fmt, ...) +{ + va_list argptr; + static char *txt = NULL; + + if (txt == NULL) + txt = malloc(8192); + + va_start(argptr, fmt); + vsnprintf(txt, 8192, fmt, argptr); + va_end(argptr); + + CONS_PrintMsg(txt); +} + void CONS_Alert(alerttype_t level, const char *fmt, ...) { va_list argptr; @@ -1288,9 +1418,7 @@ void CONS_Alert(alerttype_t level, const char *fmt, ...) break; } - // I am lazy and I feel like just letting CONS_Printf take care of things. - // Is that okay? - CONS_Printf("%s", txt); + CONS_PrintMsg(txt); } void CONS_Debug(INT32 debugflags, const char *fmt, ...) @@ -1308,11 +1436,9 @@ void CONS_Debug(INT32 debugflags, const char *fmt, ...) vsnprintf(txt, 8192, fmt, argptr); va_end(argptr); - // Again I am lazy, oh well - CONS_Printf("%s", txt); + CONS_PrintMsg(txt); } - // Print an error message, and wait for ENTER key to continue. // To make sure the user has seen the message // @@ -1324,6 +1450,8 @@ void CONS_Error(const char *msg) // dirty quick hack, but for the good cause while (I_GetKey() != KEY_ENTER) { + I_HandleInterrupt(); + // Sleep so we don't take too much of cpu usage I_Sleep(1.f/TICRATE*1000); @@ -1522,53 +1650,54 @@ static void CON_DrawConsole(void) } // draw console text lines from top to bottom - if (con_curlines < minheight) - return; - - i = con_cy - con_scrollup; - - // skip the last empty line due to the cursor being at the start of a new line - i--; - - i -= (con_curlines - minheight) / charheight; - - if (rendermode == render_none) return; - - for (y = (con_curlines-minheight) % charheight; y <= con_curlines-minheight; y += charheight, i++) + if (con_curlines >= minheight) { - INT32 x; - size_t c; + i = con_cy - con_scrollup; - p = (UINT8 *)&con_buffer[((i > 0 ? i : 0)%con_totallines)*con_width]; + // skip the last empty line due to the cursor being at the start of a new line + i--; - for (c = 0, x = charwidth; c < con_width; c++, x += charwidth, p++) + i -= (con_curlines - minheight) / charheight; + + if (rendermode == render_none) + return; + + for (y = (con_curlines-minheight) % charheight; y <= con_curlines-minheight; y += charheight, i++) { - while (*p & 0x80) + INT32 x; + size_t c; + + p = (UINT8 *)&con_buffer[((i > 0 ? i : 0)%con_totallines)*con_width]; + + for (c = 0, x = charwidth; c < con_width; c++, x += charwidth, p++) { - charflags = (*p & 0x7f) << V_CHARCOLORSHIFT; - p++; - c++; + while (*p & 0x80) + { + charflags = (*p & 0x7f) << V_CHARCOLORSHIFT; + p++; + c++; + } + + if (c >= con_width) + break; + + int emotelen; + emote_t *emote; + + if ((emote = M_VerifyEmote((const char *)p, &emotelen))) + { + M_DrawScaledEmote(x<= con_width) - break; - - int emotelen; - emote_t *emote; - - if ((emote = M_VerifyEmote((const char *)p, &emotelen))) - { - M_DrawScaledEmote(x<= minheight) && !con_startup) + if ((con_curlines >= (minheight-charheight)) && !con_startup) CON_DrawInput(); } diff --git a/src/console.h b/src/console.h index a16ef47b6..abb506609 100644 --- a/src/console.h +++ b/src/console.h @@ -13,6 +13,10 @@ #ifndef __CONSOLE__ #define __CONSOLE__ +#ifdef __cplusplus +extern "C" { +#endif + #include "d_event.h" #include "command.h" #include "i_threads.h" @@ -45,7 +49,6 @@ extern UINT8 *yellowmap, *purplemap, *greenmap, *bluemap, *graymap, *redmap, *or extern UINT8 *consolebgmap; INT32 CON_ShiftChar(INT32 ch); -INT32 CON_ShitAndAltGrChar(INT32 ch); void CON_SetupBackColormap(void); void CON_ClearHUD(void); // clear heads up messages @@ -63,4 +66,8 @@ boolean CON_Ready(void); void CON_LogMessage(const char *msg); +#ifdef __cplusplus +} // extern "C" +#endif + #endif diff --git a/src/core/memory.cpp b/src/core/memory.cpp index 9e591e78c..e0289a579 100644 --- a/src/core/memory.cpp +++ b/src/core/memory.cpp @@ -1,7 +1,7 @@ -// BLANKART +// DR. ROBOTNIK'S RING RACERS //----------------------------------------------------------------------------- -// Copyright (C) 2024 by Ronald "Eidolon" Kinard -// Copyright (C) 2024 by Kart Krew +// Copyright (C) 2025 by Ronald "Eidolon" Kinard +// Copyright (C) 2025 by Kart Krew // // This program is free software distributed under the // terms of the GNU General Public License, version 2. @@ -114,6 +114,7 @@ void* PoolAllocator::allocate() FreeBlock* ret = head_; head_ = head_->next; + allocated_blocks_++; return ret; } @@ -125,6 +126,7 @@ void PoolAllocator::deallocate(void* p) FreeBlock* block = reinterpret_cast(p); block->next = head_; head_ = block; + allocated_blocks_--; } void PoolAllocator::release() @@ -144,6 +146,7 @@ void PoolAllocator::release() first_chunk_ = nullptr; head_ = nullptr; + allocated_blocks_ = 0; } static LinearMemory g_frame_memory {4 * 1024 * 1024}; diff --git a/src/core/memory.h b/src/core/memory.h index 77e7206b5..14b51a039 100644 --- a/src/core/memory.h +++ b/src/core/memory.h @@ -1,7 +1,7 @@ -// SONIC ROBO BLAST 2 KART +// DR. ROBOTNIK'S RING RACERS //----------------------------------------------------------------------------- -// Copyright (C) 2024 by Ronald "Eidolon" Kinard -// Copyright (C) 2024 by Kart Krew +// Copyright (C) 2025 by Ronald "Eidolon" Kinard +// Copyright (C) 2025 by Kart Krew // // This program is free software distributed under the // terms of the GNU General Public License, version 2. @@ -37,6 +37,7 @@ class PoolAllocator final FreeBlock* head_; size_t block_size_; size_t blocks_; + size_t allocated_blocks_; int32_t tag_; ChunkFooter* allocate_chunk(); @@ -47,6 +48,7 @@ public: , head_(nullptr) , block_size_(block_size) , blocks_(blocks) + , allocated_blocks_(0) , tag_(tag) {} PoolAllocator(const PoolAllocator&) = delete; @@ -59,6 +61,8 @@ public: void* allocate(); void deallocate(void* p); constexpr size_t block_size() const noexcept { return block_size_; }; + constexpr size_t allocated_blocks() const noexcept { return allocated_blocks_; }; + constexpr size_t allocated_bytes() const noexcept { return allocated_blocks_ * block_size_; }; void release(); }; diff --git a/src/core/static_vec.hpp b/src/core/static_vec.hpp index c1f486a2b..f31f17939 100644 --- a/src/core/static_vec.hpp +++ b/src/core/static_vec.hpp @@ -1,7 +1,7 @@ -// SONIC ROBO BLAST 2 KART +// DR. ROBOTNIK'S RING RACERS //----------------------------------------------------------------------------- -// Copyright (C) 2024 by Ronald "Eidolon" Kinard -// Copyright (C) 2024 by Kart Krew +// Copyright (C) 2025 by Ronald "Eidolon" Kinard +// Copyright (C) 2025 by Kart Krew // // This program is free software distributed under the // terms of the GNU General Public License, version 2. diff --git a/src/core/thread_pool.cpp b/src/core/thread_pool.cpp index 11aa6f1bb..c716b6470 100644 --- a/src/core/thread_pool.cpp +++ b/src/core/thread_pool.cpp @@ -1,7 +1,7 @@ -// BLANKART +// DR. ROBOTNIK'S RING RACERS //----------------------------------------------------------------------------- -// Copyright (C) 2024 by Ronald "Eidolon" Kinard -// Copyright (C) 2024 by Kart Krew +// Copyright (C) 2025 by Ronald "Eidolon" Kinard +// Copyright (C) 2025 by Kart Krew // // This program is free software distributed under the // terms of the GNU General Public License, version 2. diff --git a/src/core/thread_pool.h b/src/core/thread_pool.h index 71eebdaf1..0c1fc88ad 100644 --- a/src/core/thread_pool.h +++ b/src/core/thread_pool.h @@ -1,7 +1,7 @@ -// SONIC ROBO BLAST 2 KART +// DR. ROBOTNIK'S RING RACERS //----------------------------------------------------------------------------- -// Copyright (C) 2024 by Ronald "Eidolon" Kinard -// Copyright (C) 2024 by Kart Krew +// Copyright (C) 2025 by Ronald "Eidolon" Kinard +// Copyright (C) 2025 by Kart Krew // // This program is free software distributed under the // terms of the GNU General Public License, version 2. diff --git a/src/d_clisrv.c b/src/d_clisrv.c index fa1536e72..5a87b6da0 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -100,13 +100,17 @@ static int map_icon_request_count; // current count of icon requests sent static UINT8 *map_icon_data; static patch_t *map_icon; +// if true, signals the game to only load addons AND gamestate +// instead of fully joining a server +static boolean cl_addonsonly = false; + plrinfo playerinfo[MAXPLAYERS] = {}; SINT8 joinnode = 0; // used for CL_VIEWSERVER boolean player_muted[MAXPLAYERS] = {}; // Server specific vars -UINT8 playernode[MAXPLAYERS] = {}; +UINT8 playernode[MAXPLAYERS] = {UINT8_MAX}; // Minimum timeout for sending the savegame // The actual timeout will be longer depending on the savegame length @@ -121,6 +125,7 @@ static tic_t freezetimeout[MAXNETNODES]; // Until when can this node freeze the UINT16 pingmeasurecount = 1; UINT32 realpingtable[MAXPLAYERS] = {}; //the base table of ping where an average will be sent to everyone. UINT32 playerpingtable[MAXPLAYERS] = {}; //table of player latency values. +UINT32 localplayerping = 0; #define GENTLEMANSMOOTHING (TICRATE) static tic_t reference_lag = 0; @@ -173,11 +178,11 @@ static UINT16 resynch_delay[MAXNETNODES]; // delay time before the player can be static UINT32 resynch_status[MAXNETNODES]; // 0 bit means synched for that player, 1 means possibly desynched static UINT8 resynch_sent[MAXNETNODES][MAXPLAYERS]; // what synch packets have we attempted to send to the player static UINT8 resynch_inprogress[MAXNETNODES]; -static UINT8 resynch_local_inprogress = false; // WE are desynched and getting packets to fix it. -UINT8 hu_resynching = 0; +static boolean resynch_local_inprogress = false; // WE are desynched and getting packets to fix it. +boolean hu_resynching = false; #ifdef SATURNPAK -UINT8 hu_redownloadinggamestate = 0; +boolean hu_redownloadinggamestate = false; static UINT8 gamestate_resend_counter[MAXNETNODES]; #endif @@ -192,7 +197,7 @@ static UINT8 mynode; // my address pointofview server #ifdef SATURNPAK static boolean cl_redownloadinggamestate = false; -boolean is_client_saturn[MAXNETNODES]; +static boolean is_client_saturn[MAXNETNODES]; #endif #ifdef SATURNJOIN @@ -212,14 +217,9 @@ tic_t firstconnectattempttime = 0; // engine -// Must be a power of two -#define TEXTCMD_HASH_SIZE 4 - typedef struct textcmdtic_s { - tic_t tic; UINT8 *playercmds[MAXPLAYERS]; - struct textcmdtic_s *next; } textcmdtic_t; typedef struct textcmdbuf_s textcmdbuf_t; @@ -234,7 +234,7 @@ static textcmdbuf_t *textcmdbuf[MAXSPLITSCREENPLAYERS] = {NULL}; static ticcmd_t playercmds[MAXPLAYERS]; ticcmd_t netcmds[BACKUPTICS][MAXPLAYERS] = {}; -static textcmdtic_t *textcmds[TEXTCMD_HASH_SIZE] = {NULL}; +static textcmdtic_t *textcmds[BACKUPTICS] = {NULL}; consvar_t cv_showjoinaddress = {"showjoinaddress", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; @@ -332,7 +332,7 @@ void RegisterNetXCmd(netxcmd_t id, void (*cmd_f)(const UINT8 **p, INT32 playernu #ifdef PARANOIA if (id >= MAXNETXCMD) I_Error("Command id %d too big", id); - if (listnetxcmd[id] != 0) + if (listnetxcmd[id] != NULL) I_Error("Command id %d already used", id); #endif listnetxcmd[id] = cmd_f; @@ -357,15 +357,16 @@ void SendNetXCmdForPlayer(UINT8 playerid, netxcmd_t id, const void *param, size_ if (2+nparam > MAXTEXTCMD) { - CONS_Alert(CONS_ERROR, M_GetText("packet too large to fit NetXCmd, cannot add netcmd %d! (size: %s, max: %d)\n"), id, sizeu1(2+nparam), MAXTEXTCMD); + CONS_Alert(CONS_ERROR, M_GetText("packet too large to fit NetXCmd, cannot add netcmd %s with id %d! (size: %s, max: %d)\n"), netxcmdnames[id-1], id, sizeu1(2+nparam), MAXTEXTCMD); return; } // for future reference: if (cv_debug) != debug disabled. - CONS_Alert(CONS_NOTICE, M_GetText("NetXCmd buffer full, delaying netcmd %d... (size: %d, needed: %s)\n"), id, localtextcmd[playerid][0], sizeu1(nparam)); + CONS_Alert(CONS_NOTICE, M_GetText("NetXCmd buffer full, delaying netcmd %s with id %d... (size: %d, needed: %s)\n"), netxcmdnames[id-1], id, localtextcmd[playerid][0], sizeu1(nparam)); + if (buf == NULL) { - textcmdbuf[playerid] = Z_Malloc(sizeof(textcmdbuf_t), PU_STATIC, NULL); + textcmdbuf[playerid] = (textcmdbuf_t*)Z_Malloc(sizeof(textcmdbuf_t), PU_STATIC, NULL); textcmdbuf[playerid]->cmd[0] = 0; textcmdbuf[playerid]->next = NULL; WriteNetXCmd(textcmdbuf[playerid]->cmd, id, param, nparam); @@ -377,7 +378,7 @@ void SendNetXCmdForPlayer(UINT8 playerid, netxcmd_t id, const void *param, size_ if (buf->cmd[0]+2+nparam > MAXTEXTCMD) { - buf->next = Z_Malloc(sizeof(textcmdbuf_t), PU_STATIC, NULL); + buf->next = (textcmdbuf_t*)Z_Malloc(sizeof(textcmdbuf_t), PU_STATIC, NULL); buf->next->cmd[0] = 0; buf->next->next = NULL; WriteNetXCmd(buf->next->cmd, id, param, nparam); @@ -396,20 +397,10 @@ void SendNetXCmdForPlayer(UINT8 playerid, netxcmd_t id, const void *param, size_ // Frees all textcmd memory for the specified tic static void D_FreeTextcmd(tic_t tic) { - textcmdtic_t **tctprev = &textcmds[tic & (TEXTCMD_HASH_SIZE - 1)]; - textcmdtic_t *textcmdtic = *tctprev; - - while (textcmdtic && textcmdtic->tic != tic) - { - tctprev = &textcmdtic->next; - textcmdtic = textcmdtic->next; - } + textcmdtic_t *textcmdtic = textcmds[tic%BACKUPTICS]; if (textcmdtic) { - // Remove this tic from the list. - *tctprev = textcmdtic->next; - // Free all players. for (INT32 i = 0; i < MAXPLAYERS; i++) { @@ -418,14 +409,14 @@ static void D_FreeTextcmd(tic_t tic) // Free this tic's own memory. Z_Free(textcmdtic); + textcmds[tic%BACKUPTICS] = NULL; } } // Gets the buffer for the specified ticcmd, or NULL if there isn't one static UINT8* D_GetExistingTextcmd(tic_t tic, INT32 playernum) { - textcmdtic_t *textcmdtic = textcmds[tic & (TEXTCMD_HASH_SIZE - 1)]; - while (textcmdtic && textcmdtic->tic != tic) textcmdtic = textcmdtic->next; + textcmdtic_t *textcmdtic = textcmds[tic%BACKUPTICS]; // Do we have an entry for the tic? If so, look for player. if (textcmdtic) @@ -441,26 +432,15 @@ static UINT8* D_GetExistingTextcmd(tic_t tic, INT32 playernum) // Gets the buffer for the specified ticcmd, creating one if necessary static UINT8* D_GetTextcmd(tic_t tic, INT32 playernum) { - textcmdtic_t *textcmdtic = textcmds[tic & (TEXTCMD_HASH_SIZE - 1)]; - textcmdtic_t **tctprev = &textcmds[tic & (TEXTCMD_HASH_SIZE - 1)]; - - // Look for the tic. - while (textcmdtic && textcmdtic->tic != tic) - { - tctprev = &textcmdtic->next; - textcmdtic = textcmdtic->next; - } + textcmdtic_t *textcmdtic = textcmds[tic%BACKUPTICS]; // If we don't have an entry for the tic, make it. if (!textcmdtic) - { - textcmdtic = *tctprev = Z_Calloc(sizeof (textcmdtic_t), PU_STATIC, NULL); - textcmdtic->tic = tic; - } + textcmds[tic%BACKUPTICS] = textcmdtic = (textcmdtic_t*)Z_Calloc(sizeof(textcmdtic_t), PU_STATIC, NULL); // If we don't have an entry for the player, make it. if (!textcmdtic->playercmds[playernum]) - textcmdtic->playercmds[playernum] = Z_Calloc(MAXTEXTCMD, PU_STATIC, NULL); + textcmdtic->playercmds[playernum] = (UINT8*)Z_Calloc(MAXTEXTCMD, PU_STATIC, NULL); return textcmdtic->playercmds[playernum]; } @@ -540,9 +520,8 @@ void D_ResetTiccmds(void) } // Reset the net command list - for (i = 0; i < TEXTCMD_HASH_SIZE; i++) - while (textcmds[i]) - D_Clearticcmd(textcmds[i]->tic); + for (i = 0; i < BACKUPTICS; i++) + D_Clearticcmd(i); } void SendKick(UINT8 playernum, UINT8 msg) @@ -862,11 +841,13 @@ static void resynch_write_ctf(resynchend_pak *rst) rst->flagplayer[i] = (SINT8)j; break; } + if (j == MAXPLAYERS) // fine, no I_Error { CONS_Alert(CONS_ERROR, "One of the flags has gone completely missing...\n"); rst->flagplayer[i] = -2; } + continue; } @@ -1141,10 +1122,10 @@ typedef enum static void GetPackets(void); static cl_mode_t cl_mode = CL_SEARCHING; -static UINT16 cl_lastcheckedfilecount = 0; // used for full file list +static UINT16 cl_lastcheckedfilecount = 0; // used for full file list // Player name send/load - +#ifndef PHOBOS_BUILD static void CV_SavePlayerNames(UINT8 **p) { INT32 i = 0; @@ -1156,6 +1137,7 @@ static void CV_SavePlayerNames(UINT8 **p) WRITEUINT8(*p, 0); continue; } + WRITESTRING(*p, player_names[i]); } } @@ -1169,20 +1151,85 @@ static void CV_LoadPlayerNames(UINT8 **p) for (; i < MAXPLAYERS; ++i) { READSTRING(*p, tmp_name); + if (tmp_name[0] == 0) continue; + if (tmp_name[MAXPLAYERNAME]) // overflow detected I_Error("Received bad server config packet when trying to join"); + memcpy(player_names[i], tmp_name, MAXPLAYERNAME+1); } } +#endif + +static void CL_DrawAddonTypes(void) +{ + if (!cv_serveraddoninfo.value) + return; + + INT32 y = 0; + + INT32 addontypes_downloaded[NUMADDONTYPES] = {0}; + + for (INT32 i = 0; i < fileneedednum; ++i) + { + switch (fileneeded[i].status) + { + case FS_FOUND: + case FS_OPEN: + addontypes_downloaded[fileneeded[i].type]++; + break; + + default: + break; + } + } + + for (addontype_t type = 0; type < NUMADDONTYPES; ++type) + { + if (addontypes[type] == 0) + continue; + + INT32 flags = V_SNAPTOTOP|V_SNAPTOLEFT|V_ALLOWLOWERCASE; + + if (addontypes[type] == addontypes_downloaded[type]) + flags |= V_GREENMAP; + else + flags |= V_YELLOWMAP; + + const char *typestr = "Misc"; + + switch (type) + { + case ADDON_SCRIPT: + typestr = "Script"; + break; + + case ADDON_MAP: + typestr = "Map"; + break; + + case ADDON_CHARACTER: + typestr = "Character"; + break; + + default: + break; + } + + V_DrawSmallString(4, 4 + y, flags, va("%s addons", typestr)); + V_DrawRightAlignedSmallString(100, 4 + y, flags, va("%d/%d", addontypes_downloaded[type], addontypes[type])); + y += 6; + } +} // // CL_DrawConnectionStatus // // Keep the local client informed of our status. // -static inline void CL_DrawConnectionStatus(void) +static void CL_DrawConnectionStatus(void) { INT32 ccstime = I_GetTime(); @@ -1217,24 +1264,24 @@ static inline void CL_DrawConnectionStatus(void) case CL_DOWNLOADSAVEGAME: if (filedownload.current != -1) { - UINT32 currentsize = fileneeded[filedownload.current].currentsize; - UINT32 totalsize = fileneeded[filedownload.current].totalsize; - INT32 dldlength; + UINT32 dldlength = 0; + fileneeded_t *file = &fileneeded[filedownload.current]; + UINT32 totalsize = file->totalsize; + UINT32 currentsize = min(file->currentsize, totalsize); cltext = M_GetText("Downloading game state..."); Net_GetNetStat(); - dldlength = (INT32)((currentsize/(double)totalsize) * 256); - if (dldlength > 256) - dldlength = 256; + if (totalsize != 0) + dldlength = (UINT32)((currentsize/(double)totalsize) * 256); V_DrawFill(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, 256, 8, 111); - V_DrawFill(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, dldlength, 8, 96); + V_DrawFill(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, (INT32)dldlength, 8, 96); V_DrawString(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, V_20TRANS|V_MONOSPACE, - va(" %4uK/%4uK",currentsize>>10,totalsize>>10)); + va(" %4uK/%4uK", currentsize>>10, totalsize>>10)); V_DrawRightAlignedString(BASEVIDWIDTH/2+128, BASEVIDHEIGHT-24, V_20TRANS|V_MONOSPACE, - va("%3.1fK/s ", ((double)getbps)/1024)); + va("%3.1fK/s ", ((double)getbps)/1024.0)); } else cltext = M_GetText("Waiting to download game state..."); @@ -1270,29 +1317,32 @@ static inline void CL_DrawConnectionStatus(void) { if (cl_mode == CL_CHECKFILES) { - INT32 totalfileslength; + INT32 totalfileslength = 0; INT32 checkednum = 0; INT32 i; V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-24, V_YELLOWMAP|MENUCAPS, "Press ESC to abort"); - //ima just count files here + // ima just count files here for (i = 0; i < fileneedednum; i++) if (fileneeded[i].status != FS_NOTCHECKED) checkednum++; // Loading progress V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-32, V_YELLOWMAP|MENUCAPS, "Checking server addons..."); - totalfileslength = (INT32)((checkednum/(double)(fileneedednum)) * 256); + if (fileneedednum != 0) + totalfileslength = (INT32)((checkednum/(double)fileneedednum) * 256); M_DrawTextBox(BASEVIDWIDTH/2-128-8, BASEVIDHEIGHT-24-8, 32, 1); V_DrawFill(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, 256, 8, 175); V_DrawFill(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, totalfileslength, 8, 160); V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24, V_20TRANS|V_MONOSPACE|MENUCAPS, - va(" %2u/%2u Files",checkednum,fileneedednum)); + va(" %2u/%2u Files", checkednum, fileneedednum)); + + CL_DrawAddonTypes(); } else if (cl_mode == CL_LOADFILES) { - INT32 totalfileslength; + INT32 totalfileslength = 0; INT32 loadcompletednum = 0; INT32 i; @@ -1305,12 +1355,15 @@ static inline void CL_DrawConnectionStatus(void) // Loading progress V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-32, V_YELLOWMAP|MENUCAPS, "Loading server addons..."); - totalfileslength = (INT32)((loadcompletednum/(double)(fileneedednum)) * 256); + if (fileneedednum != 0) + totalfileslength = (INT32)((loadcompletednum/(double)fileneedednum) * 256); M_DrawTextBox(BASEVIDWIDTH/2-128-8, BASEVIDHEIGHT-24-8, 32, 1); V_DrawFill(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, 256, 8, 175); V_DrawFill(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, totalfileslength, 8, 160); V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24, V_20TRANS|V_MONOSPACE|MENUCAPS, - va(" %2u/%2u Files",loadcompletednum,fileneedednum)); + va(" %2u/%2u Files", loadcompletednum, fileneedednum)); + + CL_DrawAddonTypes(); } else if (cl_mode == CL_VIEWSERVER) { @@ -1403,6 +1456,7 @@ static inline void CL_DrawConnectionStatus(void) if (playerinfo[i].node < 255) { strncpy(player_name, playerinfo[i].name, MAXPLAYERNAME); + player_name[MAXPLAYERNAME] = '\0'; // if we get a skin color // try to colourize the player name @@ -1434,35 +1488,40 @@ static inline void CL_DrawConnectionStatus(void) // Buttons V_DrawFill(8, BASEVIDHEIGHT - 14, BASEVIDWIDTH - 16, 12, 239); V_DrawThinString(16, BASEVIDHEIGHT - 12, V_ALLOWLOWERCASE, va("[%sESC%s] = Abort", "\x82", "\x80")); + V_DrawCenteredThinString(BASEVIDWIDTH/2, BASEVIDHEIGHT - 12, V_ALLOWLOWERCASE, va("[%sSPACE%s] = Load Addons", "\x82", "\x80")); V_DrawRightAlignedThinString(BASEVIDWIDTH - 12, BASEVIDHEIGHT - 12, V_ALLOWLOWERCASE, va("[%sENTER%s] = Join", "\x82", "\x80")); } else if (filedownload.current != -1) { - INT32 dldlength; - INT32 totalfileslength; - UINT32 totaldldsize; + UINT32 dldlength = 0; + UINT32 totaldldsize = 0; + UINT32 totalfileslength = 0; static char tempname[28]; fileneeded_t *file = &fileneeded[filedownload.current]; char *filename = file->filename; + UINT32 totalsize = file->totalsize; + UINT32 currentsize = min(file->currentsize, totalsize); + UINT32 fdtotalsize = filedownload.totalsize; // Draw the bottom box. M_DrawTextBox(BASEVIDWIDTH/2-128-8, BASEVIDHEIGHT-58-8, 32, 1); V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-58-14, V_YELLOWMAP|MENUCAPS, "Press ESC to abort"); Net_GetNetStat(); - dldlength = (INT32)((file->currentsize/(double)file->totalsize) * 256); - if (dldlength > 256) - dldlength = 256; + if (totalsize != 0) + dldlength = (UINT32)((currentsize/(double)totalsize) * 256); V_DrawFill(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-58, 256, 8, 175); - V_DrawFill(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-58, dldlength, 8, 160); + V_DrawFill(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-58, (INT32)dldlength, 8, 160); memset(tempname, 0, sizeof(tempname)); + // offset filename to just the name only part filename += strlen(filename) - nameonlylength(filename); + const size_t filenamelength = strlen(filename); - if (strlen(filename) > sizeof(tempname)-1) // too long to display fully + if (filenamelength > sizeof(tempname)-1) // too long to display fully { - size_t endhalfpos = strlen(filename)-10; + size_t endhalfpos = filenamelength-10; // display as first 14 chars + ... + last 10 chars // which should add up to 27 if our math(s) is correct snprintf(tempname, sizeof(tempname), "%.14s...%.10s", filename, filename+endhalfpos); @@ -1481,32 +1540,35 @@ static inline void CL_DrawConnectionStatus(void) V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-58-22, V_YELLOWMAP|MENUCAPS, va(M_GetText("\"%s\""), tempname)); V_DrawString(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-58, V_20TRANS|V_MONOSPACE|MENUCAPS, - va(" %4uK/%4uK",file->currentsize>>10,file->totalsize>>10)); + va(" %4uK/%4uK", currentsize>>10, totalsize>>10)); V_DrawRightAlignedString(BASEVIDWIDTH/2+128, BASEVIDHEIGHT-58, V_20TRANS|V_MONOSPACE|MENUCAPS, - va("%3.1fK/s ", ((double)getbps)/1024)); + va("%3.1fK/s ", ((double)getbps)/1024.0)); // Download progress - if (file->currentsize != file->totalsize) - totaldldsize = filedownload.completedsize+file->currentsize; //Add in single file progress download if applicable + if (currentsize != totalsize) + totaldldsize = filedownload.completedsize+currentsize; // Add in single file progress download if applicable else totaldldsize = filedownload.completedsize; V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-14, V_YELLOWMAP|MENUCAPS, "Overall Download Progress"); - totalfileslength = (INT32)((totaldldsize/(double)filedownload.totalsize) * 256); + if (fdtotalsize != 0) + totalfileslength = (UINT32)((totaldldsize/(double)fdtotalsize) * 256); M_DrawTextBox(BASEVIDWIDTH/2-128-8, BASEVIDHEIGHT-24-8, 32, 1); V_DrawFill(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, 256, 8, 175); - V_DrawFill(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, totalfileslength, 8, 160); + V_DrawFill(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, (INT32)totalfileslength, 8, 160); - if (filedownload.totalsize>>20 >= 10) //display in MB if over 10MB + if ((fdtotalsize>>20) >= 10) // display in MB if over 10MB V_DrawString(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, V_20TRANS|V_MONOSPACE|MENUCAPS, - va(" %4uM/%4uM",totaldldsize>>20,filedownload.totalsize>>20)); + va(" %4uM/%4uM", (INT32)(totaldldsize>>20), (INT32)(fdtotalsize>>20))); else V_DrawString(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, V_20TRANS|V_MONOSPACE|MENUCAPS, - va(" %4uK/%4uK",totaldldsize>>10,filedownload.totalsize>>10)); + va(" %4uK/%4uK", (INT32)(totaldldsize>>10), (INT32)(fdtotalsize>>10))); V_DrawRightAlignedString(BASEVIDWIDTH/2+128, BASEVIDHEIGHT-24, V_20TRANS|V_MONOSPACE|MENUCAPS, va("%2u/%2u Files ", filedownload.completednum, filedownload.totalnum)); + + CL_DrawAddonTypes(); } else { @@ -1523,6 +1585,8 @@ static inline void CL_DrawConnectionStatus(void) V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-32, V_YELLOWMAP|MENUCAPS, M_GetText("Waiting to download files...")); + + CL_DrawAddonTypes(); } } } @@ -1566,8 +1630,8 @@ static boolean CL_SendJoin(void) netbuffer->u.clientcfg.packetversion = PACKETVERSION; netbuffer->u.clientcfg.version = VERSION; netbuffer->u.clientcfg.subversion = SUBVERSION; - strncpy(netbuffer->u.clientcfg.application, SRB2APPLICATION, - sizeof(netbuffer->u.clientcfg.application)); + strncpy(netbuffer->u.clientcfg.application, SRB2APPLICATION, sizeof(netbuffer->u.clientcfg.application)-1); + netbuffer->u.clientcfg.application[sizeof(netbuffer->u.clientcfg.application)-1] = '\0'; #ifdef SATURNJOIN netbuffer->u.clientcfg.issaturn = ISSATURN; #endif @@ -1592,88 +1656,91 @@ static void SV_SendServerInfo(INT32 node, tic_t servertime) doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); + serverinfo_pak *serverinfo = &netbuffer->u.serverinfo; + netbuffer->packettype = PT_SERVERINFO; - netbuffer->u.serverinfo._255 = 255; - netbuffer->u.serverinfo.packetversion = PACKETVERSION; - netbuffer->u.serverinfo.version = VERSION; - netbuffer->u.serverinfo.subversion = SUBVERSION; - strncpy(netbuffer->u.serverinfo.application, SRB2APPLICATION, - sizeof netbuffer->u.serverinfo.application); + serverinfo->_255 = 255; + serverinfo->packetversion = PACKETVERSION; + serverinfo->version = VERSION; + serverinfo->subversion = SUBVERSION; + strncpy(serverinfo->application, SRB2APPLICATION, sizeof(serverinfo->application)-1); + serverinfo->application[sizeof(serverinfo->application)-1] = '\0'; // return back the time value so client can compute their ping - netbuffer->u.serverinfo.time = (tic_t)LONG(servertime); - netbuffer->u.serverinfo.leveltime = (tic_t)LONG(leveltime); + serverinfo->time = (tic_t)LONG(servertime); + serverinfo->leveltime = (tic_t)LONG(leveltime); // force 1 player if (UseFakeSeed()) - netbuffer->u.serverinfo.numberofplayer = (UINT8)1; + serverinfo->numberofplayer = (UINT8)1; else - netbuffer->u.serverinfo.numberofplayer = (UINT8)D_NumPlayers(); + serverinfo->numberofplayer = (UINT8)D_NumPlayers(); - netbuffer->u.serverinfo.maxplayer = (UINT8)(min((dedicated ? MAXPLAYERS-1 : MAXPLAYERS), cv_maxplayers.value)); + serverinfo->maxplayer = (UINT8)(min((dedicated ? MAXPLAYERS-1 : MAXPLAYERS), cv_maxplayers.value)); // SRB2Kart: Vanilla's gametype constants for MS support - netbuffer->u.serverinfo.gametype = (UINT8)((gt == GT_MATCH) ? VANILLA_GT_MATCH : VANILLA_GT_RACE); + serverinfo->gametype = (UINT8)((gt == GT_MATCH) ? VANILLA_GT_MATCH : VANILLA_GT_RACE); - netbuffer->u.serverinfo.modifiedgame = (UINT8)modifiedgame; - netbuffer->u.serverinfo.cheatsenabled = CV_CheatsEnabled(); + serverinfo->modifiedgame = (UINT8)modifiedgame; + serverinfo->cheatsenabled = CV_CheatsEnabled(); - netbuffer->u.serverinfo.kartvars = (UINT8) ( + serverinfo->kartvars = (UINT8) ( (cv_kartspeed.value & SV_SPEEDMASK) | (dedicated ? SV_DEDICATED : 0) ); - CopyCaretColors(netbuffer->u.serverinfo.servername, cv_servername.string, - MAXSERVERNAME); - strncpy(netbuffer->u.serverinfo.mapname, G_BuildMapName(gamemap), sizeof(netbuffer->u.serverinfo.mapname)-1); + CopyCaretColors(serverinfo->servername, cv_servername.string, MAXSERVERNAME); - memcpy(netbuffer->u.serverinfo.mapmd5, mapmd5, sizeof(netbuffer->u.serverinfo.mapmd5)); + strncpy(serverinfo->mapname, G_BuildMapName(gamemap), sizeof(serverinfo->mapname)-1); + serverinfo->mapname[sizeof(serverinfo->mapname)-1] = '\0'; - netbuffer->u.serverinfo.iszone = 0; + memcpy(serverinfo->mapmd5, mapmd5, sizeof(serverinfo->mapmd5)); - memset(netbuffer->u.serverinfo.maptitle, 0, sizeof(netbuffer->u.serverinfo.maptitle)); - memset(netbuffer->u.serverinfo.httpsource, 0, MAX_MIRROR_LENGTH); + serverinfo->iszone = 0; + + memset(serverinfo->maptitle, 0, sizeof(serverinfo->maptitle)); + memset(serverinfo->httpsource, 0, MAX_MIRROR_LENGTH); if (!(mapheaderinfo[gamemap-1]->menuflags & LF2_HIDEINMENU) && mapheaderinfo[gamemap-1]->lvlttl[0]) { - strncpy(netbuffer->u.serverinfo.maptitle, mapheaderinfo[gamemap-1]->lvlttl, sizeof(netbuffer->u.serverinfo.maptitle)-1); + strncpy(serverinfo->maptitle, mapheaderinfo[gamemap-1]->lvlttl, sizeof(serverinfo->maptitle)-1); if (!(mapheaderinfo[gamemap-1]->levelflags & LF_NOZONE)) { if (mapheaderinfo[gamemap-1]->zonttl[0]) { - strncat(netbuffer->u.serverinfo.maptitle, " ", sizeof(netbuffer->u.serverinfo.maptitle)-1); - strncat(netbuffer->u.serverinfo.maptitle, mapheaderinfo[gamemap-1]->zonttl, - sizeof(netbuffer->u.serverinfo.maptitle)-1); + strncat(serverinfo->maptitle, " ", sizeof(serverinfo->maptitle)-1); + strncat(serverinfo->maptitle, mapheaderinfo[gamemap-1]->zonttl, sizeof(serverinfo->maptitle)-1); } else { - netbuffer->u.serverinfo.iszone = 1; // ms and clients will append this themselves + serverinfo->iszone = 1; // ms and clients will append this themselves } } if (mapheaderinfo[gamemap-1]->actnum[0]) { - strncat(netbuffer->u.serverinfo.maptitle, " ", sizeof(netbuffer->u.serverinfo.maptitle)-1); - strncat(netbuffer->u.serverinfo.maptitle, mapheaderinfo[gamemap-1]->actnum, - sizeof(netbuffer->u.serverinfo.maptitle)-1); + strncat(serverinfo->maptitle, " ", sizeof(serverinfo->maptitle)-1); + strncat(serverinfo->maptitle, mapheaderinfo[gamemap-1]->actnum, sizeof(serverinfo->maptitle)-1); } } else - strncpy(netbuffer->u.serverinfo.maptitle, "Unknown", 33); + { + strncpy(serverinfo->maptitle, "Unknown", sizeof(serverinfo->maptitle)-1); + } - netbuffer->u.serverinfo.maptitle[32] = '\0'; + serverinfo->maptitle[sizeof(serverinfo->maptitle)-1] = '\0'; - netbuffer->u.serverinfo.actnum = 0; //mapheaderinfo[gamemap-1]->actnum + serverinfo->actnum = 0; //mapheaderinfo[gamemap-1]->actnum mirror_length = strlen(httpurl); if (mirror_length > MAX_MIRROR_LENGTH) mirror_length = MAX_MIRROR_LENGTH; - if (snprintf(netbuffer->u.serverinfo.httpsource, mirror_length+1, "%s", httpurl) < 0) + if (snprintf(serverinfo->httpsource, mirror_length+1, "%s", httpurl) < 0) // If there's an encoding error, send nothing, we accept that the above may be truncated - strncpy(netbuffer->u.serverinfo.httpsource, "", mirror_length); + strncpy(serverinfo->httpsource, "", mirror_length); - netbuffer->u.serverinfo.httpsource[MAX_MIRROR_LENGTH-1] = '\0'; + serverinfo->httpsource[MAX_MIRROR_LENGTH-1] = '\0'; p = PutFileNeeded(0); @@ -1706,7 +1773,7 @@ static void SV_SendPlayerInfo(INT32 node) // doesent really matter what we put here lel netbuffer->u.playerinfo[0].score = LONG(42069); netbuffer->u.playerinfo[0].timeinserver = SHORT(42069); - netbuffer->u.playerinfo[0].skin = (UINT8)1; // no clue wtf skin 1 is, tails maybe? + netbuffer->u.playerinfo[0].skin = (skinnum_t)1; // no clue wtf skin 1 is, tails maybe? netbuffer->u.playerinfo[0].data = 0; @@ -1751,7 +1818,7 @@ static void SV_SendPlayerInfo(INT32 node) netbuffer->u.playerinfo[i].score = LONG(players[i].score); netbuffer->u.playerinfo[i].timeinserver = SHORT((UINT16)(players[i].jointime / TICRATE)); - netbuffer->u.playerinfo[i].skin = (UINT8)players[i].skin; + netbuffer->u.playerinfo[i].skin = (skinnum_t)players[i].skin; // Extra data // Kart has extra skincolors, so we can't use this @@ -1775,6 +1842,9 @@ static void SV_SendPlayerInfo(INT32 node) static void SV_SendMapIcon(INT32 node) { + if (node == 0) + return; + doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); const char *map = va("%sP", G_BuildMapName(gamemap)); @@ -1858,8 +1928,10 @@ static void SV_SendMapIcon(INT32 node) */ static boolean SV_SendServerConfig(INT32 node) { +#ifndef PHOBOS_BUILD INT32 i; UINT8 *p, *op; +#endif boolean waspacketsent; doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); @@ -1877,6 +1949,7 @@ static boolean SV_SendServerConfig(INT32 node) netbuffer->u.servercfg.gametype = (UINT8)gametype; netbuffer->u.servercfg.modifiedgame = (UINT8)modifiedgame; +#ifndef PHOBOS_BUILD // we fill these structs with FFs so that any players not in game get sent as 0xFFFF // which is nice and easy for us to detect memset(netbuffer->u.servercfg.playerskins, 0xFF, sizeof(netbuffer->u.servercfg.playerskins)); @@ -1892,6 +1965,7 @@ static boolean SV_SendServerConfig(INT32 node) netbuffer->u.servercfg.playerskins[i] = (UINT8)players[i].skin; netbuffer->u.servercfg.playercolor[i] = (UINT8)players[i].skincolor; } +#endif netbuffer->u.servercfg.maxplayer = (UINT8)(min((dedicated ? MAXPLAYERS-1 : MAXPLAYERS), cv_maxplayers.value)); netbuffer->u.servercfg.allownewplayer = cv_allownewplayer.value; @@ -1899,12 +1973,16 @@ static boolean SV_SendServerConfig(INT32 node) memcpy(netbuffer->u.servercfg.server_context, server_context, 8); +#ifdef PHOBOS_BUILD + const size_t len = sizeof(serverconfig_pak); +#else op = p = netbuffer->u.servercfg.varlengthinputs; CV_SavePlayerNames(&p); CV_SaveNetVars(&p, false); const size_t len = sizeof (serverconfig_pak) + (size_t)(p - op); +#endif #ifdef DEBUGFILE if (debugfile) @@ -1933,16 +2011,17 @@ static boolean SV_SendServerConfig(INT32 node) return waspacketsent; } -#define SAVEGAMESIZE (768*1024) - #ifdef SATURNPAK static boolean SV_ResendingSavegameToAnyone(void) { INT32 i; for (i = 0; i < MAXNETNODES; i++) + { if (nodeingame[i] && resendingsavegame[i]) return true; + } + return false; } #endif @@ -1950,7 +2029,7 @@ static boolean SV_ResendingSavegameToAnyone(void) static void SV_SendSaveGame(INT32 node, boolean resending) { size_t length, compressedlen; - savebuffer_t save = {0}; + savebuffer_t save = {}; UINT8 *compressedsave; UINT8 *buffertosend; @@ -1968,6 +2047,7 @@ static void SV_SendSaveGame(INT32 node, boolean resending) P_SaveNetGame(&save, resending); length = save.p - save.buffer; + if (length > SAVEGAMESIZE) { Z_Free(save.buffer); @@ -2020,13 +2100,13 @@ static consvar_t cv_dumpconsistency = {"dumpconsistency", "Off", CV_NETVAR, CV_O static void SV_SavedGame(void) { size_t length; - savebuffer_t save = {0}; + savebuffer_t save = {}; char tmpsave[264]; if (!cv_dumpconsistency.value) return; - sprintf(tmpsave, "%s" PATHSEP TMPSAVENAME, srb2home); + snprintf(tmpsave, sizeof(tmpsave), "%s" PATHSEP TMPSAVENAME, srb2home); // first save it in a malloced buffer save.p = save.buffer = (UINT8 *)Z_Malloc(SAVEGAMESIZE, PU_STATIC, NULL); @@ -2060,11 +2140,11 @@ static void SV_SavedGame(void) static void CL_LoadReceivedSavegame(boolean reloading) { - savebuffer_t save = {0}; + savebuffer_t save = {}; size_t length, decompressedlen; char tmpsave[264]; - sprintf(tmpsave, "%s" PATHSEP TMPSAVENAME, srb2home); + snprintf(tmpsave, sizeof(tmpsave), "%s" PATHSEP TMPSAVENAME, srb2home); length = FIL_ReadFile(tmpsave, &save.buffer); @@ -2120,7 +2200,8 @@ static void CL_LoadReceivedSavegame(boolean reloading) if (unlink(tmpsave) == -1) CONS_Alert(CONS_ERROR, M_GetText("Can't delete %s\n"), tmpsave); consistancy[gametic%BACKUPTICS] = Consistancy(); - CON_ToggleOff(); + if (!reloading) + CON_ToggleOff(); #ifdef SATURNPAK // Tell the server we have received and reloaded the gamestate @@ -2142,7 +2223,7 @@ static void CL_ReloadReceivedSavegame(void) for (i = 0; i < MAXPLAYERS; i++) { LUA_InvalidatePlayer(&players[i]); - sprintf(player_names[i], "Player %d", i + 1); + snprintf(player_names[i], MAXPLAYERNAME+1, "Player %d", i + 1); } CL_LoadReceivedSavegame(true); @@ -2170,7 +2251,12 @@ static void CL_ReloadReceivedSavegame(void) static void SendAskInfo(INT32 node) { tic_t asktime; - doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); + doomdata_t *netbuffer; + + if (node == -1) + return; + + netbuffer = DOOMCOM_DATA(doomcom); #ifdef HOLEPUNCH if (node != 0 && node != BROADCASTADDR && @@ -2517,7 +2603,7 @@ static boolean CL_FinishedFileList(void) * \sa CL_ConnectToServer * */ -static boolean CL_ServerConnectionSearchTicker(tic_t *asksent) +static void CL_ServerConnectionSearchTicker(tic_t *asksent) { INT32 i; @@ -2535,7 +2621,7 @@ static boolean CL_ServerConnectionSearchTicker(tic_t *asksent) { i = SL_SearchServer(servernode); if (i < 0) - return true; + return; } joinnode = i; @@ -2563,10 +2649,11 @@ static boolean CL_ServerConnectionSearchTicker(tic_t *asksent) { cl_mode = CL_ASKFULLFILELIST; cl_lastcheckedfilecount = 0; - return true; + return; } - cl_mode = (cv_serverinfoscreen.value) ? CL_VIEWSERVER : CL_CHECKFILES; + cl_mode = cv_serverinfoscreen.value ? CL_VIEWSERVER : CL_CHECKFILES; + CL_CheckAddonTypes(); } else { @@ -2574,7 +2661,7 @@ static boolean CL_ServerConnectionSearchTicker(tic_t *asksent) *asksent = 0; } - return true; + return; } // Ask the info to the server (askinfo packet) @@ -2584,7 +2671,17 @@ static boolean CL_ServerConnectionSearchTicker(tic_t *asksent) *asksent = I_GetTime() + NEWTICRATE; } - return true; +} + +static void FreeMapIcon(void) +{ + if (map_icon != NULL) + Patch_Free(map_icon); + map_icon = NULL; + if (map_icon_data != NULL) + Z_Free(map_icon_data); + map_icon_data = NULL; + map_icon_request_count = 0; } /** Called by CL_ConnectToServer @@ -2605,13 +2702,15 @@ static boolean CL_ServerConnectionTicker(const char *tmpsave, tic_t *oldtic, tic switch (cl_mode) { case CL_SEARCHING: - if (!CL_ServerConnectionSearchTicker(asksent)) - return false; + CL_ServerConnectionSearchTicker(asksent); break; case CL_ASKFULLFILELIST: if (cl_lastcheckedfilecount == UINT16_MAX) // All files retrieved - cl_mode = (cv_serverinfoscreen.value) ? CL_VIEWSERVER : CL_CHECKFILES; + { + cl_mode = cv_serverinfoscreen.value ? CL_VIEWSERVER : CL_CHECKFILES; + CL_CheckAddonTypes(); + } else if (fileneedednum != cl_lastcheckedfilecount || I_GetTime() >= *asksent) { if (CL_AskFileList(fileneedednum)) @@ -2744,7 +2843,19 @@ static boolean CL_ServerConnectionTicker(const char *tmpsave, tic_t *oldtic, tic { // Gamestate is now handled within CL_LoadReceivedSavegame() CL_LoadReceivedSavegame(false); - cl_mode = CL_CONNECTED; + + if (cl_addonsonly) + { + // close connection after savegame load + // we want the actual server state + // in case theres some stuff like records to be synched + cl_mode = CL_ABORTED; + } + else + { + cl_mode = CL_CONNECTED; + } + break; } // don't break case continue to CL_CONNECTED else @@ -2758,7 +2869,6 @@ static boolean CL_ServerConnectionTicker(const char *tmpsave, tic_t *oldtic, tic case CL_ABORTED: cl_mode = CL_SEARCHING; return false; - } GetPackets(); @@ -2769,6 +2879,8 @@ static boolean CL_ServerConnectionTicker(const char *tmpsave, tic_t *oldtic, tic { INT32 key; + I_HandleInterrupt(); + I_OsPolling(); if (cl_mode == CL_CONFIRMCONNECT) @@ -2780,24 +2892,21 @@ static boolean CL_ServerConnectionTicker(const char *tmpsave, tic_t *oldtic, tic { if (key == KEY_ENTER || key == KEY_JOY1) { + cl_addonsonly = false; cl_mode = CL_CHECKFILES; - if (map_icon != NULL) - Patch_Free(map_icon); - map_icon = NULL; - if (map_icon_data != NULL) - Z_Free(map_icon_data); - map_icon_data = NULL; + FreeMapIcon(); } else if (key == KEY_ESCAPE || key == KEY_JOY1+1) { cl_mode = CL_ABORTED; - if (map_icon != NULL) - Patch_Free(map_icon); - map_icon = NULL; - if (map_icon_data != NULL) - Z_Free(map_icon_data); - map_icon_data = NULL; - map_icon_request_count = 0; + cl_addonsonly = false; + FreeMapIcon(); + } + else if (key == KEY_SPACE || key == KEY_JOY1+2) + { + cl_addonsonly = true; + cl_mode = CL_CHECKFILES; + FreeMapIcon(); } } @@ -2806,6 +2915,7 @@ static boolean CL_ServerConnectionTicker(const char *tmpsave, tic_t *oldtic, tic { CONS_Printf(M_GetText("Network game synchronization aborted.\n")); CL_AbortConnection(); + cl_addonsonly = false; return false; } @@ -2849,7 +2959,7 @@ static void CL_ConnectToServer(void) tic_t asksent; char tmpsave[264]; - sprintf(tmpsave, "%s" PATHSEP TMPSAVENAME, srb2home); + snprintf(tmpsave, sizeof(tmpsave), "%s" PATHSEP TMPSAVENAME, srb2home); filedownload.current = -1; cl_mode = CL_SEARCHING; @@ -2925,8 +3035,10 @@ static void CL_ConnectToServer(void) { pnumnodes = 0; for (i = 0; i < MAXNETNODES; i++) + { if (nodeingame[i]) pnumnodes++; + } } } while (!(cl_mode == CL_CONNECTED && (client || (server && nodewaited <= pnumnodes)))); @@ -3300,9 +3412,21 @@ static void Command_connect(void) } else CONS_Alert(CONS_ERROR, M_GetText("There is no network driver\n")); + + // invalid address + if (servernode == -1) + { + D_QuitNetGame(); // this will also call D_CloseConnection for us + CL_Reset(); + servernode = 0; // not sure if this is cool, but if this is -1 then bad things happen in alot of networking code + D_StartTitle(); + M_StartMessage(M_GetText("Failed to connect to server\nMake sure you put in a valid Address!\n"), NULL, MM_NOTHING); + return; + } } - CV_Set(&cv_lastserver, I_GetNodeAddress(servernode)); + if (I_GetNodeAddress) + CV_Set(&cv_lastserver, I_GetNodeAddress(servernode)); if (splitscreen != cv_splitplayers.value-1) { @@ -3337,7 +3461,7 @@ void CL_ClearPlayer(INT32 playernum) if (players[playernum].mo) { // Don't leave a NiGHTS ghost! - if ((players[playernum].pflags & PF_NIGHTSMODE) && players[playernum].mo->tracer) + if (nightsplayer(&players[playernum]) && players[playernum].mo->tracer) P_RemoveMobj(players[playernum].mo->tracer); P_RemoveMobj(players[playernum].mo); } @@ -3394,8 +3518,11 @@ void CL_RemovePlayer(INT32 playernum, INT32 reason) while ((doomcom->numslots > 1) && !playeringame[doomcom->numslots-1]) doomcom->numslots--; + // Unmute slot if player was muted + player_muted[playernum] = false; + // Reset the name - sprintf(player_names[playernum], "Player %d", playernum+1); + snprintf(player_names[playernum], MAXPLAYERNAME+1, "Player %d", playernum+1); player_name_changes[playernum] = 0; @@ -3472,6 +3599,9 @@ void CL_Reset(void) memset(player_muted, 0, sizeof(player_muted)); + for (INT32 i = 0; i < MAXPLAYERS; ++i) + playerinfo[i].node = 255; + // D_StartTitle should get done now, but the calling function will handle it } @@ -3480,6 +3610,7 @@ static void Command_GetPlayerNum(void) INT32 i; for (i = 0; i < MAXPLAYERS; i++) + { if (playeringame[i]) { if (serverplayer == i) @@ -3487,6 +3618,7 @@ static void Command_GetPlayerNum(void) else CONS_Printf(M_GetText("\x82num:%2d node:%2d %s\n"), i, playernode[i], player_names[i]); } + } } SINT8 nametonum(const char *name) @@ -3647,6 +3779,10 @@ static void Command_Ban(void) if (pn == -1 || pn == 0) return; + // player does not exist + if (!playeringame[pn]) + return; + WRITEUINT8(p, pn); if (COM_Argc() == 2) @@ -3764,6 +3900,10 @@ static void Command_Kick(void) if (pn == -1 || pn == 0) return; + // player does not exist + if (!playeringame[pn]) + return; + // Special case if we are trying to kick a player who is downloading the game state: // trigger a timeout instead of kicking them, because a kick would only // take effect after they have finished downloading @@ -3813,6 +3953,13 @@ static void Got_KickCmd(const UINT8 **p, INT32 playernum) pnum = READUINT8(*p); msg = READUINT8(*p); + if (pnum >= MAXPLAYERS) + { + CONS_Alert(CONS_WARNING, M_GetText("Illegal kick command received from %s for player %d\n"), player_names[playernum], pnum); + return; + } + + // FIXME: this does not work at all on dedi, servernode == 0 which is prevented from kick/ban command if (pnum == serverplayer && IsPlayerAdmin(playernum)) { CONS_Printf(M_GetText("Server is being shut down remotely. Goodbye!\n")); @@ -3867,6 +4014,16 @@ static void Got_KickCmd(const UINT8 **p, INT32 playernum) msg = KICK_MSG_CON_FAIL; } + // without this the server will remove itself and thus self destruct on dedicated + if (server && (playernode[pnum] == UINT8_MAX || !playeringame[pnum])) + { + CONS_Alert(CONS_WARNING, M_GetText("Attempting to kick player %d which is not in game received from %s\n"), pnum, player_names[playernum]); + return; + } + + // make sure we dont read garbage anywhere + memset(reason, 0, sizeof(buf)); + if (msg == KICK_MSG_CUSTOM_BAN || msg == KICK_MSG_CUSTOM_KICK) { READSTRINGN(*p, reason, MAX_REASONLENGTH+1); @@ -4129,7 +4286,7 @@ static void Command_ResendGamestate(void) } playernum = nametonum(COM_Argv(1)); - if (playernum == -1 || playernum == 0) + if (playernum <= 0) return; doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); @@ -4192,6 +4349,8 @@ consvar_t cv_connectawaittime = {"connectawaittime", "5", CV_SAVE, connectawaitt consvar_t cv_serverinfoscreen = {"serverinfoscreen", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_serveraddoninfo = {"serveraddoninfo", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; + static void Got_AddPlayer(const UINT8 **p, INT32 playernum); static void Got_RemovePlayer(const UINT8 **p, INT32 playernum); @@ -4260,8 +4419,11 @@ void D_ClientServerInit(void) #endif D_LoadBan(false); + for (INT32 i = 0; i < MAXPLAYERS; ++i) + playerinfo[i].node = 255; + gametic = 0; - localgametic = 0; + leveltime = 0; // do not send anything before the real begin SV_StopServer(); @@ -4322,7 +4484,7 @@ void SV_ResetServer(void) for (i = 0; i < MAXPLAYERS; i++) { LUA_InvalidatePlayer(&players[i]); - sprintf(player_names[i], "Player %d", i + 1); + snprintf(player_names[i], MAXPLAYERNAME+1, "Player %d", i + 1); } memset(player_name_changes, 0, sizeof(player_name_changes)); @@ -4333,6 +4495,7 @@ void SV_ResetServer(void) pingmeasurecount = 1; memset(realpingtable, 0, sizeof(realpingtable)); memset(playerpingtable, 0, sizeof(playerpingtable)); + localplayerping = 0; ClearAdminPlayers(); @@ -4402,8 +4565,10 @@ void D_QuitNetGame(void) netbuffer->packettype = PT_SERVERSHUTDOWN; for (i = 0; i < MAXNETNODES; i++) + { if (nodeingame[i]) HSendPacket(i, true, 0, 0); + } #ifdef MASTERSERVER if (serverrunning && netgame && cv_advertise.value) // see mserv.c Online() UnregisterServer(); @@ -4447,18 +4612,21 @@ static inline void SV_AddNode(INT32 node) // Xcmd XD_ADDPLAYER static void Got_AddPlayer(const UINT8 **p, INT32 playernum) { + UINT8 i; INT16 node, newplayernum; UINT8 splitscreenplayer = 0; - UINT8 i; + player_t *newplayer; if (playernum != serverplayer && !IsPlayerAdmin(playernum)) { // protect against hacked/buggy client CONS_Alert(CONS_WARNING, M_GetText("Illegal add player command received from %s\n"), player_names[playernum]); + if (server) { SendKick(playernum, KICK_MSG_CON_FAIL); } + return; } @@ -4467,14 +4635,19 @@ static void Got_AddPlayer(const UINT8 **p, INT32 playernum) splitscreenplayer = newplayernum/MAXPLAYERS; newplayernum %= MAXPLAYERS; + CONS_Debug(DBG_NETPLAY, "addplayer: %d %d\n", node, newplayernum); + // Clear player before joining, lest some things get set incorrectly CL_ClearPlayer(newplayernum); playeringame[newplayernum] = true; G_AddPlayer(newplayernum); + if (newplayernum+1 > doomcom->numslots) doomcom->numslots = (INT16)(newplayernum+1); + newplayer = &players[newplayernum]; + // the server is creating my player if (node == mynode) { @@ -4485,7 +4658,7 @@ static void Got_AddPlayer(const UINT8 **p, INT32 playernum) displayplayers[splitscreenplayer] = newplayernum; DEBFILE(va("spawning one of my sister number %d\n", splitscreenplayer)); if (splitscreenplayer == 1 && botingame) - players[newplayernum].bot = 1; + newplayer->bot = 1; // do we really want this löl } else { @@ -4495,13 +4668,13 @@ static void Got_AddPlayer(const UINT8 **p, INT32 playernum) DEBFILE("spawning me\n"); } - P_ForceLocalAngle(&players[newplayernum], (angle_t)(players[newplayernum].cmd.angleturn << TICCMD_REDUCE)); + P_ForceLocalAngle(newplayer, (angle_t)(newplayer->cmd.angleturn << TICCMD_REDUCE)); - D_SendPlayerConfig(); + D_SendPlayerConfig(splitscreenplayer); addedtogame = true; } - players[newplayernum].splitscreenindex = splitscreenplayer; + newplayer->splitscreenindex = splitscreenplayer; if (netgame) { @@ -4565,71 +4738,81 @@ static void Got_RemovePlayer(const UINT8 **p, INT32 playernum) #endif } -static boolean SV_AddWaitingPlayers(void) +static boolean SV_AddWaitingPlayers(SINT8 node) { - INT32 node, n, newplayer = false; + INT32 n; UINT8 buf[2]; UINT8 newplayernum = 0; + boolean newplayer = false; - // What is the reason for this? Why can't newplayernum always be 0? - // Sal: Because the dedicated player is stupidly forced into players[0]..... - if (dedicated) - newplayernum = 1; - - for (node = 0; node < MAXNETNODES; node++) + // splitscreen can allow 2+ players in one node + for (; nodewaiting[node] > 0; nodewaiting[node]--) { - // splitscreen can allow 2+ players in one node - for (; nodewaiting[node] > 0; nodewaiting[node]--) - { - newplayer = true; + newplayer = true; - // search for a free playernum - // we can't use playeringame since it is not updated here - for (; newplayernum < MAXPLAYERS; newplayernum++) + // search for a free playernum + // we can't solely use playeringame since it is not updated here + for (newplayernum = dedicated ? 1 : 0; newplayernum < MAXPLAYERS; newplayernum++) + { + if (playeringame[newplayernum]) + continue; + + for (n = 0; n < MAXNETNODES; n++) { - for (n = 0; n < MAXNETNODES; n++) - if (nodetoplayer[n] == newplayernum || nodetoplayer2[n] == newplayernum - || nodetoplayer3[n] == newplayernum || nodetoplayer4[n] == newplayernum) - break; - if (n == MAXNETNODES) + if (nodetoplayer[n] == newplayernum || + nodetoplayer2[n] == newplayernum || + nodetoplayer3[n] == newplayernum || + nodetoplayer4[n] == newplayernum) break; } - // should never happen since we check the playernum - // before accepting the join - I_Assert(newplayernum < MAXPLAYERS); - - playernode[newplayernum] = (UINT8)node; - - buf[0] = (UINT8)node; - buf[1] = newplayernum; - if (playerpernode[node] < 1) - { - nodetoplayer[node] = newplayernum; - } - else if (playerpernode[node] < 2) - { - nodetoplayer2[node] = newplayernum; - buf[1] += MAXPLAYERS; - } - else if (playerpernode[node] < 3) - { - nodetoplayer3[node] = newplayernum; - buf[1] += MAXPLAYERS*2; - } - else - { - nodetoplayer4[node] = newplayernum; - buf[1] += MAXPLAYERS*3; - } - playerpernode[node]++; - - SendNetXCmd(XD_ADDPLAYER, &buf, 2); - - DEBFILE(va("Server added player %d node %d\n", newplayernum, node)); - // use the next free slot (we can't put playeringame[newplayernum] = true here) - newplayernum++; + if (n == MAXNETNODES) + break; } + + // should never happen since we check the playernum + // before accepting the join + I_Assert(newplayernum < MAXPLAYERS); + + buf[0] = (UINT8)node; + buf[1] = newplayernum; + + if (playerpernode[node] < 1) + { + nodetoplayer[node] = newplayernum; + } + else if (playerpernode[node] < 2) + { + nodetoplayer2[node] = newplayernum; + buf[1] += MAXPLAYERS; + } + else if (playerpernode[node] < 3) + { + nodetoplayer3[node] = newplayernum; + buf[1] += MAXPLAYERS*2; + } + else if (playerpernode[node] < 4) + { + nodetoplayer4[node] = newplayernum; + buf[1] += MAXPLAYERS*3; + } + else + { + // I don't know if it's safe to assert here, + // but I do know this should not be allowed + // to be reached. + return newplayer; + } + + playernode[newplayernum] = (UINT8)node; + + playerpernode[node]++; + + SendNetXCmd(XD_ADDPLAYER, &buf, 2); + + DEBFILE(va("Server added player %d node %d\n", newplayernum, node)); + // use the next free slot (we can't put playeringame[newplayernum] = true here) + newplayernum++; } return newplayer; @@ -4661,11 +4844,13 @@ void CL_RemoveSplitscreenPlayer(UINT8 p) // is there a game running boolean Playing(void) { - return (server && serverrunning) || (client && cl_mode == CL_CONNECTED); + return ((server && serverrunning) || (client && cl_mode == CL_CONNECTED)); } boolean SV_SpawnServer(void) { + boolean result = false; + if (demo.playback) G_StopDemo(); // reset engine parameter @@ -4686,7 +4871,15 @@ boolean SV_SpawnServer(void) else doomcom->numslots = 1; } - return SV_AddWaitingPlayers(); + // strictly speaking, i'm not convinced the following is necessary + // but I'm not confident enough to remove it entirely in case it breaks something + { + SINT8 node = 0; + for (; node < MAXNETNODES; node++) + result |= SV_AddWaitingPlayers(node); + } + + return result; } void SV_StopServer(void) @@ -4740,17 +4933,6 @@ void SV_StartSinglePlayerServer(void) multiplayer = true; } -static void SV_SendRefuse(INT32 node, const char *reason) -{ - doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); - - strcpy(netbuffer->u.serverrefuse.reason, reason); - - netbuffer->packettype = PT_SERVERREFUSE; - HSendPacket(node, false, 0, strlen(netbuffer->u.serverrefuse.reason) + 1); - Net_CloseConnection(node); -} - // used at txtcmds received to check packetsize bound static size_t TotalTextCmdPerTic(tic_t tic) { @@ -4767,15 +4949,25 @@ static size_t TotalTextCmdPerTic(tic_t tic) return total; } -/** Called when a PT_CLIENTJOIN packet is received - * - * \param node The packet sender - * - */ -static void HandleConnect(SINT8 node) +static void SV_SendRefuse(INT32 node, const char *reason) { doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); + strcpy(netbuffer->u.serverrefuse.reason, reason); + + netbuffer->packettype = PT_SERVERREFUSE; + HSendPacket(node, false, 0, strlen(netbuffer->u.serverrefuse.reason) + 1); + Net_CloseConnection(node); +} + +static const char *GetRefuseMessage(SINT8 node) +{ + doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); + clientconfig_pak *cc = &netbuffer->u.clientcfg; + + if (!node) /* server connecting to itself */ + return NULL; + // Sal: Dedicated mode is INCREDIBLY hacked together. // If a server filled out, then it'd overwrite the host and turn everyone into weird husks..... // It's too much effort to legimately fix right now. Just prevent it from reaching that state. @@ -4783,11 +4975,19 @@ static void HandleConnect(SINT8 node) UINT8 connectedplayers = 0; for (UINT8 i = dedicated ? 1 : 0; i < MAXPLAYERS; i++) - if (playernode[i] != UINT8_MAX) // We use this to count players because it is affected by SV_AddWaitingPlayers when more than one client joins on the same tic, unlike playeringame and D_NumPlayers. UINT8_MAX denotes no node for that player + { + // We use this to count players because it is affected by SV_AddWaitingPlayers when + // more than one client joins on the same tic, unlike playeringame and D_NumPlayers. + // UINT8_MAX denotes no node for that player. + + if (playernode[i] != UINT8_MAX) + { connectedplayers++; + } + } #ifdef SATURNJOIN - const boolean issaturn = (((doomcom->datalength) == sizeof(clientconfig_pak)) && netbuffer->u.clientcfg.issaturn == ISSATURN); // Check the packet lenght to skip potential garbo data! + const boolean issaturn = (((doomcom->datalength) == sizeof(clientconfig_pak)) && (cc->issaturn == ISSATURN)); // Check the packet length to skip garbo data! #endif if (bannednode && bannednode[node].banid != SIZE_MAX) @@ -4800,47 +5000,44 @@ static void HandleConnect(SINT8 node) if (bannednode[node].timeleft != NO_BAN_TIME) { - // these are fudged a little to allow it to sink in for impatient rejoiners + // these are fudged a little to allow it to sink in for impatient rejoiners int minutes = (bannednode[node].timeleft + 30) / 60; int hours = (minutes + 1) / 60; int days = (hours + 1) / 24; if (days) { - SV_SendRefuse(node, va("K|%s\n(Time remaining: %d day%s)", reason, days, days > 1 ? "s" : "")); + return va("K|%s\n(Time remaining: %d day%s)", reason, days, days > 1 ? "s" : ""); } else if (hours) { - SV_SendRefuse(node, va("K|%s\n(Time remaining: %d hour%s)", reason, hours, hours > 1 ? "s" : "")); + return va("K|%s\n(Time remaining: %d hour%s)", reason, hours, hours > 1 ? "s" : ""); } else if (minutes) { - SV_SendRefuse(node, va("K|%s\n(Time remaining: %d minute%s)", reason, minutes, minutes > 1 ? "s" : "")); + return va("K|%s\n(Time remaining: %d minute%s)", reason, minutes, minutes > 1 ? "s" : ""); } else { - SV_SendRefuse(node, va("K|%s\n(Time remaining: <1 minute)", reason)); + return va("K|%s\n(Time remaining: <1 minute)", reason); } } else { - SV_SendRefuse(node, va("B|%s", reason)); + return va("B|%s", reason); } } - else if (netbuffer->u.clientcfg._255 != 255 || - netbuffer->u.clientcfg.packetversion != PACKETVERSION) + else if (cc->_255 != 255 || cc->packetversion != PACKETVERSION) { - SV_SendRefuse(node, "Incompatible packet formats."); + return "Incompatible packet formats."; } - else if (strncmp(netbuffer->u.clientcfg.application, SRB2APPLICATION, - sizeof netbuffer->u.clientcfg.application)) + else if (strncmp(cc->application, SRB2APPLICATION, sizeof(cc->application))) { - SV_SendRefuse(node, "Different SRB2Kart modifications\nare not compatible."); + return "Different SRB2Kart modifications\nare not compatible."; } - else if (netbuffer->u.clientcfg.version != VERSION - || netbuffer->u.clientcfg.subversion != SUBVERSION) + else if (cc->version != VERSION || cc->subversion != SUBVERSION) { - SV_SendRefuse(node, va(M_GetText("Different SRB2Kart versions cannot\nplay a netgame!\n(server version %d.%d)"), VERSION, SUBVERSION)); + return va("Different SRB2Kart versions cannot\nplay a netgame!\n(server version %d.%d)", VERSION, SUBVERSION); } #ifdef SATURNJOIN else if (((!cv_allownewplayer.value && !issaturn) || (!cv_allownewsaturnplayer.value && issaturn)) && node) @@ -4848,72 +5045,85 @@ static void HandleConnect(SINT8 node) else if (!cv_allownewplayer.value && node) #endif { - SV_SendRefuse(node, M_GetText(cv_joinrefusemessage.string)); + return cv_joinrefusemessage.string; } else if (connectedplayers >= maxplayers) { - SV_SendRefuse(node, va(M_GetText("Maximum players reached: %d"), maxplayers)); + return va("Maximum players reached: %d", maxplayers); } - else if (netgame && netbuffer->u.clientcfg.localplayers > 4) // Hacked client? + else if (netgame && !cc->localplayers) // Stealth join? { - SV_SendRefuse(node, M_GetText("Too many players from\nthis node.")); + return "No players from\nthis node."; } - else if (netgame && connectedplayers + netbuffer->u.clientcfg.localplayers > maxplayers) + else if (netgame && cc->localplayers > 4) // Hacked client? { - SV_SendRefuse(node, va(M_GetText("Number of local players\nwould exceed maximum: %d"), maxplayers)); + return "Too many players from\nthis node."; } - else if (netgame && !netbuffer->u.clientcfg.localplayers) // Stealth join? + else if (netgame && connectedplayers + cc->localplayers > maxplayers) { - SV_SendRefuse(node, M_GetText("No players from\nthis node.")); + return va("Number of local players\nwould exceed maximum: %d", maxplayers); } - else - { - boolean newnode = false; - // client authorised to join - nodewaiting[node] = (UINT8)(netbuffer->u.clientcfg.localplayers - playerpernode[node]); + return NULL; +} - if (!nodeingame[node]) +/** Called when a PT_CLIENTJOIN packet is received + * + * \param node The packet sender + * + */ +static void PT_ClientJoin(SINT8 node) +{ + // Ignore duplicate packets + if (client || nodeingame[node] || levelloading) + return; + + const char *refuse = GetRefuseMessage(node); + + if (refuse) + { + SV_SendRefuse(node, refuse); + return; + } + + doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); + + // client authorised to join + nodewaiting[node] = (UINT8)(netbuffer->u.clientcfg.localplayers - playerpernode[node]); + + gamestate_t backupstate = gamestate; + + SV_AddNode(node); + + /// \note Wait what??? + /// What if the gamestate takes more than one second to get downloaded? + /// Or if a lagspike happens? + // you get a free second before desynch checks. use it wisely. + SV_InitResynchVars(node); + + if (!SV_SendServerConfig(node)) + { + G_SetGamestate(backupstate); + /// \note Shouldn't SV_SendRefuse be called before ResetNode? + SV_SendRefuse(node, "Server couldn't send info, please try again"); + ResetNode(node); // Yeah, lets try it! + /// \todo fix this !!! + return; // restart the while + } + + SV_SendServerInfo(node, 0); // Dunno if 0 time is good idea + G_SetGamestate(backupstate); + DEBFILE("new node joined\n"); + + if (nodewaiting[node]) + { + if (node) { - gamestate_t backupstate = gamestate; - - newnode = true; - - SV_AddNode(node); - - /// \note Wait what??? - /// What if the gamestate takes more than one second to get downloaded? - /// Or if a lagspike happens? - // you get a free second before desynch checks. use it wisely. - SV_InitResynchVars(node); - - if (!SV_SendServerConfig(node)) - { - G_SetGamestate(backupstate); - /// \note Shouldn't SV_SendRefuse be called before ResetNode? - SV_SendRefuse(node, M_GetText("Server couldn't send info, please try again")); - ResetNode(node); // Yeah, lets try it! - /// \todo fix this !!! - return; // restart the while - } - - SV_SendServerInfo(node, 0); // Dunno if 0 time is good idea - //if (gamestate != GS_LEVEL) // GS_INTERMISSION, etc? - // SV_SendPlayerConfigs(node); // send bare minimum player info - G_SetGamestate(backupstate); - DEBFILE("new node joined\n"); + SV_SendSaveGame(node, false); // send a complete game state + DEBFILE("send savegame\n"); } - if (nodewaiting[node]) - { - if (node && newnode) - { - SV_SendSaveGame(node, false); // send a complete game state - DEBFILE("send savegame\n"); - } - - SV_AddWaitingPlayers(); - } + SV_AddWaitingPlayers(node); } } @@ -4922,8 +5132,11 @@ static void HandleConnect(SINT8 node) * \param node The packet sender (should be the server) * */ -static void HandleShutdown(SINT8 node) +static void PT_ServerShutdown(SINT8 node) { + if (node != servernode || server || cl_mode == CL_SEARCHING) + return; + (void)node; D_QuitNetGame(); CL_Reset(); @@ -4951,7 +5164,7 @@ static void HandleTimeout(SINT8 node) * \note What happens if the packet comes from a client or something like that? * */ -static void HandleServerInfo(SINT8 node) +static void PT_ServerInfo(SINT8 node) { char servername[MAXSERVERNAME]; doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); @@ -4974,7 +5187,7 @@ static void HandleServerInfo(SINT8 node) memcpy(connectedservername, netbuffer->u.serverinfo.servername, MAXSERVERNAME); } -static void HandlePlayerInfo(void) +static void PT_PlayerInfo(void) { INT32 i; doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); @@ -5210,8 +5423,10 @@ static void PT_ServerRefuse(SINT8 node) // Positive response of client join request static void PT_ServerCFG(SINT8 node) { +#ifndef PHOBOS_BUILD INT32 j; UINT8 *scp; +#endif if (server && serverrunning && node != servernode) { // but wait I thought I'm the server? @@ -5232,10 +5447,12 @@ static void PT_ServerCFG(SINT8 node) { maketic = gametic = neededtic = (tic_t)LONG(netbuffer->u.servercfg.gametic); if ((gametype = netbuffer->u.servercfg.gametype) >= NUMGAMETYPES) - I_Error("Bad gametype in cliserv!"); + I_Error("Bad gametype %d in cliserv!", gametype); modifiedgame = netbuffer->u.servercfg.modifiedgame; +#ifndef PHOBOS_BUILD for (j = 0; j < MAXPLAYERS; j++) adminplayers[j] = netbuffer->u.servercfg.adminplayers[j]; +#endif memcpy(server_context, netbuffer->u.servercfg.server_context, 8); } @@ -5261,6 +5478,7 @@ static void PT_ServerCFG(SINT8 node) SendSaturnInfo(node); #endif +#ifndef PHOBOS_BUILD memset(playeringame, 0, sizeof(playeringame)); for (j = 0; j < MAXPLAYERS; j++) @@ -5277,6 +5495,7 @@ static void PT_ServerCFG(SINT8 node) scp = netbuffer->u.servercfg.varlengthinputs; CV_LoadPlayerNames(&scp); scp += CV_LoadNetVars(scp); +#endif /// \note Wait. What if a Lua script uses some global custom variables synched with the NetVars hook? /// Shouldn't them be downloaded even at intermission time? @@ -5330,7 +5549,7 @@ static void PT_WillResendGamestate(void) CONS_Printf(M_GetText("Reloading game state...\n")); - sprintf(tmpsave, "%s" PATHSEP TMPSAVENAME, srb2home); + snprintf(tmpsave, sizeof(tmpsave), "%s" PATHSEP TMPSAVENAME, srb2home); // Don't get a corrupt savegame error because tmpsave already exists if (FIL_FileExists(tmpsave) && unlink(tmpsave) == -1) @@ -5372,6 +5591,9 @@ static void HandlePacketFromAwayNode(SINT8 node) case PT_ASKINFOVIAMS: Net_CloseConnection(node); break; + case PT_SERVERINFO: + PT_ServerInfo(node); + break; case PT_TELLFILESNEEDED: PT_TellFilesNeeded(node); break; @@ -5402,7 +5624,7 @@ static void HandlePacketFromAwayNode(SINT8 node) case PT_CLIENTCMD: break; // This is not an "unknown packet" case PT_PLAYERINFO: - HandlePlayerInfo(); + PT_PlayerInfo(); break; case PT_MAPICON: PT_MapIcon(); @@ -5410,12 +5632,17 @@ static void HandlePacketFromAwayNode(SINT8 node) case PT_NEEDMAPICON: PT_NeedMapIcon(node); break; + case PT_SERVERSHUTDOWN: + PT_ServerShutdown(node); + break; + case PT_CLIENTJOIN: + PT_ClientJoin(node); + break; case PT_SERVERTICS: // Do not remove my own server (we have just get a out of order packet) if (node == servernode) break; /* FALLTHRU */ - default: DEBFILE(va("unknown packet received (%d) from unknown host\n", netbuffer->packettype)); Net_CloseConnection(node); @@ -5459,7 +5686,7 @@ static void PT_ClientCmd(INT32 netconsole, SINT8 node) realstart = ExpandTics(netbuffer->u.clientpak.client_tic, nettics[node]); realend = ExpandTics(netbuffer->u.clientpak.resendfrom, nettics[node]); - if (netbuffer->packettype == PT_CLIENTMIS || netbuffer->packettype == PT_CLIENT2MIS + if ( netbuffer->packettype == PT_CLIENTMIS || netbuffer->packettype == PT_CLIENT2MIS || netbuffer->packettype == PT_CLIENT3MIS || netbuffer->packettype == PT_CLIENT4MIS || netbuffer->packettype == PT_NODEKEEPALIVEMIS || supposedtics[node] < realend) @@ -5502,10 +5729,10 @@ static void PT_ClientCmd(INT32 netconsole, SINT8 node) return; // Splitscreen cmd - if (((netbuffer->packettype == PT_CLIENT2CMD || netbuffer->packettype == PT_CLIENT2MIS) + if ((nodetoplayer2[node] >= 0) && + ((netbuffer->packettype == PT_CLIENT2CMD || netbuffer->packettype == PT_CLIENT2MIS) || (netbuffer->packettype == PT_CLIENT3CMD || netbuffer->packettype == PT_CLIENT3MIS) - || (netbuffer->packettype == PT_CLIENT4CMD || netbuffer->packettype == PT_CLIENT4MIS)) - && (nodetoplayer2[node] >= 0)) + || (netbuffer->packettype == PT_CLIENT4CMD || netbuffer->packettype == PT_CLIENT4MIS))) { G_MoveTiccmd(&playercmds[(UINT8)nodetoplayer2[node]], &netbuffer->u.client2pak.cmd2, 1); @@ -5513,9 +5740,9 @@ static void PT_ClientCmd(INT32 netconsole, SINT8 node) return; } - if (((netbuffer->packettype == PT_CLIENT3CMD || netbuffer->packettype == PT_CLIENT3MIS) - || (netbuffer->packettype == PT_CLIENT4CMD || netbuffer->packettype == PT_CLIENT4MIS)) - && (nodetoplayer3[node] >= 0)) + if ((nodetoplayer3[node] >= 0) && + ((netbuffer->packettype == PT_CLIENT3CMD || netbuffer->packettype == PT_CLIENT3MIS) + || (netbuffer->packettype == PT_CLIENT4CMD || netbuffer->packettype == PT_CLIENT4MIS))) { G_MoveTiccmd(&playercmds[(UINT8)nodetoplayer3[node]], &netbuffer->u.client3pak.cmd3, 1); @@ -5523,8 +5750,8 @@ static void PT_ClientCmd(INT32 netconsole, SINT8 node) return; } - if ((netbuffer->packettype == PT_CLIENT4CMD || netbuffer->packettype == PT_CLIENT4MIS) - && (nodetoplayer4[node] >= 0)) + if ((nodetoplayer4[node] >= 0) && + (netbuffer->packettype == PT_CLIENT4CMD || netbuffer->packettype == PT_CLIENT4MIS)) { G_MoveTiccmd(&playercmds[(UINT8)nodetoplayer4[node]], &netbuffer->u.client4pak.cmd4, 1); @@ -5659,6 +5886,10 @@ static void PT_BasicKeepAlive(INT32 netconsole, SINT8 node) static void PT_TextCmd(INT32 netconsole, SINT8 node) { + size_t j; + tic_t tic; + UINT8 *textcmd; + if (client) return; @@ -5680,79 +5911,84 @@ static void PT_TextCmd(INT32 netconsole, SINT8 node) } if (netconsole < 0 || netconsole >= MAXPLAYERS) - Net_UnAcknowledgePacket(node); - else { - size_t j; - tic_t tic = maketic; - UINT8 *textcmd; - - // ignore if the textcmd has a reported size of zero - // this shouldn't be sent at all - if (!netbuffer->u.textcmd[0]) - { - DEBFILE(va("GetPacket: Textcmd with size 0 detected! (node %u, player %d)\n", - node, netconsole)); - Net_UnAcknowledgePacket(node); - return; - } - - // ignore if the textcmd size var is actually larger than it should be - // BASEPACKETSIZE + 1 (for size) + textcmd[0] should == datalength - if (netbuffer->u.textcmd[0] > (size_t)doomcom->datalength-1) - { - DEBFILE(va("GetPacket: Bad Textcmd packet size! (expected %d, actual %s, node %u, player %d)\n", - netbuffer->u.textcmd[0], sizeu1((size_t)doomcom->datalength-1), - node, netconsole)); - Net_UnAcknowledgePacket(node); - return; - } - - // check if tic that we are making isn't too large else we cannot send it :( - // doomcom->numslots+1 "+1" since doomcom->numslots can change within this time and sent time - j = (software_MAXPACKETLENGTH - (netbuffer->u.textcmd[0]+2+BASESERVERTICSSIZE + (doomcom->numslots+1)*sizeof(ticcmd_t))); - - // search a tic that have enougth space in the ticcmd - while ((textcmd = D_GetExistingTextcmd(tic, netconsole)), - (TotalTextCmdPerTic(tic) > j || netbuffer->u.textcmd[0] + (textcmd ? textcmd[0] : 0) > MAXTEXTCMD) - && tic < firstticstosend + BACKUPTICS) - { - tic++; - } - - if (tic >= firstticstosend + BACKUPTICS) - { - DEBFILE(va("GetPacket: Textcmd too long (max %s, used %s, mak %d, " - "tosend %u, node %u, player %d)\n", sizeu1(j), sizeu2(TotalTextCmdPerTic(maketic)), - maketic, firstticstosend, node, netconsole)); - Net_UnAcknowledgePacket(node); - return; - } - - // Make sure we have a buffer - if (!textcmd) - textcmd = D_GetTextcmd(tic, netconsole); - - DEBFILE(va("textcmd put in tic %u at position %d (player %d) ftts %u mk %u\n", - tic, textcmd[0]+1, netconsole, firstticstosend, maketic)); - - memcpy(&textcmd[textcmd[0]+1], netbuffer->u.textcmd+1, netbuffer->u.textcmd[0]); - textcmd[0] += (UINT8)netbuffer->u.textcmd[0]; + Net_UnAcknowledgePacket(node); + return; } + + // ignore if the textcmd has a reported size of zero + // this shouldn't be sent at all + if (!netbuffer->u.textcmd[0]) + { + DEBFILE(va("GetPacket: Textcmd with size 0 detected! (node %u, player %d)\n", + node, netconsole)); + Net_UnAcknowledgePacket(node); + return; + } + + // ignore if the textcmd size var is actually larger than it should be + // BASEPACKETSIZE + 1 (for size) + textcmd[0] should == datalength + if (netbuffer->u.textcmd[0] > (size_t)doomcom->datalength-1) + { + DEBFILE(va("GetPacket: Bad Textcmd packet size! (expected %d, actual %s, node %u, player %d)\n", + netbuffer->u.textcmd[0], sizeu1((size_t)doomcom->datalength-1), + node, netconsole)); + Net_UnAcknowledgePacket(node); + return; + } + + // check if tic that we are making isn't too large else we cannot send it :( + // doomcom->numslots+1 "+1" since doomcom->numslots can change within this time and sent time + j = (software_MAXPACKETLENGTH - (netbuffer->u.textcmd[0]+2+BASESERVERTICSSIZE + (doomcom->numslots+1)*sizeof(ticcmd_t))); + + tic = maketic; + + // search a tic that have enougth space in the ticcmd + while ((textcmd = D_GetExistingTextcmd(tic, netconsole)), + (TotalTextCmdPerTic(tic) > j || netbuffer->u.textcmd[0] + (textcmd ? textcmd[0] : 0) > MAXTEXTCMD) + && tic < firstticstosend + BACKUPTICS) + { + tic++; + } + + if (tic >= firstticstosend + BACKUPTICS) + { + DEBFILE(va("GetPacket: Textcmd too long (max %s, used %s, mak %d, " + "tosend %u, node %u, player %d)\n", sizeu1(j), sizeu2(TotalTextCmdPerTic(maketic)), + maketic, firstticstosend, node, netconsole)); + Net_UnAcknowledgePacket(node); + return; + } + + // Make sure we have a buffer + if (!textcmd) + textcmd = D_GetTextcmd(tic, netconsole); + + DEBFILE(va("textcmd put in tic %u at position %d (player %d) ftts %u mk %u\n", + tic, textcmd[0]+1, netconsole, firstticstosend, maketic)); + + memcpy(&textcmd[textcmd[0]+1], netbuffer->u.textcmd+1, netbuffer->u.textcmd[0]); + textcmd[0] += (UINT8)netbuffer->u.textcmd[0]; } static void PT_ClientQuit(INT32 netconsole, SINT8 node) { + doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); + if (client) + { + if (node == servernode && cl_mode != CL_SEARCHING && netbuffer->packettype == PT_NODETIMEOUT) + HandleTimeout(node); return; + } // nodeingame will be put false in the execution of kick command // this allow to send some packets to the quitting client to have their ack back nodewaiting[node] = 0; if (netconsole != -1 && playeringame[netconsole]) { - doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); - SendKick(netconsole, (netbuffer->packettype == PT_NODETIMEOUT) ? KICK_MSG_TIMEOUT : KICK_MSG_PLAYER_QUIT); + const int quitreason = ((netbuffer->packettype == PT_NODETIMEOUT) ? KICK_MSG_TIMEOUT : KICK_MSG_PLAYER_QUIT); + SendKick(netconsole, quitreason); } Net_CloseConnection(node); nodeingame[node] = false; @@ -5811,13 +6047,11 @@ static void PT_ServerTics(SINT8 node) realend = gametic + CLIENTBACKUPTICS; cl_packetmissed = realstart > neededtic; - UINT8 *pak = (UINT8 *)&packet->cmds; - UINT8 *txtpak = (UINT8 *)&packet->cmds[packet->numslots * packet->numtics]; - if (realstart <= neededtic && realend > neededtic) { tic_t i, j; - pak = (UINT8 *)&packet->cmds; + UINT8 *pak = (UINT8 *)&packet->cmds; + UINT8 *txtpak = (UINT8 *)&packet->cmds[packet->numslots * packet->numtics]; for (i = realstart; i < realend; i++) { @@ -5938,9 +6172,6 @@ static void HandlePacketFromPlayer(SINT8 node) switch (netbuffer->packettype) { // -------------------------------------------- SERVER RECEIVE ---------- - case PT_RESYNCHGET: - SV_AcknowledgeResynchAck(node, netbuffer->u.resynchgot); - break; case PT_CLIENTCMD: case PT_CLIENT2CMD: case PT_CLIENT3CMD: @@ -5966,24 +6197,6 @@ static void HandlePacketFromPlayer(SINT8 node) case PT_CLIENTQUIT: PT_ClientQuit(netconsole, node); break; -// -------------------------------------------- CLIENT RECEIVE ---------- - case PT_RESYNCHEND: - PT_Resynched(node); - break; - case PT_SERVERTICS: - PT_ServerTics(node); - break; - case PT_RESYNCHING: - PT_Resynching(node); - break; - case PT_PING: - PT_Ping(node); - break; - case PT_SERVERCFG: - break; - case PT_FILEFRAGMENT: - PT_FileFragmentFromPlayer(node); - break; #ifdef SATURNPAK case PT_CANRECEIVEGAMESTATE: PT_CanReceiveGamestate(node); @@ -5991,6 +6204,25 @@ static void HandlePacketFromPlayer(SINT8 node) case PT_RECEIVEDGAMESTATE: PT_ReceivedGamestate(node); break; +#endif + case PT_SERVERINFO: + PT_ServerInfo(node); + break; + case PT_RESYNCHGET: + SV_AcknowledgeResynchAck(node, netbuffer->u.resynchgot); + break; +// -------------------------------------------- CLIENT RECEIVE ---------- + case PT_SERVERTICS: + PT_ServerTics(node); + break; + case PT_PING: + PT_Ping(node); + break; + + case PT_FILEFRAGMENT: + PT_FileFragmentFromPlayer(node); + break; +#ifdef SATURNPAK case PT_WILLRESENDGAMESTATE: PT_WillResendGamestate(); break; @@ -5999,6 +6231,20 @@ static void HandlePacketFromPlayer(SINT8 node) is_client_saturn[node] = true; break; #endif + case PT_SERVERSHUTDOWN: + PT_ServerShutdown(node); + break; + case PT_SERVERCFG: + break; + case PT_CLIENTJOIN: + PT_ClientJoin(node); + break; + case PT_RESYNCHING: + PT_Resynching(node); + break; + case PT_RESYNCHEND: + PT_Resynched(node); + break; default: DEBFILE(va("UNKNOWN PACKET TYPE RECEIVED %d from host %d\n", netbuffer->packettype, node)); } @@ -6019,36 +6265,6 @@ static void GetPackets(void) { node = (SINT8)doomcom->remotenode; - if (server && netbuffer->packettype == PT_CLIENTJOIN) - { - if (!levelloading) // Otherwise just ignore - { - HandleConnect(node); - } - - continue; - } - - if (client && node == servernode && cl_mode != CL_SEARCHING) - { - if (netbuffer->packettype == PT_SERVERSHUTDOWN) - { - HandleShutdown(node); - continue; - } - if (netbuffer->packettype == PT_NODETIMEOUT) - { - HandleTimeout(node); - continue; - } - } - - if (netbuffer->packettype == PT_SERVERINFO) - { - HandleServerInfo(node); - continue; - } - /*if (netbuffer->packettype == PT_PLAYERINFO) continue; // We do nothing with PLAYERINFO, that's for the MS browser. Not quite true anymore :p*/ @@ -6367,21 +6583,7 @@ static void CL_SendClientCmd(void) { if (localtextcmd[i][0]) { - switch (i) - { - case 3: - netbuffer->packettype = PT_TEXTCMD4; - break; - case 2: - netbuffer->packettype = PT_TEXTCMD3; - break; - case 1: - netbuffer->packettype = PT_TEXTCMD2; - break; - default: - netbuffer->packettype = PT_TEXTCMD; - break; - } + netbuffer->packettype = PT_TEXTCMD + i; memcpy(netbuffer->u.textcmd, localtextcmd[i], localtextcmd[i][0]+1); @@ -6425,7 +6627,7 @@ static void SV_SendTics(void) continue; // assert supposedtics[n]>=nettics[n] - realfirsttic = max(supposedtics[n], firstticstosend); + realfirsttic = supposedtics[n]; lasttictosend = min(maketic, nettics[n] + CLIENTBACKUPTICS); if (realfirsttic >= lasttictosend) @@ -6599,7 +6801,7 @@ void SV_SpawnPlayer(INT32 playernum, INT32 x, INT32 y, angle_t angle) // create missed tic static void SV_Maketic(void) { - G_MoveTiccmd(netcmds[maketic % BACKUPTICS], playercmds, MAXPLAYERS); + G_CopyTiccmd(netcmds[maketic % BACKUPTICS], playercmds, MAXPLAYERS); maketic++; } @@ -6686,10 +6888,13 @@ boolean TryRunTics(tic_t realtics) { boolean update_stats = !(paused || P_AutoPause()); - DEBFILE(va("============ Running tic %d (local %d)\n", gametic, localgametic)); + DEBFILE(va("============ Running tic %d (local %d)\n", gametic, leveltime)); if (update_stats) + { + ps_prevtictime = ps_tictime; PS_START_TIMING(ps_tictime); + } G_Ticker((gametic % NEWTICRATERATIO) == 0); ExtraDataTicker(); @@ -6816,8 +7021,10 @@ static inline void PingUpdate(void) //send out our ping packets for (i = 0; i < MAXNETNODES; i++) + { if (nodeingame[i]) HSendPacket(i, true, 0, sizeof(INT32) * (MAXPLAYERS+1)); + } pingmeasurecount = 0; //Reset count } @@ -6834,10 +7041,12 @@ static void UpdatePingTable(void) INT32 i; + const boolean playing = Playing(); + if (server) { - //if (Playing() && !(gametime % 8)) // Value chosen based on _my vibes man_ << dont do this for v8 atleast, this is placeboeing ppl to hell and back - if (Playing() && !(gametime % 35)) // update once per second. + //if (playing && !(gametime % 8)) // Value chosen based on _my vibes man_ << dont do this for v8 atleast, this is placeboeing ppl to hell and back + if (playing && !(gametime % 35)) // update once per second. PingUpdate(); fastest = 0; @@ -6896,6 +7105,10 @@ static void UpdatePingTable(void) else lowest_lag = simulated_lag = 0; } + + // this is really dumb but oh well + if (playing && !(gametime % 35)) + localplayerping = playerpingtable[consoleplayer]; } #ifdef HOLEPUNCH @@ -6920,10 +7133,15 @@ static void RenewHolePunch(void) static void HandleNodeTimeouts(void) { INT32 i; + if (server) + { for (i = 1; i < MAXNETNODES; i++) + { if (nodeingame[i] && freezetimeout[i] < I_GetTime()) Net_ConnectionTimeout(i); + } + } } // Keep the network alive while not advancing tics! @@ -7133,11 +7351,13 @@ void NetUpdate(void) } for (i = 0; i < MAXNETNODES; ++i) + { if (resynch_inprogress[i]) { SV_SendResynch(i); counts = -666; } + } // Do not make tics while resynching if (counts != -666) @@ -7164,6 +7384,8 @@ void NetUpdate(void) Net_AckTicker(); HandleNodeTimeouts(); + nowtime /= NEWTICRATERATIO; + if (nowtime > resptime) { resptime = nowtime; @@ -7189,9 +7411,15 @@ void NetUpdate(void) INT32 D_NumPlayers(void) { INT32 num = 0, ix; + for (ix = 0; ix < MAXPLAYERS; ix++) + { if (playeringame[ix]) + { num++; + } + } + return num; } @@ -7218,7 +7446,7 @@ void CL_ClearRewinds(void) rewind_t *CL_SaveRewindPoint(size_t demopos) { - savebuffer_t save = {0}; + savebuffer_t save = {}; rewind_t *rewind; if (rewindhead && rewindhead->leveltime + REWIND_POINT_INTERVAL > leveltime) @@ -7241,7 +7469,7 @@ rewind_t *CL_SaveRewindPoint(size_t demopos) rewind_t *CL_RewindToTime(tic_t time) { - savebuffer_t save = {0}; + savebuffer_t save = {}; rewind_t *rewind; while (rewindhead && rewindhead->leveltime > time) diff --git a/src/d_clisrv.h b/src/d_clisrv.h index 430729bc2..16602976c 100644 --- a/src/d_clisrv.h +++ b/src/d_clisrv.h @@ -339,13 +339,17 @@ typedef struct UINT8 clientnode; UINT8 gamestate; +#ifndef PHOBOS_BUILD // 0xFF == not in game; else player skin num UINT8 playerskins[MAXPLAYERS]; UINT8 playercolor[MAXPLAYERS]; +#endif UINT8 gametype; UINT8 modifiedgame; +#ifndef PHOBOS_BUILD SINT8 adminplayers[MAXPLAYERS]; // Needs to be signed +#endif char server_context[8]; // Unique context id, generated at server startup. @@ -354,7 +358,9 @@ typedef struct boolean allownewplayer; boolean discordinvites; +#ifndef PHOBOS_BUILD UINT8 varlengthinputs[0]; // Playernames and netvars +#endif } ATTRPACK serverconfig_pak; typedef struct { @@ -444,7 +450,7 @@ typedef struct char name[MAXPLAYERNAME+1]; UINT8 address[4]; // sending another string would run us up against MAXPACKETLENGTH UINT8 team; - UINT8 skin; + skinnum_t skin; UINT8 data; // Color is first four bits, hasflag, isit and issuper have one bit each, the last is unused. UINT32 score; UINT16 timeinserver; // In seconds. @@ -454,7 +460,7 @@ typedef struct typedef struct { char name[MAXPLAYERNAME+1]; - UINT8 skin; + skinnum_t skin; UINT8 color; UINT32 pflags; UINT32 score; @@ -600,6 +606,8 @@ extern consvar_t cv_discordinvites; extern consvar_t cv_serverinfoscreen; +extern consvar_t cv_serveraddoninfo; + // Used in d_net, the only dependence //tic_t ExpandTics(INT32 low, tic_t basetic); void D_ClientServerInit(void); @@ -648,21 +656,25 @@ extern UINT8 playernode[MAXPLAYERS]; extern boolean player_muted[MAXPLAYERS]; +extern UINT32 localplayerping; + INT32 D_NumPlayers(void); void D_ResetTiccmds(void); tic_t GetLag(INT32 node); -extern UINT8 hu_resynching; +extern boolean hu_resynching; #ifdef SATURNPAK -extern UINT8 hu_redownloadinggamestate; +extern boolean hu_redownloadinggamestate; #endif extern boolean hu_stopped; // kart, true when the game is stopped for players due to a disconnecting or connecting player +#define SAVEGAMESIZE (768*1024) + typedef struct rewind_s { - UINT8 savebuffer[(768*1024)]; + UINT8 savebuffer[SAVEGAMESIZE]; tic_t leveltime; size_t demopos; diff --git a/src/d_main.c b/src/d_main.c index c46ef0c44..a3a769dac 100644 --- a/src/d_main.c +++ b/src/d_main.c @@ -79,6 +79,32 @@ #include "core/memory.h" #include "lua_script.h" +#include "lua_profile.h" + +/* Manually defined asset hashes for non-CMake builds + * Last updated 2015 / 05 / 03 - SRB2 v2.1.15 - srb2.srb + * Last updated 2018 / 12 / 23 - SRB2 v2.1.22 - patch.dta + * Last updated 2019 / 01 / 18 - Kart v1.0.2 - Main assets + * Last updated 2020 / 08 / 30 - Kart v1.3 - patch.kart + * Last updated 2022 / 08 / 16 - Kart v1.4 - Main assets + * Last updated 2022 / 08 / 19 - Kart v1.5 - gfx.kart + * Last updated 2022 / 11 / 01 - Kart v1.6 - gfx.kart, maps.kart + */ + +// Base SRB2 hashes +#define ASSET_HASH_SRB2_SRB "c1b9577687f8a795104aef4600720ea7" +#ifdef USE_PATCH_DTA +#define ASSET_HASH_PATCH_DTA "b04fd9624bfd94dc96dcf4f400f7deb4" +#endif + +// SRB2Kart-specific hashes +#define ASSET_HASH_GFX_KART "06f86ee16136eb8a7043b15001797034" +#define ASSET_HASH_TEXTURES_KART "abb53d56aba47c3a8cb0f764da1c8b80" +#define ASSET_HASH_CHARS_KART "e2c428347dde52858a3dacd29fc5b964" +#define ASSET_HASH_MAPS_KART "d051e55141ba736582228c456953cd98" +#ifdef USE_PATCH_KART +#define ASSET_HASH_PATCH_KART "00000000000000000000000000000000" +#endif #ifdef CMAKECONFIG #include "config.h" @@ -105,14 +131,15 @@ static size_t startuppwadcount = 0; // autoloading static char *autoloadwadfiles[MAX_WADFILES]; static char *autoloadwadfilespost[MAX_WADFILES]; -static size_t autoloadcount = 0; -static size_t postloadcount = 0; +static size_t autoloadwadcount = 0; +static size_t postloadwadcount = 0; // boolean devparm = false; // started game with -devparm boolean singletics = false; // timedemo boolean lastdraw = false; +boolean intermissionbginit = false; #ifdef MOTIONBLUR INT32 postimgparam[MAXSPLITSCREENPLAYERS]; @@ -128,7 +155,7 @@ boolean music_disabled = false; INT32 debugload = 0; #endif -char savegamename[256]; +char savegamename[256] = {}; char srb2home[256] = "."; char srb2path[256] = "."; @@ -249,24 +276,6 @@ static void D_Renderview(void) R_ApplyLevelInterpolators(R_GetTimeFrac(RTF_LEVEL)); - if (rendermode == render_soft) - { - // if this is display player 1 - if (cv_homremoval.value) - { - if (cv_homremoval.value == 1) - { - // Clear the software screen buffer to remove HOM - memset(vid.screens[0], 31, vid.width * vid.height); - } - else if (cv_homremoval.value == 2) - { - //'development' HOM removal -- makes it blindingly obvious if HOM is spotted. - memset(vid.screens[0], 32+(timeinmap&15), vid.width * vid.height); - } - } - } - for (i = 0; i <= splitscreen; i++) { if (!P_MobjWasRemoved(players[displayplayers[i]].mo) || players[displayplayers[i]].playerstate == PST_DEAD) @@ -297,7 +306,6 @@ static void D_Renderview(void) break; default: // Initialize for P1 viewwindowy = viewwindowx = 0; - objectsdrawn = 0; break; } @@ -308,19 +316,17 @@ static void D_Renderview(void) } else if (rendermode == render_soft) #endif + { R_RenderPlayerView(&players[displayplayers[i]]); - } - - if (rendermode == render_soft) - { - if (i == 0) - R_ApplyViewMorph(); + if (i == 0) + R_ApplyViewMorph(); #ifdef MOTIONBLUR - V_DoPostProcessor(i, postimgparam[i]); + V_DoPostProcessor(i, postimgparam[i]); #else - V_DoPostProcessor(i, 0); + V_DoPostProcessor(i, 0); #endif + } } } @@ -344,6 +350,33 @@ static void D_Renderview(void) // added comment : there is a wipe eatch change of the gamestate gamestate_t wipegamestate = GS_LEVEL; +static void D_MakeIntermissionBG(void) +{ + if (!lastdraw) + return; + + if (rendermode == render_none) + { + lastdraw = false; + intermissionbginit = false; + return; + } + +#ifdef HWRENDER + if (rendermode == render_opengl) + { + HWR_MakeScreenTexture(); + } + else +#endif + { + VID_BlitLinearScreen(vid.screens[0], vid.screens[1], vid.width, vid.height, vid.width, vid.width); + } + + lastdraw = false; + intermissionbginit = true; +} + static boolean D_Display(void) { boolean ranwipe = false; @@ -509,16 +542,8 @@ static boolean D_Display(void) PS_START_TIMING(ps_rendercalltime); D_Renderview(); PS_STOP_TIMING(ps_rendercalltime); - } - if (lastdraw) - { - if (rendermode == render_soft) - { - VID_BlitLinearScreen(vid.screens[0], vid.screens[1], vid.width, vid.height, vid.width, vid.width); - } - - lastdraw = false; + D_MakeIntermissionBG(); } PS_START_TIMING(ps_uitime); @@ -620,6 +645,11 @@ static boolean D_Display(void) CON_Drawer(); // Ha, i LIED! + if (cv_lua_profile.value > 0) + { + LUA_RenderTimers(); + } + PS_START_TIMING(ps_swaptime); I_FinishUpdate(); // page flip or blit buffer PS_STOP_TIMING(ps_swaptime); @@ -639,7 +669,7 @@ void D_SRB2Loop(void) tic_t entertic = 0, oldentertics = 0, realtics = 0, rendertimeout = INFTICS; double deltatics = 0.0; double deltasecs = 0.0; - UINT64 precision; + UINT64 precision = 0; boolean interp = false; boolean doDisplay = false; @@ -684,8 +714,12 @@ void D_SRB2Loop(void) precise_t elapsed; precise_t enterprecise, finishprecise; + boolean ranwipe = false; + enterprecise = I_GetPreciseTime(); + I_HandleInterrupt(); + memset(&g_dc, 0, sizeof(g_dc)); Z_Frame_Reset(); @@ -693,8 +727,6 @@ void D_SRB2Loop(void) const UINT32 framecap = R_GetFramerateCap(); capbudget = (framecap == 0) ? 0 : (precise_t)((double)precision / (double)framecap + 0.5); // + 0.5 instead of round - boolean ranwipe = false; - I_UpdateTime(cv_timescale.value); if (lastwipetic) @@ -758,11 +790,6 @@ void D_SRB2Loop(void) doDisplay = true; } - - if (!dedicated) - { - G_DeviceLEDTick(); - } } if (interp) @@ -804,6 +831,13 @@ void D_SRB2Loop(void) if (takescreenshot) M_DoScreenShot(); +#ifndef DEDICATED + if (!dedicated && renderisnewtic) + { + G_DeviceLEDTick(); + } +#endif + // consoleplayer -> displayplayers (hear sounds from viewpoint) S_UpdateSounds(); // move positional sounds @@ -882,7 +916,9 @@ void D_ClearState(void) // okay, stop now // (otherwise the game still thinks we're playing!) +#ifdef HAVE_CURL CURLAbortFile(); +#endif SV_StopServer(); SV_ResetServer(); @@ -946,6 +982,9 @@ void D_ClearState(void) // void D_StartTitle(void) { + if (dedicated) + I_Error("D_StartTitle is called on dedicated server"); + D_ClearState(); multiplayer = netgame = false; // title menu shouldnt be a netgame or multiplayer lmao F_StartTitleScreen(); @@ -1007,25 +1046,38 @@ static INT32 D_DetectFileType(const char* filename) } // autoload that shit -static void D_AutoloadFile(const char *file, char **filearray, size_t index) +static void D_AutoloadFile(const char *file, char **filearray, size_t *index) { char *newfile; INT32 fileType = D_DetectFileType(file); + if (*index >= MAX_WADFILES) + { + CONS_Printf("D_AutoloadFile: Failed to add file %s! Too many autoloaded files\n", file); + return; + } + if (!fileType) { CONS_Printf("D_AutoloadFile: File %s is unknown or invalid\n", file); return; } + if (fileType == 1) + { + CONS_Printf("D_AutoloadFile: File %s is a directory\n", file); + return; + } + if (fileType <= 6) { newfile = malloc(strlen(file) + 1); if (!newfile) - I_Error("No more free memory to AutoloadFile %s",file); + I_Error("D_AutoloadFile: No more free memory to autoload file %s", file); strcpy(newfile, file); - filearray[index] = newfile; + filearray[*index] = newfile; + (*index)++; } else { @@ -1068,7 +1120,7 @@ static void D_FindAddonsToAutoload(void) // If the file is found, run our shit if (!autoloadconfigfile) // nope outta here { - autoloadcount = postloadcount = 0; // so D_AddAutoloadFiles can skip everything since nothings there to autoload + autoloadwadcount = postloadwadcount = 0; // so D_AddAutoloadFiles can skip everything since nothings there to autoload return; } @@ -1094,27 +1146,34 @@ static void D_FindAddonsToAutoload(void) if (newline) *newline = '\0'; + // ok so theres still issues with players adding stuff to autoload by accident + // sometimes this stuff contains maps + // you can probably imagine how that goes in a netgame.... + if (W_CheckAutoLoadContainsMap(wadsToAutoload)) + { + CONS_Alert(CONS_WARNING, "Autoload: file %s contains map data, this WILL cause crashes and desynchs! skipping...\n", wadsToAutoload); + continue; + } + if (!postload && W_CheckPostLoadList(wadsToAutoload)) { - CONS_Printf("forcing postload for file %s\n", wadsToAutoload); + CONS_Printf("Autoload: forcing postload for file %s\n", wadsToAutoload); postload = true; } // LOAD IT if (!postload) { - D_AutoloadFile(wadsToAutoload, autoloadwadfiles, autoloadcount); - autoloadcount++; + D_AutoloadFile(wadsToAutoload, autoloadwadfiles, &autoloadwadcount); } else { - D_AutoloadFile(wadsToAutoload, autoloadwadfilespost, postloadcount); - postloadcount++; + D_AutoloadFile(wadsToAutoload, autoloadwadfilespost, &postloadwadcount); } } - autoloadwadfiles[autoloadcount] = NULL; - autoloadwadfilespost[postloadcount] = NULL; + autoloadwadfiles[autoloadwadcount] = NULL; + autoloadwadfilespost[postloadwadcount] = NULL; // we dont want memory leaks around here do we? fclose(autoloadconfigfile); @@ -1123,7 +1182,7 @@ static void D_FindAddonsToAutoload(void) static void D_AddAutoloadFiles(void) { // nothing to autoload - if (autoloadcount == 0) + if (autoloadwadcount == 0) return; CONS_Printf("D_AutoloadFile(): Loading autoloaded addons...\n"); @@ -1131,15 +1190,15 @@ static void D_AddAutoloadFiles(void) if (W_AddAutoloadedLocalFiles(autoloadwadfiles) == 0) CONS_Printf("D_AutoloadFile(): Are you sure you put in valid files or what?\n"); - D_CleanFile(autoloadwadfiles, autoloadcount); + D_CleanFile(autoloadwadfiles, autoloadwadcount); - autoloadcount = 0; + autoloadwadcount = 0; } void D_AddPostloadFiles(void) { // nothing to postload - if (postloadcount == 0 || !netgame) + if (postloadwadcount == 0 || !netgame) return; CONS_Printf("D_AddPostloadFiles(): Loading postloaded addons...\n"); @@ -1147,9 +1206,9 @@ void D_AddPostloadFiles(void) if (W_AddAutoloadedLocalFiles(autoloadwadfilespost) == 0) CONS_Printf("D_AddPostloadFiles(): Are you sure you put in valid files or what?\n"); - D_CleanFile(autoloadwadfilespost, postloadcount); + D_CleanFile(autoloadwadfilespost, postloadwadcount); - postloadcount = 0; + postloadwadcount = 0; } // ========================================================================== @@ -1158,7 +1217,7 @@ void D_AddPostloadFiles(void) static boolean AddIWAD(const char * file, const char *dir) { - char * path = va(pandf, dir, file); + char *path = va(pandf, dir, file); if (FIL_ReadFileOK(path)) { @@ -1186,17 +1245,13 @@ static void IdentifyVersion(void) #endif char tempsrb2path[256] = "."; - getcwd(tempsrb2path, 256); + if (I_GetCwd(tempsrb2path, 256) == NULL) + strcpy(tempsrb2path, "."); // get the current directory (possible problem on NT with "." as current dir) if (!srb2waddir) { - if (tempsrb2path[0]) - srb2waddir = tempsrb2path; - else - { - srb2waddir = "."; - } + srb2waddir = tempsrb2path; } #if (1) // reduce the amount of findfile by only using full cwd in this func @@ -1290,20 +1345,24 @@ static void IdentifyVersion(void) // // search for maps // -static void D_CheckMaps(boolean checkreplaced) +static void D_CheckMapReplacements(boolean pwad) { INT32 i; char *name; UINT16 wadnum; lumpinfo_t *lumpinfo; + size_t numfiles; - for (wadnum = 0; wadnum < mainwads; wadnum++) + wadnum = pwad ? (mainwads+1) : 0; + numfiles = pwad ? numwadfiles : mainwads; + + for (; wadnum < numfiles; wadnum++) { lumpinfo = wadfiles[wadnum]->lumpinfo; for (i = 0; i < wadfiles[wadnum]->numlumps; i++, lumpinfo++) { name = lumpinfo->name; - P_CheckMapReplacements(name, checkreplaced); + P_CheckMapReplacements(name, pwad); } } } @@ -1339,8 +1398,6 @@ static inline void D_MakeTitleString(char *s) // extra graphic patches for saturn specific thingies boolean xtra_speedo = false; // extra speedometer check boolean xtra_speedo_clr = false; // extra speedometer colour check -boolean xtra_speedo3 = false; // 80x 11 extra speedometer check -boolean xtra_speedo_clr3 = false; // 80x 11 extra speedometer colour check boolean achi_speedo = false; // achiiro speedometer check boolean achi_speedo_clr = false; // extra speedometer colour check boolean dial_speedo = false; // dial speedometer check @@ -1370,7 +1427,6 @@ static void D_CheckSaturnExtraFiles(void) CV_PossibleValue_t minimapdot_cons_temp[NUMMINIMAPDOTSTUFF] = {{0, "Off"}, {0, NULL}, {0, NULL}, {0, NULL}, {0, NULL}}; unsigned last_speedo_i = 0; - unsigned last_driftgauge_i = 3; unsigned last_inputdisplay_i = 2; unsigned last_minimapdot_i = 0; #define PUSHCONS(cons, i, id, name) { ++i; cons[i].value = id; cons[i].strvalue = name; } @@ -1529,20 +1585,6 @@ static void D_CheckSaturnExtraFiles(void) if (found_extra3_kart) { mainwads++; - - // 80x11 speedometer crap - if (W_LumpExists("SP_SM3TC")) - { - xtra_speedo3 = true; - PUSHCONS(speedo_cons_temp, last_speedo_i, 7, "Extra"); - PUSHCONS(driftgaugestyle_cons_temp, last_driftgauge_i, 5, "Extra"); - } - - // 80x11 speedometer crap but colour - if (W_LumpExists("SC_SM3TC")) - { - xtra_speedo_clr3 = true; - } } #undef PUSHCONS @@ -1617,12 +1659,6 @@ void D_SRB2Main(void) strcpy(srb2, "SRB2Kart"); D_MakeTitleString(srb2); -#if defined (__OS2__) && !defined (HAVE_SDL) - // set PM window title - snprintf(pmData->title, sizeof (pmData->title), "SRB2Kart" VERSIONSTRING ": %s", title); - pmData->title[sizeof (pmData->title) - 1] = '\0'; -#endif - if (devparm) CONS_Printf(M_GetText("Development mode ON.\n")); @@ -1746,10 +1782,6 @@ void D_SRB2Main(void) // Setup default unlockable conditions M_SetupDefaultConditionSets(); - // Setup character tables - // Have to be done here before files are loaded - M_InitCharacterTables(); - // load wad, including the main wad file CONS_Printf("W_InitMultipleFiles(): Adding IWAD and main PWADs.\n"); @@ -1793,17 +1825,19 @@ void D_SRB2Main(void) // conversion sometimes needs the palette V_ReloadPalette(); - D_CheckMaps(false); + D_CheckMapReplacements(false); - W_InitMultipleFiles(startuppwads, startuppwadcount, true); - - // Only search for pwad maps if we actually have a pwad added if (startuppwadcount > 0) { - D_CheckMaps(true); + CONS_Printf("W_InitMultipleFiles(): Adding extra PWADs.\n"); + W_InitMultipleFiles(startuppwads, startuppwadcount, true); + + // Only search for pwad maps if we actually have a pwad added + D_CheckMapReplacements(true); + + D_CleanFile(startuppwads, startuppwadcount); } - D_CleanFile(startuppwads, startuppwadcount); startuppwadcount = 0; cht_Init(); @@ -1869,7 +1903,8 @@ void D_SRB2Main(void) if (M_CheckParm("-warp") && M_IsNextParm()) { const char *word = M_GetNextParm(); - pstartmap = G_FindMapByNameOrCode(word, 0); + pstartmap = G_FindMapByNameOrCode(word, NULL); + if (! pstartmap) I_Error("Cannot find a map remotely named '%s'\n", word); else @@ -1889,7 +1924,7 @@ void D_SRB2Main(void) CONS_Printf("R_Init(): Init SRB2 refresh daemon.\n"); R_Init(); -#if SOUND==SOUND_DUMMY +#if SOUND == SOUND_DUMMY sound_disabled = true; music_disabled = true; #else @@ -2002,9 +2037,13 @@ void D_SRB2Main(void) if (M_CheckProtoParam("replay")) { const char *replayurl = M_GetProtoParam(); - char *replayname = strrchr(replayurl, '/'); - if (!replayname || !replayurl) + if (!replayurl) + I_Error("REPLAY: Invalid URL."); + + gconst char *replayname = strrchr(replayurl, '/'); + + if (!replayname) I_Error("REPLAY: Invalid URL."); #define REPLAYDIR "/DownloadedReplays/" @@ -2118,8 +2157,8 @@ void D_SRB2Main(void) if (dedicated && server) { - levelstarttic = gametic; G_SetGamestate(GS_LEVEL); + if (!P_SetupLevel(false, false)) I_Quit(); // fail so reset game stuff } diff --git a/src/d_main.h b/src/d_main.h index 8f1475706..8bbf79df0 100644 --- a/src/d_main.h +++ b/src/d_main.h @@ -38,8 +38,6 @@ extern boolean found_extra3_kart; // for use in k_kart.c extern boolean xtra_speedo; // extra speedometer check extern boolean xtra_speedo_clr; // extra speedometer colour check -extern boolean xtra_speedo3; // 80x11 extra speedometer check -extern boolean xtra_speedo_clr3; // 80x11 extra speedometer colour check extern boolean achi_speedo; // achiiro speedometer check extern boolean achi_speedo_clr; // extra speedometer colour check extern boolean dial_speedo; // dial speedometer check diff --git a/src/d_net.c b/src/d_net.c index 59b31a1fb..a11dd3401 100644 --- a/src/d_net.c +++ b/src/d_net.c @@ -59,7 +59,7 @@ static INT16 reboundsize[MAXREBOUND]; static INT32 rebound_head, rebound_tail; /// \brief max length per packet -INT16 hardware_MAXPACKETLENGTH; +INT16 hardware_MAXPACKETLENGTH = 0; boolean (*I_NetGet)(void) = NULL; void (*I_NetSend)(void) = NULL; @@ -96,7 +96,7 @@ INT32 ticruned = 0, ticmiss = 0; // globals INT32 getbps = 0, sendbps = 0; -float lostpercent = 0, duppercent = 0, gamelostpercent = 0; +float lostpercent = 0.0f, duppercent = 0.0f, gamelostpercent = 0.0f; INT32 packetheaderlength = 0; boolean Net_GetNetStat(void) @@ -612,12 +612,8 @@ void Net_WaitAllAckReceived(UINT32 timeout) static void InitNode(node_t *node) { - node->acktosend_head = node->acktosend_tail = 0; - memset(node->acktosend, 0, sizeof(node->acktosend)); - node->firstacktosend = 0; + memset(node, 0, sizeof(node_t)); node->nextacknum = 1; - node->remotefirstack = 0; - node->flags = 0; } static void InitAck(void) @@ -1319,7 +1315,9 @@ boolean D_CheckNetGame(void) while (!debugfile && k < MAXPLAYERS) { k++; - sprintf(filename, "debug%d.txt", k); + + snprintf(filename, sizeof(filename), "debug%d.txt", k); + debugfile = fopen(va("%s" PATHSEP "%s", srb2home, filename), "w"); } diff --git a/src/d_net.h b/src/d_net.h index f170cdf05..739b4f2fb 100644 --- a/src/d_net.h +++ b/src/d_net.h @@ -27,7 +27,6 @@ extern "C" { // SINT8 is used for nodes sometimes >:( #define MAXNETNODES 127 #define BROADCASTADDR MAXNETNODES -#define NETSPLITSCREEN // Kart's splitscreen netgame feature #define STATLENGTH (TICRATE*2) diff --git a/src/d_netcmd.c b/src/d_netcmd.c index 8fca12794..f0ebc5fc4 100644 --- a/src/d_netcmd.c +++ b/src/d_netcmd.c @@ -47,6 +47,7 @@ #include "z_zone.h" #include "lua_script.h" #include "lua_hook.h" +#include "lua_profile.h" #include "m_cond.h" #include "m_anigif.h" #include "k_kart.h" // SRB2kart @@ -54,6 +55,9 @@ #include "fastcmp.h" #include "m_perfstats.h" +#include "r_data.h" +#include "r_skins.h" + #ifdef NETGAME_DEVMODE #define CV_RESTRICT CV_NETVAR #else @@ -147,6 +151,7 @@ static void Command_ListWADS_f(void); static void Command_LocateLump_f(void); static void Command_ListDoomednums_f(void); static void Command_ListUnusedSprites_f(void); +static void Command_ListUnusedMapSlots_f(void); static void Command_RunSOC(void); static void Command_Pause(void); static void Command_Respawn(void); @@ -249,7 +254,7 @@ consvar_t cv_competitionboxes = {"competitionboxes", "Random", CV_NETVAR|CV_CHEA #ifdef SEENAMES static CV_PossibleValue_t seenames_cons_t[] = {{0, "Off"}, {1, "Colorless"}, {2, "Team"}, {3, "Ally/Foe"}, {0, NULL}}; -consvar_t cv_seenames = {"seenames", "Off", CV_SAVE, seenames_cons_t, 0, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_seenames = {"seenames", "Off", CV_SAVE, seenames_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_allowseenames = {"allowseenames", "No", CV_NETVAR, CV_YesNo, NULL, 0, NULL, NULL, 0, 0, NULL}; #endif @@ -430,10 +435,18 @@ consvar_t cv_pointlimit = {"pointlimit", "0", CV_NETVAR|CV_CALL|CV_NOINIT, point static CV_PossibleValue_t timelimit_cons_t[] = {{0, "MIN"}, {30, "MAX"}, {0, NULL}}; consvar_t cv_timelimit = {"timelimit", "0", CV_NETVAR|CV_CALL|CV_NOINIT, timelimit_cons_t, TimeLimit_OnChange, 0, NULL, NULL, 0, 0, NULL}; +#ifdef PHOBOS_BUILD +static CV_PossibleValue_t numlaps_cons_t[] = {{1, "MIN"}, {255, "MAX"}, {0, NULL}}; +#else static CV_PossibleValue_t numlaps_cons_t[] = {{1, "MIN"}, {50, "MAX"}, {0, NULL}}; +#endif consvar_t cv_numlaps = {"numlaps", "3", CV_NETVAR|CV_CALL|CV_NOINIT, numlaps_cons_t, NumLaps_OnChange, 0, NULL, NULL, 0, 0, NULL}; +#ifdef PHOBOS_BUILD +static CV_PossibleValue_t basenumlaps_cons_t[] = {{1, "MIN"}, {255, "MAX"}, {0, "Map default"}, {0, NULL}}; +#else static CV_PossibleValue_t basenumlaps_cons_t[] = {{1, "MIN"}, {50, "MAX"}, {0, "Map default"}, {0, NULL}}; +#endif consvar_t cv_basenumlaps = {"basenumlaps", "Map default", CV_NETVAR|CV_CALL|CV_CHEAT, basenumlaps_cons_t, BaseNumLaps_OnChange, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_forceskin = {"forceskin", "Off", CV_NETVAR|CV_CALL|CV_CHEAT, Forceskin_cons_t, ForceSkin_OnChange, 0, NULL, NULL, 0, 0, NULL}; @@ -458,16 +471,16 @@ consvar_t cv_showping = {"showping", "Always", CV_SAVE, showping_cons_t, NULL, 0 static CV_PossibleValue_t pingmeasurement_cons_t[] = {{0, "Frames"}, {1, "Milliseconds"}, {0, NULL}}; consvar_t cv_pingmeasurement = {"pingmeasurement", "Frames", CV_SAVE, pingmeasurement_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_pingicon = {"pingicon", "On", CV_SAVE, CV_OnOff, 0, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_pingicon = {"pingicon", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; static CV_PossibleValue_t cv_pingstyle_cons_t[] = {{0, "New"}, {1, "Old"}, {0, NULL}}; -consvar_t cv_pingstyle = {"pingstyle", "New", CV_SAVE, cv_pingstyle_cons_t, 0, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_pingstyle = {"pingstyle", "New", CV_SAVE, cv_pingstyle_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_luaimmersion = {"luaimmersion", "On", CV_SAVE, CV_OnOff, 0, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_luaimmersion = {"luaimmersion", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_showviewpointtext = {"showviewpointtext", "On", CV_SAVE, CV_OnOff, 0, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_showviewpointtext = {"showviewpointtext", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_showdownloadprompt = {"showdownloadprompt", "On", CV_SAVE, CV_OnOff, 0, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_showdownloadprompt = {"showdownloadprompt", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; // Intermission time Tails 04-19-2002 static CV_PossibleValue_t inttime_cons_t[] = {{0, "MIN"}, {3600, "MAX"}, {0, NULL}}; @@ -502,6 +515,9 @@ static CV_PossibleValue_t ps_descriptor_cons_t[] = { {1, "Average"}, {2, "SD"}, {3, "Minimum"}, {4, "Maximum"}, {0, NULL}}; consvar_t cv_ps_descriptor = {"ps_descriptor", "Average", 0, ps_descriptor_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; +//consvar_t cv_lua_profile = {"lua_profile", "0").values(CV_Unsigned).onchange(lua_profile_OnChange).description("Show hook timings over an average of N tics"); +consvar_t cv_lua_profile = {"lua_profile", "0", CV_CALL, CV_Unsigned, lua_profile_OnChange, 0, NULL, NULL, 0, 0, NULL}; + // only there to better keep track of it globally consvar_t cv_director = {"director", "Off", CV_HIDEN, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; @@ -562,6 +578,7 @@ const char *netxcmdnames[MAXNETXCMD - 1] = "MODIFYVOTE", "PICKVOTE", "REMOVEPLAYER", + "DISCORD", "LUACMD", "LUAVAR" }; @@ -595,6 +612,12 @@ void D_RegisterServerCommands(void) Forceskin_cons_t[i].value = 0; Forceskin_cons_t[i].strvalue = NULL; } + + // Set default player names + // Monster Iestyn (12/08/19): not sure where else I could have actually put this, but oh well + for (i = 0; i < MAXPLAYERS; i++) + snprintf(player_names[i], sizeof(player_names[i]), "Player %d", 1 + i); + RegisterNetXCmd(XD_NAMEANDCOLOR, Got_NameAndColor); RegisterNetXCmd(XD_WEAPONPREF, Got_WeaponPref); RegisterNetXCmd(XD_MAP, Got_Mapcmd); @@ -642,6 +665,7 @@ void D_RegisterServerCommands(void) COM_AddCommand("locatelump", Command_LocateLump_f); COM_AddCommand("listmapthings", Command_ListDoomednums_f); COM_AddCommand("listunusedsprites", Command_ListUnusedSprites_f); + COM_AddCommand("listunusedmapslots", Command_ListUnusedMapSlots_f); COM_AddCommand("runsoc", Command_RunSOC); COM_AddCommand("pause", Command_Pause); @@ -897,6 +921,7 @@ void D_RegisterClientCommands(void) CV_RegisterVar(&cv_mindelay); CV_RegisterVar(&cv_gentlemens); CV_RegisterVar(&cv_serverinfoscreen); + CV_RegisterVar(&cv_serveraddoninfo); #ifdef NETGAME_DEVMODE CV_RegisterVar(&cv_fishcake); @@ -924,11 +949,11 @@ void D_RegisterClientCommands(void) COM_AddCommand("displayplayer", Command_Displayplayer_f); - CV_RegisterVar(&cv_audbuffersize); - CV_RegisterVar(&cv_palette); CV_RegisterVar(&cv_palettenum); + CV_RegisterVar(&cv_lua_profile); + // m_menu.c CV_RegisterVar(&cv_chatheight); CV_RegisterVar(&cv_chatwidth); @@ -936,6 +961,9 @@ void D_RegisterClientCommands(void) CV_RegisterVar(&cv_chatspamprotection); CV_RegisterVar(&cv_consolechat); CV_RegisterVar(&cv_chatnotifications); + CV_RegisterVar(&cv_chat_xoffset); + CV_RegisterVar(&cv_chat_yoffset); + CV_RegisterVar(&cv_chat_showlimit); CV_RegisterVar(&cv_chatbacktint); CV_RegisterVar(&cv_chatcentertext); CV_RegisterVar(&cv_songcredits); @@ -997,13 +1025,27 @@ void D_RegisterClientCommands(void) CV_RegisterVar(&cv_litesteer[i]); + CV_RegisterVar(&cv_autoaccel[i]); + CV_RegisterVar(&cv_usejoystick[i]); CV_RegisterVar(&cv_joyscale[i]); - CV_RegisterVar(&cv_rumble[i]); - CV_RegisterVar(&cv_rumblestrength[i]); CV_RegisterVar(&cv_gamepadled[i]); + + CV_RegisterVar(&cv_rumble[i]); + CV_RegisterVar(&cv_rumble_strength[i]); + CV_RegisterVar(&cv_rumble_spinout[i]); + CV_RegisterVar(&cv_rumble_sneakerboost[i]); + CV_RegisterVar(&cv_rumble_offroad[i]); + CV_RegisterVar(&cv_rumble_bananadrag[i]); + CV_RegisterVar(&cv_rumble_stairjank[i]); + CV_RegisterVar(&cv_rumble_brakedrift[i]); + CV_RegisterVar(&cv_rumble_driftcharge[i]); } + CV_RegisterVar(&cv_gamepadifunfocused); + CV_RegisterVar(&cv_gamepadledifunfocused); + CV_RegisterVar(&cv_rumbleifunfocused); + CV_RegisterVar(&cv_usemouse); CV_RegisterVar(&cv_invertmouse); CV_RegisterVar(&cv_mousexsens); @@ -1017,6 +1059,7 @@ void D_RegisterClientCommands(void) CV_RegisterVar(&cv_midimusicvolume); #endif CV_RegisterVar(&cv_numChannels); + CV_RegisterVar(&cv_audbuffersize); #ifdef HAVE_OPENMPT CV_RegisterVar(&cv_modfilter); @@ -1200,17 +1243,26 @@ static boolean AllowedPlayerNameChar(char ch) static boolean EnsurePlayerNameIsGood(char *name, INT32 playernum) { - INT32 ix; + size_t ix, len = strlen(name); - if (strlen(name) == 0 || strlen(name) > MAXPLAYERNAME) + if (len == 0 || len > MAXPLAYERNAME) return false; // Empty or too long. - if (name[0] == ' ' || name[strlen(name)-1] == ' ') - return false; // Starts or ends with a space. + if (name[0] == ' ') + return false; // Starts with a space. if (isdigit(name[0])) return false; // Starts with a digit. if (name[0] == '@' || name[0] == '~') return false; // Starts with an admin symbol. + // Clean up trailing whitespace. + while (len && name[len-1] == ' ') + { + name[len-1] = '\0'; + len--; + } + if (len == 0) + return false; + // Check if it contains a non-printing character. // Note: ANSI C isprint() considers space a printing character. // Also don't allow semicolons, since they are used as @@ -1218,20 +1270,19 @@ static boolean EnsurePlayerNameIsGood(char *name, INT32 playernum) // Also, anything over 0x80 is disallowed too, since compilers love to // differ on whether they're printable characters or not. - for (ix = 0; name[ix] != '\0'; ix++) + for (ix = 0; ix < len; ix++) if (!AllowedPlayerNameChar(name[ix])) return false; // Check if a player is currently using the name, case-insensitively. for (ix = 0; ix < MAXPLAYERS; ix++) { - if (ix != playernum && playeringame[ix] + if (ix != (size_t)playernum && playeringame[ix] && fasticmp(name, player_names[ix])) { // We shouldn't kick people out just because // they joined the game with the same name // as someone else -- modify the name instead. - size_t len = strlen(name); // Recursion! // Slowly strip characters off the end of the @@ -1245,7 +1296,8 @@ static boolean EnsurePlayerNameIsGood(char *name, INT32 playernum) else if (len == 1) // Agh! { // Last ditch effort... - sprintf(name, "%d", M_RandomKey(10)); + snprintf(name, MAXPLAYERNAME+1, "%d", M_RandomKey(10)); + if (!EnsurePlayerNameIsGood(name, playernum)) return false; } @@ -1264,7 +1316,8 @@ static boolean EnsurePlayerNameIsGood(char *name, INT32 playernum) * is restored to what it was before. * * We assume that if playernum is ::consoleplayer or ::secondarydisplayplayer - * the console variable ::cv_playername or ::cv_playername2 respectively is + * (unless clientjoin is true, a necessary evil) + * the console variable ::cv_playername to ::cv_playername4 respectively is * already set to newname. However, the player name table is assumed to * contain the old name. * @@ -1284,6 +1337,10 @@ static void CleanupPlayerName(INT32 playernum, const char *newname) char *tmpname = NULL; INT32 i; boolean namefailed = true; + boolean clientjoin = !!(playernum >= MAXPLAYERS); + + if (clientjoin) + playernum -= MAXPLAYERS; buf = Z_StrDup(newname); @@ -1340,17 +1397,20 @@ static void CleanupPlayerName(INT32 playernum, const char *newname) } // no stealing another player's name - for (i = 0; i < MAXPLAYERS; i++) + if (!clientjoin) { - if (i != playernum && playeringame[i] - && fasticmp(tmpname, player_names[i])) + for (i = 0; i < MAXPLAYERS; i++) { - break; + if (i != playernum && playeringame[i] + && fasticmp(tmpname, player_names[i])) + { + break; + } } - } - if (i < MAXPLAYERS) - break; + if (i < MAXPLAYERS) + break; + } // name is okay then namefailed = false; @@ -1361,15 +1421,23 @@ static void CleanupPlayerName(INT32 playernum, const char *newname) // set consvars whether namefailed or not, because even if it succeeded, // spaces may have been removed - if (playernum == consoleplayer) - CV_StealthSet(&cv_playername, tmpname); - else if (playernum == displayplayers[1] || (!netgame && playernum == 1)) - CV_StealthSet(&cv_playername2, tmpname); - else if (playernum == displayplayers[2] || (!netgame && playernum == 2)) - CV_StealthSet(&cv_playername3, tmpname); - else if (playernum == displayplayers[3] || (!netgame && playernum == 3)) - CV_StealthSet(&cv_playername4, tmpname); - else I_Assert(((void)"CleanupPlayerName used on non-local player", 0)); + if (clientjoin) + { + consvar_t *namevars[] = {&cv_playername, &cv_playername2, &cv_playername3, &cv_playername4}; + CV_StealthSet(namevars[playernum], tmpname); + } + else + { + if (playernum == consoleplayer) + CV_StealthSet(&cv_playername, tmpname); + else if (playernum == displayplayers[1] || (!netgame && playernum == 1)) + CV_StealthSet(&cv_playername2, tmpname); + else if (playernum == displayplayers[2] || (!netgame && playernum == 2)) + CV_StealthSet(&cv_playername3, tmpname); + else if (playernum == displayplayers[3] || (!netgame && playernum == 3)) + CV_StealthSet(&cv_playername4, tmpname); + else I_Assert(((void)"CleanupPlayerName used on non-local player", 0)); + } Z_Free(buf); } @@ -1450,7 +1518,9 @@ UINT8 CanChangeSkin(INT32 playernum) return true; } - if (players[playernum].spectator || players[playernum].playerstate == PST_DEAD || players[playernum].playerstate == PST_REBORN) + if (players[playernum].spectator || + players[playernum].playerstate == PST_DEAD || + players[playernum].playerstate == PST_REBORN) return true; return false; @@ -1484,470 +1554,174 @@ static void ForceAllSkins(INT32 forcedskin) } } -static INT32 snacpending = 0, snac2pending = 0, snac3pending = 0, snac4pending = 0, chmappending = 0; +static INT32 chmappending; +#ifdef PARANOIA +static INT32 snacpending[MAXSPLITSCREENPLAYERS]; +#endif + +// wonky compat, idk if anything uses this.... +#define playerisbot (splitplayer == 1 && botingame) // name, color, or skin has changed // -static void SendNameAndColor(void) +static void SendNameAndColor(UINT8 splitplayer) { char buf[MAXPLAYERNAME+2]; char *p; p = buf; + // splitscreen + if (splitscreen < splitplayer && !playerisbot) + return; + + const INT32 pnum = P_GetLocalPlayerNumForNum(splitplayer); + + player_t *player = &players[pnum]; + + // TODO: make those cvars arrays + consvar_t *playercolor, *playername, *playerskin; + consvar_t *colorvars[] = {&cv_playercolor, &cv_playercolor2, &cv_playercolor3, &cv_playercolor4}; + consvar_t *namevars[] = {&cv_playername, &cv_playername2, &cv_playername3, &cv_playername4}; + consvar_t *skinvars[] = {&cv_skin, &cv_skin2, &cv_skin3, &cv_skin4}; + + playercolor = colorvars[splitplayer]; + playername = namevars[splitplayer]; + playerskin = skinvars[splitplayer]; + // normal player colors if (G_GametypeHasTeams()) { - if (players[consoleplayer].ctfteam == 1 && cv_playercolor.value != skincolor_redteam) - CV_StealthSetValue(&cv_playercolor, skincolor_redteam); - else if (players[consoleplayer].ctfteam == 2 && cv_playercolor.value != skincolor_blueteam) - CV_StealthSetValue(&cv_playercolor, skincolor_blueteam); + if (player->ctfteam == 1 && playercolor->value != skincolor_redteam) + CV_StealthSetValue(playercolor, skincolor_redteam); + else if (player->ctfteam == 2 && playercolor->value != skincolor_blueteam) + CV_StealthSetValue(playercolor, skincolor_blueteam); } // never allow the color "none" - if (!cv_playercolor.value) + if (!playercolor->value) { - if (players[consoleplayer].skincolor) - CV_StealthSetValue(&cv_playercolor, players[consoleplayer].skincolor); - else if (skins[players[consoleplayer].skin].prefcolor) - CV_StealthSetValue(&cv_playercolor, skins[players[consoleplayer].skin].prefcolor); + if (player->skincolor) + CV_StealthSetValue(playercolor, player->skincolor); + else if (skins[player->skin].prefcolor) + CV_StealthSetValue(playercolor, skins[player->skin].prefcolor); else - CV_StealthSet(&cv_playercolor, cv_playercolor.defaultvalue); + CV_StealthSet(playercolor, playercolor->defaultvalue); } - if (fastcmp(cv_playername.string, player_names[consoleplayer]) - && cv_playercolor.value == players[consoleplayer].skincolor - && fastcmp(cv_skin.string, skins[players[consoleplayer].skin].name)) - return; - // We'll handle it later if we're not playing. if (!Playing()) return; + if (fastcmp(playername->string, player_names[pnum]) + && playercolor->value == player->skincolor + && fastcmp(playerskin->string, skins[player->skin].name)) + return; + + if (playerisbot) + { + players[pnum].skincolor = botcolor; + if (players[pnum].mo) + players[pnum].mo->color = players[pnum].skincolor; + SetPlayerSkinByNum(pnum, botskin-1); + return; + } + // If you're not in a netgame, merely update the skin, color, and name. if (!netgame) { INT32 foundskin; - CleanupPlayerName(consoleplayer, cv_playername.zstring); - strcpy(player_names[consoleplayer], cv_playername.zstring); + CleanupPlayerName(pnum, playername->zstring); + strcpy(player_names[pnum], playername->zstring); - players[consoleplayer].skincolor = cv_playercolor.value; + player->skincolor = playercolor->value; - if (players[consoleplayer].mo) - players[consoleplayer].mo->color = players[consoleplayer].skincolor; + if (player->mo) + player->mo->color = player->skincolor; - if ((foundskin = R_SkinAvailable(cv_skin.string)) != -1) + if ((foundskin = R_SkinAvailable(playerskin->string)) != -1) { - cv_skin.value = foundskin; - SetPlayerSkin(consoleplayer, cv_skin.string); - CV_StealthSet(&cv_skin, skins[cv_skin.value].name); + playerskin->value = foundskin; + SetPlayerSkin(pnum, playerskin->string); + CV_StealthSet(playerskin, skins[playerskin->value].name); } else { - cv_skin.value = players[consoleplayer].skin; - CV_StealthSet(&cv_skin, skins[players[consoleplayer].skin].name); + playerskin->value = player->skin; + CV_StealthSet(playerskin, skins[player->skin].name); // will always be same as current - SetPlayerSkin(consoleplayer, cv_skin.string); + SetPlayerSkin(pnum, playerskin->string); } return; } - snacpending++; +#ifdef PARANOIA + snacpending[splitplayer]++; +#endif // Don't change name if muted - if (player_name_changes[consoleplayer] >= MAXNAMECHANGES) + if (player_name_changes[pnum] >= MAXNAMECHANGES) { - CV_StealthSet(&cv_playername, player_names[consoleplayer]); + CV_StealthSet(playername, player_names[pnum]); HU_AddChatText("\x85*You must wait to change your name again", false); } - else if (cv_mute.value && !(server || IsPlayerAdmin(consoleplayer))) - CV_StealthSet(&cv_playername, player_names[consoleplayer]); + else if (cv_mute.value && !(server || IsPlayerAdmin(pnum))) + CV_StealthSet(playername, player_names[pnum]); else // Cleanup name if changing it - CleanupPlayerName(consoleplayer, cv_playername.zstring); + CleanupPlayerName(pnum, playername->zstring); // Don't change skin if the server doesn't want you to. - if (!CanChangeSkin(consoleplayer)) - CV_StealthSet(&cv_skin, skins[players[consoleplayer].skin].name); + if (!CanChangeSkin(pnum)) + CV_StealthSet(playerskin, skins[player->skin].name); // check if player has the skin loaded (cv_skin may have // the name of a skin that was available in the previous game) - cv_skin.value = R_SkinAvailable(cv_skin.string); - if (cv_skin.value < 0) + playerskin->value = R_SkinAvailable(playerskin->string); + if (playerskin->value < 0) { - INT32 skinnum = players[consoleplayer].skin; - CV_StealthSet(&cv_skin, skins[skinnum].name); - cv_skin.value = skinnum; + INT32 skinnum = player->skin; + CV_StealthSet(playerskin, skins[skinnum].name); + playerskin->value = skinnum; } // Finally write out the complete packet and send it off. - WRITESTRINGN(p, cv_playername.zstring, MAXPLAYERNAME); - WRITEUINT8(p, (UINT8)cv_playercolor.value); - WRITEUINT8(p, (UINT8)cv_skin.value); - SendNetXCmdForPlayer(0, XD_NAMEANDCOLOR, buf, p - buf); -} + WRITESTRINGN(p, playername->zstring, MAXPLAYERNAME); + WRITEUINT8(p, (UINT8)playercolor->value); + WRITESKIN(p, (skinnum_t)playerskin->value); -// splitscreen -static void SendNameAndColor2(void) -{ - INT32 secondplaya = -1; - char buf[MAXPLAYERNAME+2]; - char *p; - - if (splitscreen < 1 && !botingame) - return; // can happen if skin2/color2/name2 changed - - if (displayplayers[1] != consoleplayer) - secondplaya = displayplayers[1]; - else if (!netgame) // HACK - secondplaya = 1; - - if (secondplaya == -1) - return; - - p = buf; - - // normal player colors - if (G_GametypeHasTeams()) - { - if (players[secondplaya].ctfteam == 1 && cv_playercolor2.value != skincolor_redteam) - CV_StealthSetValue(&cv_playercolor2, skincolor_redteam); - else if (players[secondplaya].ctfteam == 2 && cv_playercolor2.value != skincolor_blueteam) - CV_StealthSetValue(&cv_playercolor2, skincolor_blueteam); - } - - // never allow the color "none" - if (!cv_playercolor2.value) - { - if (players[secondplaya].skincolor) - CV_StealthSetValue(&cv_playercolor2, players[secondplaya].skincolor); - else if (skins[players[secondplaya].skin].prefcolor) - CV_StealthSetValue(&cv_playercolor2, skins[players[secondplaya].skin].prefcolor); - else - CV_StealthSet(&cv_playercolor2, cv_playercolor2.defaultvalue); - } - - // We'll handle it later if we're not playing. - if (!Playing()) - return; - - // If you're not in a netgame, merely update the skin, color, and name. - if (botingame) - { - players[secondplaya].skincolor = botcolor; - if (players[secondplaya].mo) - players[secondplaya].mo->color = players[secondplaya].skincolor; - SetPlayerSkinByNum(secondplaya, botskin-1); - return; - } - else if (!netgame) - { - INT32 foundskin; - - CleanupPlayerName(secondplaya, cv_playername2.zstring); - strcpy(player_names[secondplaya], cv_playername2.zstring); - - // don't use displayplayers[1]: the second player must be 1 - players[secondplaya].skincolor = cv_playercolor2.value; - if (players[secondplaya].mo) - players[secondplaya].mo->color = players[secondplaya].skincolor; - - if ((foundskin = R_SkinAvailable(cv_skin2.string)) != -1) - { - cv_skin2.value = foundskin; - SetPlayerSkin(secondplaya, cv_skin2.string); - } - else - { - cv_skin2.value = players[secondplaya].skin; - CV_StealthSet(&cv_skin2, skins[players[secondplaya].skin].name); - // will always be same as current - SetPlayerSkin(secondplaya, cv_skin2.string); - } - return; - } - - snac2pending++; - - // Don't change name if muted - if (player_name_changes[displayplayers[1]] >= MAXNAMECHANGES) - { - CV_StealthSet(&cv_playername2, player_names[displayplayers[1]]); - HU_AddChatText("\x85*You must wait to change your name again", false); - } - else if (cv_mute.value && !(server || IsPlayerAdmin(displayplayers[1]))) - CV_StealthSet(&cv_playername2, player_names[displayplayers[1]]); - else // Cleanup name if changing it - CleanupPlayerName(displayplayers[1], cv_playername2.zstring); - - // Don't change skin if the server doesn't want you to. - if (!CanChangeSkin(displayplayers[1])) - CV_StealthSet(&cv_skin2, skins[players[displayplayers[1]].skin].name); - - // check if player has the skin loaded (cv_skin2 may have - // the name of a skin that was available in the previous game) - cv_skin2.value = R_SkinAvailable(cv_skin2.string); - if (cv_skin2.value < 0) - { - INT32 skinnum = players[displayplayers[1]].skin; - CV_StealthSet(&cv_skin2, skins[skinnum].name); - cv_skin2.value = skinnum; - } - - // Finally write out the complete packet and send it off. - WRITESTRINGN(p, cv_playername2.zstring, MAXPLAYERNAME); - WRITEUINT8(p, (UINT8)cv_playercolor2.value); - WRITEUINT8(p, (UINT8)cv_skin2.value); - SendNetXCmdForPlayer(1, XD_NAMEANDCOLOR, buf, p - buf); -} - -static void SendNameAndColor3(void) -{ - INT32 thirdplaya = -1; - char buf[MAXPLAYERNAME+2]; - char *p; - - if (splitscreen < 2) - return; // can happen if skin3/color3/name3 changed - - if (displayplayers[2] != consoleplayer) - thirdplaya = displayplayers[2]; - else if (!netgame) // HACK - thirdplaya = 2; - - if (thirdplaya == -1) - return; - - p = buf; - - // normal player colors - if (G_GametypeHasTeams()) - { - if (players[thirdplaya].ctfteam == 1 && cv_playercolor3.value != skincolor_redteam) - CV_StealthSetValue(&cv_playercolor3, skincolor_redteam); - else if (players[thirdplaya].ctfteam == 2 && cv_playercolor3.value != skincolor_blueteam) - CV_StealthSetValue(&cv_playercolor3, skincolor_blueteam); - } - - // never allow the color "none" - if (!cv_playercolor3.value) - { - if (players[thirdplaya].skincolor) - CV_StealthSetValue(&cv_playercolor3, players[thirdplaya].skincolor); - else if (skins[players[thirdplaya].skin].prefcolor) - CV_StealthSetValue(&cv_playercolor3, skins[players[thirdplaya].skin].prefcolor); - else - CV_StealthSet(&cv_playercolor3, cv_playercolor3.defaultvalue); - } - - // We'll handle it later if we're not playing. - if (!Playing()) - return; - - // If you're not in a netgame, merely update the skin, color, and name. - if (!netgame) - { - INT32 foundskin; - - CleanupPlayerName(thirdplaya, cv_playername3.zstring); - strcpy(player_names[thirdplaya], cv_playername3.zstring); - - // don't use displayplayers[2]: the third player must be 2 - players[thirdplaya].skincolor = cv_playercolor3.value; - if (players[thirdplaya].mo) - players[thirdplaya].mo->color = players[thirdplaya].skincolor; - - if ((foundskin = R_SkinAvailable(cv_skin3.string)) != -1) - { - cv_skin3.value = foundskin; - SetPlayerSkin(thirdplaya, cv_skin3.string); - } - else - { - cv_skin3.value = players[thirdplaya].skin; - CV_StealthSet(&cv_skin3, skins[players[thirdplaya].skin].name); - // will always be same as current - SetPlayerSkin(thirdplaya, cv_skin3.string); - } - return; - } - - snac3pending++; - - // Don't change name if muted - if (player_name_changes[displayplayers[2]] >= MAXNAMECHANGES) - { - CV_StealthSet(&cv_playername3, player_names[displayplayers[2]]); - HU_AddChatText("\x85*You must wait to change your name again", false); - } - else if (cv_mute.value && !(server || IsPlayerAdmin(displayplayers[2]))) - CV_StealthSet(&cv_playername3, player_names[displayplayers[2]]); - else // Cleanup name if changing it - CleanupPlayerName(displayplayers[2], cv_playername3.zstring); - - // Don't change skin if the server doesn't want you to. - if (!CanChangeSkin(displayplayers[2])) - CV_StealthSet(&cv_skin3, skins[players[displayplayers[2]].skin].name); - - // check if player has the skin loaded (cv_skin3 may have - // the name of a skin that was available in the previous game) - cv_skin3.value = R_SkinAvailable(cv_skin3.string); - if (cv_skin3.value < 0) - { - INT32 skinnum = players[displayplayers[2]].skin; - CV_StealthSet(&cv_skin3, skins[skinnum].name); - cv_skin3.value = skinnum; - } - - // Finally write out the complete packet and send it off. - WRITESTRINGN(p, cv_playername3.zstring, MAXPLAYERNAME); - WRITEUINT8(p, (UINT8)cv_playercolor3.value); - WRITEUINT8(p, (UINT8)cv_skin3.value); - SendNetXCmdForPlayer(2, XD_NAMEANDCOLOR, buf, p - buf); -} - -static void SendNameAndColor4(void) -{ - INT32 fourthplaya = -1; - char buf[MAXPLAYERNAME+2]; - char *p; - - if (splitscreen < 3) - return; // can happen if skin4/color4/name4 changed - - if (displayplayers[3] != consoleplayer) - fourthplaya = displayplayers[3]; - else if (!netgame) // HACK - fourthplaya = 3; - - if (fourthplaya == -1) - return; - - p = buf; - - // normal player colors - if (G_GametypeHasTeams()) - { - if (players[fourthplaya].ctfteam == 1 && cv_playercolor4.value != skincolor_redteam) - CV_StealthSetValue(&cv_playercolor4, skincolor_redteam); - else if (players[fourthplaya].ctfteam == 2 && cv_playercolor4.value != skincolor_blueteam) - CV_StealthSetValue(&cv_playercolor4, skincolor_blueteam); - } - - // never allow the color "none" - if (!cv_playercolor4.value) - { - if (players[fourthplaya].skincolor) - CV_StealthSetValue(&cv_playercolor4, players[fourthplaya].skincolor); - else if (skins[players[fourthplaya].skin].prefcolor) - CV_StealthSetValue(&cv_playercolor4, skins[players[fourthplaya].skin].prefcolor); - else - CV_StealthSet(&cv_playercolor4, cv_playercolor4.defaultvalue); - } - - // We'll handle it later if we're not playing. - if (!Playing()) - return; - - // If you're not in a netgame, merely update the skin, color, and name. - if (botingame) - { - players[fourthplaya].skincolor = botcolor; - if (players[fourthplaya].mo) - players[fourthplaya].mo->color = players[fourthplaya].skincolor; - SetPlayerSkinByNum(fourthplaya, botskin-1); - return; - } - else if (!netgame) - { - INT32 foundskin; - - CleanupPlayerName(fourthplaya, cv_playername4.zstring); - strcpy(player_names[fourthplaya], cv_playername4.zstring); - - // don't use displayplayers[3]: the second player must be 4 - players[fourthplaya].skincolor = cv_playercolor4.value; - if (players[fourthplaya].mo) - players[fourthplaya].mo->color = players[fourthplaya].skincolor; - - if ((foundskin = R_SkinAvailable(cv_skin4.string)) != -1) - { - cv_skin4.value = foundskin; - SetPlayerSkin(fourthplaya, cv_skin4.string); - } - else - { - cv_skin4.value = players[fourthplaya].skin; - CV_StealthSet(&cv_skin4, skins[players[fourthplaya].skin].name); - // will always be same as current - SetPlayerSkin(fourthplaya, cv_skin4.string); - } - return; - } - - snac4pending++; - - // Don't change name if muted - if (player_name_changes[displayplayers[3]] >= MAXNAMECHANGES) - { - CV_StealthSet(&cv_playername4, player_names[displayplayers[3]]); - HU_AddChatText("\x85*You must wait to change your name again", false); - } - else if (cv_mute.value && !(server || IsPlayerAdmin(displayplayers[3]))) - CV_StealthSet(&cv_playername4, player_names[displayplayers[3]]); - else // Cleanup name if changing it - CleanupPlayerName(displayplayers[3], cv_playername4.zstring); - - // Don't change skin if the server doesn't want you to. - if (!CanChangeSkin(displayplayers[3])) - CV_StealthSet(&cv_skin4, skins[players[displayplayers[3]].skin].name); - - // check if player has the skin loaded (cv_skin4 may have - // the name of a skin that was available in the previous game) - cv_skin4.value = R_SkinAvailable(cv_skin4.string); - if (cv_skin4.value < 0) - { - INT32 skinnum = players[displayplayers[3]].skin; - CV_StealthSet(&cv_skin4, skins[skinnum].name); - cv_skin4.value = skinnum; - } - - // Finally write out the complete packet and send it off. - WRITESTRINGN(p, cv_playername4.zstring, MAXPLAYERNAME); - WRITEUINT8(p, (UINT8)cv_playercolor4.value); - WRITEUINT8(p, (UINT8)cv_skin4.value); - SendNetXCmdForPlayer(3, XD_NAMEANDCOLOR, buf, p - buf); + SendNetXCmdForPlayer(splitplayer, XD_NAMEANDCOLOR, buf, p - buf); } static void Got_NameAndColor(const UINT8 **cp, INT32 playernum) { - player_t *p = &players[playernum]; - char name[MAXPLAYERNAME+1]; - UINT8 color, skin; + player_t *player; + char name[MAXPLAYERNAME+1] = {}; + UINT8 color; + skinnum_t skin; #ifdef PARANOIA if (playernum < 0 || playernum > MAXPLAYERS) I_Error("There is no player %d!", playernum); #endif - if (playernum == consoleplayer) - snacpending--; // TODO: make snacpending an array instead of 4 separate vars? - else if (playernum == displayplayers[1]) - snac2pending--; - else if (playernum == displayplayers[2]) - snac3pending--; - else if (playernum == displayplayers[3]) - snac4pending--; + player = &players[playernum]; #ifdef PARANOIA - if (snacpending < 0 || snac2pending < 0 || snac3pending < 0 || snac4pending < 0) - I_Error("snacpending negative!"); + if (P_IsLocalPlayer(player)) + { + const INT32 localpnum = P_GetLocalPlayerNumForPlayer(player); + snacpending[localpnum]--; + + if (snacpending[localpnum] < 0) + I_Error("snacpending negative for player %d!", localpnum); + } #endif READSTRINGN(*cp, name, MAXPLAYERNAME); color = READUINT8(*cp); - skin = READUINT8(*cp); + skin = READSKIN(*cp); // set name if (player_name_changes[playernum] < MAXNAMECHANGES) @@ -1957,33 +1731,32 @@ static void Got_NameAndColor(const UINT8 **cp, INT32 playernum) } // set color - p->skincolor = color % MAXSKINCOLORS; - if (p->mo) - p->mo->color = (UINT8)p->skincolor; + player->skincolor = color % MAXSKINCOLORS; + if (player->mo) + player->mo->color = (UINT8)player->skincolor; demo_extradata[playernum] |= DXD_COLOR; // normal player colors - if (server && (p != &players[consoleplayer] && p != &players[displayplayers[1]] - && p != &players[displayplayers[2]] && p != &players[displayplayers[3]])) + if (server && !P_IsLocalPlayer(player)) { boolean kick = false; // team colors if (G_GametypeHasTeams()) { - if (p->ctfteam == 1 && p->skincolor != skincolor_redteam) + if (player->ctfteam == 1 && player->skincolor != skincolor_redteam) kick = true; - else if (p->ctfteam == 2 && p->skincolor != skincolor_blueteam) + else if (player->ctfteam == 2 && player->skincolor != skincolor_blueteam) kick = true; } // don't allow color "none" - if (!p->skincolor) + if (!player->skincolor) kick = true; if (kick) { - CONS_Alert(CONS_WARNING, M_GetText("Illegal color change received from %s (team: %d), color: %d)\n"), player_names[playernum], p->ctfteam, p->skincolor); + CONS_Alert(CONS_WARNING, M_GetText("Illegal color change received from %s (team: %d), color: %d)\n"), player_names[playernum], player->ctfteam, player->skincolor); SendKick(playernum, KICK_MSG_CON_FAIL); return; } @@ -1995,6 +1768,7 @@ static void Got_NameAndColor(const UINT8 **cp, INT32 playernum) const INT32 forcedskin = cv_forceskin.value; SetPlayerSkinByNum(playernum, forcedskin); + // TODO: make cv_skin an array if (playernum == consoleplayer) CV_StealthSet(&cv_skin, skins[forcedskin].name); else if (playernum == displayplayers[1]) @@ -2008,44 +1782,16 @@ static void Got_NameAndColor(const UINT8 **cp, INT32 playernum) SetPlayerSkinByNum(playernum, skin); } -void SendWeaponPref(void) +void SendWeaponPref(UINT8 splitplayer) { UINT8 buf[1]; buf[0] = 0; - if (cv_flipcam[0].value) + + if (cv_flipcam[splitplayer].value) buf[0] |= 1; - SendNetXCmdForPlayer(0, XD_WEAPONPREF, buf, 1); -} -void SendWeaponPref2(void) -{ - UINT8 buf[1]; - - buf[0] = 0; - if (cv_flipcam[1].value) - buf[0] |= 1; - SendNetXCmdForPlayer(1, XD_WEAPONPREF, buf, 1); -} - -void SendWeaponPref3(void) -{ - UINT8 buf[1]; - - buf[0] = 0; - if (cv_flipcam[2].value) - buf[0] |= 1; - SendNetXCmdForPlayer(2, XD_WEAPONPREF, buf, 1); -} - -void SendWeaponPref4(void) -{ - UINT8 buf[1]; - - buf[0] = 0; - if (cv_flipcam[3].value) - buf[0] |= 1; - SendNetXCmdForPlayer(3, XD_WEAPONPREF, buf, 1); + SendNetXCmdForPlayer(splitplayer, XD_WEAPONPREF, buf, 1); } static void Got_WeaponPref(const UINT8 **cp, INT32 playernum) @@ -2061,23 +1807,10 @@ static void Got_WeaponPref(const UINT8 **cp, INT32 playernum) player->pflags |= PF_ANALOGMODE; } -void D_SendPlayerConfig(void) +void D_SendPlayerConfig(UINT8 splitplayer) { - SendNameAndColor(); - if (splitscreen || botingame) - SendNameAndColor2(); - if (splitscreen > 1) - SendNameAndColor3(); - if (splitscreen > 2) - SendNameAndColor4(); - - SendWeaponPref(); - if (splitscreen) - SendWeaponPref2(); - if (splitscreen > 1) - SendWeaponPref3(); - if (splitscreen > 2) - SendWeaponPref4(); + SendNameAndColor(splitplayer); + SendWeaponPref(splitplayer); } // Only works for displayplayer, sorry! @@ -2096,14 +1829,16 @@ INT32 D_LookupPlayer(const char *s) if ((playernum = atoi(s))) { - playernum = max(min(playernum, MAXPLAYERS-1), 0);/* not out of range */ + playernum = max(min(playernum, MAXPLAYERS-1), 0); /* not out of range */ return playernum; } + const size_t len = strlen(s); + for (playernum = 0; playernum < MAXPLAYERS; ++playernum) { /* Match name case-insensitively: fully, or partially the start. */ - if (playeringame[playernum] && (strnicmp(player_names[playernum], s, strlen(s)) == 0)) + if (playeringame[playernum] && (strnicmp(player_names[playernum], s, len) == 0)) { return playernum; } @@ -2143,13 +1878,15 @@ static void GetViewablePlayerPlaceRange(INT32 *first, INT32 *last) (*last) = 0; for (i = 0; i < MAXPLAYERS; ++i) - if (G_CouldView(i)) { - place = players[i].kartstuff[k_position]; - if (place < (*first)) - (*first) = place; - if (place > (*last)) - (*last) = place; + if (G_CouldView(i)) + { + place = players[i].kartstuff[k_position]; + if (place < (*first)) + (*first) = place; + if (place > (*last)) + (*last) = place; + } } } @@ -2483,7 +2220,7 @@ void D_MapChange(INT32 mapnum, INT32 newgametype, boolean pencoremode, boolean r displayplayers[1] = 1; playeringame[1] = true; players[1].bot = 1; - SendNameAndColor2(); + SendNameAndColor(1); } } @@ -2521,7 +2258,6 @@ void D_SetupVote(void) WRITEUINT8(p, secondgt); secondgt &= ~0x80; - for (i = 0; i < 4; i++) { UINT16 m; @@ -2617,11 +2353,12 @@ static char *ConcatCommandArgv(int start, int end) if (!p) I_Error("ConcatCommandArgv: Out of memory!\n"); - --end;/* handle the final argument separately */ + --end; /* handle the final argument separately */ for (i = start; i < end; ++i) { - p += sprintf(p, "%s ", COM_Argv(i)); + if (size - (p - final) > 0) + p += snprintf(p, size - (p - final), "%s ", COM_Argv(i)); } /* at this point "end" is actually the last argument's position */ @@ -2650,7 +2387,6 @@ static void Command_Map_f(void) return; } - last_map_cmd = I_GetTime(); size_t first_option; @@ -2787,7 +2523,7 @@ static void Command_Map_f(void) // G_TOLFlag handles both multiplayer gametype and ignores it for !multiplayer else { - if (!mapheaderinfo[newmapnum-1]) + if (mapheaderinfo[newmapnum-1] == NULL) { CONS_Alert(CONS_WARNING, M_GetText("Invalid mapheaderinfo for Course %s (%s)\n"), realmapname, G_BuildMapName(newmapnum)); return; @@ -3036,11 +2772,11 @@ static void Command_ReplayMarker(void) if (title) { - snprintf(demo.titlename, 64, "%s [%i:%02d/%.5s]", title, G_TicsToMinutes(adjustedleveltime, false), G_TicsToSeconds(adjustedleveltime), modeattacking ? "Record Attack" : connectedservername); + snprintf(demo.titlename, sizeof(demo.titlename)-1, "%s [%i:%02d/%.5s]", title, G_TicsToMinutes(adjustedleveltime, false), G_TicsToSeconds(adjustedleveltime), modeattacking ? "Record Attack" : connectedservername); Z_Free(title); } else - snprintf(demo.titlename, 64, "[%i:%02d/%.5s]", G_TicsToMinutes(adjustedleveltime, false), G_TicsToSeconds(adjustedleveltime), modeattacking ? "Record Attack" : connectedservername); + snprintf(demo.titlename, sizeof(demo.titlename)-1, "[%i:%02d/%.5s]", G_TicsToMinutes(adjustedleveltime, false), G_TicsToSeconds(adjustedleveltime), modeattacking ? "Record Attack" : connectedservername); CONS_Printf("Replay will be saved!\n"); } @@ -4637,13 +4373,13 @@ static void Got_RequestAddfilecmd(const UINT8 **cp, INT32 playernum) char message[275]; if (toomany) - sprintf(message, M_GetText("Too many files loaded to add %s\n"), filename); + snprintf(message, sizeof(message), M_GetText("Too many files loaded to add %s\n"), filename); else if (ncs == FS_NOTFOUND) - sprintf(message, M_GetText("The server doesn't have %s\n"), filename); + snprintf(message, sizeof(message), M_GetText("The server doesn't have %s\n"), filename); else if (ncs == FS_MD5SUMBAD) - sprintf(message, M_GetText("Checksum mismatch on %s\n"), filename); + snprintf(message, sizeof(message), M_GetText("Checksum mismatch on %s\n"), filename); else - sprintf(message, M_GetText("Unknown error finding wad file (%s)\n"), filename); + snprintf(message, sizeof(message), M_GetText("Unknown error finding wad file (%s)\n"), filename); CONS_Printf("%s",message); @@ -4749,8 +4485,6 @@ static void Command_LocateLump_f(void) } } -#define MAXDOOMEDNUM 4095 - static void Command_ListDoomednums_f(void) { INT16 i, j, k = 0, l = 0; @@ -4894,6 +4628,23 @@ void Command_ListUnusedSprites_f(void) } } +void Command_ListUnusedMapSlots_f(void) +{ + INT32 i; + + CONS_Printf("\x82Printing map slot non-usage...\n"); + + for (i = 0; i < NUMMAPS; i++) + { + // is checking this enough? + if (mapheaderinfo[i]) + continue; + + CONS_Printf("%s\n", G_BuildMapName(i+1)); + } +} + + // ========================================================================= // MISC. COMMANDS // ========================================================================= @@ -5462,8 +5213,10 @@ static void Command_Mapmd5_f(void) { INT32 i; char md5tmp[33]; + for (i = 0; i < 16; ++i) - sprintf(&md5tmp[i*2], "%02x", mapmd5[i]); + snprintf(&md5tmp[i*2], 3, "%02x", mapmd5[i]); + CONS_Printf("%s: %s\n", G_BuildMapName(gamemap), md5tmp); } else @@ -5763,50 +5516,53 @@ static void ForceSkin_OnChange(void) } } -//Allows the player's name to be changed if cv_mute is off. +// Allows the player's name to be changed if cv_mute is off. static void Name_OnChange(void) { if (cv_mute.value && !(server || IsPlayerAdmin(consoleplayer))) { CONS_Alert(CONS_NOTICE, M_GetText("You may not change your name when chat is muted.\n")); CV_StealthSet(&cv_playername, player_names[consoleplayer]); + return; } - else - SendNameAndColor(); + SendNameAndColor(0); } static void Name2_OnChange(void) { - if (cv_mute.value) //Secondary player can't be admin. + if (cv_mute.value) // Secondary player can't be admin. { CONS_Alert(CONS_NOTICE, M_GetText("You may not change your name when chat is muted.\n")); CV_StealthSet(&cv_playername2, player_names[displayplayers[1]]); + return; } - else - SendNameAndColor2(); + + SendNameAndColor(1); } static void Name3_OnChange(void) { - if (cv_mute.value) //Third player can't be admin. + if (cv_mute.value) // Third player can't be admin. { CONS_Alert(CONS_NOTICE, M_GetText("You may not change your name when chat is muted.\n")); CV_StealthSet(&cv_playername3, player_names[displayplayers[2]]); + return; } - else - SendNameAndColor3(); + + SendNameAndColor(2); } static void Name4_OnChange(void) { - if (cv_mute.value) //Secondary player can't be admin. + if (cv_mute.value) // Secondary player can't be admin. { CONS_Alert(CONS_NOTICE, M_GetText("You may not change your name when chat is muted.\n")); CV_StealthSet(&cv_playername4, player_names[displayplayers[3]]); + return; } - else - SendNameAndColor4(); + + SendNameAndColor(3); } /** Sends a skin change for the console player, unless that player is moving. @@ -5828,7 +5584,7 @@ static void Skin_OnChange(void) } if (CanChangeSkin(consoleplayer) && !P_PlayerMoving(consoleplayer)) - SendNameAndColor(); + SendNameAndColor(0); else { CONS_Alert(CONS_NOTICE, M_GetText("You can't change your skin at the moment.\n")); @@ -5849,7 +5605,7 @@ static void Skin2_OnChange(void) return; // do whatever you want if (CanChangeSkin(displayplayers[1]) && !P_PlayerMoving(displayplayers[1])) - SendNameAndColor2(); + SendNameAndColor(1); else { CONS_Alert(CONS_NOTICE, M_GetText("You can't change your skin at the moment.\n")); @@ -5865,7 +5621,7 @@ static void Skin3_OnChange(void) return; // do whatever you want if (CanChangeSkin(displayplayers[2]) && !P_PlayerMoving(displayplayers[2])) - SendNameAndColor3(); + SendNameAndColor(2); else { CONS_Alert(CONS_NOTICE, M_GetText("You can't change your skin at the moment.\n")); @@ -5881,7 +5637,7 @@ static void Skin4_OnChange(void) return; // do whatever you want if (CanChangeSkin(displayplayers[3]) && !P_PlayerMoving(displayplayers[3])) - SendNameAndColor4(); + SendNameAndColor(3); else { CONS_Alert(CONS_NOTICE, M_GetText("You can't change your skin at the moment.\n")); @@ -5961,19 +5717,22 @@ static void Command_SkinSearch(void) size_t i; UINT16 s; UINT16 ic = 0; - //skin_t *skininput = &skins[s]; - for (i = 1; i < COM_Argc(); i++){ - for( s = 0 ; s < numallskins ; s++ ) + + for (i = 1; i < COM_Argc(); i++) + { + for (s = 0; s < numskins; s++) { skin_t *skininput = &skins[s]; - if (strcasestr(skininput->realname,COM_Argv(i))) + + if (strcasestr(skininput->realname, COM_Argv(i))) { ic++; - CONS_Printf("%d. %s%s:\x80 %s\n", ic,HU_SkinColorToConsoleColor(skininput->prefcolor),skininput->realname,skininput->name); + CONS_Printf("%d. %s%s:\x80 %s\n", ic, HU_SkinColorToConsoleColor(skininput->prefcolor), skininput->realname, skininput->name); } } } - CONS_Printf("Total %d skins.\n", ic); + + CONS_Printf("Total %d skins.\n", ic); } /** Sends a color change for the console player, unless that player is moving. @@ -5994,7 +5753,7 @@ static void Color_OnChange(void) if (!P_PlayerMoving(consoleplayer)) { // Color change menu scrolling fix is no longer necessary - SendNameAndColor(); + SendNameAndColor(0); } else { @@ -6016,7 +5775,7 @@ static void Color2_OnChange(void) if (!P_PlayerMoving(displayplayers[1])) { // Color change menu scrolling fix is no longer necessary - SendNameAndColor2(); + SendNameAndColor(1); } else { @@ -6033,7 +5792,7 @@ static void Color3_OnChange(void) if (!P_PlayerMoving(displayplayers[2])) { // Color change menu scrolling fix is no longer necessary - SendNameAndColor3(); + SendNameAndColor(2); } else { @@ -6050,7 +5809,7 @@ static void Color4_OnChange(void) if (!P_PlayerMoving(displayplayers[3])) { // Color change menu scrolling fix is no longer necessary - SendNameAndColor4(); + SendNameAndColor(3); } else { @@ -6147,7 +5906,6 @@ static void BaseNumLaps_OnChange(void) } } - static void KartFrantic_OnChange(void) { if ((boolean)cv_kartfrantic.value != franticitems && gamestate == GS_LEVEL && leveltime > starttime) diff --git a/src/d_netcmd.h b/src/d_netcmd.h index 6b7382403..25e050a13 100644 --- a/src/d_netcmd.h +++ b/src/d_netcmd.h @@ -21,10 +21,7 @@ extern "C" { #include "command.h" -void SendWeaponPref(void); -void SendWeaponPref2(void); -void SendWeaponPref3(void); -void SendWeaponPref4(void); +void SendWeaponPref(UINT8 splitplayer); // console vars extern consvar_t cv_playername; @@ -54,10 +51,6 @@ extern consvar_t cv_mousevisible; //WTF extern consvar_t cv_mouseturn; extern consvar_t cv_usejoystick[4]; //MAXSPLITSCREENPLAYERS -#ifdef LJOYSTICK -extern consvar_t cv_joyport; -extern consvar_t cv_joyport2; -#endif extern consvar_t cv_joyscale[4]; //MAXSPLITSCREENPLAYERS // normally in p_mobj but the .h is not read @@ -96,11 +89,6 @@ extern consvar_t cv_pause; extern consvar_t cv_restrictskinchange, cv_allowteamchange, cv_ingamecap, cv_respawntime; extern consvar_t cv_spectatorreentry, cv_antigrief; -/*extern consvar_t cv_teleporters, cv_superring, cv_supersneakers, cv_invincibility; -extern consvar_t cv_jumpshield, cv_watershield, cv_ringshield, cv_forceshield, cv_bombshield; -extern consvar_t cv_1up, cv_eggmanbox; -extern consvar_t cv_recycler;*/ - // SRB2kart items extern consvar_t cv_sneaker, cv_rocketsneaker, cv_invincibility, cv_banana; extern consvar_t cv_eggmanmonitor, cv_orbinaut, cv_jawz, cv_mine; @@ -158,8 +146,10 @@ extern consvar_t cv_pingstyle; //extern consvar_t cv_smallpos; extern consvar_t cv_showminimapnames; +extern consvar_t cv_showminimapfinished; extern consvar_t cv_minihead; extern consvar_t cv_showminimapangle; +extern consvar_t cv_spinoutroll; extern consvar_t cv_showlapemblem; @@ -199,6 +189,8 @@ extern consvar_t cv_ps_thinkframe_page; extern consvar_t cv_ps_samplesize; extern consvar_t cv_ps_descriptor; +extern consvar_t cv_lua_profile; + extern consvar_t cv_director, cv_kartdebugdirector, cv_showdirectorhud; extern consvar_t cv_showtrackaddon; @@ -295,7 +287,7 @@ typedef union { // add game commands, needs cleanup void D_RegisterServerCommands(void); void D_RegisterClientCommands(void); -void D_SendPlayerConfig(void); +void D_SendPlayerConfig(UINT8 splitplayer); void Command_ExitGame_f(void); void Command_Retry_f(void); void D_GameTypeChanged(INT32 lastgametype); // not a real _OnChange function anymore diff --git a/src/d_netfil.c b/src/d_netfil.c index d35bb09b3..e8d3baa7e 100644 --- a/src/d_netfil.c +++ b/src/d_netfil.c @@ -116,6 +116,8 @@ static I_mutex downloadmutex; #endif char downloaddir[512] = "DOWNLOAD"; +INT32 addontypes[NUMADDONTYPES] = {0}; + file_download_t filedownload = {}; #ifdef HAVE_CURL @@ -131,8 +133,12 @@ static UINT32 curl_origtotalfilesize; static char *curl_realname = NULL; fileneeded_t *curl_curfile = NULL; HTTP_login *curl_logins = NULL; + +static void CURLGetFile(void); #endif +static addontype_t GetAddonType(const char *name); + /** Fills a serverinfo packet with information about wad files loaded. * * \todo Give this function a better name since it is in global scope. @@ -161,7 +167,9 @@ UINT8 *PutFileNeeded(UINT16 firstfile) continue; } - nameonly(strcpy(wadfilename, wadfiles[i]->filename)); + strncpy(wadfilename, wadfiles[i]->filename, MAX_WADPATH); + wadfilename[MAX_WADPATH-1] = '\0'; + nameonly(wadfilename); // Look below at the WRITE macros to understand what these numbers mean. const size_t len = strlen(wadfilename) + 1; @@ -223,8 +231,11 @@ void D_ParseFileneeded(INT32 fileneedednum_parm, UINT8 *fileneededstr, UINT16 fi fileneeded[i].willsend = (UINT8)(filestatus >> 4); fileneeded[i].totalsize = READUINT32(p); // The four next bytes are the file size fileneeded[i].file = NULL; // The file isn't open yet - READSTRINGN(p, fileneeded[i].filename, MAX_WADPATH); // The next bytes are the file name + READSTRINGL(p, fileneeded[i].filename, MAX_WADPATH); // The next bytes are the file name READMEM(p, fileneeded[i].md5sum, 16); // The last 16 bytes are the file checksum + + // Should be good place to calculate that? + fileneeded[i].type = GetAddonType(fileneeded[i].filename); } } @@ -248,9 +259,10 @@ void CL_PrepareDownloadSaveGame(const char *tmpsave) */ boolean CL_CheckDownloadable(void) { - UINT8 i,dlstatus = 0; + UINT8 i, dlstatus = 0; for (i = 0; i < fileneedednum; i++) + { if (fileneeded[i].status != FS_FOUND && fileneeded[i].status != FS_OPEN) { if (fileneeded[i].willsend == 1) @@ -261,6 +273,7 @@ boolean CL_CheckDownloadable(void) else //if (fileneeded[i].willsend == 2) dlstatus = 2; } + } // Downloading locally disabled if (!dlstatus && M_CheckParm("-nodownload")) @@ -271,25 +284,31 @@ boolean CL_CheckDownloadable(void) // not downloadable, put reason in console CONS_Alert(CONS_NOTICE, M_GetText("You need additional files to connect to this server:\n")); + for (i = 0; i < fileneedednum; i++) + { if (fileneeded[i].status != FS_FOUND && fileneeded[i].status != FS_OPEN) { CONS_Printf(" * \"%s\" (%dK)", fileneeded[i].filename, fileneeded[i].totalsize >> 10); - if (fileneeded[i].status == FS_MD5SUMBAD) - CONS_Printf(M_GetText(" wrong version, md5: ")); - else - CONS_Printf(M_GetText(" not found, md5: ")); + if (fileneeded[i].status == FS_MD5SUMBAD) + CONS_Printf(M_GetText(" wrong version, md5: ")); + else + CONS_Printf(M_GetText(" not found, md5: ")); { INT32 j; char md5tmp[33]; + for (j = 0; j < 16; j++) - sprintf(&md5tmp[j*2], "%02x", fileneeded[i].md5sum[j]); + snprintf(&md5tmp[j*2], 3, "%02x", fileneeded[i].md5sum[j]); + CONS_Printf("%s", md5tmp); } + CONS_Printf("\n"); } + } switch (dlstatus) { @@ -303,6 +322,7 @@ boolean CL_CheckDownloadable(void) CONS_Printf(M_GetText("All files downloadable, but you have chosen to disable downloading locally.\n")); break; } + return false; } @@ -540,7 +560,7 @@ INT32 CL_CheckFiles(void) if (fileneeded[i].status != FS_OPEN) filestoload++; - if (fileneeded[i].status != FS_NOTCHECKED) //since we're running this over multiple tics now, its possible for us to come across files checked in previous tics + if (fileneeded[i].status != FS_NOTCHECKED) // since we're running this over multiple tics now, its possible for us to come across files checked in previous tics continue; CONS_Debug(DBG_NETPLAY, "searching for '%s' ", fileneeded[i].filename); @@ -548,14 +568,18 @@ INT32 CL_CheckFiles(void) // Check in already loaded files for (j = mainwads+1; j < numwadfiles; j++) { - nameonly(strcpy(wadfilename, wadfiles[j]->filename)); - - if (fasticmp(wadfilename, fileneeded[i].filename) && - !memcmp(wadfiles[j]->md5sum, fileneeded[i].md5sum, 16)) + if (!memcmp(wadfiles[j]->md5sum, fileneeded[i].md5sum, 16)) { - CONS_Debug(DBG_NETPLAY, "already loaded\n"); - fileneeded[i].status = FS_OPEN; - return 4; + strncpy(wadfilename, wadfiles[j]->filename, MAX_WADPATH); + wadfilename[MAX_WADPATH-1] = '\0'; + nameonly(wadfilename); + + if (fasticmp(wadfilename, fileneeded[i].filename)) + { + CONS_Debug(DBG_NETPLAY, "already loaded\n"); + fileneeded[i].status = FS_OPEN; + return 4; + } } } @@ -573,6 +597,48 @@ INT32 CL_CheckFiles(void) return 1; //everything is FS_OPEN or FS_FOUND, proceed to loading } +static addontype_t GetAddonType(const char *name) +{ + const char *prefix = strchr(name, '_'); + + // Doesn't have prefix (no '_' character or it is too far and is probably not for prefix but for something like version) + // KRBCL_ is longest prefix i can think of so this should be enough + if (prefix == NULL || prefix - name > 5) + return ADDON_MISC; + + // Skip 'K' + if (*name == 'K') + ++name; + + switch (*name) + { + case 'L': + return ADDON_SCRIPT; + break; + + case 'R': + case 'B': + return ADDON_MAP; + break; + + case 'C': + return ADDON_CHARACTER; + break; + } + + return ADDON_MISC; +} + +void CL_CheckAddonTypes(void) +{ + memset(&addontypes, 0, sizeof(addontypes)); + + for (INT32 i = 0; i < fileneedednum; i++) + { + addontypes[fileneeded[i].type]++; + } +} + // Load it now boolean CL_LoadServerFiles(void) { @@ -594,7 +660,7 @@ boolean CL_LoadServerFiles(void) else { const char *s; - switch(fileneeded[i].status) + switch (fileneeded[i].status) { case FS_NOTFOUND: s = "FS_NOTFOUND"; @@ -637,7 +703,7 @@ static boolean SV_SendFile(INT32 node, const char *filename, UINT8 fileid) char wadfilename[MAX_WADPATH]; - if (cv_noticedownload.value) + if (cv_noticedownload.value && I_GetNodeAddress) CONS_Printf("Sending file \"%s\" (id %d) to node %d (%s)\n", filename, fileid, node, I_GetNodeAddress(node)); // Find the last file in the list and set a pointer to its "next" field @@ -662,7 +728,9 @@ static boolean SV_SendFile(INT32 node, const char *filename, UINT8 fileid) // Look for the requested file through all loaded files for (wadnum = 0; wadfiles[wadnum]; wadnum++) { - strlcpy(wadfilename, wadfiles[wadnum]->filename, MAX_WADPATH); + // im a certified strlcpy hater + strncpy(wadfilename, wadfiles[wadnum]->filename, MAX_WADPATH); + wadfilename[MAX_WADPATH-1] = '\0'; nameonly(wadfilename); if (fasticmp(wadfilename, p->id.filename)) @@ -958,7 +1026,7 @@ void Got_Filetxpak(void) || fastcmp(filename, "music.kart") || fastcmp(filename, "patch.kart") )) - I_Error("Tried to download \"%s\"", filename); + I_Error("Tried to download base-game file: \"%s\"", filename); if (filenum >= fileneedednum) { @@ -1015,23 +1083,23 @@ void Got_Filetxpak(void) { const char *s; - switch(file->status) + switch (file->status) { - case FS_NOTFOUND: - s = "FS_NOTFOUND"; - break; - case FS_FOUND: - s = "FS_FOUND"; - break; - case FS_OPEN: - s = "FS_OPEN"; - break; - case FS_MD5SUMBAD: - s = "FS_MD5SUMBAD"; - break; - default: - s = "unknown"; - break; + case FS_NOTFOUND: + s = "FS_NOTFOUND"; + break; + case FS_FOUND: + s = "FS_FOUND"; + break; + case FS_OPEN: + s = "FS_OPEN"; + break; + case FS_MD5SUMBAD: + s = "FS_MD5SUMBAD"; + break; + default: + s = "unknown"; + break; } I_Error("Received a file not requested (file id: %d, file status: %s)\n", filenum, s); @@ -1079,12 +1147,14 @@ void CloseNetFile(void) // Receiving a file? for (i = 0; i < MAX_WADFILES; i++) + { if (fileneeded[i].status == FS_DOWNLOADING && fileneeded[i].file) { fclose(fileneeded[i].file); // File is not complete delete it remove(fileneeded[i].filename); } + } // Remove PT_FILEFRAGMENT from acknowledge list Net_AbortPacketType(PT_FILEFRAGMENT); @@ -1098,17 +1168,16 @@ void nameonly(char *s) void *ns; for (j = strlen(s); j != (size_t)-1; j--) + { if ((s[j] == '\\') || (s[j] == ':') || (s[j] == '/')) { ns = &(s[j+1]); len = strlen(ns); -#if 0 - memcpy(s, ns, len+1); -#else - memmove(s, ns, len+1); -#endif + memmove(s, ns, len+1); + return; } + } } // Returns the length in characters of the last element of a path. @@ -1142,7 +1211,7 @@ filestatus_t checkfilemd5(char *filename, const UINT8 *wantedmd5sum) fhandle = fopen(filename, "rb"); if (fhandle) { - md5_stream(fhandle,md5sum); + md5_stream(fhandle, md5sum); fclose(fhandle); if (!memcmp(wantedmd5sum, md5sum, 16)) return FS_FOUND; @@ -1162,8 +1231,12 @@ filestatus_t findfile(char *filename, const UINT8 *wantedmd5sum, boolean complet filestatus_t homecheck; // store result of last file search boolean badmd5 = false; // store whether md5 was bad from either of the first two searches (if nothing was found in the third) - // skip for startup, our mainwads wont be in there - if (loaded_config) + // see IdentifyVersion + // Iwads skip findfile due to passing fullpath to W_OpenWadFile +#if 0 + // skip for Iwads, as they wont be in there + if (!startupiwadcount) +#endif { if (cv_addons_option.value == 3 && *cv_addons_folder.string != '\0') { @@ -1300,6 +1373,7 @@ void CURLPrepareFile(const char* url, int dfilenum) if (!multi_handle) { cc = curl_global_init(CURL_GLOBAL_ALL); + if (cc < 0) { I_OutputMsg("libcurl: curl_global_init() returned %d\n", cc); @@ -1308,6 +1382,7 @@ void CURLPrepareFile(const char* url, int dfilenum) { multi_handle = curl_multi_init(); } + if (!multi_handle) { I_OutputMsg("libcurl: curl_multi_init() failed\n"); @@ -1436,7 +1511,7 @@ void CURLAbortFile(void) #endif } -void CURLGetFile(void) +static void CURLGetFile(void) { #ifdef HAVE_THREADS I_lock_mutex(&downloadmutex); @@ -1478,7 +1553,8 @@ void CURLGetFile(void) e = m->easy_handle; easyres = m->data.result; - char *filename = Z_StrDup(curl_realname); + char *filename = malloc(strlen(curl_realname)+1); + strcpy(filename, curl_realname); nameonly(filename); if (easyres != CURLE_OK) @@ -1516,7 +1592,7 @@ void CURLGetFile(void) } } - Z_Free(filename); + free(filename); curl_curfile->file = NULL; filedownload.remaining--; mc = curl_multi_remove_handle(multi_handle, e); @@ -1543,8 +1619,7 @@ void CURLGetFile(void) #endif } -HTTP_login * -CURLGetLogin (const char *url, HTTP_login ***return_prev_next) +HTTP_login *CURLGetLogin(const char *url, HTTP_login ***return_prev_next) { HTTP_login * login; HTTP_login ** prev_next; @@ -1554,7 +1629,7 @@ CURLGetLogin (const char *url, HTTP_login ***return_prev_next) ( login = (*prev_next)); prev_next = &login->next ){ - if (fastcmp(login->url, url) != 0) + if (fastcmp(login->url, url)) { if (return_prev_next) (*return_prev_next) = prev_next; diff --git a/src/d_netfil.h b/src/d_netfil.h index 3c7502451..4d4cdba74 100644 --- a/src/d_netfil.h +++ b/src/d_netfil.h @@ -40,6 +40,15 @@ typedef enum FS_FALLBACK, // HTTP failed } filestatus_t; +typedef enum addontype_e +{ + ADDON_SCRIPT, + ADDON_MAP, + ADDON_CHARACTER, + ADDON_MISC, + NUMADDONTYPES, +} addontype_t; + typedef struct { UINT8 willsend; // Is the server willing to send it? @@ -51,11 +60,13 @@ typedef struct UINT32 totalsize; filestatus_t status; // The value returned by recsearch boolean justdownloaded; // To prevent late fragments from causing an I_Error + addontype_t type; } fileneeded_t; extern INT32 fileneedednum; extern fileneeded_t fileneeded[MAX_WADFILES]; extern char downloaddir[512]; +extern INT32 addontypes[NUMADDONTYPES]; typedef struct { @@ -91,6 +102,7 @@ void D_ParseFileneeded(INT32 fileneedednum_parm, UINT8 *fileneededstr, UINT16 fi void CL_PrepareDownloadSaveGame(const char *tmpsave); INT32 CL_CheckFiles(void); +void CL_CheckAddonTypes(void); boolean CL_LoadServerFiles(void); void SV_SendRam(INT32 node, void *data, size_t size, freemethod_t freemethod, UINT8 fileid); @@ -119,7 +131,6 @@ size_t nameonlylength(const char *s); #ifdef HAVE_CURL void CURLPrepareFile(const char* url, int dfilenum); void CURLAbortFile(void); -void CURLGetFile(void); HTTP_login * CURLGetLogin (const char *url, HTTP_login ***return_prev_next); size_t curlwrite_data(void *ptr, size_t size, size_t nmemb, FILE *stream); #endif diff --git a/src/d_player.h b/src/d_player.h index bcecb66a5..e4aded95b 100644 --- a/src/d_player.h +++ b/src/d_player.h @@ -566,6 +566,8 @@ typedef struct player_s fixed_t fovadd; // adjust FOV for hw rendering SINT8 driftlevel; // just for controller rumble for now + + UINT8 stairjank; } player_t; #endif diff --git a/src/d_protocol.c b/src/d_protocol.c index 963d8e587..7cf84be93 100644 --- a/src/d_protocol.c +++ b/src/d_protocol.c @@ -211,12 +211,12 @@ void D_SetupProtocol(void) if (result) { - if (!fastcmp(buffer, "no")) + if (fastcmp(buffer, "no")) { fclose(fp); return; } - else if (fastcmp(buffer, exe_path)) + else if (!fastcmp(buffer, exe_path)) { // overwrite fclose(fp); diff --git a/src/dedicated/CMakeLists.txt b/src/dedicated/CMakeLists.txt index 36f670251..38fb179f0 100644 --- a/src/dedicated/CMakeLists.txt +++ b/src/dedicated/CMakeLists.txt @@ -1,21 +1,75 @@ # Declare dedicated interface sources -target_sourcefile(c) +set(SRB2_DEDICATED_SOURCES + i_system.c + i_main.c + i_video.c + i_sound.c + i_threads.c + dosstr.c + endtxt.c +) -target_sources(SRB2SDL2 PRIVATE) +set(SRB2_DEDICATED_HEADERS + endtxt.h +) + +source_group("Interface Code" FILES ${SRB2_DEDICATED_SOURCES} ${SRB2_DEDICATED_HEADERS}) + +set(SRB2_DEDICATED_TOTAL_SOURCES + ${SRB2_CORE_SOURCES} + ${SRB2_CORE_HEADERS} + ${SRB2_PNG_SOURCES} + ${SRB2_PNG_HEADERS} + ${SRB2_CORE_RENDER_SOURCES} + ${SRB2_CORE_GAME_SOURCES} + ${SRB2_LUA_SOURCES} + ${SRB2_LUA_HEADERS} + ${SRB2_BLUA_SOURCES} + ${SRB2_BLUA_HEADERS} + ${SRB2_DEDICATED_SOURCES} + ${SRB2_DEDICATED_HEADERS} +) + +source_group("Main" FILES ${SRB2_CORE_SOURCES} ${SRB2_CORE_HEADERS}) +source_group("Renderer" FILES ${SRB2_CORE_RENDER_SOURCES}) +source_group("Game" FILES ${SRB2_CORE_GAME_SOURCES}) +source_group("LUA" FILES ${SRB2_LUA_SOURCES} ${SRB2_LUA_HEADERS}) +source_group("LUA\\Interpreter" FILES ${SRB2_BLUA_SOURCES} ${SRB2_BLUA_HEADERS}) if(${CMAKE_SYSTEM} MATCHES Windows) - target_sources(SRB2SDL2 PRIVATE - ../win32/win_dbg.c - ../win32/Srb2win.rc) + set(SRB2_DEDICATED_TOTAL_SOURCES ${SRB2_DEDICATED_TOTAL_SOURCES} + ${CMAKE_SOURCE_DIR}/src/win32/win_dbg.c + ${CMAKE_SOURCE_DIR}/src/win32/Srb2win.rc + ) endif() +add_executable(SRB2SDL2 MACOSX_BUNDLE WIN32 ${SRB2_DEDICATED_TOTAL_SOURCES}) + if(${CMAKE_SYSTEM} MATCHES Windows) - set_target_properties(SRB2SDL2 PROPERTIES OUTPUT_NAME srb2legacy) + set_target_properties(SRB2SDL2 PROPERTIES OUTPUT_NAME srb2kartd) elseif(${CMAKE_SYSTEM} MATCHES Linux) - set_target_properties(SRB2SDL2 PROPERTIES OUTPUT_NAME lsrb2dlegacy) + set_target_properties(SRB2SDL2 PROPERTIES OUTPUT_NAME lsrb2kartd) else() - set_target_properties(SRB2SDL2 PROPERTIES OUTPUT_NAME srb2legacy) + set_target_properties(SRB2SDL2 PROPERTIES OUTPUT_NAME srb2kartd) +endif() + +if(${CMAKE_SYSTEM} MATCHES Darwin) + find_library(CORE_FOUNDATION_LIBRARY "CoreFoundation") + target_link_libraries(SRB2SDL2 PRIVATE + ${CORE_FOUNDATION_LIBRARY} + ) + set_target_properties(SRB2SDL2 PROPERTIES OUTPUT_NAME "${CPACK_PACKAGE_DESCRIPTION_SUMMARY}") + + # Configure the app bundle icon and plist properties + target_sources(SRB2SDL2 PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/macosx/Srb2mac.icns") + set_target_properties(SRB2SDL2 PROPERTIES + MACOSX_BUNDLE_ICON_FILE "Srb2mac" + MACOSX_BUNDLE_BUNDLE_NAME "Sonic Robo Blast 2" + MACOSX_BUNDLE_BUNDLE_VERSION ${SRB2_VERSION} + + RESOURCE "${CMAKE_CURRENT_SOURCE_DIR}/macosx/Srb2mac.icns" + ) endif() if(${CMAKE_SYSTEM} MATCHES Darwin) @@ -24,25 +78,27 @@ if(${CMAKE_SYSTEM} MATCHES Darwin) ${CORE_LIB} ${PNG_LIBRARIES} ${ZLIB_LIBRARIES} + ${CURL_LIBRARIES} ) set_target_properties(SRB2SDL2 PROPERTIES OUTPUT_NAME "${CPACK_PACKAGE_DESCRIPTION_SUMMARY}") else() target_link_libraries(SRB2SDL2 PRIVATE ${PNG_LIBRARIES} ${ZLIB_LIBRARIES} + ${CURL_LIBRARIES} ) - if(${CMAKE_SYSTEM} MATCHES Linux) target_link_libraries(SRB2SDL2 PRIVATE m rt + pthread ) endif() endif() -#target_link_libraries(SRB2SDL2 PRIVATE SRB2Core) - -set_target_properties(SRB2SDL2 PROPERTIES VERSION ${SRB2_VERSION}) +if(${SRB2_HAVE_LIBBACKTRACE}) + target_link_libraries(SRB2SDL2 PRIVATE ${LIBBACKTRACE_LIBRARIES}) +endif() if(${CMAKE_SYSTEM} MATCHES Windows) target_link_libraries(SRB2SDL2 PRIVATE @@ -60,20 +116,35 @@ target_include_directories(SRB2SDL2 PRIVATE target_compile_definitions(SRB2SDL2 PRIVATE -DDEDICATED + -DHAVE_THREADS ) -## strip debug symbols into separate file when using gcc -if(CMAKE_COMPILER_IS_GNUCC) - if(${CMAKE_BUILD_TYPE} MATCHES Debug) - message(STATUS "Will make separate debug symbols in *.debug") - add_custom_command(TARGET SRB2SDL2 POST_BUILD - COMMAND ${OBJCOPY} --only-keep-debug $ $.debug - COMMAND ${OBJCOPY} --strip-debug $ - COMMAND ${OBJCOPY} --add-gnu-debuglink=$.debug $ - ) - endif() +if(SRB2_CONFIG_LTO AND NOT SRB2_CONFIG_DEBUGMODE) + set_property(TARGET SRB2SDL2 PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE) endif() +if(SRB2_CONFIG_ASAN) + target_compile_options(SRB2SDL2 PRIVATE -fsanitize=address) + target_link_options(SRB2SDL2 PRIVATE -fsanitize=address) +endif() + +if(SRB2_CONFIG_UBSAN) + target_compile_options(SRB2SDL2 PRIVATE -fsanitize=undefined) + target_link_options(SRB2SDL2 PRIVATE -fsanitize=undefined) +endif() + +## strip debug symbols into separate file when using gcc +# if(CMAKE_COMPILER_IS_GNUCC) +# if(${CMAKE_BUILD_TYPE} MATCHES Debug) +# message(STATUS "Will make separate debug symbols in *.debug") +# add_custom_command(TARGET SRB2SDL2 POST_BUILD +# COMMAND ${OBJCOPY} --only-keep-debug $ $.debug +# COMMAND ${OBJCOPY} --strip-debug $ +# COMMAND ${OBJCOPY} --add-gnu-debuglink=$.debug $ +# ) +# endif() +# endif() + #### Installation #### if(${CMAKE_SYSTEM} MATCHES Darwin) install(TARGETS SRB2SDL2 diff --git a/src/dedicated/i_system.c b/src/dedicated/i_system.c index 31eaf0346..ec469620b 100644 --- a/src/dedicated/i_system.c +++ b/src/dedicated/i_system.c @@ -68,6 +68,12 @@ typedef LPVOID (WINAPI *p_MapViewOfFile) (HANDLE, DWORD, DWORD, DWORD, SIZE_T); #include #if defined (__linux__) #include +#elif defined(__APPLE__) +#include +#include +#include +#include +#include #else #include #include @@ -156,8 +162,7 @@ const char *wadSearchPaths[] = { /** \brief WAD file to look for */ -#define WADKEYWORD1 "srb2.srb" -#define WADKEYWORD2 "srb2.wad" +#define WADKEYWORD "srb2.srb" /** \brief holds wad path */ static char returnWadPath[256]; @@ -167,6 +172,8 @@ static char returnWadPath[256]; #include "../i_video.h" #include "../i_sound.h" #include "../i_system.h" +#include "../i_time.h" +#include "../i_net.h" #include "../screen.h" //vid.WndParent #include "../d_net.h" #include "../g_game.h" @@ -178,10 +185,6 @@ static char returnWadPath[256]; #include "../m_argv.h" -#ifdef MAC_ALERT -#include "macosx/mac_alert.h" -#endif - #include "../d_main.h" #if !defined(NOMUMBLE) && defined(HAVE_MUMBLE) @@ -196,8 +199,6 @@ UINT8 keyboard_started = false; #ifdef HAVE_TERMIOS // TERMIOS console code from Quake3: thank you! -boolean stdin_active = true; - typedef struct { size_t cursor; @@ -524,17 +525,24 @@ void I_OutputMsg(const char *fmt, ...) { size_t len; char *txt; - va_list argptr; + va_list argptr; - va_start(argptr,fmt); + if (!fmt) + return; + + va_start(argptr, fmt); len = vsnprintf(NULL, 0, fmt, argptr); va_end(argptr); if (len == 0) return; - txt = malloc(len+1); - va_start(argptr,fmt); - vsprintf(txt, fmt, argptr); + txt = (char*)(malloc(len+1)); + + if (!txt) + I_Error("I_OutputMsg: Out of memory!\n"); + + va_start(argptr, fmt); + vsnprintf(txt, len+1, fmt, argptr); va_end(argptr); #ifdef HAVE_TTF @@ -542,7 +550,7 @@ void I_OutputMsg(const char *fmt, ...) DEFAULTFONTBGR, DEFAULTFONTBGG, DEFAULTFONTBGB, DEFAULTFONTBGA, txt); #endif - len = strlen(txt); + len = strnlen(txt, len+1); #ifdef LOGMESSAGES if (logstream) @@ -699,11 +707,7 @@ void I_JoyScale4(void) */ -void I_ShutdownJoystick(void) -{ -} - -void I_GetJoystickEvents(UINT8 index) +void I_ShutdownJoystick(UINT8 index) { (void)index; } @@ -743,6 +747,22 @@ const char *I_GetJoyName(INT32 joyindex) return NULL; } +void I_SetJoystickFocus(void) +{ +} + +boolean I_GamepadHasLED(INT32 playernum) +{ + (void)playernum; + return false; +} + +boolean I_GamepadHasRumble(INT32 playernum) +{ + (void)playernum; + return false; +} + void I_GamepadRumble(INT32 playernum, UINT16 low_strength, UINT16 high_strength, UINT32 duration) { (void)playernum; @@ -948,14 +968,18 @@ void I_Sleep(UINT32 ms) void I_SleepDuration(precise_t duration) { -#if defined(__linux__) || defined(__FreeBSD__) || defined(__HAIKU__) +#if defined(__linux__) || defined(__FreeBSD__) || defined(__HAIKU__) || defined(__OpenBSD__) UINT64 precision = I_GetPrecisePrecision(); struct timespec ts = { .tv_sec = duration / precision, .tv_nsec = duration * 1000000000 / precision % 1000000000, }; int status; +#ifdef __OpenBSD__ + do status = nanosleep(&ts, &ts); +#else do status = clock_nanosleep(CLOCK_MONOTONIC, 0, &ts, &ts); +#endif while (status == EINTR); #elif defined (MIN_SLEEP_DURATION_MS) UINT64 precision = I_GetPrecisePrecision(); @@ -992,7 +1016,7 @@ void I_SleepDuration(precise_t duration) #endif } -boolean g_in_exiting_signal_handler = false; +static volatile sig_atomic_t g_in_exiting_signal_handler = false; static void I_PrintSignal(INT32 signal_num, boolean core_dumped, char *signal_msg) { @@ -1015,8 +1039,13 @@ static void I_PrintSignal(INT32 signal_num, boolean core_dumped, char *signal_ms sigmsg = ("SIGSEGV - SRB2Kart-Saturn has attempted to access a memory location that it shouldn't and needs to close."); break; #ifdef SIGTERM - case SIGTERM: // Software termination signal from kill - sigmsg = ("SIGTERM - SRB2Kart-Saturn was terminated by a kill signal."); + case SIGTERM: // Software termination signal from terminate + sigmsg = ("SIGTERM - SRB2Kart-Saturn was terminated by a terminate signal."); + break; +#endif +#ifdef SIGKILL + case SIGKILL: // Software termination signal from kill + sigmsg = ("SIGKILL - SRB2Kart-Saturn was terminated by a kill signal."); break; #endif #ifdef SIGBREAK @@ -1028,7 +1057,7 @@ static void I_PrintSignal(INT32 signal_num, boolean core_dumped, char *signal_ms sigmsg = ("SIGABRT - SRB2Kart-Saturn was terminated by an abort signal."); break; default: - sprintf(signal_msg, "Signal number %d", signal_num); + snprintf(signal_msg, 512, "Signal number %d", signal_num); sigmsg = (core_dumped ? "Unknown signal" : signal_msg); break; } @@ -1036,13 +1065,17 @@ static void I_PrintSignal(INT32 signal_num, boolean core_dumped, char *signal_ms if (core_dumped) { if (sigmsg) - sprintf(signal_msg, "%s (core dumped)", sigmsg); + { + snprintf(signal_msg, 512, "%s (core dumped)", sigmsg); + } else + { strcat(signal_msg, " (core dumped)"); + } } else { - sprintf(signal_msg, "%s", sigmsg); + snprintf(signal_msg, 512, "%s", sigmsg); } } @@ -1056,6 +1089,11 @@ static void I_ReportSignal(int num, int coredumped) I_OutputMsg("\nProcess killed by signal: %s\n\n", sigmsg); } +boolean I_In_Exiting_Signal_Handler(void) +{ + return g_in_exiting_signal_handler; +} + #ifndef NEWSIGNALHANDLER FUNCNORETURN static ATTRNORETURN void signal_handler(INT32 num) { @@ -1075,11 +1113,17 @@ FUNCNORETURN static ATTRNORETURN void signal_handler(INT32 num) } #endif -FUNCNORETURN static ATTRNORETURN void quit_handler(int num) +static volatile sig_atomic_t interrupted = 0; + +boolean I_Interrupted(void) { - signal(num, SIG_DFL); //default signal action - raise(num); - I_Quit(); + return interrupted; +} + +static void quit_handler(int num) +{ + (void)num; + interrupted = 1; } #ifdef HAVE_LIBBACKTRACE @@ -1308,7 +1352,7 @@ FUNCNORETURN static ATTRNORETURN void newsignalhandler_Warn(const char *pr) { char text[128]; - snprintf(text, sizeof text, + snprintf(text, sizeof(text), "Error while setting up signal reporting: %s: %s", pr, strerror(errno) @@ -1338,18 +1382,28 @@ static void I_Fork(void) I_RegisterChildSignals(); break; default: + // ignore those, those are handled by child process + // otherwise parent might exit before it + // and the below stuff wont run and your terminal will be left in an awkward state +#ifdef SIGINT + signal(SIGINT, SIG_IGN); +#endif +#ifdef SIGBREAK + signal(SIGBREAK, SIG_IGN); +#endif +#ifdef SIGTERM + signal(SIGTERM, SIG_IGN); +#endif if (logstream) fclose(logstream);/* the child has this */ c = wait(&status); - #ifdef LOGMESSAGES /* By the way, exit closes files. */ logstream = fopen(logfilename, "at"); #else logstream = 0; #endif - if (c == -1) { kill(child, SIGKILL); @@ -1379,6 +1433,12 @@ static void I_Fork(void) } #endif/*NEWSIGNALHANDLER*/ +int I_OpenURL(const char *url) +{ + (void)url; + return -1; +} + INT32 I_StartupSystem(void) { I_StartupConsole(); @@ -1409,8 +1469,8 @@ void I_Quit(void) /* prevent recursive I_Quit() */ if (quiting) goto death; + quiting = false; - I_ShutdownConsole(); M_SaveConfig(NULL); //save game config, cvars.. D_SaveBan(); // save the ban list G_SaveGameData(false); // Tails 12-08-2002 @@ -1426,16 +1486,18 @@ void I_Quit(void) // use this for 1.28 19990220 by Kin I_ShutdownGraphics(); I_ShutdownSystem(); + /* if option -noendtxt is set, don't print the text */ if (!M_CheckParm("-noendtxt") && W_CheckNumForName("ENDOOM") != LUMPERROR) { printf("\r"); ShowEndTxt(); } + if (myargmalloc) free(myargv); // Deallocate allocated memory + death: - W_Shutdown(); exit(0); } @@ -1476,12 +1538,11 @@ FUNCIERROR void ATTRNORETURN I_Error(const char *error, ...) if (errorcount > 20) { va_start(argptr, error); - vsnprintf(buffer, 8192, error, argptr); + vsnprintf(buffer, sizeof(buffer), error, argptr); va_end(argptr); I_OutputMsg("SRB2Kart %s Recursive Error", buffer); - W_Shutdown(); exit(-1); // recursive errors detected } } @@ -1490,7 +1551,7 @@ FUNCIERROR void ATTRNORETURN I_Error(const char *error, ...) // Display error message in the console before we start shutting it down va_start(argptr, error); - vsnprintf(buffer, 8192, error, argptr); + vsnprintf(buffer, sizeof(buffer), error, argptr); va_end(argptr); I_OutputMsg("\nI_Error(): %s\n", buffer); @@ -1499,8 +1560,6 @@ FUNCIERROR void ATTRNORETURN I_Error(const char *error, ...) #endif // --- - I_ShutdownConsole(); - M_SaveConfig(NULL); // save game config, cvars.. D_SaveBan(); // save the ban list G_SaveGameData(false); // Tails 12-08-2002 @@ -1516,8 +1575,6 @@ FUNCIERROR void ATTRNORETURN I_Error(const char *error, ...) I_ShutdownGraphics(); I_ShutdownSystem(); - W_Shutdown(); - #if defined (PARANOIA) && defined (__CYGWIN__) *(INT32 *)2 = 4; //Alam: Debug! #endif @@ -1623,9 +1680,10 @@ void I_ShutdownSystem(void) { INT32 c; -#ifndef NEWSIGNALHANDLER - I_ShutdownConsole(); +#ifdef NEWSIGNALHANDLER + if (M_CheckParm("-nofork")) #endif + I_ShutdownConsole(); for (c = MAX_QUIT_FUNCS-1; c >= 0; c--) if (quit_funcs[c]) @@ -1714,7 +1772,8 @@ char *I_GetUserName(void) } } } - strncpy(username, p, MAXPLAYERNAME); + + snprintf(username, sizeof(username), "%s", p); } if (!fastcmp(username, "")) @@ -1738,6 +1797,24 @@ INT32 I_mkdir(const char *dirname, INT32 unixright) #endif } +INT32 I_ChDir(const char *path) +{ +#ifdef _WIN32 + return (SetCurrentDirectoryA(path) ? 0 : -1); +#else + return chdir(path); +#endif +} + +char *I_GetCwd(char *buf, size_t size) +{ +#ifdef _WIN32 + return (GetCurrentDirectoryA((DWORD)size, buf) ? buf : NULL); +#else + return getcwd(buf, size); +#endif +} + char *I_GetEnv(const char *name) { return getenv(name); @@ -1770,42 +1847,34 @@ const char *I_ClipboardPaste(void) */ static boolean isWadPathOk(const char *path) { - char *wad3path = malloc(256); + char wad3path[256]; - if (!wad3path) - return false; - - sprintf(wad3path, pandf, path, WADKEYWORD1); + snprintf(wad3path, sizeof(wad3path), pandf, path, WADKEYWORD); if (FIL_ReadFileOK(wad3path)) { - free(wad3path); return true; } - sprintf(wad3path, pandf, path, WADKEYWORD2); - - if (FIL_ReadFileOK(wad3path)) - { - free(wad3path); - return true; - } - - free(wad3path); return false; } -static void pathonly(char *s) +static void pathonly(char *s, size_t size) { size_t j; - for (j = strlen(s); j != (size_t)-1; j--) + for (j = strnlen(s, size); j != (size_t)-1; j--) + { if ((s[j] == '\\') || (s[j] == ':') || (s[j] == '/')) { - if (s[j] == ':') s[j+1] = 0; - else s[j] = 0; + if (s[j] == ':') + s[j+1] = 0; + else + s[j] = 0; + return; } + } } /** \brief search for srb2.srb in the given path @@ -1821,11 +1890,12 @@ static const char *searchWad(const char *searchDir) static char tempsw[256] = ""; filestatus_t fstemp; - strcpy(tempsw, WADKEYWORD1); + snprintf(tempsw, sizeof(tempsw), "%s", WADKEYWORD); fstemp = filesearch(tempsw, searchDir, NULL, true, 20); + if (fstemp == FS_FOUND) { - pathonly(tempsw); + pathonly(tempsw, sizeof(tempsw)); return tempsw; } @@ -1863,7 +1933,7 @@ static const char *locateWad(void) #ifndef NOCWD // examine current dir - strcpy(returnWadPath, "."); + snprintf(returnWadPath, sizeof(returnWadPath), "%s", "."); I_OutputMsg(",%s", returnWadPath); if (isWadPathOk(returnWadPath)) return NULL; @@ -1875,7 +1945,7 @@ static const char *locateWad(void) // examine user jart directory if ((envstr = I_GetEnv("HOME")) != NULL) { - sprintf(returnWadPath, "%s" PATHSEP DEFAULTDIR, envstr); + snprintf(returnWadPath, sizeof(returnWadPath), "%s" PATHSEP DEFAULTDIR, envstr); CHECKWADPATH(returnWadPath); } #endif @@ -1889,7 +1959,7 @@ static const char *locateWad(void) // examine default dirs for (i = 0; wadDefaultPaths[i]; i++) { - strcpy(returnWadPath, wadDefaultPaths[i]); + snprintf(returnWadPath, sizeof(returnWadPath), "%s", wadDefaultPaths[i]); CHECKWADPATH(returnWadPath); } @@ -1917,12 +1987,11 @@ const char *I_LocateWad(void) // change to the directory where we found srb2.srb #if defined (_WIN32) waddir = _fullpath(NULL, waddir, MAX_PATH); - SetCurrentDirectoryA(waddir); #else waddir = realpath(waddir, NULL); - if (waddir == NULL || chdir(waddir) == -1) - I_OutputMsg("Couldn't change working directory\n"); #endif + if (waddir == NULL || I_ChDir(waddir) == -1) + I_OutputMsg("Couldn't change working directory\n"); } return waddir; @@ -1942,17 +2011,22 @@ const char *I_LocateWad(void) static long get_entry(const char* name, const char* buf) { long val; - char* hit = strstr(buf, name); - if (hit == NULL) { + const char* hit = strstr(buf, name); + + if (hit == NULL) + { return -1; } errno = 0; val = strtol(hit + strlen(name), NULL, 10); - if (errno != 0) { + + if (errno != 0) + { CONS_Alert(CONS_ERROR, M_GetText("get_entry: strtol() failed: %s\n"), strerror(errno)); return -1; } + return val; } #endif @@ -1977,13 +2051,13 @@ size_t I_GetFreeMem(size_t *total) *total = 32 << 20; return 32 << 20; #elif defined (_WIN32) - MEMORYSTATUS info; + MEMORYSTATUSEX info; - info.dwLength = sizeof (MEMORYSTATUS); - GlobalMemoryStatus( &info ); + info.dwLength = sizeof (MEMORYSTATUSEX); + GlobalMemoryStatusEx( &info ); if (total) - *total = (size_t)info.dwTotalPhys; - return (size_t)info.dwAvailPhys; + *total = (size_t)info.ullTotalPhys; + return (size_t)info.ullAvailPhys; #elif defined (__OS2__) UINT32 pr_arena; @@ -2016,7 +2090,7 @@ size_t I_GetFreeMem(size_t *total) { // Error if (total) - *total = 0L; + *total = 0; return 0; } @@ -2025,12 +2099,12 @@ size_t I_GetFreeMem(size_t *total) { // Error if (total) - *total = 0L; + *total = 0; return 0; } memTag += sizeof (MEMTOTAL); - totalKBytes = (size_t)atoi(memTag); + totalKBytes = strtoul(memTag, NULL, 10); if ((memTag = strstr(buf, MEMAVAILABLE)) == NULL) { @@ -2044,7 +2118,7 @@ size_t I_GetFreeMem(size_t *total) { // Error if (total) - *total = 0L; + *total = 0; return 0; } freeKBytes = MemAvailable; @@ -2052,16 +2126,46 @@ size_t I_GetFreeMem(size_t *total) else { memTag += sizeof (MEMAVAILABLE); - freeKBytes = atoi(memTag); + freeKBytes = strtoul(memTag, NULL, 10); } if (total) *total = totalKBytes << 10; return freeKBytes << 10; +#elif defined(__APPLE__) + /* macOS */ + mach_port_t host = mach_host_self(); + kern_return_t kr; + mach_msg_type_number_t count; + vm_size_t v_page_size; + struct vm_statistics64 vm_stats; + uint64_t total_mem, free_mem; + size_t size; + + size = sizeof(total_mem); + if (sysctlbyname("hw.memsize", &total_mem, &size, NULL, 0) < 0) + total_mem = 0; + + kr = host_page_size(host, &v_page_size); + if (kr != KERN_SUCCESS) + v_page_size = 4096; + + count = HOST_VM_INFO64_COUNT; + kr = host_statistics64(host, HOST_VM_INFO64, (host_info64_t)&vm_stats, &count); + if (kr == KERN_SUCCESS) + free_mem = (uint64_t)(vm_stats.free_count + vm_stats.inactive_count) * v_page_size; + else + free_mem = 0; + + if (total) + *total = (size_t)total_mem; + return (size_t)free_mem; #else // Guess 48 MB. if (total) + { *total = 48<<20; + } return 48<<20; #endif } diff --git a/src/dehacked.c b/src/dehacked.c index a3540fdff..cfac59656 100644 --- a/src/dehacked.c +++ b/src/dehacked.c @@ -43,6 +43,9 @@ #include "m_cond.h" +// idk how PUSHGETTER works, but this is unused +static UINT8 ultimatemode = false; + #define REQUIRE_MATHLIB_GUID "{748fcbc8-6480-4013-ac4e-7afce6cab766}" // Free slot names @@ -115,20 +118,25 @@ char *myfgets(char *buf, size_t bufsize, MYFILE *f) size_t i = 0; if (myfeof(f)) return NULL; + // we need one byte for a null terminated string bufsize--; + while (i < bufsize && !myfeof(f)) { char c = *f->curpos++; + if (c == '^') buf[i++] = myfget_color(f); else if (c == '\\') buf[i++] = myfget_hex(f); else if (c != '\r') buf[i++] = c; + if (c == '\n') break; } + buf[i] = '\0'; dbg_line++; @@ -138,25 +146,31 @@ char *myfgets(char *buf, size_t bufsize, MYFILE *f) static char *myhashfgets(char *buf, size_t bufsize, MYFILE *f) { size_t i = 0; + if (myfeof(f)) return NULL; + // we need one byte for a null terminated string bufsize--; + while (i < bufsize && !myfeof(f)) { char c = *f->curpos++; + if (c == '^') buf[i++] = myfget_color(f); else if (c == '\\') buf[i++] = myfget_hex(f); else if (c != '\r') buf[i++] = c; + if (c == '\n') // Ensure debug line is right... dbg_line++; + if (c == '#') break; } - i++; + buf[i] = '\0'; return buf; @@ -173,7 +187,7 @@ FUNCPRINTF static void deh_warning(const char *first, ...) vsnprintf(buf, 1000, first, argptr); // sizeof only returned 4 here. it didn't like that pointer. va_end(argptr); - if(dbg_line == -1) // Not in a SOC, line number unknown. + if (dbg_line == -1) // Not in a SOC, line number unknown. CONS_Alert(CONS_WARNING, "%s\n", buf); else CONS_Alert(CONS_WARNING, "Line %u: %s\n", dbg_line, buf); @@ -261,7 +275,6 @@ static void clear_levels(void) // (no need to set num to 0, we're freeing the entire header shortly) Z_Free(mapheaderinfo[i]->customopts); - P_DeleteGrades(i); Z_Free(mapheaderinfo[i]); mapheaderinfo[i] = NULL; } @@ -270,143 +283,6 @@ static void clear_levels(void) P_AllocMapHeader(gamemap-1); } -static boolean findFreeSlot(INT32 *num) -{ - // Send the character select entry to a free slot. - while (*num < MAXSKINS && PlayerMenu[*num].status != IT_DISABLED) - *num = *num+1; - - // No more free slots. :( - if (*num >= MAXSKINS) - return false; - - // Found one! ^_^ - return true; -} - -// Reads a player. -// For modifying the character select screen -static void readPlayer(MYFILE *f, INT32 num) -{ - char *s = Z_Malloc(MAXLINELEN, PU_STATIC, NULL); - char *word; - char *word2; - INT32 i; - boolean slotfound = false; - - do - { - if (myfgets(s, MAXLINELEN, f)) - { - if (s[0] == '\n') - break; - - word = strtok(s, " "); - if (word) - strupr(word); - else - break; - - if (fastcmp(word, "PLAYERTEXT")) - { - char *playertext = NULL; - - if (!slotfound && (slotfound = findFreeSlot(&num)) == false) - goto done; - PlayerMenu[num].status = IT_CALL; - - for (i = 0; i < MAXLINELEN-3; i++) - { - if (s[i] == '=') - { - playertext = &s[i+2]; - break; - } - } - if (playertext) - { - strcpy(description[num].notes, playertext); - strcat(description[num].notes, myhashfgets(playertext, sizeof (description[num].notes), f)); - } - else - strcpy(description[num].notes, ""); - - // For some reason, cutting the string did not work above. Most likely due to strcpy or strcat... - // It works down here, though. - { - INT32 numline = 0; - for (i = 0; (size_t)i < sizeof(description[num].notes)-1; i++) - { - if (numline < 20 && description[num].notes[i] == '\n') - numline++; - - if (numline >= 20 || description[num].notes[i] == '\0' || description[num].notes[i] == '#') - break; - } - } - description[num].notes[strlen(description[num].notes)-1] = '\0'; - description[num].notes[i] = '\0'; - continue; - } - - word2 = strtok(NULL, " = "); - if (word2) - strupr(word2); - else - break; - - if (word2[strlen(word2)-1] == '\n') - word2[strlen(word2)-1] = '\0'; - i = atoi(word2); - - if (fastcmp(word, "PICNAME")) - { - if (!slotfound && (slotfound = findFreeSlot(&num)) == false) - goto done; - PlayerMenu[num].status = IT_CALL; - strncpy(description[num].picname, word2, 8); - } - else if (fastcmp(word, "STATUS")) - { - // Limit the status to only IT_DISABLED and IT_CALL - if (i) - i = IT_CALL; - else - i = IT_DISABLED; - - /* - You MAY disable previous entries if you so desire... - But try to enable something that's already enabled and you will be sent to a free slot. - - Because of this, you are allowed to edit any previous entrys you like, but only if you - signal that you are purposely doing so by disabling and then reenabling the slot. - - ... Or use MENUPOSITION first, that works too. Hell, you could edit multiple character - slots in a single section that way, due to how SOC editing works. - */ - if (i != IT_DISABLED && !slotfound && (slotfound = findFreeSlot(&num)) == false) - goto done; - PlayerMenu[num].status = (INT16)i; - } - else if (fastcmp(word, "SKINNAME")) - { - // Send to free slot. - if (!slotfound && (slotfound = findFreeSlot(&num)) == false) - goto done; - PlayerMenu[num].status = IT_CALL; - - strlcpy(description[num].skinname, word2, sizeof description[num].skinname); - strlwr(description[num].skinname); - } - else - deh_warning("readPlayer %d: unknown word '%s'", num, word); - } - } while (!myfeof(f)); // finish when the line is empty - -done: - Z_Free(s); -} - static int freeslotusage[2][2] = {{0, 0}, {0, 0}}; // [S_, MT_][max, previous .wad's max] void DEH_UpdateMaxFreeslots(void) @@ -461,12 +337,14 @@ static void readfreeslots(MYFILE *f) { if (used_spr[(i-SPR_FIRSTFREESLOT)/8] & (1<<(i%8))) { - if (!sprnames[i][4] && memcmp(sprnames[i],word,4)==0) + if (!sprnames[i][4] && memcmp(sprnames[i], word, 4) == 0) sprnames[i][4] = (char)f->wad; + continue; // Already allocated, next. } + // Found a free slot! - strncpy(sprnames[i],word,4); + strncpy(sprnames[i], word, 4); //sprnames[i][4] = 0; CONS_Printf("Sprite SPR_%s allocated.\n",word); @@ -475,22 +353,26 @@ static void readfreeslots(MYFILE *f) used_spr[(i-SPR_FIRSTFREESLOT)/8] |= 1<<(i%8); // Okay, this sprite slot has been named now. break; } + if (i > SPR_LASTFREESLOT) I_Error("Out of Sprite Freeslots while allocating \"%s\"\nLoad less addons to fix this.", word); } else if (fastcmp(type, "S")) { for (i = 0; i < NUMSTATEFREESLOTS; i++) - if (!FREE_STATES[i]) { - CONS_Printf("State S_%s allocated.\n",word); + { + if (!FREE_STATES[i]) + { + CONS_Printf("State S_%s allocated.\n", word); LUA_InvalidateMathlibCache(va("S_%s", word)); FREE_STATES[i] = Z_Malloc(strlen(word)+1, PU_STATIC, NULL); - strcpy(FREE_STATES[i],word); + strcpy(FREE_STATES[i], word); freeslotusage[0][0]++; break; } + } if (i == NUMSTATEFREESLOTS) I_Error("Out of State Freeslots while allocating \"%s\"\nLoad less addons to fix this.", word); @@ -498,16 +380,19 @@ static void readfreeslots(MYFILE *f) else if (fastcmp(type, "MT")) { for (i = 0; i < NUMMOBJFREESLOTS; i++) - if (!FREE_MOBJS[i]) { - CONS_Printf("MobjType MT_%s allocated.\n",word); + { + if (!FREE_MOBJS[i]) + { + CONS_Printf("MobjType MT_%s allocated.\n", word); LUA_InvalidateMathlibCache(va("MT_%s", word)); FREE_MOBJS[i] = Z_Malloc(strlen(word)+1, PU_STATIC, NULL); - strcpy(FREE_MOBJS[i],word); + strcpy(FREE_MOBJS[i], word); freeslotusage[1][0]++; break; } + } if (i == NUMMOBJFREESLOTS) I_Error("Out of Mobj Freeslots while allocating \"%s\"\nLoad less addons to fix this.", word); @@ -550,8 +435,11 @@ static void readthing(MYFILE *f, INT32 num) strupr(word2); else break; - if (word2[strlen(word2)-1] == '\n') - word2[strlen(word2)-1] = '\0'; + + const size_t word2len = strlen(word2); + + if (word2[word2len-1] == '\n') + word2[word2len-1] = '\0'; if (fastcmp(word, "MAPTHINGNUM") || fastcmp(word, "DOOMEDNUM")) { @@ -819,22 +707,8 @@ static void readlevelheader(MYFILE *f, INT32 num, INT32 wadnum) // Now go to uppercase strupr(word2); - // NiGHTS grades - if (fastncmp(word, "GRADES", 6)) - { - UINT8 mare = (UINT8)atoi(word + 6); - - if (mare <= 0 || mare > 8) - { - deh_warning("Level header %d: unknown word '%s'", num, word); - continue; - } - - P_AddGradesForMare((INT16)(num-1), mare-1, word2); - } - // Strings that can be truncated - else if (fastcmp(word, "SCRIPTNAME")) + if (fastcmp(word, "SCRIPTNAME")) { deh_strlcpy(mapheaderinfo[num-1]->scriptname, word2, sizeof(mapheaderinfo[num-1]->scriptname), va("Level header %d: scriptname", num)); @@ -846,10 +720,6 @@ static void readlevelheader(MYFILE *f, INT32 num, INT32 wadnum) } else if (fastcmp(word, "ACT")) { - /*if (i >= 0 && i < 20) // 0 for no act number, TTL1 through TTL19 - mapheaderinfo[num-1]->actnum = (UINT8)i; - else - deh_warning("Level header %d: invalid act number %d", num, i);*/ deh_strlcpy(mapheaderinfo[num-1]->actnum, word2, sizeof(mapheaderinfo[num-1]->actnum), va("Level header %d: actnum", num)); } @@ -876,14 +746,20 @@ static void readlevelheader(MYFILE *f, INT32 num, INT32 wadnum) { UINT16 tol = 0; tmp = strtok(word2,","); + do { for (i = 0; TYPEOFLEVEL[i].name; i++) + { if (fastcmp(tmp, TYPEOFLEVEL[i].name)) break; + } + if (!TYPEOFLEVEL[i].name) deh_warning("Level header %d: unknown typeoflevel flag %s\n", num, tmp); + tol |= TYPEOFLEVEL[i].flag; } while((tmp = strtok(NULL,",")) != NULL); + mapheaderinfo[num-1]->typeoflevel = tol; } } @@ -914,11 +790,7 @@ static void readlevelheader(MYFILE *f, INT32 num, INT32 wadnum) mapheaderinfo[num-1]->mustrack = ((UINT16)i - 1); else if (fastcmp(word, "MUSICPOS")) mapheaderinfo[num-1]->muspos = (UINT32)get_number(word2); - else if (fastcmp(word, "MUSICINTERFADEOUT")) - mapheaderinfo[num-1]->musinterfadeout = (UINT32)get_number(word2); - else if (fastcmp(word, "MUSICINTER")) - deh_strlcpy(mapheaderinfo[num-1]->musintername, word2, - sizeof(mapheaderinfo[num-1]->musintername), va("Level header %d: intermission music", num)); + else if (fastcmp(word, "FORCECHARACTER")) { strlcpy(mapheaderinfo[num-1]->forcecharacter, word2, SKINNAMESIZE+1); @@ -960,44 +832,12 @@ static void readlevelheader(MYFILE *f, INT32 num, INT32 wadnum) else if (fastcmp(word, "SKYBOXSCALEZ")) mapheaderinfo[num-1]->skybox_scalez = (INT16)i; - else if (fastcmp(word, "BONUSTYPE")) - { - if (fastcmp(word2, "NONE")) i = -1; - else if (fastcmp(word2, "NORMAL")) i = 0; - else if (fastcmp(word2, "BOSS")) i = 1; - else if (fastcmp(word2, "ERZ3")) i = 2; - - if (i >= -1 && i <= 2) // -1 for no bonus. Max is 2. - mapheaderinfo[num-1]->bonustype = (SINT8)i; - else - deh_warning("Level header %d: invalid bonus type number %d", num, i); - } - - else if (fastcmp(word, "SAVEOVERRIDE")) - { - if (fastcmp(word2, "DEFAULT")) i = SAVE_DEFAULT; - else if (fastcmp(word2, "ALWAYS")) i = SAVE_ALWAYS; - else if (fastcmp(word2, "NEVER")) i = SAVE_NEVER; - - if (i >= SAVE_NEVER && i <= SAVE_ALWAYS) - mapheaderinfo[num-1]->saveoverride = (SINT8)i; - else - deh_warning("Level header %d: invalid save override number %d", num, i); - } - else if (fastcmp(word, "LEVELFLAGS")) mapheaderinfo[num-1]->levelflags = get_number(word2); else if (fastcmp(word, "MENUFLAGS")) mapheaderinfo[num-1]->menuflags = get_number(word2); // SRB2Kart - /*else if (fastcmp(word, "AUTOMAP")) - { - if (i || word2[0] == 'T' || word2[0] == 'Y') - mapheaderinfo[num-1]->automap = true; - else - mapheaderinfo[num-1]->automap = false; - }*/ else if (fastcmp(word, "MOBJSCALE")) mapheaderinfo[num-1]->mobj_scale = get_number(word2); else if (fastcmp(word, "LIGHTCONTRAST") || fastcmp(word, "ENCORELIGHTCONTRAST")) @@ -1110,6 +950,26 @@ static void readlevelheader(MYFILE *f, INT32 num, INT32 wadnum) else mapheaderinfo[num-1]->menuflags &= ~LF2_NOVISITNEEDED; } + else if (fastcmp(word, "MUSICINTERFADEOUT")) + { + continue; // unused + } + else if (fastcmp(word, "MUSICINTER")) + { + continue; // unused + } + else if (fastcmp(word, "BONUSTYPE")) + { + continue; // unused + } + else if (fastcmp(word, "SAVEOVERRIDE")) + { + continue; // unused + } + else if (fastncmp(word, "GRADES", 6)) // NiGHTS grades + { + continue; // unused + } else deh_warning("Level header %d: unknown word '%s'", num, word); } @@ -1195,12 +1055,14 @@ static void readcutscenescene(MYFILE *f, INT32 num, INT32 scenenum) else break; - if (word2[strlen(word2)-1] == '\n') - word2[strlen(word2)-1] = '\0'; + const size_t word2len = strlen(word2); + + if (word2[word2len-1] == '\n') + word2[word2len-1] = '\0'; + i = atoi(word2); usi = (UINT16)i; - if (fastcmp(word, "NUMBEROFPICS")) { cutscenes[num]->scene[scenenum].numpics = (UINT8)i; @@ -1247,12 +1109,14 @@ static void readcutscenescene(MYFILE *f, INT32 num, INT32 scenenum) else if (fastcmp(word, "MUSICSLOT")) { i = get_mus(word2, true); + if (i && i <= 1035) snprintf(cutscenes[num]->scene[scenenum].musswitch, 7, "%sM", G_BuildMapName(i)); else if (i && i <= 1050) strncpy(cutscenes[num]->scene[scenenum].musswitch, compat_special_music_slots[i - 1036], 7); else cutscenes[num]->scene[scenenum].musswitch[0] = 0; // becomes empty string + cutscenes[num]->scene[scenenum].musswitch[6] = 0; } #endif @@ -1657,8 +1521,11 @@ static void readframe(MYFILE *f, INT32 num) strupr(word2); else break; - if (word2[strlen(word2)-1] == '\n') - word2[strlen(word2)-1] = '\0'; + + const size_t word2len = strlen(word2); + + if (word2[word2len-1] == '\n') + word2[word2len-1] = '\0'; if (fastcmp(word1, "SPRITENUMBER") || fastcmp(word1, "SPRITENAME")) { @@ -1881,16 +1748,8 @@ static void reademblemdata(MYFILE *f, INT32 num) emblemlocations[num-1].type = ET_GLOBAL; else if (fastcmp(word2, "SKIN")) emblemlocations[num-1].type = ET_SKIN; - /*else if (fastcmp(word2, "SCORE")) - emblemlocations[num-1].type = ET_SCORE;*/ else if (fastcmp(word2, "TIME")) emblemlocations[num-1].type = ET_TIME; - /*else if (fastcmp(word2, "RINGS")) - emblemlocations[num-1].type = ET_RINGS; - else if (fastcmp(word2, "NGRADE")) - emblemlocations[num-1].type = ET_NGRADE; - else if (fastcmp(word2, "NTIME")) - emblemlocations[num-1].type = ET_NTIME;*/ else emblemlocations[num-1].type = (UINT8)value; } @@ -1995,13 +1854,19 @@ static void readextraemblemdata(MYFILE *f, INT32 num) value = atoi(word2); // used for numerical settings if (fastcmp(word, "NAME")) + { deh_strlcpy(extraemblems[num-1].name, word2, - sizeof (extraemblems[num-1].name), va("Extra emblem %d: name", num)); + sizeof (extraemblems[num-1].name), va("Extra emblem %d: name", num)); + } else if (fastcmp(word, "OBJECTIVE")) + { deh_strlcpy(extraemblems[num-1].description, word2, - sizeof (extraemblems[num-1].description), va("Extra emblem %d: objective", num)); + sizeof (extraemblems[num-1].description), va("Extra emblem %d: objective", num)); + } else if (fastcmp(word, "CONDITIONSET")) + { extraemblems[num-1].conditionset = (UINT8)value; + } else if (fastcmp(word, "SPRITE")) { if (word2[0] >= 'A' && word2[0] <= 'Z') @@ -2073,11 +1938,15 @@ static void readunlockable(MYFILE *f, INT32 num) i = atoi(word2); // used for numerical settings if (fastcmp(word, "NAME")) + { deh_strlcpy(unlockables[num].name, word2, - sizeof (unlockables[num].name), va("Unlockable %d: name", num)); + sizeof (unlockables[num].name), va("Unlockable %d: name", num)); + } else if (fastcmp(word, "OBJECTIVE")) + { deh_strlcpy(unlockables[num].objective, word2, - sizeof (unlockables[num].objective), va("Unlockable %d: objective", num)); + sizeof (unlockables[num].objective), va("Unlockable %d: objective", num)); + } else if (fastcmp(word, "SHOWCONDITIONSET")) unlockables[num].showconditionset = (UINT8)i; else if (fastcmp(word, "CONDITIONSET")) @@ -2179,14 +2048,11 @@ static void readcondition(UINT8 set, UINT32 id, char *word2) } else if ((offset=0) || fastcmp(params[0], "GAMECLEAR") || (++offset && fastcmp(params[0], "ALLEMERALDS"))) - //|| (++offset && fastcmp(params[0], "ULTIMATECLEAR"))) { ty = UC_GAMECLEAR + offset; re = (params[1]) ? atoi(params[1]) : 1; } else if ((offset=0) || fastcmp(params[0], "OVERALLTIME")) - //|| (++offset && fastcmp(params[0], "OVERALLSCORE")) - //|| (++offset && fastcmp(params[0], "OVERALLRINGS"))) { PARAMCHECK(1); ty = UC_OVERALLTIME + offset; @@ -2195,8 +2061,6 @@ static void readcondition(UINT8 set, UINT32 id, char *word2) else if ((offset=0) || fastcmp(params[0], "MAPVISITED") || (++offset && fastcmp(params[0], "MAPBEATEN")) || (++offset && fastcmp(params[0], "MAPALLEMERALDS"))) - //|| (++offset && fastcmp(params[0], "MAPULTIMATE")) - //|| (++offset && fastcmp(params[0], "MAPPERFECT"))) { PARAMCHECK(1); ty = UC_MAPVISITED + offset; @@ -2214,8 +2078,6 @@ static void readcondition(UINT8 set, UINT32 id, char *word2) } } else if ((offset=0) || fastcmp(params[0], "MAPTIME")) - //|| (++offset && fastcmp(params[0], "MAPSCORE")) - //|| (++offset && fastcmp(params[0], "MAPRINGS"))) { PARAMCHECK(2); ty = UC_MAPTIME + offset; @@ -2537,26 +2399,12 @@ static void readmaincfg(MYFILE *f) { flashingtics = (UINT16)get_number(word2); } - else if (fastcmp(word, "TAILSFLYTICS")) - { - tailsflytics = (UINT16)get_number(word2); - } - else if (fastcmp(word, "UNDERWATERTICS")) - { - underwatertics = (UINT16)get_number(word2); - } - else if (fastcmp(word, "SPACETIMETICS")) - { - spacetimetics = (UINT16)get_number(word2); - } else if (fastcmp(word, "EXTRALIFETICS")) { + // this modifies player->powers[pw_extralife] + // which still has some game behaviour attached to it... extralifetics = (UINT16)get_number(word2); } - else if (fastcmp(word, "GAMEOVERTICS")) - { - gameovertics = get_number(word2); - } else if (fastcmp(word, "INTROTOPLAY")) { @@ -2580,10 +2428,7 @@ static void readmaincfg(MYFILE *f) if (creditscutscene > 128) creditscutscene = 128; } - else if (fastcmp(word, "NUMDEMOS")) - { - numDemos = (UINT8)get_number(word2); - } + else if (fastcmp(word, "DEMODELAYTIME")) { demoDelayTime = get_number(word2); @@ -2596,10 +2441,6 @@ static void readmaincfg(MYFILE *f) { use1upSound = (UINT8)(value || word2[0] == 'T' || word2[0] == 'Y'); } - else if (fastcmp(word, "MAXXTRALIFE")) - { - maxXtraLife = (UINT8)get_number(word2); - } else if (fastcmp(word, "GAMEDATA")) { // just ignore it but dont throw a warning @@ -2628,6 +2469,7 @@ static void readmaincfg(MYFILE *f) strcatbf(savegamename, srb2home, PATHSEP); refreshdirmenu |= REFRESHDIR_GAMEDATA;*/ + continue; } else if (fastcmp(word, "RESETDATA")) { @@ -2637,6 +2479,30 @@ static void readmaincfg(MYFILE *f) { strlcpy(customversionstring, word2, sizeof (customversionstring)); } + else if (fastcmp(word, "NUMDEMOS")) + { + continue; // unused + } + else if (fastcmp(word, "TAILSFLYTICS")) + { + continue; // unused + } + else if (fastcmp(word, "UNDERWATERTICS")) + { + continue; // unused + } + else if (fastcmp(word, "SPACETIMETICS")) + { + continue; // unused + } + else if (fastcmp(word, "GAMEOVERTICS")) + { + continue; // unused + } + else if (fastcmp(word, "MAXXTRALIFE")) + { + continue; // unused + } else deh_warning("Maincfg: unknown word '%s'", word); } @@ -2845,17 +2711,12 @@ static void DEH_LoadDehackedFile(MYFILE *f, UINT16 wad) deh_num_warning = 0; // save values for cross reference - /* - for (i = 0; i < NUMSTATES; i++) - saveactions[i] = states[i].action; - for (i = 0; i < NUMSPRITES; i++) - savesprnames[i] = sprnames[i]; - */ for (i = 0; i < NUMSFX; i++) savesfxnames[i] = S_sfx[i].name; // it doesn't test the version of SRB2 and version of dehacked file dbg_line = -1; // start at -1 so the first line is 0. + while (!myfeof(f)) { char origpos[256]; @@ -2883,11 +2744,15 @@ static void DEH_LoadDehackedFile(MYFILE *f, UINT16 wad) strncpy(origpos, s, size); origpos[size] = '\0'; - if (NULL != (word = strtok(s, " "))) { + if (NULL != (word = strtok(s, " "))) + { strupr(word); - if (word[strlen(word)-1] == '\n') - word[strlen(word)-1] = '\0'; + const size_t wordlen = strlen(word); + + if (word[wordlen-1] == '\n') + word[wordlen-1] = '\0'; } + if (word) { if (fastcmp(word, "FREESLOT")) @@ -2908,32 +2773,46 @@ static void DEH_LoadDehackedFile(MYFILE *f, UINT16 wad) // This is not a major mod. continue; } + word2 = strtok(NULL, " "); + if (fastcmp(word, "CHARACTER")) { - if (word2) { + if (word2) + { strupr(word2); - if (word2[strlen(word2)-1] == '\n') - word2[strlen(word2)-1] = '\0'; + const size_t wordlen = strlen(word2); + + if (word2[wordlen-1] == '\n') + word2[wordlen-1] = '\0'; + i = atoi(word2); - } else + } + else i = 0; + if (i >= 0 && i < 32) - readPlayer(f, i); + ignorelines(f); // unused else { deh_warning("Character %d out of range (0 - 31)", i); ignorelines(f); } + // This is not a major mod. continue; } + if (word2) { strupr(word2); - if (word2[strlen(word2)-1] == '\n') - word2[strlen(word2)-1] = '\0'; + const size_t wordlen = strlen(word2); + + if (word2[wordlen-1] == '\n') + word2[wordlen-1] = '\0'; + i = atoi(word2); + if (fastcmp(word, "PATCH")) { // Read patch from spec file. @@ -2944,6 +2823,7 @@ static void DEH_LoadDehackedFile(MYFILE *f, UINT16 wad) { if (i == 0 && word2[0] != '0') // If word2 isn't a number i = get_mobjtype(word2); // find a thing by name + if (i < NUMMOBJTYPES && i >= 0) { if (i < (MT_FIRSTFREESLOT+freeslotusage[1][1])) @@ -2991,6 +2871,7 @@ static void DEH_LoadDehackedFile(MYFILE *f, UINT16 wad) { if (i == 0 && word2[0] != '0') // If word2 isn't a number i = get_state(word2); // find a state by name + if (i < NUMSTATES && i >= 0) { if (i < (S_FIRSTFREESLOT+freeslotusage[0][1])) @@ -3007,6 +2888,7 @@ static void DEH_LoadDehackedFile(MYFILE *f, UINT16 wad) { if (i == 0 && word2[0] != '0') // If word2 isn't a number i = get_sfx(word2); // find a sound by name + if (i < NUMSFX && i >= 0) readsound(f, i, savesfxnames); else @@ -3020,6 +2902,7 @@ static void DEH_LoadDehackedFile(MYFILE *f, UINT16 wad) { if (i == 0 && word2[0] != '0') // If word2 isn't a number i = get_huditem(word2); // find a huditem by name + if (i >= 0 && i < NUMHUDITEMS) readhuditem(f, i); else @@ -3157,11 +3040,8 @@ static void DEH_LoadDehackedFile(MYFILE *f, UINT16 wad) if (deh_num_warning) { CONS_Printf(M_GetText("%d warning%s in the SOC lump\n"), deh_num_warning, deh_num_warning == 1 ? "" : "s"); - if (devparm) { + if (devparm) I_Error("%s%s",va(M_GetText("%d warning%s in the SOC lump\n"), deh_num_warning, deh_num_warning == 1 ? "" : "s"), M_GetText("See log.txt for details.\n")); - //while (!I_GetKey()) - //I_OsPolling(); - } } deh_loaded = true; @@ -8250,95 +8130,121 @@ struct { {NULL,0} }; +// Returns the vlaue of MT_ enumerations static mobjtype_t get_mobjtype(const char *word) -{ // Returns the vlaue of MT_ enumerations +{ mobjtype_t i; + if (*word >= '0' && *word <= '9') return atoi(word); - if (fastncmp("MT_",word,3)) + + if (fastncmp("MT_", word, 3)) word += 3; // take off the MT_ - for (i = 0; i < NUMMOBJFREESLOTS; i++) { + + for (i = 0; i < NUMMOBJFREESLOTS; i++) + { if (!FREE_MOBJS[i]) break; if (fastcmp(word, FREE_MOBJS[i])) return MT_FIRSTFREESLOT+i; } + for (i = 0; i < MT_FIRSTFREESLOT; i++) if (fastcmp(word, MOBJTYPE_LIST[i]+3)) return i; + deh_warning("Couldn't find mobjtype named 'MT_%s'",word); return MT_BLUECRAWLA; } +// Returns the value of S_ enumerations static statenum_t get_state(const char *word) -{ // Returns the value of S_ enumerations +{ statenum_t i; if (*word >= '0' && *word <= '9') return atoi(word); - if (fastncmp("S_",word,2)) + + if (fastncmp("S_", word, 2)) word += 2; // take off the S_ - for (i = 0; i < NUMSTATEFREESLOTS; i++) { + + for (i = 0; i < NUMSTATEFREESLOTS; i++) + { if (!FREE_STATES[i]) break; + if (fastcmp(word, FREE_STATES[i])) return S_FIRSTFREESLOT+i; } + for (i = 0; i < S_FIRSTFREESLOT; i++) if (fastcmp(word, STATE_LIST[i]+2)) return i; + deh_warning("Couldn't find state named 'S_%s'",word); return S_NULL; } +// Returns the value of SPR_ enumerations static spritenum_t get_sprite(const char *word) -{ // Returns the value of SPR_ enumerations +{ spritenum_t i; if (*word >= '0' && *word <= '9') return atoi(word); - if (fastncmp("SPR_",word,4)) + + if (fastncmp("SPR_", word, 4)) word += 4; // take off the SPR_ + for (i = 0; i < NUMSPRITES; i++) - if (!sprnames[i][4] && memcmp(word,sprnames[i],4)==0) + if (!sprnames[i][4] && memcmp(word, sprnames[i], 4) == 0) return i; + deh_warning("Couldn't find sprite named 'SPR_%s'",word); return SPR_NULL; } +// Returns the value of SFX_ enumerations static sfxenum_t get_sfx(const char *word) -{ // Returns the value of SFX_ enumerations +{ sfxenum_t i; + if (*word >= '0' && *word <= '9') return atoi(word); + if (fastncmp("SFX_",word,4)) word += 4; // take off the SFX_ else if (fastncmp("DS",word,2)) word += 2; // take off the DS + for (i = 0; i < NUMSFX; i++) if (S_sfx[i].name && fasticmp(word, S_sfx[i].name)) return i; + deh_warning("Couldn't find sfx named 'SFX_%s'",word); return sfx_None; } #ifdef MUSICSLOT_COMPATIBILITY +// Returns the value of MUS_ enumerations static UINT16 get_mus(const char *word, UINT8 dehacked_mode) -{ // Returns the value of MUS_ enumerations +{ UINT16 i; char lumptmp[4]; if (*word >= '0' && *word <= '9') return atoi(word); + if (!word[2] && toupper(word[0]) >= 'A' && toupper(word[0]) <= 'Z') return (UINT16)M_MapNumber(word[0], word[1]); - if (fastncmp("MUS_",word,4)) + if (fastncmp("MUS_", word, 4)) word += 4; // take off the MUS_ - else if (fastncmp("O_",word,2) || fastncmp("D_",word,2)) + else if (fastncmp("O_", word, 2) || fastncmp("D_", word, 2)) word += 2; // take off the O_ or D_ strncpy(lumptmp, word, 4); lumptmp[3] = 0; - if (fasticmp("MAP",lumptmp)) + + if (fasticmp("MAP", lumptmp)) { word += 3; if (toupper(word[0]) >= 'A' && toupper(word[0]) <= 'Z') @@ -8351,25 +8257,33 @@ static UINT16 get_mus(const char *word, UINT8 dehacked_mode) deh_warning("Couldn't find music named 'MUS_%s'",word); return 0; } + for (i = 0; compat_special_music_slots[i][0]; ++i) if (fasticmp(word, compat_special_music_slots[i])) return i + 1036; + if (dehacked_mode) deh_warning("Couldn't find music named 'MUS_%s'",word); + return 0; } #endif +// Returns the value of HUD_ enumerations static hudnum_t get_huditem(const char *word) -{ // Returns the value of HUD_ enumerations +{ hudnum_t i; + if (*word >= '0' && *word <= '9') return atoi(word); + if (fastncmp("HUD_",word,4)) word += 4; // take off the HUD_ + for (i = 0; i < NUMHUDITEMS; i++) if (fastcmp(word, HUDITEMS_LIST[i])) return i; + deh_warning("Couldn't find huditem named 'HUD_%s'",word); return HUD_LIVESNAME; } @@ -8416,15 +8330,16 @@ static inline int lib_freeslot(lua_State *L) { int n = lua_gettop(L); int r = 0; // args returned - char *s, *type,*word; + char *s, *type, *word; - while (n-- > 0) - { + while (n-- > 0) + { s = Z_StrDup(luaL_checkstring(L,1)); type = strtok(s, "_"); if (type) strupr(type); - else { + else + { Z_Free(s); return luaL_error(L, "Unknown enum type in '%s'\n", luaL_checkstring(L, 1)); } @@ -8432,19 +8347,25 @@ static inline int lib_freeslot(lua_State *L) word = strtok(NULL, "\n"); if (word) strupr(word); - else { + else + { Z_Free(s); return luaL_error(L, "Missing enum name in '%s'\n", luaL_checkstring(L, 1)); } - if (fastcmp(type, "SFX")) { + + if (fastcmp(type, "SFX")) + { sfxenum_t sfx; strlwr(word); - CONS_Printf("Sound sfx_%s allocated.\n",word); + CONS_Printf("Sound sfx_%s allocated.\n", word); sfx = S_AddSoundFx(word, false, 0, false); - if (sfx != sfx_None) { + + if (sfx != sfx_None) + { lua_pushinteger(L, sfx); r++; - } else + } + else I_Error("Out of Sfx Freeslots while allocating \"%s\"\nLoad less addons to fix this.", word); //Should never get here since S_AddSoundFx was changed to throw I_Error when it can't allocate } else if (fastcmp(type, "SPR")) @@ -8458,10 +8379,12 @@ static inline int lib_freeslot(lua_State *L) { if (used_spr[(j-SPR_FIRSTFREESLOT)/8] & (1<<(j%8))) { - if (!sprnames[j][4] && memcmp(sprnames[j],word,4)==0) + if (!sprnames[j][4] && memcmp(sprnames[j], word, 4) == 0) sprnames[j][4] = wad; + continue; // Already allocated, next. } + // Found a free slot! CONS_Printf("Sprite SPR_%s allocated.\n",word); @@ -8469,13 +8392,14 @@ static inline int lib_freeslot(lua_State *L) lua_pushfstring(L, "SPR_%s", word); lua_call(L, 1, 0); - strncpy(sprnames[j],word,4); + strncpy(sprnames[j], word, 4); //sprnames[j][4] = 0; used_spr[(j-SPR_FIRSTFREESLOT)/8] |= 1<<(j%8); // Okay, this sprite slot has been named now. lua_pushinteger(L, j); r++; break; } + if (j > SPR_LASTFREESLOT) I_Error("Out of Sprite Freeslots while allocating \"%s\"\nLoad less addons to fix this.", word); } @@ -8483,8 +8407,10 @@ static inline int lib_freeslot(lua_State *L) { statenum_t i; for (i = 0; i < NUMSTATEFREESLOTS; i++) - if (!FREE_STATES[i]) { - CONS_Printf("State S_%s allocated.\n",word); + { + if (!FREE_STATES[i]) + { + CONS_Printf("State S_%s allocated.\n", word); lua_pushcfunction(L, lua_glib_invalidate_cache); lua_pushfstring(L, "S_%s", word); @@ -8497,6 +8423,8 @@ static inline int lib_freeslot(lua_State *L) r++; break; } + } + if (i == NUMSTATEFREESLOTS) I_Error("Out of State Freeslots while allocating \"%s\"\nLoad less addons to fix this.", word); } @@ -8504,27 +8432,33 @@ static inline int lib_freeslot(lua_State *L) { mobjtype_t i; for (i = 0; i < NUMMOBJFREESLOTS; i++) - if (!FREE_MOBJS[i]) { - CONS_Printf("MobjType MT_%s allocated.\n",word); + { + if (!FREE_MOBJS[i]) + { + CONS_Printf("MobjType MT_%s allocated.\n", word); lua_pushcfunction(L, lua_glib_invalidate_cache); lua_pushfstring(L, "MT_%s", word); lua_call(L, 1, 0); FREE_MOBJS[i] = Z_Malloc(strlen(word)+1, PU_STATIC, NULL); - strcpy(FREE_MOBJS[i],word); + strcpy(FREE_MOBJS[i], word); freeslotusage[1][0]++; lua_pushinteger(L, i); r++; break; } + } + if (i == NUMMOBJFREESLOTS) I_Error("Out of Mobj Freeslots while allocating \"%s\"\nLoad less addons to fix this.", word); } + Z_Free(s); lua_remove(L, 1); continue; } + return r; } @@ -8537,15 +8471,17 @@ static inline int lib_action(lua_State *L) mobj_t *actor = *((mobj_t **)luaL_checkudata(L,1,META_MOBJ)); var1 = (INT32)luaL_optinteger(L,2,0); var2 = (INT32)luaL_optinteger(L,3,0); + if (!actor) return LUA_ErrInvalid(L, "mobj_t"); + (*action)(actor); return 0; } // Hardcoded A_Action name to call for super() or NULL if super() would be invalid. // Set in lua_infolib. -const char *superactions[MAXRECURSION]; +const char *superactions[MAXRECURSION] = {}; UINT8 superstack = 0; static int lib_dummysuper(lua_State *L) @@ -8560,23 +8496,29 @@ FUNCINLINE static ATTRINLINE int lib_getenum(lua_State *L) const char *word; boolean mathlib = lua_toboolean(L, UV_MATHLIB); - if (lua_type(L,2) != LUA_TSTRING) + + if (lua_type(L, 2) != LUA_TSTRING) return 0; - word = lua_tostring(L,2); + + word = lua_tostring(L, 2); /* First check actions, as they can be overridden. */ - if (!mathlib && fastncmp("A_",word,2)) { + if (!mathlib && fastncmp("A_", word, 2)) + { char *caps; // Try to get a Lua action first. /// \todo Push a closure that sets superactions[] and superstack. lua_getfield(L, LUA_REGISTRYINDEX, LREG_ACTIONS); + // actions are stored in all uppercase. caps = Z_StrDup(word); strupr(caps); lua_getfield(L, -1, caps); Z_Free(caps); + if (!lua_isnil(L, -1)) return 1; // Success! :D That was easy. + // Welp, that failed. lua_pop(L, 2); // pop nil and LREG_ACTIONS // Hardcoded actions are handled by the proxy. @@ -8585,12 +8527,14 @@ FUNCINLINE static ATTRINLINE int lib_getenum(lua_State *L) /* Then check the globals proxy table. */ lua_pushvalue(L, 2); lua_gettable(L, GLIB_PROXY); + if (!lua_isnil(L, -1)) { return 1; } - if (mathlib) return luaL_error(L, "constant '%s' could not be parsed.\n", word); + if (mathlib) + return luaL_error(L, "constant '%s' could not be parsed.\n", word); return 0; } @@ -8648,6 +8592,7 @@ static int lua_enumlib_server_get(lua_State *L) { if ((!multiplayer || !(netgame || demo.playback)) && !playeringame[serverplayer]) return 0; + LUA_PushUserdata(L, &players[serverplayer], META_PLAYER); return 1; } @@ -8656,6 +8601,7 @@ static int lua_enumlib_consoleplayer_get(lua_State *L) { if (consoleplayer < 0 || !playeringame[consoleplayer]) return 0; + LUA_PushUserdata(L, &players[consoleplayer], META_PLAYER); return 1; } @@ -8683,6 +8629,7 @@ static int lua_enumlib_mobjtype_get(lua_State *L) { if (!FREE_MOBJS[i]) break; + if (fastcmp(s+3, FREE_MOBJS[i])) { lua_pushinteger(L, MT_FIRSTFREESLOT+i); @@ -8771,30 +8718,29 @@ static int lua_enumlib_sfx_get_ds(lua_State *L) } #ifdef MUSICSLOT_COMPATIBILITY +static int lua_enumlib_mus_get(lua_State *L) +{ + const char *name = strchr(lua_tostring(L, 1), '_') + 1; + int mus = get_mus(name, false); - static int lua_enumlib_mus_get(lua_State *L) - { - const char *name = strchr(lua_tostring(L, 1), '_') + 1; - int mus = get_mus(name, false); + if (mus == 0) + return 0; - if (mus == 0) - return 0; + lua_pushinteger(L, mus); + return 1; +} - lua_pushinteger(L, mus); - return 1; - } +static int lua_enumlib_mus_get_mathlib(lua_State *L) +{ + const char *name = strchr(lua_tostring(L, 1), '_') + 1; + int mus = get_mus(name, false); - static int lua_enumlib_mus_get_mathlib(lua_State *L) - { - const char *name = strchr(lua_tostring(L, 1), '_') + 1; - int mus = get_mus(name, false); + if (mus == 0) + return luaL_error(L, "music '%s' could not be found.\n", lua_tostring(L, 1)); - if (mus == 0) - return luaL_error(L, "music '%s' could not be found.\n", lua_tostring(L, 1)); - - lua_pushinteger(L, mus); - return 1; - } + lua_pushinteger(L, mus); + return 1; +} #endif static int lua_enumlib_power_get(lua_State *L) @@ -8848,12 +8794,15 @@ static int lua_enumlib_action_get(lua_State *L) const char *action = lua_tostring(L, 1); for (int i = 0; actionpointers[i].name; i++) - if (fasticmp(action, actionpointers[i].name)) { + { + if (fasticmp(action, actionpointers[i].name)) + { // push lib_action as a C closure with the actionf_t* as an upvalue. lua_pushlightuserdata(L, &actionpointers[i].action); lua_pushcclosure(L, lib_action, 1); return 1; } + } return 0; } @@ -8871,8 +8820,13 @@ static char *lua_enumlib_sprintf_upper(char **buf, int* size, const char *format va_list va; va_start(va, format); - int length = vsnprintf(*buf, *size, format, va); - if (length > *size) + va_list vacpy; + va_copy(vacpy, va); + + int length = vsnprintf(*buf, *size, format, vacpy); + va_end(vacpy); + + if (length >= *size) { void *ptr = realloc(*buf, length+1); if (!ptr) @@ -8880,12 +8834,13 @@ static char *lua_enumlib_sprintf_upper(char **buf, int* size, const char *format va_end(va); return NULL; } + *buf = ptr; *size = length+1; - va_start(va, format); - vsnprintf(*buf, *size, format, va); + length = vsnprintf(*buf, *size, format, va); } + va_end(va); for (int i = 0; i < length; i++) @@ -8910,11 +8865,14 @@ static int lua_enumlib_super_get(lua_State *L) } for (int i = 0; actionpointers[i].name; i++) - if (fasticmp(superactions[superstack-1], actionpointers[i].name)) { + { + if (fasticmp(superactions[superstack-1], actionpointers[i].name)) + { lua_pushlightuserdata(L, &actionpointers[i].action); lua_pushcclosure(L, lib_action, 1); return 1; } + } return 0; } @@ -9383,7 +9341,10 @@ enum actionnum LUA_GetActionNumByName(const char *actiontocompare) { size_t z; for (z = 0; actionpointers[z].name; z++) + { if (fasticmp(actiontocompare, actionpointers[z].name)) return z; + } + return z; } diff --git a/src/dehacked.h b/src/dehacked.h index eb22c5f6a..0db20ee56 100644 --- a/src/dehacked.h +++ b/src/dehacked.h @@ -13,6 +13,10 @@ #ifndef __DEHACKED_H__ #define __DEHACKED_H__ +#ifdef __cplusplus +extern "C" { +#endif + #include "m_fixed.h" // for get_number #include "info.h" @@ -71,4 +75,9 @@ typedef struct } MYFILE; #define myfeof(a) (a->data + a->size <= a->curpos) char *myfgets(char *buf, size_t bufsize, MYFILE *f); + +#ifdef __cplusplus +} // extern "C" +#endif + #endif diff --git a/src/discord.c b/src/discord.c index 8f937cfc1..a5e5f59c9 100644 --- a/src/discord.c +++ b/src/discord.c @@ -402,7 +402,7 @@ static void Discordrp_OnChange(void) static void DRPC_GotServerIP(UINT32 address) { const unsigned char * p = (const unsigned char *)&address; - sprintf(self_ip, "%u.%u.%u.%u:%u", p[0], p[1], p[2], p[3], current_port); + snprintf(self_ip, IP_SIZE+1, "%u.%u.%u.%u:%u", p[0], p[1], p[2], p[3], current_port); } /*-------------------------------------------------- diff --git a/src/doomdata.h b/src/doomdata.h index a646686f1..77dd84c50 100644 --- a/src/doomdata.h +++ b/src/doomdata.h @@ -61,7 +61,7 @@ enum typedef struct { INT16 x, y; -}ATTRPACK mapvertex_t; +} ATTRPACK mapvertex_t; // A SideDef, defining the visual appearance of a wall, // by setting textures and offsets. @@ -81,10 +81,12 @@ typedef struct INT16 flags; INT16 special; INT16 tag; - // sidenum[1] will be 0xffff if one sided + // sidenum[1] will be NO_INDEX if one sided UINT16 sidenum[2]; } ATTRPACK maplinedef_t; +#define NO_INDEX 0xffff + // // LineDef attributes. // diff --git a/src/doomdef.h b/src/doomdef.h index 0d40e6e30..7dab8035e 100644 --- a/src/doomdef.h +++ b/src/doomdef.h @@ -40,22 +40,45 @@ #define ASMCALL #endif -#ifdef __cplusplus -extern "C" { -#endif - #include "doomtype.h" +#ifdef __cplusplus /* Only when compiled as C++ */ + #include /* std::min, std::max, std::sort, … */ +#endif + +#ifdef __cplusplus +// Force libc++ to expose std::min/std::max even when is included first (Apple clang quirk) +#ifndef _LIBCPP_ENABLE_CXX17_REMOVED_FEATURES +#define _LIBCPP_ENABLE_CXX17_REMOVED_FEATURES +#endif +#ifndef _LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS +#define _LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS +#endif + +// Optional: only try if it actually exists (newer Xcode) +#if __has_include() +#include +#endif + +#define _USE_MATH_DEFINES +#include +#include +#include +#include +#include +#include +#include + +extern "C" { +#else +#include #include #include #include +#include #include -#define _USE_MATH_DEFINES // fixes M_PI errors in r_plane.c for Visual Studio -#ifdef __cplusplus -#include -#else -#include +#include #endif #include @@ -107,8 +130,17 @@ extern char logfilename[1024]; #else #define VERSION 1 // Game version #define SUBVERSION 6 // more precise version number -#define VERSIONSTRING "Saturn v9.2" -#define VERSIONSTRINGW L"Saturn v9.2" + +#ifdef PHOBOS_BUILD +#define CLIENTNAME "Phobos" +#define CLIENTNAMEW L"Phobos" +#else +#define CLIENTNAME "Saturn" +#define CLIENTNAMEW L"Saturn" +#endif + +#define VERSIONSTRING CLIENTNAME " v10" +#define VERSIONSTRINGW CLIENTNAMEW L" v10" //#define SATURN_TESTING // comment out for saturn release builds! @@ -493,22 +525,6 @@ extern boolean capslock; // i_system.c, replace getchar() once the keyboard has been appropriated INT32 I_GetKey(void); -/* http://www.cse.yorku.ca/~oz/hash.html */ -static inline -UINT32 quickncasehash (const char *p, size_t n) -{ - size_t i = 0; - UINT32 x = 5381; - - while (i < n && p[i]) - { - x = (x * 33) ^ tolower(p[i]); - i++; - } - - return x; -} - #ifndef __cplusplus #ifndef min // Double-Check with WATTCP-32's cdefs.h #define min(x, y) (((x) < (y)) ? (x) : (y)) @@ -566,6 +582,13 @@ UINT32 quickncasehash (const char *p, size_t n) // NOTE: you WILL have nasal troubles if the variable is not initialized #define CLEANUP(f) __attribute__((__cleanup__(f))) +// the GNU constructor and destructor attributes +// The constructor attribute causes the function to be called automatically before execution enters main (). +// Similarly, the destructor attribute causes the function to be called automatically after main () has completed or exit () has been called. +// Functions with these attributes are useful for initializing data that will be used implicitly during the execution of the program. +#define CONSTRUCTOR __attribute__((constructor, used)) +#define DESTRUCTOR __attribute__((destructor, used)) + // An assert-type mechanism. #ifdef PARANOIA #define I_Assert(e) ((e) ? (void)0 : I_Error("assert failed: %s, file %s, line %d", #e, __FILE__, __LINE__)) @@ -588,6 +611,21 @@ extern const char *compdate, *comptime, *comprevision, *compbranch; // None of these that are disabled in the normal build are guaranteed to work perfectly // Compile them at your own risk! +#ifdef PHOBOS_BUILD +// we want 32 players yesss +#undef MAXPLAYERS +#define MAXPLAYERS 32 + +// raise skinlimit to 1024 +#undef MAXSKINS +#define MAXSKINS 1024 + +// overwrite some of those +// when not compiling in vanilla compat mode +#define SATURNJOIN +#define SATURNPAK +#endif + //-- SATURN __ /// Detect if a client is on Saturn in the clientconfig. /// To seperately allow them to join or block joining from vanilla clients. diff --git a/src/doomstat.h b/src/doomstat.h index 80f86b974..86d742183 100644 --- a/src/doomstat.h +++ b/src/doomstat.h @@ -54,7 +54,6 @@ extern INT16 maptol; extern UINT8 globalweather; extern INT32 curWeather; extern INT32 cursaveslot; -extern INT16 lastmapsaved; extern boolean gamecomplete; #define PRECIP_NONE 0 @@ -78,7 +77,6 @@ extern boolean imcontinuing; // Temporary flag while continuing extern UINT8 modeattacking; // menu demo things -extern UINT8 numDemos; extern UINT32 demoDelayTime; extern UINT32 demoIdleTime; @@ -114,8 +112,8 @@ extern UINT8 paused; // Game paused? extern UINT8 window_notinfocus; // are we in focus? (backend independant -- handles auto pausing and display of "focus lost" message) extern boolean nodrawers; -extern boolean noblit; extern boolean lastdraw; +extern boolean intermissionbginit; #ifdef MOTIONBLUR extern INT32 postimgparam[MAXSPLITSCREENPLAYERS]; @@ -205,12 +203,6 @@ extern struct quake fixed_t radius, intensity; } quake; -// NiGHTS grades -typedef struct -{ - UINT32 grade[6]; // D, C, B, A, S, X (F: failed to reach any of these) -} nightsgrades_t; - // Custom Lua values // (This is not ifdeffed so the map header structure can stay identical, just in case.) typedef struct @@ -261,28 +253,16 @@ typedef struct UINT8 numlaps; ///< Number of laps in circuit mode, unless overridden. SINT8 unlockrequired; ///< Is an unlockable required to play this level? -1 if no. UINT8 levelselect; ///< Is this map available in the level select? If so, which map list is it available in? - SINT8 bonustype; ///< What type of bonus does this level have? (-1 for null.) - SINT8 saveoverride; ///< Set how the game is allowed to save (1 for always, -1 for never, 0 is 2.1 default) - UINT8 levelflags; ///< LF_flags: merged eight booleans into one UINT8 for space, see below UINT8 menuflags; ///< LF2_flags: options that affect record attack / nights mode menus - // NiGHTS stuff. - UINT8 numGradedMares; ///< Internal. For grade support. - nightsgrades_t *grades; ///< NiGHTS grades. Allocated dynamically for space reasons. Be careful. - // SRB2kart - //boolean automap; ///< Displays a level's white map outline in modified games fixed_t mobj_scale; ///< Replacement for TOL_ERZ3 mapheader_lighting_t lighting; ///< Wall and sprite lighting mapheader_lighting_t lighting_encore; ///< Alternative lighting for Encore mode boolean use_encore_lighting; ///< Whether to use separate Encore lighting - // Music stuff. - UINT32 musinterfadeout; ///< Fade out level music on intermission screen in milliseconds - char musintername[7]; ///< Intermission screen music. - // Lua stuff. // (This is not ifdeffed so the map header structure can stay identical, just in case.) UINT8 numCustomOptions; ///< Internal. For Lua custom value support. @@ -379,8 +359,6 @@ typedef struct { tic_t time; ///< Time in which the level was finished. tic_t lap; ///< Best lap time for this level. - //UINT32 score; ///< Score when the level was finished. - //UINT16 rings; ///< Rings when the level was finished. } recorddata_t; /** Setup for one NiGHTS map. @@ -394,34 +372,19 @@ typedef struct #define GRADE_A 5 #define GRADE_S 6 -/*typedef struct -{ - // 8 mares, 1 overall (0) - UINT8 nummares; - UINT32 score[9]; - UINT8 grade[9]; - tic_t time[9]; -} nightsdata_t;*/ - -//extern nightsdata_t *nightsrecords[NUMMAPS]; extern recorddata_t *mainrecords[NUMMAPS]; // mapvisited is now a set of flags that says what we've done in the map. #define MV_VISITED 1 #define MV_BEATEN 2 #define MV_ALLEMERALDS 4 -//#define MV_ULTIMATE 8 -//#define MV_PERFECT 16 #define MV_MAX 7 // used in gamedata check extern UINT8 mapvisited[NUMMAPS]; -// Temporary holding place for nights data for the current map -//nightsdata_t ntemprecords; - -extern UINT32 token; ///< Number of tokens collected in a level +extern UINT32 token; ///< Number of tokens collected in a level extern UINT32 tokenlist; ///< List of tokens collected -extern INT32 tokenbits; ///< Used for setting token bits -extern INT32 sstimer; ///< Time allotted in the special stage +extern INT32 tokenbits; ///< Used for setting token bits +extern INT32 sstimer; ///< Time allotted in the special stage extern UINT32 bluescore; ///< Blue Team Scores extern UINT32 redscore; ///< Red Team Scores @@ -437,9 +400,6 @@ extern boolean CheckForReverseGravity; extern UINT16 invulntics; extern UINT16 sneakertics; extern UINT16 flashingtics; -extern UINT16 tailsflytics; -extern UINT16 underwatertics; -extern UINT16 spacetimetics; extern UINT16 extralifetics; // SRB2kart @@ -461,7 +421,6 @@ extern UINT8 introtoplay; extern UINT8 creditscutscene; extern UINT8 use1upSound; -extern UINT8 maxXtraLife; // Max extra lives from rings extern mobj_t *hunt1, *hunt2, *hunt3; // Emerald hunt locations @@ -526,7 +485,6 @@ extern UINT32 timesBeatenWithEmeralds; // WAD, partly set at startup time. extern tic_t gametic; -#define localgametic leveltime // Player spawn spots. extern mapthing_t *playerstarts[MAXPLAYERS]; // Cooperative diff --git a/src/doomtype.h b/src/doomtype.h index ed6248129..2b5319bc2 100644 --- a/src/doomtype.h +++ b/src/doomtype.h @@ -42,6 +42,12 @@ extern "C" { #define INT64 int64_t #define UINT64 uint64_t +#ifdef PHOBOS_BUILD +typedef uint16_t skinnum_t; +#else +typedef uint8_t skinnum_t; +#endif + #ifdef __APPLE_CC__ #define DEBUG_LOG #define NOIPX @@ -68,8 +74,21 @@ extern "C" { #define strnicmp(x,y,n) strncasecmp(x,y,n) #endif -char *nongnu_strcasestr(const char *in, const char *what); +// glibc 2.43 made alot of standard lib functions propagate the constness of its input pointers +// to not cause warnings or compile issues on older glibc versions we do this silly thing +// to not have a gazillion glibc version checks +#if defined(__GLIBC_PREREQ) +#if __GLIBC_PREREQ(2, 43) + #define gconst const +#else + #define gconst +#endif +#else + #define gconst +#endif + #ifndef _GNU_SOURCE +char *nongnu_strcasestr(const char *in, const char *what); #define strcasestr nongnu_strcasestr #endif @@ -127,9 +146,9 @@ size_t strlcpy(char *dst, const char *src, size_t dsize); #define STRBUFCPY(dst,src) strlcpy(dst, src, sizeof dst) /* Boolean type definition */ +#include #ifndef _WIN32 -#include // dont use stdbools _BOOL type // its smaller (1 byte) than the old interger bool (4 bytes) // which results in packed struct sizes being mismatched between vanilla and this @@ -137,9 +156,7 @@ size_t strlcpy(char *dst, const char *src, size_t dsize); // which we cant use as enumeration constants typedef int32_t boolean; #else -#define false FALSE -#define true TRUE -#define boolean BOOL +#define boolean int32_t #endif /* 7.18.2.1 Limits of exact-width integer types */ diff --git a/src/f_finale.c b/src/f_finale.c index 801af8ab5..624b64739 100644 --- a/src/f_finale.c +++ b/src/f_finale.c @@ -1110,14 +1110,6 @@ void F_TitleScreenTicker(boolean run) return; } - // Replay intro when done cycling through demos - /*if (curDemo == numDemos) -- uuuh... we have a LOT of maps AND a big devteam... probably not gonna see a repeat unless you're super unlucky :V - { - curDemo = 0; - F_StartIntro(); - return; - }*/ - mapname = G_BuildMapName(G_RandMap(TOL_RACE, -2, false, 0, false, NULL)+1); numstaff = 1; @@ -1172,9 +1164,7 @@ void F_StartWaitingPlayers(void) randskin = M_RandomKey(numskins); boolean waithires = skins[randskin].flags && SF_HIRES; - if (waitcolormap) - Z_Free(waitcolormap); - + Z_Free(waitcolormap); waitcolormap = R_GetTranslationColormap(randskin, skins[randskin].prefcolor, 0); if (waithires) @@ -1318,7 +1308,7 @@ boolean F_ContinueResponder(event_t *event) keypressed = true; imcontinuing = true; continuetime = TICRATE; - S_StartSound(0, sfx_itemup); + S_StartSound(NULL, sfx_itemup); return true; } diff --git a/src/f_wipe.c b/src/f_wipe.c index 6615cb53c..8abbe3397 100644 --- a/src/f_wipe.c +++ b/src/f_wipe.c @@ -111,7 +111,8 @@ static fademask_t *F_GetFadeMask(UINT8 masknum, UINT8 scrnnum) goto freemask; // SRB2Kart: This suddenly triggers ERRORMODE now - //sprintf(&lumpname[4], "%.2hu%.2hu", (UINT16)masknum, (UINT16)scrnnum); + //snprintf(&lumpname[4], 3, "%.2hu%.2hu", (UINT16)masknum, (UINT16)scrnnum); + //lumpname[8] = 0; lumpname[4] = '0'+(masknum/10); lumpname[5] = '0'+(masknum%10); @@ -361,6 +362,8 @@ void F_RunWipe(UINT8 wipetype, boolean drawMenu) // on for fade-to-black for (;;) { + I_HandleInterrupt(); + // get fademask first so we can tell if it exists or not fmask = F_GetFadeMask(wipetype, wipeframe++); diff --git a/src/fastcmp.h b/src/fastcmp.h index 0f7c24aaa..ea87bee4d 100644 --- a/src/fastcmp.h +++ b/src/fastcmp.h @@ -10,7 +10,7 @@ FUNCINLINE static ATTRINLINE boolean fasticmp(const char *s, const char *c) } // case-sensitive of the above -FUNCINLINE static ATTRINLINE boolean fastcmp(const char *s, const char *c) +FUNCINLINE static ATTRINLINE PUREFUNC boolean fastcmp(const char *s, const char *c) { for (; *s && *s == *c; s++, c++) ; return (*s == *c); // make sure both strings ended @@ -18,7 +18,7 @@ FUNCINLINE static ATTRINLINE boolean fastcmp(const char *s, const char *c) // length-limited of the above // only true if both strings are at least l characters long AND match, case-sensitively! -FUNCINLINE static ATTRINLINE boolean fastncmp(const char *s, const char *c, UINT16 l) +FUNCINLINE static ATTRINLINE PUREFUNC boolean fastncmp(const char *s, const char *c, UINT16 l) { for (; *s && *s == *c && --l; s++, c++) ; return !l; // make sure you reached the end diff --git a/src/filesrch.c b/src/filesrch.c index f7ff612bd..1647e1705 100644 --- a/src/filesrch.c +++ b/src/filesrch.c @@ -49,7 +49,7 @@ size_t menupathindex[menudepth] = {}; size_t menudepthleft = menudepth; char menusearchbuf[MAXSTRINGLENGTH+1]; -textinput_t menusearch; +textinput_t menusearch = {}; char **dirmenu = NULL, **coredirmenu = NULL; // core only local for this file size_t sizedirmenu = 0, sizecoredirmenu = 0; // ditto @@ -111,10 +111,12 @@ filestatus_t filesearch(char *filename, const char *startpath, const UINT8 *want char *searchname; int depthleft = maxsearchdepth; char searchpath[MAXFILEPATH]; - size_t *searchpathindex; + size_t *searchpathindex = NULL; dirhandle = (DIR**)malloc(maxsearchdepth * sizeof(DIR*)); searchpathindex = (size_t *)malloc(maxsearchdepth * sizeof(size_t)); + if (!searchpathindex) + I_Error("out of memory while searching for file %s\n", filename); strcpy(searchpath, startpath); searchpathindex[--depthleft] = strlen(searchpath) + 1; @@ -271,10 +273,13 @@ static boolean filemenucmp(char *haystack, char *needle) { static char localhaystack[128]; strlcpy(localhaystack, haystack, 128); + if (!cv_addons_search_case.value) strupr(localhaystack); + if (cv_addons_search_type.value) - return (strstr(localhaystack, needle) != 0); + return (strstr(localhaystack, needle) != NULL); + return (!strncmp(localhaystack, needle, menusearch.length)); } @@ -314,8 +319,7 @@ void closefilemenu(boolean validsize) coredirmenu = NULL; } - if (refreshdirname) - Z_Free(refreshdirname); + Z_Free(refreshdirname); refreshdirname = NULL; } @@ -343,8 +347,7 @@ void searchfilemenu(char *tempname) if (!menusearch.length) { - if (dirmenu) - Z_Free(dirmenu); + Z_Free(dirmenu); dirmenu = coredirmenu; sizedirmenu = sizecoredirmenu; @@ -386,8 +389,8 @@ void searchfilemenu(char *tempname) I_Error("searchfilemenu(): could not create \"No results...\"."); sizedirmenu = 1; dir_on[menudepthleft] = 0; - if (tempname) - Z_Free(tempname); + Z_Free(tempname); + return; } @@ -502,8 +505,8 @@ boolean preparefilemenu(boolean samedepth, boolean replayhut) { closedir(dirhandle); closefilemenu(false); - if (tempname) - Z_Free(tempname); + Z_Free(tempname); + return false; } diff --git a/src/g_demo.c b/src/g_demo.c index f828d0343..d39bbaec7 100644 --- a/src/g_demo.c +++ b/src/g_demo.c @@ -55,6 +55,8 @@ #include "k_stats.h" // SRB2kart #include "r_fps.h" // frame interpolation/uncapped +#include + #ifdef HAVE_DISCORDRPC #include "discord.h" #endif @@ -64,17 +66,15 @@ #include // menu demo things -UINT8 numDemos = 0; //3; -- i'm FED UP of losing my skincolour to a broken demo. change this back when we make new ones UINT32 demoDelayTime = 15*TICRATE; UINT32 demoIdleTime = 3*TICRATE; boolean nodrawers = false; // for comparative timing purposes -boolean noblit = false; // for comparative timing purposes static tic_t demostarttime; // for comparative timing purposes //@TODO put these all in a struct for namespacing purposes? static char demoname[128]; -savebuffer_t demobuf = {0}; +savebuffer_t demobuf = {}; static UINT8 *demotime_p, *demoinfo_p; static UINT8 *demoend; static UINT8 demoflags; @@ -447,7 +447,8 @@ void G_WriteDemoExtraData(void) { static UINT8 timeout = 0; - if (timeout) timeout--; + if (timeout) + timeout--; if (demo_writerng == 1 || (demo_writerng == 2 && timeout == 0)) { @@ -467,6 +468,7 @@ void G_ReadDemoTiccmd(ticcmd_t *cmd, INT32 playernum) if (!demobuf.p || !demo.deferstart) return; + ziptic = READUINT8(demobuf.p); if (ziptic & ZT_FWD) @@ -488,11 +490,12 @@ void G_ReadDemoTiccmd(ticcmd_t *cmd, INT32 playernum) // what in the actual fuck is this??? // SRB2kart: Copy-pasted from ticcmd building, removes that crappy demo cam - if (((players[displayplayers[0]].mo && players[displayplayers[0]].speed > 0) // Moving + const player_t *player = &players[displayplayers[0]]; + if (((player->mo && player->speed > 0) // Moving || (leveltime > starttime && (cmd->buttons & BT_ACCELERATE && cmd->buttons & BT_BRAKE)) // Rubber-burn turn - || (players[displayplayers[0]].kartstuff[k_respawn]) // Respawning - || (players[displayplayers[0]].spectator || objectplacing)) // Not a physical player - && !(players[displayplayers[0]].kartstuff[k_spinouttimer] && players[displayplayers[0]].kartstuff[k_sneakertimer])) // Spinning and boosting cancels out spinout + || (player->kartstuff[k_respawn]) // Respawning + || (player->spectator || objectplacing)) // Not a physical player + && !(player->kartstuff[k_spinouttimer] && player->kartstuff[k_sneakertimer])) // Spinning and boosting cancels out spinout localangle[0] += (cmd->angleturn<<16); if (!(demoflags & DF_GHOST) && *demobuf.p == DEMOMARKER) @@ -515,49 +518,49 @@ void G_WriteDemoTiccmd(ticcmd_t *cmd, INT32 playernum) if (cmd->forwardmove != oldcmd[playernum].forwardmove) { - WRITEUINT8(demobuf.p,cmd->forwardmove); + WRITEUINT8(demobuf.p, cmd->forwardmove); oldcmd[playernum].forwardmove = cmd->forwardmove; ziptic |= ZT_FWD; } if (cmd->sidemove != oldcmd[playernum].sidemove) { - WRITEUINT8(demobuf.p,cmd->sidemove); + WRITEUINT8(demobuf.p, cmd->sidemove); oldcmd[playernum].sidemove = cmd->sidemove; ziptic |= ZT_SIDE; } if (cmd->angleturn != oldcmd[playernum].angleturn) { - WRITEINT16(demobuf.p,cmd->angleturn); + WRITEINT16(demobuf.p, cmd->angleturn); oldcmd[playernum].angleturn = cmd->angleturn; ziptic |= ZT_ANGLE; } if (cmd->buttons != oldcmd[playernum].buttons) { - WRITEUINT16(demobuf.p,cmd->buttons); + WRITEUINT16(demobuf.p, cmd->buttons); oldcmd[playernum].buttons = cmd->buttons; ziptic |= ZT_BUTTONS; } if (cmd->aiming != oldcmd[playernum].aiming) { - WRITEINT16(demobuf.p,cmd->aiming); + WRITEINT16(demobuf.p, cmd->aiming); oldcmd[playernum].aiming = cmd->aiming; ziptic |= ZT_AIMING; } if (cmd->driftturn != oldcmd[playernum].driftturn) { - WRITEINT16(demobuf.p,cmd->driftturn); + WRITEINT16(demobuf.p, cmd->driftturn); oldcmd[playernum].driftturn = cmd->driftturn; ziptic |= ZT_DRIFT; } if (cmd->latency != oldcmd[playernum].latency) { - WRITEUINT8(demobuf.p,cmd->latency); + WRITEUINT8(demobuf.p, cmd->latency); oldcmd[playernum].latency = cmd->latency; ziptic |= ZT_LATENCY; } @@ -713,7 +716,7 @@ void G_WriteGhostTic(mobj_t *ghost, INT32 playernum) if (!(demoflags & DF_GHOST)) return; // No ghost data to write. - if (ghost->player && ghost->player->pflags & PF_NIGHTSMODE && ghost->tracer) + if (ghost->player && nightsplayer(ghost->player) && ghost->tracer) { // We're talking about the NiGHTS thing, not the normal platforming thing! ziptic |= GZT_NIGHTS; @@ -726,8 +729,8 @@ void G_WriteGhostTic(mobj_t *ghost, INT32 playernum) // GZT_XYZ is only useful if you've moved 256 FRACUNITS or more in a single tic. if (abs(ghost->x-oldghost[playernum].x) > MAXMOM - || abs(ghost->y-oldghost[playernum].y) > MAXMOM - || abs(ghost->z-oldghost[playernum].z) > MAXMOM + || abs(ghost->y-oldghost[playernum].y) > MAXMOM + || abs(ghost->z-oldghost[playernum].z) > MAXMOM || ((UINT8)(leveltime & 255) > 0 && (UINT8)(leveltime & 255) <= (UINT8)cv_netdemosyncquality.value)) // Hack to enable slightly nicer resyncing { oldghost[playernum].x = ghost->x; @@ -931,7 +934,7 @@ void G_ConsAllGhostTics(void) void G_ConsGhostTic(INT32 playernum) { UINT8 ziptic; - fixed_t px,py,pz,gx,gy,gz; + fixed_t px, py, pz, gx, gy, gz; mobj_t *testmo; fixed_t syncleeway; boolean nightsfail = false; @@ -976,7 +979,7 @@ void G_ConsGhostTic(INT32 playernum) if (ziptic & GZT_NIGHTS) { - if (!testmo || !testmo->player || !(testmo->player->pflags & PF_NIGHTSMODE) || !testmo->tracer) + if (!testmo || !testmo->player || !nightsplayer(testmo->player) || !testmo->tracer) nightsfail = true; else testmo = testmo->tracer; @@ -1344,7 +1347,7 @@ fadeghost: } else { - mobj = P_SpawnMobj(g->mo->x, g->mo->y, g->mo->z - FixedDiv(FixedMul(g->mo->info->height, g->mo->scale) - g->mo->height,3*FRACUNIT), MT_THOK); + mobj = P_SpawnMobj(g->mo->x, g->mo->y, g->mo->z - FixedDiv(FixedMul(g->mo->info->height, g->mo->scale) - g->mo->height, 3*FRACUNIT), MT_THOK); mobj->sprite = states[mobjinfo[type].spawnstate].sprite; mobj->frame = (states[mobjinfo[type].spawnstate].frame & FF_FRAMEMASK) | tr_trans60<tics = -1; // nope. @@ -1375,7 +1378,7 @@ fadeghost: UINT16 i, health; UINT16 count = READUINT16(g->p); //UINT32 type; - fixed_t x,y,z; + fixed_t x, y, z; angle_t angle; mobj_t *poof; @@ -1518,7 +1521,9 @@ void G_PreviewRewind(tic_t previewtime) for (i = 0; i < MAXPLAYERS; i++) { - if (!playeringame[i] || players[i].spectator) + player_t *player = &players[i]; + + if (!playeringame[i] || player->spectator) { if (info->playerinfo[i].player.mo) { @@ -1530,35 +1535,35 @@ void G_PreviewRewind(tic_t previewtime) if (!info->playerinfo[i].ingame || !info->playerinfo[i].player.mo) { - if (players[i].mo) - players[i].mo->flags2 |= MF2_DONTDRAW; + if (player->mo) + player->mo->flags2 |= MF2_DONTDRAW; continue; } - if (!players[i].mo) + if (!player->mo) continue; //@TODO spawn temp object to act as a player display - players[i].mo->flags2 &= ~MF2_DONTDRAW; + player->mo->flags2 &= ~MF2_DONTDRAW; - P_UnsetThingPosition(players[i].mo); + P_UnsetThingPosition(player->mo); #define TWEEN(pr) info->playerinfo[i].mobj.pr + FixedMul((INT32) (next_info->playerinfo[i].mobj.pr - info->playerinfo[i].mobj.pr), tweenvalue) - players[i].mo->x = TWEEN(x); - players[i].mo->y = TWEEN(y); - players[i].mo->z = TWEEN(z); - players[i].mo->angle = TWEEN(angle); + player->mo->x = TWEEN(x); + player->mo->y = TWEEN(y); + player->mo->z = TWEEN(z); + player->mo->angle = TWEEN(angle); #undef TWEEN - P_SetThingPosition(players[i].mo); + P_SetThingPosition(player->mo); - players[i].frameangle = info->playerinfo[i].player.frameangle + FixedMul((INT32) (next_info->playerinfo[i].player.frameangle - info->playerinfo[i].player.frameangle), tweenvalue); + player->frameangle = info->playerinfo[i].player.frameangle + FixedMul((INT32) (next_info->playerinfo[i].player.frameangle - info->playerinfo[i].player.frameangle), tweenvalue); - players[i].mo->sprite = info->playerinfo[i].mobj.sprite; - players[i].mo->frame = info->playerinfo[i].mobj.frame; + player->mo->sprite = info->playerinfo[i].mobj.sprite; + player->mo->frame = info->playerinfo[i].mobj.frame; - players[i].realtime = info->playerinfo[i].player.realtime; + player->realtime = info->playerinfo[i].player.realtime; for (j = 0; j < NUMKARTSTUFF; j++) - players[i].kartstuff[j] = info->playerinfo[i].player.kartstuff[j]; + player->kartstuff[j] = info->playerinfo[i].player.kartstuff[j]; } for (i = splitscreen; i >= 0; i--) @@ -1651,10 +1656,12 @@ void G_RecordDemo(const char *name) maxsize = cv_maxdemosize.value*1024*1024; demobuf.buffer = Z_Malloc(maxsize + 100*1024, PU_STATIC, NULL); - demoend = demobuf.buffer + maxsize; if (demobuf.buffer) + { + demoend = demobuf.buffer + maxsize; demo.recording = true; + } else CONS_Alert(CONS_ERROR, "Failed to allocate demo buffer\n"); } @@ -1689,7 +1696,7 @@ void G_BeginRecording(void) return; } - memset(name,0,sizeof(name)); + memset(name, 0, sizeof(name)); demobuf.p = demobuf.buffer; demoflags = DF_GHOST|(multiplayer ? DF_MULTIPLAYER : (modeattacking<important && j > mainwads) - nmusfilecount++; - else - continue; - - if (memcmp(md5sum, wadfiles[j]->md5sum, 16) == 0) - { - alreadyloaded = true; - - if (i != nmusfilecount-1 && error < DFILE_ERROR_OUTOFORDER) - error |= DFILE_ERROR_OUTOFORDER; - - break; - } - } - - if (alreadyloaded) - { - filesloaded++; + if (wadfiles[j]->important && j > mainwads) + nmusfilecount++; + else continue; - } - if (numwadfiles >= MAX_WADFILES) - error = DFILE_ERROR_CANNOTLOAD; - else if (!quick && findfile(filename, md5sum, false) != FS_FOUND) - error = DFILE_ERROR_CANNOTLOAD; - else if (error < DFILE_ERROR_INCOMPLETEOUTOFORDER) - error |= DFILE_ERROR_NOTLOADED; - } else + if (memcmp(md5sum, wadfiles[j]->md5sum, 16) == 0) + { + alreadyloaded = true; + + if (i != nmusfilecount-1 && error < DFILE_ERROR_OUTOFORDER) + error |= DFILE_ERROR_OUTOFORDER; + + break; + } + } + + if (alreadyloaded) + { + filesloaded++; + continue; + } + + if (numwadfiles >= MAX_WADFILES) error = DFILE_ERROR_CANNOTLOAD; + else if (!quick && findfile(filename, md5sum, false) != FS_FOUND) + error = DFILE_ERROR_CANNOTLOAD; + else if (error < DFILE_ERROR_INCOMPLETEOUTOFORDER) + error |= DFILE_ERROR_NOTLOADED; } // Get final file count @@ -2215,7 +2212,7 @@ void G_LoadDemoInfo(menudemo_t *pdemo) { CONS_Alert(CONS_ERROR, M_GetText("Failed to read file '%s'.\n"), pdemo->filepath); pdemo->type = MD_INVALID; - sprintf(pdemo->title, "INVALID REPLAY"); + snprintf(pdemo->title, sizeof(pdemo->title), "INVALID REPLAY"); return; } @@ -2225,7 +2222,7 @@ void G_LoadDemoInfo(menudemo_t *pdemo) { CONS_Alert(CONS_ERROR, M_GetText("%s is not a SRB2Kart replay file.\n"), pdemo->filepath); pdemo->type = MD_INVALID; - sprintf(pdemo->title, "INVALID REPLAY"); + snprintf(pdemo->title, sizeof(pdemo->title), "INVALID REPLAY"); return; } @@ -2250,14 +2247,14 @@ void G_LoadDemoInfo(menudemo_t *pdemo) #ifdef DEMO_COMPAT_100 case 0x0001: pdemo->type = MD_OUTDATED; - sprintf(pdemo->title, "Legacy Replay"); + snprintf(pdemo->title, sizeof(pdemo->title), "Legacy Replay"); break; #endif // too old, cannot support. default: CONS_Alert(CONS_ERROR, M_GetText("%s is an incompatible replay format and cannot be played.\n"), pdemo->filepath); pdemo->type = MD_INVALID; - sprintf(pdemo->title, "INVALID REPLAY"); + snprintf(pdemo->title, sizeof(pdemo->title), "INVALID REPLAY"); return; } @@ -2270,7 +2267,7 @@ void G_LoadDemoInfo(menudemo_t *pdemo) { CONS_Alert(CONS_ERROR, M_GetText("%s is the wrong type of recording and cannot be played.\n"), pdemo->filepath); pdemo->type = MD_INVALID; - sprintf(pdemo->title, "INVALID REPLAY"); + snprintf(pdemo->title, sizeof(pdemo->title), "INVALID REPLAY"); return; } @@ -2291,7 +2288,7 @@ void G_LoadDemoInfo(menudemo_t *pdemo) { CONS_Alert(CONS_ERROR, M_GetText("%s is a legacy multiplayer replay and cannot be played.\n"), pdemo->filepath); pdemo->type = MD_INVALID; - sprintf(pdemo->title, "INVALID REPLAY"); + snprintf(pdemo->title, sizeof(pdemo->title), "INVALID REPLAY"); return; } #endif @@ -2338,7 +2335,7 @@ void G_LoadDemoInfo(menudemo_t *pdemo) while (READUINT8(extrainfo_p) == DW_STANDING) // Assume standings are always first in the extrainfo { INT32 i; - char temp[16]; + char temp[17]; pdemo->standings[count].ranking = READUINT8(extrainfo_p); @@ -2347,7 +2344,8 @@ void G_LoadDemoInfo(menudemo_t *pdemo) extrainfo_p += 16; // Skin - memcpy(temp,extrainfo_p,16); + memcpy(temp, extrainfo_p, 16); + temp[16] = '\0'; extrainfo_p += 16; pdemo->standings[count].skin = UINT8_MAX; @@ -2361,12 +2359,13 @@ void G_LoadDemoInfo(menudemo_t *pdemo) } // Color - memcpy(temp,extrainfo_p,16); + memcpy(temp, extrainfo_p, 16); + temp[16] = '\0'; extrainfo_p += 16; for (i = 0; i < MAXSKINCOLORS; i++) { - if (fasticmp(KartColor_Names[i],temp)) // SRB2kart + if (fasticmp(KartColor_Names[i], temp)) // SRB2kart { pdemo->standings[count].color = i; break; @@ -2401,49 +2400,69 @@ static long G_GetCreationTime(char *filepath) static char *G_GetDemoDate(menudemo_t *pdemo) { - char *datetime; - datetime = malloc(sizeof(pdemo->date)); // mallocma balls - - // no mallocma balls... :c - if (!datetime) - { - return NULL; - } - + char *endPos = NULL; + static char datetime[11]; time_t file_time = 0; + const char *format = NULL; + struct tm *tm_buf = NULL; + CLEANUP(pfree) char *filename = NULL; // get le filepath - char *filename; filename = strdup(pdemo->filepath); -#if defined (_WIN32) if (!filename) { - // if we cant get a filename try just getting the file create time +#if defined (_WIN32) + // if we cant get a filename try just getting the file creation time file_time = G_GetCreationTime(pdemo->filepath); goto skipfilenametime; - } #else - if (!filename) - { - free(datetime); return NULL; - } #endif + } // get the actual filename Zzz... nameonly(filename); - // convert it to long Zzz.... - file_time = strtol(filename, NULL, 10); - free(filename); // dont need this anymore a + // the first 10 characters of a replay name usually is a unix timestamp + + // not long enough to contain a valid timestamp + if (strlen(filename) < 10) + { +#if defined (_WIN32) + // try to get file creation time + file_time = G_GetCreationTime(pdemo->filepath); + goto skipfilenametime; +#else + return NULL; +#endif + } + +#ifndef AVOID_ERRNO + errno = 0; +#endif + // get the timestamp as actual numbers lul + file_time = strtol(filename, &endPos, 10); + + if (endPos == filename // Empty string +#ifndef AVOID_ERRNO + || errno == ERANGE // Number out-of-range +#endif + || file_time < 0) // Number is not positive + { +#if defined (_WIN32) + // just try and get the creation time then + file_time = G_GetCreationTime(pdemo->filepath); +#else + return NULL; +#endif + } #if defined (_WIN32) skipfilenametime: #endif // then throw it into localtime to get an actual human readable format lmao - struct tm *tm_buf = NULL; tm_buf = localtime(&file_time); // cant believe we ended up in 1970 @@ -2456,14 +2475,10 @@ skipfilenametime: tm_buf = localtime(&file_time); if (tm_buf == NULL || tm_buf->tm_year <= 110) - { - free(datetime); return NULL; - } goto gotcreationtime; #else - free(datetime); return NULL; #endif } @@ -2472,17 +2487,27 @@ skipfilenametime: gotcreationtime: #endif - const char *format; - // US ppl are special (: if (cv_demodateformat.value == 2) format = "%m.%d.%Y"; else if (cv_demodateformat.value == 1) format = "%d.%m.%Y"; else - format = strstr(setlocale(LC_TIME, NULL), "en_US") ? "%m.%d.%Y" : "%d.%m.%Y"; + { + const char *locale = setlocale(LC_TIME, NULL); - strftime(datetime, sizeof(pdemo->date), format, tm_buf); + if (locale == NULL) + format = "%d.%m.%Y"; // fallback to non US format + else if (strstr(locale, "en_US")) + format = "%m.%d.%Y"; + else + format = "%d.%m.%Y"; + } + + if (strftime(datetime, sizeof(datetime), format, tm_buf) == 0) + { + return NULL; + } return datetime; } @@ -2491,6 +2516,7 @@ void G_LoadDemoTitle(menudemo_t *pdemo) { UINT8 infobuffer[96], *info_p; UINT16 pdemoversion; + char *demodate = NULL; size_t count; FILE *handle = fopen(pdemo->filepath, "rb"); @@ -2498,7 +2524,7 @@ void G_LoadDemoTitle(menudemo_t *pdemo) if (!handle) { CONS_Alert(CONS_ERROR, M_GetText("Failed to read file '%s'.\n"), pdemo->filepath); - sprintf(pdemo->title, "INVALID REPLAY"); + snprintf(pdemo->title, sizeof(pdemo->title), "INVALID REPLAY"); return; } @@ -2510,7 +2536,7 @@ void G_LoadDemoTitle(menudemo_t *pdemo) if (count < 96 || memcmp(info_p, DEMOHEADER, 12)) { CONS_Alert(CONS_ERROR, M_GetText("%s is not a SRB2Kart replay file.\n"), pdemo->filepath); - sprintf(pdemo->title, "INVALID REPLAY"); + snprintf(pdemo->title, sizeof(pdemo->title), "INVALID REPLAY"); return; } @@ -2529,23 +2555,23 @@ void G_LoadDemoTitle(menudemo_t *pdemo) memcpy(pdemo->title, info_p, 64); // demo date - char *demodate; demodate = G_GetDemoDate(pdemo); if (demodate) - strncpy(pdemo->date, demodate, sizeof(pdemo->date)); + { + strlcpy(pdemo->date, demodate, sizeof(pdemo->date)); + } - free(demodate); break; #ifdef DEMO_COMPAT_100 case 0x0001: - sprintf(pdemo->title, "Legacy Replay"); + snprintf(pdemo->title, sizeof(pdemo->title), "Legacy Replay"); break; #endif // too old, cannot support. default: CONS_Alert(CONS_ERROR, M_GetText("%s is an incompatible replay format and cannot be played.\n"), pdemo->filepath); - sprintf(pdemo->title, "INVALID REPLAY"); + snprintf(pdemo->title, sizeof(pdemo->title), "INVALID REPLAY"); } } @@ -2576,7 +2602,7 @@ void G_DoPlayDemo(char *defdemoname) boolean skiperrors = false; #endif boolean spectator; - UINT8 slots[MAXPLAYERS], kartspeed[MAXPLAYERS], kartweight[MAXPLAYERS], numslots = 0; + UINT8 slots[MAXPLAYERS] = {}, kartspeed[MAXPLAYERS] = {}, kartweight[MAXPLAYERS] = {}, numslots = 0; G_InitDemoRewind(); @@ -2587,7 +2613,7 @@ void G_DoPlayDemo(char *defdemoname) if (defdemoname == NULL) { demobuf.p = demobuf.buffer; - pdemoname = ZZ_Alloc(1); // Easier than adding checks for this everywhere it's freed + pdemoname = ZZ_Calloc(1); // Easier than adding checks for this everywhere it's freed } else { @@ -2599,7 +2625,7 @@ void G_DoPlayDemo(char *defdemoname) n++; pdemoname = ZZ_Alloc(strlen(n)+1); - strcpy(pdemoname,n); + strcpy(pdemoname, n); M_SetPlaybackMenuPointer(); @@ -2609,7 +2635,7 @@ void G_DoPlayDemo(char *defdemoname) //FIL_DefaultExtension(defdemoname, ".lmp"); if (!FIL_ReadFile(defdemoname, &demobuf.buffer)) { - snprintf(msg, 1024, M_GetText("Failed to read file '%s'.\n"), defdemoname); + snprintf(msg, sizeof(msg), M_GetText("Failed to read file '%s'.\n"), defdemoname); CONS_Alert(CONS_ERROR, "%s", msg); gameaction = ga_nothing; M_StartMessage(msg, M_ReturnToTitleFromError, MM_EVENTHANDLER); @@ -2621,7 +2647,7 @@ void G_DoPlayDemo(char *defdemoname) // load demo resource from WAD else if ((l = W_CheckNumForName(defdemoname)) == LUMPERROR) { - snprintf(msg, 1024, M_GetText("Failed to read lump '%s'.\n"), defdemoname); + snprintf(msg, sizeof(msg), M_GetText("Failed to read lump '%s'.\n"), defdemoname); CONS_Alert(CONS_ERROR, "%s", msg); gameaction = ga_nothing; M_StartMessage(msg, M_ReturnToTitleFromError, MM_EVENTHANDLER); @@ -2642,7 +2668,7 @@ void G_DoPlayDemo(char *defdemoname) if (memcmp(demobuf.p, DEMOHEADER, 12)) { - snprintf(msg, 1024, M_GetText("%s is not a SRB2Kart replay file.\n"), pdemoname); + snprintf(msg, sizeof(msg), M_GetText("%s is not a SRB2Kart replay file.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, M_ReturnToTitleFromError, MM_EVENTHANDLER); G_ResetDemoPlayback(); @@ -2668,7 +2694,7 @@ void G_DoPlayDemo(char *defdemoname) #endif // too old, cannot support. default: - snprintf(msg, 1024, M_GetText("%s is an incompatible replay format and cannot be played.\n"), pdemoname); + snprintf(msg, sizeof(msg), M_GetText("%s is an incompatible replay format and cannot be played.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, M_ReturnToTitleFromError, MM_EVENTHANDLER); G_ResetDemoPlayback(); @@ -2679,7 +2705,7 @@ void G_DoPlayDemo(char *defdemoname) if (memcmp(demobuf.p, "PLAY", 4)) { - snprintf(msg, 1024, M_GetText("%s is the wrong type of recording and cannot be played.\n"), pdemoname); + snprintf(msg, sizeof(msg), M_GetText("%s is the wrong type of recording and cannot be played.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, M_ReturnToTitleFromError, MM_EVENTHANDLER); G_ResetDemoPlayback(); @@ -2696,7 +2722,7 @@ void G_DoPlayDemo(char *defdemoname) { if (demoflags & DF_MULTIPLAYER) { - snprintf(msg, 1024, M_GetText("%s is an alpha multiplayer replay and cannot be played.\n"), pdemoname); + snprintf(msg, sizeof(msg), M_GetText("%s is an alpha multiplayer replay and cannot be played.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, M_ReturnToTitleFromError, MM_EVENTHANDLER); G_ResetDemoPlayback(); @@ -2723,31 +2749,31 @@ void G_DoPlayDemo(char *defdemoname) switch (error) { case DFILE_ERROR_NOTLOADED: - snprintf(msg, 1024, + snprintf(msg, sizeof(msg), "Required files for this demo are not loaded.\n\nUse\n\"playdemo %s -addfiles\"\nto load them and play the demo.\n", pdemoname); break; case DFILE_ERROR_OUTOFORDER: - snprintf(msg, 1024, + snprintf(msg, sizeof(msg), "Required files for this demo are loaded out of order.\n\nUse\n\"playdemo %s -force\"\nto play the demo anyway.\n", pdemoname); break; case DFILE_ERROR_INCOMPLETEOUTOFORDER: - snprintf(msg, 1024, + snprintf(msg, sizeof(msg), "Required files for this demo are not loaded, and some are out of order.\n\nUse\n\"playdemo %s -addfiles\"\nto load needed files and play the demo.\n", pdemoname); break; case DFILE_ERROR_CANNOTLOAD: - snprintf(msg, 1024, + snprintf(msg, sizeof(msg), "Required files for this demo cannot be loaded.\n\nUse\n\"playdemo %s -force\"\nto play the demo anyway.\n", pdemoname); break; case DFILE_ERROR_EXTRAFILES: - snprintf(msg, 1024, + snprintf(msg, sizeof(msg), "You have additional files loaded beyond the demo's file list.\n\nUse\n\"playdemo %s -force\"\nto play the demo anyway.\n", pdemoname); break; @@ -2795,9 +2821,9 @@ void G_DoPlayDemo(char *defdemoname) demobuf.p += 4; // Extrainfo location // ...*map* not loaded? - if (!gamemap || (gamemap > NUMMAPS) || !mapheaderinfo[gamemap-1] || !(mapheaderinfo[gamemap-1]->menuflags & LF2_EXISTSHACK)) + if (!gamemap || (gamemap > NUMMAPS) || (W_CheckNumForName(G_BuildMapName(gamemap)) == LUMPERROR)) { - snprintf(msg, 1024, M_GetText("%s features a course that is not currently loaded.\n"), pdemoname); + snprintf(msg, sizeof(msg), M_GetText("%s features a course that is not currently loaded.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, M_ReturnToTitleFromError, MM_EVENTHANDLER); G_ResetDemoPlayback(); @@ -2808,15 +2834,15 @@ void G_DoPlayDemo(char *defdemoname) if (demo.version == 0x0001) { // Player name - memcpy(player_names[0],demobuf.p,16); + memcpy(player_names[0], demobuf.p, 16); demobuf.p += 16; // Skin - memcpy(skin,demobuf.p,16); + memcpy(skin, demobuf.p, 16); demobuf.p += 16; // Color - memcpy(color,demobuf.p,16); + memcpy(color, demobuf.p, 16); demobuf.p += 16; demobuf.p += 5; // Backwards compat - some stats @@ -2829,7 +2855,17 @@ void G_DoPlayDemo(char *defdemoname) // Skin not loaded? if (!SetPlayerSkin(0, skin)) { - snprintf(msg, 1024, M_GetText("%s features a character that is not currently loaded.\n"), pdemoname); + snprintf(msg, sizeof(msg), M_GetText("%s features a character that is not currently loaded.\n"), pdemoname); + CONS_Alert(CONS_ERROR, "%s", msg); + M_StartMessage(msg, M_ReturnToTitleFromError, MM_EVENTHANDLER); + G_ResetDemoPlayback(); + return; + } + + // ...*map* not loaded? + if (!gamemap || (gamemap > NUMMAPS) || !mapheaderinfo[gamemap-1] || !(mapheaderinfo[gamemap-1]->menuflags & LF2_EXISTSHACK)) + { + snprintf(msg, sizeof(msg), M_GetText("%s features a course that is not currently loaded.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, M_ReturnToTitleFromError, MM_EVENTHANDLER); G_ResetDemoPlayback(); @@ -2839,7 +2875,7 @@ void G_DoPlayDemo(char *defdemoname) // Set color for (i = 0; i < MAXSKINCOLORS; i++) { - if (fasticmp(KartColor_Names[i],color)) // SRB2kart + if (fasticmp(KartColor_Names[i], color)) // SRB2kart { players[0].skincolor = i; break; @@ -2852,16 +2888,16 @@ void G_DoPlayDemo(char *defdemoname) // Sigh ... it's an empty demo. if (*demobuf.p == DEMOMARKER) { - snprintf(msg, 1024, M_GetText("%s contains no data to be played.\n"), pdemoname); + snprintf(msg, sizeof(msg), M_GetText("%s contains no data to be played.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, M_ReturnToTitleFromError, MM_EVENTHANDLER); G_ResetDemoPlayback(); return; } - memset(&oldcmd,0,sizeof(oldcmd)); - memset(&oldghost,0,sizeof(oldghost)); - memset(&ghostext,0,sizeof(ghostext)); + memset(&oldcmd, 0, sizeof(oldcmd)); + memset(&oldghost, 0, sizeof(oldghost)); + memset(&ghostext, 0, sizeof(ghostext)); CONS_Alert(CONS_WARNING, M_GetText("Demo version does not match game version. Desyncs may occur.\n")); @@ -2890,7 +2926,7 @@ void G_DoPlayDemo(char *defdemoname) // Sigh ... it's an empty demo. if (*demobuf.p == DEMOMARKER) { - snprintf(msg, 1024, M_GetText("%s contains no data to be played.\n"), pdemoname); + snprintf(msg, sizeof(msg), M_GetText("%s contains no data to be played.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, M_ReturnToTitleFromError, MM_EVENTHANDLER); G_ResetDemoPlayback(); @@ -2939,7 +2975,7 @@ void G_DoPlayDemo(char *defdemoname) if (modeattacking) { - snprintf(msg, 1024, M_GetText("%s is a Record Attack replay with spectators, and is thus invalid.\n"), pdemoname); + snprintf(msg, sizeof(msg), M_GetText("%s is a Record Attack replay with spectators, and is thus invalid.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, M_ReturnToTitleFromError, MM_EVENTHANDLER); G_ResetDemoPlayback(); @@ -2951,7 +2987,7 @@ void G_DoPlayDemo(char *defdemoname) if (modeattacking && numslots > 1) { - snprintf(msg, 1024, M_GetText("%s is a Record Attack replay with multiple players, and is thus invalid.\n"), pdemoname); + snprintf(msg, sizeof(msg), M_GetText("%s is a Record Attack replay with multiple players, and is thus invalid.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, M_ReturnToTitleFromError, MM_EVENTHANDLER); G_ResetDemoPlayback(); @@ -2965,16 +3001,16 @@ void G_DoPlayDemo(char *defdemoname) players[p].spectator = spectator; // Name - memcpy(player_names[p],demobuf.p,16); + memcpy(player_names[p], demobuf.p, 16); demobuf.p += 16; // Skin - memcpy(skin,demobuf.p,16); + memcpy(skin, demobuf.p, 16); demobuf.p += 16; SetPlayerSkin(p, skin); // Color - memcpy(color,demobuf.p,16); + memcpy(color, demobuf.p, 16); demobuf.p += 16; for (i = 0; i < MAXSKINCOLORS; i++) @@ -3051,6 +3087,9 @@ post_compat: if (cv_director.value) CV_SetValue(&cv_director, 0); + if (demo.timing) + G_DoneLevelLoad(); + demo.deferstart = true; } #undef SKIPERRORS @@ -3189,15 +3228,15 @@ void G_AddGhost(char *defdemoname) if (ghostversion == 0x0001) { // Player name (TODO: Display this somehow if it doesn't match cv_playername!) - memcpy(name, p,16); + memcpy(name, p, 16); p += 16; // Skin - memcpy(skin, p,16); + memcpy(skin, p, 16); p += 16; // Color - memcpy(color, p,16); + memcpy(color, p, 16); p += 16; // Ghosts do not have a player structure to put this in. @@ -3349,7 +3388,7 @@ void G_AddGhost(char *defdemoname) for (i = 0; i < MAXSKINCOLORS; i++) { - if (fasticmp(KartColor_Names[i],color)) // SRB2kart + if (fasticmp(KartColor_Names[i], color)) // SRB2kart { gh->mo->color = (UINT8)i; break; @@ -3441,7 +3480,7 @@ void G_UpdateStaffGhostName(lumpnum_t l) if (ghostversion == 0x0001) { // Player name - memcpy(dummystaffname, p,16); + memcpy(dummystaffname, p, 16); dummystaffname[16] = '\0'; return; // Not really a failure but whatever } @@ -3478,10 +3517,11 @@ static INT32 restorecv_vidwait; void G_TimeDemo(const char *name) { nodrawers = M_CheckParm("-nodraw"); - noblit = M_CheckParm("-noblit"); + restorecv_vidwait = cv_vidwait.value; if (cv_vidwait.value) CV_Set(&cv_vidwait, "0"); + demo.timing = true; singletics = true; framecount = 0; diff --git a/src/g_demo.h b/src/g_demo.h index 5e430a2e8..280185ce6 100644 --- a/src/g_demo.h +++ b/src/g_demo.h @@ -82,7 +82,8 @@ typedef struct menudemo_s { struct { UINT8 ranking; char name[17]; - UINT8 skin, color; + skinnum_t skin; + UINT8 color; UINT32 timeorscore; } standings[MAXPLAYERS]; } menudemo_t; diff --git a/src/g_game.c b/src/g_game.c index b76c1290a..b8c9a2530 100644 --- a/src/g_game.c +++ b/src/g_game.c @@ -61,17 +61,11 @@ gameaction_t gameaction = 0; gamestate_t gamestate = GS_NULL; -UINT8 ultimatemode = false; boolean botingame = false; -UINT8 botskin = 0; +skinnum_t botskin = 0; UINT8 botcolor = 0; -JoyType_t Joystick[MAXSPLITSCREENPLAYERS] = {}; - -// 1024 bytes is plenty for a savegame -#define SAVEGAMESIZE (1024) - // SRB2kart char gamedatafilename[64] = "kartdata.dat"; char timeattackfolder[64] = "kart"; @@ -90,7 +84,6 @@ INT16 maptol = 0; UINT8 globalweather = 0; INT32 curWeather = PRECIP_NONE; INT32 cursaveslot = -1; // Auto-save 1p savegame slot -INT16 lastmapsaved = 0; // Last map we auto-saved at boolean gamecomplete = false; UINT16 mainwads = 0; @@ -100,7 +93,6 @@ boolean savemoddata = false; UINT8 paused = 0; UINT8 modeattacking = ATTACKING_NONE; boolean imcontinuing = false; -boolean runemeraldmanager = false; boolean netgame = false; // only true if packets are broadcast boolean multiplayer = false; @@ -112,7 +104,6 @@ INT32 consoleplayer = 0; // player taking events and displaying INT32 displayplayers[MAXSPLITSCREENPLAYERS] = {}; // view being displayed tic_t gametic = 0; -tic_t levelstarttic = 0; // gametic at level start UINT32 totalrings = 0; // for intermission INT16 lastmap = 0; // last level you were at (returning from special stages) tic_t timeinmap = 0; // Ticker for time spent in level (used for levelcard display) @@ -132,7 +123,7 @@ UINT8 skincolor_bluering = SKINCOLOR_STEEL; tic_t countdowntimer = 0; boolean countdowntimeup = false; -cutscene_t *cutscenes[128]; +cutscene_t *cutscenes[128] = {}; INT16 nextmapoverride = 0; boolean skipstats = false; @@ -144,7 +135,7 @@ mobj_t *blueflag = NULL; mapthing_t *rflagpoint = NULL; mapthing_t *bflagpoint = NULL; -struct quake quake; +struct quake quake = {}; // Map Header Information mapheader_t* mapheaderinfo[NUMMAPS] = {}; @@ -190,9 +181,6 @@ boolean CheckForReverseGravity = false; UINT16 invulntics = 20*TICRATE; UINT16 sneakertics = 20*TICRATE; UINT16 flashingtics = 3*TICRATE/2; // SRB2kart -UINT16 tailsflytics = 8*TICRATE; -UINT16 underwatertics = 30*TICRATE; -UINT16 spacetimetics = 11*TICRATE + (TICRATE/2); UINT16 extralifetics = 4*TICRATE; // SRB2kart @@ -210,10 +198,7 @@ const INT32 wipeoutslowtime = 20; const INT32 wantedreduce = 5*TICRATE; const INT32 wantedfrequency = 10*TICRATE; -INT32 gameovertics = 15*TICRATE; - UINT8 use1upSound = 0; -UINT8 maxXtraLife = 2; // Max extra lives from rings UINT8 introtoplay = 0; UINT8 creditscutscene = 0; @@ -228,7 +213,7 @@ tic_t racecountdown = 0, exitcountdown = 0; // for racing fixed_t gravity = 0; fixed_t mapobjectscale = FRACUNIT; -struct maplighting maplighting; +struct maplighting maplighting = {}; INT16 autobalance = 0; //for CTF team balance INT16 teamscramble = 0; //for CTF team scramble @@ -454,40 +439,27 @@ consvar_t cv_litesteer[MAXSPLITSCREENPLAYERS] = { {"litesteer4", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL} }; +//static CV_PossibleValue_t autoaccelcons_t[] = {{0, "Off"}, {1, "Manual"}, {2, "Automatic"}, {0, NULL}}; +consvar_t cv_autoaccel[MAXSPLITSCREENPLAYERS] = { + {"kartautoaccel", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"kartautoaccel2", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"kartautoaccel3", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"kartautoaccel4", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL} +}; + static CV_PossibleValue_t driftsparkpulse_t[] = {{0, "MIN"}, {FRACUNIT*3, "MAX"}, {0, NULL}}; consvar_t cv_driftsparkpulse = {"driftsparkpulse", "1.4", CV_FLOAT | CV_SAVE, driftsparkpulse_t, NULL, 0, NULL, NULL, 0, 0, NULL}; static CV_PossibleValue_t cechotoggle_t[] = {{0, "Off"}, {1, "On"}, {2, "Console"}, {0, NULL}}; consvar_t cv_cechotoggle = {"show_cecho", "On", CV_SAVE, cechotoggle_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -#if MAXPLAYERS > 16 -#error "please update player_name table using the new value for MAXPLAYERS" -#endif - #ifdef SEENAMES player_t *seenplayer = NULL; // player we're aiming at right now #endif -char player_names[MAXPLAYERS][MAXPLAYERNAME+1] = -{ - "Player 1", - "Player 2", - "Player 3", - "Player 4", - "Player 5", - "Player 6", - "Player 7", - "Player 8", - "Player 9", - "Player 10", - "Player 11", - "Player 12", - "Player 13", - "Player 14", - "Player 15", - "Player 16" -}; // SRB2kart - removed Players 17 through 32 - +// now automatically allocated in D_RegisterServerCommands +// so that it doesn't have to be updated depending on the value of MAXPLAYERS +char player_names[MAXPLAYERS][MAXPLAYERNAME+1]; INT32 player_name_changes[MAXPLAYERS] = {}; INT16 rw_maximums[NUM_WEAPONS] = @@ -515,11 +487,8 @@ void G_ClearRecords(void) INT16 i; for (i = 0; i < NUMMAPS; ++i) { - if (mainrecords[i]) - { - Z_Free(mainrecords[i]); - mainrecords[i] = NULL; - } + Z_Free(mainrecords[i]); + mainrecords[i] = NULL; } } @@ -635,14 +604,18 @@ const char *G_BuildMapName(INT32 map) } if (map < 100 && map >= 0) // ...but why use signed integer in first place? idk but this prevents warning (and potential buffer overflow lol) - sprintf(&mapname[3], "%.2d", map); + { + snprintf(&mapname[3], sizeof(mapname)-3, "%.2d", map); + } else { mapname[3] = (char)('A' + (char)((map - 100) / 36)); + if ((map - 100) % 36 < 10) mapname[4] = (char)('0' + (char)((map - 100) % 36)); else mapname[4] = (char)('A' + (char)((map - 100) % 36) - 10); + mapname[5] = '\0'; } @@ -763,7 +736,7 @@ INT32 JoyAxis(axis_input_e axissel, UINT8 player) if (retaxis > (+JOYAXISRANGE)) retaxis = +JOYAXISRANGE; - if (!Joystick[pnum].bGamepadStyle && axissel < AXISDEAD) + if (!DigitalGamepadStyle(pnum) && axissel < AXISDEAD) { const INT32 jdeadzone = ((JOYAXISRANGE-1) * deadzone) >> FRACBITS; @@ -800,6 +773,10 @@ static fixed_t forwardmove[2] = {25<>16, 50<>16}; static fixed_t sidemove[2] = {2<>16, 4<>16}; static fixed_t angleturn[3] = {KART_FULLTURN/2, KART_FULLTURN, KART_FULLTURN/4}; // + slow turn +// +// G_HandleLocalDriftturn +// Hack for Lua menus that check directional inputs with driftturn +// static void G_HandleLocalDriftturn(ticcmd_t *cmd, UINT8 ssplayer) { INT32 axis = 0; @@ -807,8 +784,8 @@ static void G_HandleLocalDriftturn(ticcmd_t *cmd, UINT8 ssplayer) const UINT8 forplayer = (ssplayer-1); - const boolean analogjoystickmove = cv_usejoystick[forplayer].value && !Joystick[forplayer].bGamepadStyle; - const boolean gamepadjoystickmove = cv_usejoystick[forplayer].value && Joystick[forplayer].bGamepadStyle; + const boolean analogjoystickmove = cv_usejoystick[forplayer].value && !DigitalGamepadStyle(forplayer); + const boolean gamepadjoystickmove = cv_usejoystick[forplayer].value && DigitalGamepadStyle(forplayer); turnright = InputDown(gc_turnright, ssplayer); turnleft = InputDown(gc_turnleft, ssplayer); @@ -862,9 +839,9 @@ static void G_HandleLocalDriftturn(ticcmd_t *cmd, UINT8 ssplayer) // static void G_BuildLocalTiccmd(ticcmd_t *cmd, UINT8 ssplayer, boolean freecam) { - boolean moveinput = false; INT32 axis = 0; - const boolean usejoystick = (cv_usejoystick[(ssplayer-1)].value); + const UINT8 forplayer = (ssplayer-1); + const boolean usejoystick = cv_usejoystick[forplayer].value; // check for inputs and return button commands // for stuff like joining with item button, saltyhop, honking, etc. @@ -899,15 +876,11 @@ static void G_BuildLocalTiccmd(ticcmd_t *cmd, UINT8 ssplayer, boolean freecam) #undef CHECKINPUT - moveinput = (InputDown(gc_turnleft, ssplayer) || InputDown(gc_turnright, ssplayer) - || InputDown(gc_aimforward, ssplayer) || InputDown(gc_aimbackward, ssplayer) || - (usejoystick && JoyAxis(AXISAIM, ssplayer) != 0) || (usejoystick && JoyAxis(AXISTURN, ssplayer) != 0)); - axis = JoyAxis(AXISLOOKBACK, ssplayer); - camspin[ssplayer-1] = (InputDown(gc_lookback, ssplayer) || (usejoystick && axis > 0)); + camspin[forplayer] = (InputDown(gc_lookback, ssplayer) || (usejoystick && axis > 0)); // Reset to our spec player if we watch someone else. - if ((moveinput || cmd->buttons) + if ((cmd->driftturn || cmd->buttons) && displayplayers[0] != consoleplayer && ssplayer == 1) { if (cv_director.value) @@ -919,6 +892,63 @@ static void G_BuildLocalTiccmd(ticcmd_t *cmd, UINT8 ssplayer, boolean freecam) } } +// +// G_HandleAutoAcceleration +// +static void G_HandleAutoAcceleration(ticcmd_t *cmd, player_t *player, UINT8 forplayer) +{ + if (!cv_autoaccel[forplayer].value) + return; + + if (gamestate != GS_LEVEL) + return; + + // dont accel before and during countdown + if (leveltime <= starttime) + return; + + // dont do this in menus or when console is onscreen + if (menuactive || CON_Ready()) + return; + + // gotta have a player that aint respawning + if (!player->mo || player->kartstuff[k_respawn]) + return; + + // dont need for "finished" players + if (player->exiting || (player->pflags & PF_TIMEOVER)) + return; + + // dont do during spinout + if (player->kartstuff[k_spinouttimer]) + return; + + // spectators and freecam dont need special handling, see G_BuildTiccmd + + if (cmd->buttons & BT_BRAKE) + { + if (cmd->buttons & BT_DRIFT || + player->kartstuff[k_sneakertimer] || + player->kartstuff[k_squishedtimer]) + { + cmd->forwardmove = (SINT8)forwardmove[0]; + cmd->buttons |= BT_ACCELERATE; + } + else + { + // allows us to drive backwards if we need to + if (cmd->forwardmove > 0) + cmd->forwardmove = 0; + cmd->buttons &= ~BT_ACCELERATE; + } + } + else + { + cmd->forwardmove = (SINT8)forwardmove[1]; + cmd->buttons |= BT_ACCELERATE; + } +} + // // G_BuildTiccmd // Builds a ticcmd from all of the available inputs @@ -944,10 +974,7 @@ void G_BuildTiccmd(ticcmd_t *cmd, INT32 realtics, UINT8 ssplayer) player_t *player = P_GetLocalPlayerForNum(forplayer); camera_t *thiscam = &camera[forplayer]; - const boolean freecam = camera[forplayer].freecam; - - const boolean analogjoystickmove = cv_usejoystick[forplayer].value && !Joystick[forplayer].bGamepadStyle; - const boolean gamepadjoystickmove = cv_usejoystick[forplayer].value && Joystick[forplayer].bGamepadStyle; + const boolean freecam = thiscam->freecam; lang = localangle[forplayer]; laim = localaiming[forplayer]; @@ -979,6 +1006,9 @@ void G_BuildTiccmd(ticcmd_t *cmd, INT32 realtics, UINT8 ssplayer) return; } + const boolean analogjoystickmove = cv_usejoystick[forplayer].value && !DigitalGamepadStyle(forplayer); + const boolean gamepadjoystickmove = cv_usejoystick[forplayer].value && DigitalGamepadStyle(forplayer); + usejoystick = (analogjoystickmove || gamepadjoystickmove); turnright = InputDown(gc_turnright, ssplayer); turnleft = InputDown(gc_turnleft, ssplayer); @@ -1066,7 +1096,7 @@ void G_BuildTiccmd(ticcmd_t *cmd, INT32 realtics, UINT8 ssplayer) if (InputDown(gc_accelerate, ssplayer) || (gamepadjoystickmove && axis > 0) || player->kartstuff[k_sneakertimer]) { cmd->buttons |= BT_ACCELERATE; - forward = forwardmove[1]; // 50 + forward = forwardmove[1]; // 50 } else if (analogjoystickmove && axis > 0) { @@ -1147,6 +1177,8 @@ void G_BuildTiccmd(ticcmd_t *cmd, INT32 realtics, UINT8 ssplayer) cmd->sidemove = (SINT8)(cmd->sidemove + side); } + G_HandleAutoAcceleration(cmd, player, forplayer); + //{ SRB2kart - Drift support // Not grouped with the rest of turn stuff because it needs to know what buttons you're pressing for rubber-burn turn // limit turning to angleturn[1] to stop mouselook letting you look too fast @@ -1240,8 +1272,6 @@ static void G_DoLoadLevel(boolean resetplayer) // Make sure objectplace is OFF when you first start the level! OP_ResetObjectplace(); - levelstarttic = gametic; // for time calculation - if (wipegamestate == GS_LEVEL) wipegamestate = -1; // force a wipe @@ -1263,6 +1293,7 @@ static void G_DoLoadLevel(boolean resetplayer) { // fail so reset game stuff Command_ExitGame_f(); + P_FreeCorruptMapWarnings(); return; } @@ -1296,6 +1327,8 @@ static void G_DoLoadLevel(boolean resetplayer) // clear hud messages remains (usually from game startup) CON_ClearHUD(); + // print any map errors now due to clearhud above :chaosleep: + P_PrintCorruptMapWarnings(); server_lagless = !cv_gentlemens.value; @@ -2597,12 +2630,18 @@ mapthing_t *G_FindRaceStart(INT32 playernum) // Just spawn there. //return playerstarts[0]; +#if MAXPLAYERS > 16 + //this section courtesy of fickle - v1.1 battle royale + // screw collision chex + return playerstarts[pos % numcoopstarts]; +#else if (P_IsLocalPlayerNum(playernum)) { CONS_Alert(CONS_WARNING, "Could not spawn at any Race starts!\n"); } return NULL; +#endif } if (P_IsLocalPlayerNum(playernum)) @@ -3295,18 +3334,6 @@ static void G_DoStartVote(void) gameaction = ga_nothing; } -// -// G_UseContinue -// -void G_UseContinue(void) -{ - if (gamestate == GS_LEVEL && !netgame && !multiplayer) - { - gameaction = ga_startcont; - lastdraw = true; - } -} - static void G_DoStartContinue(void) { I_Assert(!netgame && !multiplayer); @@ -3345,7 +3372,7 @@ static void G_DoContinued(void) token = 0; // Reset # of lives - pl->lives = (ultimatemode) ? 1 : 3; + pl->lives = 3; D_MapChange(gamemap, gametype, false, false, 0, false, false); @@ -3435,7 +3462,7 @@ void G_LoadGameData(void) INT32 i, j; UINT8 modded = false; UINT8 rtemp; - savebuffer_t save = {0}; + savebuffer_t save = {}; //For records tic_t rectime; @@ -3568,7 +3595,7 @@ void G_SaveGameData(boolean force) size_t length; INT32 i, j; UINT8 btemp; - savebuffer_t save = {0}; + savebuffer_t save = {}; (void)force; char backupfile[MAX_WADPATH+4]; @@ -3739,7 +3766,7 @@ void G_LoadGame(UINT32 slot, INT16 mapoverride) size_t length; char vcheck[VERSIONSIZE]; char savename[255]; - savebuffer_t save = {0}; + savebuffer_t save = {}; // memset savedata to all 0, fixes calling perfectly valid saves corrupt because of bots memset(&savedata, 0, sizeof(savedata)); @@ -3749,7 +3776,7 @@ void G_LoadGame(UINT32 slot, INT16 mapoverride) startonmapnum = mapoverride; #endif - sprintf(savename, savegamename, slot); + snprintf(savename, sizeof(savename), savegamename, slot); length = FIL_ReadFile(savename, &save.buffer); if (!length) @@ -3761,7 +3788,7 @@ void G_LoadGame(UINT32 slot, INT16 mapoverride) save.p = save.buffer; memset(vcheck, 0, sizeof (vcheck)); - sprintf(vcheck, "version %d", VERSION); + snprintf(vcheck, sizeof(vcheck), "version %d", VERSION); if (!fastcmp((const char *)save.p, (const char *)vcheck)) { @@ -3825,10 +3852,10 @@ void G_SaveGame(UINT32 savegameslot) boolean saved; char savename[256] = ""; const char *backup; - savebuffer_t save = {0}; + savebuffer_t save = {}; - sprintf(savename, savegamename, savegameslot); - backup = va("%s",savename); + snprintf(savename, sizeof(savename), savegamename, savegameslot); + backup = va("%s", savename); // save during evaluation or credits? game's over, folks! if (gamestate == GS_CREDITS || gamestate == GS_EVALUATION) @@ -3839,15 +3866,15 @@ void G_SaveGame(UINT32 savegameslot) char name[VERSIONSIZE]; size_t length; - save.p = save.buffer = (UINT8 *)Z_Malloc(SAVEGAMESIZE, PU_STATIC, NULL); + save.p = save.buffer = (UINT8 *)Z_Malloc(1024, PU_STATIC, NULL); // 1024 bytes is plenty for a savegame if (!save.p) { CONS_Alert(CONS_ERROR, M_GetText("No more free memory for saving game data\n")); return; } - memset(name, 0, sizeof (name)); - sprintf(name, "version %d", VERSION); + memset(name, 0, sizeof(name)); + snprintf(name, sizeof(name), "version %d", VERSION); WRITEMEM(save.p, name, VERSIONSIZE); P_SaveGame(&save); @@ -3989,7 +4016,6 @@ void G_InitNew(UINT8 pencoremode, const char *mapname, boolean resetplayer, bool if (W_CheckNumForName(mapname) == LUMPERROR) { I_Error("Internal game map '%s' not found\n", mapname); - Command_ExitGame_f(); return; } @@ -4054,6 +4080,7 @@ char *G_BuildMapTitle(INT32 mapnum) const char *actnum = NULL; len += strlen(mapheaderinfo[mapnum-1]->lvlttl); + if (strlen(mapheaderinfo[mapnum-1]->zonttl) > 0) { zonetext = M_GetText(mapheaderinfo[mapnum-1]->zonttl); @@ -4064,6 +4091,7 @@ char *G_BuildMapTitle(INT32 mapnum) zonetext = M_GetText("Zone"); len += strlen(zonetext) + 1; // ' ' + zonetext } + if (strlen(mapheaderinfo[mapnum-1]->actnum) > 0) { actnum = M_GetText(mapheaderinfo[mapnum-1]->actnum); @@ -4075,10 +4103,12 @@ char *G_BuildMapTitle(INT32 mapnum) if (!title) return NULL; - sprintf(title, "%s", mapheaderinfo[mapnum-1]->lvlttl); + snprintf(title, len, "%s", mapheaderinfo[mapnum-1]->lvlttl); - if (zonetext) sprintf(title + strlen(title), " %s", zonetext); - if (actnum) sprintf(title + strlen(title), " %s", actnum); + if (zonetext) + snprintf(title + strlen(title), len - strlen(title), " %s", zonetext); + if (actnum) + snprintf(title + strlen(title), len - strlen(title), " %s", actnum); } return title; @@ -4090,12 +4120,13 @@ static void measurekeywords(mapsearchfreq_t *fr, { char *qp; char *sp; + if (wanttable) (*dimp) = Z_Realloc((*dimp), 255 * sizeof (struct searchdim), PU_STATIC, NULL); for (qp = strtok(va("%s", q), " "); qp && fr->total < 255; - qp = strtok(0, " ")) + qp = strtok(NULL, " ")) { if (( sp = strcasestr(s, qp) )) { @@ -4104,10 +4135,12 @@ static void measurekeywords(mapsearchfreq_t *fr, (*dimp)[(*cuntp)].pos = sp - s; (*dimp)[(*cuntp)].siz = strlen(qp); } + (*cuntp)++; fr->total++; } } + if (wanttable) (*dimp) = Z_Realloc((*dimp), (*cuntp) * sizeof (struct searchdim), PU_STATIC, NULL); @@ -4176,7 +4209,7 @@ INT32 G_FindMap(const char *mapname, char **foundmapnamep, { newmapnum = mapnum; newmapname = realmapname; - realmapname = 0; + realmapname = NULL; Z_Free(apromapname); if (!wanttable) break; @@ -4197,7 +4230,7 @@ INT32 G_FindMap(const char *mapname, char **foundmapnamep, { apromapnum = mapnum; apromapname = realmapname; - realmapname = 0; + realmapname = NULL; } } else/* ...match individual keywords */ diff --git a/src/g_game.h b/src/g_game.h index c3b89435d..038bc68df 100644 --- a/src/g_game.h +++ b/src/g_game.h @@ -39,12 +39,8 @@ extern INT32 player_name_changes[MAXPLAYERS]; extern player_t players[MAXPLAYERS]; extern boolean playeringame[MAXPLAYERS]; -// gametic at level start -extern tic_t levelstarttic; - // for modding? extern INT16 prevmap, nextmap; -extern INT32 gameovertics; extern tic_t timeinmap; // Ticker for time spent in level (used for levelcard display) extern INT16 rw_maximums[NUM_WEAPONS]; @@ -74,6 +70,8 @@ extern consvar_t cv_ydeadzone[MAXSPLITSCREENPLAYERS]; extern consvar_t cv_litesteer[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_autoaccel[MAXSPLITSCREENPLAYERS]; + extern consvar_t cv_ghost_besttime, cv_ghost_bestlap, cv_ghost_last, cv_ghost_guest, cv_ghost_staff; // Hud offsets @@ -120,14 +118,16 @@ extern consvar_t cv_driftsparkpulse; extern consvar_t cv_gravstretch; extern consvar_t cv_sloperoll; extern consvar_t cv_sliptideroll; +extern consvar_t cv_stairjank; +extern consvar_t cv_stairjanksfx; extern consvar_t cv_slamsound; extern consvar_t cv_sloperolldist; extern consvar_t cv_sparkroll; -extern consvar_t cv_spinoutroll; extern consvar_t cv_squishdance, cv_squishdancespeed; extern consvar_t cv_playerblendeffects; +extern consvar_t cv_reducevfx; extern consvar_t cv_cechotoggle; @@ -228,10 +228,11 @@ void G_SaveGameData(boolean force); void G_SaveGame(UINT32 slot); -#define G_GametypeHasTeams() (G_IsGameType(GT_TEAMMATCH) || G_IsGameType(GT_CTF)) +#define G_RaceGametype() (G_IsGameType(GT_RACE)) #define G_BattleGametype() (G_IsGameType(GT_MATCH)) -#define G_RaceGametype() (G_IsGameType(GT_RACE)) -#define G_TagGametype() (G_IsGameType(GT_TAG) || G_IsGameType(GT_HIDEANDSEEK)) + +#define G_GametypeHasTeams() (UNLIKELY(G_IsGameType(GT_TEAMMATCH) || G_IsGameType(GT_CTF))) +#define G_TagGametype() (UNLIKELY(G_IsGameType(GT_TAG) || G_IsGameType(GT_HIDEANDSEEK))) FUNCINLINE static ATTRINLINE boolean G_IsGameType(int type) { @@ -249,7 +250,6 @@ UINT8 G_GetGametypeColor(INT16 gt); void G_ExitLevel(void); void G_NextLevel(void); void G_Continue(void); -void G_UseContinue(void); void G_AfterIntermission(void); void G_EndGame(void); // moved from y_inter.c/h and renamed diff --git a/src/g_input.c b/src/g_input.c index 0082df273..31df065fc 100644 --- a/src/g_input.c +++ b/src/g_input.c @@ -66,13 +66,30 @@ consvar_t cv_rumble[MAXSPLITSCREENPLAYERS] = { static CV_PossibleValue_t rumblestrength_cons_t[] = {{FRACUNIT/4, "MIN"}, {FRACUNIT*4, "MAX"}, {0, NULL}}; -consvar_t cv_rumblestrength[MAXSPLITSCREENPLAYERS] = { +consvar_t cv_rumble_strength[MAXSPLITSCREENPLAYERS] = { {"rumblestrength", "1.0", CV_SAVE|CV_FLOAT, rumblestrength_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, {"rumblestrength2", "1.0", CV_SAVE|CV_FLOAT, rumblestrength_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, {"rumblestrength3", "1.0", CV_SAVE|CV_FLOAT, rumblestrength_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, {"rumblestrength4", "1.0", CV_SAVE|CV_FLOAT, rumblestrength_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL} }; +#define IMPL_RUMBLE_TYPE(type)\ +consvar_t cv_rumble_##type [MAXSPLITSCREENPLAYERS] = {\ + {"rumble_" #type, "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL},\ + {"rumble2_" #type, "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL},\ + {"rumble3_" #type, "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL},\ + {"rumble4_" #type, "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}\ +}; + +IMPL_RUMBLE_TYPE(spinout); +IMPL_RUMBLE_TYPE(sneakerboost); +IMPL_RUMBLE_TYPE(offroad); +IMPL_RUMBLE_TYPE(bananadrag); +IMPL_RUMBLE_TYPE(stairjank); +IMPL_RUMBLE_TYPE(brakedrift); +IMPL_RUMBLE_TYPE(driftcharge); + + static CV_PossibleValue_t gamepadled_cons_t[] = {{0, "Off"}, {1, "Skincolor"}, {2, "Mobjcolor"}, {0, NULL}}; consvar_t cv_gamepadled[MAXSPLITSCREENPLAYERS] = { {"gamepadled", "Skincolor", CV_SAVE|CV_CALL|CV_NOINIT, gamepadled_cons_t, led_off_handle, 0, NULL, NULL, 0, 0, NULL}, @@ -81,6 +98,10 @@ consvar_t cv_gamepadled[MAXSPLITSCREENPLAYERS] = { {"gamepadled4", "Skincolor", CV_SAVE|CV_CALL|CV_NOINIT, gamepadled_cons_t, led_off_handle4, 0, NULL, NULL, 0, 0, NULL} }; +consvar_t cv_gamepadifunfocused = {"gamepadunfocused", "Off", CV_SAVE|CV_CALL, CV_OnOff, I_SetJoystickFocus, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_gamepadledifunfocused = {"gamepadledunfocused", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_rumbleifunfocused = {"rumbleifunfocused", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; + static void rumble_off_handle(void) { if (!cv_rumble[0].value) @@ -930,12 +951,17 @@ void G_SetPlayerGamepadIndicatorColor(INT32 playernum, UINT8 color) I_Assert(playernum >= 0 && playernum < MAXSPLITSCREENPLAYERS); - if (cv_gamepadled[playernum].value == 0 + if (cv_gamepadled[playernum].value == 0 || (window_notinfocus && cv_gamepadledifunfocused.value == 0) || color >= MAXTRANSLATIONS) { return; } + if (!I_GamepadHasLED(playernum)) + { + return; + } + // so we can override this skincolor = color ? color : G_GetSkinColorForGamepad(playernum); byte_color = V_GetColor(colortranslations[skincolor][8]).s; @@ -945,6 +971,8 @@ void G_SetPlayerGamepadIndicatorColor(INT32 playernum, UINT8 color) static void G_ResetPlayerGamepadIndicatorColor(INT32 playernum) { + I_Assert(playernum >= 0 && playernum < MAXSPLITSCREENPLAYERS); + if (cv_gamepadled[playernum].value == 0) { I_SetGamepadIndicatorColor(playernum, 0, 0, 255); @@ -969,17 +997,22 @@ void G_DeviceLEDTick(void) for (i = 0; i <= splitscreen; i++) { if (!cv_usejoystick[i].value || !cv_gamepadled[i].value) + { continue; + } + + // does not have a configurable led! :c + if (!I_GamepadHasLED(i)) + { + continue; + } newcolor = G_GetSkinColorForGamepad(i); - // compiler be absolutely tripping - // delet this if this gets fixed within gcc -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Warray-bounds" if (curcolor[i] == newcolor) // dont update if same colour + { continue; -#pragma GCC diagnostic pop + } G_SetPlayerGamepadIndicatorColor(i, newcolor); curcolor[i] = newcolor; @@ -994,6 +1027,7 @@ void G_ResetDeviceLED(void) static void G_ResetPlayerDeviceRumble(INT32 playernum) { + I_Assert(playernum >= 0 && playernum < MAXSPLITSCREENPLAYERS); I_GamepadRumble(playernum, 0, 0, 0); } @@ -1011,7 +1045,7 @@ void G_PlayerDeviceRumble(INT32 playernum, UINT16 low_strength, UINT16 high_stre { I_Assert(playernum >= 0 && playernum < MAXSPLITSCREENPLAYERS); - if (cv_rumble[playernum].value == 0) + if (cv_rumble[playernum].value == 0 || (window_notinfocus && cv_rumbleifunfocused.value == 0)) { return; } @@ -1019,8 +1053,8 @@ void G_PlayerDeviceRumble(INT32 playernum, UINT16 low_strength, UINT16 high_stre // doesent need to be super precise // but ensure this is within range (0-65535) // placed here so it applies to lua aswell - low_strength = (UINT16)min(FixedMul(low_strength, cv_rumblestrength[playernum].value), UINT16_MAX); - high_strength = (UINT16)min(FixedMul(high_strength, cv_rumblestrength[playernum].value), UINT16_MAX); + low_strength = (UINT16)min(FixedMul(low_strength, cv_rumble_strength[playernum].value), UINT16_MAX); + high_strength = (UINT16)min(FixedMul(high_strength, cv_rumble_strength[playernum].value), UINT16_MAX); I_GamepadRumble(playernum, low_strength, high_strength, duration); } @@ -1042,7 +1076,7 @@ void G_DeviceRumbleTick(void) { UINT8 i; - if (dedicated || numcontrollers == 0 || gamestate != GS_LEVEL) + if (dedicated || numcontrollers == 0 || gamestate != GS_LEVEL || demo.playback) { return; } @@ -1054,6 +1088,12 @@ void G_DeviceRumbleTick(void) continue; } + // does not support rumble! :c + if (!I_GamepadHasRumble(i)) + { + continue; + } + if (camera[i].freecam) { continue; @@ -1067,6 +1107,11 @@ void G_DeviceRumbleTick(void) const player_t *player = P_GetLocalPlayerForNum(i); + if (!player) + { + continue; + } + // allow lua to do some crap for spectators if (player->spectator || !player->mo) { @@ -1082,17 +1127,20 @@ void G_DeviceRumbleTick(void) continue; } - if (player->kartstuff[k_spinouttimer]) + if (cv_rumble_spinout[i].value + && player->kartstuff[k_spinouttimer]) { //low = high = FRACUNIT / 6; low = high = FixedMul((RUMBLE_VERYSTRONG), (FixedDiv(player->kartstuff[k_spinouttimer], (3*TICRATE / 2)))); // try do some some kinda fadeout, 3*TICRATE / 2 is the "default" spinout time } - else if (player->kartstuff[k_sneakertimer] > (sneakertime-(TICRATE/2))) + else if (cv_rumble_sneakerboost[i].value + && (player->kartstuff[k_sneakertimer] > (sneakertime-(TICRATE/2)))) { low = high = RUMBLE_STRONG; } - else if ((player->kartstuff[k_offroad]) - && player->speed != 0 + else if (cv_rumble_offroad[i].value + && (player->kartstuff[k_offroad]) + && (player->speed != 0) && P_IsObjectOnGround(player->mo)) { // weaken this depending on if you got hyu or invinc @@ -1109,26 +1157,37 @@ void G_DeviceRumbleTick(void) low = high = RUMBLE_MODERATE; } } - else if ((player->kartstuff[k_bananadrag] > TICRATE) - && player->speed != 0 + else if (cv_rumble_bananadrag[i].value + && (player->kartstuff[k_bananadrag] > TICRATE) + && (player->speed != 0) && P_IsObjectOnGround(player->mo)) { if (leveltime & 1) // this is actually funny lel high = RUMBLE_MODERATE; } + else if (cv_rumble_stairjank[i].value + && (player->stairjank > 8) + && (player->speed != 0) + && P_IsObjectOnGround(player->mo)) + { + low = high = RUMBLE_VERYWEAK; + } - if (player->kartstuff[k_brakedrift]) + if (cv_rumble_brakedrift[i].value + && player->kartstuff[k_brakedrift]) { high = CLAMP((high + RUMBLE_VERYWEAK), 0, UINT16_MAX); } // pulse when gettin new driftlevel // let this come last - if (player->kartstuff[k_driftcharge] + if (cv_rumble_driftcharge[i].value + && player->kartstuff[k_driftcharge] && player->driftlevel) { high = CLAMP((high + RUMBLE_VERYWEAK), 0, UINT16_MAX); + // make it rumble slightly longer the higher your driftlevel! if (player->driftlevel == 2) lenght = 114; else if (player->driftlevel == 3) @@ -1191,7 +1250,8 @@ const char *G_KeynumToString(INT32 keynum) return keynames[j].name; // create a name for unknown keys - sprintf(keynamestr, "KEY%d", keynum); + snprintf(keynamestr, sizeof(keynamestr), "KEY%d", keynum); + return keynamestr; } diff --git a/src/g_input.h b/src/g_input.h index 9831e6d8f..bed5beb0e 100644 --- a/src/g_input.h +++ b/src/g_input.h @@ -100,9 +100,10 @@ typedef enum gc_custom2, // Lua scriptable gc_custom3, // Lua scriptable gc_director, - gc_freecam, // Toggle for freecam while ingame - gc_camfloat, // alternative button for raising cam - gc_camsink, // alternative button for sinking + // freecam specific controls + gc_freecam, // Toggle for freecam while ingame + gc_camfloat, // alternative button for raising camera + gc_camsink, // alternative button for sinking camera gc_strafeleft, gc_straferight, num_gamecontrols @@ -112,10 +113,23 @@ typedef enum extern consvar_t cv_mousexsens, cv_mouseysens; extern consvar_t cv_controlperkey; extern consvar_t cv_turnsmooth[MAXSPLITSCREENPLAYERS]; -extern consvar_t cv_rumble[MAXSPLITSCREENPLAYERS]; -extern consvar_t cv_rumblestrength[MAXSPLITSCREENPLAYERS]; + extern consvar_t cv_gamepadled[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_rumble[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_rumble_strength[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_rumble_spinout[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_rumble_sneakerboost[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_rumble_offroad[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_rumble_bananadrag[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_rumble_stairjank[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_rumble_brakedrift[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_rumble_driftcharge[MAXSPLITSCREENPLAYERS]; + +extern consvar_t cv_gamepadifunfocused; +extern consvar_t cv_gamepadledifunfocused; +extern consvar_t cv_rumbleifunfocused; + extern INT32 mousex, mousey; extern INT32 joyxmove[MAXSPLITSCREENPLAYERS][JOYAXISSET], joyymove[MAXSPLITSCREENPLAYERS][JOYAXISSET]; diff --git a/src/g_state.h b/src/g_state.h index f9f1babd3..fd3d7f062 100644 --- a/src/g_state.h +++ b/src/g_state.h @@ -52,10 +52,10 @@ typedef enum } gameaction_t; extern gamestate_t gamestate; -extern UINT8 ultimatemode; // was sk_insane extern gameaction_t gameaction; extern boolean botingame; -extern UINT8 botskin, botcolor; +extern skinnum_t botskin; +extern UINT8 botcolor; #endif //__G_STATE__ diff --git a/src/hardware/hw_batching.c b/src/hardware/hw_batching.c index 4d6b1ea6e..9b1699029 100644 --- a/src/hardware/hw_batching.c +++ b/src/hardware/hw_batching.c @@ -183,6 +183,7 @@ static int comparePolygons(const void *p1, const void *p2) UINT32 downloaded1 = poly1->texture ? poly1->texture->downloaded : 0; // there should be a opengl texture name here, usable for comparisons UINT32 downloaded2 = poly2->texture ? poly2->texture->downloaded : 0; + diff64 = downloaded1 - downloaded2; if (diff64 != 0) return diff64; @@ -391,7 +392,7 @@ void HWR_RenderBatches(void) nextSurfaceInfo = nextEntry->surf; if (nextPolyFlags & PF_NoTexture) - nextTexture = 0; + nextTexture = NULL; if (useshader && currentShader != nextShader) { diff --git a/src/hardware/hw_bsp.c b/src/hardware/hw_bsp.c index 79069857c..0a4b0af36 100644 --- a/src/hardware/hw_bsp.c +++ b/src/hardware/hw_bsp.c @@ -12,20 +12,21 @@ /// \brief convert SRB2 map #include "../doomdef.h" -#include "../doomstat.h" + #ifdef HWRENDER + #include "hw_main.h" #include "hw_glob.h" -#include "../r_local.h" #include "../z_zone.h" + +#ifdef HWR_LOADING_SCREEN #include "../console.h" -#include "../v_video.h" #include "../m_menu.h" -#include "../i_system.h" -#include "../m_argv.h" -#include "../i_video.h" -#include "../w_wad.h" #include "../p_setup.h" // levelfadecol +#include "../i_video.h" +#endif + +//#define DEBUG_HWBSP // -------------------------------------------------------------------------- // This is global data for planes rendering @@ -33,19 +34,20 @@ extrasubsector_t *extrasubsectors = NULL; -// newsubsectors are subsectors without segs, added for the plane polygons -#define NEWSUBSECTORS 50 -static size_t totsubsectors; +// extra subsectors are subsectors without segs, added for the plane polygons +#define NUM_EXTRA_SUBSECTORS 50 +static size_t num_alloc_extra_subsector; #ifdef PARANOIA -size_t addsubsector; +size_t num_extra_subsector; #else -static size_t addsubsector; +static size_t num_extra_subsector; #endif -typedef struct -{ +typedef struct { float x, y; float dx, dy; + polyvertex_t divpt; + float divfrac; } fdivline_t; // when loading the map, this is set to true if portals are found. @@ -53,7 +55,7 @@ typedef struct boolean gl_maphasportals = false; // Determine on mapload if current map has any Horizonlines present -// so we can avoid rather hot checks in HWR_Subsector +// avoids doing a bunch of work during rendering boolean gl_maphashorizonlines = false; // ========================================================================== @@ -80,26 +82,25 @@ static poly_t *HWR_AllocPoly(INT32 numpts) return p; } -/// \todo polygons should be freed in reverse order for efficiency, +/// TODO: polygons should be freed in reverse order for efficiency, /// for now don't free because it doesn't free in reverse order static void HWR_FreePoly(poly_t *poly) { Z_Free(poly); } -// Return interception along bsp line, +// Return interception along bsp line (partline), // with the polygon segment -// -static float bspfrac; -static polyvertex_t *fracdivline(fdivline_t *bsp, polyvertex_t *v1, - polyvertex_t *v2) + +// Return the division in partline div fields. +// divfrac = how far along partline vector is crossing pt +static boolean fracdivline(fdivline_t *partline, polyvertex_t *v1, polyvertex_t *v2) { - static polyvertex_t pt; - double frac; - double num; - double den; - double v1x, v1y, v1dx, v1dy; - double v2x, v2y, v2dx, v2dy; + double frac1, frac2; + double num; // numerator + double den; // denominator + double v1x, v1y, v1dx, v1dy; // polygon side vector, v1->v2 + double v3x, v3y, v3dx, v3dy; // partline vector // a segment of a polygon v1x = v1->x; @@ -108,111 +109,118 @@ static polyvertex_t *fracdivline(fdivline_t *bsp, polyvertex_t *v1, v1dy = v2->y - v1->y; // the bsp partition line - v2x = bsp->x; - v2y = bsp->y; - v2dx = bsp->dx; - v2dy = bsp->dy; + v3x = partline->x; + v3y = partline->y; + v3dx = partline->dx; + v3dy = partline->dy; - den = v2dy*v1dx - v2dx*v1dy; + den = v3dy*v1dx - v3dx*v1dy; - if (fabsf((float)den) < 1.0E-36f) // avoid checking exactly for 0.0 - return NULL; // parallel + if (fabs(den) < 1.0E-36) // avoid check of float for exact 0 + return false; // partline and polygon side are effectively parallel // first check the frac along the polygon segment, // (do not accept hit with the extensions) - num = (v2x - v1x)*v2dy + (v1y - v2y)*v2dx; - frac = num / den; + num = (v3x - v1x)*v3dy + (v1y - v3y)*v3dx; + frac1 = num / den; - if (frac < 0.0l || frac > 1.0l) - return NULL; + // 0= cross at v1, 1.0= cross at v2 + if (frac1 < 0.0 || frac1 > 1.0) // double + return false; // not within the polygon side // now get the frac along the BSP line // which is useful to determine what is left, what is right - num = (v2x - v1x)*v1dy + (v1y - v2y)*v1dx; - frac = num / den; - bspfrac = (float)frac; + num = (v3x - v1x)*v1dy + (v1y - v3y)*v1dx; + frac2 = num / den; - // find the interception point along the partition line - pt.x = (float)(v2x + v2dx*frac); - pt.y = (float)(v2y + v2dy*frac); + partline->divfrac = frac2; // how far along partline vector - return &pt; + // [WDJ] find the interception point along the segment. + // It should be slightly more accurate because it is always closer to the + // crossing point than arbitrary positions on the partition line. + partline->divpt.x = v1x + v1dx*frac1; + partline->divpt.y = v1y + v1dy*frac1; + + return true; } +// BOOMEDIT.WAD has a vertex error of .21 #define DIVLINE_VERTEX_DIFF 0.45f // if two vertice coords have a x and/or y difference // of less or equal than 1 FRACUNIT, they are considered the same // point. Note: hardcoded value, 1.0f could be anything else. -static boolean SameVertice (polyvertex_t *p1, polyvertex_t *p2) +static boolean SameVertex(polyvertex_t *p1, polyvertex_t *p2) { - if (fabsf( p2->x - p1->x ) > DIVLINE_VERTEX_DIFF) + if (fabsf(p2->x - p1->x) > DIVLINE_VERTEX_DIFF) return false; - if (fabsf( p2->y - p1->y ) > DIVLINE_VERTEX_DIFF) + if (fabsf(p2->y - p1->y) > DIVLINE_VERTEX_DIFF) return false; // p1 and p2 are considered the same vertex return true; } - // split a _CONVEX_ polygon in two convex polygons // outputs: // frontpoly : polygon on right side of bsp line // backpoly : polygon on left side // -static void SplitPoly (fdivline_t *bsp, //splitting parametric line - poly_t *poly, //the convex poly we split - poly_t **frontpoly, //return one poly here - poly_t **backpoly) //return the other here +// Called from: WalkBSPNode +static void SplitPoly (fdivline_t *dlnp, // splitting parametric line + poly_t *poly, // the convex poly we split + poly_t **frontpoly, // return one poly here + poly_t **backpoly) // return the other here { INT32 i, j; polyvertex_t *pv; - INT32 ps = -1, pe = -1; - INT32 nptfront, nptback; + INT32 ps, pe; // poly start, end + INT32 ps_online, pe_online; + INT32 nptfront, nptback; polyvertex_t vs = {}; polyvertex_t ve = {}; polyvertex_t lastpv = {}; - float fracs = 0.0f, frace = 0.0f; //used to tell which poly is on - // the front side of the bsp partition line - INT32 psonline = 0, peonline = 0; + float ps_frac = 0.0f, pe_frac = 0.0f; // used to tell which poly is on + // the front side of the bsp partition line + ps = pe = -1; + ps_online = pe_online = 0; for (i = 0; i < poly->numpts; i++) { - j = i + 1; + // i, j are one side of the poly + j = i+1; if (j == poly->numpts) - j = 0; + j = 0; // wrap poly // start & end points - pv = fracdivline(bsp, &poly->pts[i], &poly->pts[j]); - - if (pv == NULL) + if (!fracdivline(dlnp, &poly->pts[i], &poly->pts[j])) continue; + // have dividing pt if (ps < 0) { // first point ps = i; - vs = *pv; - fracs = bspfrac; + vs = dlnp->divpt; + ps_frac = dlnp->divfrac; } else { - //the partition line traverse a junction between two segments + // the partition line can traverse a junction between two segments // or the two points are so close, they can be considered as one // thus, don't accept, since split 2 must be another vertex - if (SameVertice(pv, &lastpv)) + if (SameVertex(&dlnp->divpt, &lastpv)) { if (pe < 0) { ps = i; - psonline = 1; + ps_online = 1; } else { pe = i; - peonline = 1; + pe_online = 1; } } else @@ -220,24 +228,25 @@ static void SplitPoly (fdivline_t *bsp, //splitting parametric line if (pe < 0) { pe = i; - ve = *pv; - frace = bspfrac; + ve = dlnp->divpt; + pe_frac = dlnp->divfrac; } else { - // a frac, not same vertice as last one - // we already got pt2 so pt 2 is not on the line, - // so we probably got back to the start point - // which is on the line - if (SameVertice(pv, &vs)) - psonline = 1; + // a frac, not same vertice as last one + // we already got pt2 so pt 2 is not on the line, + // so we probably got back to the start point + // which is on the line + if (SameVertex(&dlnp->divpt, &vs)) + ps_online = 1; + break; } } } // remember last point intercept to detect identical points - lastpv = *pv; + lastpv = dlnp->divpt; } // no split: the partition line is either parallel and @@ -254,28 +263,34 @@ static void SplitPoly (fdivline_t *bsp, //splitting parametric line // linedefs where each side point the same sector, that is: // the deep water effect with the original Doom - /// \todo make sure front poly is to front of partition line? + //TODO: make sure front poly is to front of partition line? *frontpoly = poly; - *backpoly = NULL; + *backpoly = NULL; return; } + //if (ps >= 0 && pe < 0) if (pe < 0) { //I_Error("SplitPoly: only one point for split line (%d %d)", ps, pe); *frontpoly = poly; - *backpoly = NULL; + *backpoly = NULL; return; } - if (UNLIKELY(pe <= ps)) - I_Error("SplitPoly: invalid splitting line (%d %d)", ps, pe); + if (pe <= ps) + { + //I_Error("SplitPoly: invalid splitting line (%d %d)", ps, pe); + *frontpoly = poly; + *backpoly = NULL; + return; + } - // number of points on each side, _not_ counting those - // that may lie just one the line - nptback = pe - ps - peonline; - nptfront = poly->numpts - peonline - psonline - nptback; + // Number of points on each side, _not_ counting those + // that may lie just on the line. + nptback = pe - ps - pe_online; + nptfront = poly->numpts - pe_online - ps_online - nptback; if (nptback > 0) *backpoly = HWR_AllocPoly(2 + nptback); @@ -295,11 +310,9 @@ static void SplitPoly (fdivline_t *bsp, //splitting parametric line *pv++ = ve; i = pe; - do - { + do { if (++i == poly->numpts) i = 0; - *pv++ = poly->pts[i]; } while (i != ps && --nptfront); } @@ -312,68 +325,81 @@ static void SplitPoly (fdivline_t *bsp, //splitting parametric line *pv++ = vs; i = ps; - do - { + do { if (++i == poly->numpts) i = 0; - *pv++ = poly->pts[i]; } while (i != pe && --nptback); } // make sure frontpoly is the one on the 'right' side // of the partition line - if (fracs > frace) + if (ps_frac > pe_frac) { - poly_t *swappoly; - swappoly = *backpoly; - *backpoly = *frontpoly; + poly_t* swappoly; + swappoly = *backpoly; + *backpoly = *frontpoly; *frontpoly = swappoly; } - HWR_FreePoly (poly); + HWR_FreePoly(poly); } +// checks if any line is a portal or horizonline, for optimization +static inline void CheckForPortalsAndHorizonLines(boolean firstside, const line_t *line) +{ + // portal check + if (!gl_maphasportals && firstside && line->special == PORTALSPECIAL) + { + // Find the other side! + INT32 line2 = P_FindSpecialLineFromTag(PORTALSPECIAL, line->tag, -1); -// use each seg of the poly as a partition line, keep only the + if (line2 >= 0 && line == &lines[line2]) + line2 = P_FindSpecialLineFromTag(PORTALSPECIAL, line->tag, line2); + + if (line2 >= 0) // found it! + gl_maphasportals = 1; + } + + // horizonline check + if (!gl_maphashorizonlines && line->special == HORIZONSPECIAL) + gl_maphashorizonlines = true; +} + +// Use each seg of the poly as a partition line, keep only the // part of the convex poly to the front of the seg (that is, -// the part inside the sector), the part behind the seg, is -// the void space and is cut out +// the part inside the sector). The part behind the seg, is +// the void space and is cut out. // -static poly_t *CutOutSubsecPoly(seg_t *lseg, INT32 count, poly_t *poly) +// poly : surrounding convex polygon, non-destructive +// lseg : array of seg +// segcount : number of seg in the array +// Return frontpoly, which may be new or ptr to poly. +// Called from: HWR_SubsecPoly +static poly_t *CutOutSubsecPoly(seg_t *lseg, INT32 segcount, poly_t *poly) { INT32 i, j; + poly_t* frontpoly = poly; // default, return same poly polyvertex_t *pv; - INT32 nump = 0, ps, pe; + INT32 poly_num_pts = 0, ps, pe; polyvertex_t vs = {}, ve = {}, p1 = {}, p2 = {}; - float fracs = 0.0f; + float ps_frac = 0.0f; + vertex_t *v1, *v2; fdivline_t cutseg; // x, y, dx, dy as start of node_t struct - poly_t *temppoly; // for each seg of the subsector - for (; count--; lseg++) + for (; segcount--; lseg++) { // x, y, dx, dy (like a divline) const line_t *line = lseg->linedef; - // portal check - if (UNLIKELY(!gl_maphasportals && line->special == PORTALSPECIAL && lseg->side == 0)) - { - // Find the other side! - INT32 line2 = P_FindSpecialLineFromTag(PORTALSPECIAL, line->tag, -1); + if (!line) + continue; - if (line == &lines[line2]) - line2 = P_FindSpecialLineFromTag(PORTALSPECIAL, line->tag, line2); + CheckForPortalsAndHorizonLines(lseg->side == 0, line); - if (line2 >= 0) // found it! - gl_maphasportals = 1; - } - - if (!gl_maphashorizonlines && line->special == HORIZONSPECIAL) - gl_maphashorizonlines = true; - - if (line->sidenum[1] != 0xffff) + if (line->sidenum[1] != NO_INDEX) { if (sides[line->sidenum[0]].sector == sides[line->sidenum[1]].sector) { @@ -385,10 +411,21 @@ static poly_t *CutOutSubsecPoly(seg_t *lseg, INT32 count, poly_t *poly) } } - p1.x = FIXED_TO_FLOAT(lseg->side ? line->v2->x : line->v1->x); - p1.y = FIXED_TO_FLOAT(lseg->side ? line->v2->y : line->v1->y); - p2.x = FIXED_TO_FLOAT(lseg->side ? line->v1->x : line->v2->x); - p2.y = FIXED_TO_FLOAT(lseg->side ? line->v1->y : line->v2->y); + if (lseg->side) // side 1 + { + v1 = line->v2; + v2 = line->v1; + } + else // side 0 + { + v1 = line->v1; + v2 = line->v2; + } + + p1.x = FixedToFloat(v1->x); + p1.y = FixedToFloat(v1->y); + p2.x = FixedToFloat(v2->x); + p2.y = FixedToFloat(v2->y); cutseg.x = p1.x; cutseg.y = p1.y; @@ -401,125 +438,130 @@ static poly_t *CutOutSubsecPoly(seg_t *lseg, INT32 count, poly_t *poly) for (i = 0; i < poly->numpts; i++) { - j = i + 1; + // i, j are one side of the poly + j = i+1; if (j == poly->numpts) j = 0; - pv = fracdivline(&cutseg, &poly->pts[i], &poly->pts[j]); - - if (pv == NULL) + if (!fracdivline(&cutseg, &poly->pts[i], &poly->pts[j])) continue; + // have dividing pt if (ps < 0) { ps = i; - vs = *pv; - fracs = bspfrac; + vs = cutseg.divpt; + ps_frac = cutseg.divfrac; + continue; + } + + // frac 1 on previous segment, + // 0 on the next, + // the split line goes through one of the convex poly + // vertices, happens quite often since the convex + // poly is already adjacent to the subsector segs + // on most borders + if (SameVertex(&cutseg.divpt, &vs)) + continue; + + if (ps_frac <= cutseg.divfrac) + { + poly_num_pts = 2 + poly->numpts - (i-ps); + pe = ps; + ps = i; + ve = cutseg.divpt; } else { - //frac 1 on previous segment, - // 0 on the next, - //the split line goes through one of the convex poly - // vertices, happens quite often since the convex - // poly is already adjacent to the subsector segs - // on most borders - if (SameVertice(pv, &vs)) - continue; - - if (fracs <= bspfrac) - { - nump = 2 + poly->numpts - (i-ps); - pe = ps; - ps = i; - ve = *pv; - } - else - { - nump = 2 + (i-ps); - pe = i; - ve = vs; - vs = *pv; - } - - //found 2nd point - break; + poly_num_pts = 2 + (i-ps); + pe = i; + ve = vs; + vs = cutseg.divpt; } + + // found 2nd point + break; } // there was a split if (ps >= 0) { - //need 2 points + // need 2 points if (pe >= 0) { // generate FRONT poly - temppoly = HWR_AllocPoly(nump); + frontpoly = HWR_AllocPoly(poly_num_pts); - pv = temppoly->pts; + pv = frontpoly->pts; *pv++ = vs; *pv++ = ve; - do - { - if (++ps == poly->numpts) + do { + if (++ps == poly->numpts) // poly wrap ps = 0; *pv++ = poly->pts[ps]; } while (ps != pe); HWR_FreePoly(poly); - poly = temppoly; + poly = frontpoly; } #ifdef DEBUG_HWBSP - // hmmm... maybe we should NOT accept this, but this happens - // only when the cut is not needed it seems (when the cut - // line is aligned to one of the borders of the poly, and - // only some times..) else { + // hmmm... maybe we should NOT accept this, but this happens + // only when the cut is not needed it seems (when the cut + // line is aligned to one of the borders of the poly, and + // only some times..) + // [WDJ] This happens often (27 times in Doom2 map01). skipcut++; - I_Error("CutOutPoly: only one point for split line (%d %d) %d", ps, pe, debugpos); + //I_Error("CutOutPoly: only one point for split line (%d %d) %d", ps, pe, debugpos); } #endif } } - return poly; + + return frontpoly; } // At this point, the poly should be convex and the exact -// layout of the subsector, it is not always the case, +// layout of the subsector. It is not always the case, // so continue to cut off the poly into smaller parts with // each seg of the subsector. // -static inline void HWR_SubsecPoly(INT32 num, poly_t *poly) +// ssindex : subsec index, 0..(numsubsectors-1) +// poly : surrounding convex polygon, non-destructive +// Called from WalkBSPNode +static inline void HWR_SubsecPoly(INT32 ssindex, poly_t *poly) { - INT16 count; + INT16 segcount; subsector_t *sub; seg_t *lseg; - sub = &subsectors[num]; - count = sub->numlines; + sub = &subsectors[ssindex]; + segcount = sub->numlines; lseg = &segs[sub->firstline]; if (poly) { - poly = CutOutSubsecPoly(lseg,count,poly); + poly = CutOutSubsecPoly(lseg, segcount, poly); #ifdef DEBUG_HWBSP totalsubsecpolys++; #endif //extra data for this subsector - extrasubsectors[num].planepoly = poly; + extrasubsectors[ssindex].planepoly = poly; } } -// the bsp divline have not enouth presition -// search for the segs source of this divline -static inline void SearchDivline(node_t *bsp, fdivline_t *divline) +// The bsp divline does not have enough precision. +// Search for the segs source of this divline. +static inline void SetDivline(node_t *bsp, fdivline_t *divline) { - divline->x = FIXED_TO_FLOAT(bsp->x); - divline->y = FIXED_TO_FLOAT(bsp->y); - divline->dx = FIXED_TO_FLOAT(bsp->dx); - divline->dy = FIXED_TO_FLOAT(bsp->dy); + // MAR - If you don't use the same partition line that the BSP uses, + // the front/back polys won't match the subsectors in the BSP! + divline->x = FixedToFloat(bsp->x); + divline->y = FixedToFloat(bsp->y); + divline->dx = FixedToFloat(bsp->dx); + divline->dy = FixedToFloat(bsp->dy); } //Hurdler: implement a loading status @@ -532,20 +574,26 @@ static void loading_status(void) char s[16]; int x, y; + /*if (g_reloadinggamestate) + { + return; + }*/ + I_OsPolling(); CON_Drawer(); - sprintf(s, "%d%%", (++ls_percent)<<1); + snprintf(s, sizeof(s), "%d%%", (++ls_percent)<<1); + x = BASEVIDWIDTH/2; y = BASEVIDHEIGHT/2; - V_DrawFill(0, 0, BASEVIDWIDTH, BASEVIDHEIGHT, 31); // Black background to match fade in effect + V_DrawFill(0, 0, BASEVIDWIDTH, BASEVIDHEIGHT, levelfadecol); // Black background to match fade in effect //V_DrawPatchFill(srb2back); // SRB2 background, ehhh too bright. M_DrawTextBox(x-58, y-8, 13, 1); V_DrawString(x-50, y, V_YELLOWMAP, "Loading..."); V_DrawRightAlignedString(x+50, y, V_YELLOWMAP, s); // Is this really necessary at this point..? - V_DrawCenteredString(BASEVIDWIDTH/2, 40, V_YELLOWMAP, "OPENGL MODE IS INCOMPLETE AND MAY"); - V_DrawCenteredString(BASEVIDWIDTH/2, 50, V_YELLOWMAP, "NOT DISPLAY SOME SURFACES."); + V_DrawCenteredString(BASEVIDWIDTH/2, 40, V_YELLOWMAP, "OPENGL MODE IS INCOMPLETE AND SOME"); + V_DrawCenteredString(BASEVIDWIDTH/2, 50, V_YELLOWMAP, "VISUAL FEATURES ARE MISSING/BROKEN."); V_DrawCenteredString(BASEVIDWIDTH/2, 70, V_YELLOWMAP, "USE AT SONIC'S RISK."); I_UpdateNoVsync(); @@ -576,14 +624,14 @@ static void WalkBSPNode(INT32 bspnum, poly_t *poly, UINT16 *leafnode, fixed_t *b { CONS_Debug(DBG_RENDER, "Adding a new subsector\n"); - if (UNLIKELY(addsubsector == numsubsectors + NEWSUBSECTORS)) - I_Error("WalkBSPNode: not enough addsubsectors\n"); - else if (UNLIKELY(addsubsector > 0x7fff)) - I_Error("WalkBSPNode: addsubsector > 0x7fff\n"); + if (num_extra_subsector == numsubsectors + NUM_EXTRA_SUBSECTORS) + I_Error("WalkBSPNode: not enough num_extra_subsectors\n"); + else if (num_extra_subsector > 0x7fff) + I_Error("WalkBSPNode: num_extra_subsector > 0x7fff\n"); - *leafnode = (UINT16)((UINT16)addsubsector | NF_SUBSECTOR); - extrasubsectors[addsubsector].planepoly = poly; - addsubsector++; + *leafnode = (UINT16)((UINT16)num_extra_subsector | NF_SUBSECTOR); + extrasubsectors[num_extra_subsector].planepoly = poly; + num_extra_subsector++; } //add subsectors without segs here? @@ -593,8 +641,8 @@ static void WalkBSPNode(INT32 bspnum, poly_t *poly, UINT16 *leafnode, fixed_t *b { HWR_SubsecPoly(bspnum & ~NF_SUBSECTOR, poly); - //Hurdler: implement a loading status #ifdef HWR_LOADING_SCREEN + //Hurdler: implement a loading status if (ls_count-- <= 0) { ls_count = numsubsectors/50; @@ -613,7 +661,7 @@ static void WalkBSPNode(INT32 bspnum, poly_t *poly, UINT16 *leafnode, fixed_t *b } bsp = &nodes[bspnum]; - SearchDivline(bsp, &fdivline); + SetDivline(bsp, &fdivline); SplitPoly(&fdivline, poly, &frontpoly, &backpoly); poly = NULL; @@ -656,12 +704,12 @@ void HWR_FreeExtraSubsectors(void) extrasubsectors = NULL; } -#define MAXDIST 1.5f +#define MAXDIST (1.5f) // BP: can't move vertex: DON'T change polygon geometry! (convex) //#define MOVEVERTEX // Is vertex va within the seg v1, v2 -static boolean PointInSeg(polyvertex_t *va,polyvertex_t *v1,polyvertex_t *v2) +static boolean PointInSeg(polyvertex_t *va, polyvertex_t *v1, polyvertex_t *v2) { register float ax, ay, bx, by, cx, cy, d, norm; @@ -736,8 +784,8 @@ static boolean PointInSeg(polyvertex_t *va,polyvertex_t *v1,polyvertex_t *v2) if (cx*cx+cy*cy <= MAXDIST*MAXDIST) { // ajust a little the point position - a->x = ax*d+v1->x; - a->y = ay*d+v1->y; + va->x = ax*d+v1->x; + va->y = ay*d+v1->y; // anyway the correction is not enouth return true; } @@ -749,10 +797,10 @@ static boolean PointInSeg(polyvertex_t *va,polyvertex_t *v1,polyvertex_t *v2) static INT32 numsplitpoly; -static void SearchSegInBSP(INT32 bspnum,polyvertex_t *p,poly_t *poly) +static void SearchSegInBSP(INT32 bspnum, polyvertex_t *p, poly_t *poly) { poly_t *q; - INT32 j,k; + INT32 j, k; if (bspnum & NF_SUBSECTOR) { @@ -772,12 +820,12 @@ static void SearchSegInBSP(INT32 bspnum,polyvertex_t *p,poly_t *poly) if (k == numpts) k = 0; - if (!SameVertice(p, &q->pts[j]) - && !SameVertice(p, &q->pts[k]) - && PointInSeg(p, &q->pts[j], &q->pts[k])) + if (!SameVertex(p, &q->pts[j]) && + !SameVertex(p, &q->pts[k]) && + PointInSeg(p, &q->pts[j], &q->pts[k])) { - poly_t *newpoly = HWR_AllocPoly(numpts+1); INT32 n; + poly_t *newpoly = HWR_AllocPoly(numpts+1); for (n = 0; n <= j; n++) newpoly->pts[n] = q->pts[n]; @@ -798,16 +846,17 @@ static void SearchSegInBSP(INT32 bspnum,polyvertex_t *p,poly_t *poly) return; } - if ((FIXED_TO_FLOAT(nodes[bspnum].bbox[0][BOXBOTTOM])-MAXDIST <= p->y) && - (FIXED_TO_FLOAT(nodes[bspnum].bbox[0][BOXTOP ])+MAXDIST >= p->y) && - (FIXED_TO_FLOAT(nodes[bspnum].bbox[0][BOXLEFT ])-MAXDIST <= p->x) && - (FIXED_TO_FLOAT(nodes[bspnum].bbox[0][BOXRIGHT ])+MAXDIST >= p->x)) + // Not a subsector, visit left and right children. + if ((FixedToFloat(nodes[bspnum].bbox[0][BOXBOTTOM])-MAXDIST <= p->y) && + (FixedToFloat(nodes[bspnum].bbox[0][BOXTOP ])+MAXDIST >= p->y) && + (FixedToFloat(nodes[bspnum].bbox[0][BOXLEFT ])-MAXDIST <= p->x) && + (FixedToFloat(nodes[bspnum].bbox[0][BOXRIGHT ])+MAXDIST >= p->x)) SearchSegInBSP(nodes[bspnum].children[0], p, poly); - if ((FIXED_TO_FLOAT(nodes[bspnum].bbox[1][BOXBOTTOM])-MAXDIST <= p->y) && - (FIXED_TO_FLOAT(nodes[bspnum].bbox[1][BOXTOP ])+MAXDIST >= p->y) && - (FIXED_TO_FLOAT(nodes[bspnum].bbox[1][BOXLEFT ])-MAXDIST <= p->x) && - (FIXED_TO_FLOAT(nodes[bspnum].bbox[1][BOXRIGHT ])+MAXDIST >= p->x)) + if ((FixedToFloat(nodes[bspnum].bbox[1][BOXBOTTOM])-MAXDIST <= p->y) && + (FixedToFloat(nodes[bspnum].bbox[1][BOXTOP ])+MAXDIST >= p->y) && + (FixedToFloat(nodes[bspnum].bbox[1][BOXLEFT ])-MAXDIST <= p->x) && + (FixedToFloat(nodes[bspnum].bbox[1][BOXRIGHT ])+MAXDIST >= p->x)) SearchSegInBSP(nodes[bspnum].children[1], p, poly); } @@ -816,38 +865,43 @@ static void SearchSegInBSP(INT32 bspnum,polyvertex_t *p,poly_t *poly) // but we must use a different structure : polygone pointing on segs // segs pointing on polygone and on vertex (too mush complicated, well not // realy but i am soo lasy), the methode discibed is also better for segs presition -static INT32 SolveTProblem(void) +static void SolveTProblem(void) { poly_t *p; - INT32 i; - size_t l; + INT32 i, numpts; + size_t ssnum; - if (cv_glsolvetjoin.value == 0) - return 0; + if (!cv_glsolvetjoin.value) + return; CONS_Debug(DBG_RENDER, "Solving T-joins. This may take a while. Please wait...\n"); +#ifdef HWR_LOADING_SCREEN + CON_Drawer(); //let the user know what we are doing + I_FinishUpdate(); // page flip or blit buffer +#endif + numsplitpoly = 0; - for (l = 0; l < addsubsector; l++) + for (ssnum = 0; ssnum < num_extra_subsector; ssnum++) { - p = extrasubsectors[l].planepoly; + p = extrasubsectors[ssnum].planepoly; - if (!p) + if (!p || p->numpts == 0) continue; - for (i = 0; i < p->numpts; i++) + numpts = p->numpts; + + for (i = 0; i < numpts; i++) SearchSegInBSP((INT32)numnodes-1, &p->pts[i], p); } #ifdef DEBUG_HWBSP CONS_Debug(DBG_RENDER, "numsplitpoly %d\n", numsplitpoly); + CONS_Debug(DBG_RENDER, "%d point divides a polygon line\n", numsplitpoly); #endif - - return numsplitpoly; } - // call this routine after the BSP of a Doom wad file is loaded, // and it will generate all the convex polys for the hardware renderer void HWR_CreatePlanePolygons(INT32 bspnum) @@ -865,7 +919,7 @@ void HWR_CreatePlanePolygons(INT32 bspnum) #endif // reset the portal and horizonline flag - gl_maphasportals = gl_maphashorizonlines = 0; + gl_maphasportals = gl_maphashorizonlines = false; // find min/max boundaries of map #ifdef DEBUG_HWBSP @@ -882,39 +936,35 @@ void HWR_CreatePlanePolygons(INT32 bspnum) HWR_FreeExtraSubsectors(); // allocate extra data for each subsector present in map - totsubsectors = numsubsectors + NEWSUBSECTORS; - extrasubsectors = calloc(totsubsectors, sizeof(*extrasubsectors)); + num_alloc_extra_subsector = numsubsectors + NUM_EXTRA_SUBSECTORS; + extrasubsectors = (extrasubsector_t*)calloc(num_alloc_extra_subsector, sizeof(*extrasubsectors)); if (UNLIKELY(!extrasubsectors)) - I_Error("couldn't malloc extrasubsectors totsubsectors %s\n", sizeu1(totsubsectors)); + I_Error("couldn't malloc extrasubsectors num_alloc_extra_subsector %s\n", sizeu1(num_alloc_extra_subsector)); // number of the first new subsector that might be added - addsubsector = numsubsectors; + num_extra_subsector = numsubsectors; // construct the initial convex poly that encloses the full map rootp = HWR_AllocPoly(4); rootpv = rootp->pts; - rootpv->x = FIXED_TO_FLOAT(rootbbox[BOXLEFT ]); - rootpv->y = FIXED_TO_FLOAT(rootbbox[BOXBOTTOM]); //lr + // clockwise polygon + rootpv->x = FixedToFloat(rootbbox[BOXLEFT ]); + rootpv->y = FixedToFloat(rootbbox[BOXBOTTOM]); //lr rootpv++; - rootpv->x = FIXED_TO_FLOAT(rootbbox[BOXLEFT ]); - rootpv->y = FIXED_TO_FLOAT(rootbbox[BOXTOP ]); //ur + rootpv->x = FixedToFloat(rootbbox[BOXLEFT ]); + rootpv->y = FixedToFloat(rootbbox[BOXTOP ]); //ur rootpv++; - rootpv->x = FIXED_TO_FLOAT(rootbbox[BOXRIGHT ]); - rootpv->y = FIXED_TO_FLOAT(rootbbox[BOXTOP ]); //ul + rootpv->x = FixedToFloat(rootbbox[BOXRIGHT ]); + rootpv->y = FixedToFloat(rootbbox[BOXTOP ]); //ul rootpv++; - rootpv->x = FIXED_TO_FLOAT(rootbbox[BOXRIGHT ]); - rootpv->y = FIXED_TO_FLOAT(rootbbox[BOXBOTTOM]); //ll + rootpv->x = FixedToFloat(rootbbox[BOXRIGHT ]); + rootpv->y = FixedToFloat(rootbbox[BOXBOTTOM]); //ll rootpv++; WalkBSPNode(bspnum, rootp, NULL, rootbbox); -#ifdef DEBUG_HWBSP - i = SolveTProblem(); - CONS_Debug(DBG_RENDER, "%d point divides a polygon line\n",i); -#else SolveTProblem(); -#endif #ifdef DEBUG_HWBSP //debug debug.. diff --git a/src/hardware/hw_cache.cpp b/src/hardware/hw_cache.c similarity index 91% rename from src/hardware/hw_cache.cpp rename to src/hardware/hw_cache.c index c20d7e9bb..13354bda4 100644 --- a/src/hardware/hw_cache.cpp +++ b/src/hardware/hw_cache.c @@ -15,8 +15,6 @@ #ifdef HWRENDER -#include - #include "hw_main.h" #include "hw_glob.h" #include "hw_gl.h" @@ -100,7 +98,7 @@ static void HWR_DrawColumnInCache(const column_t *patchcol, UINT8 *block, GLMipm position = 0; } - position = std::max(((position * scale_y) + (FRACUNIT/2)) >> FRACBITS, 0); + position = max(((position * scale_y) + (FRACUNIT/2)) >> FRACBITS, 0); if (position + count >= pblockheight) count = pblockheight - position; @@ -164,7 +162,7 @@ static void HWR_DrawPatchInCache(GLMipmap_t *mipmap, fixed_t xfrac, xfracstep; fixed_t yfracstep, scale_y; const column_t *patchcol; - UINT8 *block = static_cast(mipmap->data); + UINT8 *block = (UINT8 *)(mipmap->data); INT32 bpp; INT32 blockmodulo; RGBA_t *palette; @@ -214,7 +212,7 @@ static void HWR_DrawTexturePatchInCache(GLMipmap_t *mipmap, fixed_t xfrac, xfracstep; fixed_t yfracstep, scale_y; const column_t *patchcol; - UINT8 *block = static_cast(mipmap->data); + UINT8 *block = (UINT8 *)(mipmap->data); INT32 bpp; INT32 blockmodulo; INT32 width, height; @@ -290,7 +288,7 @@ static UINT8 *MakeBlock(GLMipmap_t *glMipmap) INT32 blocksize = (glMipmap->width * glMipmap->height); bpp = format2bpp(glMipmap->format); - block = static_cast(Z_Malloc(blocksize*bpp, PU_HWRCACHE, &(glMipmap->data))); + block = (UINT8 *)(Z_Malloc(blocksize*bpp, PU_HWRCACHE, &(glMipmap->data))); switch (bpp) { @@ -327,7 +325,7 @@ static void HWR_GenerateTexture(INT32 texnum, GLMapTexture_t *gltex, boolean noe texture = textures[texnum]; gltex->mipmap.flags = TF_CHROMAKEYED | TF_WRAPXY; - gltex->mipmap.format = static_cast(textureformat); + gltex->mipmap.format = (GLTextureFormat_t)(textureformat); // hack the Legacy skies.. if (UNLIKELY(memcmp(texture->name, "SKY", 3) == 0 && @@ -346,7 +344,7 @@ static void HWR_GenerateTexture(INT32 texnum, GLMapTexture_t *gltex, boolean noe colormap += COLORMAP_REMAPOFFSET; #endif - gltex->mipmap.colormap = static_cast(Z_Calloc(sizeof(*gltex->mipmap.colormap), PU_HWRPATCHCOLMIPMAP, NULL)); + gltex->mipmap.colormap = (GLColormap_t *)(Z_Calloc(sizeof(*gltex->mipmap.colormap), PU_HWRPATCHCOLMIPMAP, NULL)); gltex->mipmap.colormap->source = colormap; memcpy(gltex->mipmap.colormap->data, colormap, 256 * sizeof(UINT8)); @@ -379,7 +377,7 @@ static void HWR_GenerateTexture(INT32 texnum, GLMapTexture_t *gltex, boolean noe // Composite the columns together. for (i = 0, patch = texture->patches; i < texture->patchcount; i++, patch++) { - pdata = static_cast(W_CacheLumpNumPwad(patch->wad, patch->lump, PU_LEVEL)); + pdata = (UINT8 *)(W_CacheLumpNumPwad(patch->wad, patch->lump, PU_LEVEL)); realpatch = (softwarepatch_t *)pdata; HWR_DrawTexturePatchInCache(&gltex->mipmap, blockwidth, blockheight, texture, patch, realpatch); @@ -415,7 +413,7 @@ void HWR_MakePatch(const patch_t *patch, GLPatch_t *glPatch, GLMipmap_t *glMipma glMipmap->flags = 0; // setup the texture info - glMipmap->format = static_cast(patchformat); + glMipmap->format = (GLTextureFormat_t)(patchformat); glPatch->max_s = (float)patch->width / (float)glMipmap->width; glPatch->max_t = (float)patch->height / (float)glMipmap->height; @@ -448,7 +446,7 @@ typedef struct } GLMapTextureSet_t; // idk i suck at naming things static size_t gl_numtextures = 0; // Texture count -static GLMapTextureSet_t *gl_textures; // For all textures +static GLMapTextureSet_t *gl_textures = NULL; // For all textures static void HWR_FreeTextureData(patch_t *patch) { @@ -457,7 +455,7 @@ static void HWR_FreeTextureData(patch_t *patch) if (!patch || !patch->hardware) return; - glPatch = static_cast(patch->hardware); + glPatch = (GLPatch_t *)(patch->hardware); if (vid.glstate == VID_GL_LIBRARY_LOADED) GL_DeleteTexture(glPatch->mipmap); @@ -473,7 +471,7 @@ void HWR_FreeTexture(patch_t *patch) if (patch->hardware) { - GLPatch_t *glPatch = static_cast(patch->hardware); + GLPatch_t *glPatch = (GLPatch_t *)(patch->hardware); HWR_FreeTextureColormaps(patch); @@ -499,7 +497,7 @@ static void HWR_FreeTextureColormaps(patch_t *patch) if (!patch) return; - pat = static_cast(patch->hardware); + pat = (GLPatch_t *)(patch->hardware); if (!pat) return; @@ -557,7 +555,8 @@ static void HWR_FreePatchCache(boolean freeall) callback = FreeColormapsCallback; //Z_IterateTags(PU_PATCH, PU_PATCH_ROTATED, callback); - Z_IterateTags(PU_PATCH, PU_PATCH, callback); + //Z_IterateTags(PU_PATCH, PU_PATCH_LOWPRIORITY, callback); // we dont really need to free low priority patches here as P_FreeLevelState takes care of them + Z_IterateTag(PU_PATCH, callback); Z_IterateTags(PU_SPRITE, PU_HUDGFX, callback); } @@ -572,7 +571,8 @@ void HWR_ClearAllTextures(void) /*static void HWR_FreeColormapCache(void) { HWR_FreePatchCache(false); -}*/ +} +*/ void HWR_InitMapTextures(void) { @@ -614,26 +614,36 @@ void HWR_FreeMapTextures(void) gl_numtextures = 0; } +#define NAME flatcheck +#define KEY_TY UINT32 +#define HASH_FN vt_hash_integer +#define CMPR_FN vt_cmpr_integer +#include "../verstable.h" + static void HWR_PrecacheLevelFlats(void) { // lookup for flats that may´ve been already loaded - // too lazy to make a hashtable or smth so unordered set will do :carbuncle: - std::unordered_set flatpresent; - lumpnum_t lump; - size_t i, j; + flatcheck flatpresent; + size_t i; +#if 0 + size_t j; +#endif INT32 k; - auto load_flat = [&](lumpnum_t lump, boolean noencoremap) + // this kinda messes up encore remapping behavior at times + // so just disable it for now ig +#ifdef GLENCORE + if (encoremap) { - // flat already loaded? - if (flatpresent.count(lump) == 0) - { - HWR_GetFlat(lump, noencoremap); - flatpresent.insert(lump); - } - }; + return; + } +#endif + + flatcheck_init(&flatpresent); + flatcheck_reserve(&flatpresent, numlevelflats); // special case for encore +#if 0 #ifdef GLENCORE if (encoremap) { @@ -649,22 +659,31 @@ static void HWR_PrecacheLevelFlats(void) const INT32 pic = ceiling ? sec->ceilingpic : sec->floorpic; const levelflat_t *levelflat = &levelflats[pic]; - lump = levelflat->lumpnum; - load_flat(lump, R_NoEncore(sec, ceiling)); + if (flatcheck_is_end(flatcheck_get(&flatpresent, levelflat->lumpnum))) + { + HWR_GetFlat(levelflat->lumpnum, R_NoEncore(sec, ceiling)); + flatcheck_insert(&flatpresent, levelflat->lumpnum); + } if (levelflat->speed) // is it an animated flat ? { // start from 0, occasionally basenumlump != flat->lumpnum for (k = 0; k < levelflat->numpics; k++) { - load_flat(levelflat->baselumpnum + k, R_NoEncore(sec, ceiling)); + lumpnum_t lump = levelflat->baselumpnum + k; + if (flatcheck_is_end(flatcheck_get(&flatpresent, lump))) + { + HWR_GetFlat(lump, R_NoEncore(sec, ceiling)); + flatcheck_insert(&flatpresent, lump); + } } } } } } else +#endif #endif { // on non encore we have it simple @@ -672,20 +691,30 @@ static void HWR_PrecacheLevelFlats(void) for (i = 0; i < numlevelflats; i++) { const levelflat_t *levelflat = &levelflats[i]; - lump = levelflat->lumpnum; - load_flat(lump, false); + if (flatcheck_is_end(flatcheck_get(&flatpresent, levelflat->lumpnum))) + { + HWR_GetFlat(levelflat->lumpnum, false); + flatcheck_insert(&flatpresent, levelflat->lumpnum); + } if (levelflat->speed) // is it an animated flat ? { // start from 0, occasionally basenumlump != flat->lumpnum for (k = 0; k < levelflat->numpics; k++) { - load_flat(levelflat->baselumpnum + k, false); + lumpnum_t lump = levelflat->baselumpnum + k; + if (flatcheck_is_end(flatcheck_get(&flatpresent, lump))) + { + HWR_GetFlat(lump, false); + flatcheck_insert(&flatpresent, lump); + } } } } } + + flatcheck_cleanup(&flatpresent); } static void HWR_PrecacheLevelTextures(void) @@ -695,7 +724,7 @@ static void HWR_PrecacheLevelTextures(void) size_t i, j, f; INT32 h; - texturepresent = static_cast(calloc(gl_numtextures, sizeof(*texturepresent))); + texturepresent = (char *)(calloc(gl_numtextures, sizeof(*texturepresent))); if (texturepresent == NULL) I_Error("%s: Out of memory looking up textures", "HWR_PrecacheLevel"); @@ -715,7 +744,7 @@ static void HWR_PrecacheLevelTextures(void) for (j = 0; j < 2; j++) { // check if single-sided linedef - if (line->sidenum[j] == 0xffff) + if (line->sidenum[j] == NO_INDEX) continue; const side_t *side = &sides[line->sidenum[j]]; @@ -870,7 +899,7 @@ void HWR_LoadMapTextures(size_t pnumtextures) HWR_FreeMapTextures(); gl_numtextures = pnumtextures; - gl_textures = static_cast(calloc(gl_numtextures, sizeof(*gl_textures))); // *2 - 1 for encore-remapped texture and another for noencore texture (unused when not in encore), see: GLMapTextureSet_t + gl_textures = (GLMapTextureSet_t *)(calloc(gl_numtextures, sizeof(*gl_textures))); // *2 - 1 for encore-remapped texture and another for noencore texture (unused when not in encore), see: GLMapTextureSet_t if (gl_textures == NULL) I_Error("HWR_LoadMapTextures: ran out of memory for OpenGL textures. Sad!"); @@ -967,7 +996,7 @@ static void HWR_CacheFlat(GLMipmap_t *glMipmap, lumpnum_t flatlumpnum) W_ReadLump(flatlumpnum, Z_Malloc(size, PU_HWRCACHE, &glMipmap->data)); #ifdef GLENCORE - flat = static_cast(glMipmap->data); + flat = (UINT8 *)(glMipmap->data); for (steppy = 0; steppy < size; steppy++) { if (flat[steppy] == HWR_PATCHES_CHROMAKEY_COLORINDEX) @@ -978,18 +1007,18 @@ static void HWR_CacheFlat(GLMipmap_t *glMipmap, lumpnum_t flatlumpnum) flat[steppy] = glMipmap->colormap->source[flat[steppy]]; } -#endif if (haschromakey) { const char *flatname = W_CheckNameForNum(flatlumpnum); // hack for gba rainbow roads cyan floors - if (UNLIKELY(memcmp(flatname, "GBA_RRF5", 8) == 0 && flatname[8] == 0)) + if (UNLIKELY(flatname && memcmp(flatname, "GBA_RRF5", 8) == 0 && flatname[8] == 0)) { glMipmap->flags &= ~TF_CHROMAKEYED; } } +#endif } // Download a Doom 'flat' to the hardware cache and make it ready for use @@ -1011,7 +1040,7 @@ void HWR_GetFlat(lumpnum_t flatlumpnum, boolean noencoremap) if (!noencoremap && encoremap) colormap += COLORMAP_REMAPOFFSET; #endif - glMipmap->colormap = static_cast(Z_Calloc(sizeof(*glMipmap->colormap), PU_HWRPATCHCOLMIPMAP, NULL)); + glMipmap->colormap = (GLColormap_t *)(Z_Calloc(sizeof(*glMipmap->colormap), PU_HWRPATCHCOLMIPMAP, NULL)); glMipmap->colormap->source = colormap; memcpy(glMipmap->colormap->data, colormap, 256 * sizeof(UINT8)); } @@ -1035,7 +1064,7 @@ void HWR_GetFlat(lumpnum_t flatlumpnum, boolean noencoremap) // --------------------+ static void HWR_LoadPatchMipmap(patch_t *patch, GLMipmap_t *glMipmap) { - GLPatch_t *glPatch = static_cast(patch->hardware); + GLPatch_t *glPatch = (GLPatch_t *)(patch->hardware); if (!glMipmap->downloaded) { @@ -1056,7 +1085,7 @@ static void HWR_LoadPatchMipmap(patch_t *patch, GLMipmap_t *glMipmap) // ----------------------+ static void HWR_UpdatePatchMipmap(patch_t *patch, GLMipmap_t *glMipmap) { - GLPatch_t *glPatch = static_cast(patch->hardware); + GLPatch_t *glPatch = (GLPatch_t *)(patch->hardware); HWR_MakePatch(patch, glPatch, glMipmap, true); // If hardware does not have the texture, then call GL_SetTexture to upload it @@ -1092,7 +1121,7 @@ void HWR_GetMappedPatch(patch_t *patch, const UINT8 *colormap) if (!patch->hardware) Patch_CreateGL(patch); - glPatch = static_cast(patch->hardware); + glPatch = (GLPatch_t *)(patch->hardware); // Blatant hack for encore colormapping aside... if (colormap == colormaps || colormap == NULL || colormap == (const UINT8*)(COLORMAP_REMAPOFFSET)) @@ -1116,7 +1145,9 @@ void HWR_GetMappedPatch(patch_t *patch, const UINT8 *colormap) HWR_UpdatePatchMipmap(patch, glMipmap); } else + { HWR_LoadPatchMipmap(patch, glMipmap); + } return; } @@ -1128,12 +1159,12 @@ void HWR_GetMappedPatch(patch_t *patch, const UINT8 *colormap) // (it have a liste of mipmap) // this malloc is cleared in HWR_FreeColormapCache // (...) unfortunately z_malloc fragment alot the memory :(so malloc is better - newMipmap = static_cast(calloc(1, sizeof (*newMipmap))); + newMipmap = (GLMipmap_t *)(calloc(1, sizeof (*newMipmap))); if (newMipmap == NULL) I_Error("%s: Out of memory", "HWR_GetMappedPatch"); glMipmap->nextcolormap = newMipmap; - newMipmap->colormap = static_cast(Z_Calloc(sizeof(*newMipmap->colormap), PU_HWRPATCHCOLMIPMAP, NULL)); + newMipmap->colormap = (GLColormap_t *)(Z_Calloc(sizeof(*newMipmap->colormap), PU_HWRPATCHCOLMIPMAP, NULL)); newMipmap->colormap->source = colormap; memcpy(newMipmap->colormap->data, colormap, 256 * sizeof(UINT8)); @@ -1156,7 +1187,7 @@ patch_t *HWR_GetCachedGLPatchPwad(UINT16 wadnum, UINT16 lumpnum) { void *ptr = Z_Calloc(sizeof(patch_t), PU_PATCH, &lumpcache[lumpnum]); Patch_Create(NULL, 0, ptr); - Patch_AllocateHardwarePatch(static_cast(ptr)); + Patch_AllocateHardwarePatch((patch_t *)(ptr)); } return (patch_t *)(lumpcache[lumpnum]); @@ -1173,7 +1204,7 @@ static void HWR_DrawFadeMaskInCache(GLMipmap_t *mipmap, INT32 pblockwidth, INT32 { INT32 i,j; fixed_t posx, posy, stepx, stepy; - UINT8 *block = static_cast(mipmap->data); // places the data directly into here + UINT8 *block = (UINT8 *)(mipmap->data); // places the data directly into here UINT8 *flat; UINT8 *dest, *src, texel; RGBA_t col; @@ -1298,6 +1329,7 @@ void HWR_SetPalette(RGBA_t *palette) crushed_palette[i].s.blue = (UINT8)(fblue / 31.0f * 255.0f); crushed_palette[i].s.alpha = 255; } + GL_SetScreenPalette(crushed_palette); } else @@ -1329,7 +1361,7 @@ void HWR_SetPalette(RGBA_t *palette) static void HWR_SetPaletteLookup(RGBA_t *palette) { int r, g, b; - UINT8 *lut = static_cast(Z_Malloc( + UINT8 *lut = (UINT8 *)(Z_Malloc( HWR_PALETTE_LUT_SIZE*HWR_PALETTE_LUT_SIZE*HWR_PALETTE_LUT_SIZE*sizeof(UINT8), PU_STATIC, NULL)); #define STEP_SIZE (256/HWR_PALETTE_LUT_SIZE) @@ -1374,7 +1406,8 @@ void HWR_SetMapPalette(void) if (palsize < 768) // 256 * 3 I_Error("HWR_SetMapPalette: A programmer assumed palette lumps are at least 768 bytes long, but apparently this was a wrong assumption!\n"); - RGB_data = static_cast(W_CacheLumpNum(lumpnum, PU_CACHE)); + RGB_data = (UINT8 *)(W_CacheLumpNum(lumpnum, PU_CACHE)); + // we got the RGB palette now, but we need it in RGBA format. for (i = 0; i < 256; i++) { @@ -1383,6 +1416,7 @@ void HWR_SetMapPalette(void) RGBA_converted[i].s.blue = *(RGB_data++); RGBA_converted[i].s.alpha = 255; } + palette = RGBA_converted; } @@ -1390,6 +1424,7 @@ void HWR_SetMapPalette(void) if (memcmp(mapPalette, palette, sizeof(mapPalette))) { memcpy(mapPalette, palette, sizeof(mapPalette)); + // in palette rendering mode, this means that all rgba textures now have wrong colors // and the lookup table is outdated HWR_SetPaletteLookup(mapPalette); @@ -1409,7 +1444,7 @@ static UINT32 HWR_CreateLightTable(UINT8 *lighttable) { UINT32 i, id; RGBA_t *palette = HWR_GetTexturePalette(); - RGBA_t *hw_lighttable = static_cast(Z_Malloc(256 * 32 * sizeof(RGBA_t), PU_STATIC, NULL)); + RGBA_t *hw_lighttable = (RGBA_t *)(Z_Malloc(256 * 32 * sizeof(RGBA_t), PU_STATIC, NULL)); // To make the palette index -> RGBA mapping easier for the shader, // the hardware lighttable is composed of RGBA colors instead of palette indices. diff --git a/src/hardware/hw_clip.c b/src/hardware/hw_clip.c index 3f9536436..68bbc98e3 100644 --- a/src/hardware/hw_clip.c +++ b/src/hardware/hw_clip.c @@ -319,23 +319,24 @@ angle_t gld_FrustumAngle(angle_t tiltangle) double clipfov; double floatangle; angle_t a1; - - float tilt = fabsf(((float)(int)tiltangle) / (float)ANG1); - - if (tilt > 90.0f) - tilt = 90.0f; + float tilt; // If the pitch is larger than this you can look all around at a FOV of 90 if (abs((signed)tiltangle) > 46 * ANG1) return 0xffffffff; + tilt = fabsf(((float)(int)tiltangle) / (float)ANG1); + + if (tilt > 90.0f) + tilt = 90.0f; + // ok, this is a gross hack that barely works... // but at least it doesn't overestimate too much... clipfov = atan(1 / (GLdouble)projMatrix[0]) * 360.0 / M_PI; floatangle = 2.0 + (45.0 + ((double)tilt / 1.9)) * clipfov / 90.0; if (floatangle >= 180.0) return 0xffffffff; - a1 = (angle_t)xs_CRoundToInt(ANG1 * floatangle); + a1 = (angle_t)lrint(ANG1 * floatangle); return a1; } diff --git a/src/hardware/hw_data.h b/src/hardware/hw_data.h index bb174b205..93ccfd4ac 100644 --- a/src/hardware/hw_data.h +++ b/src/hardware/hw_data.h @@ -54,7 +54,7 @@ struct GLMipmap_s UINT16 width, height; UINT32 downloaded; // The GPU has this texture. - struct GLMipmap_s *nextcolormap; + struct GLMipmap_s *nextcolormap; struct GLColormap_s *colormap; }; typedef struct GLMipmap_s GLMipmap_t; diff --git a/src/hardware/hw_defs.h b/src/hardware/hw_defs.h index 6a8649099..ed4bff5a2 100644 --- a/src/hardware/hw_defs.h +++ b/src/hardware/hw_defs.h @@ -96,7 +96,6 @@ typedef struct typedef struct { float x, y, z; - fixed_t x2, y2, z2; } polyvertex_t; // a convex 'plane' polygon, clockwise order diff --git a/src/hardware/hw_draw.c b/src/hardware/hw_draw.c index 4797f21de..981e54f0a 100644 --- a/src/hardware/hw_draw.c +++ b/src/hardware/hw_draw.c @@ -32,20 +32,6 @@ #include -typedef struct -{ - UINT8 id_field_length ; // 1 - UINT8 color_map_type ; // 2 - UINT8 image_type ; // 3 - UINT8 dummy[5] ; // 4, 8 - INT16 x_origin ; // 9, 10 - INT16 y_origin ; //11, 12 - INT16 width ; //13, 14 - INT16 height ; //15, 16 - UINT8 image_pix_size ; //17 - UINT8 image_descriptor; //18 -} ATTRPACK TGAHeader; // sizeof is 18 - static const UINT8 softwaretranstogl[11] = { 0, 25, 51, 76,102,127,153,178,204,229,255}; static const UINT8 softwaretranstogl_hi[11] = { 0, 51,102,153,204,255,255,255,255,255,255}; static const UINT8 softwaretranstogl_lo[11] = { 0, 12, 24, 36, 48, 60, 71, 83, 95,111,127}; @@ -57,8 +43,7 @@ void HWR_DrawStretchyFixedPatch(patch_t *gpatch, fixed_t x, fixed_t y, fixed_t p { FOutVector v[4]; FBITFIELD flags; - float cx = FIXED_TO_FLOAT(x); - float cy = FIXED_TO_FLOAT(y); + float cx, cy; UINT8 alphalevel = ((option & V_ALPHAMASK) >> V_ALPHASHIFT); UINT8 blendmode = ((bflags & V_BLENDMASK) >> V_BLENDSHIFT); GLPatch_t *hwrPatch; @@ -72,6 +57,9 @@ void HWR_DrawStretchyFixedPatch(patch_t *gpatch, fixed_t x, fixed_t y, fixed_t p if (alphalevel >= 10 && alphalevel < 13) return; + cx = FIXED_TO_FLOAT(x); + cy = FIXED_TO_FLOAT(y); + const float fvw = (float)vid.width; const float fvh = (float)vid.height; @@ -150,7 +138,7 @@ void HWR_DrawStretchyFixedPatch(patch_t *gpatch, fixed_t x, fixed_t y, fixed_t p if (!column->topdelta) { const UINT8 *source = (const UINT8 *)(column) + 3; - HWR_DrawFill(0, 0, BASEVIDWIDTH, BASEVIDHEIGHT, (column->topdelta == 0xff ? 31 : source[0])); + HWR_DrawFill(0, 0, BASEVIDWIDTH, BASEVIDHEIGHT, source[0]); } } @@ -222,7 +210,7 @@ void HWR_DrawStretchyFixedPatch(patch_t *gpatch, fixed_t x, fixed_t y, fixed_t p if (alphalevel) { - FSurfaceInfo Surf; + FSurfaceInfo Surf = {}; Surf.PolyColor.s.red = Surf.PolyColor.s.green = Surf.PolyColor.s.blue = 0xff; switch (alphalevel) @@ -244,8 +232,7 @@ void HWR_DrawCroppedPatch(patch_t *gpatch, fixed_t x, fixed_t y, fixed_t pscale, { FOutVector v[4]; FBITFIELD flags; - float cx = FIXED_TO_FLOAT(x); - float cy = FIXED_TO_FLOAT(y); + float cx, cy; UINT8 alphalevel = ((option & V_ALPHAMASK) >> V_ALPHASHIFT); GLPatch_t *hwrPatch; @@ -258,6 +245,9 @@ void HWR_DrawCroppedPatch(patch_t *gpatch, fixed_t x, fixed_t y, fixed_t pscale, if (alphalevel >= 10 && alphalevel < 13) return; + cx = FIXED_TO_FLOAT(x); + cy = FIXED_TO_FLOAT(y); + const float fvw = (float)vid.width; const float fvh = (float)vid.height; @@ -302,7 +292,7 @@ void HWR_DrawCroppedPatch(patch_t *gpatch, fixed_t x, fixed_t y, fixed_t pscale, if (!column->topdelta) { const UINT8 *source = (const UINT8 *)(column) + 3; - HWR_DrawFill(0, 0, BASEVIDWIDTH, BASEVIDHEIGHT, (column->topdelta == 0xff ? 31 : source[0])); + HWR_DrawFill(0, 0, BASEVIDWIDTH, BASEVIDHEIGHT, source[0]); } } @@ -385,7 +375,7 @@ void HWR_DrawCroppedPatch(patch_t *gpatch, fixed_t x, fixed_t y, fixed_t pscale, // clip it since it is used for bunny scroll in doom I if (alphalevel) { - FSurfaceInfo Surf; + FSurfaceInfo Surf = {}; Surf.PolyColor.s.red = Surf.PolyColor.s.green = Surf.PolyColor.s.blue = 0xff; switch (alphalevel) @@ -490,7 +480,7 @@ void HWR_DrawFlatFill(INT32 x, INT32 y, INT32 w, INT32 h, lumpnum_t flatlumpnum) void HWR_FadeScreenMenuBack(UINT16 color, UINT8 strength) { FOutVector v[4]; - FSurfaceInfo Surf; + FSurfaceInfo Surf = {}; FBITFIELD poly_flags = PF_NoTexture|PF_Modulated|PF_NoDepthTest; v[0].x = v[3].x = -1.0f; @@ -543,7 +533,7 @@ void HWR_FadeScreenMenuBack(UINT16 color, UINT8 strength) void HWR_DrawConsoleBack(UINT32 color, INT32 height) { FOutVector v[4]; - FSurfaceInfo Surf; + FSurfaceInfo Surf = {}; // setup some neat-o translucency effect if (!height) //cool hack 0 height is full height @@ -598,7 +588,7 @@ void HWR_drawAMline(const fline_t *fl, INT32 color) void HWR_DrawDiag(INT32 x, INT32 y, INT32 wh, INT32 color) { FOutVector v[4]; - FSurfaceInfo Surf; + FSurfaceInfo Surf = {}; float fx, fy, fw, fh, fwait = 0; RGBA_t *palette; @@ -702,7 +692,7 @@ void HWR_DrawDiag(INT32 x, INT32 y, INT32 wh, INT32 color) void HWR_DrawConsoleFill(INT32 x, INT32 y, INT32 w, INT32 h, UINT32 color, INT32 options) { FOutVector v[4]; - FSurfaceInfo Surf; + FSurfaceInfo Surf = {}; float fx, fy, fw, fh; if (w < 0 || h < 0) @@ -820,7 +810,7 @@ void HWR_DrawConsoleFill(INT32 x, INT32 y, INT32 w, INT32 h, UINT32 color, INT32 void HWR_DrawFill(INT32 x, INT32 y, INT32 w, INT32 h, INT32 color) { FOutVector v[4]; - FSurfaceInfo Surf; + FSurfaceInfo Surf = {}; float fx, fy, fw, fh; if (w < 0 || h < 0) @@ -964,6 +954,20 @@ void HWR_DrawFill(INT32 x, INT32 y, INT32 w, INT32 h, INT32 color) #endif #ifndef USE_PNG +typedef struct +{ + UINT8 id_field_length ; // 1 + UINT8 color_map_type ; // 2 + UINT8 image_type ; // 3 + UINT8 dummy[5] ; // 4, 8 + INT16 x_origin ; // 9, 10 + INT16 y_origin ; //11, 12 + INT16 width ; //13, 14 + INT16 height ; //15, 16 + UINT8 image_pix_size ; //17 + UINT8 image_descriptor; //18 +} ATTRPACK TGAHeader; // sizeof is 18 + // -------------------------------------------------------------------------- // save screenshots with TGA format // -------------------------------------------------------------------------- diff --git a/src/hardware/hw_gl.h b/src/hardware/hw_gl.h index 7e167485e..b808ed09a 100644 --- a/src/hardware/hw_gl.h +++ b/src/hardware/hw_gl.h @@ -32,8 +32,12 @@ void GL_SetSpecialState(hwdspecialstate_t IdState, INT32 Value); void GL_SetTransform(FTransform *stransform); void GL_SetBlend(FBITFIELD PolyFlags); void GL_SetPalette(RGBA_t *palette); + void GL_ClearBuffer(FBOOLEAN ColorMask, FBOOLEAN DepthMask, FBOOLEAN StencilMask, FRGBAFloat * ClearColor); +void GL_EnableStencilTest(void); +void GL_DisableStencilTest(void); + void GL_DrawPolygon(FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPts, FBITFIELD PolyFlags); void GL_DrawIndexedTriangles(FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPts, FBITFIELD PolyFlags, unsigned int *IndexArray); void GL_Draw2DLine(F2DCoord *v1, F2DCoord *v2, RGBA_t Color); @@ -63,7 +67,7 @@ void GL_FlushScreenTextures(void); void GL_DrawScreenTexture(int tex, FSurfaceInfo *surf, FBITFIELD polyflags); void GL_DoScreenWipe(int wipeStart, int wipeEnd); void GL_RenderVhsEffect(fixed_t upbary, fixed_t downbary, UINT8 updistort, UINT8 downdistort, UINT8 barsize); -void GL_DrawScreenFinalTexture(int tex, INT32 width, INT32 height, boolean useshader); +void GL_DrawScreenFinalTexture(int tex, INT32 width, INT32 height); void GL_PostImgRedraw(float points[SCREENVERTS][SCREENVERTS][2]); @@ -72,6 +76,7 @@ void GL_LoadShader(int slot, char *code, hwdshaderstage_t stage); boolean GL_CompileShader(int slot); void GL_SetShader(int slot); void GL_UnSetShader(void); +void GL_EnableShader(void); void GL_SetShaderInfo(hwdshaderinfo_t info, INT32 value); @@ -80,6 +85,9 @@ UINT32 GL_CreateLightTable(RGBA_t *hw_lighttable); void GL_ClearLightTables(void); void GL_SetScreenPalette(RGBA_t *palette); +void GL_Draw2DModel(model_t *model, INT32 frameIndex, INT32 duration, INT32 tics, INT32 nextFrameIndex, + FTransform *pos, float hscale, float vscale, UINT8 flipped, UINT8 hflipped, FSurfaceInfo *Surface); + #ifdef __cplusplus } // extern "C" #endif diff --git a/src/hardware/hw_glob.h b/src/hardware/hw_glob.h index e6b6734a5..0fd28dd4d 100644 --- a/src/hardware/hw_glob.h +++ b/src/hardware/hw_glob.h @@ -34,8 +34,8 @@ typedef struct gl_vissprite_s float gz, gzt; float tz; float scale; - float spritexscale, spriteyscale; - float spritexoffset, spriteyoffset; + //float spritexscale, spriteyscale; + //float spritexoffset, spriteyoffset; patch_t *gpatch; boolean flip; UINT8 translucency; //alpha level 0-255 @@ -54,7 +54,7 @@ void HWR_ObjectLightLevelPost(gl_vissprite_t *spr, const sector_t *sector, INT32 // -------- extern extrasubsector_t *extrasubsectors; #ifdef PARANOIA -extern size_t addsubsector; +extern size_t num_extra_subsector; #endif void HWR_FreeExtraSubsectors(void); diff --git a/src/hardware/hw_main.cpp b/src/hardware/hw_main.cpp index 9f1a90769..ad5137eaa 100644 --- a/src/hardware/hw_main.cpp +++ b/src/hardware/hw_main.cpp @@ -14,6 +14,7 @@ #ifdef HWRENDER #include +#include #include "../doomstat.h" #include "../doomdef.h" @@ -83,11 +84,6 @@ float gl_viewsin = 0.0f, gl_viewcos = 0.0f; static float gl_viewludsin, gl_viewludcos; static angle_t gl_aimingangle; -static float yaw = 0.0f; -static float inv_yaw = 0.0f; -static float cos_inv_yaw = 0.0f; -static float sin_inv_yaw = 0.0f; - static constexpr float deg2radians = (M_PIf / 180.0f); seg_t *gl_curline = NULL; @@ -100,7 +96,8 @@ sector_t *gl_backsector = NULL; static constexpr float clipping_distances[] = {1024.0f, 2048.0f, 4096.0f, 6144.0f, 8192.0f, 12288.0f, 16384.0f}; // values for bsp culling // slightly higher than the far clipping plane to compensate for impreciseness -static constexpr INT32 bsp_culling_distances[] = {(1024+512)*FRACUNIT, (2048+512)*FRACUNIT, (4096+512)*FRACUNIT, +static constexpr INT32 bsp_culling_distances[] = { + (1024+512)*FRACUNIT, (2048+512)*FRACUNIT, (4096+512)*FRACUNIT, (6144+512)*FRACUNIT, (8192+512)*FRACUNIT, (12288+512)*FRACUNIT, (16384+512)*FRACUNIT}; // Performance stats @@ -240,7 +237,6 @@ consvar_t cv_glportals = {"gr_portals", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, consvar_t cv_glpaletterendering = {"gr_paletteshader", "Off", CV_CALL|CV_SAVE, CV_OnOff, CV_glpaletterendering_OnChange, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_glpalettedepth = {"gr_palettedepth", "16 bits", CV_SAVE|CV_CALL, glpalettedepth_cons_t, CV_glpalettedepth_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_glflashpal = {"gr_flashpal", "On", CV_CALL|CV_SAVE, CV_OnOff, CV_glpaletterendering_OnChange, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_gltexturedepth = {"gr_texturedepth", "32 bits", CV_CALL|CV_SAVE, gltexdepth_cons_t, CV_gltextureformat_OnChange, 0, NULL, NULL, 0, 0, NULL}; @@ -253,11 +249,11 @@ static void CV_screentextures_OnChange(void) { if (cv_glpaletterendering.value != 0) CV_SetValue(&cv_glpaletterendering, 0); - #ifdef USE_FBO_OGL if (cv_glframebuffer.value != 0) CV_SetValue(&cv_glframebuffer, 0); #endif + intermissionbginit = false; } GL_SetSpecialState(HWD_SET_SCREEN_TEXTURES, cv_glscreentextures.value); M_UpdateOGLMenu(); @@ -274,6 +270,7 @@ static void CV_glframebuffer_OnChange(void) I_DownSample(); RefreshOGLSDLSurface(); M_UpdateOGLMenu(); + intermissionbginit = false; } #endif @@ -387,11 +384,11 @@ void HWR_ObjectLightLevelPost(gl_vissprite_t *spr, const sector_t *sector, INT32 extralight = FixedMul(extralight, std::min(std::max(0, *lightlevel), 255) * FRACUNIT / 255); // simple OGL approximation - fixed_t tr = R_QuickCamDist(spr->mobj->x, spr->mobj->y); - fixed_t xscale = FixedDiv((vid.width / 2) << FRACBITS, tr); + const fixed_t tr = R_QuickCamDist(spr->mobj->x, spr->mobj->y); + const fixed_t xscale = FixedDiv((vid.width / 2) << FRACBITS, tr); // Less change in contrast at further distances, to counteract DOOM diminished light - fixed_t n = FixedDiv(FixedMul(xscale, LIGHTRESOLUTIONFIX), ((MAXLIGHTSCALE-1) << LIGHTSCALESHIFT)); + const fixed_t n = FixedDiv(FixedMul(xscale, LIGHTRESOLUTIONFIX), ((MAXLIGHTSCALE-1) << LIGHTSCALESHIFT)); extralight = FixedMul(extralight, std::min(n, FRACUNIT)); // Contrast is stronger for normal sprites, stronger than wall lighting is at the same distance @@ -509,15 +506,15 @@ static FUINT HWR_CalcWallLight(FUINT lightnum, seg_t *seg, extracolormap_t *colo { INT16 finallight = lightnum; - if (cv_glfakecontrast.value == 0 || (HWR_ShouldUsePaletteRendering() && colormap)) + if (cv_glfakecontrast.value == 0 || (colormap && HWR_ShouldUsePaletteRendering())) return (FUINT)finallight; if (seg != NULL && P_ApplyLightOffsetFine(lightnum, seg->frontsector)) { - INT16 offset = (cv_glfakecontrast.value == 2) ? seg->hwLightOffset : ((INT16)seg->lightOffset * 8); + const INT16 offset = (cv_glfakecontrast.value == 2) ? seg->hwLightOffset : ((INT16)seg->lightOffset * 8); finallight += offset; - finallight = CLAMP(finallight, 0 , 255); + finallight = CLAMP(finallight, 0, 255); } return (FUINT)finallight; @@ -532,10 +529,10 @@ static FUINT HWR_CalcSlopeLight(FUINT lightnum, pslope_t *slope, const sector_t if (slope != NULL && sector != NULL && P_ApplyLightOffsetFine(lightnum, sector)) { - INT16 offset = (cv_glfakecontrast.value == 2) ? slope->hwLightOffset : ((INT16)slope->lightOffset * 8); + const INT16 offset = (cv_glfakecontrast.value == 2) ? slope->hwLightOffset : ((INT16)slope->lightOffset * 8); finallight += (fof ? -offset : offset); - finallight = CLAMP(finallight, 0 , 255); + finallight = CLAMP(finallight, 0, 255); } return (FUINT)finallight; @@ -549,7 +546,7 @@ static FUINT HWR_CalcSlopeLight(FUINT lightnum, pslope_t *slope, const sector_t // Render a floor or ceiling convex polygon static void HWR_RenderPlane(subsector_t *subsector, extrasubsector_t *xsub, boolean isceiling, fixed_t fixedheight, FBITFIELD PolyFlags, INT32 lightlevel, lumpnum_t lumpnum, sector_t *FOFsector, UINT8 alpha, extracolormap_t *planecolormap) { - FSurfaceInfo Surf; + FSurfaceInfo Surf = {}; FOutVector *v3d; polyvertex_t *pv; pslope_t *slope = NULL; @@ -586,15 +583,11 @@ static void HWR_RenderPlane(subsector_t *subsector, extrasubsector_t *xsub, bool const sector_t *sec = FOFsector ? FOFsector : gl_frontsector; // Get the slope pointer to simplify future code - if (sec->f_slope && !isceiling) + if (!isceiling && sec->f_slope) slope = sec->f_slope; - else if (sec->c_slope && isceiling) + else if (isceiling && sec->c_slope) slope = sec->c_slope; - // Set fixedheight to the slope's height from our viewpoint, if we have a slope - if (slope) - fixedheight = P_GetSlopeZAt(slope, viewx, viewy); - height = FixedToFloat(fixedheight); // Allocate plane-vertex buffer if we need to @@ -686,18 +679,19 @@ static void HWR_RenderPlane(subsector_t *subsector, extrasubsector_t *xsub, bool vert->s = (tempxsow * cosangf) - (tempytow * sinangf);\ vert->t = (tempxsow * sinangf) + (tempytow * cosangf);\ }\ +\ + if (slope)\ + {\ + fixedheight = P_GetSlopeZAt(slope, FloatToFixed((vx)), FloatToFixed((vy)));\ + height = FixedToFloat(fixedheight);\ + }\ \ vert->x = (vx);\ vert->y = height;\ vert->z = (vy);\ \ - if (slope)\ - {\ - fixedheight = P_GetSlopeZAt(slope, FloatToFixed((vx)), FloatToFixed((vy)));\ - vert->y = FixedToFloat(fixedheight);\ - }\ } - for (i = 0, v3d = planeVerts; i < (INT32)nrPlaneVerts; i++,v3d++,pv++) + for (i = 0, v3d = planeVerts; i < (INT32)nrPlaneVerts; i++, v3d++, pv++) SETUP3DVERT(v3d, pv->x, pv->y); if (slope) @@ -1002,8 +996,9 @@ static void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum, const fixed_t v2y = FloatToFixed(wallVerts[1].z); const UINT8 alpha = Surf->PolyColor.s.alpha; - FUINT lightnum = HWR_CalcWallLight(sector->lightlevel, gl_curline, NULL); + FUINT lightnum = sector->lightlevel; extracolormap_t *colormap = NULL; + lightnum = HWR_CalcWallLight(lightnum, gl_curline, NULL); realtop = top = wallVerts[3].y; realbot = bot = wallVerts[0].y; @@ -1072,22 +1067,22 @@ static void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum, else solid = false; - height = FixedToFloat(P_GetLightZAt(&list[i], v1x, v1y)); - endheight = FixedToFloat(P_GetLightZAt(&list[i], v2x, v2y)); - if (solid) { + height = FixedToFloat(P_GetLightZAt(&list[i], v1x, v1y)); + endheight = FixedToFloat(P_GetLightZAt(&list[i], v2x, v2y)); + bheight = FixedToFloat(P_GetFFloorBottomZAt(list[i].caster, v1x, v1y)); endbheight = FixedToFloat(P_GetFFloorBottomZAt(list[i].caster, v2x, v2y)); - } - if (endheight >= endtop && height >= top) - { - if (solid && top > bheight) - top = bheight; + if (endheight >= endtop && height >= top) + { + if (top > bheight) + top = bheight; - if (solid && endtop > endbheight) - endtop = endbheight; + if (endtop > endbheight) + endtop = endbheight; + } } if (i + 1 < sector->numlights) @@ -1106,8 +1101,8 @@ static void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum, // Found a break // The heights are clamped to ensure the polygon doesn't cross itself. - bot = std::max(bheight, realbot); - endbot = std::max(endbheight, endrealbot); + bot = std::min(std::max(bheight, realbot), top); + endbot = std::min(std::max(endbheight, endrealbot), endtop); Surf->PolyColor.s.alpha = alpha; @@ -1168,7 +1163,6 @@ static void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum, static FOutVector* skyWallVertexArray = NULL; static int skyWallVertexArraySize = 0; -static int skyWallVertexArrayAllocSize = 65536;// what a mouthful static boolean gl_collect_skywalls = false; @@ -1179,13 +1173,14 @@ static void HWR_SkyWallList_Clear(void) static void HWR_SkyWallList_Add(FOutVector *wallVerts) { + static int skyWallVertexArrayAllocSize = 65536; // what a mouthful + if (!skyWallVertexArray) { // array has not been allocated yet. allocate it now skyWallVertexArray = static_cast(Z_Malloc(sizeof(FOutVector) * 4 * skyWallVertexArrayAllocSize, PU_STATIC, NULL)); } - - if (skyWallVertexArraySize == skyWallVertexArrayAllocSize) + else if (skyWallVertexArraySize >= skyWallVertexArrayAllocSize) { // allocated array got full, allocate more space skyWallVertexArrayAllocSize *= 2; @@ -1223,7 +1218,7 @@ static void HWR_DrawSkyWall(FOutVector *wallVerts, FSurfaceInfo *Surf) wallVerts[0].s = wallVerts[3].s = 0; wallVerts[2].s = wallVerts[1].s = 0; - if (UNLIKELY(gl_collect_skywalls)) + if (gl_collect_skywalls) { HWR_SkyWallList_Add(wallVerts); } @@ -1232,6 +1227,7 @@ static void HWR_DrawSkyWall(FOutVector *wallVerts, FSurfaceInfo *Surf) HWR_SetCurrentTexture(NULL); HWR_ProjectWall(wallVerts, Surf, PF_Invisible|PF_NoTexture|PF_Skydecal, 255, NULL); } + // PF_Invisible so it's not drawn into the colour buffer // PF_NoTexture for no texture // PF_Occlude is set in HWR_ProjectWall to draw into the depth buffer @@ -1377,10 +1373,9 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom extracolormap_t *colormap = gl_frontsector->extra_colormap; lightnum = HWR_CalcWallLight(lightnum, gl_curline, colormap); - FSurfaceInfo Surf; + FSurfaceInfo Surf = {}; - if (gl_frontsector) - Surf.PolyColor.s.alpha = 255; + Surf.PolyColor.s.alpha = 255; const INT32 gl_midtexture = R_GetTextureNum(gl_sidedef->midtexture); GLMapTexture_t *glTex = NULL; @@ -1404,11 +1399,12 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom // Sky Ceilings wallVerts[3].y = wallVerts[2].y = FLOATMAX; - auto draw_sky_walls = [&](int vert1, int vert2, fixed_t world, fixed_t worldslope) + auto draw_sky_walls = [] + (int vert1, int vert2, fixed_t world, fixed_t worldslope, auto& wwallVerts, auto& sSurf) FUNCINLINE { - wallVerts[vert1].y = FixedToFloat(world); - wallVerts[vert2].y = FixedToFloat(worldslope); - HWR_DrawSkyWall(wallVerts, &Surf); + wwallVerts[vert1].y = FixedToFloat(world); + wwallVerts[vert2].y = FixedToFloat(worldslope); + HWR_DrawSkyWall(wwallVerts, &sSurf); }; if (gl_frontsector->ceilingpic == skyflatnum) @@ -1421,19 +1417,24 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom && (worldhigh != worldtop || worldhighslope != worldtopslope)) // Removing the second line above will render more rarely visible skywalls. Example: Cave garden ceiling in Dark race { - draw_sky_walls(0, 1, worldhigh, worldhighslope); + draw_sky_walls(0, 1, worldhigh, worldhighslope, wallVerts, Surf); } + + // hack to allow height changes in outdoor areas + // This is what gets rid of the upper textures if there should be sky + worldtop = worldhigh; + worldtopslope = worldhighslope; } else { // Only the frontsector is sky, just draw a skywall from the front ceiling - draw_sky_walls(0, 1, worldtop, worldtopslope); + draw_sky_walls(0, 1, worldtop, worldtopslope, wallVerts, Surf); } } else if (gl_backsector->ceilingpic == skyflatnum) { // Only the backsector is sky, just draw a skywall from the front ceiling - draw_sky_walls(0, 1, worldtop, worldtopslope); + draw_sky_walls(0, 1, worldtop, worldtopslope, wallVerts, Surf); } // Sky Floors @@ -1451,31 +1452,22 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom // Removing the second line above will render more rarely visible skywalls. Example: Cave garden ceiling in Dark race && !(gl_sidedef->bottomtexture)) { - draw_sky_walls(3, 2, worldlow, worldlowslope); + draw_sky_walls(3, 2, worldlow, worldlowslope, wallVerts, Surf); } } else { // Only the backsector has sky, just draw a skywall from the back floor - draw_sky_walls(3, 2, worldbottom, worldbottomslope); + draw_sky_walls(3, 2, worldbottom, worldbottomslope, wallVerts, Surf); } } else if ((gl_backsector->floorpic == skyflatnum) && !(gl_sidedef->bottomtexture)) { // Only the backsector has sky, just draw a skywall from the back floor if there's no bottomtexture - draw_sky_walls(3, 2, worldlow, worldlowslope); + draw_sky_walls(3, 2, worldlow, worldlowslope, wallVerts, Surf); } } - // hack to allow height changes in outdoor areas - // This is what gets rid of the upper textures if there should be sky - if (gl_frontsector->ceilingpic == skyflatnum - && gl_backsector->ceilingpic == skyflatnum) - { - worldtop = worldhigh; - worldtopslope = worldhighslope; - } - gl_toptexture = R_GetTextureNum(gl_sidedef->toptexture); // check TOP TEXTURE @@ -1784,10 +1776,10 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom // Single sided line... Deal only with the middletexture (if one exists) if (gl_midtexture && gl_linedef->special != HORIZONSPECIAL) // Ignore horizon line for OGL { - glTex = HWR_GetTexture(gl_midtexture, noencore); - fixed_t texturevpeg; + glTex = HWR_GetTexture(gl_midtexture, noencore); + // PEGGING if ((gl_linedef->flags & (ML_DONTPEGBOTTOM|ML_EFFECT2)) == (ML_DONTPEGBOTTOM|ML_EFFECT2)) texturevpeg = gl_frontsector->floorheight + textureheight[gl_sidedef->midtexture] - gl_frontsector->ceilingheight + gl_sidedef->rowoffset; @@ -1860,6 +1852,7 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom HWR_DrawSkyWall(wallVerts, &Surf); } + if (gl_frontsector->floorpic == skyflatnum) { wallVerts[3].y = FixedToFloat(worldbottom); @@ -1874,40 +1867,38 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom //Hurdler: 3d-floors test if (!gl_drawing_stencil && gl_backsector && gl_frontsector->tag != gl_backsector->tag && (gl_backsector->ffloors || gl_frontsector->ffloors)) { - ffloor_t * rover; - fixed_t highcut = 0, lowcut = 0; + fixed_t highcut = 0, lowcut = 0; fixed_t lowcutslope = 0, highcutslope = 0; - // Used for height comparisons and etc across FOFs and slopes - fixed_t high1, highslope1, low1, lowslope1; - - INT32 texnum; - lowcut = std::max(worldbottom, worldlow); highcut = std::min(worldtop, worldhigh); lowcutslope = std::max(worldbottomslope, worldlowslope); highcutslope = std::min(worldtopslope, worldhighslope); - if (gl_backsector->ffloors) + auto process_ffloors = [&](boolean backsec) FUNCINLINE { - for (rover = gl_backsector->ffloors; rover; rover = rover->next) + ffloor_t *rover; + INT32 texnum; + + // Used for height comparisons and etc across FOFs and slopes + fixed_t high1, highslope1, low1, lowslope1; + fixed_t high2, highslope2, low2, lowslope2; + + // i suck at naming stuff lul + sector_t* main_sector = backsec ? gl_backsector : gl_frontsector; + sector_t* other_sector = backsec ? gl_frontsector : gl_backsector; + + for (rover = main_sector->ffloors; rover; rover = rover->next) { - boolean bothsides = false; - // Skip if it exists on both sectors. - ffloor_t * r2; - for (r2 = gl_frontsector->ffloors; r2; r2 = r2->next) - if (rover->master == r2->master) - { - bothsides = true; - break; - } - - if (bothsides) - continue; - const ffloortype_e roverflags = rover->flags; - if (!(roverflags & FF_EXISTS) || !(roverflags & FF_RENDERSIDES) || (roverflags & FF_INVERTSIDES)) + if (!(roverflags & FF_EXISTS) || !(roverflags & FF_RENDERSIDES)) + continue; + + if (backsec && (roverflags & FF_INVERTSIDES)) + continue; + + if (!backsec && !(roverflags & FF_ALLSIDES)) continue; SLOPEPARAMS(*rover->t_slope, high1, highslope1, *rover->topheight) @@ -1916,14 +1907,53 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom if ((high1 < lowcut || highslope1 < lowcutslope) || (low1 > highcut || lowslope1 > highcutslope)) continue; - side_t *side = R_GetFFloorSide(gl_curline->linedef, rover, gl_backsector); + ffloor_t * r2; + for (r2 = other_sector->ffloors; r2; r2 = r2->next) + { + if (r2->master == rover->master) // Skip if same control line. + break; + + const ffloortype_e r2flags = r2->flags; + + if (!(r2flags & FF_EXISTS) || !(r2flags & FF_RENDERSIDES)) + continue; + + if (rover->flags & FF_EXTRA) + { + if (!(r2flags & FF_CUTEXTRA)) + continue; + + if (r2flags & FF_EXTRA && (r2flags & (FF_TRANSLUCENT|FF_FOG)) != (rover->flags & (FF_TRANSLUCENT|FF_FOG))) + continue; + } + else + { + if (!(r2flags & FF_CUTSOLIDS)) + continue; + } + + SLOPEPARAMS(*r2->t_slope, high2, highslope2, *r2->topheight) + SLOPEPARAMS(*r2->b_slope, low2, lowslope2, *r2->bottomheight) + + if ((high2 < lowcut || highslope2 < lowcutslope) || (low2 > highcut || lowslope2 > highcutslope)) + continue; + if ((high1 > high2 || highslope1 > highslope2) || (low1 < low2 || lowslope1 < lowslope2)) + continue; + + break; + } + + if (r2) + continue; + + const side_t *side = R_GetFFloorSide(gl_curline->linedef, rover, main_sector); boolean do_texture_skew; boolean dont_peg_bottom; if (rover->master->flags & ML_TFERLINE) { - line_t *newline = R_GetFFloorLine(gl_curline->linedef, rover, gl_backsector); + const line_t *newline = R_GetFFloorLine(gl_curline->linedef, rover, main_sector); do_texture_skew = newline->flags & ML_DONTPEGTOP; dont_peg_bottom = newline->flags & ML_DONTPEGBOTTOM; } @@ -1946,6 +1976,7 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom h = highcut; hS = highcutslope; } + if (l <= lowcut && lS <= lowcutslope) { l = lowcut; @@ -2015,13 +2046,12 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom lightnum = rover->master->frontsector->lightlevel; colormap = rover->master->frontsector->extra_colormap; + lightnum = HWR_CalcWallLight(lightnum, gl_curline, colormap); Surf.PolyColor.s.alpha = HWR_FogBlockAlpha(lightnum, colormap); - lightnum = HWR_CalcWallLight(lightnum, gl_curline, colormap); - - if (gl_frontsector->numlights) - HWR_SplitWall(gl_frontsector, wallVerts, 0, false, &Surf, roverflags, rover, blendmode); + if (other_sector->numlights) + HWR_SplitWall(other_sector, wallVerts, 0, false, &Surf, roverflags, rover, blendmode); else HWR_AddTransparentWall(wallVerts, &Surf, 0, false, blendmode, true, lightnum, colormap); } @@ -2035,8 +2065,8 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom Surf.PolyColor.s.alpha = CLAMP(rover->alpha, 0, 255); } - if (gl_frontsector->numlights) - HWR_SplitWall(gl_frontsector, wallVerts, texnum, noencore, &Surf, roverflags, rover, blendmode); + if (other_sector->numlights) + HWR_SplitWall(other_sector, wallVerts, texnum, noencore, &Surf, roverflags, rover, blendmode); else { if (blendmode != PF_Masked) @@ -2046,166 +2076,16 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom } } } + }; + + if (gl_backsector->ffloors) + { + process_ffloors(true); } if (gl_frontsector->ffloors) // Putting this seperate should allow 2 FOF sectors to be connected without too many errors? I think? { - for (rover = gl_frontsector->ffloors; rover; rover = rover->next) - { - boolean bothsides = false; - // Skip if it exists on both sectors. - ffloor_t * r2; - for (r2 = gl_backsector->ffloors; r2; r2 = r2->next) - if (rover->master == r2->master) - { - bothsides = true; - break; - } - - if (bothsides) - continue; - - const ffloortype_e roverflags = rover->flags; - - if (!(roverflags & FF_EXISTS) || !(roverflags & FF_RENDERSIDES) || !(roverflags & FF_ALLSIDES)) - continue; - - SLOPEPARAMS(*rover->t_slope, high1, highslope1, *rover->topheight) - SLOPEPARAMS(*rover->b_slope, low1, lowslope1, *rover->bottomheight) - - if ((high1 < lowcut || highslope1 < lowcutslope) || (low1 > highcut || lowslope1 > highcutslope)) - continue; - - side_t *side = R_GetFFloorSide(gl_curline->linedef, rover, gl_backsector); - - boolean do_texture_skew; - boolean dont_peg_bottom; - - if (rover->master->flags & ML_TFERLINE) - { - line_t *newline = R_GetFFloorLine(gl_curline->linedef, rover, gl_backsector); - do_texture_skew = newline->flags & ML_DONTPEGTOP; - dont_peg_bottom = newline->flags & ML_DONTPEGBOTTOM; - } - else - { - do_texture_skew = rover->master->flags & ML_DONTPEGTOP; - dont_peg_bottom = gl_curline->linedef->flags & ML_DONTPEGBOTTOM; - } - - texnum = R_GetTextureNum(side->midtexture); - - h = P_GetFFloorTopZAt (rover, v1x, v1y); - hS = P_GetFFloorTopZAt (rover, v2x, v2y); - l = P_GetFFloorBottomZAt(rover, v1x, v1y); - lS = P_GetFFloorBottomZAt(rover, v2x, v2y); - - // Adjust the heights so the FOF does not overlap with top and bottom textures. - if (h >= highcut && hS >= highcutslope) - { - h = highcut; - hS = highcutslope; - } - if (l <= lowcut && lS <= lowcutslope) - { - l = lowcut; - lS = lowcutslope; - } - - //Hurdler: HW code starts here - //FIXME: check if peging is correct - // set top/bottom coords - - wallVerts[3].y = FixedToFloat(h); - wallVerts[2].y = FixedToFloat(hS); - wallVerts[0].y = FixedToFloat(l); - wallVerts[1].y = FixedToFloat(lS); - - if (roverflags & FF_FOG) - { - wallVerts[3].t = wallVerts[2].t = 0; - wallVerts[0].t = wallVerts[1].t = 0; - wallVerts[0].s = wallVerts[3].s = 0; - wallVerts[2].s = wallVerts[1].s = 0; - } - else - { - // Wow, how was this missing from OpenGL for so long? - // ...Oh well, anyway, Lower Unpegged now changes pegging of FOFs like in software - // -- Monster Iestyn 26/06/18 - fixed_t texturevpeg = side->rowoffset; - - glTex = HWR_GetTexture(texnum, noencore); - - if (!do_texture_skew) // no skewing - { - if (dont_peg_bottom) - texturevpeg -= (*rover->topheight - *rover->bottomheight); - - wallVerts[3].t = static_cast((*rover->topheight - h) + texturevpeg) * glTex->scaleY; - wallVerts[2].t = static_cast((*rover->topheight - hS) + texturevpeg) * glTex->scaleY; - wallVerts[0].t = static_cast((*rover->topheight - l) + texturevpeg) * glTex->scaleY; - wallVerts[1].t = static_cast((*rover->topheight - lS) + texturevpeg) * glTex->scaleY; - } - else - { - if (!dont_peg_bottom) // skew by top - { - wallVerts[3].t = wallVerts[2].t = (static_cast(texturevpeg) * glTex->scaleY); - wallVerts[0].t = static_cast((h - l) + texturevpeg) * glTex->scaleY; - wallVerts[1].t = static_cast((hS - lS) + texturevpeg) * glTex->scaleY; - } - else // skew by bottom - { - wallVerts[0].t = wallVerts[1].t = (static_cast(texturevpeg) * glTex->scaleY); - wallVerts[3].t = wallVerts[0].t - static_cast(h - l) * glTex->scaleY; - wallVerts[2].t = wallVerts[1].t - static_cast(hS - lS) * glTex->scaleY; - } - } - - wallVerts[0].s = wallVerts[3].s = cliplow * glTex->scaleX; - wallVerts[2].s = wallVerts[1].s = cliphigh * glTex->scaleX; - } - - FBITFIELD blendmode; - - if (roverflags & FF_FOG) - { - blendmode = PF_Fog|PF_NoTexture; - - lightnum = rover->master->frontsector->lightlevel; - colormap = rover->master->frontsector->extra_colormap; - - Surf.PolyColor.s.alpha = HWR_FogBlockAlpha(lightnum, colormap); - - lightnum = HWR_CalcWallLight(lightnum, gl_curline, colormap); - - if (gl_backsector->numlights) - HWR_SplitWall(gl_backsector, wallVerts, 0, false, &Surf, roverflags, rover, blendmode); - else - HWR_AddTransparentWall(wallVerts, &Surf, 0, false, blendmode, true, lightnum, colormap); - } - else - { - blendmode = PF_Masked; - - if ((roverflags & FF_TRANSLUCENT && rover->alpha < 256) || rover->blend) - { - blendmode = rover->blend ? HWR_GetBlendModeFlag(rover->blend) : static_cast(PF_Translucent); - Surf.PolyColor.s.alpha = CLAMP(rover->alpha, 0, 255); - } - - if (gl_backsector->numlights) - HWR_SplitWall(gl_backsector, wallVerts, texnum, noencore, &Surf, roverflags, rover, blendmode); - else - { - if (blendmode != PF_Masked) - HWR_AddTransparentWall(wallVerts, &Surf, texnum, noencore, blendmode, false, lightnum, colormap); - else - HWR_ProjectWall(wallVerts, &Surf, PF_Masked, lightnum, colormap); - } - } - } + process_ffloors(false); } } #undef SLOPEPARAMS @@ -2214,7 +2094,7 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom static inline boolean HWR_UsePortals(void) { - return supportstencil && cv_glportals.value && gl_maphasportals; + return supportstencil && gl_maphasportals && cv_glportals.value; } // From PrBoom: @@ -2358,7 +2238,8 @@ static inline void DoAddLine(seg_t* line, angle_t angle1, angle_t angle2) // SoM: Backsector needs to be run through R_FakeFlat static sector_t tempsec; - auto do_addline = [&](bool dontdraw) { + auto do_addline = [&](bool dontdraw) FUNCINLINE + { // Single sided line? if (!line->backsector) { @@ -2425,7 +2306,7 @@ static inline void DoAddLine(seg_t* line, angle_t angle1, angle_t angle2) // Find the other side! INT32 line2 = P_FindSpecialLineFromTag(PORTALSPECIAL, line->linedef->tag, -1); - if (line->linedef == &lines[line2]) + if (line2 >= 0 && line->linedef == &lines[line2]) line2 = P_FindSpecialLineFromTag(PORTALSPECIAL, line->linedef->tag, line2); if (line2 >= 0) // found it! @@ -2437,7 +2318,7 @@ static inline void DoAddLine(seg_t* line, angle_t angle1, angle_t angle2) } } else - return;// dont do anything with the other side i guess? + return; // dont do anything with the other side i guess? } doaddline: @@ -2457,11 +2338,11 @@ static void HWR_AddLine(seg_t *line) gl_curline = line; - v1x = gl_curline->v1->x; - v1y = gl_curline->v1->y; + v1x = line->v1->x; + v1y = line->v1->y; - v2x = gl_curline->v2->x; - v2y = gl_curline->v2->y; + v2x = line->v2->x; + v2y = line->v2->y; // OPTIMIZE: quickly reject orthogonal back sides. angle1 = R_PointToAngle64(v1x, v1y); @@ -2497,6 +2378,7 @@ static boolean HWR_CheckBBox(const fixed_t *bspcoord) { fixed_t px1, py1, px2, py2; angle_t angle1, angle2; + const INT32* check; // Find the corners of the box // that define the edges from current viewpoint. @@ -2508,10 +2390,12 @@ static boolean HWR_CheckBBox(const fixed_t *bspcoord) if (boxpos == 5) return true; - px1 = bspcoord[checkcoord[boxpos][0]]; - py1 = bspcoord[checkcoord[boxpos][1]]; - px2 = bspcoord[checkcoord[boxpos][2]]; - py2 = bspcoord[checkcoord[boxpos][3]]; + check = checkcoord[boxpos]; + + px1 = bspcoord[check[0]]; + py1 = bspcoord[check[1]]; + px2 = bspcoord[check[2]]; + py2 = bspcoord[check[3]]; if (current_bsp_culling_distance) { @@ -2585,7 +2469,6 @@ static boolean HWR_CheckBBox(const fixed_t *bspcoord) return gld_clipper_SafeCheckRange(angle2, angle1); } - // // HWR_AddPolyObjectSegs // @@ -2625,8 +2508,8 @@ static void HWR_RenderPolyObjectPlane(polyobj_t *polysector, boolean isceiling, float scrollx = 0.0f, scrolly = 0.0f; float anglef = 0.0f, cosangf = 0.0f, sinangf = 0.0f; angle_t angle = 0; - FSurfaceInfo Surf; - fixed_t tempxsow, tempytow; + FSurfaceInfo Surf = {}; + float tempxsow, tempytow; size_t nrPlaneVerts; static FOutVector *planeVerts = NULL; @@ -2639,14 +2522,6 @@ static void HWR_RenderPolyObjectPlane(polyobj_t *polysector, boolean isceiling, if (nrPlaneVerts < 3) // not even a triangle ? return; - if (nrPlaneVerts > INT16_MAX) // FIXME: exceeds plVerts size - { - CONS_Debug(DBG_RENDER, "polygon size of %s exceeds max value of %d vertices\n", sizeu1(nrPlaneVerts), UINT16_MAX); - return; - } - - const sector_t *sec = FOFsector ? FOFsector : gl_frontsector; - // Allocate plane-vertex buffer if we need to if (!planeVerts || nrPlaneVerts > numAllocedPlaneVerts) { @@ -2655,6 +2530,8 @@ static void HWR_RenderPolyObjectPlane(polyobj_t *polysector, boolean isceiling, Z_Malloc(numAllocedPlaneVerts * sizeof(FOutVector), PU_LEVEL, &planeVerts); } + const sector_t *sec = FOFsector ? FOFsector : gl_frontsector; + height = FixedToFloat(fixedheight); len = W_LumpLength(lumpnum); @@ -2777,57 +2654,61 @@ static void HWR_AddPolyObjectPlanes(void) for (i = 0; i < numpolys; i++) { - polyobjsector = po_ptrs[i]->lines[0]->backsector; // the in-level polyobject sector - if (!(po_ptrs[i]->flags & POF_RENDERPLANES)) // Only render planes when you should continue; if (po_ptrs[i]->translucency >= NUMTRANSMAPS) continue; - if (polyobjsector->floorheight <= gl_frontsector->ceilingheight - && polyobjsector->floorheight >= gl_frontsector->floorheight - && (viewz < polyobjsector->floorheight)) + polyobjsector = po_ptrs[i]->lines[0]->backsector; // the in-level polyobject sector + + if (polyobjsector->floorheight <= gl_frontsector->ceilingheight && + polyobjsector->floorheight >= gl_frontsector->floorheight && + (viewz < polyobjsector->floorheight)) { light = R_GetPlaneLight(gl_frontsector, polyobjsector->floorheight, true); + const INT16 llevel = (light == -1 ? gl_frontsector->lightlevel : *gl_frontsector->lightlist[light].lightlevel); + extracolormap_t *colmap = (light == -1 ? gl_frontsector->extra_colormap : gl_frontsector->lightlist[light].extra_colormap); + if (po_ptrs[i]->translucency > 0) { - FSurfaceInfo Surf; + FSurfaceInfo Surf = {}; FBITFIELD blendmode; - memset(&Surf, 0x00, sizeof(Surf)); blendmode = HWR_TranstableToAlpha(po_ptrs[i]->translucency, &Surf); HWR_AddTransparentPolyobjectFloor(levelflats[polyobjsector->floorpic].lumpnum, po_ptrs[i], false, polyobjsector->floorheight, - (light == -1 ? gl_frontsector->lightlevel : *gl_frontsector->lightlist[light].lightlevel), Surf.PolyColor.s.alpha, polyobjsector, blendmode, (light == -1 ? gl_frontsector->extra_colormap : gl_frontsector->lightlist[light].extra_colormap)); + llevel, Surf.PolyColor.s.alpha, polyobjsector, blendmode, colmap); } else { HWR_GetFlat(levelflats[polyobjsector->floorpic].lumpnum, R_NoEncore(polyobjsector, false)); HWR_RenderPolyObjectPlane(po_ptrs[i], false, polyobjsector->floorheight, PF_Occlude, - (light == -1 ? gl_frontsector->lightlevel : *gl_frontsector->lightlist[light].lightlevel), levelflats[polyobjsector->floorpic].lumpnum, - polyobjsector, 255, (light == -1 ? gl_frontsector->extra_colormap : gl_frontsector->lightlist[light].extra_colormap)); + llevel, levelflats[polyobjsector->floorpic].lumpnum, + polyobjsector, 255, colmap); } } - if (polyobjsector->ceilingheight >= gl_frontsector->floorheight - && polyobjsector->ceilingheight <= gl_frontsector->ceilingheight - && (viewz > polyobjsector->ceilingheight)) + if (polyobjsector->ceilingheight >= gl_frontsector->floorheight && + polyobjsector->ceilingheight <= gl_frontsector->ceilingheight && + (viewz > polyobjsector->ceilingheight)) { light = R_GetPlaneLight(gl_frontsector, polyobjsector->ceilingheight, true); + const INT16 llevel = (light == -1 ? gl_frontsector->lightlevel : *gl_frontsector->lightlist[light].lightlevel); + extracolormap_t *colmap = (light == -1 ? gl_frontsector->extra_colormap : gl_frontsector->lightlist[light].extra_colormap); + if (po_ptrs[i]->translucency > 0) { - FSurfaceInfo Surf; + FSurfaceInfo Surf = {}; FBITFIELD blendmode; - memset(&Surf, 0x00, sizeof(Surf)); blendmode = HWR_TranstableToAlpha(po_ptrs[i]->translucency, &Surf); HWR_AddTransparentPolyobjectFloor(levelflats[polyobjsector->ceilingpic].lumpnum, po_ptrs[i], true, polyobjsector->ceilingheight, - (light == -1 ? gl_frontsector->lightlevel : *gl_frontsector->lightlist[light].lightlevel), Surf.PolyColor.s.alpha, polyobjsector, blendmode, (light == -1 ? gl_frontsector->extra_colormap : gl_frontsector->lightlist[light].extra_colormap)); + llevel, Surf.PolyColor.s.alpha, polyobjsector, blendmode, colmap); } else { HWR_GetFlat(levelflats[polyobjsector->ceilingpic].lumpnum, R_NoEncore(polyobjsector, true)); HWR_RenderPolyObjectPlane(po_ptrs[i], true, polyobjsector->ceilingheight, PF_Occlude, - (light == -1 ? gl_frontsector->lightlevel : *gl_frontsector->lightlist[light].lightlevel), levelflats[polyobjsector->ceilingpic].lumpnum, - polyobjsector, 255, (light == -1 ? gl_frontsector->extra_colormap : gl_frontsector->lightlist[light].extra_colormap)); + llevel, levelflats[polyobjsector->ceilingpic].lumpnum, + polyobjsector, 255, colmap); } } } @@ -2894,7 +2775,7 @@ static void HWR_Subsector(size_t num) static sector_t tempsec; //SoM: 4/7/2000 INT32 floorlightlevel; INT32 ceilinglightlevel; - INT32 locFloorHeight, locCeilingHeight; + INT32 locFloorHeight = 0, locCeilingHeight = 0; INT32 cullFloorHeight, cullCeilingHeight; INT32 light = 0; extracolormap_t *floorcolormap; @@ -2902,9 +2783,9 @@ static void HWR_Subsector(size_t num) ffloor_t *rover; #ifdef PARANOIA // no risk while developing, enough debugging nights! - if (num >= addsubsector) + if (num >= num_extra_subsector) I_Error("HWR_Subsector: ss %s with numss = %s, addss = %s\n", - sizeu1(num), sizeu2(numsubsectors), sizeu3(addsubsector)); + sizeu1(num), sizeu2(numsubsectors), sizeu3(num_extra_subsector)); #endif if (num < numsubsectors) @@ -2938,32 +2819,30 @@ static void HWR_Subsector(size_t num) floorcolormap = ceilingcolormap = gl_frontsector->extra_colormap; - cullFloorHeight = P_GetSectorFloorZAt (gl_frontsector, viewx, viewy); - cullCeilingHeight = P_GetSectorCeilingZAt(gl_frontsector, viewx, viewy); - locFloorHeight = P_GetSectorFloorZAt (gl_frontsector, gl_frontsector->soundorg.x, gl_frontsector->soundorg.y); - locCeilingHeight = P_GetSectorCeilingZAt(gl_frontsector, gl_frontsector->soundorg.x, gl_frontsector->soundorg.y); - if (gl_frontsector->ffloors) { + locFloorHeight = P_GetSectorFloorZAt (gl_frontsector, gl_frontsector->soundorg.x, gl_frontsector->soundorg.y); + locCeilingHeight = P_GetSectorCeilingZAt(gl_frontsector, gl_frontsector->soundorg.x, gl_frontsector->soundorg.y); + boolean anyMoved = gl_frontsector->moved; if (anyMoved == false) { - for (rover = gl_frontsector->ffloors; rover; rover = rover->next) + if (sub->validcount != validcount) { - if (!(rover->flags & FF_EXISTS) || !(rover->flags & FF_RENDERPLANES)) - continue; + for (rover = gl_frontsector->ffloors; rover; rover = rover->next) + { + if (!(rover->flags & FF_EXISTS) || !(rover->flags & FF_RENDERPLANES)) + continue; - if (sub->validcount == validcount) - continue; + const sector_t *controlSec = §ors[rover->secnum]; - const sector_t *controlSec = §ors[rover->secnum]; + if (controlSec->moved != true) + continue; - if (controlSec->moved != true) - continue; - - anyMoved = true; - break; + anyMoved = true; + break; + } } } @@ -2989,151 +2868,134 @@ static void HWR_Subsector(size_t num) sub->sector->extra_colormap = gl_frontsector->extra_colormap; - // render floor ? - // yeah, easy backface cull! :) - if (cullFloorHeight < viewz) + if (sub->validcount != validcount) { if (gl_frontsector->floorpic != skyflatnum) { - if (sub->validcount != validcount) + cullFloorHeight = P_GetSectorFloorZAt(gl_frontsector, viewx, viewy); + + // render floor ? + // yeah, easy backface cull! :) + if (cullFloorHeight < viewz) { HWR_GetFlat(levelflats[gl_frontsector->floorpic].lumpnum, R_NoEncore(gl_frontsector, false)); HWR_RenderPlane(sub, &extrasubsectors[num], false, - // Hack to make things continue to work around slopes. - locFloorHeight == cullFloorHeight ? locFloorHeight : gl_frontsector->floorheight, + gl_frontsector->floorheight, // We now return you to your regularly scheduled rendering. PF_Occlude, floorlightlevel, levelflats[gl_frontsector->floorpic].lumpnum, NULL, 255, floorcolormap); } } - } - if (cullCeilingHeight > viewz) - { if (gl_frontsector->ceilingpic != skyflatnum) { - if (sub->validcount != validcount) + cullCeilingHeight = P_GetSectorCeilingZAt(gl_frontsector, viewx, viewy); + + if (cullCeilingHeight > viewz) { HWR_GetFlat(levelflats[gl_frontsector->ceilingpic].lumpnum, R_NoEncore(gl_frontsector, true)); HWR_RenderPlane(sub, &extrasubsectors[num], true, - // Hack to make things continue to work around slopes. - locCeilingHeight == cullCeilingHeight ? locCeilingHeight : gl_frontsector->ceilingheight, + gl_frontsector->ceilingheight, // We now return you to your regularly scheduled rendering. PF_Occlude, ceilinglightlevel, levelflats[gl_frontsector->ceilingpic].lumpnum, NULL, 255, ceilingcolormap); } } - } - if (gl_frontsector->ffloors) - { - /// \todo fix light, xoffs, yoffs, extracolormap ? - for (rover = gl_frontsector->ffloors; rover; rover = rover->next) + if (gl_frontsector->ffloors) { - fixed_t bottomCullHeight, topCullHeight, centerHeight; - - if (!(rover->flags & FF_EXISTS) || !(rover->flags & FF_RENDERPLANES) || !(rover->flags & FF_RENDERALL)) - continue; - if (sub->validcount == validcount) - continue; - - // rendering heights for bottom and top planes - // yes there were functions for this stuff, no idea why it wasnt used but bleh - bottomCullHeight = P_GetFFloorBottomZAt(rover, viewx, viewy); - topCullHeight = P_GetFFloorTopZAt(rover, viewx, viewy); - - if (gl_frontsector->cullheight) + /// \todo fix light, xoffs, yoffs, extracolormap ? + for (rover = gl_frontsector->ffloors; rover; rover = rover->next) { - if (HWR_DoCulling(gl_frontsector->cullheight, viewsector->cullheight, gl_viewz, FixedToFloat(*rover->bottomheight), FixedToFloat(*rover->topheight))) + fixed_t bottomCullHeight, topCullHeight, centerHeight; + + if (!(rover->flags & FF_EXISTS) || !(rover->flags & FF_RENDERPLANES) || !(rover->flags & FF_RENDERALL)) continue; - } - // bottom plane - centerHeight = P_GetFFloorBottomZAt(rover, gl_frontsector->soundorg.x, gl_frontsector->soundorg.y); - - if (centerHeight <= locCeilingHeight && centerHeight >= locFloorHeight && - ((viewz < bottomCullHeight && !(rover->flags & FF_INVERTPLANES)) || - (viewz > bottomCullHeight && (rover->flags & FF_BOTHPLANES || rover->flags & FF_INVERTPLANES)))) - { - if (rover->flags & FF_FOG) + if (gl_frontsector->cullheight) { - UINT8 alpha; - - light = R_GetPlaneLight(gl_frontsector, centerHeight, (viewz < bottomCullHeight)); - - alpha = HWR_FogBlockAlpha(*gl_frontsector->lightlist[light].lightlevel, rover->master->frontsector->extra_colormap); - - HWR_AddTransparentFloor(0, - &extrasubsectors[num], - false, - *rover->bottomheight, - *gl_frontsector->lightlist[light].lightlevel, - alpha, rover->master->frontsector, PF_Fog|PF_NoTexture, - true, rover->master->frontsector->extra_colormap); + if (HWR_DoCulling(gl_frontsector->cullheight, viewsector->cullheight, gl_viewz, FixedToFloat(*rover->bottomheight), FixedToFloat(*rover->topheight))) + continue; } - else if ((rover->flags & FF_TRANSLUCENT && rover->alpha < 256) || rover->blend) // SoM: Flags are more efficient - { - light = R_GetPlaneLight(gl_frontsector, centerHeight, (viewz < bottomCullHeight)); - HWR_AddTransparentFloor(levelflats[*rover->bottompic].lumpnum, - &extrasubsectors[num], - false, - *rover->bottomheight, - *gl_frontsector->lightlist[light].lightlevel, - CLAMP(rover->alpha, 0 ,255), rover->master->frontsector, HWR_RippleBlend(gl_frontsector, rover, false) | (rover->blend ? HWR_GetBlendModeFlag(rover->blend) : static_cast(PF_Translucent)), - false, gl_frontsector->lightlist[light].extra_colormap); + auto render_fof_plane = [&](boolean bottom, boolean underside) FUNCINLINE + { + fixed_t roverheight; + lumpnum_t flatlump; + + if (bottom) + { + roverheight = *rover->bottomheight; + flatlump = levelflats[*rover->bottompic].lumpnum; + } + else + { + roverheight = *rover->topheight; + flatlump = levelflats[*rover->toppic].lumpnum; + } + + if (rover->flags & FF_FOG) + { + UINT8 alpha; + + light = R_GetPlaneLight(gl_frontsector, centerHeight, underside); + + alpha = HWR_FogBlockAlpha(*gl_frontsector->lightlist[light].lightlevel, rover->master->frontsector->extra_colormap); + + HWR_AddTransparentFloor(0, + &extrasubsectors[num], + !bottom, + roverheight, + *gl_frontsector->lightlist[light].lightlevel, + alpha, rover->master->frontsector, PF_Fog|PF_NoTexture, + true, rover->master->frontsector->extra_colormap); + } + else if ((rover->flags & FF_TRANSLUCENT && rover->alpha < 256) || rover->blend) // SoM: Flags are more efficient + { + light = R_GetPlaneLight(gl_frontsector, centerHeight, underside); + + HWR_AddTransparentFloor(flatlump, + &extrasubsectors[num], + !bottom, + roverheight, + *gl_frontsector->lightlist[light].lightlevel, + CLAMP(rover->alpha, 0, 255), rover->master->frontsector, HWR_RippleBlend(gl_frontsector, rover, false) | (rover->blend ? HWR_GetBlendModeFlag(rover->blend) : static_cast(PF_Translucent)), + false, gl_frontsector->lightlist[light].extra_colormap); + } + else + { + HWR_GetFlat(flatlump, R_NoEncore(gl_frontsector, !bottom)); + light = R_GetPlaneLight(gl_frontsector, centerHeight, underside); + + HWR_RenderPlane(sub, &extrasubsectors[num], !bottom, roverheight, HWR_RippleBlend(gl_frontsector, rover, false)|PF_Occlude, *gl_frontsector->lightlist[light].lightlevel, flatlump, + rover->master->frontsector, 255, gl_frontsector->lightlist[light].extra_colormap); + } + }; + + // bottom plane + centerHeight = P_GetFFloorBottomZAt(rover, gl_frontsector->soundorg.x, gl_frontsector->soundorg.y); + + if (centerHeight <= locCeilingHeight && centerHeight >= locFloorHeight) + { + bottomCullHeight = P_GetFFloorBottomZAt(rover, viewx, viewy); + + if ((viewz < bottomCullHeight && !(rover->flags & FF_INVERTPLANES)) || + (viewz > bottomCullHeight && (rover->flags & FF_BOTHPLANES || rover->flags & FF_INVERTPLANES))) + { + render_fof_plane(true, (viewz < bottomCullHeight)); + } } - else + + // top plane + centerHeight = P_GetFFloorTopZAt(rover, gl_frontsector->soundorg.x, gl_frontsector->soundorg.y); + + if (centerHeight >= locFloorHeight && centerHeight <= locCeilingHeight) { - HWR_GetFlat(levelflats[*rover->bottompic].lumpnum, R_NoEncore(gl_frontsector, false)); - light = R_GetPlaneLight(gl_frontsector, centerHeight, (viewz < bottomCullHeight)); + topCullHeight = P_GetFFloorTopZAt(rover, viewx, viewy); - HWR_RenderPlane(sub, &extrasubsectors[num], false, *rover->bottomheight, HWR_RippleBlend(gl_frontsector, rover, false)|PF_Occlude, *gl_frontsector->lightlist[light].lightlevel, levelflats[*rover->bottompic].lumpnum, - rover->master->frontsector, 255, gl_frontsector->lightlist[light].extra_colormap); - } - } - - // top plane - centerHeight = P_GetFFloorTopZAt(rover, gl_frontsector->soundorg.x, gl_frontsector->soundorg.y); - - if (centerHeight >= locFloorHeight && - centerHeight <= locCeilingHeight && - ((viewz > topCullHeight && !(rover->flags & FF_INVERTPLANES)) || - (viewz < topCullHeight && (rover->flags & FF_BOTHPLANES || rover->flags & FF_INVERTPLANES)))) - { - if (rover->flags & FF_FOG) - { - UINT8 alpha; - - light = R_GetPlaneLight(gl_frontsector, centerHeight, (viewz < topCullHeight)); - - alpha = HWR_FogBlockAlpha(*gl_frontsector->lightlist[light].lightlevel, rover->master->frontsector->extra_colormap); - - HWR_AddTransparentFloor(0, - &extrasubsectors[num], - true, - *rover->topheight, - *gl_frontsector->lightlist[light].lightlevel, - alpha, rover->master->frontsector, PF_Fog|PF_NoTexture, - true, rover->master->frontsector->extra_colormap); - } - else if ((rover->flags & FF_TRANSLUCENT && rover->alpha < 256) || rover->blend) - { - light = R_GetPlaneLight(gl_frontsector, centerHeight, (viewz < topCullHeight)); - - HWR_AddTransparentFloor(levelflats[*rover->toppic].lumpnum, - &extrasubsectors[num], - true, - *rover->topheight, - *gl_frontsector->lightlist[light].lightlevel, - CLAMP(rover->alpha, 0 ,255), rover->master->frontsector, HWR_RippleBlend(gl_frontsector, rover, false) | (rover->blend ? HWR_GetBlendModeFlag(rover->blend) : static_cast(PF_Translucent)), - false, gl_frontsector->lightlist[light].extra_colormap); - } - else - { - HWR_GetFlat(levelflats[*rover->toppic].lumpnum, R_NoEncore(gl_frontsector, true)); - light = R_GetPlaneLight(gl_frontsector, centerHeight, (viewz < topCullHeight)); - - HWR_RenderPlane(sub, &extrasubsectors[num], true, *rover->topheight, HWR_RippleBlend(gl_frontsector, rover, false)|PF_Occlude, *gl_frontsector->lightlist[light].lightlevel, levelflats[*rover->toppic].lumpnum, - rover->master->frontsector, 255, gl_frontsector->lightlist[light].extra_colormap); + if ((viewz > topCullHeight && !(rover->flags & FF_INVERTPLANES)) || + (viewz < topCullHeight && (rover->flags & FF_BOTHPLANES || rover->flags & FF_INVERTPLANES))) + { + render_fof_plane(false, (viewz < topCullHeight)); + } } } } @@ -3176,15 +3038,12 @@ doaddline: // hurdler: false: we only add the sprites, the walls are drawn first if (line) { - if (sub->sector->validcount != validcount) - { - // draw sprites first, coz they are clipped to the solidsegs of - // subsectors more 'in front' - if (cv_drawdist.value || current_bsp_culling_distance) - HWR_AddSprites(gl_frontsector); - else - HWR_AddSprites(gl_frontsector); - } + // draw sprites first, coz they are clipped to the solidsegs of + // subsectors more 'in front' + if (cv_drawdist.value || current_bsp_culling_distance) + HWR_AddSprites(gl_frontsector); + else + HWR_AddSprites(gl_frontsector); //Hurdler: at this point validcount must be the same, but is not because // gl_frontsector doesn't point anymore to sub->sector due to @@ -3194,11 +3053,11 @@ doaddline: // without talking about the overdraw of course. sub->sector->validcount = validcount;/// \todo fix that in a better way - if (UNLIKELY(numpolys)) + if (UNLIKELY(sub->polyList)) { while (count--) { - if (LIKELY(!line->polyseg)) // ignore segs that belong to polyobjects + if (!line->polyseg) // ignore segs that belong to polyobjects { HWR_AddLine(line); } @@ -3370,7 +3229,7 @@ static void HWR_DrawSpriteShadow(gl_vissprite_t *spr, patch_t *gpatch, GLPatch_t { float this_scale = 1.0f; FOutVector swallVerts[4]; - FSurfaceInfo sSurf; + FSurfaceInfo sSurf = {}; FBITFIELD blendmode = 0; fixed_t floorheight, mobjfloor; pslope_t *floorslope; @@ -3380,6 +3239,18 @@ static void HWR_DrawSpriteShadow(gl_vissprite_t *spr, patch_t *gpatch, GLPatch_t if (!spr->mobj) return; + // Ceiling scenery have no shadow. + if ((spr->mobj->flags & (MF_SCENERY|MF_SPAWNCEILING|MF_NOGRAVITY)) == (MF_SCENERY|MF_SPAWNCEILING|MF_NOGRAVITY)) + return; + + // Debris have no corona or shadow. + if (spr->mobj->flags2 & MF2_DEBRIS) + return; + + // Without this, your shadow shows on the floor, even after you die and fall through the ground. + if (spr->mobj->z < spr->mobj->floorz) + return; + R_GetShadowZ(spr->mobj, &floorslope); mobjfloor = HWR_OpaqueFloorAtPos( @@ -3606,7 +3477,7 @@ static void HWR_SplitSprite(gl_vissprite_t *spr, const boolean papersprite) FOutVector baseWallVerts[4]; // This is what the verts should end up as patch_t *gpatch; GLPatch_t *hwrpatch; - FSurfaceInfo Surf; + FSurfaceInfo Surf = {}; extracolormap_t *colormap; INT32 lightlevel; boolean lightset = true; @@ -3628,6 +3499,8 @@ static void HWR_SplitSprite(gl_vissprite_t *spr, const boolean papersprite) fixed_t v1x, v1y, v2x, v2y; INT32 shader = SHADER_NONE; + const boolean billboarding = (cv_glspritebillboarding.value && !cv_glshearing.value && !papersprite); + gpatch = spr->gpatch; // cache the patch in the graphics card memory @@ -3635,13 +3508,10 @@ static void HWR_SplitSprite(gl_vissprite_t *spr, const boolean papersprite) //Hurdler: 25/04/2000: now support colormap in hardware mode HWR_GetMappedPatch(gpatch, spr->colormap); - hwrpatch = ((GLPatch_t *)gpatch->hardware); + hwrpatch = static_cast(gpatch->hardware); // Draw shadow BEFORE sprite - if (UNLIKELY(cv_shadow.value // Shadows enabled - && (sprmo->flags & (MF_SCENERY|MF_SPAWNCEILING|MF_NOGRAVITY)) != (MF_SCENERY|MF_SPAWNCEILING|MF_NOGRAVITY) // Ceiling scenery have no shadow. - && !(sprmo->flags2 & MF2_DEBRIS) // Debris have no corona or shadow. - && (sprmo->z >= sprmo->floorz))) // Without this, your shadow shows on the floor, even after you die and fall through the ground. + if (UNLIKELY(cv_shadow.value)) { //////////////////// // SHADOW SPRITE! // @@ -3733,8 +3603,15 @@ static void HWR_SplitSprite(gl_vissprite_t *spr, const boolean papersprite) blend = HWR_GetBlendModeFlag(blendmode)|PF_Occlude; } - if (cv_playerfade.value && sprmo->player) - Surf.PolyColor.s.alpha = FixedMul(R_DoPlayerFade(sprmo), Surf.PolyColor.s.alpha); + if (sprmo->player) + { + // make hyu´d players translucent with reducevfx, could be done better, but im lazy as crap + if (cv_reducevfx.value && sprmo->player->kartstuff[k_hyudorotimer] > 0) + Surf.PolyColor.s.alpha = static_cast(FixedMul(FRACUNIT/2, static_cast(Surf.PolyColor.s.alpha))); + + if (cv_playerfade.value) + Surf.PolyColor.s.alpha = static_cast(FixedMul(R_DoPlayerFade(sprmo), static_cast(Surf.PolyColor.s.alpha))); + } if (HWR_UseShader()) { @@ -3756,7 +3633,7 @@ static void HWR_SplitSprite(gl_vissprite_t *spr, const boolean papersprite) { const fixed_t h = P_GetLightZAt(§or->lightlist[i], sprmo->x, sprmo->y); - if (!(h <= temp)) + if (h > temp) continue; if (!lightset) @@ -3804,8 +3681,8 @@ static void HWR_SplitSprite(gl_vissprite_t *spr, const boolean papersprite) // Found a break // The heights are clamped to ensure the polygon doesn't cross itself. - bot = std::max(bheight, realbot); - endbot = std::max(endbheight, endrealbot); + bot = std::clamp(bheight, realbot, top); + endbot = std::clamp(endbheight, endrealbot, endtop); wallVerts[3].t = towtop + ((realtop - top) * towmult); wallVerts[2].t = towtop + ((endrealtop - endtop) * towmult); @@ -3818,7 +3695,7 @@ static void HWR_SplitSprite(gl_vissprite_t *spr, const boolean papersprite) wallVerts[1].y = endbot; // The x and y only need to be adjusted in the case that it's not a papersprite - if (cv_glspritebillboarding.value && sprmo && !papersprite) + if (billboarding) { // Get the x and z of the vertices so billboarding draws correctly realheight = realbot - realtop; @@ -3840,11 +3717,11 @@ static void HWR_SplitSprite(gl_vissprite_t *spr, const boolean papersprite) wallVerts[1].z = baseWallVerts[2].z + (baseWallVerts[2].z - baseWallVerts[1].z) * heightmult; } - HWR_Lighting(&Surf, lightlevel, colormap, P_SectorUsesDirectionalLighting(sector) && !(sprmo->frame & FF_FULLBRIGHT)); + HWR_Lighting(&Surf, lightlevel, colormap, P_SectorUsesDirectionalLighting(sector) && !R_ThingIsFullBright(sprmo)); Surf.PolyColor.s.alpha = alpha; - HWR_ProcessPolygon(&Surf, wallVerts, 4, blend|PF_Modulated, shader, false); // sprite shader + HWR_ProcessPolygon(&Surf, wallVerts, 4, blend|PF_Modulated, shader, false); top = bot; endtop = endbot; @@ -3871,7 +3748,7 @@ static void HWR_SplitSprite(gl_vissprite_t *spr, const boolean papersprite) Surf.PolyColor.s.alpha = alpha; - HWR_ProcessPolygon(&Surf, wallVerts, 4, blend|PF_Modulated, shader, false); // sprite shader + HWR_ProcessPolygon(&Surf, wallVerts, 4, blend|PF_Modulated, shader, false); } // -----------------+ @@ -3884,17 +3761,17 @@ static void HWR_DrawSprite(gl_vissprite_t *spr) FOutVector wallVerts[4]; patch_t *gpatch; // sprite patch converted to hardware GLPatch_t *hwrpatch; - FSurfaceInfo Surf; + FSurfaceInfo Surf = {}; FBITFIELD blend = 0; INT32 shader = SHADER_NONE; mobj_t *sprmo = spr->mobj; - if (UNLIKELY(!sprmo->subsector)) + if (!sprmo->subsector) return; - const boolean papersprite = (sprmo->frame & FF_PAPERSPRITE); + const boolean papersprite = R_ThingIsPaperSprite(sprmo); const sector_t *sector = sprmo->subsector->sector; if (sector->numlights) @@ -3916,7 +3793,7 @@ static void HWR_DrawSprite(gl_vissprite_t *spr) //Hurdler: 25/04/2000: now support colormap in hardware mode HWR_GetMappedPatch(gpatch, spr->colormap); - hwrpatch = ((GLPatch_t *)gpatch->hardware); + hwrpatch = static_cast(gpatch->hardware); // create the sprite billboard // @@ -3960,10 +3837,7 @@ static void HWR_DrawSprite(gl_vissprite_t *spr) } // Draw shadow BEFORE sprite - if (UNLIKELY(cv_shadow.value // Shadows enabled - && (sprmo->flags & (MF_SCENERY|MF_SPAWNCEILING|MF_NOGRAVITY)) != (MF_SCENERY|MF_SPAWNCEILING|MF_NOGRAVITY) // Ceiling scenery have no shadow. - && !(sprmo->flags2 & MF2_DEBRIS) // Debris have no corona or shadow. - && (sprmo->z >= sprmo->floorz))) // Without this, your shadow shows on the floor, even after you die and fall through the ground. + if (UNLIKELY(cv_shadow.value)) { //////////////////// // SHADOW SPRITE! // @@ -4023,8 +3897,15 @@ static void HWR_DrawSprite(gl_vissprite_t *spr) blend = HWR_GetBlendModeFlag(blendmode)|PF_Occlude; } - if (cv_playerfade.value && sprmo->player) - Surf.PolyColor.s.alpha = FixedMul(R_DoPlayerFade(sprmo), Surf.PolyColor.s.alpha); + if (sprmo->player) + { + // make hyu´d players translucent with reducevfx, could be done better, but im lazy as crap + if (cv_reducevfx.value && sprmo->player->kartstuff[k_hyudorotimer] > 0) + Surf.PolyColor.s.alpha = static_cast(FixedMul(FRACUNIT/2, static_cast(Surf.PolyColor.s.alpha))); + + if (cv_playerfade.value) + Surf.PolyColor.s.alpha = static_cast(FixedMul(R_DoPlayerFade(sprmo), static_cast(Surf.PolyColor.s.alpha))); + } if (HWR_UseShader()) { @@ -4042,13 +3923,13 @@ static void HWR_DrawPrecipitationSprite(gl_vissprite_t *spr) FOutVector wallVerts[4]; patch_t *gpatch; // sprite patch converted to hardware GLPatch_t *hwrpatch; - FSurfaceInfo Surf; + FSurfaceInfo Surf = {}; INT32 shader = SHADER_NONE; - const precipmobj_t *sprmo = spr->precip; + precipmobj_t *sprmo = spr->precip; - if (UNLIKELY(!sprmo->subsector)) + if (!sprmo->subsector) return; // cache sprite graphics @@ -4059,7 +3940,7 @@ static void HWR_DrawPrecipitationSprite(gl_vissprite_t *spr) //Hurdler: 25/04/2000: now support colormap in hardware mode HWR_GetMappedPatch(gpatch, spr->colormap); - hwrpatch = ((GLPatch_t *)gpatch->hardware); + hwrpatch = static_cast(gpatch->hardware); // create the sprite billboard // @@ -4092,11 +3973,10 @@ static void HWR_DrawPrecipitationSprite(gl_vissprite_t *spr) if (sector->numlights) { - INT32 light; + // Always use the light at the top instead of whatever I was doing before + INT32 light = R_GetPlaneLight(sector, sprmo->z, false); // sprmo->z + sprmo->height - light = R_GetPlaneLight(sector, sprmo->z, false); // Always use the light at the top instead of whatever I was doing before - - if (!(sprmo->frame & FF_FULLBRIGHT)) + if (!R_PrecipThingIsFullBright(sprmo)) lightlevel = static_cast(*sector->lightlist[light].lightlevel); if (sector->lightlist[light].extra_colormap) @@ -4104,7 +3984,7 @@ static void HWR_DrawPrecipitationSprite(gl_vissprite_t *spr) } else { - if (!(sprmo->frame & FF_FULLBRIGHT)) + if (!R_PrecipThingIsFullBright(sprmo)) lightlevel = static_cast(sector->lightlevel); if (sector->extra_colormap) @@ -4174,6 +4054,7 @@ static int CompareVisSprites(const void *p1, const void *p2) static void HWR_SortVisSprites(void) { UINT32 i; + for (i = 0; i < gl_visspritecount; i++) { gl_vsprorder[i] = HWR_GetVisSprite(i); @@ -4242,26 +4123,17 @@ typedef struct // initial size of drawnode array #define DRAWNODES_INIT_SIZE 64 -gl_drawnode_t *drawnodes = NULL; -INT32 numdrawnodes = 0; -INT32 alloceddrawnodes = 0; +// no reason to waste all the allocations since every map will have atleast one translucent thing +static std::vector drawnodes; static void *HWR_CreateDrawNode(gl_drawnode_type_t type) { gl_drawnode_t *drawnode; + drawnodes.reserve(DRAWNODES_INIT_SIZE); - if (!drawnodes) - { - alloceddrawnodes = DRAWNODES_INIT_SIZE; - drawnodes = static_cast(Z_Malloc(alloceddrawnodes * sizeof(gl_drawnode_t), PU_LEVEL, &drawnodes)); - } - else if (numdrawnodes >= alloceddrawnodes) - { - alloceddrawnodes *= 2; - Z_Realloc(drawnodes, alloceddrawnodes * sizeof(gl_drawnode_t), PU_LEVEL, &drawnodes); - } + drawnodes.emplace_back(); - drawnode = &drawnodes[numdrawnodes++]; + drawnode = &drawnodes.back(); drawnode->type = type; // not sure if returning different pointers to a union is necessary @@ -4274,6 +4146,7 @@ static void *HWR_CreateDrawNode(gl_drawnode_type_t type) case DRAWNODE_WALL: return &drawnode->u.wall; } + return NULL; } @@ -4282,7 +4155,7 @@ static void HWR_AddTransparentWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, I wallinfo_t *wallinfo = static_cast(HWR_CreateDrawNode(DRAWNODE_WALL)); memcpy(wallinfo->wallVerts, wallVerts, sizeof (wallinfo->wallVerts)); - memcpy(&wallinfo->Surf, pSurf, sizeof (FSurfaceInfo)); + memcpy(&wallinfo->Surf, pSurf, sizeof(FSurfaceInfo)); wallinfo->texnum = texnum; wallinfo->noencore = noencore; wallinfo->blend = blend; @@ -4337,11 +4210,13 @@ static int CompareDrawNodePlanes(const void *p1, const void *p2) // Sorts and renders the list of drawnodes for the scene being rendered. static void HWR_RenderDrawNodes(void) { - INT32 i = 0, run_start = 0; + size_t i = 0, run_start = 0; + static std::vector sortindex(DRAWNODES_INIT_SIZE); // Array for storing the rendering order. // A list of indices into the drawnodes array. - INT32 *sortindex; + + const size_t numdrawnodes = drawnodes.size(); if (!numdrawnodes) return; @@ -4350,7 +4225,7 @@ static void HWR_RenderDrawNodes(void) PS_START_TIMING(ps_hw_nodesorttime); - sortindex = static_cast(Z_Malloc(sizeof(INT32) * numdrawnodes, PU_STATIC, NULL)); + sortindex.resize(numdrawnodes); // Reversed order for (i = 0; i < numdrawnodes; i++) @@ -4366,7 +4241,7 @@ static void HWR_RenderDrawNodes(void) if (drawnodes[sortindex[run_start]].type == DRAWNODE_PLANE) { // found it, now look for run end - INT32 run_end; // (inclusive) + size_t run_end; // (inclusive) for (i = run_start+1; i < numdrawnodes; i++) { @@ -4379,7 +4254,7 @@ static void HWR_RenderDrawNodes(void) if (run_end > run_start) // if there are multiple consecutive planes, not just one { // consecutive run of planes found, now sort it - qs22j(sortindex + run_start, run_end - run_start + 1, sizeof(INT32), CompareDrawNodePlanes); + qs22j(sortindex.data() + run_start, run_end - run_start + 1, sizeof(INT32), CompareDrawNodePlanes); } run_start = run_end + 1; // continue looking for runs coming right after this one @@ -4412,7 +4287,7 @@ static void HWR_RenderDrawNodes(void) gl_frontsector = NULL; if (!(plane->blend & PF_NoTexture)) - HWR_GetFlat(plane->lumpnum, R_NoEncore(plane->FOFSector, plane->isceiling)); + HWR_GetFlat(plane->lumpnum, R_NoEncore(plane->FOFSector, plane->isceiling)); HWR_RenderPlane(NULL, plane->xsub, plane->isceiling, plane->fixedheight, plane->blend, plane->lightlevel, plane->lumpnum, plane->FOFSector, plane->alpha, plane->planecolormap); @@ -4426,10 +4301,10 @@ static void HWR_RenderDrawNodes(void) gl_frontsector = NULL; if (!(polyplane->blend & PF_NoTexture)) - HWR_GetFlat(polyplane->lumpnum, R_NoEncore(polyplane->FOFSector, polyplane->isceiling)); + HWR_GetFlat(polyplane->lumpnum, R_NoEncore(polyplane->FOFSector, polyplane->isceiling)); HWR_RenderPolyObjectPlane(polyplane->polysector, polyplane->isceiling, polyplane->fixedheight, polyplane->blend, polyplane->lightlevel, - polyplane->lumpnum, polyplane->FOFSector, polyplane->alpha, polyplane->planecolormap); + polyplane->lumpnum, polyplane->FOFSector, polyplane->alpha, polyplane->planecolormap); } break; @@ -4441,7 +4316,7 @@ static void HWR_RenderDrawNodes(void) HWR_GetTexture(wall->texnum, wall->noencore); HWR_RenderWall(wall->wallVerts, &wall->Surf, wall->blend, wall->fogwall, - wall->lightlevel, wall->wallcolormap); + wall->lightlevel, wall->wallcolormap); } break; default: @@ -4451,12 +4326,9 @@ static void HWR_RenderDrawNodes(void) PS_STOP_TIMING(ps_hw_nodedrawtime); - numdrawnodes = 0; - - Z_Free(sortindex); + drawnodes.clear(); // clear so our size is 0 again! } - // -------------------------------------------------------------------------- // Draw all vissprites // -------------------------------------------------------------------------- @@ -4696,7 +4568,7 @@ static void HWR_ProjectSprite(mobj_t *thing) return; } - const boolean papersprite = (thing->frame & FF_PAPERSPRITE); + const boolean papersprite = R_ThingIsPaperSprite(thing); // transform the origin point tr_x = FixedToFloat(interp.x); @@ -4710,8 +4582,8 @@ static void HWR_ProjectSprite(mobj_t *thing) return; const boolean mirrored = thing->mirrored; - const boolean vflip = (thing->eflags & MFE_VERTICALFLIP); - const boolean hflip = (!(thing->frame & FF_HORIZONTALFLIP) != !mirrored); + const boolean vflip = R_ThingVerticallyFlipped(thing); + const boolean hflip = (!R_ThingHorizontallyFlipped(thing) != !mirrored); // decide which patch to use for sprite relative to player #ifdef RANGECHECK @@ -4764,7 +4636,7 @@ static void HWR_ProjectSprite(mobj_t *thing) #ifdef ROTSPRITE // determine here if sprite should rotate for optimization const boolean sliprollrotate = (cv_sliptideroll.value && (thing->player && thing->player->sliproll)); - const boolean shouldrotate = (interp.sloperoll || interp.slopepitch || interp.roll || interp.pitch || thing->rollangle || sliprollrotate); + const boolean shouldrotate = (interp.sloperoll || interp.slopepitch || interp.roll || interp.pitch || thing->rollangle || thing->temprollangle || sliprollrotate); #endif if (sprframe->rotate != SRF_SINGLE || papersprite @@ -4774,11 +4646,9 @@ static void HWR_ProjectSprite(mobj_t *thing) ) { ang = R_PointToAngle(interp.x, interp.y); - #ifdef ROTSPRITE camang = ang; #endif - ang -= interp.angle; if (mirrored) @@ -4793,7 +4663,7 @@ static void HWR_ProjectSprite(mobj_t *thing) flip = sprframe->flip; // Will only be 0x00 or 0xFF if (papersprite && ang < ANGLE_180) - flip ^= 0xFFFF; + flip ^= 0xFF; } else { @@ -4813,9 +4683,9 @@ static void HWR_ProjectSprite(mobj_t *thing) flip ^= (1<rollangle; + rollangle = (thing->rollangle - thing->temprollangle); if (rollangle || pitchnroll || sliprollrotate) { @@ -4900,12 +4770,12 @@ static void HWR_ProjectSprite(mobj_t *thing) // if the sprite is out of our view, dont need to draw it X) if (!gld_SphereInFrustum( - (FixedToFloat(interp.x)) + cos_inv_yaw * (x1 + x2) / 2.0f, - FixedToFloat(interp.z) + (y1 + y2) / 2.0f, - FixedToFloat(interp.y) - sin_inv_yaw * (x1 + x2) / 2.0f, - //1.5 == sqrt(2) + small delta for MF_FOREGROUND - std::max(FixedToFloat(spr_width) * spritexscale, - FixedToFloat(spr_height) * spriteyscale) / 2.0f * 1.5f)) + (FixedToFloat(interp.x)) + gl_viewsin * (x1 + x2) / 2.0f, + FixedToFloat(interp.z) + (y1 + y2) / 2.0f, + FixedToFloat(interp.y) - (-gl_viewcos) * (x1 + x2) / 2.0f, + //1.5 == sqrt(2) + small delta for MF_FOREGROUND + std::max(FixedToFloat(spr_width) * spritexscale, + FixedToFloat(spr_height) * spriteyscale) / 2.0f * 1.5f)) { return; } @@ -4964,10 +4834,10 @@ static void HWR_ProjectSprite(mobj_t *thing) vis->flip = flip; vis->scale = thing_scale; - vis->spritexscale = spritexscale; + /*vis->spritexscale = spritexscale; vis->spriteyscale = spriteyscale; vis->spritexoffset = FixedToFloat(spr_offset); - vis->spriteyoffset = FixedToFloat(spr_topoffset); + vis->spriteyoffset = FixedToFloat(spr_topoffset);*/ #ifdef ROTSPRITE if (rotsprite != NULL) @@ -5096,9 +4966,9 @@ static void HWR_ProjectPrecipitationSprite(precipmobj_t *thing) lumpoff = sprframe->lumpid[0]; flip = sprframe->flip; // Will only be 0x00 or 0xFF - spr_width = spritecachedinfo[lumpoff].width; - spr_height = spritecachedinfo[lumpoff].height; - spr_offset = spritecachedinfo[lumpoff].offset; + spr_width = spritecachedinfo[lumpoff].width; + spr_height = spritecachedinfo[lumpoff].height; + spr_offset = spritecachedinfo[lumpoff].offset; spr_topoffset = spritecachedinfo[lumpoff].topoffset; if (flip) @@ -5120,12 +4990,12 @@ static void HWR_ProjectPrecipitationSprite(precipmobj_t *thing) y2 *= thing_scale; if (!gld_SphereInFrustum( - (FixedToFloat(interp.x)) + cos_inv_yaw * (x1 + x2) / 2.0f, - FixedToFloat(interp.z) + (y1 + y2) / 2.0f, - FixedToFloat(interp.y) - sin_inv_yaw * (x1 + x2) / 2.0f, - //1.5 == sqrt(2) + small delta for MF_FOREGROUND - std::max(FixedToFloat(spr_width) * thing_scale, - FixedToFloat(spr_height) * thing_scale) / 2.0f * 1.5f)) + (FixedToFloat(interp.x)) + gl_viewsin * (x1 + x2) / 2.0f, + FixedToFloat(interp.z) + (y1 + y2) / 2.0f, + FixedToFloat(interp.y) - (-gl_viewcos) * (x1 + x2) / 2.0f, + //1.5 == sqrt(2) + small delta for MF_FOREGROUND + std::max(FixedToFloat(spr_width) * thing_scale, + FixedToFloat(spr_height) * thing_scale) / 2.0f * 1.5f)) { return; } @@ -5238,7 +5108,6 @@ void HWR_ClearSkyDome(void) sky->loops = NULL; sky->data = NULL; - sky->vbo = 0; sky->rows = sky->columns = 0; sky->loopcount = 0; @@ -5253,24 +5122,22 @@ void HWR_BuildSkyDome(void) int c, r; signed char yflip; static constexpr int row_count = 4; - int col_count = 4; + static constexpr int col_count = (4 * 16); float delta; gl_sky_t *sky = &gl_sky; gl_skyvertex_t *vertex_p; const texture_t *texture = textures[texturetranslation[skytexture]]; - col_count *= 16; - if ((sky->columns != col_count) || (sky->rows != row_count)) HWR_ClearSkyDome(); sky->columns = col_count; sky->rows = row_count; - sky->vertex_count = 2 * sky->rows * (sky->columns * 2 + 2) + sky->columns * 2; + sky->vertex_count = 2 * row_count * (col_count * 2 + 2) + col_count * 2; if (!sky->loops) - sky->loops = static_cast(malloc((sky->rows * 2 + 2) * sizeof(sky->loops[0]))); + sky->loops = static_cast(malloc((row_count * 2 + 2) * sizeof(sky->loops[0]))); // create vertex array if (!sky->data) @@ -5323,15 +5190,10 @@ void HWR_BuildSkyDome(void) // precompute to save a bit of division static constexpr float FINEDEGREE = (360.0f/static_cast(FINEANGLES)); -static void HWR_DrawSkyBackground(void) +static void HWR_DrawSkyDome(void) { FTransform dometransform; - if (HWR_IsWireframeMode()) - return; - - GL_SetBlend(PF_Translucent|PF_NoDepthTest|PF_Modulated); - memcpy(&dometransform, &atransform, sizeof(FTransform)); dometransform.x = dometransform.y = dometransform.z = 0.0; @@ -5356,6 +5218,124 @@ static void HWR_DrawSkyBackground(void) GL_RenderSkyDome(&gl_sky); } +// the following is karts old sky code from before the skydome stuff +// this appears to differ a bit from srb2´s old sky code +static void HWR_DrawSkyTexture(void) +{ + FOutVector v[4]; + angle_t angle; + float dimensionmultiply; + float aspectratio; + float angleturn; + + HWR_GetTexture(texturetranslation[skytexture], false); + + aspectratio = (float)vid.width/(float)vid.height; + + //Hurdler: the sky is the only texture who need 4.0f instead of 1.0 + // because it's called just after clearing the screen + // and thus, the near clipping plane is set to 3.99 + // Sryder: Just use the near clipping plane value then + + // 3--2 + // | /| + // |/ | + // 0--1 + v[0].x = v[3].x = -ZCLIP_PLANE-1; + v[1].x = v[2].x = ZCLIP_PLANE+1; + v[0].y = v[1].y = -ZCLIP_PLANE-1; + v[2].y = v[3].y = ZCLIP_PLANE+1; + + v[0].z = v[1].z = v[2].z = v[3].z = ZCLIP_PLANE+1; + + // X + + // NOTE: This doesn't work right with texture widths greater than 1024 + // software doesn't draw any further than 1024 for skies anyway, but this doesn't overlap properly + // The only time this will probably be an issue is when a sky wider than 1024 is used as a sky AND a regular wall texture + + //angle = (viewangle + ANGLE_45); + angle = (viewangle + xtoviewangle[0]); + dimensionmultiply = ((float)textures[texturetranslation[skytexture]]->width/256.0f); + + if (atransform.fliptype == TRANSFORM_MIRROR || + atransform.fliptype == TRANSFORM_MIRRORFLIP) + { + angle = InvAngle(angle); + dimensionmultiply *= -1; + } + + v[0].s = v[3].s = ((float)angle / ((float)(ANGLE_90-1)*dimensionmultiply)); + v[2].s = v[1].s = (-1.0f/dimensionmultiply)+((float) angle / ((float)(ANGLE_90-1)*dimensionmultiply)); + + // Y + angle = aimingangle; + dimensionmultiply = ((float)textures[texturetranslation[skytexture]]->height/(128.0f*aspectratio)); + + if (splitscreen == 1) + { + dimensionmultiply *= 2; + angle *= 2; + } + + // Middle of the sky should always be at angle 0 + // need to keep correct aspect ratio with X + if (atransform.fliptype == TRANSFORM_FLIP || + atransform.fliptype == TRANSFORM_MIRRORFLIP) + { + // During vertical flip the sky should be flipped and it's y movement should also be flipped obviously + v[3].t = v[2].t = -(0.5f-(0.5f/dimensionmultiply)); + v[0].t = v[1].t = (-1.0f/dimensionmultiply)-(0.5f-(0.5f/dimensionmultiply)); + } + else + { + v[3].t = v[2].t = (-1.0f/dimensionmultiply)-(0.5f-(0.5f/dimensionmultiply)); + v[0].t = v[1].t = -(0.5f-(0.5f/dimensionmultiply)); + } + + angleturn = (((float)ANGLE_45-1.0f)*aspectratio)*dimensionmultiply; + + if (cv_glshearing.value) + { + // Doesn't really make sense, but what can I do? + angle_t dy = FixedAngle(FixedMul(360*FRACUNIT, FixedDiv(AIMINGTODY(aimingangle), 900*FRACUNIT))); + v[3].t = v[2].t -= ((float) dy / angleturn); + v[0].t = v[1].t -= ((float) dy / angleturn); + } + else + { + if (angle > ANGLE_180) // Do this because we don't want the sky to suddenly teleport when crossing over 0 to 360 and vice versa + { + angle = InvAngle(angle); + v[3].t = v[2].t += ((float) angle / angleturn); + v[0].t = v[1].t += ((float) angle / angleturn); + } + else + { + v[3].t = v[2].t -= ((float) angle / angleturn); + v[0].t = v[1].t -= ((float) angle / angleturn); + } + } + + // since sky is drawn as a "flat quad" this way, we have to unset any view transformations for it to work + GL_SetTransform(NULL); + GL_UnSetShader(); + GL_DrawPolygon(NULL, v, 4, 0); +} + +static void HWR_DrawSkyBackground(void) +{ + if (HWR_IsWireframeMode()) + return; + + GL_SetBlend(PF_Translucent|PF_NoDepthTest|PF_Modulated); + + if (cv_skydome.value) + HWR_DrawSkyDome(); + else + HWR_DrawSkyTexture(); +} + // -----------------+ // HWR_ClearView : clear the viewwindow, with maximum z value. also clears stencil buffer. // -----------------+ @@ -5386,7 +5366,7 @@ static void HWR_SetTransformAiming(FTransform *trans) fixed_t fixedaiming = AIMINGTODY(aimingangle); trans->viewaiming = FixedToFloat(fixedaiming) * (static_cast(vid.width) / static_cast(vid.height)) / (static_cast(BASEVIDWIDTH) / static_cast(BASEVIDHEIGHT)); if (splitscreen == 1) // only for 2 player splitscreen - trans->viewaiming *= 2.125; // splitscreen adjusts fov with 0.8, so compensate (but only halfway, since splitscreen means only half the screen is used) + trans->viewaiming *= 2.125f; // splitscreen adjusts fov with 0.8, so compensate (but only halfway, since splitscreen means only half the screen is used) trans->shearing = true; gl_aimingangle = 0; } @@ -5421,12 +5401,6 @@ void HWR_SetTransform(float fpov) HWR_SetTransformAiming(&atransform); atransform.angley = static_cast(viewangle >> ANGLETOFINESHIFT)*(FINEDEGREE); - yaw = 270.0f - atransform.angley; - inv_yaw = 180.0f - yaw; - const float inv_yaw_radians = inv_yaw * deg2radians; - cos_inv_yaw = cosf(inv_yaw_radians); - sin_inv_yaw = sinf(inv_yaw_radians); - // only needed for sprite billboarding if (cv_glspritebillboarding.value && !cv_glshearing.value) { @@ -5459,6 +5433,7 @@ void HWR_SetTransform(float fpov) void HWR_ClearClipper(void) { const angle_t a1 = gld_FrustumAngle(gl_aimingangle); + gld_clipper_Clear(); gld_clipper_SafeAddClipRange(viewangle + a1, viewangle - a1); #ifdef HAVE_SPHEREFRUSTRUM @@ -5488,12 +5463,14 @@ static void HWR_RenderViewpoint(gl_portal_t *rootportal, int stencil_level, bool { gl_portallist_t portallist; + const boolean wireframe = HWR_IsWireframeMode(); + player_t *viewplayer = &players[displayplayers[viewssnum]]; const float fpov = FixedToFloat(R_GetPlayerFov(viewplayer)); - auto reset_viewstate = [&](const float fpov) + auto reset_viewstate = [](const float pfov) FUNCINLINE { - HWR_SetTransform(fpov); + HWR_SetTransform(pfov); HWR_ClearSprites(); HWR_ClearClipper(); }; @@ -5543,12 +5520,12 @@ static void HWR_RenderViewpoint(gl_portal_t *rootportal, int stencil_level, bool { if (allow_portals && rootportal) { - HWR_PortalFrame(rootportal);// for portalclipsector, it could have gone null from search + HWR_PortalFrame(rootportal); // for portalclipsector, it could have gone null from search HWR_PortalClipping(rootportal); } } - if (HWR_IsWireframeMode()) + if (wireframe) GL_SetSpecialState(HWD_SET_WIREFRAME, 1); // FIXME: perfstats does not account for portal rendering! @@ -5563,7 +5540,8 @@ static void HWR_RenderViewpoint(gl_portal_t *rootportal, int stencil_level, bool if constexpr (Type == RenderViewpointType::kPortal) { - gl_collect_skywalls = (allow_portals && !rootportal && portallist.base && (!skyboxmo[0] || !cv_skybox.value)); // if portals have been drawn in the main view, then render skywalls differently + // if portals have been drawn in the main view, then render skywalls differently + gl_collect_skywalls = (allow_portals && !rootportal && portallist.base && (!skyboxmo[0] || !cv_skybox.value)); // HAYA: Save the old portal state, and turn portals off while normally rendering the BSP tree. // This fixes specific effects not working, such as horizon lines. @@ -5619,6 +5597,7 @@ static void HWR_RenderViewpoint(gl_portal_t *rootportal, int stencil_level, bool PS_START_TIMING(ps_hw_spritesorttime); HWR_SortVisSprites(); PS_STOP_TIMING(ps_hw_spritesorttime); + PS_START_TIMING(ps_hw_spritedrawtime); if (UNLIKELY(cv_glmdls.value)) HWR_DrawSprites(); @@ -5632,7 +5611,7 @@ static void HWR_RenderViewpoint(gl_portal_t *rootportal, int stencil_level, bool HWR_RenderDrawNodes(); - if (HWR_IsWireframeMode()) + if (wireframe) GL_SetSpecialState(HWD_SET_WIREFRAME, 0); HWR_FreePortalList(portallist); // always call this just in case @@ -5640,8 +5619,8 @@ static void HWR_RenderViewpoint(gl_portal_t *rootportal, int stencil_level, bool }; extern "C" { - void HWR_RenderPortalViewpoint(gl_portal_t *rootportal, int stencil_level, boolean allow_portals) { - HWR_RenderViewpoint(rootportal, stencil_level, allow_portals); + void HWR_RenderPortalViewpoint(gl_portal_t *rootportal, int stencil_level) { + HWR_RenderViewpoint(rootportal, stencil_level, true); } } @@ -5650,6 +5629,12 @@ extern "C" { // ========================================================================== static void HWR_RenderFrame(boolean skybox, boolean drawsky) { + // NetUpdate below may cause this to be false midrender if toggled + const boolean useportals = HWR_UsePortals(); + + if (useportals) + GL_EnableStencilTest(); + // Clear view, set viewport (glViewport), set perspective... HWR_ClearView(); @@ -5667,7 +5652,7 @@ static void HWR_RenderFrame(boolean skybox, boolean drawsky) viewwindowy, (viewwindowx + viewwidth), (viewwindowy + viewheight), - ZCLIP_PLANE, clipping_distances[renderdist - 1]); + ZCLIP_PLANE, clipping_distances[renderdist - 1]); current_bsp_culling_distance = bsp_culling_distances[renderdist- 1]; } @@ -5675,11 +5660,14 @@ static void HWR_RenderFrame(boolean skybox, boolean drawsky) NetUpdate(); portalclipline = NULL; - if (UNLIKELY(HWR_UsePortals())) + if (useportals) HWR_RenderViewpoint(NULL, 0, !skybox); else HWR_RenderViewpoint(NULL, 0, !skybox); + if (useportals) + GL_DisableStencilTest(); + // Check for new console commands. NetUpdate(); } @@ -5856,7 +5844,6 @@ void HWR_AddCommands(void) CV_RegisterVar(&cv_glpaletterendering); CV_RegisterVar(&cv_glpalettedepth); - CV_RegisterVar(&cv_glflashpal); } // -------------------------------------------------------------------------- @@ -5936,7 +5923,7 @@ static void COM_HWR_glinfo(void) // if the GPU is super new and supports a bajillion extensions - xyzzy char *copy = strdup((const char*)gl_extensions); - char *ext = strtok(copy, " "); + char *ext; if (copy == NULL) { @@ -5944,6 +5931,8 @@ static void COM_HWR_glinfo(void) return; } + ext = strtok(copy, " "); + do { CONS_Printf(" - %s\n", ext); @@ -6011,9 +6000,13 @@ static void HWR_RenderWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, FBITFIELD static void HWR_DoPostProcessor(void) { + // no flashes or screen waving if we want less vfx! + if (cv_reducevfx.value) + return; + // Armageddon Blast Flash! // Could this even be considered postprocessor? - if (!HWR_PalRenderFlashpal()) + if (!HWR_ShouldUsePaletteRendering()) { const player_t *player = &players[displayplayers[viewssnum]]; @@ -6026,7 +6019,7 @@ static void HWR_DoPostProcessor(void) {-4.0f, -4.0f, 4.0f, 0.0f, 0.0f} }; - FSurfaceInfo Surf; + FSurfaceInfo Surf = {}; // This won't change if the flash palettes are changed unfortunately, but it works for its purpose if (player->flashpal == PAL_NUKE) @@ -6045,105 +6038,123 @@ static void HWR_DoPostProcessor(void) } } - if (cv_glscreentextures.value != 2) // screen textures are needed for the rest of the effects + // screen textures are needed for the rest of the effects + if (cv_glscreentextures.value != 2) return; - //UINT8 viewnum = R_GetViewNumber(); // see below + // Not supported in splitscreen - someone want to add support? + if (splitscreen) + return; + + //UINT8 viewnum = R_GetViewNumber(); //camera_t *thiscam = &camera[viewnum]; const camera_t *thiscam = &camera[0]; - // Not supported in splitscreen - someone want to add support? - const boolean screenwave = (!splitscreen && (thiscam->postimg & POSTIMG_WATER || thiscam->postimg & POSTIMG_HEAT)); + if (!(thiscam->postimg & POSTIMG_WATER || thiscam->postimg & POSTIMG_HEAT)) + return; // Capture the screen for intermission and screen waving - if ((lastdraw || screenwave) && gamestate != GS_INTERMISSION) + if (gamestate != GS_INTERMISSION) GL_MakeScreenTexture(HWD_SCREENTEXTURE_GENERIC1); // Drunken vision! WooOOooo~ - if (screenwave) + // 10 by 10 grid. 2 coordinates (xy) + float v[SCREENVERTS][SCREENVERTS][2]; + float disStart = (leveltime-1) + FixedToFloat(R_GetTimeFrac(RTF_LEVEL)); + + UINT8 x, y; + float WAVELENGTH; + float AMPLITUDE; + float FREQUENCY; + + // Modifies the wave. + if (thiscam->postimg & POSTIMG_WATER) { - // 10 by 10 grid. 2 coordinates (xy) - float v[SCREENVERTS][SCREENVERTS][2]; - float disStart = (leveltime-1) + FixedToFloat(R_GetTimeFrac(RTF_LEVEL)); - - UINT8 x, y; - float WAVELENGTH; - float AMPLITUDE; - float FREQUENCY; - - // Modifies the wave. - if (thiscam->postimg & POSTIMG_WATER) - { - WAVELENGTH = 5.0f; - AMPLITUDE = 40.0f; - FREQUENCY = 8.0f; - } - else - { - WAVELENGTH = 10.0f; - AMPLITUDE = 60.0f; - FREQUENCY = 4.0f; - } - - //static constexpr float scale = ((float)SCREENVERTS - 1.0f) / 9.0f; // well this evals to just 1.0f and what is x / 1? kek - - for (x = 0; x < SCREENVERTS; x++) - { - for (y = 0; y < SCREENVERTS; y++) - { - // Change X position based on its Y position. - v[x][y][0] = x-4.5f + sinf(((disStart+(static_cast(y) * WAVELENGTH)) / FREQUENCY)) / AMPLITUDE; // (x / scale) - v[x][y][1] = y-4.5f; // (y / scale) - } - } - - GL_PostImgRedraw(v); - - // Capture the screen again for screen waving on the intermission - if (gamestate != GS_INTERMISSION) - GL_MakeScreenTexture(HWD_SCREENTEXTURE_GENERIC1); + WAVELENGTH = 5.0f; + AMPLITUDE = 40.0f; + FREQUENCY = 8.0f; } + else + { + WAVELENGTH = 10.0f; + AMPLITUDE = 60.0f; + FREQUENCY = 4.0f; + } + + //static constexpr float scale = ((float)SCREENVERTS - 1.0f) / 9.0f; // well this evals to just 1.0f and what is x / 1? kek + + for (x = 0; x < SCREENVERTS; x++) + { + for (y = 0; y < SCREENVERTS; y++) + { + // Change X position based on its Y position. + v[x][y][0] = x-4.5f + sinf(((disStart+(static_cast(y) * WAVELENGTH)) / FREQUENCY)) / AMPLITUDE; // (x / scale) + v[x][y][1] = y-4.5f; // (y / scale) + } + } + + GL_PostImgRedraw(v); + + // Capture the screen again for screen waving on the intermission + if (gamestate != GS_INTERMISSION) + GL_MakeScreenTexture(HWD_SCREENTEXTURE_GENERIC1); // Flipping of the screen isn't done here anymore } -void HWR_DoWipe(UINT8 wipenum, UINT8 scrnnum) +// +// wipes +// +static lumpnum_t wipelumpnum; + +// puts wipe lumpname in wipename[9] +static boolean HWR_WipeCheck(UINT8 wipenum, UINT8 scrnnum) { static char lumpname[9] = "FADEmmss"; - lumpnum_t lumpnum; size_t lsize; + // screen textures disabled completely if (cv_glscreentextures.value == 0) { - V_DrawFill(0, 0, BASEVIDWIDTH, BASEVIDHEIGHT, 31); // just draw a black screen instead of flashing and crap - return; + return false; } - if (wipenum > 99 || scrnnum > 99) // not a valid wipe number + // not a valid wipe number + if (wipenum > 99 || scrnnum > 99) { - V_DrawFill(0, 0, BASEVIDWIDTH, BASEVIDHEIGHT, 31); // just draw a black screen instead of flashing and crap - return; // shouldn't end up here really, the loop should've stopped running beforehand + return false; // shouldn't end up here really, the loop should've stopped running beforehand } // puts the numbers into the lumpname - sprintf(&lumpname[4], "%.2hu%.2hu", (UINT16)wipenum, (UINT16)scrnnum); - lumpnum = W_CheckNumForName(lumpname); + snprintf(&lumpname[4], sizeof(lumpname) - 4, "%.2hu%.2hu", (UINT16)wipenum, (UINT16)scrnnum); + wipelumpnum = W_CheckNumForName(lumpname); - if (lumpnum == LUMPERROR) // again, shouldn't be here really + // again, shouldn't be here really + if (wipelumpnum == LUMPERROR) { - V_DrawFill(0, 0, BASEVIDWIDTH, BASEVIDHEIGHT, 31); // just draw a black screen instead of flashing and crap - return; + return false; } - lsize = W_LumpLength(lumpnum); + lsize = W_LumpLength(wipelumpnum); if (!(lsize == 256000 || lsize == 64000 || lsize == 16000 || lsize == 4000)) { CONS_Alert(CONS_WARNING, "Fade mask lump %s of incorrect size, ignored\n", lumpname); - V_DrawFill(0, 0, BASEVIDWIDTH, BASEVIDHEIGHT, 31); // just draw a black screen instead of flashing and crap - return; // again, shouldn't get here if it is a bad size + return false; // again, shouldn't get here if it is a bad size } - HWR_GetFadeMask(lumpnum); + return true; +} + +void HWR_DoWipe(UINT8 wipenum, UINT8 scrnnum) +{ + if (!HWR_WipeCheck(wipenum, scrnnum)) + { + // just draw a black screen instead of rapidly flashing a white screen + V_DrawFill(0, 0, BASEVIDWIDTH, BASEVIDHEIGHT, 31); + return; + } + + HWR_GetFadeMask(wipelumpnum); GL_DoScreenWipe(HWD_SCREENTEXTURE_WIPE_START, HWD_SCREENTEXTURE_WIPE_END); } diff --git a/src/hardware/hw_main.h b/src/hardware/hw_main.h index 8b5284acb..4856f7574 100644 --- a/src/hardware/hw_main.h +++ b/src/hardware/hw_main.h @@ -102,7 +102,7 @@ void HWR_SetViewSize(void); void HWR_AddCommands(void); void HWR_RenderPlayerView(void); -void HWR_RenderPortalViewpoint(gl_portal_t *rootportal, int stencil_level, boolean allow_portals); +void HWR_RenderPortalViewpoint(gl_portal_t *rootportal, int stencil_level); void HWR_ClearSkyDome(void); void HWR_BuildSkyDome(void); @@ -151,14 +151,19 @@ FUNCINLINE static ATTRINLINE void HWR_RenderVhsEffect(fixed_t upbary, fixed_t do GL_RenderVhsEffect(upbary, downbary, updistort, downdistort, barsize); } +FUNCINLINE static ATTRINLINE void HWR_MakeScreenTexture(void) +{ + GL_MakeScreenTexture(HWD_SCREENTEXTURE_GENERIC1); +} + FUNCINLINE static ATTRINLINE void HWR_MakeScreenFinalTexture(void) { GL_MakeScreenTexture(HWD_SCREENTEXTURE_GENERIC2); } -FUNCINLINE static ATTRINLINE void HWR_DrawScreenFinalTexture(INT32 width, INT32 height, boolean useshader) +FUNCINLINE static ATTRINLINE void HWR_DrawScreenFinalTexture(INT32 width, INT32 height) { - GL_DrawScreenFinalTexture(HWD_SCREENTEXTURE_GENERIC2, width, height, useshader); + GL_DrawScreenFinalTexture(HWD_SCREENTEXTURE_GENERIC2, width, height); } // hw_main.c: Segs @@ -208,7 +213,6 @@ extern consvar_t cv_glportals; extern consvar_t cv_glpaletterendering; extern consvar_t cv_glpalettedepth; -extern consvar_t cv_glflashpal; FUNCINLINE static ATTRINLINE boolean HWR_UseShader(void) { @@ -220,11 +224,6 @@ FUNCINLINE static ATTRINLINE boolean HWR_ShouldUsePaletteRendering(void) return (cv_glpaletterendering.value && (pLocalPalette != NULL) && HWR_UseShader()); } -FUNCINLINE static ATTRINLINE boolean HWR_PalRenderFlashpal(void) -{ - return (cv_glflashpal.value && HWR_ShouldUsePaletteRendering()); -} - // Returns a pointer to the palette which should be used for caching textures. FUNCINLINE static ATTRINLINE RGBA_t *HWR_GetTexturePalette(void) { diff --git a/src/hardware/hw_md2.c b/src/hardware/hw_md2.c index 763fb873c..f21f2f82d 100644 --- a/src/hardware/hw_md2.c +++ b/src/hardware/hw_md2.c @@ -579,7 +579,7 @@ md2found: fclose(f); } -void HWR_AddPlayerMD2(int skin, boolean local) // For MD2's that were added after startup +void HWR_AddPlayerMD2(INT32 skin, boolean local) // For MD2's that were added after startup { FILE *f; char name[20], filename[32]; @@ -693,17 +693,15 @@ static void HWR_CreateBlendedTexture(patch_t *gpatch, patch_t *blendgpatch, GLMi GLPatch_t *hwrBlendPatch = blendgpatch->hardware; UINT16 w = gpatch->width, h = gpatch->height; UINT32 size = w*h; - RGBA_t *image, *blendimage, *cur, blendcolor; + RGBA_t *image, *blendimage, *cur; + RGBA_t blendcolor = {}; RGBA_t *palette = HWR_GetTexturePalette(); - UINT8 translation[17]; // First the color index - UINT8 cutoff[17]; // Brightness cutoff before using the next color + UINT8 translation[17] = {}; // First the color index + UINT8 cutoff[17] = {}; // Brightness cutoff before using the next color UINT8 translen = 0; UINT8 i; - UINT8 colorbrightnesses[17]; - UINT8 color_match_lookup[256]; // optimization attempt - - memset(translation, 0, sizeof(translation)); - memset(cutoff, 0, sizeof(cutoff)); + UINT8 colorbrightnesses[17] = {}; + UINT8 color_match_lookup[256] = {}; // optimization attempt if (glMipmap->width == 0) { @@ -716,14 +714,10 @@ static void HWR_CreateBlendedTexture(patch_t *gpatch, patch_t *blendgpatch, GLMi glMipmap->format = GL_TEXFMT_RGBA; } - if (glMipmap->data) - { - Z_Free(glMipmap->data); - glMipmap->data = NULL; - } + Z_Free(glMipmap->data); + glMipmap->data = NULL; - cur = Z_Malloc(size*4, PU_HWRMODELTEXTURE, &glMipmap->data); - memset(cur, 0x00, size*4); + cur = Z_Calloc(size*4, PU_HWRMODELTEXTURE, &glMipmap->data); image = hwrPatch->mipmap->data; blendimage = hwrBlendPatch->mipmap->data; @@ -1037,7 +1031,6 @@ static void HWR_GetBlendedTexture(patch_t *patch, patch_t *blendgpatch, INT32 sk GLPatch_t *glPatch = patch->hardware; GLMipmap_t *glMipmap, *newMipmap; - if (blendgpatch == NULL || colormap == colormaps || colormap == NULL) { // Don't do any blending @@ -1106,7 +1099,7 @@ void HWR_DrawMD2(gl_vissprite_t *spr) INT32 frame = 0; INT32 nextFrame = -1; FTransform p; - FSurfaceInfo Surf; + FSurfaceInfo Surf = {}; if (!cv_glmdls.value || spr->precip) return; @@ -1160,8 +1153,11 @@ void HWR_DrawMD2(gl_vissprite_t *spr) INT32 durs = spr->mobj->state->tics; INT32 tics = spr->mobj->tics; //mdlframe_t *next = NULL; + + //const UINT8 flip = (UINT8)(!(spr->mobj->eflags & MFE_VERTICALFLIP) != !R_ThingVerticallyFlipped(spr->mobj)); // :chaosleep: const UINT8 flip = (UINT8)((spr->mobj->eflags & MFE_VERTICALFLIP) == MFE_VERTICALFLIP); - const UINT8 hflip = (UINT8)(!(spr->mobj->mirrored) != !(spr->mobj->frame & FF_HORIZONTALFLIP)); + const UINT8 hflip = (UINT8)(!(spr->mobj->mirrored) != !R_ThingHorizontallyFlipped(spr->mobj)); + spritedef_t *sprdef; spriteframe_t *sprframe; spriteinfo_t *sprinfo; @@ -1198,8 +1194,15 @@ void HWR_DrawMD2(gl_vissprite_t *spr) Surf.PolyFlags = HWR_GetBlendModeFlag(blendmode); } - if (cv_playerfade.value && spr->mobj->player) - Surf.PolyColor.s.alpha = FixedMul(R_DoPlayerFade(spr->mobj), Surf.PolyColor.s.alpha); + if (spr->mobj->player) + { + // make hyu´d players translucent with reducevfx, could be done better, but im lazy as crap + if (cv_reducevfx.value && spr->mobj->player->kartstuff[k_hyudorotimer] > 0) + Surf.PolyColor.s.alpha = FixedMul(FRACUNIT/2, Surf.PolyColor.s.alpha); + + if (cv_playerfade.value) + Surf.PolyColor.s.alpha = FixedMul(R_DoPlayerFade(spr->mobj), Surf.PolyColor.s.alpha); + } // dont forget to enabled the depth test because we can't do this like // before: polygons models are not sorted @@ -1244,7 +1247,7 @@ void HWR_DrawMD2(gl_vissprite_t *spr) if (!md2->model) { CONS_Debug(DBG_RENDER, "Loading model... (%s, %s)", sprnames[spr->mobj->sprite], md2->filename); - sprintf(filename, "mdls/%s", md2->filename); + snprintf(filename, sizeof(filename), "mdls/%s", md2->filename); md2->model = md2_readModel(filename); if (md2->model) @@ -1336,8 +1339,8 @@ void HWR_DrawMD2(gl_vissprite_t *spr) if (spr->mobj->frame & FF_ANIMATE) { // set duration and tics to be the correct values for FF_ANIMATE states - durs = (float)spr->mobj->state->var2; - tics = (float)spr->mobj->anim_duration; + durs = spr->mobj->state->var2; + tics = (INT32)spr->mobj->anim_duration; } //FIXME: this is not yet correct @@ -1400,12 +1403,11 @@ void HWR_DrawMD2(gl_vissprite_t *spr) const angle_t sliptideroll = ((cv_sliptideroll.value && spr->mobj->player) ? spr->mobj->player->sliproll : 0); const SINT8 flipfactor = flip ? -1 : 1; + const angle_t thingrollangle = (spr->mobj->rollangle - spr->mobj->temprollangle); - if (spr->mobj->rollangle || sliptideroll) + if (thingrollangle || sliptideroll) { - angle_t rollang = sliptideroll - ? (spr->mobj->rollangle) + (sliptideroll * spr->mobj->player->kartstuff[k_aizdriftstrat]) - : (spr->mobj->rollangle); + angle_t rollang = sliptideroll ? (thingrollangle + (sliptideroll * spr->mobj->player->kartstuff[k_aizdriftstrat])) : thingrollangle; rollang *= flipfactor; @@ -1468,4 +1470,115 @@ void HWR_DrawMD2(gl_vissprite_t *spr) } } +// mostly copy paste of HWR_DrawMD2 +// very ugly but our model code kinda sucks +void HWR_Draw2DModel(md2_t *md2, INT32 x, INT32 y, INT32 skinnum, skincolors_t color, const UINT8 *colormap, fixed_t scale, INT32 frame, angle_t angle) +{ + patch_t *gpatch, *blendgpatch; + GLPatch_t *hwrPatch = NULL, *hwrBlendPatch = NULL; + FTransform p; + FSurfaceInfo Surf = {}; + + if (!md2->model) + { + char filename[64]; + CONS_Debug(DBG_RENDER, "Loading model... (%s)\n", md2->filename); + snprintf(filename, sizeof(filename), "mdls/%s", md2->filename); + md2->model = md2_readModel(filename); + + if (md2->model) + { + md2_printModelInfo(md2->model); + GL_CreateModelVBOs(md2->model); + } + else + { + md2->error = true; + return; + } + } + + if (md2->model->meshes[0].numFrames > 0) + frame = frame % md2->model->meshes[0].numFrames; + else + frame = 0; + + gpatch = (patch_t *)(md2->glpatch); + if (gpatch) + hwrPatch = ((GLPatch_t *)gpatch->hardware); + + if (!gpatch || !hwrPatch || + ((!hwrPatch->mipmap->format || !hwrPatch->mipmap->downloaded) && !md2->notexturefile)) + md2_loadTexture(md2); + + gpatch = (patch_t*)(md2->glpatch); + if (gpatch) + hwrPatch = ((GLPatch_t *)gpatch->hardware); + + blendgpatch = (patch_t*)(md2->blendglpatch); + if (blendgpatch) + hwrBlendPatch = ((GLPatch_t *)blendgpatch->hardware); + + if ((gpatch && hwrPatch && hwrPatch->mipmap->format) && + (!blendgpatch || !hwrBlendPatch || + ((!hwrBlendPatch->mipmap->format || !hwrBlendPatch->mipmap->downloaded) && !md2->noblendfile))) + md2_loadBlendTexture(md2); + + blendgpatch = (patch_t*)(md2->blendglpatch); + if (blendgpatch) + hwrBlendPatch = ((GLPatch_t *)blendgpatch->hardware); + + Surf.PolyColor.rgba = 0xFFFFFFFF; + Surf.PolyFlags = PF_Occlude | PF_Modulated; + + Surf.LightInfo.light_level = 255; + Surf.LightInfo.fade_start = 0; + Surf.LightInfo.fade_end = 31; + + if (color != SKINCOLOR_NONE && + blendgpatch && hwrBlendPatch->mipmap->format && + gpatch->width == blendgpatch->width && gpatch->height == blendgpatch->height) + { + INT32 tcskinnum = TC_DEFAULT; + + if (color) + tcskinnum = skinnum; + + HWR_GetBlendedTexture(gpatch, blendgpatch, tcskinnum, colormap, color); + } + else if (hwrPatch && hwrPatch->mipmap->format) + { + GL_SetTexture(hwrPatch->mipmap); + } + + memset(&p, 0x00, sizeof(FTransform)); + + p.x = x*vid.dup + (float)(vid.width - BASEVIDWIDTH*vid.dup)/2.f; + p.y = -420.f; // push it back to prevent wonky culling, idk lul + p.z = y*vid.dup + (float)(vid.height - BASEVIDHEIGHT*vid.dup)/2.f; + + p.angley = FixedToFloat(AngleFixed(angle)); + p.anglex = 0.f; + p.anglez = 0.f; + + p.roll = false; + p.fliptype = TRANSFORM_NONE; + + const float fscale = FixedToFloat(scale*vid.dup); + + GL_Draw2DModel( + md2->model, + frame, + 0.f, + 0.f, + -1, + &p, + fscale, + fscale, + true, // flip it vertically lul + false, + &Surf + ); +} + #endif //HWRENDER diff --git a/src/hardware/hw_md2.h b/src/hardware/hw_md2.h index 62de1f35e..0f8bd5342 100644 --- a/src/hardware/hw_md2.h +++ b/src/hardware/hw_md2.h @@ -45,6 +45,9 @@ void HWR_InitMD2(void); void HWR_DrawMD2(gl_vissprite_t *spr); void HWR_AddPlayerMD2(INT32 skin, boolean local); void HWR_AddSpriteMD2(size_t spritenum); +void HWR_Draw2DModel(md2_t *md2, INT32 x, INT32 y, INT32 skinnum, + skincolors_t color, const UINT8 *colormap, + fixed_t scale, INT32 frame, angle_t angle); #ifdef __cplusplus } // extern "C" diff --git a/src/hardware/hw_md2load.c b/src/hardware/hw_md2load.c index 3805deffb..a880aa677 100644 --- a/src/hardware/hw_md2load.c +++ b/src/hardware/hw_md2load.c @@ -274,27 +274,20 @@ model_t *MD2_LoadModel(const char *fileName, int ztag, boolean useFloat) if (!f) return NULL; - retModel = (model_t*)Z_Calloc(sizeof(model_t), ztag, 0); - - //size_t fileLen; - - //int i, j; - - //size_t namelen; - //char *texturefilename; + retModel = (model_t*)Z_Calloc(sizeof(model_t), ztag, NULL); texPos = strchr(fileName, '/'); if (texPos) { texPos++; namelen = strlen(texPos) + 1; - texturefilename = (char*)Z_Malloc(namelen, PU_CACHE, 0); + texturefilename = (char*)Z_Malloc(namelen, PU_CACHE, NULL); strcpy(texturefilename, texPos); } else { namelen = strlen(fileName) + 1; - texturefilename = (char*)Z_Malloc(namelen, PU_CACHE, 0); + texturefilename = (char*)Z_Malloc(namelen, PU_CACHE, NULL); strcpy(texturefilename, fileName); } @@ -316,10 +309,8 @@ model_t *MD2_LoadModel(const char *fileName, int ztag, boolean useFloat) header = (md2header_t*)buffer; retModel->numMeshes = 1; // MD2 only has one mesh - retModel->meshes = (mesh_t*)Z_Calloc(sizeof(mesh_t) * retModel->numMeshes, ztag, 0); + retModel->meshes = (mesh_t*)Z_Calloc(sizeof(mesh_t) * retModel->numMeshes, ztag, NULL); retModel->meshes[0].numFrames = header->numFrames; - // const float WUNITS = 1.0f; - // float dataScale = WUNITS; // Tris and ST are simple structures that can be straight-copied tris = (md2triangle_t*)&buffer[header->offsetTris]; @@ -332,7 +323,7 @@ model_t *MD2_LoadModel(const char *fileName, int ztag, boolean useFloat) if (retModel->numMaterials <= 0) // Always at least one skin, duh retModel->numMaterials = 1; - retModel->materials = (material_t*)Z_Calloc(sizeof(material_t)*retModel->numMaterials, ztag, 0); + retModel->materials = (material_t*)Z_Calloc(sizeof(material_t)*retModel->numMaterials, ztag, NULL); // int t; for (t = 0; t < retModel->numMaterials; t++) @@ -355,47 +346,6 @@ model_t *MD2_LoadModel(const char *fileName, int ztag, boolean useFloat) retModel->materials[t].specular[3] = 1.0f; retModel->materials[t].shininess = 0.0f; retModel->materials[t].spheremap = false; - - /* retModel->materials[t].texture = Texture::ReadTexture((char*)texturefilename, ZT_TEXTURE); - - if (!systemSucks) - { - // Check for a normal map...?? - char openfilename[1024]; - char normalMapName[1024]; - strcpy(normalMapName, texturefilename); - size_t len = strlen(normalMapName); - char *ptr = &normalMapName[len]; - ptr--; // z - ptr--; // u - ptr--; // b - ptr--; // . - *ptr++ = '_'; - *ptr++ = 'n'; - *ptr++ = '.'; - *ptr++ = 'b'; - *ptr++ = 'u'; - *ptr++ = 'z'; - *ptr++ = '\0'; - - sprintf(openfilename, "%s/%s", "textures", normalMapName); - // Convert backslashes to forward slashes - for (int k = 0; k < 1024; k++) - { - if (openfilename[k] == '\0') - break; - - if (openfilename[k] == '\\') - openfilename[k] = '/'; - } - - Resource::resource_t *res = Resource::Open(openfilename); - if (res) - { - Resource::Close(res); - retModel->materials[t].lightmap = Texture::ReadTexture(normalMapName, ZT_TEXTURE); - } - }*/ } retModel->meshes[0].numTriangles = header->numTris; @@ -409,9 +359,9 @@ model_t *MD2_LoadModel(const char *fileName, int ztag, boolean useFloat) float *uvptr; dataScale = 0.015624f; // 1 / 64.0f - retModel->meshes[0].tinyframes = (tinyframe_t*)Z_Calloc(sizeof(tinyframe_t)*header->numFrames, ztag, 0); + retModel->meshes[0].tinyframes = (tinyframe_t*)Z_Calloc(sizeof(tinyframe_t)*header->numFrames, ztag, NULL); retModel->meshes[0].numVertices = header->numXYZ; - retModel->meshes[0].uvs = (float*)Z_Malloc(sizeof(float) * 2 * retModel->meshes[0].numVertices, ztag, 0); + retModel->meshes[0].uvs = (float*)Z_Malloc(sizeof(float) * 2 * retModel->meshes[0].numVertices, ztag, NULL); ptr = (char*)frames; for (i = 0; i < header->numFrames; i++, ptr += header->framesize) @@ -423,17 +373,13 @@ model_t *MD2_LoadModel(const char *fileName, int ztag, boolean useFloat) md2vertex_t *vertex; md2frame_t *framePtr = (md2frame_t*)ptr; - retModel->meshes[0].tinyframes[i].vertices = (short*)Z_Malloc(sizeof(short) * 3 * header->numXYZ, ztag, 0); - retModel->meshes[0].tinyframes[i].normals = (char*)Z_Malloc(sizeof(char) * 3 * header->numXYZ, ztag, 0); - - // if (retModel->materials[0].lightmap) - // retModel->meshes[0].tinyframes[i].tangents = (char*)malloc(sizeof(char));//(char*)Z_Malloc(sizeof(char)*3*header->numVerts, ztag); - retModel->meshes[0].indices = (unsigned short*)Z_Malloc(sizeof(unsigned short) * 3 * header->numTris, ztag, 0); + retModel->meshes[0].tinyframes[i].vertices = (short*)Z_Malloc(sizeof(short) * 3 * header->numXYZ, ztag, NULL); + retModel->meshes[0].tinyframes[i].normals = (char*)Z_Malloc(sizeof(char) * 3 * header->numXYZ, ztag, NULL); + retModel->meshes[0].indices = (unsigned short*)Z_Malloc(sizeof(unsigned short) * 3 * header->numTris, ztag, NULL); vertptr = retModel->meshes[0].tinyframes[i].vertices; normptr = retModel->meshes[0].tinyframes[i].normals; - // tanptr = retModel->meshes[0].tinyframes[i].tangents; retModel->meshes[0].tinyframes[i].material = &retModel->materials[0]; framePtr++; // Advance to vertex list @@ -484,8 +430,8 @@ model_t *MD2_LoadModel(const char *fileName, int ztag, boolean useFloat) char *ptr; retModel->meshes[0].numVertices = header->numTris * 3; - retModel->meshes[0].frames = (mdlframe_t*)Z_Calloc(sizeof(mdlframe_t)*header->numFrames, ztag, 0); - retModel->meshes[0].uvs = (float*)Z_Malloc(sizeof(float) * 2 * retModel->meshes[0].numVertices, ztag, 0); + retModel->meshes[0].frames = (mdlframe_t*)Z_Calloc(sizeof(mdlframe_t)*header->numFrames, ztag, NULL); + retModel->meshes[0].uvs = (float*)Z_Malloc(sizeof(float) * 2 * retModel->meshes[0].numVertices, ztag, NULL); trisPtr = tris; uvptr = retModel->meshes[0].uvs; @@ -507,11 +453,9 @@ model_t *MD2_LoadModel(const char *fileName, int ztag, boolean useFloat) md2vertex_t *vertex; md2frame_t *framePtr = (md2frame_t*)ptr; - retModel->meshes[0].frames[i].normals = (float*)Z_Malloc(sizeof(float) * 3 * header->numTris * 3, ztag, 0); - retModel->meshes[0].frames[i].vertices = (float*)Z_Malloc(sizeof(float) * 3 * header->numTris * 3, ztag, 0); - // if (retModel->materials[0].lightmap) - // retModel->meshes[0].frames[i].tangents = (float*)malloc(sizeof(float));//(float*)Z_Malloc(sizeof(float)*3*header->numTris*3, ztag); - //float *vertptr, *normptr; + retModel->meshes[0].frames[i].normals = (float*)Z_Malloc(sizeof(float) * 3 * header->numTris * 3, ztag, NULL); + retModel->meshes[0].frames[i].vertices = (float*)Z_Malloc(sizeof(float) * 3 * header->numTris * 3, ztag, NULL); + normptr = (float*)retModel->meshes[0].frames[i].normals; vertptr = (float*)retModel->meshes[0].frames[i].vertices; trisPtr = tris; diff --git a/src/hardware/hw_md3load.c b/src/hardware/hw_md3load.c index 53f6034c0..73111f63e 100644 --- a/src/hardware/hw_md3load.c +++ b/src/hardware/hw_md3load.c @@ -154,7 +154,7 @@ model_t *MD3_LoadModel(const char *fileName, int ztag, boolean useFloat) char *buffer; int surfEnd; int i, t; - int matCount; + //int matCount; FILE *f; if (!latlnginit) @@ -168,7 +168,7 @@ model_t *MD3_LoadModel(const char *fileName, int ztag, boolean useFloat) if (!f) return NULL; - retModel = (model_t*)Z_Calloc(sizeof(model_t), ztag, 0); + retModel = (model_t*)Z_Calloc(sizeof(model_t), ztag, NULL); // find length of file fseek(f, 0, SEEK_END); @@ -201,7 +201,7 @@ model_t *MD3_LoadModel(const char *fileName, int ztag, boolean useFloat) if (retModel->numMaterials <= 0) // Always at least one skin, duh retModel->numMaterials = 1; - retModel->materials = (material_t*)Z_Calloc(sizeof(material_t)*retModel->numMaterials, ztag, 0); + retModel->materials = (material_t*)Z_Calloc(sizeof(material_t)*retModel->numMaterials, ztag, NULL); for (t = 0; t < retModel->numMaterials; t++) { @@ -225,9 +225,9 @@ model_t *MD3_LoadModel(const char *fileName, int ztag, boolean useFloat) retModel->materials[t].spheremap = false; } - retModel->meshes = (mesh_t*)Z_Calloc(sizeof(mesh_t)*retModel->numMeshes, ztag, 0); + retModel->meshes = (mesh_t*)Z_Calloc(sizeof(mesh_t)*retModel->numMeshes, ztag, NULL); - matCount = 0; + //matCount = 0; for (i = 0, surfEnd = 0; i < mdh->numSurfaces; i++) { int j; @@ -237,54 +237,12 @@ model_t *MD3_LoadModel(const char *fileName, int ztag, boolean useFloat) mdShader = (md3Shader*)((char*)mdS + mdS->offsetShaders); - for (j = 0; j < mdS->numShaders; j++, matCount++) + for (j = 0; j < mdS->numShaders; j++ /*, matCount++*/) { size_t len = strlen(mdShader[j].name); mdShader[j].name[len-1] = 'z'; mdShader[j].name[len-2] = 'u'; mdShader[j].name[len-3] = 'b'; - - // Load material -/* retModel->materials[matCount].texture = Texture::ReadTexture(mdShader[j].name, ZT_TEXTURE); - - if (!systemSucks) - { - // Check for a normal map...?? - char openfilename[1024]; - char normalMapName[1024]; - strcpy(normalMapName, mdShader[j].name); - len = strlen(normalMapName); - char *ptr = &normalMapName[len]; - ptr--; // z - ptr--; // u - ptr--; // b - ptr--; // . - *ptr++ = '_'; - *ptr++ = 'n'; - *ptr++ = '.'; - *ptr++ = 'b'; - *ptr++ = 'u'; - *ptr++ = 'z'; - *ptr++ = '\0'; - - sprintf(openfilename, "%s/%s", "textures", normalMapName); - // Convert backslashes to forward slashes - for (int k = 0; k < 1024; k++) - { - if (openfilename[k] == '\0') - break; - - if (openfilename[k] == '\\') - openfilename[k] = '/'; - } - - Resource::resource_t *res = Resource::Open(openfilename); - if (res) - { - Resource::Close(res); - retModel->materials[matCount].lightmap = Texture::ReadTexture(normalMapName, ZT_TEXTURE); - } - }*/ } retModel->meshes[i].numFrames = mdS->numFrames; @@ -298,26 +256,22 @@ model_t *MD3_LoadModel(const char *fileName, int ztag, boolean useFloat) unsigned short *indexptr; md3Triangle *mdT; - retModel->meshes[i].tinyframes = (tinyframe_t*)Z_Calloc(sizeof(tinyframe_t)*mdS->numFrames, ztag, 0); + retModel->meshes[i].tinyframes = (tinyframe_t*)Z_Calloc(sizeof(tinyframe_t)*mdS->numFrames, ztag, NULL); retModel->meshes[i].numVertices = mdS->numVerts; - retModel->meshes[i].uvs = (float*)Z_Malloc(sizeof(float)*2*mdS->numVerts, ztag, 0); + retModel->meshes[i].uvs = (float*)Z_Malloc(sizeof(float)*2*mdS->numVerts, ztag, NULL); for (j = 0; j < mdS->numFrames; j++) { short *vertptr; char *normptr; - // char *tanptr; int k; md3Vertex *mdV = (md3Vertex*)((char*)mdS + mdS->offsetXYZNormal + (mdS->numVerts*j*sizeof(md3Vertex))); - retModel->meshes[i].tinyframes[j].vertices = (short*)Z_Malloc(sizeof(short)*3*mdS->numVerts, ztag, 0); - retModel->meshes[i].tinyframes[j].normals = (char*)Z_Malloc(sizeof(char)*3*mdS->numVerts, ztag, 0); + retModel->meshes[i].tinyframes[j].vertices = (short*)Z_Malloc(sizeof(short)*3*mdS->numVerts, ztag, NULL); + retModel->meshes[i].tinyframes[j].normals = (char*)Z_Malloc(sizeof(char)*3*mdS->numVerts, ztag, NULL); -// if (retModel->materials[0].lightmap) -// retModel->meshes[i].tinyframes[j].tangents = (char*)malloc(sizeof(char));//(char*)Z_Malloc(sizeof(char)*3*mdS->numVerts, ztag); - retModel->meshes[i].indices = (unsigned short*)Z_Malloc(sizeof(unsigned short) * 3 * mdS->numTriangles, ztag, 0); + retModel->meshes[i].indices = (unsigned short*)Z_Malloc(sizeof(unsigned short) * 3 * mdS->numTriangles, ztag, NULL); vertptr = retModel->meshes[i].tinyframes[j].vertices; normptr = retModel->meshes[i].tinyframes[j].normals; -// tanptr = retModel->meshes[i].tinyframes[j].tangents; retModel->meshes[i].tinyframes[j].material = &retModel->materials[i]; for (k = 0; k < mdS->numVerts; k++) @@ -374,18 +328,17 @@ model_t *MD3_LoadModel(const char *fileName, int ztag, boolean useFloat) int k; retModel->meshes[i].numVertices = mdS->numTriangles * 3;//mdS->numVerts; - retModel->meshes[i].frames = (mdlframe_t*)Z_Calloc(sizeof(mdlframe_t)*mdS->numFrames, ztag, 0); - retModel->meshes[i].uvs = (float*)Z_Malloc(sizeof(float)*2*mdS->numTriangles*3, ztag, 0); + retModel->meshes[i].frames = (mdlframe_t*)Z_Calloc(sizeof(mdlframe_t)*mdS->numFrames, ztag, NULL); + retModel->meshes[i].uvs = (float*)Z_Malloc(sizeof(float)*2*mdS->numTriangles*3, ztag, NULL); for (j = 0; j < mdS->numFrames; j++) { float *vertptr; float *normptr; md3Vertex *mdV = (md3Vertex*)((char*)mdS + mdS->offsetXYZNormal + (mdS->numVerts*j*sizeof(md3Vertex))); - retModel->meshes[i].frames[j].vertices = (float*)Z_Malloc(sizeof(float)*3*mdS->numTriangles*3, ztag, 0); - retModel->meshes[i].frames[j].normals = (float*)Z_Malloc(sizeof(float)*3*mdS->numTriangles*3, ztag, 0); -// if (retModel->materials[i].lightmap) -// retModel->meshes[i].frames[j].tangents = (float*)malloc(sizeof(float));//(float*)Z_Malloc(sizeof(float)*3*mdS->numTriangles*3, ztag); + retModel->meshes[i].frames[j].vertices = (float*)Z_Malloc(sizeof(float)*3*mdS->numTriangles*3, ztag, NULL); + retModel->meshes[i].frames[j].normals = (float*)Z_Malloc(sizeof(float)*3*mdS->numTriangles*3, ztag, NULL); + vertptr = retModel->meshes[i].frames[j].vertices; normptr = retModel->meshes[i].frames[j].normals; retModel->meshes[i].frames[j].material = &retModel->materials[i]; @@ -471,38 +424,6 @@ model_t *MD3_LoadModel(const char *fileName, int ztag, boolean useFloat) } } } - /* - // Tags? - retModel->numTags = mdh->numTags; - retModel->maxNumFrames = mdh->numFrames; - retModel->tags = (tag_t*)Z_Calloc(sizeof(tag_t) * retModel->numTags * mdh->numFrames, ztag); - md3Tag *mdTag = (md3Tag*)&buffer[mdh->offsetTags]; - tag_t *curTag = retModel->tags; - for (i = 0; i < mdh->numFrames; i++) - { - int j; - for (j = 0; j < retModel->numTags; j++, mdTag++) - { - strcpys(curTag->name, mdTag->name, sizeof(curTag->name) / sizeof(char)); - curTag->transform.m[0][0] = mdTag->axis[0]; - curTag->transform.m[0][1] = mdTag->axis[1]; - curTag->transform.m[0][2] = mdTag->axis[2]; - curTag->transform.m[1][0] = mdTag->axis[3]; - curTag->transform.m[1][1] = mdTag->axis[4]; - curTag->transform.m[1][2] = mdTag->axis[5]; - curTag->transform.m[2][0] = mdTag->axis[6]; - curTag->transform.m[2][1] = mdTag->axis[7]; - curTag->transform.m[2][2] = mdTag->axis[8]; - curTag->transform.m[3][0] = mdTag->origin[0] * WUNITS; - curTag->transform.m[3][1] = mdTag->origin[1] * WUNITS; - curTag->transform.m[3][2] = mdTag->origin[2] * WUNITS; - curTag->transform.m[3][3] = 1.0f; - - Matrix::Rotate(&curTag->transform, 90.0f, &Vector::Xaxis); - curTag++; - } - }*/ - free(buffer); diff --git a/src/hardware/hw_model.c b/src/hardware/hw_model.c index 8698365e4..274c23394 100644 --- a/src/hardware/hw_model.c +++ b/src/hardware/hw_model.c @@ -189,7 +189,7 @@ model_t *LoadModel(const char *filename, int ztag) return NULL; } - model->mdlFilename = (char*)Z_Malloc(strlen(filename)+1, ztag, 0); + model->mdlFilename = (char*)Z_Malloc(strlen(filename)+1, ztag, NULL); strcpy(model->mdlFilename, filename); Optimize(model); @@ -237,7 +237,7 @@ void GenerateVertexNormals(model_t *model) { mdlframe_t *frame = &mesh->frames[j]; int memTag = PU_STATIC; - float *newNormals = (float*)Z_Malloc(sizeof(float)*3*mesh->numTriangles*3, memTag, 0); + float *newNormals = (float*)Z_Malloc(sizeof(float)*3*mesh->numTriangles*3, memTag, NULL); int k; float *vertPtr = frame->vertices; float *oldNormals; @@ -309,7 +309,7 @@ static boolean AddMaterialToList(materiallist_t **head, material_t *material) } // Didn't find it, so add to the list - newMatNode = (materiallist_t*)Z_Malloc(sizeof(materiallist_t), PU_CACHE, 0); + newMatNode = (materiallist_t*)Z_Malloc(sizeof(materiallist_t), PU_CACHE, NULL); newMatNode->material = material; ListAdd(newMatNode, (listitem_t**)head); return true; @@ -351,7 +351,7 @@ void Optimize(model_t *model) } memTag = PU_STATIC; - newMeshes = (mesh_t*)Z_Calloc(sizeof(mesh_t) * numMeshes, memTag, 0); + newMeshes = (mesh_t*)Z_Calloc(sizeof(mesh_t) * numMeshes, memTag, NULL); i = 0; for (node = matListHead; node; node = node->next) @@ -377,14 +377,14 @@ void Optimize(model_t *model) newMesh->numFrames = 1; newMesh->numTriangles = numTriangles; newMesh->numVertices = numTriangles * 3; - newMesh->uvs = (float*)Z_Malloc(sizeof(float)*2*numTriangles*3, memTag, 0); - newMesh->frames = (mdlframe_t*)Z_Calloc(sizeof(mdlframe_t), memTag, 0); + newMesh->uvs = (float*)Z_Malloc(sizeof(float)*2*numTriangles*3, memTag, NULL); + newMesh->frames = (mdlframe_t*)Z_Calloc(sizeof(mdlframe_t), memTag, NULL); curFrame = &newMesh->frames[0]; curFrame->material = curMat; - curFrame->normals = (float*)Z_Malloc(sizeof(float)*3*numTriangles*3, memTag, 0); - curFrame->vertices = (float*)Z_Malloc(sizeof(float)*3*numTriangles*3, memTag, 0); - curFrame->colors = (char*)Z_Malloc(sizeof(char)*4*numTriangles*3, memTag, 0); + curFrame->normals = (float*)Z_Malloc(sizeof(float)*3*numTriangles*3, memTag, NULL); + curFrame->vertices = (float*)Z_Malloc(sizeof(float)*3*numTriangles*3, memTag, NULL); + curFrame->colors = (char*)Z_Malloc(sizeof(char)*4*numTriangles*3, memTag, NULL); // Now traverse the meshes of the model, adding in // vertices/normals/uvs that match the current material diff --git a/src/hardware/hw_portal.c b/src/hardware/hw_portal.c index e588adea1..c64eedad0 100644 --- a/src/hardware/hw_portal.c +++ b/src/hardware/hw_portal.c @@ -80,8 +80,8 @@ void HWR_Portal_Add2Lines(const INT32 line1, const INT32 line2, seg_t *seg) gl_portal_t *portal = HWR_Portal_Add(seg); // Offset the portal view by the linedef centers - line_t* start = &lines[line1]; - line_t* dest = &lines[line2]; + line_t* start = &lines[line1]; + line_t* dest = &lines[line2]; angle_t dangle = R_PointToAngle2(0, 0, dest->dx, dest->dy) - R_PointToAngle2(start->dx, start->dy, 0, 0); @@ -99,7 +99,7 @@ void HWR_Portal_Add2Lines(const INT32 line1, const INT32 line2, seg_t *seg) dest_c.y = dest->v1->y/2 + dest->v2->y/2; disttopoint = R_PointToDist2(start_c.x, start_c.y, viewx, viewy); - angtopoint = R_PointToAngle2(start_c.x, start_c.y, viewx, viewy); + angtopoint = R_PointToAngle2(start_c.x, start_c.y, viewx, viewy); angtopoint += dangle; portal->viewx = dest_c.x + FixedMul(FINECOSINE(angtopoint>>ANGLETOFINESHIFT), disttopoint); @@ -170,7 +170,7 @@ void HWR_RenderPortal(gl_portal_t* portal, gl_portal_t* rootportal, const float HWR_PortalFrame(portal); // call HWR_RenderViewpoint - HWR_RenderPortalViewpoint(portal, stencil_level + 1, true); + HWR_RenderPortalViewpoint(portal, stencil_level + 1); // return to current frame if (rootportal) @@ -220,9 +220,9 @@ boolean HWR_PortalCheckBBox(const fixed_t *bspcoord) if (!portalclipline) return true; - if (HWR_PortalCheckPointSide(bspcoord[BOXLEFT], bspcoord[BOXTOP]) || - HWR_PortalCheckPointSide(bspcoord[BOXLEFT], bspcoord[BOXBOTTOM]) || - HWR_PortalCheckPointSide(bspcoord[BOXRIGHT], bspcoord[BOXTOP]) || + if (HWR_PortalCheckPointSide(bspcoord[BOXLEFT], bspcoord[BOXTOP]) || + HWR_PortalCheckPointSide(bspcoord[BOXLEFT], bspcoord[BOXBOTTOM]) || + HWR_PortalCheckPointSide(bspcoord[BOXRIGHT], bspcoord[BOXTOP]) || HWR_PortalCheckPointSide(bspcoord[BOXRIGHT], bspcoord[BOXBOTTOM])) { return true; diff --git a/src/hardware/hw_shaders.c b/src/hardware/hw_shaders.c index 28f8e46d7..31723eab1 100644 --- a/src/hardware/hw_shaders.c +++ b/src/hardware/hw_shaders.c @@ -109,7 +109,7 @@ boolean HWR_InitShaders(void) // returns INT32_MAX if not found static INT32 strstr_int(const char *str1, const char *str2) { - char *location = strstr(str1, str2); + gconst char *location = strstr(str1, str2); if (location) return location - str1; else @@ -365,13 +365,17 @@ static void HWR_CompileShader(int index) if (vertex_source) { char *preprocessed = HWR_PreprocessShader(vertex_source); - if (!preprocessed) return; + if (!preprocessed) + return; + GL_LoadShader(index, preprocessed, HWD_SHADERSTAGE_VERTEX); } if (fragment_source) { char *preprocessed = HWR_PreprocessShader(fragment_source); - if (!preprocessed) return; + if (!preprocessed) + return; + GL_LoadShader(index, preprocessed, HWD_SHADERSTAGE_FRAGMENT); } @@ -387,8 +391,10 @@ void HWR_CompileShaders(void) { int custom_index = gl_shadertargets[i].custom_shader; HWR_CompileShader(i); + if (!gl_shaders[i].compiled) CONS_Alert(CONS_ERROR, "HWR_CompileShaders: Compilation failed for base %s shader!\n", shaderxlat[i].type); + if (custom_index != -1) { HWR_CompileShader(custom_index); diff --git a/src/hardware/hw_shaders.h b/src/hardware/hw_shaders.h index 40f936f69..baedebf64 100644 --- a/src/hardware/hw_shaders.h +++ b/src/hardware/hw_shaders.h @@ -76,35 +76,30 @@ // // Include GLSL_FLOOR_FUDGES or GLSL_WALL_FUDGES or define the fudges in shaders that use this macro. + +// dither shader based on +// https://github.com/hughsk/glsl-dither/blob/master/8x8.glsl +// https://github.com/libretro/glsl-shaders/blob/master/dithering/shaders/bayer_4x4.glsl +// adapted and messed about to work with srb2 and scale per resolution #define GLSL_DOOM_COLORMAP_DITHER \ "float baseValue = max(startmap * STARTMAP_FUDGE - scale * 0.5 * SCALE_FUDGE, cap);\n" \ - "float endResolutionx = scr_resolution.x;\n" \ - "float endResolutiony = scr_resolution.y;\n" \ - "if (scr_resolution.x > 1280.0) {\n" \ - "endResolutionx = scr_resolution.x * 0.5;\n" \ - "}\n" \ - "if (scr_resolution.y > 720.0) {\n" \ - "endResolutiony = scr_resolution.y * 0.5;\n" \ - "}\n" \ - "float zFactor = clamp((z - 192.0) / (6144.0 - 192.0), 0.0, 1.0);\n" \ - "int scaleFactor = int(mix(1.0, 8.0, zFactor));\n" \ - "endResolutionx = endResolutionx * scaleFactor;\n" \ - "endResolutiony = endResolutiony * scaleFactor;\n" \ - "vec2 normalizedPosition = position * vec2(endResolutionx / scr_resolution.x, endResolutiony / scr_resolution.y);\n" \ - "int x = int(mod(normalizedPosition.x, 4.0));\n" \ - "int y = int(mod(normalizedPosition.y, 4.0));\n" \ + "float patscale = min(scr_resolution.x / 1280.0, scr_resolution.y / 720.0);\n" \ + "patscale = max(floor(patscale + 0.5), 1.0);\n" \ + "patscale = 1.0 / patscale;\n" \ + "ivec2 p = ivec2(mod(floor(position * patscale), 4.0));\n" \ + "float depthfactor = clamp((z - 192.0) / (6144.0 - 192.0), 0.0, 1.0);\n" \ "float bayerMatrix[4*4] = float[4*4](\n" \ "0.0, 8.0, 2.0, 10.0,\n" \ "12.0, 4.0, 14.0, 6.0,\n" \ "3.0, 11.0, 1.0, 9.0,\n" \ "15.0, 7.0, 13.0, 5.0\n" \ ");\n" \ + "float threshold = 16.0;\n" \ "#ifdef SRB2_PALETTE_RENDERING\n" \ - "float threshold = (1.0 - pow(zFactor, 2.0)) * (bayerMatrix[y*4 + x] / 11.0);\n" \ - "#else\n" \ - "float threshold = (1.0 - pow(zFactor, 2.0)) * (bayerMatrix[y*4 + x] / 16.0);\n" \ + "threshold = 11.0;\n" \ "#endif\n" \ - "return mix(baseValue + threshold - 0.5 / 16.0, baseValue, zFactor);\n" + "threshold = (1.0 - pow(depthfactor, 2.0)) * (bayerMatrix[p.y*4 + p.x] / threshold);\n" \ + "return mix(baseValue + threshold - 0.5 / 16.0, baseValue, depthfactor);\n" #define GLSL_DOOM_COLORMAP_NODITHER \ "return max(startmap * STARTMAP_FUDGE - scale * 0.5 * SCALE_FUDGE, cap);\n" \ diff --git a/src/hardware/r_opengl/ogl_win.c b/src/hardware/r_opengl/ogl_win.c deleted file mode 100644 index 31daa22fd..000000000 --- a/src/hardware/r_opengl/ogl_win.c +++ /dev/null @@ -1,549 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// Copyright (C) 1998-2000 by DooM Legacy Team. -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -//----------------------------------------------------------------------------- -/// \file -/// \brief Windows specific part of the OpenGL API for Doom Legacy -/// -/// TODO: -/// - check if windowed mode works -/// - support different pixel formats - - -#if defined (_WIN32) - -//#define WIN32_LEAN_AND_MEAN -#define RPC_NO_WINDOWS_H -#include -#include -#include "r_opengl.h" - - -// ************************************************************************** -// GLOBALS -// ************************************************************************** - -#ifdef DEBUG_TO_FILE -static unsigned long nb_frames = 0; -static clock_t my_clock; -FILE *gllogstream; -#endif - -static HDC hDC = NULL; // the window's device context -static HGLRC hGLRC = NULL; // the OpenGL rendering context -static HWND hWnd = NULL; -static BOOL WasFullScreen = FALSE; -static void UnSetRes(void); - -#ifdef USE_WGL_SWAP -PFNWGLEXTSWAPCONTROLPROC wglSwapIntervalEXT = NULL; -#endif - -PFNglClear pglClear; -PFNglGetIntegerv pglGetIntegerv; -PFNglGetString pglGetString; - -#define MAX_VIDEO_MODES 32 -static vmode_t video_modes[MAX_VIDEO_MODES]; -INT32 oglflags = 0; - -// ************************************************************************** -// FUNCTIONS -// ************************************************************************** - -// -----------------+ -// APIENTRY DllMain : DLL Entry Point, -// : open/close debug log -// Returns : -// -----------------+ -BOOL WINAPI DllMain(HINSTANCE hinstDLL, // handle to DLL module - DWORD fdwReason, // reason for calling function - LPVOID lpvReserved) // reserved -{ - // Perform actions based on the reason for calling. - UNREFERENCED_PARAMETER(lpvReserved); - switch (fdwReason) - { - case DLL_PROCESS_ATTACH: - // Initialize once for each new process. - // Return FALSE to fail DLL load. -#ifdef DEBUG_TO_FILE - gllogstream = fopen("ogllog.txt", "wt"); - if (gllogstream == NULL) - return FALSE; -#endif - DisableThreadLibraryCalls(hinstDLL); - break; - - case DLL_THREAD_ATTACH: - // Do thread-specific initialization. - break; - - case DLL_THREAD_DETACH: - // Do thread-specific cleanup. - break; - - case DLL_PROCESS_DETACH: - // Perform any necessary cleanup. -#ifdef DEBUG_TO_FILE - if (gllogstream) - { - fclose(gllogstream); - gllogstream = NULL; - } -#endif - break; - } - - return TRUE; // Successful DLL_PROCESS_ATTACH. -} - -#ifdef STATIC_OPENGL -#define pwglGetProcAddress wglGetProcAddress; -#define pwglCreateContext wglCreateContext; -#define pwglDeleteContext wglDeleteContext; -#define pwglMakeCurrent wglMakeCurrent; -#else -static HMODULE OGL32; -typedef void *(WINAPI *PFNwglGetProcAddress) (const char *); -static PFNwglGetProcAddress pwglGetProcAddress; -typedef HGLRC (WINAPI *PFNwglCreateContext) (HDC hdc); -static PFNwglCreateContext pwglCreateContext; -typedef BOOL (WINAPI *PFNwglDeleteContext) (HGLRC hglrc); -static PFNwglDeleteContext pwglDeleteContext; -typedef BOOL (WINAPI *PFNwglMakeCurrent) (HDC hdc, HGLRC hglrc); -static PFNwglMakeCurrent pwglMakeCurrent; -#endif - -#ifndef STATIC_OPENGL -void *GetGLFunc(const char *proc) -{ - void *func = NULL; - if (pwglGetProcAddress) - func = pwglGetProcAddress(proc); - if (!func) - func = GetProcAddress(OGL32, proc); - return func; -} -#endif - -boolean LoadGL(void) -{ -#ifndef STATIC_OPENGL - OGL32 = LoadLibrary("OPENGL32.DLL"); - - if (!OGL32) - return 0; - - pwglGetProcAddress = GetGLFunc("wglGetProcAddress"); - pwglCreateContext = GetGLFunc("wglCreateContext"); - pwglDeleteContext = GetGLFunc("wglDeleteContext"); - pwglMakeCurrent = GetGLFunc("wglMakeCurrent"); -#endif - return SetupGLfunc(); -} - -// -----------------+ -// SetupPixelFormat : Set the device context's pixel format -// Note : Because we currently use only the desktop's BPP format, all the -// : video modes in Doom Legacy OpenGL are of the same BPP, thus the -// : PixelFormat is set only once. -// : Setting the pixel format more than once on the same window -// : doesn't work. (ultimately for different pixel formats, we -// : should close the window, and re-create it) -// -----------------+ -int SetupPixelFormat(INT32 WantColorBits, INT32 WantStencilBits, INT32 WantDepthBits) -{ - static DWORD iLastPFD = 0; - INT32 nPixelFormat; - PIXELFORMATDESCRIPTOR pfd = - { - sizeof (PIXELFORMATDESCRIPTOR), // size - 1, // version - PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, - PFD_TYPE_RGBA, // color type - 32 /*WantColorBits*/, // cColorBits : prefered color depth - 0, 0, // cRedBits, cRedShift - 0, 0, // cGreenBits, cGreenShift - 0, 0, // cBlueBits, cBlueShift - 0, 0, // cAlphaBits, cAlphaShift - 0, // cAccumBits - 0, 0, 0, 0, // cAccum Red/Green/Blue/Alpha Bits - 0, // cDepthBits (0,16,24,32) - 0, // cStencilBits - 0, // cAuxBuffers - PFD_MAIN_PLANE, // iLayerType - 0, // reserved, must be zero - 0, 0, 0, // dwLayerMask, dwVisibleMask, dwDamageMask - }; - - DWORD iPFD = (WantColorBits<<16) | (WantStencilBits<<8) | WantDepthBits; - - pfd.cDepthBits = (BYTE)WantDepthBits; - pfd.cStencilBits = (BYTE)WantStencilBits; - - if (iLastPFD) - { - DBG_Printf("WARNING : SetPixelFormat() called twise not supported by all drivers !\n"); - } - - // set the pixel format only if different than the current - if (iPFD == iLastPFD) - return 2; - else - iLastPFD = iPFD; - - DBG_Printf("SetupPixelFormat() - %d ColorBits - %d StencilBits - %d DepthBits\n", - WantColorBits, WantStencilBits, WantDepthBits); - - nPixelFormat = ChoosePixelFormat(hDC, &pfd); - - if (nPixelFormat == 0) - DBG_Printf("ChoosePixelFormat() FAILED\n"); - - if (SetPixelFormat(hDC, nPixelFormat, &pfd) == 0) - { - DBG_Printf("SetPixelFormat() FAILED\n"); - return 0; - } - - return 1; -} - - -// -----------------+ -// SetRes : Set a display mode -// Notes : pcurrentmode is actually not used -// -----------------+ -static INT32 WINAPI SetRes(viddef_t *lvid, vmode_t *pcurrentmode) -{ - LPCSTR renderer; - BOOL WantFullScreen = !(lvid->u.windowed); //(lvid->u.windowed ? 0 : CDS_FULLSCREEN); - - UNREFERENCED_PARAMETER(pcurrentmode); - DBG_Printf ("SetMode(): %dx%d %d bits (%s)\n", - lvid->width, lvid->height, lvid->bpp*8, - WantFullScreen ? "fullscreen" : "windowed"); - - hWnd = lvid->WndParent; - - // BP : why flush texture ? - // if important flush also the first one (white texture) and restore it ! - Flush(); // Flush textures. - -// TODO: if not fullscreen, skip display stuff and just resize viewport stuff ... - - // Exit previous mode - //if (hGLRC) //Hurdler: TODO: check if this is valid - // UnSetRes(); - if (WasFullScreen) - ChangeDisplaySettings(NULL, CDS_FULLSCREEN); //switch in and out of fullscreen - - // Change display settings. - if (WantFullScreen) - { - DEVMODE dm; - ZeroMemory(&dm, sizeof (dm)); - dm.dmSize = sizeof (dm); - dm.dmPelsWidth = lvid->width; - dm.dmPelsHeight = lvid->height; - dm.dmBitsPerPel = lvid->bpp*8; - dm.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL; - if (ChangeDisplaySettings(&dm, CDS_TEST) != DISP_CHANGE_SUCCESSFUL) - return -2; - if (ChangeDisplaySettings(&dm, CDS_FULLSCREEN) !=DISP_CHANGE_SUCCESSFUL) - return -3; - - SetWindowLong(hWnd, GWL_STYLE, WS_POPUP|WS_VISIBLE); - // faB : book says to put these, surely for windowed mode - //WS_CLIPCHILDREN|WS_CLIPSIBLINGS); - SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, lvid->width, lvid->height, SWP_NOACTIVATE|SWP_NOZORDER); - } - else - { - RECT bounds; - INT32 x, y; - INT32 w = lvid->width, h = lvid->height; - GetWindowRect(hWnd, &bounds); - bounds.right = bounds.left+w; - bounds.bottom = bounds.top+h; - AdjustWindowRectEx(&bounds, GetWindowLong(hWnd, GWL_STYLE), (GetMenu(hWnd) != NULL), 0); - w = bounds.right-bounds.left; - h = bounds.bottom-bounds.top; - x = (GetSystemMetrics(SM_CXSCREEN)-w)/2; - y = (GetSystemMetrics(SM_CYSCREEN)-h)/2; - SetWindowPos(hWnd, NULL, x, y, w, h, SWP_NOACTIVATE|SWP_NOZORDER); - } - - if (!hDC) - hDC = GetDC(hWnd); - if (!hDC) - { - DBG_Printf("GetDC() FAILED\n"); - return 0; - } - - { - INT32 res; - - // Set res. - res = SetupPixelFormat(lvid->bpp*8, 0, 16); - - if (res == 0) - return 0; - else if (res == 1) - { - // Exit previous mode - if (hGLRC) - UnSetRes(); - hGLRC = pwglCreateContext(hDC); - if (!hGLRC) - { - DBG_Printf("pwglCreateContext() FAILED\n"); - return 0; - } - if (!pwglMakeCurrent(hDC, hGLRC)) - { - DBG_Printf("wglMakeCurrent() FAILED\n"); - return 0; - } - } - } - - gl_extensions = pglGetString(GL_EXTENSIONS); - // Get info and extensions. - //BP: why don't we make it earlier ? - //Hurdler: we cannot do that before intialising gl context - renderer = (LPCSTR)pglGetString(GL_RENDERER); - DBG_Printf("Vendor : %s\n", pglGetString(GL_VENDOR)); - DBG_Printf("Renderer : %s\n", renderer); - DBG_Printf("Version : %s\n", pglGetString(GL_VERSION)); - DBG_Printf("Extensions : %s\n", gl_extensions); - - // BP: disable advenced feature that don't work on somes hardware - // Hurdler: Now works on G400 with bios 1.6 and certified drivers 6.04 - if (strstr(renderer, "810")) oglflags |= GLF_NOZBUFREAD; - DBG_Printf("oglflags : 0x%X\n", oglflags); - -#ifdef USE_WGL_SWAP - if (isExtAvailable("WGL_EXT_swap_control",gl_extensions)) - wglSwapIntervalEXT = GetGLFunc("wglSwapIntervalEXT"); - else - wglSwapIntervalEXT = NULL; -#endif - - if (isExtAvailable("GL_EXT_texture_filter_anisotropic",gl_extensions)) - pglGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &maximumAnisotropy); - else - maximumAnisotropy = 0; - - SetupGLFunc13(); - - screen_depth = (GLbyte)(lvid->bpp*8); - if (screen_depth > 16) - textureformatGL = GL_RGBA; - else - textureformatGL = GL_RGB5_A1; - - GL_SetModelView(lvid->width, lvid->height); - GL_SetStates(); - // we need to clear the depth buffer. Very important!!! - pglClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); - - lvid->buffer = NULL; // unless we use the software view - lvid->direct = NULL; // direct access to video memory, old DOS crap - - WasFullScreen = WantFullScreen; - - return 1; // on renvoie une valeur pour dire que cela s'est bien pass� -} - - -// -----------------+ -// UnSetRes : Restore the original display mode -// -----------------+ -static void UnSetRes(void) -{ - DBG_Printf("UnSetRes()\n"); - - pwglMakeCurrent(hDC, NULL); - pwglDeleteContext(hGLRC); - hGLRC = NULL; - if (WasFullScreen) - ChangeDisplaySettings(NULL, CDS_FULLSCREEN); -} - - -// -----------------+ -// GetModeList : Return the list of available display modes. -// Returns : pvidmodes - points to list of detected OpenGL video modes -// : numvidmodes - number of detected OpenGL video modes -// -----------------+ -EXPORT void HWRAPI(GetModeList) (vmode_t** pvidmodes, INT32 *numvidmodes) -{ - INT32 i; - -#if 1 - INT32 iMode; -/* - faB test code - - Commented out because there might be a problem with combo (Voodoo2 + other card), - we need to get the 3D card's display modes only. -*/ - (*pvidmodes) = &video_modes[0]; - - // Get list of device modes - for (i = 0,iMode = 0; iMode < MAX_VIDEO_MODES; i++) - { - DEVMODE Tmp; - ZeroMemory(&Tmp, sizeof (Tmp)); - Tmp.dmSize = sizeof (Tmp); - if (!EnumDisplaySettings(NULL, i, &Tmp)) - break; - - // add video mode - if (Tmp.dmBitsPerPel == 16 && - (iMode == 0 || ! - (Tmp.dmPelsWidth == video_modes[iMode-1].width && - Tmp.dmPelsHeight == video_modes[iMode-1].height) - ) - ) - { - video_modes[iMode].pnext = &video_modes[iMode+1]; - video_modes[iMode].windowed = 0; // fullscreen is the default - video_modes[iMode].misc = 0; - video_modes[iMode].name = malloc(12 * sizeof (CHAR)); - sprintf(video_modes[iMode].name, "%dx%d", (INT32)Tmp.dmPelsWidth, (INT32)Tmp.dmPelsHeight); - DBG_Printf ("Mode: %s\n", video_modes[iMode].name); - video_modes[iMode].width = Tmp.dmPelsWidth; - video_modes[iMode].height = Tmp.dmPelsHeight; - video_modes[iMode].bytesperpixel = Tmp.dmBitsPerPel/8; - video_modes[iMode].rowbytes = Tmp.dmPelsWidth * video_modes[iMode].bytesperpixel; - video_modes[iMode].pextradata = NULL; - video_modes[iMode].setmode = SetRes; - iMode++; - } - } - (*numvidmodes) = iMode; -#else - - // classic video modes (fullscreen/windowed) - // Added some. Tails - INT32 res[][2] = { - { 320, 200}, - { 320, 240}, - { 400, 300}, - { 512, 384}, - { 640, 400}, - { 640, 480}, - { 800, 600}, - { 960, 600}, - {1024, 768}, - {1152, 864}, - {1280, 800}, - {1280, 960}, - {1280,1024}, - {1600,1000}, - {1680,1050}, - {1920,1200}, -}; - - HDC bpphdc; - INT32 iBitsPerPel; - - DBG_Printf ("HWRAPI GetModeList()\n"); - - bpphdc = GetDC(NULL); // on obtient le bpp actuel - iBitsPerPel = GetDeviceCaps(bpphdc, BITSPIXEL); - - ReleaseDC(NULL, bpphdc); - - (*pvidmodes) = &video_modes[0]; - (*numvidmodes) = sizeof (res) / sizeof (res[0]); - for (i = 0; i < (*numvidmodes); i++) - { - video_modes[i].pnext = &video_modes[i+1]; - video_modes[i].windowed = 0; // fullscreen is the default - video_modes[i].misc = 0; - video_modes[i].name = malloc(12 * sizeof (CHAR)); - sprintf(video_modes[i].name, "%dx%d", res[i][0], res[i][1]); - DBG_Printf ("Mode: %s\n", video_modes[i].name); - video_modes[i].width = res[i][0]; - video_modes[i].height = res[i][1]; - video_modes[i].bytesperpixel = iBitsPerPel/8; - video_modes[i].rowbytes = res[i][0] * video_modes[i].bytesperpixel; - video_modes[i].pextradata = NULL; - video_modes[i].setmode = SetRes; - } -#endif - video_modes[(*numvidmodes)-1].pnext = NULL; -} - - -// -----------------+ -// Shutdown : Shutdown OpenGL, restore the display mode -// -----------------+ -EXPORT void HWRAPI(Shutdown) (void) -{ -#ifdef DEBUG_TO_FILE - long nb_centiemes; - - DBG_Printf ("HWRAPI Shutdown()\n"); - nb_centiemes = ((clock()-my_clock)*100)/CLOCKS_PER_SEC; - DBG_Printf("Nb frames: %li; Nb sec: %2.2f -> %2.1f fps\n", - nb_frames, nb_centiemes/100.0f, (100*nb_frames)/(double)nb_centiemes); -#endif - - Flush(); - - // Exit previous mode - if (hGLRC) - UnSetRes(); - - if (hDC) - { - ReleaseDC(hWnd, hDC); - hDC = NULL; - } - FreeLibrary(OGL32); - DBG_Printf ("HWRAPI Shutdown(DONE)\n"); -} - -// -----------------+ -// FinishUpdate : Swap front and back buffers -// -----------------+ -void GL_FinishUpdate (INT32 waitvbl) -{ -#ifdef USE_WGL_SWAP - static INT32 oldwaitvbl = 0; -#else - UNREFERENCED_PARAMETER(waitvbl); -#endif - // DBG_Printf ("FinishUpdate()\n"); -#ifdef DEBUG_TO_FILE - if ((++nb_frames)==2) // on ne commence pas � la premi�re frame - my_clock = clock(); -#endif - -#ifdef USE_WGL_SWAP - if (oldwaitvbl != waitvbl && wglSwapIntervalEXT) - wglSwapIntervalEXT(waitvbl); - oldwaitvbl = waitvbl; -#endif - - SwapBuffers(hDC); -} -#endif diff --git a/src/hardware/r_opengl/r_opengl.c b/src/hardware/r_opengl/r_opengl.c index 94656e843..0e846a17e 100644 --- a/src/hardware/r_opengl/r_opengl.c +++ b/src/hardware/r_opengl/r_opengl.c @@ -98,10 +98,10 @@ static size_t textureBufferSize = 0; static LTListItem *LightTablesTail = NULL; static LTListItem *LightTablesHead = NULL; -static RGBA_t screenPalette[256] = {0}; // the palette for the postprocessing step in palette rendering +static RGBA_t screenPalette[256] = {}; // the palette for the postprocessing step in palette rendering static GLuint screenPaletteTex = 0; // 1D texture containing the screen palette static GLuint paletteLookupTex = 0; // 3D texture containing RGB -> palette index lookup table -RGBA_t myPaletteData[256] = {0}; // the palette for converting textures to RGBA +RGBA_t myPaletteData[256] = {}; // the palette for converting textures to RGBA static GLint gltexformat = GL_RGB5_A1; GLint screen_width = 0; // used by Draw2DLine() @@ -127,9 +127,9 @@ GLuint gl_num_extensions; int majorGL = 0, minorGL = 0; //Hurdler: 04/10/2000: added for the kick ass coronas as Boris wanted;-) -GLfloat modelMatrix[16] = {0}; -GLfloat projMatrix[16] = {0}; -static GLint viewport[4]; +GLfloat modelMatrix[16] = {}; +GLfloat projMatrix[16] = {}; +static GLint viewport[4]; #ifdef USE_FBO_OGL enum @@ -171,7 +171,7 @@ boolean supportstencil = false; // flush all of the stored textures, leaving them unavailable at times such as between levels // These need to start at 0 and be set to their number, and be reset to 0 when deleted so that Intel GPUs // can know when the textures aren't there, as textures are always considered resident in their virtual memory -static GLuint screenTextures[NUMSCREENTEXTURES] = {0}; +static GLuint screenTextures[NUMSCREENTEXTURES] = {}; #define byte2float(byte) (GLfloat)(byte / 255.0f) @@ -404,6 +404,14 @@ static PFNglEnableClientState pglEnableClientState; typedef void (APIENTRY * PFNglDisableClientState) (GLenum cap); static PFNglDisableClientState pglDisableClientState; +typedef void (APIENTRY * PFNglOrtho) (GLdouble left, + GLdouble right, + GLdouble bottom, + GLdouble top, + GLdouble nearVal, + GLdouble farVal); +static PFNglOrtho pglOrtho; + /* Lighting */ typedef void (APIENTRY * PFNglShadeModel) (GLenum mode); static PFNglShadeModel pglShadeModel; @@ -745,7 +753,7 @@ typedef struct gl_shaderstate_s static gl_shaderstate_t gl_shaderstate; // Shader info -static float shader_leveltime = 0; +static float shader_leveltime = 0.0f; static float shader_light_x = 0.0f; static float shader_light_y = 0.0f; static float shader_light_z = 0.0f; @@ -768,15 +776,15 @@ static int GLFramebuffer_CheckExt(void) // gl versions from 2.1 may still support framebuffer objects // maybe, just maybe, we support the standart extensions - if (GL_isExtAvailable("GL_ARB_framebuffer_no_attachments", gl_extensions) - && GL_isExtAvailable("GL_ARB_framebuffer_object", gl_extensions) - && GL_isExtAvailable("GL_ARB_framebuffer_sRGB", gl_extensions)) + if (GL_isExtAvailable("GL_ARB_framebuffer_no_attachments", gl_extensions) && + GL_isExtAvailable("GL_ARB_framebuffer_object", gl_extensions) && + GL_isExtAvailable("GL_ARB_framebuffer_sRGB", gl_extensions)) return FBO_ARB; // nope, try the older 2.1 extensions - if (GL_isExtAvailable("GL_EXT_framebuffer_no_attachments", gl_extensions) - && GL_isExtAvailable("GL_EXT_framebuffer_object", gl_extensions) - && GL_isExtAvailable("GL_EXT_framebuffer_sRGB", gl_extensions)) + if (GL_isExtAvailable("GL_EXT_framebuffer_no_attachments", gl_extensions) && + GL_isExtAvailable("GL_EXT_framebuffer_object", gl_extensions) && + GL_isExtAvailable("GL_EXT_framebuffer_sRGB", gl_extensions)) { // perhaps we may even support a stencil attachment if (GL_isExtAvailable("GL_EXT_packed_depth_stencil", gl_extensions)) @@ -858,6 +866,8 @@ void SetupGLFunc4(void) GetGLfunc(glUniform3fv); GetGLfunc(glGetUniformLocation); + GetGLfunc(glOrtho); + #ifdef GLDEBUGMESSAGE GetGLfunc(glDebugMessageCallback); #endif @@ -875,7 +885,7 @@ void SetupGLFunc4(void) { \ GL_MSG_Warning("failed to get OpenGL FBO function: %s\n", #func); \ GL_DBG_Printf("\nFBO: No framebuffer object support\n"); \ - supportFBO = false; \ + supportFBO = FBO_NONE; \ return; \ } \ @@ -1058,6 +1068,13 @@ void GL_SetShader(int slot) gl_shadersenabled = false; } +void GL_EnableShader(void) +{ + // we can just use GL_Shader_SetUniforms as itll enable the shader for us + // and handle any failures + GL_Shader_SetUniforms(NULL, NULL, NULL, NULL); +} + void GL_UnSetShader(void) { if (gl_shadersenabled) // don't repeatedly call glUseProgram if not needed @@ -1105,7 +1122,7 @@ static void GL_Perspective(GLfloat fovy, GLfloat aspect) const GLfloat deltaZ = FAR_CLIPPING_PLANE - NEAR_CLIPPING_PLANE; - if ((fabsf((float)deltaZ) < 1.0E-36f) || fpclassify(aspect) == FP_ZERO) + if ((fabsf(deltaZ) < 1.0E-36f) || fpclassify(aspect) == FP_ZERO) { return; } @@ -1267,7 +1284,7 @@ void GL_SetStates(void) pglColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); - pglEnable(GL_STENCIL_TEST); + pglDisable(GL_STENCIL_TEST); pglEnable(GL_DEPTH_TEST); // check the depth buffer pglDepthMask(GL_TRUE); // enable writing to depth buffer pglClearDepth(1.0f); @@ -1297,6 +1314,16 @@ void GL_SetStates(void) #endif } +void GL_EnableStencilTest(void) +{ + pglEnable(GL_STENCIL_TEST); +} + +void GL_DisableStencilTest(void) +{ + pglDisable(GL_STENCIL_TEST); +} + // -----------------+ // DeleteTexture : Deletes a texture from the GPU and frees its data // -----------------+ @@ -1373,19 +1400,19 @@ void GL_Flush(void) // -----------------+ INT32 GL_isExtAvailable(const char *extension, const GLubyte *start) { - GLubyte *where, *terminator; + gconst GLubyte *where, *terminator; if (!extension || !start) return 0; - where = (GLubyte *) strchr(extension, ' '); + where = (gconst GLubyte *)strchr(extension, ' '); if (where || *extension == '\0') return 0; for (;;) { - where = (GLubyte *) strstr((const char *) start, extension); + where = (gconst GLubyte *)strstr((const char *)start, extension); if (!where) break; @@ -1438,6 +1465,19 @@ void GL_ReadScreenTexture(int tex, UINT8 *restrict dest, INT32 scale) if (tex != HWD_SCREENTEXTURE_GENERIC2) GL_DrawScreenTexture(tex, NULL, 0); +#ifdef USE_FBO_OGL + // FIXME: this is incredibly stupid + // but the final screen texture will NOT be drawn in the downsample fbo + if (tex == HWD_SCREENTEXTURE_GENERIC2 && + UseScreenFBO() && HWR_ShouldUsePaletteRendering()) + { + GL_SetShader(HWR_GetShaderFromTarget(SHADER_PALETTE_POSTPROCESS)); + GL_EnableShader(); + GL_DrawScreenTexture(HWD_SCREENTEXTURE_GENERIC2, NULL, 0); + GL_UnSetShader(); + } +#endif + image = malloc(screen_width*screen_height*3); pglPixelStorei(GL_PACK_ALIGNMENT, 1); pglReadPixels(0, 0, screen_width, screen_height, GL_RGB, GL_UNSIGNED_BYTE, image); @@ -1556,6 +1596,7 @@ void GL_Draw2DLine(F2DCoord * v1, F2DCoord * v2, RGBA_t Color) angle = atanf((v2->y-v1->y)/(v2->x-v1->x)); else angle = (float)N_PI_DEMI; + dx = sinf(angle) / (float)screen_width; dy = cosf(angle) / (float)screen_height; @@ -1670,7 +1711,7 @@ static void GL_SetBlendMode(FBITFIELD flags) void GL_SetBlend(FBITFIELD PolyFlags) { - const FBITFIELD Xor = CurrentPolyFlags^PolyFlags;; + const FBITFIELD Xor = CurrentPolyFlags^PolyFlags; if (Xor & (PF_Blending|PF_RemoveYWrap|PF_ForceWrapX|PF_ForceWrapY|PF_Occlude|PF_NoTexture|PF_Modulated|PF_NoDepthTest|PF_Decal|PF_Skydecal|PF_Invisible)) { @@ -2462,7 +2503,7 @@ void GL_RenderSkyDome(gl_sky_t *sky) GL_Shader_SetUniforms(NULL, NULL, NULL, NULL); // Build the sky dome! Yes! - if (sky->rebuild) + if (sky->rebuild || !sky->vbo) { // delete VBO when already exists if (sky->vbo) @@ -2887,7 +2928,7 @@ void GL_CreateModelVBOs(model_t *model) } } -#define BUFFER_OFFSET(i) ((char*)(i)) +#define BUFFER_OFFSET(i) ((void*)(i)) void GL_DrawModelEx(model_t *model, INT32 frameIndex, float duration, float tics, INT32 nextFrameIndex, FTransform *pos, float hscale, float vscale, UINT8 flipped, UINT8 hflipped, FSurfaceInfo *Surface) { @@ -3090,6 +3131,39 @@ void GL_DrawModelEx(model_t *model, INT32 frameIndex, float duration, float tics pglDisable(GL_NORMALIZE); } +void GL_Draw2DModel(model_t *model, INT32 frameIndex, INT32 duration, INT32 tics, INT32 nextFrameIndex, + FTransform *pos, float hscale, float vscale, UINT8 flipped, UINT8 hflipped, FSurfaceInfo *Surface) +{ + // save our matrix´s + pglMatrixMode(GL_PROJECTION); + pglPushMatrix(); + pglMatrixMode(GL_MODELVIEW); + pglPushMatrix(); + + pglMatrixMode(GL_PROJECTION); + pglLoadIdentity(); + + // switch to ortho mode to make our lives easier + // thisll make sure our coords will be remapped to pixel coords + pglOrtho(0.0f, (float)vid.width, (float)vid.height, 0.0f, NZCLIP_PLANE, FAR_ZCLIP_DEFAULT); + + pglMatrixMode(GL_MODELVIEW); + pglLoadIdentity(); + + pglEnable(GL_DEPTH_TEST); + pglDepthMask(GL_TRUE); + pglClear(GL_DEPTH_BUFFER_BIT); + + GL_DrawModelEx(model, frameIndex, duration, tics, nextFrameIndex, + pos, hscale, vscale, flipped, hflipped, Surface); + + // restore the matrix´s + pglMatrixMode(GL_PROJECTION); + pglPopMatrix(); + pglMatrixMode(GL_MODELVIEW); + pglPopMatrix(); +} + // -----------------+ // SetTransform : // -----------------+ @@ -3147,8 +3221,8 @@ void GL_SetTransform(FTransform *stransform) { float dy = stransform->viewaiming * 2; - if (stransform->fliptype == TRANSFORM_FLIP - || stransform->fliptype == TRANSFORM_MIRRORFLIP) + if (stransform->fliptype == TRANSFORM_FLIP || + stransform->fliptype == TRANSFORM_MIRRORFLIP) dy *= -1.0f; pglTranslatef(0.0f, -dy/BASEVIDHEIGHT, 0.0f); @@ -3173,7 +3247,7 @@ void GL_SetTransform(FTransform *stransform) #ifdef USE_FBO_OGL static void GL_Framebuffer_DeleteAttachments(void) { - if (!supportFBO || !framebufferobject.init) + if (supportFBO == FBO_NONE || !framebufferobject.init) return; // Unbind the framebuffer @@ -3193,21 +3267,13 @@ static void GL_Framebuffer_DeleteAttachments(void) static void GL_Framebuffer_Generate(void) { - if (!supportFBO || framebufferobject.init || !UseScreenFBO()) + if (supportFBO == FBO_NONE || framebufferobject.init || !UseScreenFBO()) return; // Generate the framebuffer if (!framebufferobject.fboobj) pglGenFramebuffers(1, &framebufferobject.fboobj); - if (pglCheckFramebufferStatus(GL_FRAMEBUFFER_EXT) != GL_FRAMEBUFFER_COMPLETE_EXT) - { - // if this fails, dont retry it a gazillion times - // this wouldnt recover - supportFBO = false; - return; - } - // Bind the framebuffer pglBindFramebuffer(GL_FRAMEBUFFER_EXT, framebufferobject.fboobj); @@ -3221,10 +3287,10 @@ static void GL_Framebuffer_Generate(void) pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); Clamp2D(GL_TEXTURE_WRAP_S); Clamp2D(GL_TEXTURE_WRAP_T); - pglBindTexture(GL_TEXTURE_2D, 0); // Attach the framebuffer texture to the framebuffer pglFramebufferTexture2D(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, framebufferobject.tex, 0); + pglBindTexture(GL_TEXTURE_2D, 0); } // Generate the renderbuffer @@ -3259,6 +3325,18 @@ static void GL_Framebuffer_Generate(void) pglBindRenderbuffer(GL_RENDERBUFFER_EXT, 0); } + if (pglCheckFramebufferStatus(GL_FRAMEBUFFER_EXT) != GL_FRAMEBUFFER_COMPLETE_EXT) + { + //pglGetError(); TODO:implement this or smth + GL_MSG_Error("GL_Framebuffer_Generate: Failed to create Framebuffer Object"); + + // if this fails, dont retry it a gazillion times + // this wouldnt recover + supportFBO = FBO_NONE; + pglBindFramebuffer(GL_FRAMEBUFFER_EXT, 0); + return; + } + // Unbind the framebuffer pglBindFramebuffer(GL_FRAMEBUFFER_EXT, 0); @@ -3267,7 +3345,7 @@ static void GL_Framebuffer_Generate(void) void GL_Framebuffer_Unbind(void) { - if (!supportFBO || !framebufferobject.init) + if (supportFBO == FBO_NONE || !framebufferobject.init) return; pglBindFramebuffer(GL_FRAMEBUFFER_EXT, 0); @@ -3276,18 +3354,22 @@ void GL_Framebuffer_Unbind(void) void GL_Framebuffer_Enable(void) { - if (!supportFBO || !UseScreenFBO()) + if (supportFBO == FBO_NONE || !UseScreenFBO()) return; GL_Framebuffer_Generate(); + // failed + if (supportFBO == FBO_NONE || !framebufferobject.init) + return; + pglBindFramebuffer(GL_FRAMEBUFFER_EXT, framebufferobject.fboobj); pglBindRenderbuffer(GL_RENDERBUFFER_EXT, framebufferobject.rboobj); } void GL_Framebuffer_Disable(void) { - if (!supportFBO || !framebufferobject.init) + if (supportFBO == FBO_NONE || !framebufferobject.init) return; pglBindFramebuffer(GL_FRAMEBUFFER_EXT, 0); @@ -3548,22 +3630,30 @@ void GL_RenderVhsEffect(fixed_t upbary, fixed_t downbary, UINT8 updistort, UINT8 1.0f, -1.0f, 1.0f }; - xfix = 1/((float)screen_texsizew/(float)screen_width); - yfix = 1/((float)screen_texsizeh/(float)screen_height); - const GLfloat scrwf = (float)screen_width; const GLfloat scrwh = (float)screen_height; + xfix = 1/((float)screen_texsizew/scrwf); + yfix = 1/((float)screen_texsizeh/scrwh); + + GL_SetBlend(PF_Modulated|PF_Translucent|PF_NoDepthTest); + // Slight fuzziness GL_MakeScreenTexture(HWD_SCREENTEXTURE_VHS); - GL_SetBlend(PF_Modulated|PF_Translucent|PF_NoDepthTest); pglBindTexture(GL_TEXTURE_2D, screenTextures[HWD_SCREENTEXTURE_VHS]); - const float stride = 2.f/scrwh; + uint32_t r = rand(); - for (i = 0; i < 1; i += stride) + const float ystep = 2.f/scrwh * (float)vid.udup/4.f; + + for (i = 0; i < 1; i += ystep) { - fix[2] = (float)(rand() % 128) / -22000.f * xfix; + // avoid calling rand thousands of times + r ^= r >> 13; + r ^= r >> 11; + r ^= r << 21; + + fix[2] = (float)(r & 127) / -22000.f * xfix; fix[0] = fix[2]; fix[6] = fix[0] + xfix; fix[4] = fix[2] + xfix; @@ -3581,8 +3671,8 @@ void GL_RenderVhsEffect(fixed_t upbary, fixed_t downbary, UINT8 updistort, UINT8 } // Upward bar - //GL_MakeScreenTexture(HWD_SCREENTEXTURE_VHS); - //pglBindTexture(GL_TEXTURE_2D, screenTextures[HWD_SCREENTEXTURE_VHS]); + GL_MakeScreenTexture(HWD_SCREENTEXTURE_VHS); + pglBindTexture(GL_TEXTURE_2D, screenTextures[HWD_SCREENTEXTURE_VHS]); color[0] = color[1] = color[2] = 190; color[3] = 250; @@ -3605,13 +3695,14 @@ void GL_RenderVhsEffect(fixed_t upbary, fixed_t downbary, UINT8 updistort, UINT8 fix[1] = fix[7] += (fix[3] - fix[7])*2; screenVerts[1] = screenVerts[10] += (screenVerts[4] - screenVerts[1])*2; + pglTexCoordPointer(2, GL_FLOAT, 0, fix); pglVertexPointer(3, GL_FLOAT, 0, screenVerts); pglDrawArrays(GL_TRIANGLE_FAN, 0, 4); // Downward bar - //GL_MakeScreenTexture(HWD_SCREENTEXTURE_VHS); - //pglBindTexture(GL_TEXTURE_2D, screenTextures[HWD_SCREENTEXTURE_VHS]); + GL_MakeScreenTexture(HWD_SCREENTEXTURE_VHS); + pglBindTexture(GL_TEXTURE_2D, screenTextures[HWD_SCREENTEXTURE_VHS]); fix[0] = 0.0f; fix[6] = xfix; @@ -3630,6 +3721,7 @@ void GL_RenderVhsEffect(fixed_t upbary, fixed_t downbary, UINT8 updistort, UINT8 fix[1] = fix[7] += (fix[3] - fix[7])*2; screenVerts[1] = screenVerts[10] += (screenVerts[4] - screenVerts[1])*2; + pglTexCoordPointer(2, GL_FLOAT, 0, fix); pglVertexPointer(3, GL_FLOAT, 0, screenVerts); pglDrawArrays(GL_TRIANGLE_FAN, 0, 4); @@ -3665,11 +3757,11 @@ void GL_MakeScreenTexture(int tex) tex_downloaded = screenTextures[tex]; } -void GL_DrawScreenFinalTexture(int tex, INT32 width, INT32 height, boolean useshader) +void GL_DrawScreenFinalTexture(int tex, INT32 width, INT32 height) { float xfix, yfix; float origaspect, newaspect; - float xoff = 1, yoff = 1; // xoffset and yoffset for the polygon to have black bars around the screen + float xoff = 1.0f, yoff = 1.0f; // xoffset and yoffset for the polygon to have black bars around the screen static float off[12] = { @@ -3692,19 +3784,19 @@ void GL_DrawScreenFinalTexture(int tex, INT32 width, INT32 height, boolean usesh if (origaspect < newaspect) { xoff = origaspect / newaspect; - yoff = 1; + yoff = 1.0f; } else if (origaspect > newaspect) { - xoff = 1; + xoff = 1.0f; yoff = newaspect / origaspect; } // float off[12]; off[0] = off[3] = -xoff; off[1] = off[10] = -yoff; - off[4] = off[7] = yoff; - off[6] = off[9] = xoff; + off[4] = off[7] = yoff; + off[6] = off[9] = xoff; // float fix[8]; fix[3] = fix[5] = yfix; @@ -3718,9 +3810,6 @@ void GL_DrawScreenFinalTexture(int tex, INT32 width, INT32 height, boolean usesh pglBindTexture(GL_TEXTURE_2D, screenTextures[tex]); - if (useshader) - pglUseProgram(gl_shaders[SHADER_PALETTE_POSTPROCESS].program); // Final postprocess step of palette rendering, after everything else has been drawn. - pglColor4ubv(white); pglTexCoordPointer(2, GL_FLOAT, 0, fix); @@ -3728,9 +3817,6 @@ void GL_DrawScreenFinalTexture(int tex, INT32 width, INT32 height, boolean usesh pglDrawArrays(GL_TRIANGLE_FAN, 0, 4); - if (useshader) - pglUseProgram(0); - tex_downloaded = screenTextures[tex]; } diff --git a/src/hardware/r_opengl/r_opengl.dev b/src/hardware/r_opengl/r_opengl.dev deleted file mode 100644 index f0b23ae23..000000000 --- a/src/hardware/r_opengl/r_opengl.dev +++ /dev/null @@ -1,79 +0,0 @@ -[Project] -FileName=r_opengl.dev -Name=r_opengl -Ver=1 -IsCpp=1 -Type=3 -Compiler=-D_M_IX86=500_@@_-Wall_@@_-D_WINDOWS_@@_-DUSE_WGL_SWAP_@@_-Os_@@_-fomit-frame-pointer_@@_ -CppCompiler= -Includes= -Linker=--def ../r_mingw.def_@@_-lgdi32_@@_ -Libs= -UnitCount=3 -Folders= -ObjFiles= -PrivateResource= -ResourceIncludes= -MakeIncludes= -Icon= -ExeOutput=C:\srb2demo2 -ObjectOutput=..\..\..\objs\Mingw\r_opengl -OverrideOutput=1 -OverrideOutputName=r_opengl.dll -HostApplication= -CommandLine= -IncludeVersionInfo=0 -SupportXPThemes=0 -CompilerSet=0 -CompilerSettings=00000000000000000111d0 -UseCustomMakefile=0 -CustomMakefile= - -[Unit1] -FileName=ogl_win.c -Folder= -Compile=1 -CompileCpp=0 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[Unit2] -FileName=r_opengl.c -Folder= -Compile=1 -CompileCpp=0 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[Unit3] -FileName=r_opengl.h -Folder= -Compile=1 -CompileCpp=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[VersionInfo] -Major=0 -Minor=1 -Release=1 -Build=1 -LanguageID=1033 -CharsetID=1252 -CompanyName= -FileVersion=0.1 -FileDescription=Developed using the Dev-C++ IDE -InternalName= -LegalCopyright= -LegalTrademarks= -OriginalFilename=r_opengl.exe -ProductName=r_opengl -ProductVersion=0.1 -AutoIncBuildNr=0 - diff --git a/src/hardware/r_opengl/r_opengl.dsp b/src/hardware/r_opengl/r_opengl.dsp deleted file mode 100644 index b1603e7f2..000000000 --- a/src/hardware/r_opengl/r_opengl.dsp +++ /dev/null @@ -1,105 +0,0 @@ -# Microsoft Developer Studio Project File - Name="r_opengl" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 6.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102 - -CFG=r_opengl - Win32 Debug -!MESSAGE This is not a valid makefile. To build this project using NMAKE, -!MESSAGE use the Export Makefile command and run -!MESSAGE -!MESSAGE NMAKE /f "r_opengl.mak". -!MESSAGE -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "r_opengl.mak" CFG="r_opengl - Win32 Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "r_opengl - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library") -!MESSAGE "r_opengl - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library") -!MESSAGE - -# Begin Project -# PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "" -# PROP Scc_LocalPath "" -CPP=cl.exe -MTL=midl.exe -RSC=rc.exe - -!IF "$(CFG)" == "r_opengl - Win32 Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "r_opengl___Win32_Release" -# PROP BASE Intermediate_Dir "r_opengl___Win32_Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "..\..\..\bin\VC\Release\r_opengl" -# PROP Intermediate_Dir "..\..\..\objs\VC\Release\r_opengl" -# PROP Ignore_Export_Lib 1 -# PROP Target_Dir "" -# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "R_OPENGL_EXPORTS" /YX /FD /c -# ADD CPP /nologo /G5 /W3 /GX /Zi /O2 /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "__WIN32__" /D "__MSC__" /D "USE_WGL_SWAP" /FR /FD /c -# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 -# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 -# ADD BASE RSC /l 0x80c /d "NDEBUG" -# ADD RSC /l 0x409 /d "NDEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 -# ADD LINK32 user32.lib gdi32.lib /nologo /dll /pdb:"..\..\..\bin\VC\Release\r_opengl.pdb" /machine:I386 /out:"C:\srb2demo2\r_opengl.dll" -# SUBTRACT LINK32 /pdb:none /debug - -!ELSEIF "$(CFG)" == "r_opengl - Win32 Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "..\..\..\objs\Debug" -# PROP BASE Intermediate_Dir "..\..\..\objs\Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "..\..\..\bin\VC\Debug\r_opengl" -# PROP Intermediate_Dir "..\..\..\objs\VC\Debug\r_opengl" -# PROP Ignore_Export_Lib 1 -# PROP Target_Dir "" -# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "R_OPENGL_EXPORTS" /YX /FD /GZ /c -# ADD CPP /nologo /G6 /W4 /Gm /GX /ZI /Od /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "__WIN32__" /D "__MSC__" /D "USE_WGL_SWAP" /FR /FD /GZ /c -# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 -# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 -# ADD BASE RSC /l 0x80c /d "_DEBUG" -# ADD RSC /l 0x409 /d "_DEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept -# ADD LINK32 user32.lib gdi32.lib /nologo /dll /pdb:"..\..\..\bin\VC\Debug\r_opengl.pdb" /debug /machine:I386 /out:"C:\srb2demo2\r_opengld.dll" /pdbtype:sept -# SUBTRACT LINK32 /pdb:none - -!ENDIF - -# Begin Target - -# Name "r_opengl - Win32 Release" -# Name "r_opengl - Win32 Debug" -# Begin Source File - -SOURCE=.\ogl_win.c -# End Source File -# Begin Source File - -SOURCE=.\r_opengl.c -# End Source File -# Begin Source File - -SOURCE=.\r_opengl.h -# End Source File -# End Target -# End Project diff --git a/src/http-mserv.c b/src/http-mserv.c index 8e35f905d..c371dbb54 100644 --- a/src/http-mserv.c +++ b/src/http-mserv.c @@ -135,8 +135,7 @@ HMS_on_read (char *s, size_t _1, size_t n, void *userdata) return n; } -static struct HMS_buffer * -HMS_connect (const char *format, ...) +static struct HMS_buffer *HMS_connect(const char *format, ...) { va_list ap; CURL *curl; @@ -174,7 +173,7 @@ HMS_connect (const char *format, ...) if (cv_masterserver_token.string && cv_masterserver_token.string[0]) { quack_token = curl_easy_escape(curl, cv_masterserver_token.string, 0); - token_length = ( sizeof "&token="-1 )+ strlen(quack_token); + token_length = ( sizeof "&token="-1 ) + strlen(quack_token); } else { @@ -186,27 +185,30 @@ HMS_connect (const char *format, ...) I_lock_mutex(&hms_api_mutex); #endif - seek = strlen(hms_api) + 1;/* + '/' */ + seek = strlen(hms_api) + 1; /* + '/' */ va_start (ap, format); - url = malloc(seek + vsnprintf(0, 0, format, ap) + sizeof HMS_QUERY_VERSION - 1 + token_length + 1); + size_t url_size = (seek + vsnprintf(NULL, 0, format, ap) + + sizeof HMS_QUERY_VERSION - 1 + + token_length + 1); + url = malloc(url_size); va_end (ap); - sprintf(url, "%s/", hms_api); + snprintf(url, seek + 1, "%s/", hms_api); #ifdef HAVE_THREADS I_unlock_mutex(hms_api_mutex); #endif va_start (ap, format); - seek += vsprintf(&url[seek], format, ap); + seek += vsnprintf(&url[seek], url_size - seek, format, ap); va_end (ap); strcpy(&url[seek], HMS_QUERY_VERSION); seek += sizeof HMS_QUERY_VERSION - 1; if (quack_token) - sprintf(&url[seek], "&token=%s", quack_token); + snprintf(&url[seek], url_size - seek, "&token=%s", quack_token); Printf_url(url); @@ -225,9 +227,10 @@ HMS_connect (const char *format, ...) { cc = curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); if (cc != CURLE_OK) I_OutputMsg("libcurl: %s\n", buffer->errbuf); - +#ifdef LOGMESSAGES cc = curl_easy_setopt(curl, CURLOPT_STDERR, logstream); if (cc != CURLE_OK) I_OutputMsg("libcurl: %s\n", buffer->errbuf); +#endif } if (M_CheckParm("-bindaddr") && M_IsNextParm()) @@ -317,6 +320,7 @@ static void HMS_end (struct HMS_buffer *buffer) { curl_easy_cleanup(buffer->curl); + free(buffer->errbuf); free(buffer->buffer); free(buffer); } @@ -471,8 +475,8 @@ HMS_fetch_servers (msg_server_t *list, int query_id) *end = '\0'; address = strtok(p, " "); - port = strtok(0, " "); - contact = strtok(0, ""); + port = strtok(NULL, " "); + contact = strtok(NULL, ""); if (address && port) { @@ -539,7 +543,7 @@ HMS_compare_mod_version (char *buffer, size_t buffer_size) if (HMS_do(hms)) { version = strtok(hms->buffer, " "); - version_name = strtok(0, "\n"); + version_name = strtok(NULL, "\n"); if (version && version_name) { diff --git a/src/hu_stuff.c b/src/hu_stuff.c index a61199b39..8f131b3d2 100644 --- a/src/hu_stuff.c +++ b/src/hu_stuff.c @@ -97,7 +97,6 @@ static textinput_t w_chat; static boolean headsupactive = false; boolean hu_showscores = false; // draw rankings static char hu_tick; -static tic_t hu_emoteanim = 0; emote_autocomplete_t emote_autocomplete = {0}; static huddrawlist_h luahuddrawlist_scores = NULL; @@ -116,154 +115,12 @@ static patch_t *songcreditbg = NULL; // ------- static void HU_DrawRankings(void); - consvar_t cv_showspecstuff = {"showspecstuff", "No", CV_SAVE, CV_YesNo, NULL, 0, NULL, NULL, 0, 0, NULL}; -//====================================================================== -// KEYBOARD LAYOUTS FOR ENTERING TEXT -//====================================================================== - -char *shiftxform = NULL; - -char english_shiftxform[] = -{ - 0, - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, - 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, - 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, - 31, - ' ', '!', '"', '#', '$', '%', '&', - '"', // shift-' - '(', ')', '*', '+', - '<', // shift-, - '_', // shift-- - '>', // shift-. - '?', // shift-/ - ')', // shift-0 - '!', // shift-1 - '@', // shift-2 - '#', // shift-3 - '$', // shift-4 - '%', // shift-5 - '^', // shift-6 - '&', // shift-7 - '*', // shift-8 - '(', // shift-9 - ':', - ':', // shift-; - '<', - '+', // shift-= - '>', '?', '@', - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', - 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', - '{', // shift-[ - '|', // shift-backslash - OH MY GOD DOES WATCOM SUCK - '}', // shift-] - '"', '_', - '~', // shift-` - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', - 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', - '{', '|', '}', '~', 127 -}; - -char french_shiftxform[] = -{ - 0, - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, - 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, - 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, - 31, - ' ','$', //shift-! - '3', //shift-" - '#', '$', '%', - '1', //shift-& - '4', // shift-' - '5', // shift-( - ')', // shift-) - '*', '+', - '?', // shift-, - '6', // shift-- - '.', '/', - '0', '1', '2', '3', '4', '5', - '6', '7', '8', '9', - '/', // shitf-: - '.', // shift-; - '>', // shift-< - '+', // shift-= - '>', '?', '@', - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', - 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', - '[', '\\', ']', '^', - '8', //shift-_ - '`', - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', - 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', - '{', '|', '}', '~', 127, - 128, 129, - '2', - 131, 132, - '0', - 134, - '9', - 136, 137, - '7', - 139, 140, - '%' -}; - -char french_altgrxform[] = -{ - 0, - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, - 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, - 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, - 31, - ' ', '!', - '#', //altgr-" - '#', '$', '%', '&', - '{', //altgr-' - '[', //altgr-( - ']', //altgr-) - '*', '+', ',', - '|', //altg-- - '.', '/', - '0', '1', '2', '3', '4', '5', - '6', '7', '8', '9', - ':', ';', '<', - '}', //altgr-= - '>', '?', '@', - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', - 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', - '[', '\\', ']', '^', - '\\', //altgr-backslash - '`', - 'a', 'b', 'c', 'd', 'E', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', - 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', - '{', '|', '}', '~', 127, - 128, 129, - '~', - 131, 132, - '@', - 134, - '^', - 136, 137, - '`', - 139, 140, - KEY_FR_U_GRAVE -}; - -//fallback for special letter non displayable in the game (i.e.: 'é','à',etc.) -INT32 HU_FallBackFrSpecialLetter(INT32 key) -{ - switch(key){ - case KEY_FR_E_AIGUE: return 'e'; - case KEY_FR_E_GRAVE: return 'e'; - case KEY_FR_C_CEDILLE: return 'c'; - case KEY_FR_A_GRAVE: return 'a'; - case KEY_FR_U_GRAVE: return 'u'; - default: return key; - } -} +// stuff from SRB2-Banpyura thx alot! :3 +consvar_t cv_chat_xoffset = {"chat_xoffset", "0", CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_chat_yoffset = {"chat_yoffset", "0", CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_chat_showlimit = {"chat_showlimit", "No", CV_SAVE, CV_YesNo, NULL, 0, NULL, NULL, 0, 0, NULL}; static char cechotext[1024]; static tic_t cechotimer = 0; @@ -281,6 +138,7 @@ static void Command_Say_f(void); static void Command_Sayto_f(void); static void Command_Sayteam_f(void); static void Command_CSay_f(void); +static void Command_Mute_f(void); static void Got_Saycmd(const UINT8 **p, INT32 playernum); void HU_LoadGraphics(void) @@ -296,14 +154,14 @@ void HU_LoadGraphics(void) for (i = 0; i < HU_FONTSIZE; i++, j++) { // cache the heads-up font for entire game execution - sprintf(buffer, "STCFN%.3d", j); + snprintf(buffer, sizeof(buffer), "STCFN%.3d", j); if (W_CheckNumForName(buffer) == LUMPERROR) hu_font[i] = NULL; else hu_font[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX); // tiny version of the heads-up font - sprintf(buffer, "TNYFN%.3d", j); + snprintf(buffer, sizeof(buffer), "TNYFN%.3d", j); if (W_CheckNumForName(buffer) == LUMPERROR) tny_font[i] = NULL; else @@ -330,7 +188,7 @@ void HU_LoadGraphics(void) for (i = 0; i < KART_FONTSIZE; i++, j++) { // cache the heads-up font for entire game execution - sprintf(buffer, "MKFNT%.3d", j); + snprintf(buffer, sizeof(buffer), "MKFNT%.3d", j); if (W_CheckNumForName(buffer) == LUMPERROR) kart_font[i] = NULL; else @@ -341,7 +199,7 @@ void HU_LoadGraphics(void) j = LT_FONTSTART; for (i = 0; i < LT_FONTSIZE; i++) { - sprintf(buffer, "LTFNT%.3d", j); + snprintf(buffer, sizeof(buffer), "LTFNT%.3d", j); j++; if (W_CheckNumForName(buffer) == LUMPERROR) @@ -354,7 +212,7 @@ void HU_LoadGraphics(void) j = CRED_FONTSTART; for (i = 0; i < CRED_FONTSIZE; i++) { - sprintf(buffer, "CRFNT%.3d", j); + snprintf(buffer, sizeof(buffer), "CRFNT%.3d", j); j++; if (W_CheckNumForName(buffer) == LUMPERROR) @@ -366,11 +224,11 @@ void HU_LoadGraphics(void) // cache numbers too! for (i = 0; i < 10; i++) { - sprintf(buffer, "STTNUM%d", i); + snprintf(buffer, sizeof(buffer), "STTNUM%d", i); tallnum[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX); - sprintf(buffer, "PINGN%d", i); + snprintf(buffer, sizeof(buffer), "PINGN%d", i); pingnum[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX); - sprintf(buffer, "OPPRNK0%d", i); + snprintf(buffer, sizeof(buffer), "OPPRNK0%d", i); ranknum[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX); } @@ -382,7 +240,7 @@ void HU_LoadGraphics(void) // cache ping gfx: for (i = 0; i < 5; i++) { - sprintf(buffer, "PINGGFX%d", i+1); + snprintf(buffer, sizeof(buffer), "PINGGFX%d", i+1); pinggfx[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX); } @@ -408,8 +266,7 @@ void HU_Init(void) COM_AddCommand("csay", Command_CSay_f); RegisterNetXCmd(XD_SAY, Got_Saycmd); - // set shift translation table - shiftxform = english_shiftxform; + COM_AddCommand("muteplayer", Command_Mute_f); if (dedicated || rendermode == render_none) return; @@ -436,11 +293,6 @@ void HU_Start(void) headsupactive = true; } -void HU_Shiftform(void) -{ - shiftxform = (cv_keyboardlayout.value == 3) ? french_shiftxform : english_shiftxform; -} - //====================================================================== // EXECUTION //====================================================================== @@ -497,7 +349,9 @@ static void HU_removeChatText_Log(void) { chat_log[i] = chat_log[i+1]; } + chat_nummsg_log--; // lost 1 msg. + chat_log[chat_nummsg_log] = NULL; } static void Chatlogsize_OnChange(void) @@ -516,6 +370,7 @@ static void Chatlogsize_OnChange(void) if (new_chat_log == NULL) { free(chat_log); + chat_log = NULL; return; } chat_log = new_chat_log; @@ -541,6 +396,8 @@ void HU_AddChatText(const char *text, boolean playsound) HU_removeChatText_Log(); chat_log[chat_nummsg_log] = malloc(HU_MSGBUFSIZE); + if (!chat_log[chat_nummsg_log]) + I_Error("HU_AddChatText: out of memory for chat log\n"); strcpy(chat_log[chat_nummsg_log], text); ++chat_nummsg_log; @@ -596,12 +453,12 @@ static void DoSayCommand(SINT8 target, size_t usedargs, UINT8 flags) } // Only servers/admins can CSAY. - if(!server && !(IsPlayerAdmin(consoleplayer))) + if (!server && !(IsPlayerAdmin(consoleplayer))) flags &= ~HU_CSAY; // We handle HU_SERVER_SAY, not the caller. flags &= ~HU_SERVER_SAY; - if(dedicated && !(flags & HU_CSAY)) + if (dedicated && !(flags & HU_CSAY)) flags |= HU_SERVER_SAY; buf[0] = target; @@ -615,17 +472,23 @@ static void DoSayCommand(SINT8 target, size_t usedargs, UINT8 flags) strlcat(msg, COM_Argv(ix + usedargs), msgspace); } - if (strlen(msg) > 4 && strnicmp(msg, "/pm", 3) == 0) // used /pm + const size_t msglength = strlen(msg); + + if (msglength > 4 && strnicmp(msg, "/pm", 3) == 0) // used /pm { // what we're gonna do now is check if the node exists // with that logic, characters 4 and 5 are our numbers: const char *newmsg; INT32 spc = 1; // used if nodenum[1] is a space. - char *nodenum = (char*) malloc(3); + CLEANUP(pfree) char *nodenum = (char*)malloc(3); + if (!nodenum) + I_Error("DoSayCommand: out of memory for sending pm\n"); + memcpy(nodenum, msg+3, 2); nodenum[2] = '\0'; + // check for undesirable characters in our "number" - if (((nodenum[0] < '0') || (nodenum[0] > '9')) || ((nodenum[1] < '0') || (nodenum[1] > '9'))) + if (((nodenum[0] < '0') || (nodenum[0] > '9')) || ((nodenum[1] < '0') || (nodenum[1] > '9'))) { // check if nodenum[1] is a space if (nodenum[1] == ' ') @@ -634,23 +497,21 @@ static void DoSayCommand(SINT8 target, size_t usedargs, UINT8 flags) else { HU_AddChatText("\x82NOTICE: \x80Invalid command format. Correct format is \'/pm \'.", false); - free(nodenum); return; } } + // I'm very bad at C, I swear I am, additional checks eww! if (spc != 0) { if (msg[5] != ' ') { HU_AddChatText("\x82NOTICE: \x80Invalid command format. Correct format is \'/pm \'.", false); - free(nodenum); return; } } target = atoi((const char*) nodenum); // turn that into a number - free(nodenum); //CONS_Printf("%d\n", target); // check for target player, if it doesn't exist then we can't send the message! @@ -661,12 +522,13 @@ static void DoSayCommand(SINT8 target, size_t usedargs, UINT8 flags) HU_AddChatText(va("\x82NOTICE: \x80Player %d does not exist.", target), false); // same return; } + buf[0] = target; newmsg = msg+5+spc; strlcpy(msg, newmsg, HU_MAXMSGLEN + 1); } - SendNetXCmd(XD_SAY, buf, strlen(msg) + 1 + msg-buf); + SendNetXCmd(XD_SAY, buf, msglength + 1 + msg-buf); } /** Send a message to everyone. @@ -902,7 +764,7 @@ static void Got_Saycmd(const UINT8 **p, INT32 playernum) target = READSINT8(*p); flags = READUINT8(*p); msg = buf; - READSTRINGL(*p, msg, HU_MAXMSGLEN + 1); + READSTRINGN(*p, msg, HU_MAXMSGLEN + 1); if ((cv_mute.value || flags & (HU_CSAY|HU_SERVER_SAY)) && playernum != serverplayer && !(IsPlayerAdmin(playernum))) { @@ -917,10 +779,12 @@ static void Got_Saycmd(const UINT8 **p, INT32 playernum) return; } + const size_t msglength = strlen(msg); + //check for invalid characters (0x80 or above) { size_t i; - const size_t j = strlen(msg); + const size_t j = msglength; for (i = 0; i < j; i++) { if (msg[i] & 0x80) @@ -967,7 +831,7 @@ static void Got_Saycmd(const UINT8 **p, INT32 playernum) } // Handle "/me" actions, but only in messages to everyone. - if (target == 0 && strlen(msg) > 4 && strnicmp(msg, "/me ", 4) == 0) + if (target == 0 && msglength > 4 && strnicmp(msg, "/me ", 4) == 0) { msg += 4; action = true; @@ -1068,8 +932,7 @@ static void Got_Saycmd(const UINT8 **p, INT32 playernum) HU_AddChatText(va(fmt2, prefix, cstart, dispname, textcolor, msg), cv_chatnotifications.value); // add to chat - if (tempchar) - Z_Free(tempchar); + Z_Free(tempchar); } #ifdef _DEBUG // I just want to point out while I'm here that because the data is still @@ -1089,7 +952,6 @@ void HU_Ticker(void) return; hu_tick++; - hu_emoteanim++; hu_tick &= 7; // currently only to blink chat input cursor if (PLAYER1INPUTDOWN(gc_scores)) @@ -1109,7 +971,7 @@ void HU_Ticker(void) size_t i = 0; // handle spam while we're at it: - for(; (i < MAXPLAYERS); i++) + for (; (i < MAXPLAYERS); i++) { if (stop_spamming[i] > 0) stop_spamming[i]--; @@ -1125,7 +987,8 @@ void HU_Ticker(void) } } - if (cechotimer > 0) --cechotimer; + if (cechotimer > 0) + --cechotimer; // Animate the desynch dots if (hu_resynching @@ -1149,10 +1012,12 @@ static boolean HU_clearChatSpaces(void) size_t i = 0; // Used to just check our message char c; // current character we're iterating. boolean nothingbutspaces = true; + const size_t chatlength = strlen(w_chat_buf); - for (; i < strlen(w_chat_buf); i++) // iterate through message and eradicate all spaces that don't belong. + for (; i < chatlength; i++) // iterate through message and eradicate all spaces that don't belong. { c = w_chat_buf[i]; + if (!c) break; // if there's nothing, it's safe to assume our message has ended, so let's not waste any more time here. @@ -1161,24 +1026,46 @@ static boolean HU_clearChatSpaces(void) nothingbutspaces = false; } } + return nothingbutspaces; } -static void DoMute(const char *name) +static void DoMute(const char *name, boolean chat) { INT32 pnum = D_LookupPlayer(name); - if (pnum < 0) + // Shortcut to reuse this function for console and chat command +#define PRINT(msg, sound) do { \ + if (chat) \ + HU_AddChatText((msg), (sound)); \ + else \ + CONS_Printf("%s\n", msg); \ +} while (0) + + if (pnum < 0 || !playeringame[pnum]) { - HU_AddChatText("\x85""ERROR: \x80Player not found.", false); + PRINT("\x85""ERROR: \x80Player not found.", false); return; } player_muted[pnum] = !player_muted[pnum]; - HU_AddChatText(va("Player '%s' has been %smuted.", player_names[pnum], player_muted[pnum] ? "" : "un"), false); + PRINT(va("Player '%s' has been %smuted.", player_names[pnum], player_muted[pnum] ? "" : "un"), false); if (player_muted[pnum]) - HU_AddChatText("Use same command to unmute them.", false); + PRINT("Use same command to unmute them.", false); + +#undef PRINT +} + +static void Command_Mute_f(void) +{ + if (COM_Argc() < 2) + { + CONS_Printf(M_GetText("mute : mute/unmute a player\n")); + return; + } + + DoMute(COM_Argv(1), false); } static void HU_SendChatMessage(void) @@ -1207,23 +1094,25 @@ static void HU_SendChatMessage(void) return; } - size_t len = strlen(msg); + const size_t msglength = strlen(msg); - if (len >= 5 && strnicmp(msg, "/mute", 5) == 0) // Used /mute + if (msglength >= 5 && strnicmp(msg, "/mute", 5) == 0) // Used /mute { - if (len > 6) - DoMute(msg+6); + if (msglength > 6) + DoMute(msg+6, true); else HU_AddChatText("\x82NOTICE: \x80Usage: /mute ", false); return; } - if (len > 4 && strnicmp(msg, "/pm", 3) == 0) // used /pm + if (msglength > 4 && strnicmp(msg, "/pm", 3) == 0) // used /pm { INT32 spc = 1; // used if nodenum[1] is a space. const char *newmsg; - CLEANUP(pfree) char *nodenum = (char*) malloc(3); + CLEANUP(pfree) char *nodenum = (char*)malloc(3); + if (!nodenum) + I_Error("HU_SendChatMessage: out of memory for sending pm\n"); // what we're gonna do now is check if the node exists // with that logic, characters 4 and 5 are our numbers: @@ -1251,6 +1140,7 @@ static void HU_SendChatMessage(void) return; } } + // I'm very bad at C, I swear I am, additional checks eww! if (spc != 0) { @@ -1397,13 +1287,15 @@ boolean HU_Responder(event_t *ev) chat_on = false; I_SetTextInput(false); } - else if ((c == KEY_UPARROW || c == KEY_MOUSEWHEELUP) && chat_scroll > 0 && !OLDCHAT) // CHAT SCROLLING YAYS! + else if ((c == KEY_UPARROW || c == KEY_PGUP || c == KEY_MOUSEWHEELUP) && + ((chat_scroll > 0) && !OLDCHAT)) // CHAT SCROLLING YAYS! { chat_scroll--; justscrolledup = true; chat_scrolltime = 4; } - else if ((c == KEY_DOWNARROW || c == KEY_MOUSEWHEELDOWN) && chat_scroll < chat_maxscroll && chat_maxscroll > 0 && !OLDCHAT) + else if ((c == KEY_DOWNARROW || c == KEY_PGDN || c == KEY_MOUSEWHEELDOWN) && + ((chat_scroll < chat_maxscroll) && (chat_maxscroll > 0) && !OLDCHAT)) { chat_scroll++; justscrolleddown = true; @@ -1477,12 +1369,18 @@ static char *CHAT_WordWrap(INT32 x, INT32 w, INT32 option, const char *string) x = 0; } } + return newstring; } // 30/7/18: chaty is now the distance at which the lowest point of the chat will be drawn if that makes any sense. -INT16 chatx = 13, chaty = 169; // let's use this as our coordinates, shh +// let's use this as our coordinates, shh +// :chao: guess this just works lol +#define chatx ((INT16)(13 + (cv_chat_xoffset.value))) +#define chaty ((INT16)(169 + (cv_chat_yoffset.value))) + +#define CHATSNAP (V_SNAPTOBOTTOM|V_SNAPTOLEFT) // chat stuff by VincyTM LOL XD! @@ -1509,13 +1407,13 @@ static void HU_drawMiniChat(void) for (; i > 0; i--) { - char *msg = CHAT_WordWrap(x+2, boxw-(charwidth*2), V_SNAPTOBOTTOM|V_SNAPTOLEFT|V_ALLOWLOWERCASE, chat_mini[i-1]); + char *msg = CHAT_WordWrap(x+2, boxw-(charwidth*2), CHATSNAP|V_ALLOWLOWERCASE, chat_mini[i-1]); size_t j = 0; INT32 linescount = 0; emote_t *emote = NULL; int emotelen = 0; - while(msg[j]) // iterate through msg + while (msg[j]) // iterate through msg { if (msg[j] < HU_FONTSTART) // don't draw { @@ -1547,32 +1445,33 @@ static void HU_drawMiniChat(void) { j++; } + prev_linereturn = false; dx += charwidth; + if (dx >= boxw) { dx = 0; linescount += 1; } } + dy = 0; dx = 0; msglines += linescount+1; - if (msg) - Z_Free(msg); + Z_Free(msg); } y = chaty - charheight*(msglines+1); -#ifdef NETSPLITSCREEN if (splitscreen) { y -= BASEVIDHEIGHT/2; + if (splitscreen > 1) y += 16; } else -#endif y -= (cv_kartspeedometer.value ? 16 : 0); dx = 0; @@ -1586,12 +1485,12 @@ static void HU_drawMiniChat(void) INT32 timer = ((cv_chattime.value*TICRATE)-chat_timers[i]) - cv_chattime.value*TICRATE+9; // see below... INT32 transflag = (timer >= 0 && timer <= 9) ? (timer*V_10TRANS) : 0; // you can make bad jokes out of this one. size_t j = 0; - char *msg = CHAT_WordWrap(x+2, boxw-(charwidth*2), V_SNAPTOBOTTOM|V_SNAPTOLEFT|V_ALLOWLOWERCASE, chat_mini[i]); // get the current message, and word wrap it. + char *msg = CHAT_WordWrap(x+2, boxw-(charwidth*2), CHATSNAP|V_ALLOWLOWERCASE, chat_mini[i]); // get the current message, and word wrap it. UINT8 *colormap = NULL; emote_t *emote = NULL; int emotelen = 0; - while(msg[j]) // iterate through msg + while (msg[j]) // iterate through msg { if (msg[j] < HU_FONTSTART) // don't draw { @@ -1619,9 +1518,9 @@ static void HU_drawMiniChat(void) else if ((emote = M_VerifyEmote(msg+j, &emotelen))) { if (cv_chatbacktint.value) // on request of wolfy - V_DrawFillConsoleMap(x + dx + 2, y+dy, EMOTEWIDTH, charheight, 239|V_SNAPTOBOTTOM|V_SNAPTOLEFT); + V_DrawFillConsoleMap(x + dx + 2, y+dy, EMOTEWIDTH, charheight, 239|CHATSNAP); - M_DrawEmote(x+dx+2, y+dy, emote, V_SNAPTOBOTTOM|V_SNAPTOLEFT|transflag); + M_DrawEmote(x+dx+2, y+dy, emote, CHATSNAP|transflag); dx += EMOTEWIDTH - charwidth; j += emotelen; @@ -1629,23 +1528,24 @@ static void HU_drawMiniChat(void) else { if (cv_chatbacktint.value) // on request of wolfy - V_DrawFillConsoleMap(x + dx + 2, y+dy, charwidth, charheight, 239|V_SNAPTOBOTTOM|V_SNAPTOLEFT); + V_DrawFillConsoleMap(x + dx + 2, y+dy, charwidth, charheight, 239|CHATSNAP); - V_DrawChatCharacter(x + dx + 2, y+dy+cv_chatcentertext.value, msg[j++] |V_SNAPTOBOTTOM|V_SNAPTOLEFT|transflag, !cv_allcaps.value, colormap); + V_DrawChatCharacter(x + dx + 2, y+dy+cv_chatcentertext.value, msg[j++] |CHATSNAP|transflag, !cv_allcaps.value, colormap); } dx += charwidth; prev_linereturn = false; + if (dx >= boxw) { dx = 0; dy += charheight; } } + dy += charheight; dx = 0; - if (msg) - Z_Free(msg); + Z_Free(msg); } // decrement addy and make that shit smooth: @@ -1669,18 +1569,15 @@ static void HU_drawChatLog(INT32 offset) if (chat_scroll > chat_maxscroll) chat_scroll = chat_maxscroll; -#ifdef NETSPLITSCREEN if (splitscreen) { boxh = max(6, boxh/2); if (splitscreen > 1) boxw = max(64, boxw/2); } -#endif y = chaty - offset*charheight - (chat_scroll*charheight) - boxh*charheight - 12; -#ifdef NETSPLITSCREEN if (splitscreen) { y -= BASEVIDHEIGHT/2; @@ -1688,25 +1585,24 @@ static void HU_drawChatLog(INT32 offset) y += 16; } else -#endif y -= (cv_kartspeedometer.value ? 16 : 0); chat_topy = y + chat_scroll*charheight; chat_bottomy = chat_topy + boxh*charheight; - V_DrawFillConsoleMap(chatx, chat_topy, boxw, boxh*charheight +2, 239|V_SNAPTOBOTTOM|V_SNAPTOLEFT); // log box + V_DrawFillConsoleMap(chatx, chat_topy, boxw, boxh*charheight +2, 239|CHATSNAP); // log box - for (i=0; i= chat_topy) && (y+dy < (chat_bottomy))) { - M_DrawEmote(x+dx+2, y+dy+1, emote, V_SNAPTOBOTTOM|V_SNAPTOLEFT); + M_DrawEmote(x+dx+2, y+dy+1, emote, CHATSNAP); dx += EMOTEWIDTH - charwidth; } j += emotelen; @@ -1739,7 +1635,7 @@ static void HU_drawChatLog(INT32 offset) else { if ((y+dy+2 >= chat_topy) && (y+dy < (chat_bottomy))) - V_DrawChatCharacter(x + dx + 2, y+dy+2, msg[j++] |V_SNAPTOBOTTOM|V_SNAPTOLEFT, !cv_allcaps.value, colormap); + V_DrawChatCharacter(x + dx + 2, y+dy+2, msg[j++] |CHATSNAP, !cv_allcaps.value, colormap); else j++; // don't forget to increment this or we'll get stuck in the limbo. } @@ -1751,10 +1647,10 @@ static void HU_drawChatLog(INT32 offset) dy += charheight; } } + dy += charheight; dx = 0; - if (msg) - Z_Free(msg); + Z_Free(msg); } if (((chat_scroll >= chat_maxscroll) || (chat_scrollmedown)) && !(justscrolleddown || justscrolledup || chat_scrolltime)) // was already at the bottom of the page before new maxscroll calculation and was NOT scrolling. @@ -1776,9 +1672,9 @@ static void HU_drawChatLog(INT32 offset) // draw arrows to indicate that we can (or not) scroll. if (chat_scroll > 0) - V_DrawCharacter(chatx-9, ((justscrolledup) ? (chat_topy-1) : (chat_topy)), V_SNAPTOBOTTOM | V_SNAPTOLEFT | highlight | '\x1A', false); // up arrow + V_DrawCharacter(chatx-9, ((justscrolledup) ? (chat_topy-1) : (chat_topy)), CHATSNAP | highlight | '\x1A', false); // up arrow if (chat_scroll < chat_maxscroll) - V_DrawCharacter(chatx-9, chat_bottomy-((justscrolleddown) ? 5 : 6), V_SNAPTOBOTTOM | V_SNAPTOLEFT | highlight | '\x1B', false); // down arrow + V_DrawCharacter(chatx-9, chat_bottomy-((justscrolleddown) ? 5 : 6), CHATSNAP | highlight | '\x1B', false); // down arrow justscrolleddown = false; justscrolledup = false; @@ -1796,13 +1692,14 @@ static void HU_DrawChat(void) INT32 boxw = cv_chatwidth.value; INT32 t = 0, c = 0, y = chaty - (typelines*charheight); UINT32 i = 0, saylen = strlen(w_chat_buf); // You learn new things everyday! + UINT32 charcount = 0; INT32 cflag = 0; + INT32 pm_offset = 0; // for cases when you type emote while also doing /pm size_t select_start = 0, select_end = 0; const char *ntalk = "Say: ", *ttalk = "Team: "; const char *talk = ntalk; const char *mute = "Chat has been muted."; -#ifdef NETSPLITSCREEN if (splitscreen) { y -= BASEVIDHEIGHT/2; @@ -1813,7 +1710,6 @@ static void HU_DrawChat(void) } } else -#endif y -= (cv_kartspeedometer.value ? 16 : 0); if (teamtalk) @@ -1828,7 +1724,7 @@ static void HU_DrawChat(void) cflag = V_GRAYMAP; // set text in gray if chat is muted. } - V_DrawFillConsoleMap(chatx, y-1, boxw, (typelines*charheight), 239 | V_SNAPTOBOTTOM | V_SNAPTOLEFT); + V_DrawFillConsoleMap(chatx, y-1, boxw, (typelines*charheight), 239 | CHATSNAP); while (talk[i]) { @@ -1836,7 +1732,7 @@ static void HU_DrawChat(void) ++i; else { - V_DrawChatCharacter(chatx + c + 2, y, talk[i] |V_SNAPTOBOTTOM|V_SNAPTOLEFT|cflag, !cv_allcaps.value, V_GetStringColormap(talk[i]|cflag)); + V_DrawChatCharacter(chatx + c + 2, y, talk[i] |CHATSNAP|cflag, !cv_allcaps.value, V_GetStringColormap(talk[i]|cflag)); i++; } @@ -1854,7 +1750,7 @@ static void HU_DrawChat(void) typelines = 1; if ((w_chat.cursor == 0 || w_chat.length == 0) && hu_tick < 4) - V_DrawChatCharacter(chatx+2+c, y+1, '_'|V_SNAPTOBOTTOM|V_SNAPTOLEFT|t, !cv_allcaps.value, NULL); + V_DrawChatCharacter(chatx+2+c, y+1, '_'|CHATSNAP|t, !cv_allcaps.value, NULL); if (w_chat.select != w_chat.cursor) { @@ -1871,17 +1767,23 @@ static void HU_DrawChat(void) if ((emote = M_VerifyEmote(w_chat_buf+i, &emotelen))) { - M_DrawEmote(chatx + c + 2, y-1, emote, V_SNAPTOBOTTOM|V_SNAPTOLEFT|t); + M_DrawEmote(chatx + c + 2, y-1, emote, CHATSNAP|t); c += EMOTEWIDTH - charwidth; i += emotelen-1; drawwidth = EMOTEWIDTH; + if (cv_chat_showlimit.value) + charcount += emotelen; } else if (w_chat_buf[i] >= HU_FONTSTART) //Hurdler: isn't it better like that? - V_DrawChatCharacter(chatx + c + 2, y, w_chat_buf[i] | V_SNAPTOBOTTOM|V_SNAPTOLEFT | t, !cv_allcaps.value, NULL); + { + V_DrawChatCharacter(chatx + c + 2, y, w_chat_buf[i] | CHATSNAP | t, !cv_allcaps.value, NULL); + if (cv_chat_showlimit.value) + charcount++; + } // Draw selection if (i >= select_start && i < select_end) - V_DrawFill(chatx + c + 2 - (drawwidth-charwidth), y-1, drawwidth, charheight, 103|V_TRANSLUCENT|V_SNAPTOBOTTOM|V_SNAPTOLEFT|t); + V_DrawFill(chatx + c + 2 - (drawwidth-charwidth), y-1, drawwidth, charheight, 103|V_TRANSLUCENT|CHATSNAP|t); ++i; @@ -1890,7 +1792,7 @@ static void HU_DrawChat(void) INT32 cursorx = (c+charwidth < boxw-charwidth) ? (chatx + 2 + c+charwidth) : (chatx+1); // we may have to go down. INT32 cursory = (cursorx != chatx+1) ? (y) : (y+charheight); if (hu_tick < 4) - V_DrawChatCharacter(cursorx, cursory+1, '_' |V_SNAPTOBOTTOM|V_SNAPTOLEFT|t, !cv_allcaps.value, NULL); + V_DrawChatCharacter(cursorx, cursory+1, '_' |CHATSNAP|t, !cv_allcaps.value, NULL); if (cursorx == chatx+1 && saylen == i-1) // a weirdo hack { @@ -1908,62 +1810,11 @@ static void HU_DrawChat(void) } } - if (emote_autocomplete.emotestart != -1 && (emote_autocomplete.complete[0] || (w_chat.cursor - emote_autocomplete.emotestart) > 1)) + if (cv_chat_showlimit.value) { - emote_t *suggest; - int skip = 0; - - const char *complete; - int complete_len; - - if (emote_autocomplete.complete[0]) - { - complete = emote_autocomplete.complete; - complete_len = strlen(complete); - } - else - { - complete = &w_chat_buf[emote_autocomplete.emotestart]; - complete_len = w_chat.cursor - emote_autocomplete.emotestart; - } - - // A bit of copy-paste from /pm code :p - INT32 suggesty = chaty - charheight - 1; - size_t longest_suggestion_length = 0; - - while ((suggest = M_FindEmote(complete, complete_len, skip)) != NULL) - { - longest_suggestion_length = max(longest_suggestion_length, strlen(suggest->name)); - ++skip; - } - - skip = 0; - -#ifdef NETSPLITSCREEN - if (splitscreen) - { - suggesty -= BASEVIDHEIGHT/2; - if (splitscreen > 1) - suggesty += 16; - } - else -#endif - suggesty -= (cv_kartspeedometer.value ? 16 : 0); - - while ((suggest = M_FindEmote(complete, complete_len, skip)) != NULL) - { - V_DrawFillConsoleMap(chatx + boxw + 2, suggesty - (7*skip), (longest_suggestion_length+2)*4 + EMOTEWIDTH, 6, V_SNAPTOBOTTOM|V_SNAPTOLEFT); - - // Highlight currently suggested emote - int hlflag = 0; - if (skip == emote_autocomplete.skip && emote_autocomplete.complete[0]) - hlflag = V_YELLOWMAP; - - V_DrawSmallString(chatx + boxw + 4 + EMOTEWIDTH, suggesty - (7*skip), hlflag|V_SNAPTOBOTTOM|V_SNAPTOLEFT|V_ALLOWLOWERCASE, va(":%s:", suggest->name)); - M_DrawEmote(chatx + boxw + 2, suggesty - skip*7, suggest, V_SNAPTOBOTTOM|V_SNAPTOLEFT); - - ++skip; - } + // Limit + const INT32 clr = ((HU_MAXMSGLEN - charcount) > 64 ? V_TRANSLUCENT : (charcount == HU_MAXMSGLEN ? V_REDMAP : V_YELLOWMAP)); + V_DrawSmallString(chatx, y+7, CHATSNAP|clr, va("%d/%d", charcount, HU_MAXMSGLEN)); } // handle /pm list. It's messy, horrible and I don't care. @@ -1972,7 +1823,7 @@ static void HU_DrawChat(void) INT32 count = 0; INT32 p_dispy = chaty - charheight - 1; size_t longest_name_length = 0; -#ifdef NETSPLITSCREEN + if (splitscreen) { p_dispy -= BASEVIDHEIGHT/2; @@ -1980,18 +1831,18 @@ static void HU_DrawChat(void) p_dispy += 16; } else -#endif p_dispy -= (cv_kartspeedometer.value ? 16 : 0); // Find longest player name, for drawing background for /pm list later for (i = 0; i < MAXPLAYERS; i++) { - if (!playeringame[i]) continue; + if (!playeringame[i]) + continue; longest_name_length = max(longest_name_length, strlen(player_names[i])); } - for(i = 0; i < MAXPLAYERS; i++) + for (i = 0; i < MAXPLAYERS; i++) { if (!playeringame[i]) continue; @@ -2001,6 +1852,7 @@ static void HU_DrawChat(void) { char nodenum[3]; UINT32 n; + // right, that's half important: (w_chat_buf[4] may be a space since /pm0 msg is perfectly acceptable!) if (!isdigit(w_chat_buf[3]) || !(isdigit(w_chat_buf[4]) || (w_chat_buf[4] == ' ') || (w_chat_buf[4] == 0))) break; @@ -2038,16 +1890,79 @@ static void HU_DrawChat(void) } // fill it like the chat so the text doesn't become hard to read because of the hud. - V_DrawFillConsoleMap(chatx + boxw + 2, p_dispy - (6*count), (longest_name_length+4)*4, 6, 239 | V_SNAPTOBOTTOM | V_SNAPTOLEFT); + V_DrawFillConsoleMap(chatx + boxw + 2, p_dispy - (6*count), (longest_name_length+4)*4, 6, 239 | CHATSNAP); - V_DrawSmallString(chatx + boxw + 4, p_dispy - (6*count), V_SNAPTOBOTTOM|V_SNAPTOLEFT|V_ALLOWLOWERCASE, va("\x82%d\x80 - %s", i, player_names[i])); + V_DrawSmallString(chatx + boxw + 4, p_dispy - (6*count), CHATSNAP|V_ALLOWLOWERCASE, va("\x82%d\x80 - %s", i, player_names[i])); count++; } if (count == 0) // no results. { - V_DrawFillConsoleMap(chatx + boxw + 2, p_dispy - (6*count), 48, 6, 239 | V_SNAPTOBOTTOM | V_SNAPTOLEFT); // fill it like the chat so the text doesn't become hard to read because of the hud. - V_DrawSmallString(chatx + boxw + 4, p_dispy - (6*count), V_SNAPTOBOTTOM|V_SNAPTOLEFT|V_ALLOWLOWERCASE, "NO RESULT."); + pm_offset = 48 + 2; + V_DrawFillConsoleMap(chatx + boxw + 2, p_dispy - (6*count), 48, 6, 239 | CHATSNAP); // fill it like the chat so the text doesn't become hard to read because of the hud. + V_DrawSmallString(chatx + boxw + 4, p_dispy - (6*count), CHATSNAP|V_ALLOWLOWERCASE, "NO RESULT."); + } + else + { + pm_offset = (longest_name_length+4)*4 + 2; + } + } + + if (emote_autocomplete.emotestart != -1 && (emote_autocomplete.complete[0] || (w_chat.cursor - emote_autocomplete.emotestart) > 1)) + { + emote_t *suggest; + int skip = 0; + + const char *complete; + int complete_len; + + if (emote_autocomplete.complete[0]) + { + complete = emote_autocomplete.complete; + complete_len = strlen(complete); + } + else + { + complete = &w_chat_buf[emote_autocomplete.emotestart]; + complete_len = w_chat.cursor - emote_autocomplete.emotestart; + } + + // A bit of copy-paste from /pm code :p + INT32 suggesty = chaty - charheight - 1; + size_t longest_suggestion_length = 0; + + while ((suggest = M_FindEmote(complete, complete_len, skip)) != NULL) + { + longest_suggestion_length = max(longest_suggestion_length, strlen(suggest->name)); + ++skip; + } + + INT32 emote_suggest_boxw = (longest_suggestion_length+2)*4 + EMOTEWIDTH; + + skip = 0; + + if (splitscreen) + { + suggesty -= BASEVIDHEIGHT/2; + if (splitscreen > 1) + suggesty += 16; + } + else + suggesty -= (cv_kartspeedometer.value ? 16 : 0); + + while ((suggest = M_FindEmote(complete, complete_len, skip)) != NULL) + { + V_DrawFillConsoleMap(chatx + boxw + pm_offset + 2, suggesty - (7*skip), emote_suggest_boxw, 6, CHATSNAP); + + // Highlight currently suggested emote + int hlflag = 0; + if (skip == emote_autocomplete.skip && emote_autocomplete.complete[0]) + hlflag = V_YELLOWMAP; + + V_DrawSmallString(chatx + boxw + pm_offset + 4 + EMOTEWIDTH, suggesty - (7*skip), hlflag|CHATSNAP|V_ALLOWLOWERCASE, va(":%s:", suggest->name)); + M_DrawEmote(chatx + boxw + pm_offset + 2, suggesty - skip*7, suggest, CHATSNAP); + + ++skip; } } @@ -2059,6 +1974,7 @@ static void HU_DrawChat(void) static void HU_DrawChat_Old(void) { INT32 t = 0, c = 0, y = HU_INPUTY; + UINT32 charcount = 0; size_t i = 0; const char *ntalk = "Say: ", *ttalk = "Say-Team: "; const char *talk = ntalk; @@ -2104,11 +2020,17 @@ static void HU_DrawChat_Old(void) { M_DrawScaledEmote((HU_INPUTX + c)<= HU_FONTSTART) //Hurdler: isn't it better like that? { //charwidth = hu_font[w_chat[i]-HU_FONTSTART]->width * con_scalefactor; V_DrawCharacter(HU_INPUTX + c, y, w_chat_buf[i] | cv_constextsize.value | V_NOSCALESTART | t, !cv_allcaps.value); + + if (cv_chat_showlimit.value) + charcount++; } // Draw selection @@ -2121,7 +2043,7 @@ static void HU_DrawChat_Old(void) { INT32 cursorx = (HU_INPUTX+c+charwidth < vid.width) ? (HU_INPUTX + c + charwidth) : (HU_INPUTX); // we may have to go down. INT32 cursory = (cursorx != HU_INPUTX) ? (y) : (y+charheight); - V_DrawCharacter(cursorx, cursory+2*con_scalefactor, '_' |cv_constextsize.value | V_NOSCALESTART|t, !cv_allcaps.value); + V_DrawCharacter(cursorx, cursory+2*con_scalefactor, '_' | cv_constextsize.value | V_NOSCALESTART |t, !cv_allcaps.value); } c += charwidth; @@ -2131,6 +2053,24 @@ static void HU_DrawChat_Old(void) y += charheight; } } + + // console chat users are FINALLY being fed! + if (cv_chat_showlimit.value) + { + const char *lim = va(" (%i/%i)", charcount, HU_MAXMSGLEN); + for (i = 0; lim[i]; i++) + { + V_DrawCharacter(HU_INPUTX + c, y, lim[i] | cv_constextsize.value | V_NOSCALESTART | t, !cv_allcaps.value); + + c += charwidth; + if (c >= vid.width) // text wrapping + { + c = 0; + y += charheight; + } + } + } + } static void HU_DrawCEcho(void) @@ -2319,12 +2259,13 @@ static void HU_DrawSongCreditsBox(void) y = -BOXCREDITHEIGHT*dup + (FixedMul(BOXCREDITHEIGHT*FRACUNIT, FixedDiv(t*FRACUNIT, TICRATE*FRACUNIT/2))*dup - interpoffset)/FRACUNIT; } - bgt = (NUMTRANSMAPS/2) + (cursongcredit.trans/2); + bgt = (NUMTRANSMAPS/2) + (cursongcredit.trans/2) - 2; // arbitrary value, looks a bit better if (bgt < NUMTRANSMAPS) { - V_DrawFill(x, y, strwidth*dup, BOXCREDITHEIGHT*dup, 28|flags|(bgt< 1))) V_DrawVhsEffect(demo.rewinding); + HU_ForceShowChat(); + // draw chat string plus cursor if (chat_on) { @@ -2438,8 +2396,7 @@ void HU_Drawer(void) // IN-LEVEL MULTIPLAYER RANKINGS //====================================================================== -static int -Ping_gfx_num (int lag) +static int Ping_gfx_num(int lag) { if (lag < 2) return 0; @@ -2453,8 +2410,7 @@ Ping_gfx_num (int lag) return 4; } -static int -Ping_gfx_color (UINT32 lag) +static int Ping_gfx_color(UINT32 lag) { if (lag < 2) return SKINCOLOR_JAWZ; @@ -2477,8 +2433,7 @@ Ping_gfx_color (UINT32 lag) return SKINCOLOR_WHITE; // to make the flashing work } -static const UINT8 * -Ping_gfx_colormap (UINT32 lag, boolean gentleman) +static const UINT8 *Ping_gfx_colormap(UINT32 lag, boolean gentleman) { const UINT8 *colormap = NULL; @@ -2498,8 +2453,7 @@ Ping_gfx_colormap (UINT32 lag, boolean gentleman) return colormap; } -static UINT32 -Ping_conversion (UINT32 lag) +static UINT32 Ping_conversion(UINT32 lag) { if (cv_pingmeasurement.value) { @@ -2616,6 +2570,26 @@ void HU_drawPlayerPing(INT32 x, INT32 y, INT32 pnum, INT32 flags) } } +void HU_drawLocalPlayerPing(INT32 x, INT32 y, INT32 flags) +{ + UINT32 lag = localplayerping; + const boolean gentleman = (cv_mindelay.value && (lag < (tic_t)simulated_lag)); + + if (gentleman) + { + lag = simulated_lag; + } + + if (cv_pingstyle.value == 0) // kart + { + HU_drawKartPing(x, y, lag, flags, gentleman); + } + else if (cv_pingstyle.value == 1) // old style ping + { + HU_drawOldPing(x, y, lag, flags, gentleman); + } +} + // // HU_DrawSpectatorTicker // @@ -2856,8 +2830,9 @@ static void HU_DrawRankings(void) scorelines++; #if MAXPLAYERS > 16 - if (scorelines > 16) - break; //dont draw past bottom of screen, show the best only + // 32 Player TODO: port over and cleanup scoreboard from sat-32p/blankart + if (scorelines >= 16) + break; // dont draw past bottom of screen, show the best only #endif } diff --git a/src/hu_stuff.h b/src/hu_stuff.h index 85ff630f5..8cfd650cb 100644 --- a/src/hu_stuff.h +++ b/src/hu_stuff.h @@ -42,15 +42,6 @@ #define CRED_FONTEND 'Z' // the last font character #define CRED_FONTSIZE (CRED_FONTEND - CRED_FONTSTART + 1) -extern char *shiftxform; // english translation shift table -extern char english_shiftxform[]; - -extern char french_shiftxform[]; -extern char french_altgrxform[]; - -//fallback for special letter non displayable in the game (i.e.: 'é','à',etc.) -INT32 HU_FallBackFrSpecialLetter(INT32 key); - //------------------------------------ // sorted player lines //------------------------------------ @@ -68,12 +59,7 @@ typedef struct #define HU_MAXMSGLEN 223 #define HU_MSGBUFSIZE 255 #define MAX_CHAT_BUFSIZE 256 // that's enough messages, right? We'll delete the older ones when that gets out of hand. -#define NETSPLITSCREEN // why the hell WOULDN'T we want this? -#ifdef NETSPLITSCREEN #define OLDCHAT (cv_consolechat.value == 1 || dedicated || vid.width < 640) -#else -#define OLDCHAT (cv_consolechat.value == 1 || dedicated || vid.width < 640) -#endif #define CHAT_MUTE (cv_mute.value && !(server || IsPlayerAdmin(consoleplayer))) // this still allows to open the chat but not to type. That's used for scrolling and whatnot. #define OLD_MUTE (OLDCHAT && cv_mute.value && !(server || IsPlayerAdmin(consoleplayer))) // this is used to prevent oldchat from opening when muted. @@ -102,6 +88,10 @@ extern patch_t *tallminus; // set true whenever the tab rankings are being shown for any reason extern boolean hu_showscores; +extern consvar_t cv_chat_xoffset; +extern consvar_t cv_chat_yoffset; +extern consvar_t cv_chat_showlimit; + // init heads up data at game startup. void HU_Init(void); @@ -110,8 +100,6 @@ void HU_LoadGraphics(void); // reset heads up when consoleplayer respawns. void HU_Start(void); -void HU_Shiftform(void); - boolean HU_Responder(event_t *ev); void HU_Ticker(void); void HU_TickSongCredits(void); @@ -120,8 +108,7 @@ void HU_Drawer(void); char HU_dequeueChatChar(void); void HU_clearChatChars(void); void HU_drawPlayerPing(INT32 x, INT32 y, INT32 pnum, INT32 flags); // Lat': Ping drawer for scoreboard. -//void HU_DrawTeamTabRankings(playersort_t *tab, INT32 whiteplayer); -//void HU_DrawDualTabRankings(INT32 x, INT32 y, playersort_t *tab, INT32 scorelines, INT32 whiteplayer); +void HU_drawLocalPlayerPing(INT32 x, INT32 y, INT32 flags); void HU_DrawTabRankings(INT32 x, INT32 y, playersort_t *tab, INT32 scorelines, INT32 hilicol); void HU_DrawEmeralds(INT32 x, INT32 y, INT32 pemeralds); const char *HU_SkinColorToConsoleColor(skincolors_t color); diff --git a/src/i_joy.h b/src/i_joy.h index 20252b54d..62562e55c 100644 --- a/src/i_joy.h +++ b/src/i_joy.h @@ -36,28 +36,7 @@ extern "C" { "JOYBUTTONS is greater than INT64 bits can hold" #endif -/** \brief The struct JoyType_s - - share some joystick information (maybe 2 for splitscreen), to the game input code, - actually, we need to know if it is a gamepad or analog controls -*/ - -struct JoyType_s -{ - /*! if true, we MUST Poll() to get new joystick data, - that is: we NEED the DIRECTINPUTDEVICE2 ! (watchout NT compatibility) */ - INT32 bJoyNeedPoll; - /*! this joystick is a gamepad, read: digital axes - if FALSE, interpret the joystick event data as JOYAXISRANGE (see above) */ - INT32 bGamepadStyle; - -}; -typedef struct JoyType_s JoyType_t; -/** \brief Joystick info - for palyer[sic] 1-4's joystick/gamepad -*/ - -extern JoyType_t Joystick[MAXSPLITSCREENPLAYERS]; +#define DigitalGamepadStyle(i) (cv_joyscale[i].value == 0) #ifdef __cplusplus } // extern "C" diff --git a/src/i_system.h b/src/i_system.h index 7084c655f..823361ce3 100644 --- a/src/i_system.h +++ b/src/i_system.h @@ -14,6 +14,9 @@ #ifndef __I_SYSTEM__ #define __I_SYSTEM__ +// page for Saturn issue reports +#define SATURNISSUEPAGE "https://github.com/Indev450/SRB2Kart-Saturn/issues" + #ifdef __cplusplus extern "C" { #endif @@ -29,6 +32,10 @@ extern "C" { */ #define MAX_QUIT_FUNCS 16 +void I_GetConsoleEvents(void); + +extern boolean consolevent; +extern boolean framebuffer; /** \brief Graphic system had started up */ @@ -39,7 +46,7 @@ extern UINT8 graphics_started; extern UINT8 keyboard_started; /** \brief Set to true when inside a signal handler that will exit the program. */ -extern boolean g_in_exiting_signal_handler; +boolean I_In_Exiting_Signal_Handler(void); /** \brief The I_GetFreeMem function @@ -144,6 +151,11 @@ extern INT32 numcontrollers; */ const char *I_GetJoyName(INT32 joyindex); +void I_SetJoystickFocus(void); + +boolean I_GamepadHasLED(INT32 playernum); +boolean I_GamepadHasRumble(INT32 playernum); + void I_GamepadRumble(INT32 playernum, UINT16 low_strength, UINT16 high_strength, UINT32 duration); void I_SetGamepadIndicatorColor(INT32 playernum, UINT8 red, UINT8 green, UINT8 blue); @@ -191,6 +203,19 @@ INT32 I_StartupSystem(void); */ void I_ShutdownSystem(void); +/** \brief To check if a Interrupt or Terminate Signal was fired + */ +boolean I_Interrupted(void); +static inline void I_HandleInterrupt(void) +{ + if (I_Interrupted()) + I_Quit(); +} + +/** \brief Open A URL + */ +int I_OpenURL(const char *url); + /** \brief The I_GetDiskFreeSpace function \param freespace a INT64 pointer to hold the free space amount @@ -212,6 +237,21 @@ char *I_GetUserName(void); */ INT32 I_mkdir(const char *dirname, INT32 unixright); +/** \brief Change current working directory + + \param path directory path + \return 0 on success, -1 on error +*/ +INT32 I_ChDir(const char *path); + +/** \brief Get current working directory + + \param buf buffer to store path + \param size size of buffer + \return buf on success, NULL on error +*/ +char *I_GetCwd(char *buf, size_t size); + /** \brief Find main WAD \return path to main WAD */ diff --git a/src/i_tcp.c b/src/i_tcp.c index 982b327d0..565d30d3c 100644 --- a/src/i_tcp.c +++ b/src/i_tcp.c @@ -213,7 +213,7 @@ static char *get_WSAErrorStr(int e) NULL); if (!buf[0]) // provide a fallback error message if no message is available for some reason - sprintf(buf, "Unknown error"); + snprintf(buf, sizeof(buf), "Unknown error"); return buf; } @@ -364,12 +364,12 @@ static const char *SOCK_AddrToStr(mysockaddr_t *sk) if (addr == NULL) { - sprintf(s, "No address"); + snprintf(s, sizeof(s), "No address"); } else if (inet_ntop(sk->any.sa_family, addr, &s[v6], sizeof (s) - v6) == NULL) { e = errno; - sprintf(s, "Unknown family type, error #%u: %s", e, strerror(e)); + snprintf(s, sizeof(s), "Unknown family type, error #%u: %s", e, strerror(e)); } #ifdef HAVE_IPV6 else if(sk->any.sa_family == AF_INET6) @@ -392,6 +392,9 @@ static const char *SOCK_GetNodeAddress(INT32 node) if (node == 0) return "self"; + if (node < 0 || node > MAXNETNODES) + return NULL; + if (!nodeconnected[node]) return NULL; @@ -413,7 +416,7 @@ static const char *SOCK_GetBanMask(size_t ban) if (ban >= numbans) return NULL; - if (sprintf(s,"%d",banned[ban].mask) > 0) + if (snprintf(s, sizeof(s), "%d",banned[ban].mask) > 0) return s; return NULL; @@ -496,8 +499,10 @@ static void cleanupnodes(void) // Why can't I start at zero? for (j = 1; j < MAXNETNODES; j++) + { if (!(nodeingame[j] || SV_SendingFile(j))) nodeconnected[j] = false; + } } static SINT8 getfreenode(void) @@ -507,11 +512,13 @@ static SINT8 getfreenode(void) cleanupnodes(); for (j = 0; j < MAXNETNODES; j++) + { if (!nodeconnected[j]) { nodeconnected[j] = true; return j; } + } /** \warning No free node? Just in case a node might not have been freed properly, * look if there are connected nodes that aren't in game, and forget them. @@ -615,7 +622,6 @@ static boolean hole_punch(ssize_t c) { return false; } - } #endif //ifdef HOLEPUNCH @@ -812,7 +818,7 @@ static void SOCK_Send(void) static void SOCK_FreeNodenum(INT32 numnode) { // can't disconnect from self :) - if (!numnode || numnode > MAXNETNODES) + if (numnode <= 0 || numnode > MAXNETNODES) return; DEBFILE(va("Free node %d (%s)\n", numnode, SOCK_GetNodeAddress(numnode))); @@ -1432,14 +1438,12 @@ static void SOCK_RegisterHolePunch(void) static boolean SOCK_OpenSocket(void) { - size_t i; - - memset(clientaddress, 0, sizeof (clientaddress)); + memset(clientaddress, 0, sizeof(clientaddress)); + memset(nodeconnected, false, sizeof(nodeconnected)); nodeconnected[0] = true; // always connected to self - for (i = 1; i < MAXNETNODES; i++) - nodeconnected[i] = false; nodeconnected[BROADCASTADDR] = true; + I_NetSend = SOCK_Send; I_NetGet = SOCK_Get; I_NetCloseSocket = SOCK_CloseSocket; @@ -1479,7 +1483,7 @@ static boolean SOCK_Ban(INT32 node) { INT32 ban; - if (node > MAXNETNODES) + if (node < 0 || node > MAXNETNODES) return false; ban = numbans; @@ -1510,11 +1514,8 @@ static boolean SOCK_SetBanUsername(const char *username) username = "Direct IP ban"; } - if (banned[numbans - 1].username) - { - Z_Free(banned[numbans - 1].username); - banned[numbans - 1].username = NULL; - } + Z_Free(banned[numbans - 1].username); + banned[numbans - 1].username = NULL; banned[numbans - 1].username = Z_StrDup(username); @@ -1528,11 +1529,8 @@ static boolean SOCK_SetBanReason(const char *reason) reason = "No reason given"; } - if (banned[numbans - 1].reason) - { - Z_Free(banned[numbans - 1].reason); - banned[numbans - 1].reason = NULL; - } + Z_Free(banned[numbans - 1].reason); + banned[numbans - 1].reason = NULL; banned[numbans - 1].reason = Z_StrDup(reason); @@ -1695,6 +1693,7 @@ boolean I_InitTcpNetwork(void) hardware_MAXPACKETLENGTH = MAXPACKETLENGTH; } } + if (M_CheckProtoParam("ip")) { COM_ImmedExecute(va("exec \"%s"PATHSEP"kartexec.cfg\" -noerror\n", srb2home)); diff --git a/src/i_time.c b/src/i_time.c index 09d5fb3fa..6e5cc3a4d 100644 --- a/src/i_time.c +++ b/src/i_time.c @@ -21,7 +21,7 @@ #include "m_fixed.h" #include "i_system.h" -timestate_t g_time; +timestate_t g_time = {}; static CV_PossibleValue_t timescale_cons_t[] = {{FRACUNIT/20, "MIN"}, {20*FRACUNIT, "MAX"}, {0, NULL}}; consvar_t cv_timescale = {"timescale", "1.0", CV_NETVAR|CV_CHEAT|CV_FLOAT, timescale_cons_t, NULL, FRACUNIT, NULL, NULL, 0, 0, NULL}; diff --git a/src/i_video.h b/src/i_video.h index f28b5a601..9a43f82a7 100644 --- a/src/i_video.h +++ b/src/i_video.h @@ -125,8 +125,6 @@ boolean I_CheckNativeRes(void); void I_SetBorderlessWindow(void); -void I_HandleControllerHatRepeat(void); - #ifdef USE_FBO_OGL void RefreshOGLSDLSurface(void); @@ -135,6 +133,15 @@ boolean UseScreenFBO(void); extern boolean downsample; #endif +// So we can call this from i_video event loop +void I_ShutdownJoystick(UINT8 index); + +// Quick thing to make SDL_JOYDEVICEADDED events less of an abomination +void I_UpdateJoystickDeviceIndex(UINT8 player); +void I_UpdateJoystickDeviceIndices(UINT8 excludePlayer); + +void I_HandleControllerHatRepeat(void); + #ifdef __cplusplus } // extern "C" #endif diff --git a/src/info.h b/src/info.h index 4ee851cee..2baae10c2 100644 --- a/src/info.h +++ b/src/info.h @@ -19,6 +19,8 @@ #include "sounds.h" #include "m_fixed.h" +#define MAXDOOMEDNUM 4095 + // dehacked.c now has lists for the more named enums! PLEASE keep them up to date! // For great modding!! @@ -450,7 +452,11 @@ void A_SpawnFreshCopy(void *actor); extern boolean actionsoverridden[NUMACTIONS]; // ratio of states to sprites to mobj types is roughly 6 : 1 : 1 +#ifdef PHOBOS_BUILD +#define NUMMOBJFREESLOTS 4096 // should be sufficient +#else #define NUMMOBJFREESLOTS 1024 +#endif #define NUMSPRITEFREESLOTS NUMMOBJFREESLOTS #define NUMSTATEFREESLOTS (NUMMOBJFREESLOTS*8) diff --git a/src/k_director.c b/src/k_director.c index 8fd5ab960..34bf367b6 100644 --- a/src/k_director.c +++ b/src/k_director.c @@ -446,6 +446,12 @@ void K_UpdateDirector(void) } } + // not sure if we should just stop here? + if (targetposition == MAXPLAYERS) + { + break; + } + target = directorinfo.sortedplayers[targetposition]; // stop here since we're already viewing this player diff --git a/src/k_hud.c b/src/k_hud.c index 59278a229..97f927a06 100644 --- a/src/k_hud.c +++ b/src/k_hud.c @@ -83,6 +83,7 @@ IMPL_HUD_OFFSET(stat); // Stats // extra hud things consvar_t cv_showstats = {"showstats", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_showstats_skinname = {"showstats_skinname", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_highresportrait = {"highresportrait", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; // make char potraits use their high-res version instead @@ -92,10 +93,13 @@ consvar_t cv_showinput = {"showinput", "Off", CV_SAVE, inputdisplay_cons_t, NULL static CV_PossibleValue_t minihead_cons_t[] = {{0, "Off"}, {1, "On"}, {2, "Others"}, {0, NULL}}; consvar_t cv_minihead = {"smallminimapplayers", "Off", CV_SAVE, minihead_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_showminimapnames = {"showminimapnames", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_showminimapfinished = {"showminimapfinished", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; CV_PossibleValue_t minimapdot_cons_t[NUMMINIMAPDOTSTUFF]; consvar_t cv_showminimapangle = {"showminimapangle", "Off", CV_SAVE, minimapdot_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_spinoutroll = {"spinoutroll", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; + static CV_PossibleValue_t posanim_cons_t[] = {{0, "Off"}, {1, "On"}, {2, "Smooth"}, {0, NULL}}; consvar_t cv_posanim = {"postitionanimation", "On", CV_SAVE, posanim_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_smallposnum = {"smallpositionnumber", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; @@ -108,6 +112,11 @@ consvar_t cv_fancyroulette = {"animatedroulette", "Off", CV_SAVE, CV_OnOff, NULL consvar_t cv_darkitembox = {"darkitembox", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; // itembox gets a dark border with specific items consvar_t cv_multiitemicon = {"multiitemicon", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; +enum { ROULETTECOLOR_NONE = -1, ROULETTECOLOR_HUD, ROULETTECOLOR_PLAYER, ROULETTECOLOR_ITEM }; +static CV_PossibleValue_t roulettecolor_cons_t[] = { + {ROULETTECOLOR_NONE, "None"}, {ROULETTECOLOR_HUD, "Hud"}, {ROULETTECOLOR_PLAYER, "Player"}, {ROULETTECOLOR_ITEM, "Item"}, {0, NULL}}; +consvar_t cv_roulettecolor = {"roulettecolor", "Hud", CV_SAVE, roulettecolor_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; + consvar_t cv_showlaptimes = {"showlaptimes", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_biglaps = {"biglaphud", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; // here for ppl who dont want to make 2 more patches for their custom hud @@ -207,6 +216,7 @@ void K_RegisterKartHudStuff(void) CV_RegisterVar(&cv_kartspeedometer); CV_RegisterVar(&cv_showstats); + CV_RegisterVar(&cv_showstats_skinname); CV_RegisterVar(&cv_showinput); CV_RegisterVar(&cv_posanim); @@ -221,7 +231,9 @@ void K_RegisterKartHudStuff(void) CV_RegisterVar(&cv_minihead); CV_RegisterVar(&cv_showminimapnames); + CV_RegisterVar(&cv_showminimapfinished); CV_RegisterVar(&cv_showminimapangle); + CV_RegisterVar(&cv_spinoutroll); CV_RegisterVar(&cv_showlapemblem); @@ -239,6 +251,8 @@ void K_RegisterKartHudStuff(void) CV_RegisterVar(&cv_multiitemicon); CV_RegisterVar(&cv_huditemamount); + CV_RegisterVar(&cv_roulettecolor); + CV_RegisterVar(&cv_highresportrait); CV_RegisterVar(&cv_nametag); @@ -270,7 +284,6 @@ void K_RegisterKartHudStuff(void) // Smol speedo static patch_t *skp_smallsticker = NULL; -static patch_t *skp_smallsticker3 = NULL; static patch_t *skp_speedpatches[5] = {NULL}; @@ -308,7 +321,6 @@ static patch_t *kp_bumperstickerwideclr = NULL; static patch_t *kp_karmastickerclr = NULL; static patch_t *kp_timeoutstickerclr = NULL; static patch_t *skp_smallstickerclr = NULL; -static patch_t *skp_smallstickerclr3 = NULL; static patch_t *kp_itemmulstickerclr[2] = {NULL}; static patch_t *kp_itembgclr[4] = {NULL}; @@ -376,7 +388,7 @@ static void K_LoadSaturnHUDGraphics(void) skp_speedpatchesdial[3] = (patch_t *)W_CachePatchName("SP_DFRAC", PU_HUDGFX); skp_speedpatchesdial[4] = (patch_t *)W_CachePatchName("SP_DPERC", PU_HUDGFX); - sprintf(buffer, "K_DSPNMx"); + snprintf(buffer, sizeof(buffer), "K_DSPNMx"); for (i = 0; i < 10; i++) { buffer[7] = '0'+(i%10); @@ -474,11 +486,6 @@ static void K_LoadSaturnHUDGraphics(void) skp_smallstickerclr = (patch_t *)W_CachePatchName("SC_SMSTC", PU_HUDGFX); } - if (xtra_speedo_clr3) - { - skp_smallstickerclr3 = (patch_t *)W_CachePatchName("SC_SM3TC", PU_HUDGFX); - } - if (achi_speedo_clr) { skp_smallstickerachiclr = (patch_t *)W_CachePatchName("SC_AMSTC", PU_HUDGFX); @@ -500,7 +507,7 @@ static void K_LoadSaturnHUDGraphics(void) skp_speedpatchesdialclr[3] = (patch_t *)W_CachePatchName("SC_DFRAC", PU_HUDGFX); skp_speedpatchesdialclr[4] = (patch_t *)W_CachePatchName("SC_DPERC", PU_HUDGFX); - sprintf(buffer, "K_DSPNCx"); + snprintf(buffer, sizeof(buffer), "K_DSPNCx"); for (i = 0; i < 10; i++) { buffer[7] = '0'+(i%10); @@ -533,14 +540,6 @@ static void K_LoadSaturnHUDGraphics(void) kp_itemmulstickerclr[0] = (patch_t *)W_CachePatchName("K_ITMULC", PU_HUDGFX); } } - - if (found_extra3_kart) - { - if (xtra_speedo3) // 80x11 patch scaled to size - { - skp_smallsticker3 = (patch_t *)W_CachePatchName("SP_SM3TC", PU_HUDGFX); - } - } } // -- Kart patches -- @@ -568,7 +567,7 @@ static patch_t *kp_racefinish[6]; static patch_t *kp_positionnum[NUMPOSNUMS][NUMPOSFRAMES]; static patch_t *kp_winnernum[NUMPOSFRAMES]; -patch_t *kp_facenum[MAXPLAYERS+1]; +patch_t *kp_facenum[MAXPLAYERS+1] = {}; static patch_t *kp_facehighlight[8]; static patch_t *kp_rankbumper; @@ -678,7 +677,7 @@ void K_LoadKartHUDGraphics(void) kp_racefinish[5] = (patch_t *)W_CachePatchName("K_2PFINB", PU_HUDGFX); // Position numbers - sprintf(buffer, "K_POSNxx"); + snprintf(buffer, sizeof(buffer), "K_POSNxx"); for (i = 0; i < NUMPOSNUMS; i++) { buffer[6] = '0'+i; @@ -689,14 +688,17 @@ void K_LoadKartHUDGraphics(void) } } - sprintf(buffer, "K_POSNWx"); + snprintf(buffer, sizeof(buffer), "K_POSNWx"); for (i = 0; i < NUMWINFRAMES; i++) { buffer[7] = '0'+i; kp_winnernum[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX); } - sprintf(buffer, "OPPRNKxx"); + // 32 player note: there are only 16 of those! + // so slots after this will just be missing patches! + // but keeping like this incase of missed adjustments which might cause crashes otherwise + snprintf(buffer, sizeof(buffer), "OPPRNKxx"); for (i = 0; i <= MAXPLAYERS; i++) { buffer[6] = '0'+(i/10); @@ -704,7 +706,7 @@ void K_LoadKartHUDGraphics(void) kp_facenum[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX); } - sprintf(buffer, "K_CHILIx"); + snprintf(buffer, sizeof(buffer), "K_CHILIx"); for (i = 0; i < 8; i++) { buffer[7] = '0'+(i+1); @@ -773,21 +775,21 @@ void K_LoadKartHUDGraphics(void) kp_kitchensink[1] = (patch_t *)W_CachePatchName("K_ISSINK", PU_HUDGFX); kp_sadface[1] = (patch_t *)W_CachePatchName("K_ISSAD", PU_HUDGFX); - sprintf(buffer, "K_ITINVx"); + snprintf(buffer, sizeof(buffer), "K_ITINVx"); for (i = 0; i < 7; i++) { buffer[7] = '1'+i; kp_invincibility[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX); } - sprintf(buffer, "K_ITORBx"); + snprintf(buffer, sizeof(buffer), "K_ITORBx"); for (i = 0; i < 4; i++) { buffer[7] = '1'+i; kp_orbinaut[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX); } - sprintf(buffer, "K_ISINVx"); + snprintf(buffer, sizeof(buffer), "K_ISINVx"); for (i = 0; i < 6; i++) { buffer[7] = '1'+i; @@ -795,7 +797,7 @@ void K_LoadKartHUDGraphics(void) } // CHECK indicators - sprintf(buffer, "K_CHECKx"); + snprintf(buffer, sizeof(buffer), "K_CHECKx"); for (i = 0; i < 6; i++) { buffer[7] = '1'+i; @@ -803,7 +805,7 @@ void K_LoadKartHUDGraphics(void) } // Eggman warning numbers - sprintf(buffer, "K_EGGNx"); + snprintf(buffer, sizeof(buffer), "K_EGGNx"); for (i = 0; i < 4; i++) { buffer[6] = '0'+i; @@ -816,7 +818,7 @@ void K_LoadKartHUDGraphics(void) kp_fpview[2] = (patch_t *)W_CachePatchName("VIEWC0E0", PU_HUDGFX); // Input UI Wheel - sprintf(buffer, "K_WHEELx"); + snprintf(buffer, sizeof(buffer), "K_WHEELx"); for (i = 0; i < 5; i++) { buffer[7] = '0'+i; @@ -824,7 +826,7 @@ void K_LoadKartHUDGraphics(void) } // HERE COMES A NEW CHALLENGER - sprintf(buffer, "K_CHALxx"); + snprintf(buffer, sizeof(buffer), "K_CHALxx"); for (i = 0; i < 25; i++) { buffer[6] = '0'+((i+1)/10); @@ -833,14 +835,14 @@ void K_LoadKartHUDGraphics(void) } // Lap start animation - sprintf(buffer, "K_LAP0x"); + snprintf(buffer, sizeof(buffer), "K_LAP0x"); for (i = 0; i < 7; i++) { buffer[6] = '0'+(i+1); kp_lapanim_lap[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX); } - sprintf(buffer, "K_LAPFxx"); + snprintf(buffer, sizeof(buffer), "K_LAPFxx"); for (i = 0; i < 11; i++) { buffer[6] = '0'+((i+1)/10); @@ -848,7 +850,7 @@ void K_LoadKartHUDGraphics(void) kp_lapanim_final[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX); } - sprintf(buffer, "K_LAPNxx"); + snprintf(buffer, sizeof(buffer), "K_LAPNxx"); for (i = 0; i < 10; i++) { buffer[6] = '0'+i; @@ -859,14 +861,14 @@ void K_LoadKartHUDGraphics(void) } } - sprintf(buffer, "K_LAPE0x"); + snprintf(buffer, sizeof(buffer), "K_LAPE0x"); for (i = 0; i < 2; i++) { buffer[7] = '0'+(i+1); kp_lapanim_emblem[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX); } - sprintf(buffer, "K_LAPH0x"); + snprintf(buffer, sizeof(buffer), "K_LAPH0x"); for (i = 0; i < 3; i++) { buffer[7] = '0'+(i+1); @@ -875,7 +877,7 @@ void K_LoadKartHUDGraphics(void) kp_yougotem = (patch_t *)W_CachePatchName("YOUGOTEM", PU_HUDGFX); - if (found_extra_kart || found_extra2_kart || found_extra3_kart) + if (found_extra_kart || found_extra2_kart) K_LoadSaturnHUDGraphics(); } @@ -931,21 +933,21 @@ const char *K_GetItemPatch(UINT8 item, boolean tiny) //} -INT32 ITEM_X, ITEM_Y; // Item Window -INT32 TIME_X, TIME_Y; // Time Sticker -INT32 LAPS_X, LAPS_Y; // Lap Sticker -INT32 SPDM_X, SPDM_Y; // Speedometer -INT32 POSI_X, POSI_Y; // Position Number -INT32 FACE_X, FACE_Y; // Top-four Faces -INT32 STCD_X, STCD_Y; // Starting countdown -INT32 CHEK_Y; // CHECK graphic -INT32 MINI_X, MINI_Y; // Minimap -INT32 WANT_X, WANT_Y; // Battle WANTED poster +static INT32 ITEM_X, ITEM_Y; // Item Window +static INT32 TIME_X, TIME_Y; // Time Sticker +static INT32 LAPS_X, LAPS_Y; // Lap Sticker +static INT32 SPDM_X, SPDM_Y; // Speedometer +static INT32 POSI_X, POSI_Y; // Position Number +static INT32 FACE_X, FACE_Y; // Top-four Faces +static INT32 STCD_X, STCD_Y; // Starting countdown +static INT32 CHEK_Y; // CHECK graphic +static INT32 MINI_X, MINI_Y; // Minimap +static INT32 WANT_X, WANT_Y; // Battle WANTED poster // This is for the P2 and P4 side of splitscreen. Then we'll flip P1's and P2's to the bottom with V_SPLITSCREEN. -INT32 ITEM2_X, ITEM2_Y; -INT32 LAPS2_X, LAPS2_Y; -INT32 POSI2_X, POSI2_Y; +static INT32 ITEM2_X, ITEM2_Y; +static INT32 LAPS2_X, LAPS2_Y; +static INT32 POSI2_X, POSI2_Y; static void K_initKartHUD(void) { @@ -1065,7 +1067,7 @@ static void K_initKartHUD(void) } if (timeinmap > 113 || forceshowhud) - hudtrans = cv_translucenthud.value; + hudtrans = (UINT8)cv_translucenthud.value; else if (timeinmap > 105) hudtrans = ((((INT32)timeinmap) - 105)*cv_translucenthud.value)/(113-105); else @@ -1122,9 +1124,9 @@ void K_KartPlayerHUDUpdate(player_t *player) UINT8 K_GetHudColor(void) { if (cv_colorizedhud.value && cv_colorizedhudcolor.value) - return cv_colorizedhudcolor.value; + return (UINT8)cv_colorizedhudcolor.value; - return ((stplyr && gamestate == GS_LEVEL) ? stplyr->skincolor : cv_playercolor.value); + return ((stplyr && gamestate == GS_LEVEL) ? stplyr->skincolor : (UINT8)cv_playercolor.value); } boolean K_UseColorHud(void) @@ -1145,10 +1147,9 @@ enum SPEEDO_DIAL, SPEEDO_PMETER, SPEEDO_PMETERSMOL, - SPEEDO_EXTRA3, }; -static SINT8 K_GetSpeedometerStyle(void) +static UINT8 K_GetSpeedometerStyle(void) { if (cv_newspeedometer.value == 2 && xtra_speedo) return SPEEDO_EXTRA; @@ -1160,8 +1161,6 @@ static SINT8 K_GetSpeedometerStyle(void) return SPEEDO_PMETER; else if (cv_newspeedometer.value == 6 && kartz_speedo_smol) return SPEEDO_PMETERSMOL; - else if (cv_newspeedometer.value == 7 && xtra_speedo3) - return SPEEDO_EXTRA3; else return SPEEDO_VANILLA; } @@ -1179,8 +1178,6 @@ static boolean K_UseColorSpeedo(int speedostyle) return achi_speedo_clr; case SPEEDO_DIAL: return dial_speedo_clr; - case SPEEDO_EXTRA3: - return xtra_speedo_clr3; default: return false; } @@ -1192,7 +1189,6 @@ enum GAUGE_SMALL, GAUGE_BIGNUM, GAUGE_NUMONLY, - GAUGE_EXTRA, }; static SINT8 K_GetDriftgaugeStyle(void) @@ -1205,8 +1201,6 @@ static SINT8 K_GetDriftgaugeStyle(void) return GAUGE_SMALL; else if (cv_driftgaugestyle.value == 3) return GAUGE_BIGNUM; - else if (cv_driftgaugestyle.value == 5 && xtra_speedo3) - return GAUGE_EXTRA; } // Fallback @@ -1358,10 +1352,12 @@ INT32 K_getMinimapTrans(void) return -1; if (timeinmap <= 113) + { minimaptrans = ((((INT32)timeinmap) - 105)*minimaptrans)/(113-105); - if (!minimaptrans) - return -1; + if (!minimaptrans) + return -1; + } return (10-minimaptrans)<kartstuff[k_bumper] ? -5 : -8)); @@ -1436,13 +1429,16 @@ static void K_drawKartStats(void) fakeskin = K_GetPlayerSkin(stplyr); // Skin name - if (K_IsHighResolution()) // V_DrawSmallString becomes a mess at low resolutions lel + if (cv_showstats_skinname.value) { - V_DrawSmallString(x+20, y+12, flags2, fakeskin->realname); - } - else - { - V_DrawThinString(x+20, y+7, flags2, fakeskin->realname); + if (K_IsHighResolution()) // V_DrawSmallString becomes a mess at low resolutions lel + { + V_DrawSmallString(x+20, y+12, flags2, fakeskin->realname); + } + else + { + V_DrawThinString(x+20, y+7, flags2, fakeskin->realname); + } } // Icon and stats @@ -1524,74 +1520,77 @@ static void K_drawKartItem(void) if (stplyr->kartstuff[k_itemroulette]) { - localcolor = K_GetHudColor(); + if (cv_roulettecolor.value == ROULETTECOLOR_PLAYER) + localcolor = stplyr->skincolor; + else if (cv_roulettecolor.value != ROULETTECOLOR_NONE) + localcolor = K_GetHudColor(); - switch((stplyr->kartstuff[k_itemroulette] % (14*3)) / 3) + switch ((stplyr->kartstuff[k_itemroulette] % (14*3)) / 3) { // Each case is handled in threes, to give three frames of in-game time to see the item on the roulette case 0: // Sneaker localpatch = kp_sneaker[offset]; - //localcolor = SKINCOLOR_RASPBERRY; + if (cv_roulettecolor.value == ROULETTECOLOR_ITEM) localcolor = SKINCOLOR_RASPBERRY; break; case 1: // Banana localpatch = kp_banana[offset]; - //localcolor = SKINCOLOR_YELLOW; + if (cv_roulettecolor.value == ROULETTECOLOR_ITEM) localcolor = SKINCOLOR_YELLOW; break; case 2: // Orbinaut localpatch = kp_orbinaut[3+offset]; - //localcolor = SKINCOLOR_STEEL; + if (cv_roulettecolor.value == ROULETTECOLOR_ITEM) localcolor = SKINCOLOR_STEEL; break; case 3: // Mine localpatch = kp_mine[offset]; - //localcolor = SKINCOLOR_JET; + if (cv_roulettecolor.value == ROULETTECOLOR_ITEM) localcolor = SKINCOLOR_JET; break; case 4: // Grow localpatch = kp_grow[offset]; - //localcolor = SKINCOLOR_TEAL; + if (cv_roulettecolor.value == ROULETTECOLOR_ITEM) localcolor = SKINCOLOR_TEAL; break; case 5: // Hyudoro localpatch = kp_hyudoro[offset]; - //localcolor = SKINCOLOR_STEEL; + if (cv_roulettecolor.value == ROULETTECOLOR_ITEM) localcolor = SKINCOLOR_STEEL; break; case 6: // Rocket Sneaker localpatch = kp_rocketsneaker[offset]; - //localcolor = SKINCOLOR_TANGERINE; + if (cv_roulettecolor.value == ROULETTECOLOR_ITEM) localcolor = SKINCOLOR_TANGERINE; break; case 7: // Jawz localpatch = kp_jawz[offset]; - //localcolor = SKINCOLOR_JAWZ; + if (cv_roulettecolor.value == ROULETTECOLOR_ITEM) localcolor = SKINCOLOR_JAWZ; break; case 8: // Self-Propelled Bomb localpatch = kp_selfpropelledbomb[offset]; - //localcolor = SKINCOLOR_JET; + if (cv_roulettecolor.value == ROULETTECOLOR_ITEM) localcolor = SKINCOLOR_JET; break; case 9: // Shrink localpatch = kp_shrink[offset]; - //localcolor = SKINCOLOR_ORANGE; + if (cv_roulettecolor.value == ROULETTECOLOR_ITEM) localcolor = SKINCOLOR_ORANGE; break; case 10: // Invincibility localpatch = localinv; - //localcolor = SKINCOLOR_GREY; + if (cv_roulettecolor.value == ROULETTECOLOR_ITEM) localcolor = SKINCOLOR_GREY; break; case 11: // Eggman Monitor localpatch = kp_eggman[offset]; - //localcolor = SKINCOLOR_ROSE; + if (cv_roulettecolor.value == ROULETTECOLOR_ITEM) localcolor = SKINCOLOR_ROSE; break; case 12: // Ballhog localpatch = kp_ballhog[offset]; - //localcolor = SKINCOLOR_LILAC; + if (cv_roulettecolor.value == ROULETTECOLOR_ITEM) localcolor = SKINCOLOR_LILAC; break; case 13: // Thunder Shield localpatch = kp_thundershield[offset]; - //localcolor = SKINCOLOR_CYAN; + if (cv_roulettecolor.value == ROULETTECOLOR_ITEM) localcolor = SKINCOLOR_CYAN; break; /*case 14: // Pogo Spring localpatch = kp_pogospring[offset]; - localcolor = SKINCOLOR_TANGERINE; + if (cv_roulettecolor.value == ROULETTECOLOR_ITEM) localcolor = SKINCOLOR_TANGERINE; break; case 15: // Kitchen Sink localpatch = kp_kitchensink[offset]; - localcolor = SKINCOLOR_STEEL; + if (cv_roulettecolor.value == ROULETTECOLOR_ITEM) localcolor = SKINCOLOR_STEEL; break;*/ default: break; @@ -1978,7 +1977,7 @@ void K_drawKartTimestamp(tic_t drawtime, INT32 TX, INT32 TY, INT16 emblemmap, UI goto bademblem; } - snprintf(targettext, 9, "%i'%02i\"%02i", + snprintf(targettext, sizeof(targettext), "%i'%02i\"%02i", G_TicsToMinutes(timetoreach, false), G_TicsToSeconds(timetoreach), G_TicsToCentiseconds(timetoreach)); @@ -2096,7 +2095,7 @@ static void K_DrawKartPositionNum(INT32 num) fy = POSI_Y; fflags = V_SNAPTOLEFT|((stplyrnum == 2) ? V_SPLITSCREEN|V_SNAPTOBOTTOM : 0); // flip P3 to the bottom. flipdraw = true; - if (num && num >= 10) + if (num >= 10) fx += W; // this seems dumb, but we need to do this in order for positions above 10 going off screen. } else // else, that means we're P2 or P4. @@ -2178,8 +2177,9 @@ static boolean K_drawKartPositionFaces(void) UINT8 *colormap; ranklines = 0; - memset(completed, 0, sizeof (completed)); - memset(rankplayer, 0, sizeof (rankplayer)); + + if (!LUA_HudEnabled(hud_minirankings)) + return false; // Don't proceed but still return true for free play above if HUD is disabled. for (i = 0; i < MAXPLAYERS; i++) { @@ -2194,8 +2194,7 @@ static boolean K_drawKartPositionFaces(void) if (numplayersingame <= 1) return true; - if (!LUA_HudEnabled(hud_minirankings)) - return false; // Don't proceed but still return true for free play above if HUD is disabled. + memset(completed, 0, sizeof (completed)); for (j = 0; j < numplayersingame; j++) { @@ -2252,6 +2251,7 @@ static boolean K_drawKartPositionFaces(void) if (!playeringame[rankplayer[i]]) continue; + if (player->spectator || !player->mo) continue; @@ -2297,6 +2297,11 @@ static boolean K_drawKartPositionFaces(void) if (pos < 0 || pos > MAXPLAYERS) pos = 0; +#if MAXPLAYERS > 16 + if (pos > 16) + V_DrawPingNum(FACE_X+2, Y+10, V_HUDTRANS|V_SNAPTOLEFT, pos, NULL); + else +#endif // Draws the little number over the face V_DrawScaledPatch(FACE_X-5, Y+10, V_HUDTRANS|V_SNAPTOLEFT, kp_facenum[pos]); } @@ -2388,6 +2393,12 @@ void HU_DrawTabRankings(INT32 x, INT32 y, playersort_t *tab, INT32 scorelines, I INT32 pos = player->kartstuff[k_position]; if (pos < 0 || pos > MAXPLAYERS) pos = 0; + +#if MAXPLAYERS > 16 + if (pos > 16) + V_DrawPingNum(x+2, y+10, 0, pos, NULL); + else +#endif // Draws the little number over the face V_DrawScaledPatch(x-5, y+6, 0, kp_facenum[pos]); } @@ -2429,7 +2440,7 @@ void HU_DrawTabRankings(INT32 x, INT32 y, playersort_t *tab, INT32 scorelines, I static boolean K_BigLap(void) { - return (cv_biglaps.value && (cv_numlaps.value > 9) && (K_UseColorHud() ? big_lap_color : big_lap) && (!stplyr->exiting)); + return (cv_biglaps.value && (cv_numlaps.value > 9) && !stplyr->exiting && (K_UseColorHud() ? big_lap_color : big_lap)); } static void K_drawKartLaps(void) @@ -2638,7 +2649,7 @@ static void K_drawKartSpeedometer(void) return; // index 0 is the raw value, index 1 is the converted value - fixed_t convSpeed[2] = {0,0}; + fixed_t convSpeed[2] = {0, 0}; #ifdef ROTSPRITE fixed_t dial_divisor = DIALSPDDIV; #endif @@ -2707,34 +2718,28 @@ static void K_drawKartSpeedometer(void) V_DrawKartString(SPDM_X, SPDM_Y, V_HUDTRANS|splitflags, metric); } - else if (speedostyle == SPEEDO_EXTRA) // why bother if we dont? + else if (speedostyle == SPEEDO_EXTRA || speedostyle == SPEEDO_ACHII) // why bother if we dont? { - if (K_UseColorSpeedo(SPEEDO_EXTRA)) //Colourized hud + patch_t *speedopat; + UINT8 *colormap = NULL; + + if (K_UseColorSpeedo(speedostyle)) //Colourized hud { - UINT8 *colormap = R_GetTranslationColormap(TC_DEFAULT, K_GetHudColor(), GTC_CACHE); - V_DrawMappedPatch(SPDM_X + 1, SPDM_Y + 4, V_HUDTRANS|splitflags, skp_smallstickerclr, colormap); + colormap = R_GetTranslationColormap(TC_DEFAULT, K_GetHudColor(), GTC_CACHE); + + speedopat = ((speedostyle == SPEEDO_EXTRA) ? skp_smallstickerclr : skp_smallstickerachiclr); + V_DrawMappedPatch(SPDM_X + 1, SPDM_Y + 4, V_HUDTRANS|splitflags, speedopat, colormap); + speedopat = ((speedostyle == SPEEDO_EXTRA) ? skp_speedpatches[cv_kartspeedometer.value] : skp_speedpatchesachiclr[cv_kartspeedometer.value]); } else - V_DrawScaledPatch(SPDM_X + 1, SPDM_Y + 4, V_HUDTRANS|splitflags, skp_smallsticker); + { + speedopat = ((speedostyle == SPEEDO_EXTRA) ? skp_smallsticker : skp_smallstickerachi); + V_DrawScaledPatch(SPDM_X + 1, SPDM_Y + 4, V_HUDTRANS|splitflags, speedopat); + speedopat = ((speedostyle == SPEEDO_EXTRA) ? skp_speedpatches[cv_kartspeedometer.value] : skp_speedpatchesachi[cv_kartspeedometer.value]); + } V_DrawRankNum(SPDM_X + 26, SPDM_Y + 4, V_HUDTRANS|splitflags, convSpeed[1], 3, NULL); - V_DrawScaledPatch(SPDM_X + 31, SPDM_Y + 4, V_HUDTRANS|splitflags, skp_speedpatches[cv_kartspeedometer.value]); - } - else if (speedostyle == SPEEDO_ACHII) // why bother if we dont? - { - if (K_UseColorSpeedo(SPEEDO_ACHII)) //Colourized hud - { - UINT8 *colormap = R_GetTranslationColormap(TC_DEFAULT, K_GetHudColor(), GTC_CACHE); - V_DrawMappedPatch(SPDM_X + 1, SPDM_Y + 4, V_HUDTRANS|splitflags, skp_smallstickerachiclr, colormap); - V_DrawRankNum(SPDM_X + 26, SPDM_Y + 4, V_HUDTRANS|splitflags, convSpeed[1], 3, NULL); - V_DrawMappedPatch(SPDM_X + 31, SPDM_Y + 4, V_HUDTRANS|splitflags, skp_speedpatchesachiclr[cv_kartspeedometer.value], colormap); - } - else - { - V_DrawScaledPatch(SPDM_X + 1, SPDM_Y + 4, V_HUDTRANS|splitflags, skp_smallstickerachi); - V_DrawRankNum(SPDM_X + 26, SPDM_Y + 4, V_HUDTRANS|splitflags, convSpeed[1], 3, NULL); - V_DrawScaledPatch(SPDM_X + 31, SPDM_Y + 4, V_HUDTRANS|splitflags, skp_speedpatchesachi[cv_kartspeedometer.value]); - } + V_DrawMappedPatch(SPDM_X + 31, SPDM_Y + 4, V_HUDTRANS|splitflags, speedopat, colormap); } #ifdef ROTSPRITE else if (speedostyle == SPEEDO_DIAL) // why bother if we dont? @@ -2747,46 +2752,36 @@ static void K_drawKartSpeedometer(void) (K_UseColorSpeedo(SPEEDO_DIAL))); } #endif - else if (speedostyle == SPEEDO_EXTRA3) // why bother if we dont? - { - if (K_UseColorSpeedo(SPEEDO_EXTRA3)) //Colourized hud - { - UINT8 *colormap = R_GetTranslationColormap(TC_DEFAULT, K_GetHudColor(), GTC_CACHE); - V_DrawStretchyFixedPatch((SPDM_X-1)<speed, mapobjectscale)/FRACUNIT; + const fixed_t spd = FixedDiv(stplyr->speed, mapobjectscale) / FRACUNIT; - for (INT32 i = 0; i < 22; ++i) + if (spd > 54) { - if (fuspeed < speedIntervals[i]) + spdpatch = (leveltime & 4) ? 24 : 23; + } + else + { + for (INT32 i = 0; i < 22; ++i) { - spdpatch = i; - break; + if (spd < spdinterval[i]) + { + spdpatch = i; + break; + } } } - if (((fuspeed < 57 && fuspeed > 54) || (fuspeed < 60 && fuspeed > 56) || (fuspeed > 59)) && (leveltime & 4)) - spdpatch = 24; - else if (((fuspeed < 57 && fuspeed > 54) || (fuspeed < 60 && fuspeed > 56) || (fuspeed > 59)) && !(leveltime & 4)) - spdpatch = 23; - V_DrawScaledPatch(SPDM_X, SPDM_Y, V_HUDTRANS|splitflags, (speedostyle == SPEEDO_PMETER) ? kp_kartzspeedo[spdpatch] : kp_kartzspeedo_smol[spdpatch]); } } @@ -2814,7 +2809,7 @@ static void K_drawKartBumpersOrKarma(void) { const UINT8 speedostyle = K_GetSpeedometerStyle(); - if ((speedostyle == SPEEDO_EXTRA) || (speedostyle == SPEEDO_ACHII) || (speedostyle == SPEEDO_EXTRA3)) + if ((speedostyle == SPEEDO_EXTRA) || (speedostyle == SPEEDO_ACHII)) fy += 5; else fy += 7; @@ -2906,10 +2901,12 @@ static boolean K_GetScreenCoords(vector2_t *vec, player_t *player, mobj_t *targe x = (fixed_t)(viewangle - R_PointToAngle(targx, targy)); distfact = FINECOSINE((x>>ANGLETOFINESHIFT) & FINEMASK); - if (!distfact) distfact = 1; + if (!distfact) + distfact = 1; if (encoremode) x = -x; + if (x < (fixed_t)ANGLE_270 || x > (fixed_t)ANGLE_90) return false; @@ -2991,7 +2988,7 @@ static boolean K_GetScreenCoords(vector2_t *vec, player_t *player, mobj_t *targe if (stplyrnum > 0) y = y + yres; } - if (splitscreen >= 2) // 3P or 4P + else if (splitscreen >= 2) // 3P or 4P { x = x>>1; y = y>>1; @@ -3051,9 +3048,11 @@ static void K_drawNameTags(void) if (players[i].kartstuff[k_hyudorotimer]) // player is invisible continue; if (maxdistance) + { distance = R_PointToDist(players[i].mo->x, players[i].mo->y); - if (distance > maxdistance) - continue; + if (distance > maxdistance) + continue; + } if (!P_CheckSightFast(stplyr->mo, players[i].mo)) continue; @@ -3262,13 +3261,12 @@ static void K_drawDriftGauge(void) if (!splitscreen && !camera->chase) return; - if (forceshowhud) - goto skipcrap; // i will skip the drift early return and you cant stop me! - - if (!stplyr->kartstuff[k_drift]) - return; - -skipcrap: + // i will skip the drift early return and you cant stop me! + if (!forceshowhud) + { + if (!stplyr->kartstuff[k_drift]) + return; + } if (P_MobjWasRemoved(stplyr->mo)) return; @@ -3293,12 +3291,11 @@ skipcrap: { case GAUGE_DEFAULT: case GAUGE_SMALL: - case GAUGE_EXTRA: case GAUGE_BIGNUM: { patch_t *driftpatch = NULL; - if (gaugestyle == GAUGE_DEFAULT || gaugestyle == GAUGE_BIGNUM || gaugestyle == GAUGE_EXTRA) + if (gaugestyle == GAUGE_DEFAULT || gaugestyle == GAUGE_BIGNUM) { barx = basex - vid.dup*23; BAR_WIDTH = vid.dup*47; @@ -3311,30 +3308,15 @@ skipcrap: bary = basey - vid.dup*2; - if (gaugestyle == GAUGE_EXTRA) // i hate hud code i hate hud code i hate hud code i hate hud code i hate hud code..... + if (K_UseColorHud()) // Colourized hud { - if (K_UseColorSpeedo(SPEEDO_EXTRA3)) // We reuse the extra speedometer patch hence this check - { - colormap = R_GetTranslationColormap(TC_DEFAULT, K_GetHudColor(), GTC_CACHE); - driftpatch = skp_smallstickerclr3; - } - else - driftpatch = skp_smallsticker3; - - V_DrawStretchyFixedPatch((basex - vid.dup*30)<= driftval*4) // rainbow sparks { @@ -3613,6 +3595,10 @@ static void K_drawKartMinimapHead(mobj_t *mo, INT32 x, INT32 y, INT32 flags) #endif skin = K_GetMobjSkin(mo); + + if (!skin) + return; + minimaphead = (skinlocal ? localfacemmapprefix : facemmapprefix)[K_GetMobjSkinNum(skin, skinlocal)]; if (minimaphead == NULL) @@ -3632,7 +3618,7 @@ static void K_drawKartMinimapHead(mobj_t *mo, INT32 x, INT32 y, INT32 flags) V_DrawCenteredSmallStringAtFixed(amxpos + (4*FRACUNIT), amypos - (3*FRACUNIT), V_ALLOWLOWERCASE|flags|V_SkinColorToHighlightcolor(mo->color), player_names[player - players]); } - const boolean minihead = K_useSmallMinimapHead(mo->player); + const boolean minihead = K_useSmallMinimapHead(player); // thx wanted reticle for having weird offsets very cool wntdamxpos = minihead ? amxpos + (1<health <= 0 && players[localplayers[i]].pflags & PF_TIMEOVER); if (cv_showminimapangle.value && (minidoticon || minilighticon) && !playertimedout) { - UINT8 *colormap; + UINT8 *colormap = NULL; drawinfo_t dims; fixed_t interpx, interpy; fixed_t xoff = 0, yoff = 0; @@ -3829,10 +3821,27 @@ static void K_drawKartMinimap(void) if (encoremode) ang = ANGLE_180 - ang; - if (mobj->colorized) - colormap = R_GetTranslationColormap(TC_RAINBOW, mobj->color, GTC_CACHE); - else - colormap = R_GetLocalTranslationColormap(mobj->skin, mobj->localskin, mobj->color, GTC_CACHE, mobj->skinlocal); + if (mobj->color) + { + if (mobj->colorized) + { + colormap = R_GetTranslationColormap(TC_RAINBOW, mobj->color, GTC_CACHE); + } + else + { + const INT32 skinnum = K_GetMobjLocalSkinNum(mobj->skin, mobj->localskin, mobj->skinlocal); + + // special case if startcolor is not the default (160 / Green) + if (skinnum && skins[skinnum].starttranscolor != skins[0].starttranscolor) + { + colormap = R_GetTranslationColormap(TC_DEFAULT, mobj->color, GTC_CACHE); + } + else + { + colormap = R_GetLocalTranslationColormap(mobj->skin, mobj->localskin, mobj->color, GTC_CACHE, mobj->skinlocal); + } + } + } interpx = lerp(mobj->old_x, mobj->x); interpy = lerp(mobj->old_y, mobj->y); @@ -3953,10 +3962,23 @@ static void K_drawBattleFullscreen(void) INT32 x = BASEVIDWIDTH/2; INT32 y = (-64*FRACUNIT) + cardanim; // card animation goes from 0 to 164, 164 is the middle of the screen - INT32 splitflags = V_SNAPTOTOP; // I don't feel like properly supporting non-green resolutions, so you can have a misuse of SNAPTO instead + INT32 splitflags = splitscreen ? V_SNAPTOTOP : 0; // I don't feel like properly supporting non-green resolutions, so you can have a misuse of SNAPTO instead fixed_t scale = FRACUNIT; boolean drawcomebacktimer = true; // lazy hack because it's cleaner in the long run. + // Small hack, if we're not in splitscreen we will not use V_SNAPTOTOP, instead we will just slightly offset + // y position so "attack or protect" doesn't slightly show before popping in + // We will also reduce this when is closer to finishing so when its at the bottom, the "hack offset" is 0 + if (!splitscreen) + { + fixed_t offset = ((vid.height - vid.dup*BASEVIDHEIGHT)/vid.dup) * FRACUNIT/2; + + // cardanim goes from 0 to 164, so when it is 164 offset will be multiplied by (1 - 164/164) = 0 :3 + offset = FixedMul(offset, FRACUNIT - FixedDiv(cardanim, 164*FRACUNIT)); + + y -= offset; + } + if (!LUA_HudEnabled(hud_battlecomebacktimer)) drawcomebacktimer = false; @@ -3997,6 +4019,7 @@ static void K_drawBattleFullscreen(void) { if (stplyrnum == 0) V_DrawFadeScreen(0xFF00, 16); + if (stplyr->exiting < 6*TICRATE && !stplyr->spectator) { if (stplyr->kartstuff[k_position] == 1) @@ -4043,12 +4066,12 @@ static void K_drawBattleFullscreen(void) if (K_UseColorHud()) // Colourized hud { UINT8 *colormap = R_GetTranslationColormap(TC_DEFAULT, K_GetHudColor(), GTC_CACHE); - V_DrawFixedPatch(x<kartstuff[k_comebacktimer]/TICRATE)); + V_DrawKartString(x-txoff, ty, splitflags, va("%d", stplyr->kartstuff[k_comebacktimer]/TICRATE)); } } @@ -4061,7 +4084,7 @@ static void K_drawBattleFullscreen(void) { if (i == displayplayers[0]) continue; - if (playeringame[i] && !stplyr->spectator) + if (playeringame[i]) return; } @@ -4278,6 +4301,7 @@ static void K_drawInput(void) y -= FRACUNIT; + // stick displays if (cv_showinput.value == 2 || cv_showinput.value == 3) { INT32 axis; @@ -4287,7 +4311,7 @@ static void K_drawInput(void) const INT32 joyy = y>>FRACBITS; static const INT32 joyxoffs = -8; static const INT32 joyyoffs = -24; - const boolean usejoysprite = (cv_showinput.value == 3 && joystickicon); + const boolean usejoysprite = (cv_showinput.value == 3 && joystickicon); // O backing if (usejoysprite) @@ -4305,39 +4329,20 @@ static void K_drawInput(void) // kart does not have anything we can get analogue joystick y axis values from // during normal gameplay, so replicate shit here - // this is horrid but we cant get actual input in replays so uhh - if (demo.playback || !P_IsLocalPlayer(stplyr)) // yeah........... + const boolean analogjoystickmove = (!demo.playback && P_IsLocalPlayer(stplyr) && cv_usejoystick[stplyrnum].value && !DigitalGamepadStyle(stplyrnum)); + axis = analogjoystickmove ? JoyAxis(AXISAIM, stplyrnum+1) : 0; + + if (axis != 0) { - hudforward = stplyr->kartstuff[k_throwdir] * KART_FULLTURN; + hudforward -= ((axis * KART_FULLTURN) / JOYAXISRANGE); } else { - const boolean analogjoystickmove = cv_usejoystick[stplyrnum].value && !Joystick[stplyrnum].bGamepadStyle; - const boolean gamepadjoystickmove = cv_usejoystick[stplyrnum].value && Joystick[stplyrnum].bGamepadStyle; - const UINT8 ssplayer = stplyrnum+1; - - axis = JoyAxis(AXISAIM, ssplayer); - - if (analogjoystickmove && axis != 0) - { - // JOYAXISRANGE is supposed to be 1023 (divide by 1024) - hudforward -= ((axis * KART_FULLTURN) / (JOYAXISRANGE-1)); - } - else - { - if (InputDown(gc_aimforward, ssplayer) || (gamepadjoystickmove && axis < 0)) - { - hudforward += KART_FULLTURN; - } - if (InputDown(gc_aimbackward, ssplayer) || (gamepadjoystickmove && axis > 0)) - { - hudforward-= KART_FULLTURN; - } - } - - hudforward = CLAMP(hudforward, -KART_FULLTURN, KART_FULLTURN); + hudforward = stplyr->kartstuff[k_throwdir] * KART_FULLTURN; } + hudforward = CLAMP(hudforward, -KART_FULLTURN, KART_FULLTURN); + if (cmd->driftturn || hudforward) { INT16 turning = encoremode ? -cmd->driftturn : cmd->driftturn; @@ -4370,7 +4375,7 @@ static void K_drawInput(void) } } } - else + else // wheel { if (!cmd->driftturn) // no turn target = 0; @@ -4417,6 +4422,7 @@ static void K_drawChallengerScreen(void) 19,20,19,20,19,20,19,20,19,20, // frame 20-21, 1 tic, 5 alternating: all text vibrates from impact 21,22,23,24 // frame 22-25, 1 tic: CHALLENGER turns gold }; + const UINT8 offset = min(52-1, (3*TICRATE)-mapreset); V_DrawFadeScreen(0xFF00, 16); // Fade out @@ -4425,6 +4431,9 @@ static void K_drawChallengerScreen(void) static void K_drawLapStartAnim(void) { + if (!cv_showlapemblem.value) + return; + // This is an EVEN MORE insanely complicated animation. const UINT8 progress = 80-stplyr->kartstuff[k_lapanimation]; UINT8 *colormap = R_GetTranslationColormap(TC_DEFAULT, K_GetHudColor(), GTC_CACHE); @@ -4468,7 +4477,10 @@ static void K_drawLapStartAnim(void) V_DrawFixedPatch(leftx, y, FRACUNIT, vflags, kp_lapanim_lap[min(progress/2, 6)], NULL); char *lapnum = va("%02d", stplyr->laps + 1); - for (int i = 0; i < (int)strlen(lapnum); i++) + + const int laplength = (int)strlen(lapnum); + + for (int i = 0; i < laplength; i++) { int digit = lapnum[i] - '0'; int frame = min(2, progress/2 - 8 - (i*2)); @@ -4516,6 +4528,7 @@ static void K_drawDistributionDebugger(void) kp_orbinaut[4], kp_jawz[1] }; + INT32 useodds = 0; INT32 pingame = 0, bestbumper = 0; INT32 i; @@ -4532,8 +4545,10 @@ static void K_drawDistributionDebugger(void) if (!playeringame[i] || players[i].spectator) continue; pingame++; + if (players[i].exiting) dontforcespb = true; + if (players[i].kartstuff[k_bumper] > bestbumper) bestbumper = players[i].kartstuff[k_bumper]; } @@ -4595,7 +4610,11 @@ static void K_drawCheckpointDebugger(void) else V_DrawString(8, 184, 0, va("Checkpoint: %d / %d (Skip: %d)", stplyr->starpostnum, numstarposts, ((numstarposts/2) + stplyr->starpostnum))); - V_DrawString(8, 192, 0, va("Waypoint dist: Prev %d, Next %d", stplyr->kartstuff[k_prevcheck], stplyr->kartstuff[k_nextcheck])); + // really gnarly hack + const INT32 prevcheck = (stprevnextchecks[0] != INT32_MAX) ? stprevnextchecks[0]: stplyr->kartstuff[k_prevcheck]; + const INT32 nextcheck = (stprevnextchecks[1] != INT32_MAX) ? stprevnextchecks[1]: stplyr->kartstuff[k_nextcheck]; + + V_DrawString(8, 192, 0, va("Waypoint dist: Prev %d, Next %d", prevcheck, nextcheck)); } // determines if gametype info (laps/bumpers) should be hidden @@ -4687,6 +4706,7 @@ void K_drawKartHUD(void) { if (LUA_HudEnabled(hud_battlefullscreen)) K_drawBattleFullscreen(); + return; } @@ -4846,7 +4866,7 @@ void K_drawKartHUD(void) { if (stplyr->exiting) K_drawKartFinish(); - else if (stplyr->kartstuff[k_lapanimation] && !splitscreen && cv_showlapemblem.value) + else if (stplyr->kartstuff[k_lapanimation] && !splitscreen) K_drawLapStartAnim(); } diff --git a/src/k_hud.h b/src/k_hud.h index c42996a4e..45d5260d6 100644 --- a/src/k_hud.h +++ b/src/k_hud.h @@ -35,11 +35,13 @@ extern consvar_t cv_darkitembox; extern consvar_t cv_biglaps; extern consvar_t cv_highresportrait; extern consvar_t cv_showstats; +extern consvar_t cv_showstats_skinname; extern consvar_t cv_fancyroulette; extern consvar_t cv_showlaptimes; extern consvar_t cv_battlespeedo; extern consvar_t cv_multiitemicon; extern consvar_t cv_huditemamount; +extern consvar_t cv_roulettecolor; // for use in timeattack menu extern patch_t *kp_facenum[MAXPLAYERS+1]; diff --git a/src/k_kart.c b/src/k_kart.c index 767e041a1..e8b48e7d8 100644 --- a/src/k_kart.c +++ b/src/k_kart.c @@ -34,7 +34,7 @@ // extra colourisation stuff -static CV_PossibleValue_t colorspeedlines_cons_t[] = {{0, "Off"}, {1, "Normal"}, {2, "+Driftcharge"}, {3, "Drift only"}, {0, NULL}}; +static CV_PossibleValue_t colorspeedlines_cons_t[] = {{0, "Off"}, {1, "On"}, {0, NULL}}; consvar_t cv_coloredspeedlines = {"colorizedspeedlines", "Off", CV_SAVE, colorspeedlines_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_coloredsneakertrail = {"sneakertrailcolor", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; @@ -47,6 +47,8 @@ consvar_t cv_airsparks = {"airdriftsparks", "Off", CV_SAVE, CV_OnOff, NULL, 0, N consvar_t cv_playerblendeffects = {"playerblendeffects", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_reducevfx = {"reducevfx", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; + // funn-E streeetch static CV_PossibleValue_t stretchfactor_t[] = {{0, "MIN"}, {FRACUNIT, "MAX"}, {0, NULL}}; consvar_t cv_gravstretch = {"gravstretch", "MIN", CV_SAVE|CV_FLOAT, stretchfactor_t, NULL, 0, NULL, NULL, 0, 0, NULL}; @@ -65,7 +67,8 @@ static CV_PossibleValue_t sloperoll_cons_t[] = {{0, "Off"}, {1, "Players"}, {2, consvar_t cv_sloperoll = {"sloperoll", "Off", CV_SAVE|CV_CALL, sloperoll_cons_t, PDistort_menu_Onchange, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_sparkroll = {"sparkroll", "Off", CV_SAVE|CV_CALL, CV_OnOff, PDistort_menu_Onchange, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_sliptideroll = {"sliptideroll", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_spinoutroll = {"spinoutroll", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_stairjank = {"stairjank", "Off", CV_SAVE|CV_CALL, CV_OnOff, PDistort_menu_Onchange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_stairjanksfx = {"stairjanksfx", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; //hardcode saltyhop mhhm static void saltyhop_onchange(void); @@ -482,7 +485,8 @@ UINT8 colortranslations[MAXTRANSLATIONS][16] = { // UINT8 K_RainbowColor(void) { - return (UINT8)(1 + (leveltime % (MAXSKINCOLORS-1))); + const tic_t time = cv_reducevfx.value ? (leveltime >> 3) : leveltime; + return (UINT8)(1 + (time % (MAXSKINCOLORS-1))); } // Define for getting accurate color brightness readings according to how the human eye sees them. @@ -657,13 +661,22 @@ INT32 K_GetSkinNum(player_t *player) // // returns the mobj skinnumber -// accounts for localskins +// accounts for localskins ? // INT32 K_GetMobjSkinNum(const skin_t *skin, boolean local) { return skin - K_GetSkinArray(local); } +// +// returns the mobj skinnumber +// accounts for localskins +// +INT32 K_GetMobjLocalSkinNum(const skin_t *skin, const skin_t *localskin, boolean local) +{ + return localskin ? (localskin - K_GetSkinArray(local)) : (skin - skins); +} + // // returns the players skinnumber // accounts for localskins @@ -764,6 +777,8 @@ void K_RegisterClientKartStuff(void) CV_RegisterVar(&cv_playerblendeffects); + CV_RegisterVar(&cv_reducevfx); + CV_RegisterVar(&cv_saltyhop); CV_RegisterVar(&cv_saltyhopsfx); CV_RegisterVar(&cv_saltysquish); @@ -1018,6 +1033,12 @@ INT32 K_KartGetItemOdds(UINT8 pos, SINT8 item, fixed_t mashed, boolean spbrush) } } +#if MAXPLAYERS > 16 + // courtesy of fickle from 1.1 battleroyale + // battleroyale: limit how much items will scale to try to prevent shit-tier items in shit-huge netames + pingame = min(pingame, 12); +#endif + if (first != -1 && second != -1) // calculate 2nd's distance from 1st, for SPB { secondist = P_AproxDistance(P_AproxDistance(players[first].mo->x - players[second].mo->x, @@ -1475,7 +1496,6 @@ void K_KartBouncing(mobj_t *mobj1, mobj_t *mobj2, boolean bounce, boolean solid) fixed_t nx = FixedDiv(distx, dist); fixed_t ny = FixedDiv(disty, dist); - dist = dist ? dist : 1; distx = FixedMul(mobj1->radius+mobj2->radius, nx); disty = FixedMul(mobj1->radius+mobj2->radius, ny); @@ -1587,57 +1607,78 @@ static UINT8 K_CheckOffroadCollide(mobj_t *mo) sector_t *s2; // FOF sector shortcut ffloor_t *rover; // FOF - fixed_t flr; - fixed_t cel; // floor & ceiling for height checks to make sure we're touching the offroad sector. + fixed_t flr, cel; // floor & ceiling for height checks to make sure we're touching the offroad sector. + INT32 special; - I_Assert(mo != NULL); I_Assert(!P_MobjWasRemoved(mo)); for (node = mo->touching_sectorlist; node; node = node->m_sectorlist_next) { if (!node->m_sector) - break; // shouldn't happen. + break; // shouldn't happen. s = node->m_sector; + // 1: Check for the main sector, make sure we're on the floor of that sector and see if we can apply offroad. // Make arbitrary Z checks because we want to check for 1 sector in particular, we don't want to affect the player if the offroad sector is way below them and they're lineriding a normal sector above. - flr = P_MobjFloorZ(mo, s, s, mo->x, mo->y, NULL, false, true); - cel = P_MobjCeilingZ(mo, s, s, mo->x, mo->y, NULL, true, true); // get Z coords of both floors and ceilings for this sector (this accounts for slopes properly.) - // NOTE: we don't use P_GetZAt with our x/y directly because the mobj won't have the same height because of its hitbox on the slope. Complex garbage but tldr it doesn't work. + special = GETSECSPECIAL(s->special, 1); + for (i = 2; i < 5; i++) // check for sector special + { + if (special != i) + continue; - if ( ((s->flags & SF_FLIPSPECIAL_FLOOR) && mo->z == flr) // floor check - || ((mo->eflags & MFE_VERTICALFLIP && (s->flags & SF_FLIPSPECIAL_CEILING) && (mo->z + mo->height) == cel)) ) // ceiling check. + if (s->flags & SF_FLIPSPECIAL_FLOOR) + { + flr = P_MobjFloorZ(mo, s, s, mo->x, mo->y, NULL, false, true); + if (mo->z == flr) // floor check + return i-1; // return offroad type + } - for (i = 2; i < 5; i++) // check for sector special - - if (GETSECSPECIAL(s->special, 1) == i) - return i-1; // return offroad type + if (mo->eflags & MFE_VERTICALFLIP && (s->flags & SF_FLIPSPECIAL_CEILING)) + { + cel = P_MobjCeilingZ(mo, s, s, mo->x, mo->y, NULL, true, true); + // NOTE: we don't use P_GetZAt with our x/y directly because the mobj won't have the same height because of its hitbox on the slope. Complex garbage but tldr it doesn't work. + if ((mo->z + mo->height) == cel) // ceiling check + return i-1; // return offroad type + } + } // 2: If we're here, we haven't found anything. So let's try looking for FOFs in the sectors using the same logic. for (rover = s->ffloors; rover; rover = rover->next) { - if (!(rover->flags & FF_EXISTS)) // This FOF doesn't exist anymore. + if (!(rover->flags & FF_EXISTS)) // This FOF doesn't exist anymore. continue; - s2 = §ors[rover->secnum]; // makes things easier for us + s2 = §ors[rover->secnum]; // makes things easier for us - flr = P_GetFOFBottomZ(mo, s, rover, mo->x, mo->y, NULL); - cel = P_GetFOFTopZ(mo, s, rover, mo->x, mo->y, NULL); // Z coords for fof top/bottom. + special = GETSECSPECIAL(s2->special, 1); + for (i = 2; i < 5; i++) // check for sector special + { + if (special != i) + continue; - // we will do essentially the same checks as above instead of bothering with top/bottom height of the FOF. - // Reminder that an FOF's floor is its bottom, silly! - if ( ((s2->flags & SF_FLIPSPECIAL_FLOOR) && mo->z == cel) // "floor" check - || ((s2->flags & SF_FLIPSPECIAL_CEILING) && (mo->z + mo->height) == flr) ) // "ceiling" check. + // we will do essentially the same checks as above instead of bothering with top/bottom height of the FOF. + // Reminder that an FOF's floor is its bottom, silly! - for (i = 2; i < 5; i++) // check for sector special - - if (GETSECSPECIAL(s2->special, 1) == i) - return i-1; // return offroad type + if (s2->flags & SF_FLIPSPECIAL_FLOOR) + { + cel = P_GetFOFTopZ(mo, s, rover, mo->x, mo->y, NULL); // Z coords for fof top/bottom. + if (mo->z == cel) // "floor" check + return i-1; // return offroad type + } + if (s2->flags & SF_FLIPSPECIAL_CEILING) + { + flr = P_GetFOFBottomZ(mo, s, rover, mo->x, mo->y, NULL); + if ((mo->z + mo->height) == flr) // "ceiling" check + return i-1; // return offroad type + } + } } } - return 0; // couldn't find any offroad + + return 0; // couldn't find any offroad } /** \brief Updates the Player's offroad value once per frame @@ -1708,7 +1749,6 @@ static void K_SpawnDashDustRelease(player_t *player) INT32 i; I_Assert(player != NULL); - I_Assert(player->mo != NULL); I_Assert(!P_MobjWasRemoved(player->mo)); if (!player->speed && !player->kartstuff[k_startboost]) @@ -1746,7 +1786,6 @@ static void K_SpawnBrakeDriftSparks(player_t *player) // Be sure to update the m mobj_t *sparks; I_Assert(player != NULL); - I_Assert(player->mo != NULL); I_Assert(!P_MobjWasRemoved(player->mo)); // Position & etc are handled in its thinker, and its spawned invisible. @@ -1865,6 +1904,7 @@ void K_RespawnChecker(player_t *player) void K_KartMoveAnimation(player_t *player) { ticcmd_t *cmd = &player->cmd; + // Standing frames - S_KART_STND1 S_KART_STND1_L S_KART_STND1_R if (player->speed == 0) { @@ -1942,11 +1982,9 @@ static void K_PlayGenericCombatSound(mobj_t *source, mobj_t *other, sfxenum_t sf if (!skin) return; - boolean alwaysHear = false; - if (cv_kartvoices.value && !P_MobjWasRemoved(other) && other->player != NULL) { - alwaysHear = P_IsDisplayPlayer(other->player); + boolean alwaysHear = P_IsDisplayPlayer(other->player); S_StartSound(alwaysHear ? NULL : source, skin->soundsid[S_sfx[sfx_id].skinsound]); } @@ -2072,16 +2110,22 @@ static void K_HandleDelayedHitByEm(player_t *player) void K_MomentumToFacing(player_t *player) { - angle_t dangle = player->mo->angle - R_PointToAngle2(0, 0, player->mo->momx, player->mo->momy); - - if (dangle > ANGLE_180) - dangle = InvAngle(dangle); - // If you aren't on the ground or are moving in too different of a direction don't do this if (player->mo->eflags & MFE_JUSTHITFLOOR) ; // Just hit floor ALWAYS redirects - else if (!P_IsObjectOnGround(player->mo) || dangle > ANGLE_90) - return; + else + { + if (!P_IsObjectOnGround(player->mo)) + return; + + angle_t dangle = player->mo->angle - R_PointToAngle2(0, 0, player->mo->momx, player->mo->momy); + + if (dangle > ANGLE_180) + dangle = InvAngle(dangle); + + if (dangle > ANGLE_90) + return; + } P_Thrust(player->mo, player->mo->angle, player->speed - FixedMul(player->speed, player->mo->friction)); player->mo->momx = FixedMul(player->mo->momx - player->cmomx, player->mo->friction) + player->cmomx; @@ -2146,7 +2190,13 @@ static void K_GetKartBoostPower(player_t *player) && player->speed > 0 && !player->spectator) { - K_SpawnWipeoutTrail(player->mo, true); + mobj_t *dust = K_SpawnWipeoutTrail(player->mo, true); + + // Technically, all mobjs that think can cause desynchs if they are spawned conditionally, so best we can do + // is to hide them if you are in saltyhop jump + if (dust && player->mo->salty.jump) + dust->flags2 |= MF2_DONTDRAW; + if (leveltime % 6 == 0) S_StartSound(player->mo, sfx_cdfm70); } @@ -2300,10 +2350,13 @@ fixed_t K_3dKartMovement(player_t *player, boolean onground, fixed_t forwardmove finalspeed *= forwardmove/25; finalspeed /= 2; - if (forwardmove < 0 && finalspeed > mapobjectscale*2) - return finalspeed/2; - else if (forwardmove < 0) + if (forwardmove < 0) + { + if (finalspeed > mapobjectscale*2) + return finalspeed/2; + return -mapobjectscale/2; + } if (finalspeed < 0) finalspeed = 0; @@ -2353,6 +2406,7 @@ void K_SpawnBattlePoints(player_t *source, player_t *victim, UINT8 amount) break; case 3: st = S_BATTLEPOINT3A; + break; default: return; // NO STATE! } @@ -2452,6 +2506,7 @@ void K_SpinPlayer(player_t *player, mobj_t *source, INT32 type, mobj_t *inflicto if (!player->kartstuff[k_bumper]) { player->kartstuff[k_comebacktimer] = comebacktime; + if (player->kartstuff[k_comebackmode] == 2) { mobj_t *poof = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z, MT_EXPLODE); @@ -2467,9 +2522,12 @@ void K_SpinPlayer(player_t *player, mobj_t *source, INT32 type, mobj_t *inflicto if (player->kartstuff[k_spinouttype] <= 0) // type 0 is spinout, type 1 is wipeout, type 2 is spb { + const fixed_t spd = K_GetKartSpeed(player, true)/4; + // At spinout, player speed is increased to 1/4 their regular speed, moving them forward - if (player->speed < K_GetKartSpeed(player, true)/4) - P_InstaThrust(player->mo, player->mo->angle, FixedMul(K_GetKartSpeed(player, true)/4, player->mo->scale)); + if (player->speed < spd) + P_InstaThrust(player->mo, player->mo->angle, FixedMul(spd, player->mo->scale)); + S_StartSound(player->mo, sfx_slip); } @@ -2480,10 +2538,12 @@ void K_SpinPlayer(player_t *player, mobj_t *source, INT32 type, mobj_t *inflicto P_SetPlayerMobjState(player->mo, S_KART_SPIN); player->kartstuff[k_instashield] = 15; + if (cv_kartdebughuddrop.value && !modeattacking) K_DropItems(player); else K_DropHnextList(player); + return; } @@ -3006,17 +3066,24 @@ static mobj_t *K_SpawnKartMissile(mobj_t *source, mobjtype_t type, angle_t an, I fixed_t finalspeed = speed; mobj_t *throwmo; - if (source->player && source->player->speed > K_GetKartSpeed(source->player, false)) + if (source->player) { - angle_t input = source->angle - an; - boolean invert = (input > ANGLE_180); - if (invert) - input = InvAngle(input); + const fixed_t kartspd = K_GetKartSpeed(source->player, false); - finalspeed = max(speed, FixedMul(speed, FixedMul( - FixedDiv(source->player->speed, K_GetKartSpeed(source->player, false)), // Multiply speed to be proportional to your own, boosted maxspeed. - (((180<player->speed > kartspd) + { + angle_t input = source->angle - an; + boolean invert = (input > ANGLE_180); + if (invert) + input = InvAngle(input); + + finalspeed = FixedMul(speed, FixedMul( + FixedDiv(source->player->speed, kartspd), // Multiply speed to be proportional to your own, boosted maxspeed. + (((180<x + source->momx + FixedMul(finalspeed, FINECOSINE(an>>ANGLETOFINESHIFT)); @@ -3103,17 +3170,18 @@ static mobj_t *K_SpawnKartMissile(mobj_t *source, mobjtype_t type, angle_t an, I return NULL; } -static UINT16 K_DriftSparkColor(player_t *player, INT32 charge) +static UINT8 K_DriftSparkColor(player_t *player, INT32 charge) { - UINT16 color = SKINCOLOR_NONE; + UINT8 color = SKINCOLOR_NONE; + const INT32 sparkval = K_GetKartDriftSparkValue(player); - if (charge >= K_GetKartDriftSparkValue(player)*4) + if (charge >= sparkval*4) { color = K_RainbowColor(); } - else if (charge >= K_GetKartDriftSparkValue(player)*2) + else if (charge >= sparkval*2) { - if (charge <= (K_GetKartDriftSparkValue(player)*2)+(24*3)) + if (charge <= (sparkval*2)+(24*3)) color = SKINCOLOR_RASPBERRY; // transition else color = SKINCOLOR_KETCHUP; @@ -3137,7 +3205,6 @@ static void K_SpawnDriftSparks(player_t *player) INT32 i; I_Assert(player != NULL); - I_Assert(player->mo != NULL); I_Assert(!P_MobjWasRemoved(player->mo)); if (leveltime % 2 == 1) @@ -3258,6 +3325,8 @@ static void K_SpawnAIZDust(player_t *player) static void K_StretchPlayerGravity(player_t *player) { + fixed_t stretchScaleFactor; + I_Assert(player != NULL); I_Assert(!P_MobjWasRemoved(player->mo)); @@ -3266,7 +3335,8 @@ static void K_StretchPlayerGravity(player_t *player) fixed_t tempxscale = pmo->realxscale; fixed_t tempyscale = pmo->realyscale; - const fixed_t stretchScaleFactor = min(FixedDiv(FRACUNIT*60, cv_gravstretch.value), MAXSTRETCHDIV); + stretchScaleFactor = FixedDiv(FRACUNIT*60, cv_gravstretch.value); + stretchScaleFactor = min(stretchScaleFactor, MAXSTRETCHDIV); if (pmo->slamsoundtimer) pmo->slamsoundtimer--; @@ -3322,7 +3392,7 @@ static void K_SaltySquish(player_t *player) if (pmo->stretchslam > 0) { - const fixed_t slamDiv = FixedDiv(pmo->stretchslam, 3932160); // stretchScaleFactor = FixedDiv(FRACUNIT*60, FRACUNIT) + const fixed_t slamDiv = FixedDiv(pmo->stretchslam, FRACUNIT*60); // stretchScaleFactor = FixedDiv(FRACUNIT*60, FRACUNIT) pmo->spritexscale = (tempxscale + (((slamDiv*2)/3)*2)); pmo->spriteyscale = (tempyscale - slamDiv); @@ -3401,7 +3471,7 @@ static void K_QuiteSaltyHop(player_t *player) pmo->spritexscale -= (FRACUNIT/8); } - pmo->spriteyoffset = FixedMul(psalt->zoffset, cv_saltyheight.value); + pmo->spriteyoffset += FixedMul(psalt->zoffset, cv_saltyheight.value); if (cv_saltyhopsfx.value) { @@ -3448,6 +3518,16 @@ boolean K_ShouldSlopeRoll(mobj_t *mobj) return K_CheckSlopeRollDist(mobj); } +static INT32 K_AltFlip(INT32 n, tic_t tics) +{ + return leveltime % (2 * tics) < tics ? n : -(n); +} + +static INT32 K_StairJankFlip(INT32 value) +{ + return K_AltFlip(value, 2); +} + #define SLOPEROLL_DIV 3 void K_RollMobjBySlopes(mobj_t* mo, pslope_t *slope) { @@ -3509,7 +3589,6 @@ void K_SpawnBoostTrail(player_t *player) INT32 i; I_Assert(player != NULL); - I_Assert(player->mo != NULL); I_Assert(!P_MobjWasRemoved(player->mo)); if (!P_IsObjectOnGround(player->mo) @@ -3591,9 +3670,10 @@ void K_SpawnSparkleTrail(mobj_t *mo) mobj_t *sparkle; INT32 i; - I_Assert(mo != NULL); I_Assert(!P_MobjWasRemoved(mo)); + const boolean shouldblend = (mo->player && K_PlayerEffectsShouldBlend(mo->player)); + for (i = 0; i < 3; i++) { fixed_t newx = mo->x + mo->momx + (P_RandomRange(-rad, rad)<color = mo->color; - if (mo->player && K_PlayerEffectsShouldBlend(mo->player)) + if (shouldblend) sparkle->blendmode = AST_ADD; } P_SetMobjState(sparkle, S_KARTINVULN_LARGE1); } -void K_SpawnWipeoutTrail(mobj_t *mo, boolean translucent) +mobj_t *K_SpawnWipeoutTrail(mobj_t *mo, boolean translucent) { mobj_t *dust; angle_t aoff; - I_Assert(mo != NULL); I_Assert(!P_MobjWasRemoved(mo)); if (mo->player) @@ -3655,10 +3734,10 @@ void K_SpawnWipeoutTrail(mobj_t *mo, boolean translucent) dust->momx = mo->momx/2; dust->momy = mo->momy/2; dust->momz = mo->momz/2; + dust->flags2 |= MF2_SHADOW; } - if (translucent) - dust->flags2 |= MF2_SHADOW; + return dust; } // K_DriftDustHandling @@ -3672,7 +3751,7 @@ void K_DriftDustHandling(mobj_t *spawner) { angle_t anglediff; - if (!P_IsObjectOnGround(spawner) || leveltime % 2 != 0) + if (leveltime % 2 != 0 || !P_IsObjectOnGround(spawner)) return; if (spawner->player) @@ -3853,6 +3932,7 @@ static mobj_t *K_ThrowKartItem(player_t *player, boolean missile, mobjtype_t map // Shoot forward mo = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z + player->mo->height/2, mapthing); //K_FlipFromObject(mo, player->mo); + // These are really weird so let's make it a very specific case to make SURE it works... if (player->mo->eflags & MFE_VERTICALFLIP) { @@ -3882,17 +3962,16 @@ static mobj_t *K_ThrowKartItem(player_t *player, boolean missile, mobjtype_t map if (cv_bananthrowroll.value && (mapthing == MT_BANANA)) { - //mo->angle = FixedAngle(M_RandomRange(-180, 180) << FRACBITS); - if (cv_bananthrowroll.value == 1 && K_CheckSlopeRollDist(mo)) - mo->sloperoll = (angle_t)FixedAngle(M_RandomRange(-180, 180) << FRACBITS); // im lazy but this makes sure the banan goes back to upright when it lands lmao - else if (cv_bananthrowroll.value == 2) - mo->rollangle = (angle_t)FixedAngle(M_RandomRange(-180, 180) << FRACBITS); + const angle_t speen = (angle_t)FixedAngle(M_RandomRange(-180, 180) << FRACBITS); + //mo->angle = speen; + mo->rollangle = speen; } } // this is the small graphic effect that plops in you when you throw an item: throwmo = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z + player->mo->height/2, MT_FIREDITEM); P_SetTarget(&throwmo->target, player->mo); + // Ditto: if (player->mo->eflags & MFE_VERTICALFLIP) { @@ -3936,6 +4015,7 @@ static mobj_t *K_ThrowKartItem(player_t *player, boolean missile, mobjtype_t map // floorz and ceilingz aren't properly set to account for FOFs and Polyobjects on spawn // This should set it for FOFs P_SetOrigin(mo, mo->x, mo->y, mo->z); // however, THIS can fuck up your day. just absolutely ruin you. + if (P_MobjWasRemoved(mo)) return NULL; @@ -4055,7 +4135,7 @@ static void K_DoThunderShield(player_t *player) mo->scale = player->mo->scale*3 + (player->mo->scale/2); // spawn horizontal bolts; - for (i=0; i<7; i++) + for (i = 0; i < 7; i++) { mo = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z, MT_THOK); mo->angle = P_RandomRange(0, 359)*ANG1; @@ -4066,7 +4146,7 @@ static void K_DoThunderShield(player_t *player) // spawn the radius thing: an = ANGLE_22h; - for (i=0; i<15; i++) + for (i = 0; i < 15; i++) { sx = player->mo->x + FixedMul((player->mo->scale*THUNDERRADIUS), FINECOSINE((an*i)>>ANGLETOFINESHIFT)); sy = player->mo->y + FixedMul((player->mo->scale*THUNDERRADIUS), FINESINE((an*i)>>ANGLETOFINESHIFT)); @@ -4158,12 +4238,12 @@ static void K_DoHyudoroSteal(player_t *player) void K_DoSneaker(player_t *player, INT32 type) { - const fixed_t intendedboost = K_GetSneakerBoostSpeed(); - if (!player->kartstuff[k_floorboost] || player->kartstuff[k_floorboost] == 3) { S_StartSound(player->mo, sfx_cdfm01); K_SpawnDashDustRelease(player); + + const fixed_t intendedboost = K_GetSneakerBoostSpeed(); if (intendedboost > player->kartstuff[k_speedboost]) player->kartstuff[k_destboostcam] = FixedMul(FRACUNIT, FixedDiv((intendedboost - player->kartstuff[k_speedboost]), intendedboost)); } @@ -4246,8 +4326,10 @@ static void K_DoShrink(player_t *user) { players[i].mo->scalespeed = mapobjectscale/TICRATE; players[i].mo->destscale = (6*mapobjectscale)/8; + if (cv_kartdebugshrink.value && !modeattacking && !players[i].bot) players[i].mo->destscale = (6*players[i].mo->destscale)/8; + S_StartSound(players[i].mo, sfx_kc59); } } @@ -4492,49 +4574,59 @@ void K_DropHnextList(player_t *player) P_RemoveMobj(work); } + // we need this here too because this is done in afterthink - pointers are cleaned up at the START of each tic... + P_SetTarget(&player->mo->hnext, NULL); + player->kartstuff[k_bananadrag] = 0; + + if (player->kartstuff[k_eggmanheld]) + player->kartstuff[k_eggmanheld] = 0; + else if (player->kartstuff[k_itemheld] + && (dropall || (--player->kartstuff[k_itemamount] <= 0))) { - // we need this here too because this is done in afterthink - pointers are cleaned up at the START of each tic... - P_SetTarget(&player->mo->hnext, NULL); - player->kartstuff[k_bananadrag] = 0; - if (player->kartstuff[k_eggmanheld]) - player->kartstuff[k_eggmanheld] = 0; - else if (player->kartstuff[k_itemheld] - && (dropall || (--player->kartstuff[k_itemamount] <= 0))) - { - player->kartstuff[k_itemamount] = player->kartstuff[k_itemheld] = 0; - player->kartstuff[k_itemtype] = KITEM_NONE; - } + player->kartstuff[k_itemamount] = player->kartstuff[k_itemheld] = 0; + player->kartstuff[k_itemtype] = KITEM_NONE; } } +static void K_DropPaperItem(player_t *player, boolean thunderhack, INT32 itemamount) +{ + const mobj_t *pmo = player->mo; + + if (P_MobjWasRemoved(pmo)) + { + return; + } + + mobj_t *drop = P_SpawnMobj(pmo->x, pmo->y, (pmo->z + pmo->height/2), MT_FLOATINGITEM); + P_SetScale(drop, drop->scale>>4); + + drop->destscale = (3*drop->destscale)/2; + + drop->angle = pmo->angle + ANGLE_90; + P_Thrust(drop, FixedAngle(P_RandomFixed()*180) + pmo->angle + ANGLE_90, 16*mapobjectscale); + drop->momz = P_MobjFlip(pmo)*3*mapobjectscale; + if (drop->eflags & MFE_UNDERWATER) + drop->momz = (117 * drop->momz) / 200; + + drop->threshold = (thunderhack ? KITEM_THUNDERSHIELD : player->kartstuff[k_itemtype]); + drop->movecount = itemamount; + + drop->flags |= MF_NOCLIPTHING; +} + // For getting EXTRA hit! void K_DropItems(player_t *player) { - boolean thunderhack = (player->kartstuff[k_curshield] && player->kartstuff[k_itemtype] == KITEM_THUNDERSHIELD); + const boolean thunderhack = (player->kartstuff[k_curshield] && player->kartstuff[k_itemtype] == KITEM_THUNDERSHIELD); if (thunderhack) player->kartstuff[k_itemtype] = KITEM_NONE; K_DropHnextList(player); - if (!P_MobjWasRemoved(player->mo) && player->kartstuff[k_itemamount]) + if (player->kartstuff[k_itemamount]) { - mobj_t *drop = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z + player->mo->height/2, MT_FLOATINGITEM); - P_SetScale(drop, drop->scale>>4); - drop->destscale = (3*drop->destscale)/2; - - drop->angle = player->mo->angle + ANGLE_90; - P_Thrust(drop, - FixedAngle(P_RandomFixed()*180) + player->mo->angle + ANGLE_90, - 16*mapobjectscale); - drop->momz = P_MobjFlip(player->mo)*3*mapobjectscale; - if (drop->eflags & MFE_UNDERWATER) - drop->momz = (117 * drop->momz) / 200; - - drop->threshold = (thunderhack ? KITEM_THUNDERSHIELD : player->kartstuff[k_itemtype]); - drop->movecount = player->kartstuff[k_itemamount]; - - drop->flags |= MF_NOCLIPTHING; + K_DropPaperItem(player, thunderhack, player->kartstuff[k_itemamount]); } K_StripItems(player); @@ -4552,7 +4644,7 @@ void K_DropRocketSneaker(player_t *player) while ((shoe = shoe->hnext) && !P_MobjWasRemoved(shoe)) { if (shoe->type != MT_ROCKETSNEAKER) - return; //woah, not a rocketsneaker, bail! safeguard in case this gets used when you're holding non-rocketsneakers + return; // woah, not a rocketsneaker, bail! safeguard in case this gets used when you're holding non-rocketsneakers shoe->flags2 &= ~MF2_DONTDRAW; shoe->flags &= ~MF_NOGRAVITY; @@ -4579,6 +4671,7 @@ void K_DropRocketSneaker(player_t *player) leftshoe = false; } + P_SetTarget(&player->mo->hnext, NULL); player->kartstuff[k_rocketsneakertimer] = 0; } @@ -4589,7 +4682,7 @@ void K_DropKitchenSink(player_t *player) return; if (player->mo->hnext->type != MT_SINK_SHIELD) - return; //so we can just call this function regardless of what is being held + return; // so we can just call this function regardless of what is being held P_KillMobj(player->mo->hnext, NULL, NULL); @@ -4615,9 +4708,8 @@ void K_RepairOrbitChain(mobj_t *orbit) } // Then recount to make sure item amount is correct - if (orbit->target && orbit->target->player) + if (!P_MobjWasRemovedCompat(orbit->target) && orbit->target->player) { - player_t *player = orbit->target->player; INT32 num = 0; mobj_t *cur = orbit->target->hnext; @@ -4627,14 +4719,14 @@ void K_RepairOrbitChain(mobj_t *orbit) { prev = cur; cur = cur->hnext; - if (++num > player->kartstuff[k_itemamount]) + if (++num > orbit->target->player->kartstuff[k_itemamount]) P_RemoveMobj(prev); else prev->movedir = num; } - if (player->kartstuff[k_itemamount] != num) - player->kartstuff[k_itemamount] = num; + if (!P_MobjWasRemovedCompat(orbit->target)) + orbit->target->player->kartstuff[k_itemamount] = num; } } @@ -4780,7 +4872,7 @@ static void K_CalculateBananaSlope(mobj_t *mobj, fixed_t x, fixed_t y, fixed_t z // Move the hnext chain! static void K_MoveHeldObjects(player_t *player) { - if (!player->mo) + if (P_MobjWasRemovedCompat(player->mo)) return; if (!player->mo->hnext) @@ -4794,6 +4886,7 @@ static void K_MoveHeldObjects(player_t *player) player->kartstuff[k_itemamount] = player->kartstuff[k_itemheld] = 0; player->kartstuff[k_itemtype] = KITEM_NONE; } + return; } @@ -4810,6 +4903,7 @@ static void K_MoveHeldObjects(player_t *player) player->kartstuff[k_itemamount] = player->kartstuff[k_itemheld] = 0; player->kartstuff[k_itemtype] = KITEM_NONE; } + return; } @@ -4825,7 +4919,6 @@ static void K_MoveHeldObjects(player_t *player) while (!P_MobjWasRemoved(cur)) { - const fixed_t radius = FixedHypot(player->mo->radius, player->mo->radius) + FixedHypot(cur->radius, cur->radius); // mobj's distance from its Target, or Radius. fixed_t z; if (!cur->health) @@ -4834,6 +4927,8 @@ static void K_MoveHeldObjects(player_t *player) continue; } + const fixed_t radius = FixedHypot(player->mo->radius, player->mo->radius) + FixedHypot(cur->radius, cur->radius); // mobj's distance from its Target, or Radius. + cur->color = player->skincolor; cur->angle -= ANGLE_90; @@ -4863,8 +4958,10 @@ static void K_MoveHeldObjects(player_t *player) cur->momx = FixedMul(FINECOSINE(cur->angle>>ANGLETOFINESHIFT), cur->extravalue1); cur->momy = FixedMul(FINESINE(cur->angle>>ANGLETOFINESHIFT), cur->extravalue1); cur->flags &= ~MF_NOCLIPTHING; + if (!P_TryMove(cur, player->mo->x + cur->momx, player->mo->y + cur->momy, true)) P_SlideMove(cur, true); + if (P_IsObjectOnGround(player->mo)) { if (P_MobjFlip(cur) > 0) @@ -4898,14 +4995,11 @@ static void K_MoveHeldObjects(player_t *player) mobj_t *cur = player->mo->hnext; mobj_t *targ = player->mo; - const boolean ponground = P_IsObjectOnGround(player->mo); - - if (ponground && player->speed > 0) + if (player->speed > 0 && P_IsObjectOnGround(player->mo)) player->kartstuff[k_bananadrag]++; while (!P_MobjWasRemoved(cur)) { - const fixed_t radius = FixedHypot(targ->radius, targ->radius) + FixedHypot(cur->radius, cur->radius); angle_t ang; fixed_t targx, targy, targz; fixed_t speed, dist; @@ -4918,6 +5012,8 @@ static void K_MoveHeldObjects(player_t *player) continue; } + const fixed_t radius = FixedHypot(targ->radius, targ->radius) + FixedHypot(cur->radius, cur->radius); + if (cur->extravalue1 < radius) cur->extravalue1 += FixedMul(P_AproxDistance(cur->extravalue1, radius), FRACUNIT/12); if (cur->extravalue1 > radius) @@ -4948,7 +5044,8 @@ static void K_MoveHeldObjects(player_t *player) cur->angle = R_PointToAngle2(cur->x, cur->y, targx, targy); - /*if (P_IsObjectOnGround(player->mo) && player->speed > 0 && player->kartstuff[k_bananadrag] > TICRATE + /*if (player->speed > 0 && P_IsObjectOnGround(player->mo) + && player->kartstuff[k_bananadrag] > TICRATE && P_RandomChance(min(FRACUNIT/2, FixedDiv(player->speed, K_GetKartSpeed(player, false))/2))) { if (leveltime & 1) @@ -4957,8 +5054,9 @@ static void K_MoveHeldObjects(player_t *player) targz -= 8*(2*FRACUNIT)/7; }*/ - if (cv_bananajitter.value && ponground - && player->speed > 0 && player->kartstuff[k_bananadrag] > TICRATE) + // "jitter" dragged bananas around + if (cv_bananajitter.value && + player->speed > 0 && P_IsObjectOnGround(player->mo) && player->kartstuff[k_bananadrag] > TICRATE) { const fixed_t halfpspeed = FixedDiv(player->speed, K_GetKartSpeed(player, false))/2; @@ -4996,11 +5094,10 @@ static void K_MoveHeldObjects(player_t *player) while (!P_MobjWasRemoved(cur)) { - const fixed_t radius = FixedHypot(player->mo->radius, player->mo->radius) + FixedHypot(cur->radius, cur->radius); - boolean vibrate = ((leveltime & 1) && !cur->tracer); angle_t angoffset; fixed_t targx, targy, targz; - + const boolean vibrate = ((leveltime & 1) && !cur->tracer); + cur->flags &= ~MF_NOCLIPTHING; if (player->kartstuff[k_rocketsneakertimer] <= TICRATE && (leveltime & 1)) @@ -5020,6 +5117,8 @@ static void K_MoveHeldObjects(player_t *player) continue; } + const fixed_t radius = FixedHypot(player->mo->radius, player->mo->radius) + FixedHypot(cur->radius, cur->radius); + if (cur->extravalue1 < radius) cur->extravalue1 += FixedMul(P_AproxDistance(cur->extravalue1, radius), FRACUNIT/12); if (cur->extravalue1 > radius) @@ -5056,7 +5155,6 @@ static void K_MoveHeldObjects(player_t *player) targz = (player->mo->z + (player->mo->height/2)) + sine; if (player->mo->eflags & MFE_VERTICALFLIP) targz += (player->mo->height/2 - 32*player->mo->scale)*6; - } if (!P_MobjWasRemoved(cur->tracer)) @@ -5133,9 +5231,11 @@ player_t *K_FindJawzTarget(mobj_t *actor, player_t *source) // Don't go for people who are behind you if (thisang > ANGLE_67h) continue; + // Don't pay attention to people who aren't above your position if (player->kartstuff[k_position] >= source->kartstuff[k_position]) continue; + if ((best == -1) || (player->kartstuff[k_position] > best)) { wtarg = player; @@ -5284,7 +5384,7 @@ static void K_UpdateEngineSounds(player_t *player, ticcmd_t *cmd) } dist = P_AproxDistance( - P_AproxDistance( + P_AproxDistance( player->mo->x - players[i].mo->x, player->mo->y - players[i].mo->y), player->mo->z - players[i].mo->z) / 2; @@ -5368,59 +5468,15 @@ boolean K_PlayerEffectsShouldBlend(player_t *player) return false; } -static UINT8 K_GetSpeedLineColor(player_t *player, boolean colorSpeed) +FUNCINLINE static ATTRINLINE void K_SpawnNormalSpeedLines(player_t *player) { - UINT8 speedcolor = SKINCOLOR_NONE; - const UINT8 playercolor = player->mo->color; - - if (colorSpeed) - { - if (cv_coloredspeedlines.value != 3) - speedcolor = playercolor; - - if (cv_coloredspeedlines.value >= 2 && player->kartstuff[k_driftboost]) - { - if (player->kartstuff[k_driftboost] <= 20) - speedcolor = SKINCOLOR_SAPPHIRE; - else if (player->kartstuff[k_driftboost] <= 50) - speedcolor = SKINCOLOR_RASPBERRY; - else if (player->kartstuff[k_driftboost] <= 125) - speedcolor = K_RainbowColor(); - - if (cv_coloredspeedlines.value == 2) - speedcolor = (leveltime & 1) ? playercolor : speedcolor; - } - } - - if (cv_coloredspeedlines.value != 3) - { - if (player->kartstuff[k_eggmanexplode]) - { - // Make it red when you have the eggman speed boost - speedcolor = SKINCOLOR_RED; - } - else if (player->kartstuff[k_invincibilitytimer]) - { - speedcolor = playercolor; - } - } - - return speedcolor; -} - -typedef INT32 (*randomFunc)(INT32 min, INT32 max); - -FUNCINLINE static ATTRINLINE void K_SpawnNormalSpeedLines(player_t *player, boolean synched) -{ - randomFunc randomfunc = synched ? P_RandomRange : M_RandomRange; - fixed_t rand_x; fixed_t rand_y; fixed_t rand_z; - rand_z = player->mo->z + (player->mo->height/2) + (randomfunc(-20,20) * player->mo->scale); - rand_y = player->mo->y + (randomfunc(-36,36) * player->mo->scale); - rand_x = player->mo->x + (randomfunc(-36,36) * player->mo->scale); + rand_z = player->mo->z + (player->mo->height/2) + (P_RandomRange(-20, 20) * player->mo->scale); + rand_y = player->mo->y + (P_RandomRange(-36, 36) * player->mo->scale); + rand_x = player->mo->x + (P_RandomRange(-36, 36) * player->mo->scale); mobj_t *fast = P_SpawnMobj(rand_x, rand_y, rand_z, MT_FASTLINE); @@ -5428,7 +5484,7 @@ FUNCINLINE static ATTRINLINE void K_SpawnNormalSpeedLines(player_t *player, bool fast->momx = 3*player->mo->momx/4; fast->momy = 3*player->mo->momy/4; fast->momz = 3*player->mo->momz/4; - fast->islocal = !synched; + //fast->islocal = false; P_SetTarget(&fast->target, player->mo); // easier lua access K_MatchGenericExtraFlags(fast, player->mo); @@ -5439,8 +5495,11 @@ FUNCINLINE static ATTRINLINE void K_SpawnNormalSpeedLines(player_t *player, bool if (cv_coloredspeedlines.value) { - fast->color = K_GetSpeedLineColor(player, colorSpeed); - fast->colorized = true; + if (colorSpeed || player->kartstuff[k_invincibilitytimer]) // let invul color them even when players go rather slow + { + fast->color = player->mo->color; + fast->colorized = true; + } } if (colorSpeed && K_PlayerEffectsShouldBlend(player)) @@ -5469,11 +5528,7 @@ void K_KartPlayerThink(player_t *player, ticcmd_t *cmd) // Speed lines if ((player->kartstuff[k_sneakertimer] || player->kartstuff[k_driftboost] || player->kartstuff[k_startboost]) && player->speed > 0) { - K_SpawnNormalSpeedLines(player, true); - } - else if ((cv_coloredspeedlines.value == 1 || cv_coloredspeedlines.value == 2) && player->kartstuff[k_eggmanexplode]) // gotta love the speedlines calling synched rng :chaosleep: - { - K_SpawnNormalSpeedLines(player, false); + K_SpawnNormalSpeedLines(player); } if (player->playerstate == PST_DEAD || player->kartstuff[k_respawn] > 1) // Ensure these are set correctly here @@ -5685,17 +5740,19 @@ void K_KartPlayerThink(player_t *player, ticcmd_t *cmd) else { player->kartstuff[k_eggmanexplode]--; + if (player->kartstuff[k_eggmanexplode] <= 0) { - mobj_t *eggsexplode; //player->powers[pw_flashing] = 0; - eggsexplode = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z, MT_SPBEXPLOSION); - if (player->kartstuff[k_eggmanblame] >= 0 - && player->kartstuff[k_eggmanblame] < MAXPLAYERS - && playeringame[player->kartstuff[k_eggmanblame]] - && !players[player->kartstuff[k_eggmanblame]].spectator - && players[player->kartstuff[k_eggmanblame]].mo) - P_SetTarget(&eggsexplode->target, players[player->kartstuff[k_eggmanblame]].mo); + mobj_t *eggsplode = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z, MT_SPBEXPLOSION); + + const INT32 blametarg = player->kartstuff[k_eggmanblame]; + + if ((blametarg >= 0 && blametarg < MAXPLAYERS) + && playeringame[blametarg] + && !players[blametarg].spectator + && players[blametarg].mo) + P_SetTarget(&eggsplode->target, players[blametarg].mo); } } } @@ -5714,7 +5771,7 @@ void K_KartPlayerThink(player_t *player, ticcmd_t *cmd) if (player->kartstuff[k_comebacktimer]) player->kartstuff[k_comebackmode] = 0; - if (P_IsObjectOnGround(player->mo) && player->kartstuff[k_pogospring]) + if (player->kartstuff[k_pogospring] && P_IsObjectOnGround(player->mo)) { if (P_MobjFlip(player->mo)*player->mo->momz <= 0) player->kartstuff[k_pogospring] = 0; @@ -5852,7 +5909,7 @@ static INT16 K_GetKartDriftValue(player_t *player, fixed_t countersteer) //basedrift = 90*player->kartstuff[k_drift]; // 450 //basedrift = 93*player->kartstuff[k_drift] - driftweight*3*player->kartstuff[k_drift]/10; // 447 - 303 - basedrift = 83*player->kartstuff[k_drift] - (driftweight - 14)*player->kartstuff[k_drift]/5; // 415 - 303 + basedrift = 83*player->kartstuff[k_drift] - (driftweight - 14)*player->kartstuff[k_drift]/5; // 415 - 303 driftangle = abs((252 - driftweight)*player->kartstuff[k_drift]/5); return basedrift + FixedMul(driftangle, countersteer); @@ -5904,6 +5961,8 @@ INT32 K_GetKartDriftSparkValue(player_t *player) static void K_KartDrift(player_t *player, boolean onground) { + const ticcmd_t *cmd = &player->cmd; + fixed_t minspeed = (10 * player->mo->scale); INT32 dsone = K_GetKartDriftSparkValue(player); INT32 dstwo = dsone*2; @@ -5925,55 +5984,50 @@ static void K_KartDrift(player_t *player, boolean onground) { player->kartstuff[k_driftcharge] = 0; } - else if (player->kartstuff[k_driftcharge] >= dsone && player->kartstuff[k_driftcharge] < dstwo) + else if (player->kartstuff[k_driftcharge] >= dsone && + player->kartstuff[k_driftcharge] < dstwo) { if (player->kartstuff[k_driftboost] < 20) player->kartstuff[k_driftboost] = 20; + S_StartSound(player->mo, sfx_s23c); + player->kartstuff[k_driftcharge] = 0; } else if (player->kartstuff[k_driftcharge] < dsthree) { if (player->kartstuff[k_driftboost] < 50) player->kartstuff[k_driftboost] = 50; + S_StartSound(player->mo, sfx_s23c); + player->kartstuff[k_driftcharge] = 0; } else if (player->kartstuff[k_driftcharge] >= dsthree) { if (player->kartstuff[k_driftboost] < 125) player->kartstuff[k_driftboost] = 125; + S_StartSound(player->mo, sfx_s23c); + player->kartstuff[k_driftcharge] = 0; } } // Drifting: left or right? - if ((player->cmd.driftturn > 0) && player->speed > minspeed && player->kartstuff[k_jmp] == 1 - && (player->kartstuff[k_drift] == 0 || player->kartstuff[k_driftend] == 1)) // && player->kartstuff[k_drift] != 1) + if ((cmd->driftturn != 0) && player->speed > minspeed && player->kartstuff[k_jmp] == 1 + && (player->kartstuff[k_drift] == 0 || player->kartstuff[k_driftend] == 1)) { - // Starting left drift - player->kartstuff[k_drift] = 1; + // Starting left or right drift + player->kartstuff[k_drift] = intsign(cmd->driftturn); player->kartstuff[k_driftend] = 0; } - else if ((player->cmd.driftturn < 0) && player->speed > minspeed && player->kartstuff[k_jmp] == 1 - && (player->kartstuff[k_drift] == 0 || player->kartstuff[k_driftend] == 1)) // && player->kartstuff[k_drift] != -1) - { - // Starting right drift - player->kartstuff[k_drift] = -1; - player->kartstuff[k_driftend] = 0; - } - else if (player->kartstuff[k_jmp] == 0) // || player->kartstuff[k_turndir] == 0) + else if (player->kartstuff[k_jmp] == 0) { // drift is not being performed so if we're just finishing set driftend and decrement counters - if (player->kartstuff[k_drift] > 0) + if (player->kartstuff[k_drift] != 0) { - player->kartstuff[k_drift]--; - player->kartstuff[k_driftend] = 1; - } - else if (player->kartstuff[k_drift] < 0) - { - player->kartstuff[k_drift]++; + player->kartstuff[k_drift] -= intsign(player->kartstuff[k_drift]); player->kartstuff[k_driftend] = 1; } else @@ -5994,10 +6048,10 @@ static void K_KartDrift(player_t *player, boolean onground) if (player->kartstuff[k_drift] > 5) player->kartstuff[k_drift] = 5; - if (player->cmd.driftturn > 0) // Inward - driftadditive += abs(player->cmd.driftturn)/100; - if (player->cmd.driftturn < 0) // Outward - driftadditive -= abs(player->cmd.driftturn)/75; + if (cmd->driftturn > 0) // Inward + driftadditive += abs(cmd->driftturn)/100; + else if (cmd->driftturn < 0) // Outward + driftadditive -= abs(cmd->driftturn)/75; } else if (player->kartstuff[k_drift] <= -1) // Drifting to the right { @@ -6005,26 +6059,31 @@ static void K_KartDrift(player_t *player, boolean onground) if (player->kartstuff[k_drift] < -5) player->kartstuff[k_drift] = -5; - if (player->cmd.driftturn < 0) // Inward - driftadditive += abs(player->cmd.driftturn)/100; - if (player->cmd.driftturn > 0) // Outward - driftadditive -= abs(player->cmd.driftturn)/75; + if (cmd->driftturn < 0) // Inward + driftadditive += abs(cmd->driftturn)/100; + else if (cmd->driftturn > 0) // Outward + driftadditive -= abs(cmd->driftturn)/75; } // Disable drift-sparks until you're going fast enough - if (player->kartstuff[k_getsparks] == 0 || (player->kartstuff[k_offroad] && !player->kartstuff[k_invincibilitytimer] && !player->kartstuff[k_hyudorotimer] && !player->kartstuff[k_sneakertimer])) + if (player->kartstuff[k_getsparks] == 0 || + (player->kartstuff[k_offroad] && !player->kartstuff[k_invincibilitytimer] && !player->kartstuff[k_hyudorotimer] && !player->kartstuff[k_sneakertimer])) driftadditive = 0; + if (player->speed > minspeed*2) player->kartstuff[k_getsparks] = 1; - const boolean driftblue = (player->kartstuff[k_driftcharge] < dsone && player->kartstuff[k_driftcharge]+driftadditive >= dsone); - const boolean driftred = (player->kartstuff[k_driftcharge] < dstwo && player->kartstuff[k_driftcharge]+driftadditive >= dstwo); - const boolean driftrainbow = (player->kartstuff[k_driftcharge] < dsthree && player->kartstuff[k_driftcharge]+driftadditive >= dsthree); + if (player->kartstuff[k_driftcharge] < dsthree && player->kartstuff[k_driftcharge]+driftadditive >= dsthree) // rainbow drift + player->driftlevel = 3; + else if (player->kartstuff[k_driftcharge] < dstwo && player->kartstuff[k_driftcharge]+driftadditive >= dstwo) // red drift + player->driftlevel = 2; + else if (player->kartstuff[k_driftcharge] < dsone && player->kartstuff[k_driftcharge]+driftadditive >= dsone) // blue drift + player->driftlevel = 1; + else + player->driftlevel = 0; // Sound whenever you get a different tier of sparks - if (driftblue - || driftred - || driftrainbow) + if (player->driftlevel) { //S_StartSound(player->mo, sfx_s3ka2); if (P_IsLocalPlayer(player)) // UGHGHGH... @@ -6032,13 +6091,6 @@ static void K_KartDrift(player_t *player, boolean onground) S_StartSoundAtVolume(player->mo, sfx_s3ka2, 192); // Ugh... } - if (driftrainbow) - player->driftlevel = 3; - else if (driftred) - player->driftlevel = 2; - else if (driftblue) - player->driftlevel = 1; - player->driftsparkGrowTimer = DRIFTSPARKGROWTICS; } } @@ -6070,14 +6122,11 @@ static void K_KartDrift(player_t *player, boolean onground) } if ((!player->kartstuff[k_sneakertimer]) - || (!player->cmd.driftturn) + || (!cmd->driftturn) || (!player->kartstuff[k_aizdriftstrat]) - || (player->cmd.driftturn > 0) != (player->kartstuff[k_aizdriftstrat] > 0)) + || (cmd->driftturn > 0) != (player->kartstuff[k_aizdriftstrat] > 0)) { - if (!player->kartstuff[k_drift]) - player->kartstuff[k_aizdriftstrat] = 0; - else - player->kartstuff[k_aizdriftstrat] = ((player->kartstuff[k_drift] > 0) ? 1 : -1); + player->kartstuff[k_aizdriftstrat] = intsign(player->kartstuff[k_drift]); } else if (player->kartstuff[k_aizdriftstrat] && !player->kartstuff[k_drift]) { @@ -6088,18 +6137,77 @@ static void K_KartDrift(player_t *player, boolean onground) } if (player->kartstuff[k_drift] - && ((player->cmd.buttons & BT_BRAKE) - || !(player->cmd.buttons & BT_ACCELERATE)) + && ((cmd->buttons & BT_BRAKE) + || !(cmd->buttons & BT_ACCELERATE)) && P_IsObjectOnGround(player->mo)) { if (!player->kartstuff[k_brakedrift]) K_SpawnBrakeDriftSparks(player); + player->kartstuff[k_brakedrift] = 1; } else player->kartstuff[k_brakedrift] = 0; } +INT32 stprevnextchecks[2] = {INT32_MAX, INT32_MAX}; // there wont be any map this big, wont there?..... + +// K_KartUpdatePosition has a bug where whatever player comes last in the players array +// gets its distance calculations applied twice +// since we cannot fix this due to compat concerns (kartstuff is exposed after all) +// we gotta do this shit hack to atleast fix the debugcheckpoint display +static void K_KartUpdatePositionDebugHack(player_t *player, player_t *otherplayer) +{ + mobj_t *mo; + fixed_t pmo; + fixed_t ppcd, pncd; + + // dont need this crap + if (!cv_kartdebugcheckpoint.value) + return; + + // not checking against ourselves + if (player != otherplayer) + return; + + // dont care if its not first displayplayer + // since this is only used for the debug display + if (player != &players[displayplayers[0]]) + return; + + ppcd = pncd = 0; + stprevnextchecks[0] = stprevnextchecks[1] = 0; + + // This checks every thing on the map, and looks for MT_BOSS3WAYPOINT (the thing we're using for checkpoint wp's, for now) + for (mo = waypointcap; mo != NULL; mo = mo->tracer) + { + const boolean isprevcheckpointp = mo->health == player->starpostnum; + const boolean isnextcheckpointp = mo->health == (player->starpostnum + 1); + + if ((isprevcheckpointp || isnextcheckpointp) && (!mo->movecount || mo->movecount == player->laps+1)) + { + pmo = P_AproxDistance(P_AproxDistance( mo->x - player->mo->x, + mo->y - player->mo->y), + mo->z - player->mo->z) / FRACUNIT; + + if (isprevcheckpointp) + { + stprevnextchecks[0] += pmo; + ppcd++; + } + + if (isnextcheckpointp) + { + stprevnextchecks[1] += pmo; + pncd++; + } + } + } + + if (ppcd > 1) stprevnextchecks[0] /= ppcd; + if (pncd > 1) stprevnextchecks[1] /= pncd; +} + // // K_KartUpdatePosition // @@ -6111,6 +6219,9 @@ void K_KartUpdatePosition(player_t *player) fixed_t pmo, imo; mobj_t *mo; + // always reset this + stprevnextchecks[0] = stprevnextchecks[1] = INT32_MAX; + if (player->spectator || !player->mo) return; @@ -6123,11 +6234,12 @@ void K_KartUpdatePosition(player_t *player) if (G_RaceGametype()) { - if ((((players[i].starpostnum) + (numstarposts + 1) * players[i].laps) > - ((player->starpostnum) + (numstarposts + 1) * player->laps))) + const INT32 iplayerlaps = (players[i].starpostnum + (numstarposts + 1) * players[i].laps); + const INT32 pplayerlaps = (player->starpostnum + (numstarposts + 1) * player->laps); + + if (iplayerlaps > pplayerlaps) position++; - else if (((players[i].starpostnum) + (numstarposts+1)*players[i].laps) == - ((player->starpostnum) + (numstarposts+1)*player->laps)) + else if (iplayerlaps == pplayerlaps) { ppcd = pncd = ipcd = incd = 0; @@ -6159,6 +6271,13 @@ void K_KartUpdatePosition(player_t *player) } } + // the player should NOT be checked against themselves! lol + // otherwise prevcheck will effectively be halved + // sadly this stuff is exposed to lua and atleast one script uses those so we cant fix it + // oh well + //if (player == &players[i]) + //continue; + const boolean isprevcheckpointi = mo->health == players[i].starpostnum; const boolean isnextcheckpointi = mo->health == (players[i].starpostnum + 1); @@ -6173,7 +6292,8 @@ void K_KartUpdatePosition(player_t *player) players[i].kartstuff[k_prevcheck] += imo; ipcd++; } - if (isnextcheckpointi ) + + if (isnextcheckpointi) { players[i].kartstuff[k_nextcheck] += imo; incd++; @@ -6202,6 +6322,9 @@ void K_KartUpdatePosition(player_t *player) if (players[i].starposttime < player->starposttime) position++; } + + // stupid hack + K_KartUpdatePositionDebugHack(player, &players[i]); } } else if (G_BattleGametype()) @@ -6237,6 +6360,7 @@ void K_StripItems(player_t *player) { K_DropRocketSneaker(player); K_DropKitchenSink(player); + player->kartstuff[k_itemtype] = KITEM_NONE; player->kartstuff[k_itemamount] = 0; player->kartstuff[k_itemheld] = 0; @@ -6246,6 +6370,7 @@ void K_StripItems(player_t *player) player->kartstuff[k_itemroulette] = 0; player->kartstuff[k_roulettetype] = 0; } + player->kartstuff[k_eggmanheld] = 0; player->kartstuff[k_hyudorotimer] = 0; @@ -6276,18 +6401,582 @@ void K_StripOther(player_t *player) } } +static void K_PlayerItemThink(player_t *player, boolean onground, boolean oldattackdown) +{ + if (!player || !player->mo) + return; + + if (player->mo->health <= 0) + return; + + if (player->spectator) + return; + + if (player->exiting || mapreset) + return; + + if (player->kartstuff[k_spinouttimer] != 0 || + player->kartstuff[k_squishedtimer] != 0 || + player->kartstuff[k_respawn] != 0) + return; + + const ticcmd_t *cmd = &player->cmd; + + const boolean ATTACK_IS_DOWN = ((cmd->buttons & BT_ATTACK) && !oldattackdown); + const boolean HOLDING_ITEM = (player->kartstuff[k_itemheld] || player->kartstuff[k_eggmanheld]); + const boolean NO_HYUDORO = (player->kartstuff[k_stolentimer] == 0 && player->kartstuff[k_stealingtimer] == 0); + + // First, the really specific, finicky items that function without the item being directly in your item slot. + // Karma item dropping + if (ATTACK_IS_DOWN && player->kartstuff[k_comebackmode] && !player->kartstuff[k_comebacktimer]) + { + mobj_t *newitem; + + if (player->kartstuff[k_comebackmode] == 1) + { + newitem = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z, MT_RANDOMITEM); + newitem->threshold = 69; // selected "randomly". + } + else + { + newitem = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z, MT_EGGMANITEM); + + const INT32 blametarg = player->kartstuff[k_eggmanblame]; + + if ((blametarg >= 0 && blametarg < MAXPLAYERS) + && playeringame[blametarg] + && !players[blametarg].spectator + && players[blametarg].mo) + P_SetTarget(&newitem->target, players[blametarg].mo); + + player->kartstuff[k_eggmanblame] = -1; + } + + newitem->flags2 = (player->mo->flags2 & MF2_OBJECTFLIP); + newitem->fuse = 15*TICRATE; // selected randomly. + + player->kartstuff[k_comebackmode] = 0; + player->kartstuff[k_comebacktimer] = comebacktime; + S_StartSound(player->mo, sfx_s254); + } + // Eggman Monitor exploding + else if (player->kartstuff[k_eggmanexplode]) + { + if (ATTACK_IS_DOWN && player->kartstuff[k_eggmanexplode] <= 3*TICRATE && player->kartstuff[k_eggmanexplode] > 1) + player->kartstuff[k_eggmanexplode] = 1; + } + // Eggman Monitor throwing + else if (ATTACK_IS_DOWN && player->kartstuff[k_eggmanheld]) + { + K_ThrowKartItem(player, false, MT_EGGMANITEM, -1, 0); + K_PlayAttackTaunt(player->mo); + player->kartstuff[k_eggmanheld] = 0; + K_UpdateHnextList(player, true); + } + // Rocket Sneaker + else if (ATTACK_IS_DOWN && !HOLDING_ITEM && onground && NO_HYUDORO + && player->kartstuff[k_rocketsneakertimer] > 1) + { + K_DoSneaker(player, 2); + K_PlayBoostTaunt(player->mo); + + player->kartstuff[k_rocketsneakertimer] -= 2*TICRATE; + + if (player->kartstuff[k_rocketsneakertimer] < 1) + player->kartstuff[k_rocketsneakertimer] = 1; + } + // Grow Canceling + else if (player->kartstuff[k_growshrinktimer] > 0) + { + if (player->kartstuff[k_growcancel] >= 0) + { + if (cmd->buttons & BT_ATTACK) + { + player->kartstuff[k_growcancel]++; + + if (player->kartstuff[k_growcancel] > 26) + K_RemoveGrowShrink(player); + } + else + player->kartstuff[k_growcancel] = 0; + } + else + { + if ((cmd->buttons & BT_ATTACK) || (player->pflags & PF_ATTACKDOWN)) + player->kartstuff[k_growcancel] = -1; + else + player->kartstuff[k_growcancel] = 0; + } + } + else if (player->kartstuff[k_itemamount] <= 0) + { + player->kartstuff[k_itemamount] = player->kartstuff[k_itemheld] = 0; + } + else + { + switch (player->kartstuff[k_itemtype]) + { + case KITEM_SNEAKER: + if (ATTACK_IS_DOWN && !HOLDING_ITEM && onground && NO_HYUDORO) + { + K_DoSneaker(player, 1); + K_PlayBoostTaunt(player->mo); + player->kartstuff[k_itemamount]--; + } + break; + case KITEM_ROCKETSNEAKER: + if (ATTACK_IS_DOWN && !HOLDING_ITEM && onground && NO_HYUDORO + && player->kartstuff[k_rocketsneakertimer] == 0) + { + INT32 moloop; + mobj_t *mo = NULL; + mobj_t *prev = player->mo; + + K_PlayBoostTaunt(player->mo); + //player->kartstuff[k_itemheld] = 1; + S_StartSound(player->mo, sfx_s3k3a); + + //K_DoSneaker(player, 2); + + player->kartstuff[k_rocketsneakertimer] = (itemtime*3); + player->kartstuff[k_itemamount]--; + K_UpdateHnextList(player, true); + + for (moloop = 0; moloop < 2; moloop++) + { + mo = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z, MT_ROCKETSNEAKER); + K_MatchGenericExtraFlags(mo, player->mo); + mo->flags |= MF_NOCLIPTHING; + mo->angle = player->mo->angle; + mo->threshold = 10; + mo->movecount = moloop%2; + mo->movedir = mo->lastlook = moloop+1; + P_SetTarget(&mo->target, player->mo); + P_SetTarget(&mo->hprev, prev); + P_SetTarget(&prev->hnext, mo); + prev = mo; + } + } + break; + case KITEM_INVINCIBILITY: + if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO) // Doesn't hold your item slot hostage normally, so you're free to waste it if you have multiple + { + if (!player->kartstuff[k_invincibilitytimer]) + { + mobj_t *overlay = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z, MT_INVULNFLASH); + P_SetTarget(&overlay->target, player->mo); + overlay->destscale = player->mo->scale; + P_SetScale(overlay, player->mo->scale); + } + + player->kartstuff[k_invincibilitytimer] = itemtime+(2*TICRATE); // 10 seconds + + if (cv_supermusic.value == 1 && P_IsLocalPlayer(player)) + S_ChangeMusicSpecial("kinvnc"); + + P_RestoreMusic(player); + K_PlayPowerGloatSound(player->mo); + player->kartstuff[k_itemamount]--; + } + break; + case KITEM_BANANA: + if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO) + { + INT32 moloop; + mobj_t *mo; + mobj_t *prev = player->mo; + + //K_PlayAttackTaunt(player->mo); + player->kartstuff[k_itemheld] = 1; + S_StartSound(player->mo, sfx_s254); + + for (moloop = 0; moloop < player->kartstuff[k_itemamount]; moloop++) + { + mo = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z, MT_BANANA_SHIELD); + + if (P_MobjWasRemovedCompat(mo)) + { + player->kartstuff[k_itemamount] = moloop; + break; + } + + mo->flags |= MF_NOCLIPTHING; + mo->threshold = 10; + mo->movecount = player->kartstuff[k_itemamount]; + mo->movedir = moloop+1; + P_SetTarget(&mo->target, player->mo); + P_SetTarget(&mo->hprev, prev); + P_SetTarget(&prev->hnext, mo); + prev = mo; + } + } + else if (ATTACK_IS_DOWN && player->kartstuff[k_itemheld]) // Banana x3 thrown + { + K_ThrowKartItem(player, false, MT_BANANA, -1, 0); + K_PlayAttackTaunt(player->mo); + player->kartstuff[k_itemamount]--; + K_UpdateHnextList(player, false); + } + break; + case KITEM_EGGMAN: + if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO) + { + mobj_t *mo; + player->kartstuff[k_itemamount]--; + player->kartstuff[k_eggmanheld] = 1; + S_StartSound(player->mo, sfx_s254); + mo = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z, MT_EGGMANITEM_SHIELD); + + if (mo) + { + mo->flags |= MF_NOCLIPTHING; + mo->threshold = 10; + mo->movecount = 1; + mo->movedir = 1; + P_SetTarget(&mo->target, player->mo); + P_SetTarget(&player->mo->hnext, mo); + } + } + break; + case KITEM_ORBINAUT: + if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO) + { + angle_t newangle; + INT32 moloop; + mobj_t *mo = NULL; + mobj_t *prev = player->mo; + + //K_PlayAttackTaunt(player->mo); + player->kartstuff[k_itemheld] = 1; + S_StartSound(player->mo, sfx_s3k3a); + + for (moloop = 0; moloop < player->kartstuff[k_itemamount]; moloop++) + { + newangle = (player->mo->angle + ANGLE_157h) + FixedAngle(((360 / player->kartstuff[k_itemamount]) * moloop) << FRACBITS) + ANGLE_90; + mo = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z, MT_ORBINAUT_SHIELD); + + if (P_MobjWasRemovedCompat(mo)) + { + player->kartstuff[k_itemamount] = moloop; + break; + } + + mo->flags |= MF_NOCLIPTHING; + mo->angle = newangle; + mo->threshold = 10; + mo->movecount = player->kartstuff[k_itemamount]; + mo->movedir = mo->lastlook = moloop+1; + mo->color = player->skincolor; + P_SetTarget(&mo->target, player->mo); + P_SetTarget(&mo->hprev, prev); + P_SetTarget(&prev->hnext, mo); + prev = mo; + } + } + else if (ATTACK_IS_DOWN && player->kartstuff[k_itemheld]) // Orbinaut x3 thrown + { + K_ThrowKartItem(player, true, MT_ORBINAUT, 1, 0); + K_PlayAttackTaunt(player->mo); + player->kartstuff[k_itemamount]--; + K_UpdateHnextList(player, false); + } + break; + case KITEM_JAWZ: + if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO) + { + angle_t newangle; + INT32 moloop; + mobj_t *mo = NULL; + mobj_t *prev = player->mo; + + //K_PlayAttackTaunt(player->mo); + player->kartstuff[k_itemheld] = 1; + S_StartSound(player->mo, sfx_s3k3a); + + for (moloop = 0; moloop < player->kartstuff[k_itemamount]; moloop++) + { + newangle = (player->mo->angle + ANGLE_157h) + FixedAngle(((360 / player->kartstuff[k_itemamount]) * moloop) << FRACBITS) + ANGLE_90; + mo = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z, MT_JAWZ_SHIELD); + + if (P_MobjWasRemovedCompat(mo)) + { + player->kartstuff[k_itemamount] = moloop; + break; + } + + mo->flags |= MF_NOCLIPTHING; + mo->angle = newangle; + mo->threshold = 10; + mo->movecount = player->kartstuff[k_itemamount]; + mo->movedir = mo->lastlook = moloop+1; + P_SetTarget(&mo->target, player->mo); + P_SetTarget(&mo->hprev, prev); + P_SetTarget(&prev->hnext, mo); + prev = mo; + } + } + else if (ATTACK_IS_DOWN && HOLDING_ITEM && player->kartstuff[k_itemheld]) // Jawz thrown + { + if (player->kartstuff[k_throwdir] == 1 || player->kartstuff[k_throwdir] == 0) + K_ThrowKartItem(player, true, MT_JAWZ, 1, 0); + else if (player->kartstuff[k_throwdir] == -1) // Throwing backward gives you a dud that doesn't home in + K_ThrowKartItem(player, true, MT_JAWZ_DUD, -1, 0); + + K_PlayAttackTaunt(player->mo); + player->kartstuff[k_itemamount]--; + K_UpdateHnextList(player, false); + } + break; + case KITEM_MINE: + if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO) + { + mobj_t *mo; + + player->kartstuff[k_itemheld] = 1; + S_StartSound(player->mo, sfx_s254); + mo = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z, MT_SSMINE_SHIELD); + + if (mo) + { + mo->flags |= MF_NOCLIPTHING; + mo->threshold = 10; + mo->movecount = 1; + mo->movedir = 1; + P_SetTarget(&mo->target, player->mo); + P_SetTarget(&player->mo->hnext, mo); + } + } + else if (ATTACK_IS_DOWN && player->kartstuff[k_itemheld]) + { + K_ThrowKartItem(player, false, MT_SSMINE, 1, 1); + K_PlayAttackTaunt(player->mo); + player->kartstuff[k_itemamount]--; + player->kartstuff[k_itemheld] = 0; + K_UpdateHnextList(player, true); + } + break; + case KITEM_BALLHOG: + if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO) + { + player->kartstuff[k_itemamount]--; + K_ThrowKartItem(player, true, MT_BALLHOG, 1, 0); + K_PlayAttackTaunt(player->mo); + } + break; + case KITEM_SPB: + if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO) + { + player->kartstuff[k_itemamount]--; + K_ThrowKartItem(player, true, MT_SPB, 1, 0); + K_PlayAttackTaunt(player->mo); + } + break; + case KITEM_GROW: + if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO + && player->kartstuff[k_growshrinktimer] <= 0) // Grow holds the item box hostage + { + if (player->kartstuff[k_growshrinktimer] < 0) // If you're shrunk, then "grow" will just make you normal again. + K_RemoveGrowShrink(player); + else + { + K_PlayPowerGloatSound(player->mo); + player->mo->scalespeed = mapobjectscale/TICRATE; + player->mo->destscale = (3*mapobjectscale)/2; + + if (cv_kartdebugshrink.value && !modeattacking && !player->bot) + player->mo->destscale = (6*player->mo->destscale)/8; + + player->kartstuff[k_growshrinktimer] = itemtime+(4*TICRATE); // 12 seconds + + if (cv_growmusic.value == 1 && P_IsLocalPlayer(player)) + S_ChangeMusicSpecial("kgrow"); + + P_RestoreMusic(player); + S_StartSound(player->mo, sfx_kc5a); + } + + player->kartstuff[k_itemamount]--; + } + break; + case KITEM_SHRINK: + if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO) + { + K_DoShrink(player); + player->kartstuff[k_itemamount]--; + K_PlayPowerGloatSound(player->mo); + } + break; + case KITEM_THUNDERSHIELD: + if (player->kartstuff[k_curshield] != 1) + { + mobj_t *shield = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z, MT_THUNDERSHIELD); + P_SetScale(shield, (shield->destscale = (5*shield->destscale)>>2)); + P_SetTarget(&shield->target, player->mo); + S_StartSound(shield, sfx_s3k41); + player->kartstuff[k_curshield] = 1; + } + if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO) + { + K_DoThunderShield(player); + player->kartstuff[k_itemamount]--; + K_PlayAttackTaunt(player->mo); + } + break; + case KITEM_HYUDORO: + if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO) + { + player->kartstuff[k_itemamount]--; + K_DoHyudoroSteal(player); // yes. yes they do. + } + break; + case KITEM_POGOSPRING: + if (ATTACK_IS_DOWN && !HOLDING_ITEM && onground && NO_HYUDORO + && !player->kartstuff[k_pogospring]) + { + K_PlayBoostTaunt(player->mo); + K_DoPogoSpring(player->mo, 32<kartstuff[k_pogospring] = 1; + player->kartstuff[k_itemamount]--; + } + break; + case KITEM_KITCHENSINK: + if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO) + { + mobj_t *mo; + + player->kartstuff[k_itemheld] = 1; + S_StartSound(player->mo, sfx_s254); + mo = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z, MT_SINK_SHIELD); + + if (mo) + { + mo->flags |= MF_NOCLIPTHING; + mo->threshold = 10; + mo->movecount = 1; + mo->movedir = 1; + P_SetTarget(&mo->target, player->mo); + P_SetTarget(&player->mo->hnext, mo); + } + } + else if (ATTACK_IS_DOWN && HOLDING_ITEM && player->kartstuff[k_itemheld]) // Sink thrown + { + K_ThrowKartItem(player, false, MT_SINK, 1, 2); + K_PlayAttackTaunt(player->mo); + player->kartstuff[k_itemamount]--; + player->kartstuff[k_itemheld] = 0; + K_UpdateHnextList(player, true); + } + break; + case KITEM_SAD: + if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO + && !player->kartstuff[k_sadtimer]) + { + player->kartstuff[k_sadtimer] = stealtime; + player->kartstuff[k_itemamount]--; + } + break; + default: + break; + } + } + + // No more! + if (!player->kartstuff[k_itemamount]) + { + player->kartstuff[k_itemheld] = 0; + player->kartstuff[k_itemtype] = KITEM_NONE; + } + + if (player->kartstuff[k_itemtype] != KITEM_THUNDERSHIELD) + player->kartstuff[k_curshield] = 0; + + if (player->kartstuff[k_growshrinktimer] <= 0) + player->kartstuff[k_growcancel] = -1; + + if (player->kartstuff[k_itemtype] == KITEM_SPB + || player->kartstuff[k_itemtype] == KITEM_SHRINK + || player->kartstuff[k_growshrinktimer] < 0) + indirectitemcooldown = 20*TICRATE; + + if (player->kartstuff[k_hyudorotimer] > 0) + { + if (splitscreen) + { + if (!cv_reducevfx.value && leveltime & 1) + player->mo->flags2 |= MF2_DONTDRAW; + else + player->mo->flags2 &= ~MF2_DONTDRAW; + + if (player->kartstuff[k_hyudorotimer] >= (1*TICRATE/2) && player->kartstuff[k_hyudorotimer] <= hyudorotime-(1*TICRATE/2)) + { + if (player == &players[displayplayers[1]]) + player->mo->eflags |= MFE_DRAWONLYFORP2; + else if (player == &players[displayplayers[2]] && splitscreen > 1) + player->mo->eflags |= MFE_DRAWONLYFORP3; + else if (player == &players[displayplayers[3]] && splitscreen > 2) + player->mo->eflags |= MFE_DRAWONLYFORP4; + else if (player == &players[displayplayers[0]]) + player->mo->eflags |= MFE_DRAWONLYFORP1; + else + player->mo->flags2 |= MF2_DONTDRAW; + } + else + player->mo->eflags &= ~(MFE_DRAWONLYFORP1|MFE_DRAWONLYFORP2|MFE_DRAWONLYFORP3|MFE_DRAWONLYFORP4); + } + else + { + if (P_IsDisplayPlayer(player) || + (player->kartstuff[k_hyudorotimer] < (1*TICRATE/2) || player->kartstuff[k_hyudorotimer] > hyudorotime-(1*TICRATE/2))) + { + if (!cv_reducevfx.value && leveltime & 1) + player->mo->flags2 |= MF2_DONTDRAW; + else + player->mo->flags2 &= ~MF2_DONTDRAW; + } + else + player->mo->flags2 |= MF2_DONTDRAW; + } + + player->powers[pw_flashing] = player->kartstuff[k_hyudorotimer]; // We'll do this for now, let's people know about the invisible people through subtle hints + } + else if (player->kartstuff[k_hyudorotimer] == 0) + { + player->mo->flags2 &= ~MF2_DONTDRAW; + player->mo->eflags &= ~(MFE_DRAWONLYFORP1|MFE_DRAWONLYFORP2|MFE_DRAWONLYFORP3|MFE_DRAWONLYFORP4); + } + + if (G_BattleGametype() && player->kartstuff[k_bumper] <= 0) // dead in match? you da bomb + { + K_DropItems(player); //K_StripItems(player); + K_StripOther(player); + player->mo->flags2 |= MF2_SHADOW; + player->powers[pw_flashing] = player->kartstuff[k_comebacktimer]; + } + else if (G_RaceGametype() || player->kartstuff[k_bumper] > 0) + { + player->mo->flags2 &= ~MF2_SHADOW; + } +} + // // K_MoveKartPlayer // void K_MoveKartPlayer(player_t *player, boolean onground) { ticcmd_t *cmd = &player->cmd; - boolean ATTACK_IS_DOWN = ((cmd->buttons & BT_ATTACK) && !(player->pflags & PF_ATTACKDOWN)); - boolean HOLDING_ITEM = (player->kartstuff[k_itemheld] || player->kartstuff[k_eggmanheld]); - boolean NO_HYUDORO = (player->kartstuff[k_stolentimer] == 0 && player->kartstuff[k_stealingtimer] == 0); + + const boolean oldattackdown = (player->pflags & PF_ATTACKDOWN); // fun + + if ((player->pflags & PF_ATTACKDOWN) && !(cmd->buttons & BT_ATTACK)) + player->pflags &= ~PF_ATTACKDOWN; + else if (cmd->buttons & BT_ATTACK) + player->pflags |= PF_ATTACKDOWN; K_KartUpdatePosition(player); + // Play overtake sounds, but only if + // - your place changed + // - not exiting if (!player->exiting) { if (player->kartstuff[k_oldposition] < player->kartstuff[k_position]) // But first, if you lost a place, @@ -6305,521 +6994,7 @@ void K_MoveKartPlayer(player_t *player, boolean onground) if (player->kartstuff[k_positiondelay]) player->kartstuff[k_positiondelay]--; - if ((player->pflags & PF_ATTACKDOWN) && !(cmd->buttons & BT_ATTACK)) - player->pflags &= ~PF_ATTACKDOWN; - else if (cmd->buttons & BT_ATTACK) - player->pflags |= PF_ATTACKDOWN; - - if (player && player->mo && player->mo->health > 0 && !player->spectator && !(player->exiting || mapreset) - && player->kartstuff[k_spinouttimer] == 0 && player->kartstuff[k_squishedtimer] == 0 && player->kartstuff[k_respawn] == 0) - { - // First, the really specific, finicky items that function without the item being directly in your item slot. - // Karma item dropping - if (ATTACK_IS_DOWN && player->kartstuff[k_comebackmode] && !player->kartstuff[k_comebacktimer]) - { - mobj_t *newitem; - - if (player->kartstuff[k_comebackmode] == 1) - { - newitem = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z, MT_RANDOMITEM); - newitem->threshold = 69; // selected "randomly". - } - else - { - newitem = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z, MT_EGGMANITEM); - if (player->kartstuff[k_eggmanblame] >= 0 - && player->kartstuff[k_eggmanblame] < MAXPLAYERS - && playeringame[player->kartstuff[k_eggmanblame]] - && !players[player->kartstuff[k_eggmanblame]].spectator - && players[player->kartstuff[k_eggmanblame]].mo) - P_SetTarget(&newitem->target, players[player->kartstuff[k_eggmanblame]].mo); - player->kartstuff[k_eggmanblame] = -1; - } - - newitem->flags2 = (player->mo->flags2 & MF2_OBJECTFLIP); - newitem->fuse = 15*TICRATE; // selected randomly. - - player->kartstuff[k_comebackmode] = 0; - player->kartstuff[k_comebacktimer] = comebacktime; - S_StartSound(player->mo, sfx_s254); - } - // Eggman Monitor exploding - else if (player->kartstuff[k_eggmanexplode]) - { - if (ATTACK_IS_DOWN && player->kartstuff[k_eggmanexplode] <= 3*TICRATE && player->kartstuff[k_eggmanexplode] > 1) - player->kartstuff[k_eggmanexplode] = 1; - } - // Eggman Monitor throwing - else if (ATTACK_IS_DOWN && player->kartstuff[k_eggmanheld]) - { - K_ThrowKartItem(player, false, MT_EGGMANITEM, -1, 0); - K_PlayAttackTaunt(player->mo); - player->kartstuff[k_eggmanheld] = 0; - K_UpdateHnextList(player, true); - } - // Rocket Sneaker - else if (ATTACK_IS_DOWN && !HOLDING_ITEM && onground && NO_HYUDORO - && player->kartstuff[k_rocketsneakertimer] > 1) - { - K_DoSneaker(player, 2); - K_PlayBoostTaunt(player->mo); - player->kartstuff[k_rocketsneakertimer] -= 2*TICRATE; - if (player->kartstuff[k_rocketsneakertimer] < 1) - player->kartstuff[k_rocketsneakertimer] = 1; - } - // Grow Canceling - else if (player->kartstuff[k_growshrinktimer] > 0) - { - if (player->kartstuff[k_growcancel] >= 0) - { - if (cmd->buttons & BT_ATTACK) - { - player->kartstuff[k_growcancel]++; - if (player->kartstuff[k_growcancel] > 26) - K_RemoveGrowShrink(player); - } - else - player->kartstuff[k_growcancel] = 0; - } - else - { - if ((cmd->buttons & BT_ATTACK) || (player->pflags & PF_ATTACKDOWN)) - player->kartstuff[k_growcancel] = -1; - else - player->kartstuff[k_growcancel] = 0; - } - } - else if (player->kartstuff[k_itemamount] <= 0) - { - player->kartstuff[k_itemamount] = player->kartstuff[k_itemheld] = 0; - } - else - { - switch (player->kartstuff[k_itemtype]) - { - case KITEM_SNEAKER: - if (ATTACK_IS_DOWN && !HOLDING_ITEM && onground && NO_HYUDORO) - { - K_DoSneaker(player, 1); - K_PlayBoostTaunt(player->mo); - player->kartstuff[k_itemamount]--; - } - break; - case KITEM_ROCKETSNEAKER: - if (ATTACK_IS_DOWN && !HOLDING_ITEM && onground && NO_HYUDORO - && player->kartstuff[k_rocketsneakertimer] == 0) - { - INT32 moloop; - mobj_t *mo = NULL; - mobj_t *prev = player->mo; - - K_PlayBoostTaunt(player->mo); - //player->kartstuff[k_itemheld] = 1; - S_StartSound(player->mo, sfx_s3k3a); - - //K_DoSneaker(player, 2); - - player->kartstuff[k_rocketsneakertimer] = (itemtime*3); - player->kartstuff[k_itemamount]--; - K_UpdateHnextList(player, true); - - for (moloop = 0; moloop < 2; moloop++) - { - mo = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z, MT_ROCKETSNEAKER); - K_MatchGenericExtraFlags(mo, player->mo); - mo->flags |= MF_NOCLIPTHING; - mo->angle = player->mo->angle; - mo->threshold = 10; - mo->movecount = moloop%2; - mo->movedir = mo->lastlook = moloop+1; - P_SetTarget(&mo->target, player->mo); - P_SetTarget(&mo->hprev, prev); - P_SetTarget(&prev->hnext, mo); - prev = mo; - } - } - break; - case KITEM_INVINCIBILITY: - if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO) // Doesn't hold your item slot hostage normally, so you're free to waste it if you have multiple - { - if (!player->kartstuff[k_invincibilitytimer]) - { - mobj_t *overlay = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z, MT_INVULNFLASH); - P_SetTarget(&overlay->target, player->mo); - overlay->destscale = player->mo->scale; - P_SetScale(overlay, player->mo->scale); - } - player->kartstuff[k_invincibilitytimer] = itemtime+(2*TICRATE); // 10 seconds - - if (cv_supermusic.value == 1 && P_IsLocalPlayer(player)) - S_ChangeMusicSpecial("kinvnc"); - - P_RestoreMusic(player); - K_PlayPowerGloatSound(player->mo); - player->kartstuff[k_itemamount]--; - } - break; - case KITEM_BANANA: - if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO) - { - INT32 moloop; - mobj_t *mo; - mobj_t *prev = player->mo; - - //K_PlayAttackTaunt(player->mo); - player->kartstuff[k_itemheld] = 1; - S_StartSound(player->mo, sfx_s254); - - for (moloop = 0; moloop < player->kartstuff[k_itemamount]; moloop++) - { - mo = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z, MT_BANANA_SHIELD); - if (!mo) - { - player->kartstuff[k_itemamount] = moloop; - break; - } - mo->flags |= MF_NOCLIPTHING; - mo->threshold = 10; - mo->movecount = player->kartstuff[k_itemamount]; - mo->movedir = moloop+1; - P_SetTarget(&mo->target, player->mo); - P_SetTarget(&mo->hprev, prev); - P_SetTarget(&prev->hnext, mo); - prev = mo; - } - } - else if (ATTACK_IS_DOWN && player->kartstuff[k_itemheld]) // Banana x3 thrown - { - K_ThrowKartItem(player, false, MT_BANANA, -1, 0); - K_PlayAttackTaunt(player->mo); - player->kartstuff[k_itemamount]--; - K_UpdateHnextList(player, false); - } - break; - case KITEM_EGGMAN: - if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO) - { - mobj_t *mo; - player->kartstuff[k_itemamount]--; - player->kartstuff[k_eggmanheld] = 1; - S_StartSound(player->mo, sfx_s254); - mo = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z, MT_EGGMANITEM_SHIELD); - if (mo) - { - mo->flags |= MF_NOCLIPTHING; - mo->threshold = 10; - mo->movecount = 1; - mo->movedir = 1; - P_SetTarget(&mo->target, player->mo); - P_SetTarget(&player->mo->hnext, mo); - } - } - break; - case KITEM_ORBINAUT: - if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO) - { - angle_t newangle; - INT32 moloop; - mobj_t *mo = NULL; - mobj_t *prev = player->mo; - - //K_PlayAttackTaunt(player->mo); - player->kartstuff[k_itemheld] = 1; - S_StartSound(player->mo, sfx_s3k3a); - - for (moloop = 0; moloop < player->kartstuff[k_itemamount]; moloop++) - { - newangle = (player->mo->angle + ANGLE_157h) + FixedAngle(((360 / player->kartstuff[k_itemamount]) * moloop) << FRACBITS) + ANGLE_90; - mo = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z, MT_ORBINAUT_SHIELD); - if (!mo) - { - player->kartstuff[k_itemamount] = moloop; - break; - } - mo->flags |= MF_NOCLIPTHING; - mo->angle = newangle; - mo->threshold = 10; - mo->movecount = player->kartstuff[k_itemamount]; - mo->movedir = mo->lastlook = moloop+1; - mo->color = player->skincolor; - P_SetTarget(&mo->target, player->mo); - P_SetTarget(&mo->hprev, prev); - P_SetTarget(&prev->hnext, mo); - prev = mo; - } - } - else if (ATTACK_IS_DOWN && player->kartstuff[k_itemheld]) // Orbinaut x3 thrown - { - K_ThrowKartItem(player, true, MT_ORBINAUT, 1, 0); - K_PlayAttackTaunt(player->mo); - player->kartstuff[k_itemamount]--; - K_UpdateHnextList(player, false); - } - break; - case KITEM_JAWZ: - if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO) - { - angle_t newangle; - INT32 moloop; - mobj_t *mo = NULL; - mobj_t *prev = player->mo; - - //K_PlayAttackTaunt(player->mo); - player->kartstuff[k_itemheld] = 1; - S_StartSound(player->mo, sfx_s3k3a); - - for (moloop = 0; moloop < player->kartstuff[k_itemamount]; moloop++) - { - newangle = (player->mo->angle + ANGLE_157h) + FixedAngle(((360 / player->kartstuff[k_itemamount]) * moloop) << FRACBITS) + ANGLE_90; - mo = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z, MT_JAWZ_SHIELD); - if (!mo) - { - player->kartstuff[k_itemamount] = moloop; - break; - } - mo->flags |= MF_NOCLIPTHING; - mo->angle = newangle; - mo->threshold = 10; - mo->movecount = player->kartstuff[k_itemamount]; - mo->movedir = mo->lastlook = moloop+1; - P_SetTarget(&mo->target, player->mo); - P_SetTarget(&mo->hprev, prev); - P_SetTarget(&prev->hnext, mo); - prev = mo; - } - } - else if (ATTACK_IS_DOWN && HOLDING_ITEM && player->kartstuff[k_itemheld]) // Jawz thrown - { - if (player->kartstuff[k_throwdir] == 1 || player->kartstuff[k_throwdir] == 0) - K_ThrowKartItem(player, true, MT_JAWZ, 1, 0); - else if (player->kartstuff[k_throwdir] == -1) // Throwing backward gives you a dud that doesn't home in - K_ThrowKartItem(player, true, MT_JAWZ_DUD, -1, 0); - K_PlayAttackTaunt(player->mo); - player->kartstuff[k_itemamount]--; - K_UpdateHnextList(player, false); - } - break; - case KITEM_MINE: - if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO) - { - mobj_t *mo; - player->kartstuff[k_itemheld] = 1; - S_StartSound(player->mo, sfx_s254); - mo = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z, MT_SSMINE_SHIELD); - if (mo) - { - mo->flags |= MF_NOCLIPTHING; - mo->threshold = 10; - mo->movecount = 1; - mo->movedir = 1; - P_SetTarget(&mo->target, player->mo); - P_SetTarget(&player->mo->hnext, mo); - } - } - else if (ATTACK_IS_DOWN && player->kartstuff[k_itemheld]) - { - K_ThrowKartItem(player, false, MT_SSMINE, 1, 1); - K_PlayAttackTaunt(player->mo); - player->kartstuff[k_itemamount]--; - player->kartstuff[k_itemheld] = 0; - K_UpdateHnextList(player, true); - } - break; - case KITEM_BALLHOG: - if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO) - { - player->kartstuff[k_itemamount]--; - K_ThrowKartItem(player, true, MT_BALLHOG, 1, 0); - K_PlayAttackTaunt(player->mo); - } - break; - case KITEM_SPB: - if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO) - { - player->kartstuff[k_itemamount]--; - K_ThrowKartItem(player, true, MT_SPB, 1, 0); - K_PlayAttackTaunt(player->mo); - } - break; - case KITEM_GROW: - if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO - && player->kartstuff[k_growshrinktimer] <= 0) // Grow holds the item box hostage - { - if (player->kartstuff[k_growshrinktimer] < 0) // If you're shrunk, then "grow" will just make you normal again. - K_RemoveGrowShrink(player); - else - { - K_PlayPowerGloatSound(player->mo); - player->mo->scalespeed = mapobjectscale/TICRATE; - player->mo->destscale = (3*mapobjectscale)/2; - if (cv_kartdebugshrink.value && !modeattacking && !player->bot) - player->mo->destscale = (6*player->mo->destscale)/8; - player->kartstuff[k_growshrinktimer] = itemtime+(4*TICRATE); // 12 seconds - if (cv_growmusic.value == 1 && P_IsLocalPlayer(player)) - S_ChangeMusicSpecial("kgrow"); - P_RestoreMusic(player); - S_StartSound(player->mo, sfx_kc5a); - } - player->kartstuff[k_itemamount]--; - } - break; - case KITEM_SHRINK: - if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO) - { - K_DoShrink(player); - player->kartstuff[k_itemamount]--; - K_PlayPowerGloatSound(player->mo); - } - break; - case KITEM_THUNDERSHIELD: - if (player->kartstuff[k_curshield] != 1) - { - mobj_t *shield = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z, MT_THUNDERSHIELD); - P_SetScale(shield, (shield->destscale = (5*shield->destscale)>>2)); - P_SetTarget(&shield->target, player->mo); - S_StartSound(shield, sfx_s3k41); - player->kartstuff[k_curshield] = 1; - } - if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO) - { - K_DoThunderShield(player); - player->kartstuff[k_itemamount]--; - K_PlayAttackTaunt(player->mo); - } - break; - case KITEM_HYUDORO: - if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO) - { - player->kartstuff[k_itemamount]--; - K_DoHyudoroSteal(player); // yes. yes they do. - } - break; - case KITEM_POGOSPRING: - if (ATTACK_IS_DOWN && !HOLDING_ITEM && onground && NO_HYUDORO - && !player->kartstuff[k_pogospring]) - { - K_PlayBoostTaunt(player->mo); - K_DoPogoSpring(player->mo, 32<kartstuff[k_pogospring] = 1; - player->kartstuff[k_itemamount]--; - } - break; - case KITEM_KITCHENSINK: - if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO) - { - mobj_t *mo; - player->kartstuff[k_itemheld] = 1; - S_StartSound(player->mo, sfx_s254); - mo = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z, MT_SINK_SHIELD); - if (mo) - { - mo->flags |= MF_NOCLIPTHING; - mo->threshold = 10; - mo->movecount = 1; - mo->movedir = 1; - P_SetTarget(&mo->target, player->mo); - P_SetTarget(&player->mo->hnext, mo); - } - } - else if (ATTACK_IS_DOWN && HOLDING_ITEM && player->kartstuff[k_itemheld]) // Sink thrown - { - K_ThrowKartItem(player, false, MT_SINK, 1, 2); - K_PlayAttackTaunt(player->mo); - player->kartstuff[k_itemamount]--; - player->kartstuff[k_itemheld] = 0; - K_UpdateHnextList(player, true); - } - break; - case KITEM_SAD: - if (ATTACK_IS_DOWN && !HOLDING_ITEM && NO_HYUDORO - && !player->kartstuff[k_sadtimer]) - { - player->kartstuff[k_sadtimer] = stealtime; - player->kartstuff[k_itemamount]--; - } - break; - default: - break; - } - } - - // No more! - if (!player->kartstuff[k_itemamount]) - { - player->kartstuff[k_itemheld] = 0; - player->kartstuff[k_itemtype] = KITEM_NONE; - } - - if (player->kartstuff[k_itemtype] != KITEM_THUNDERSHIELD) - player->kartstuff[k_curshield] = 0; - - if (player->kartstuff[k_growshrinktimer] <= 0) - player->kartstuff[k_growcancel] = -1; - - if (player->kartstuff[k_itemtype] == KITEM_SPB - || player->kartstuff[k_itemtype] == KITEM_SHRINK - || player->kartstuff[k_growshrinktimer] < 0) - indirectitemcooldown = 20*TICRATE; - - if (player->kartstuff[k_hyudorotimer] > 0) - { - if (splitscreen) - { - if (leveltime & 1) - player->mo->flags2 |= MF2_DONTDRAW; - else - player->mo->flags2 &= ~MF2_DONTDRAW; - - if (player->kartstuff[k_hyudorotimer] >= (1*TICRATE/2) && player->kartstuff[k_hyudorotimer] <= hyudorotime-(1*TICRATE/2)) - { - if (player == &players[displayplayers[1]]) - player->mo->eflags |= MFE_DRAWONLYFORP2; - else if (player == &players[displayplayers[2]] && splitscreen > 1) - player->mo->eflags |= MFE_DRAWONLYFORP3; - else if (player == &players[displayplayers[3]] && splitscreen > 2) - player->mo->eflags |= MFE_DRAWONLYFORP4; - else if (player == &players[displayplayers[0]]) - player->mo->eflags |= MFE_DRAWONLYFORP1; - else - player->mo->flags2 |= MF2_DONTDRAW; - } - else - player->mo->eflags &= ~(MFE_DRAWONLYFORP1|MFE_DRAWONLYFORP2|MFE_DRAWONLYFORP3|MFE_DRAWONLYFORP4); - } - else - { - if (P_IsDisplayPlayer(player) - || (!P_IsDisplayPlayer(player) && (player->kartstuff[k_hyudorotimer] < (1*TICRATE/2) || player->kartstuff[k_hyudorotimer] > hyudorotime-(1*TICRATE/2)))) - { - if (leveltime & 1) - player->mo->flags2 |= MF2_DONTDRAW; - else - player->mo->flags2 &= ~MF2_DONTDRAW; - } - else - player->mo->flags2 |= MF2_DONTDRAW; - } - - player->powers[pw_flashing] = player->kartstuff[k_hyudorotimer]; // We'll do this for now, let's people know about the invisible people through subtle hints - } - else if (player->kartstuff[k_hyudorotimer] == 0) - { - player->mo->flags2 &= ~MF2_DONTDRAW; - player->mo->eflags &= ~(MFE_DRAWONLYFORP1|MFE_DRAWONLYFORP2|MFE_DRAWONLYFORP3|MFE_DRAWONLYFORP4); - } - - if (G_BattleGametype() && player->kartstuff[k_bumper] <= 0) // dead in match? you da bomb - { - K_DropItems(player); //K_StripItems(player); - K_StripOther(player); - player->mo->flags2 |= MF2_SHADOW; - player->powers[pw_flashing] = player->kartstuff[k_comebacktimer]; - } - else if (G_RaceGametype() || player->kartstuff[k_bumper] > 0) - { - player->mo->flags2 &= ~MF2_SHADOW; - } - } + K_PlayerItemThink(player, onground, oldattackdown); // JugadorXEI: Do *not* calculate friction when a player is pogo'd // because they'll be in the air and friction will not reset! @@ -6868,12 +7043,14 @@ void K_MoveKartPlayer(player_t *player, boolean onground) K_KartDrift(player, onground); - if (player->sliproll && ((!player->kartstuff[k_aizdriftstrat]) || (!P_IsObjectOnGround(player->mo)) || (player->kartstuff[k_drift]))) + //// funneh Saturn sprite stuff + + if ((player->sliproll > 0) && + (!player->kartstuff[k_aizdriftstrat] || player->kartstuff[k_drift] || !P_IsObjectOnGround(player->mo))) { player->sliproll -= (4*ANG1); } - // funneh Saturn sprite stuff if (cv_gravstretch.value) K_StretchPlayerGravity(player); else if (cv_saltyhop.value && cv_saltysquish.value) @@ -6881,6 +7058,36 @@ void K_MoveKartPlayer(player_t *player, boolean onground) K_RollMobjBySlopes(player->mo, player->mo->standingslope); + // "Stair jank" visuals akin to RR + if (cv_stairjank.value && player->stairjank > 0) + { + // only spawn em once + if (player->stairjank > 8) + { + // 90 degrees to direction you're facing + fixed_t dirx = -FINESINE(player->mo->angle>>ANGLETOFINESHIFT); + fixed_t diry = FINECOSINE(player->mo->angle>>ANGLETOFINESHIFT); + fixed_t offset = player->mo->radius; + + dirx = K_AltFlip(-dirx, 4); + diry = K_AltFlip(-diry, 4); + + mobj_t * spark = P_SpawnMobj(player->mo->x + FixedMul(dirx, offset), player->mo->y + FixedMul(diry, offset), player->mo->z, MT_DRIFTDUST); + spark->momx = FixedMul(dirx, FRACUNIT) + (6 + ((int)leveltime % 5))*(player->mo->momx)/10; + spark->momy = FixedMul(diry, FRACUNIT) + (6 + ((int)leveltime % 5))*(player->mo->momy)/10; + spark->momz = 5*FRACUNIT; + spark->scale = mapobjectscale/5; + spark->destscale = mapobjectscale/2; + spark->islocal = true; + spark->color = SKINCOLOR_WHITE; + P_SetTarget(&spark->target, player->mo); + } + + player->mo->temprollangle += K_StairJankFlip(ANGLE_11hh / 2 / (17 / player->stairjank)); // TODO: make strength adjustable? + } + + //// + // Quick Turning // You can't turn your kart when you're not moving. // So now it's time to burn some rubber! @@ -6932,6 +7139,7 @@ void K_MoveKartPlayer(player_t *player, boolean onground) { player->mo->scalespeed = mapobjectscale/12; player->mo->destscale = mapobjectscale + (FixedMul(mapobjectscale, player->kartstuff[k_boostcharge]*131)); + if (cv_kartdebugshrink.value && !modeattacking && !player->bot) player->mo->destscale = (6*player->mo->destscale)/8; } @@ -6962,6 +7170,7 @@ void K_MoveKartPlayer(player_t *player, boolean onground) else { K_SpawnDashDustRelease(player); // already handled for perfect boosts by K_DoSneaker + if ((!player->kartstuff[k_floorboost] || player->kartstuff[k_floorboost] == 3) && P_IsLocalPlayer(player)) { if (player->kartstuff[k_boostcharge] <= 40) @@ -7252,6 +7461,7 @@ void K_CheckSpectateStatus(void) { UINT8 oldrespawnlist[MAXPLAYERS]; memcpy(oldrespawnlist, respawnlist, numjoiners); + for (i = 0; i < numjoiners; i++) { UINT8 pos = 0; diff --git a/src/k_kart.h b/src/k_kart.h index ab0d8bd14..4d81375cd 100644 --- a/src/k_kart.h +++ b/src/k_kart.h @@ -32,6 +32,8 @@ extern consvar_t cv_bananajitter; extern consvar_t cv_bananthrowroll; extern consvar_t cv_airsparks; +extern INT32 stprevnextchecks[2]; + boolean K_IsPlayerLosing(player_t *player); boolean K_IsPlayerWanted(player_t *player); INT32 K_KartGetItemOdds(UINT8 pos, SINT8 item, fixed_t mashed, boolean spbrush); @@ -57,7 +59,7 @@ boolean K_ShouldSlopeRoll(mobj_t *mobj); void K_RollMobjBySlopes(mobj_t *mo, pslope_t *slope); void K_SpawnBoostTrail(player_t *player); void K_SpawnSparkleTrail(mobj_t *mo); -void K_SpawnWipeoutTrail(mobj_t *mo, boolean translucent); +mobj_t *K_SpawnWipeoutTrail(mobj_t *mo, boolean translucent); void K_DriftDustHandling(mobj_t *spawner); void K_PuntMine(mobj_t *mine, mobj_t *punter); void K_DoSneaker(player_t *player, INT32 type); diff --git a/src/k_stats.c b/src/k_stats.c index f4fac90d3..5675462fd 100644 --- a/src/k_stats.c +++ b/src/k_stats.c @@ -99,8 +99,7 @@ void K_EraseStats(void) // The only field we want to remember boolean vanilla = kartstats.vanilla; - if (kartstats.copy) - Z_Free(kartstats.copy); + Z_Free(kartstats.copy); memset(&kartstats, 0, sizeof(kartstats_t)); diff --git a/src/lua_baselib.c b/src/lua_baselib.c index 0da8abfae..9703cbafe 100644 --- a/src/lua_baselib.c +++ b/src/lua_baselib.c @@ -1293,6 +1293,7 @@ static int lib_pPlayRinglossSound(lua_State *L) player_t *player = NULL; mobj_t *damager = NULL; NOHUD + LUA_UsageWarning(L, "P_PlayRinglossSound: using this function from lua might cause desynchs, consider using S_StartSound(origin, sfx_khurt1 + P_RandomKey(2)) as workaround"); if (!source) return LUA_ErrInvalid(L, "mobj_t"); if (!lua_isnone(L, 2) && lua_isuserdata(L, 2)) @@ -3054,58 +3055,46 @@ static int lib_kSetHyuCountdown(lua_State *L) static int lib_gSetPlayerGamepadIndicatorColor(lua_State *L) { - INT32 player = -1; - player_t *plr = *((player_t **)luaL_checkudata(L, 1, META_PLAYER)); // retrieve player + INT32 pnum = -1; + player_t *player = *((player_t **)luaL_checkudata(L, 1, META_PLAYER)); // retrieve player UINT8 color = (UINT8)luaL_checkinteger(L, 2); // skincolor - if (!plr) + if (!player) return LUA_ErrInvalid(L, "player_t"); if (color >= MAXTRANSLATIONS) return luaL_error(L, "color %d out of range (0 - %d).", color, MAXTRANSLATIONS-1); - for (int i = 0; i < MAXSPLITSCREENPLAYERS; ++i) - { - if (plr - players == displayplayers[i]) - { - player = i; - break; - } - } + pnum = P_GetLocalPlayerNumForPlayer(player); // Not a local player - if (player == -1) return 0; + if (pnum == -1) return 0; // pls update with color 0 when youre done with changing led stuff so it can get player color again - G_SetPlayerGamepadIndicatorColor(player, color); + G_SetPlayerGamepadIndicatorColor(pnum, color); return 0; } static int lib_gPlayerDeviceRumble(lua_State *L) { - INT32 player = -1; - player_t *plr = *((player_t **)luaL_checkudata(L, 1, META_PLAYER)); // retrieve player + INT32 pnum = -1; + player_t *player = *((player_t **)luaL_checkudata(L, 1, META_PLAYER)); // retrieve player UINT16 low_strength = (UINT16)luaL_checkinteger(L, 2); // low frequency rumble motor strenght UINT16 high_strength = (UINT16)luaL_checkinteger(L, 3); // high frequency rumble motor strenght UINT32 duration = (UINT32)luaL_optinteger(L, 4, 84); // duration of rumble in ms - if (!plr) + if (!player) return LUA_ErrInvalid(L, "player_t"); - for (int i = 0; i < MAXSPLITSCREENPLAYERS; ++i) - { - if (plr - players == displayplayers[i]) - { - player = i; - break; - } - } + if (demo.playback) return 0; + + pnum = P_GetLocalPlayerNumForPlayer(player); // Not a local player - if (player == -1) return 0; + if (pnum == -1) return 0; - G_PlayerDeviceRumble(player, low_strength, high_strength, duration); + G_PlayerDeviceRumble(pnum, low_strength, high_strength, duration); return 0; } diff --git a/src/lua_consolelib.c b/src/lua_consolelib.c index f9d36e2cf..0f6b74f88 100644 --- a/src/lua_consolelib.c +++ b/src/lua_consolelib.c @@ -358,7 +358,8 @@ static int lib_cvRegisterVar(lua_State *L) #define TYPEERROR(f, t) FIELDERROR(f, va("%s expected, got %s", lua_typename(L, t), luaL_typename(L, -1))) lua_pushnil(L); - while (lua_next(L, 1)) { + while (lua_next(L, 1)) + { // stack: cvar table, cvar userdata, key/index, value // 1 2 3 4 i = 0; @@ -368,26 +369,40 @@ static int lib_cvRegisterVar(lua_State *L) else if (lua_isstring(L, 3)) k = lua_tostring(L, 3); - if (i == 1 || (k && fasticmp(k, "name"))) { + if (i == 1 || (k && fasticmp(k, "name"))) + { if (!lua_isstring(L, 4)) TYPEERROR("name", LUA_TSTRING) + cvar->name = Z_StrDup(lua_tostring(L, 4)); - } else if (i == 2 || (k && fasticmp(k, "defaultvalue"))) { + } + else if (i == 2 || (k && fasticmp(k, "defaultvalue"))) + { if (!lua_isstring(L, 4)) TYPEERROR("defaultvalue", LUA_TSTRING) + cvar->defaultvalue = Z_StrDup(lua_tostring(L, 4)); - } else if (i == 3 || (k && fasticmp(k, "flags"))) { + } + else if (i == 3 || (k && fasticmp(k, "flags"))) + { if (!lua_isnumber(L, 4)) TYPEERROR("flags", LUA_TNUMBER) + cvar->flags = (INT32)lua_tointeger(L, 4); - } else if (i == 4 || (k && fasticmp(k, "PossibleValue"))) { - if (lua_islightuserdata(L, 4)) { + } + else if (i == 4 || (k && fasticmp(k, "PossibleValue"))) + { + if (lua_islightuserdata(L, 4)) + { CV_PossibleValue_t *pv = lua_touserdata(L, 4); + if (pv == CV_OnOff || pv == CV_YesNo || pv == CV_Unsigned || pv == CV_Natural) cvar->PossibleValue = pv; else FIELDERROR("PossibleValue", "CV_PossibleValue_t expected, got unrecognised pointer") - } else if (lua_istable(L, 4)) { + } + else if (lua_istable(L, 4)) + { // Accepts tables in the form of {MIN=0, MAX=9999} or {Red=0, Green=1, Blue=2} // and converts them to CV_PossibleValue_t {{0,"MIN"},{9999,"MAX"}} or {{0,"Red"},{1,"Green"},{2,"Blue"}} // @@ -398,7 +413,9 @@ static int lib_cvRegisterVar(lua_State *L) CV_PossibleValue_t *cvpv; lua_pushnil(L); - while (lua_next(L, 4)) { + + while (lua_next(L, 4)) + { count++; lua_pop(L, 1); } @@ -412,7 +429,9 @@ static int lib_cvRegisterVar(lua_State *L) i = 0; lua_pushnil(L); - while (lua_next(L, 4)) { + + while (lua_next(L, 4)) + { // stack: [...] PossibleValue table, index, value // 4 5 6 if (lua_type(L, 5) != LUA_TSTRING @@ -423,14 +442,19 @@ static int lib_cvRegisterVar(lua_State *L) i++; lua_pop(L, 1); } + cvpv[i].value = 0; cvpv[i].strvalue = NULL; cvar->PossibleValue = cvpv; - } else + } + else FIELDERROR("PossibleValue", va("%s or CV_PossibleValue_t expected, got %s", lua_typename(L, LUA_TTABLE), luaL_typename(L, -1))) - } else if (i == 5 || (k && fasticmp(k, "func"))) { + } + else if (i == 5 || (k && fasticmp(k, "func"))) + { if (!lua_isfunction(L, 4)) TYPEERROR("func", LUA_TFUNCTION) + lua_getfield(L, LUA_REGISTRYINDEX, "CV_OnChange"); I_Assert(lua_istable(L, 5)); lua_pushlightuserdata(L, cvar); @@ -438,9 +462,13 @@ static int lib_cvRegisterVar(lua_State *L) lua_rawset(L, 5); lua_pop(L, 1); cvar->func = Lua_OnChange; + + if (i == 5 && !(cvar->flags & CV_CALL)) + { + category = lua_isnoneornil(L, 4) ? NULL : lua_tostring(L, 4); + } } - else if (((i == 5 && !(cvar->flags & CV_CALL)) - || (cvar->flags & CV_CALL && i == 6)) + else if ((cvar->flags & CV_CALL && i == 6) || (k && fasticmp(k, "category"))) { category = lua_isnoneornil(L, 4) ? NULL : lua_tostring(L, 4); @@ -451,6 +479,7 @@ static int lib_cvRegisterVar(lua_State *L) { menu_name = lua_isnoneornil(L, 4) ? NULL : lua_tostring(L, 4); } + lua_pop(L, 1); } #undef FIELDERROR diff --git a/src/lua_hooklib.c b/src/lua_hooklib.c index e571f7649..d8778263c 100644 --- a/src/lua_hooklib.c +++ b/src/lua_hooklib.c @@ -25,6 +25,7 @@ #include "lua_libs.h" #include "lua_hook.h" #include "lua_hud.h" // hud_running errors +#include "lua_profile.h" /* ========================================================================= ABSTRACTION @@ -65,6 +66,8 @@ static stringhook_t stringHooks[STRING_HOOK(MAX)]; bool hook_important = true; +#define NONMOHOOK ((mobjtype_t)-1) + // This will be indexed by hook id, the value of which fetches the registry. static int * hookRefs; static int nextid; @@ -199,7 +202,7 @@ FUNCINLINE static ATTRINLINE void add_hook(hook_t *map) FUNCINLINE static ATTRINLINE void add_mobj_hook(lua_State *L, int hook_type) { - mobjtype_t mobj_type = luaL_optnumber(L, 3, MT_NULL); + mobjtype_t mobj_type = luaL_optnumber(L, 3, MT_NULL); luaL_argcheck(L, mobj_type < NUMMOBJTYPES, 3, "invalid mobjtype_t"); @@ -293,18 +296,17 @@ typedef struct Hook_State Hook_State; typedef void (*Hook_Callback)(Hook_State *); struct Hook_State { - INT32 status;/* return status to calling function */ - void * userdata; - int hook_type; - mobjtype_t mobj_type;/* >0 if mobj hook */ - boolean force_mobj;// allows mobj_type equal 0 - const char * string;/* used to fetch table, ran first if set */ - int top;/* index of last argument passed to hook */ - int id;/* id to fetch ref */ - boolean important;/* is this hook from local addon */ - int values;/* num arguments passed to hook */ - int results;/* num values returned by hook */ - Hook_Callback results_handler;/* callback when hook successfully returns */ + INT32 status; /* return status to calling function */ + void * userdata; + int hook_type; + mobjtype_t mobj_type; /* != NONMOHOOK if mobj hook */ + const char * string; /* used to fetch table, ran first if set */ + int top; /* index of last argument passed to hook */ + int id; /* id to fetch ref */ + bool important; /* is this hook from local addon */ + int values; /* num arguments passed to hook */ + int results; /* num values returned by hook */ + Hook_Callback results_handler; /* callback when hook successfully returns */ }; enum { @@ -364,10 +366,8 @@ FUNCINLINE static ATTRINLINE boolean prepare_hook int default_status, int hook_type ){ - hook->force_mobj = false; - return init_hook_type(hook, default_status, - hook_type, 0, NULL, + hook_type, NONMOHOOK, NULL, hookIds[hook_type].numHooks); } @@ -381,8 +381,6 @@ FUNCINLINE static ATTRINLINE boolean prepare_mobj_hook const mobjtype_t mobj_type = primary_mobj ? primary_mobj->type : NUMMOBJTYPES; - hook->force_mobj = true; - return init_hook_type(hook, default_status, hook_type, mobj_type, NULL, mobj_hook_available(hook_type, mobj_type)); @@ -395,10 +393,8 @@ FUNCINLINE static ATTRINLINE boolean prepare_string_hook int hook_type, const char * string ){ - hook->force_mobj = false; - if (init_hook_type(hook, default_status, - hook_type, 0, string, + hook_type, NONMOHOOK, string, stringHooks[hook_type].ref)) { lua_pushstring(gL, string); @@ -414,7 +410,7 @@ FUNCINLINE static ATTRINLINE boolean prepare_hud_hook int hook_type ){ return init_hook_type(hook, 0, - hook_type, 0, NULL, + hook_type, NONMOHOOK, NULL, hudHookIds[hook_type].numHooks); } @@ -450,11 +446,54 @@ FUNCINLINE static ATTRINLINE void get_hook_from_table(Hook_State *hook, int n) lua_getref(gL, hookRefs[hook->id]); } +static int pcall(Hook_State *hook) +{ + return lua_pcall(gL, hook->values, hook->results, EINDEX); +} + +static const char *hook_name(Hook_State *hook) +{ + if (hud_running) + { + return hudHookNames[hook->hook_type]; + } + else if (hook->string) + { + return stringHookNames[hook->hook_type]; + } + //else if (hook->mobj_type > 0) + else if (hook->mobj_type != NONMOHOOK) + { + return mobjHookNames[hook->hook_type]; + } + else + { + return hookNames[hook->hook_type]; + } +} + +static int pcall_timed_or_untimed(Hook_State *hook) +{ + if (!hud_running && cv_lua_profile.value > 0) + { + lua_timer_t *timer = LUA_BeginFunctionTimer(gL, -1 - hook->values, hook_name(hook)); + int k = pcall(hook); + LUA_EndFunctionTimer(timer); + + return k; + } + else + { + return pcall(hook); + } +} + static int call_single_hook_no_copy(Hook_State *hook) { hook_important = hook->important; - if (lua_pcall(gL, hook->values, hook->results, EINDEX) == 0) + //if (lua_pcall(gL, hook->values, hook->results, EINDEX) == 0) + if (pcall_timed_or_untimed(hook) == 0) { if (hook->results > 0) { @@ -537,9 +576,45 @@ static int call_string_hooks(Hook_State *hook) FUNCINLINE static ATTRINLINE int call_mobj_type_hooks(Hook_State *hook, mobjtype_t mobj_type) { - return call_mapped(hook, &mobjHookIds[mobj_type][hook->hook_type]); + static UINT8 seen = 0; // so we dont have to check all this shit constantly + int numCalls = call_mapped(hook, &mobjHookIds[mobj_type][hook->hook_type]); + + if (!seen && numCalls > 0 && mobj_type == MT_NULL && + ( hook->hook_type == MOBJ_HOOK(MobjThinker ) + || hook->hook_type == MOBJ_HOOK(MobjCollide ) + || hook->hook_type == MOBJ_HOOK(MobjMoveCollide) + || hook->hook_type == MOBJ_HOOK(MobjFuse ) + || hook->hook_type == MOBJ_HOOK(BossThinker ) + )) + { + seen = 1; + + CONS_Alert( + CONS_WARNING, "%s\n", va( + "%s hooks not attached to a specific mobj type may cause performance issues!", + mobjHookNames[hook->hook_type]) + ); + + // print which script triggered it, ty indev <3 + for (int k = 0; k < mobjHookIds[mobj_type][hook->hook_type].numHooks; ++k) + { + lua_getref(gL, hookRefs[mobjHookIds[mobj_type][hook->hook_type].ids[k].id]); + + lua_Debug ar; + lua_getinfo(gL, ">S", &ar); + + CONS_Printf("%s:%d\n", ar.short_src, ar.linedefined); + } + } + + return numCalls; } +/*FUNCINLINE static ATTRINLINE int call_mobj_type_hooks(Hook_State *hook, mobjtype_t mobj_type) +{ + return call_mapped(hook, &mobjHookIds[mobj_type][hook->hook_type]); +}*/ + static int call_hooks ( Hook_State * hook, @@ -554,14 +629,13 @@ static int call_hooks { calls += call_string_hooks(hook); } - else if (hook->force_mobj) + //else if (hook->mobj_type > 0) + else if (hook->mobj_type != NONMOHOOK) { /* call generic mobj hooks first */ calls += call_mobj_type_hooks(hook, MT_NULL); - if (hook->mobj_type < NUMMOBJTYPES) calls += call_mobj_type_hooks(hook, hook->mobj_type); - ps_lua_mobjhooks.value.i += calls; } else @@ -615,7 +689,7 @@ FUNCINLINE static ATTRINLINE void res_hud(Hook_State *hook) int LUA_HookMobj(mobj_t *mobj, int hook_type) { - Hook_State hook; + Hook_State hook = {}; if (prepare_mobj_hook(&hook, false, hook_type, mobj)) { LUA_PushUserdata(gL, mobj, META_MOBJ); @@ -626,7 +700,7 @@ int LUA_HookMobj(mobj_t *mobj, int hook_type) int LUA_Hook2Mobj(mobj_t *t1, mobj_t *t2, int hook_type) { - Hook_State hook; + Hook_State hook = {}; if (prepare_mobj_hook(&hook, 0, hook_type, t1)) { LUA_PushUserdata(gL, t1, META_MOBJ); @@ -638,14 +712,14 @@ int LUA_Hook2Mobj(mobj_t *t1, mobj_t *t2, int hook_type) void LUA_HookVoid(int type) { - Hook_State hook; + Hook_State hook = {}; if (prepare_hook(&hook, 0, type)) call_hooks(&hook, 0, res_none); } void LUA_HookInt(INT32 number, int hook_type) { - Hook_State hook; + Hook_State hook = {}; if (prepare_hook(&hook, 0, hook_type)) { lua_pushinteger(gL, number); @@ -655,7 +729,7 @@ void LUA_HookInt(INT32 number, int hook_type) /*void LUA_HookBool(boolean value, int hook_type) { - Hook_State hook; + Hook_State hook = {}; if (prepare_hook(&hook, 0, hook_type)) { //lua_pushboolean(gL, value); @@ -665,7 +739,7 @@ void LUA_HookInt(INT32 number, int hook_type) int LUA_HookPlayer(player_t *player, int hook_type) { - Hook_State hook; + Hook_State hook = {}; if (prepare_hook(&hook, false, hook_type)) { LUA_PushUserdata(gL, player, META_PLAYER); @@ -676,7 +750,7 @@ int LUA_HookPlayer(player_t *player, int hook_type) int LUA_HookTiccmd(player_t *player, ticcmd_t *cmd, int hook_type) { - Hook_State hook; + Hook_State hook = {}; if (prepare_hook(&hook, false, hook_type)) { LUA_PushUserdata(gL, player, META_PLAYER); @@ -695,7 +769,7 @@ int LUA_HookTiccmd(player_t *player, ticcmd_t *cmd, int hook_type) void LUA_HookHUD(int hook_type, huddrawlist_h list) { - Hook_State hook; + Hook_State hook = {}; if (prepare_hud_hook(&hook, hook_type)) { LUA_SetHudHook(hook_type, list); @@ -723,12 +797,12 @@ static void hook_think_frame(int type) int hook_index = 0; precise_t time_taken = 0; - Hook_State hook; + Hook_State hook = {}; const hook_t * map = &hookIds[type]; int k; - const boolean perfstats = (cv_perfstats.value >= 3); + const boolean perfstats = (cv_perfstats.value >= PS_THINKFRAME); if (prepare_hook(&hook, 0, type)) { @@ -783,7 +857,7 @@ void LUA_HookPostThinkFrame(void) int LUA_HookTouchSpecial(mobj_t *special, mobj_t *toucher) { - Hook_State hook; + Hook_State hook = {}; if (prepare_mobj_hook(&hook, false, MOBJ_HOOK(TouchSpecial), special)) { LUA_PushUserdata(gL, special, META_MOBJ); @@ -802,7 +876,7 @@ static int damage_hook int hook_type, Hook_Callback results_handler ){ - Hook_State hook; + Hook_State hook = {}; if (prepare_mobj_hook(&hook, 0, hook_type, target)) { LUA_PushUserdata(gL, target, META_MOBJ); @@ -824,7 +898,7 @@ int LUA_HookShouldDamage(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT3 int LUA_HookMobjDamage(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 damage) { return damage_hook(target, inflictor, source, damage, - MOBJ_HOOK(MobjDamage), res_true); + MOBJ_HOOK(MobjDamage), res_true); } int LUA_HookMobjDeath(mobj_t *target, mobj_t *inflictor, mobj_t *source) @@ -890,8 +964,8 @@ int LUA_HookBotAI(mobj_t *sonic, mobj_t *tails, ticcmd_t *cmd) { const char *skin = ((skin_t *)tails->skin)->name; - Hook_State hook; - BotAI_State botai; + Hook_State hook = {}; + BotAI_State botai = {}; if (prepare_string_hook(&hook, false, STRING_HOOK(BotAI), skin)) { @@ -911,9 +985,9 @@ int LUA_HookBotAI(mobj_t *sonic, mobj_t *tails, ticcmd_t *cmd) void LUA_HookLinedefExecute(line_t *line, mobj_t *mo, sector_t *sector) { - Hook_State hook; + Hook_State hook = {}; if (prepare_string_hook - (&hook, 0, STRING_HOOK(LinedefExecute), line->text)) + (&hook, 0, STRING_HOOK(LinedefExecute), line->text)) { LUA_PushUserdata(gL, line, META_LINE); LUA_PushUserdata(gL, mo, META_MOBJ); @@ -924,7 +998,7 @@ void LUA_HookLinedefExecute(line_t *line, mobj_t *mo, sector_t *sector) int LUA_HookPlayerMsg(int source, int target, int flags, char *msg, int mute) { - Hook_State hook; + Hook_State hook = {}; if (prepare_hook(&hook, false, HOOK(PlayerMsg))) { LUA_PushUserdata(gL, &players[source], META_PLAYER); // Source player @@ -953,7 +1027,7 @@ int LUA_HookPlayerMsg(int source, int target, int flags, char *msg, int mute) int LUA_HookHurtMsg(player_t *player, mobj_t *inflictor, mobj_t *source) { - Hook_State hook; + Hook_State hook = {}; if (prepare_mobj_hook(&hook, false, MOBJ_HOOK(HurtMsg), inflictor)) { LUA_PushUserdata(gL, player, META_PLAYER); @@ -967,7 +1041,7 @@ int LUA_HookHurtMsg(player_t *player, mobj_t *inflictor, mobj_t *source) void LUA_HookNetArchive(lua_CFunction archFunc, savebuffer_t *save) { const hook_t * map = &hookIds[HOOK(NetVars)]; - Hook_State hook; + Hook_State hook = {}; /* this is a remarkable case where the stack isn't reset */ if (map->numHooks > 0) { @@ -986,6 +1060,9 @@ void LUA_HookNetArchive(lua_CFunction archFunc, savebuffer_t *save) lua_pushcclosure(gL, archFunc, 2); // stack: tables, savebuffer_t, archFunc + // Manually set the hook's variables here since we don't call prepare_hook + hook.hook_type = HOOK(NetVars); + hook.mobj_type = NONMOHOOK; // Force mobj_type to be NONMOHOOK so the mobj_type check get skipped init_hook_call(&hook, 0, res_none); call_mapped(&hook, map); @@ -997,7 +1074,7 @@ void LUA_HookNetArchive(lua_CFunction archFunc, savebuffer_t *save) void LUA_HookPlayerQuit(player_t *plr, int reason) { - Hook_State hook; + Hook_State hook = {}; if (prepare_hook(&hook, 0, HOOK(PlayerQuit))) { LUA_PushUserdata(gL, plr, META_PLAYER); // Player that quit @@ -1060,7 +1137,7 @@ int LUA_HookMusicChange(const char *oldname, struct MusicChange *param) const int type = HOOK(MusicChange); const hook_t * map = &hookIds[type]; - Hook_State hook; + Hook_State hook = {}; int k; @@ -1096,7 +1173,7 @@ int LUA_HookMusicChange(const char *oldname, struct MusicChange *param) int LUA_HookMusicCredit(musicdef_t *musicdef) { - Hook_State hook; + Hook_State hook = {}; if (prepare_hook(&hook, 0, HOOK(MusicCredit))) { LUA_PushUserdata(gL, musicdef, META_MUSICDEF); @@ -1114,7 +1191,7 @@ static int kartdamage_hook int hook_type, Hook_Callback results_handler ){ - Hook_State hook; + Hook_State hook = {}; if (prepare_hook(&hook, 0, hook_type)) { LUA_PushUserdata(gL, player, META_PLAYER); @@ -1163,7 +1240,7 @@ boolean LUA_HookPlayerExplode(player_t *player, mobj_t *inflictor, mobj_t *sourc void LUA_HookSetupVote(INT16 result[], INT16 maxresults, UINT8 gt, UINT8 secondgt) { - Hook_State hook; + Hook_State hook = {}; if (prepare_hook(&hook, 0, HOOK(SetupVote))) { // { 0, 0, 0, 0, } diff --git a/src/lua_hudlib.c b/src/lua_hudlib.c index 538463117..78a7a5e19 100644 --- a/src/lua_hudlib.c +++ b/src/lua_hudlib.c @@ -644,20 +644,22 @@ static int libd_drawScaled(lua_State *L) // KART: draw patch on minimap from x, y coordinates on the map static int libd_drawOnMinimap(lua_State *L) { - fixed_t x, y, scale; // coordinates of the object - patch_t *patch; // patch we want to draw - UINT8 *colormap = NULL; // do we want to colormap this patch? - boolean centered; // the patch is centered and doesn't need readjusting on x/y coordinates. + fixed_t x, y, scale; // coordinates of the object + patch_t *patch; // patch we want to draw + UINT8 *colormap = NULL; // do we want to colormap this patch? + boolean centered; // the patch is centered and doesn't need readjusting on x/y coordinates. huddrawlist_h list; - patch_t *AutomapPic = NULL; drawinfo_t info; + // variables used to replicate k_kart's mmap drawer: + patch_t *AutomapPic; + // variables used for actually drawing the icon: INT32 splitflags, minimaptrans; fixed_t amnumxpos, amnumypos; fixed_t amxpos, amypos; INT32 mm_x, mm_y; - fixed_t patchw = 0, patchh = 0; + fixed_t patchw, patchh; HUDONLY // only run this function in hud hooks @@ -722,8 +724,11 @@ static int libd_drawOnMinimap(lua_State *L) mm_y -= AutomapPic->topoffset; - // patch is supposedly already centered, don't butt in. - if (!centered) + if (centered) + { + patchw = patchh = 0; // patch is supposedly already centered, don't butt in. + } + else { // scale patch coords patchw = (patch->width * scale / 2); @@ -1297,7 +1302,7 @@ static int lib_hudsetvotebackground(lua_State *L) if (strlen(prefix) != 4) { - return luaL_argerror(L, 1, "prefix should 4 characters wide"); + return luaL_argerror(L, 1, "prefix should be 4 characters wide"); } strncpy(VoteScreen.luaPrefix, prefix, 4); diff --git a/src/lua_hudlib_drawlist.c b/src/lua_hudlib_drawlist.c index f267c5fe3..d2b2eeeb4 100644 --- a/src/lua_hudlib_drawlist.c +++ b/src/lua_hudlib_drawlist.c @@ -136,18 +136,9 @@ void LUA_HUD_DestroyDrawList(huddrawlist_h list) { if (list == NULL) return; - if (list->items) - { - Z_Free(list->items); - } - if (list->olditems) - { - Z_Free(list->olditems); - } - if (list->strbuf) - { - Z_Free(list->strbuf); - } + Z_Free(list->items); + Z_Free(list->olditems); + Z_Free(list->strbuf); Z_Free(list); } @@ -659,34 +650,34 @@ void LUA_HUD_DrawList(huddrawlist_h list) case DI_DrawString: switch(item->align) { - // hu_font - case align_left: - V_DrawString(LERPS(x), LERPS(y), item->flags, itemstr); - break; - case align_center: - V_DrawCenteredString(LERPS(x), LERPS(y), item->flags, itemstr); - break; - case align_right: - V_DrawRightAlignedString(LERPS(x), LERPS(y), item->flags, itemstr); - break; - case align_fixed: - V_DrawStringAtFixed(LERPS(x), LERPS(y), item->flags, itemstr); - break; - // hu_font, 0.5x scale - case align_small: - V_DrawSmallString(LERPS(x), LERPS(y), item->flags, itemstr); - break; - case align_smallright: - V_DrawRightAlignedSmallString(LERPS(x), LERPS(y), item->flags, itemstr); - break; - // tny_font - case align_thin: - V_DrawThinString(LERPS(x), LERPS(y), item->flags, itemstr); - break; - case align_thinright: - V_DrawRightAlignedThinString(LERPS(x), LERPS(y), item->flags, itemstr); - break; - } + // hu_font + case align_left: + V_DrawString(LERPS(x), LERPS(y), item->flags, itemstr); + break; + case align_center: + V_DrawCenteredString(LERPS(x), LERPS(y), item->flags, itemstr); + break; + case align_right: + V_DrawRightAlignedString(LERPS(x), LERPS(y), item->flags, itemstr); + break; + case align_fixed: + V_DrawStringAtFixed(LERPS(x), LERPS(y), item->flags, itemstr); + break; + // hu_font, 0.5x scale + case align_small: + V_DrawSmallString(LERPS(x), LERPS(y), item->flags, itemstr); + break; + case align_smallright: + V_DrawRightAlignedSmallString(LERPS(x), LERPS(y), item->flags, itemstr); + break; + // tny_font + case align_thin: + V_DrawThinString(LERPS(x), LERPS(y), item->flags, itemstr); + break; + case align_thinright: + V_DrawRightAlignedThinString(LERPS(x), LERPS(y), item->flags, itemstr); + break; + } break; case DI_DrawKartString: V_DrawKartString(LERPS(x), LERPS(y), item->flags, itemstr); @@ -699,7 +690,6 @@ void LUA_HUD_DrawList(huddrawlist_h list) break; default: I_Error("can't draw draw list item: invalid draw list item type"); - continue; } } } diff --git a/src/lua_infolib.c b/src/lua_infolib.c index 68ca6b4d0..5f2f4f80c 100644 --- a/src/lua_infolib.c +++ b/src/lua_infolib.c @@ -22,10 +22,11 @@ #include "lua_script.h" #include "lua_libs.h" #include "lua_hud.h" // hud_running errors -#include "lua_hook.h" // cmd errors +#include "lua_hook.h" // hook_cmd_running errors +#include "lua_profile.h" boolean LUA_CallAction(enum actionnum actionnum, mobj_t *actor); -state_t *astate; +state_t *astate = NULL; boolean actionsoverridden[NUMACTIONS] = {false}; @@ -110,7 +111,10 @@ static void A_Lua(mobj_t *actor) LUA_PushUserdata(gL, actor, META_MOBJ); lua_pushinteger(gL, var1); lua_pushinteger(gL, var2); + + lua_timer_t *timer = LUA_BeginFunctionTimer(gL, -4, "A_Lua"); LUA_Call(gL, 3, 0, 1); + LUA_EndFunctionTimer(timer); lua_pop(gL, 1); // pop error handler diff --git a/src/lua_maplib.c b/src/lua_maplib.c index 2931e9a16..87639b77b 100644 --- a/src/lua_maplib.c +++ b/src/lua_maplib.c @@ -652,7 +652,7 @@ static int line_get(lua_State *L) LUA_PushUserdata(L, &sides[line->sidenum[0]], META_SIDE); return 1; case line_backside: // backside - if (line->sidenum[1] == 0xffff) + if (line->sidenum[1] == NO_INDEX) return 0; LUA_PushUserdata(L, &sides[line->sidenum[1]], META_SIDE); return 1; @@ -1506,7 +1506,6 @@ enum mapheaderinfo_e mapheaderinfo_saveoverride, mapheaderinfo_levelflags, mapheaderinfo_menuflags, - //mapheaderinfo_automap, mapheaderinfo_mobj_scale, }; @@ -1542,7 +1541,6 @@ static const char *const mapheaderinfo_opt[] = { "saveoverride", "levelflags", "menuflags", - //"automap", "mobj_scale", NULL, }; @@ -1584,10 +1582,11 @@ static int mapheaderinfo_get(lua_State *L) lua_pushinteger(L, header->muspos); break; case mapheaderinfo_musinterfadeout: - lua_pushinteger(L, header->musinterfadeout); + lua_pushinteger(L, 0); // unused break; case mapheaderinfo_musintername: - lua_pushstring(L, header->musintername); + // uhh psure its fine to just push nil instead of empty string? + lua_pushstring(L, NULL); break; case mapheaderinfo_forcecharacter: lua_pushstring(L, header->forcecharacter); @@ -1641,10 +1640,10 @@ static int mapheaderinfo_get(lua_State *L) lua_pushinteger(L, header->levelselect); break; case mapheaderinfo_bonustype: - lua_pushinteger(L, header->bonustype); + lua_pushinteger(L, 0); // unused break; case mapheaderinfo_saveoverride: - lua_pushinteger(L, header->saveoverride); + lua_pushinteger(L, SAVE_DEFAULT); // unused break; case mapheaderinfo_levelflags: lua_pushinteger(L, header->levelflags); @@ -1652,28 +1651,29 @@ static int mapheaderinfo_get(lua_State *L) case mapheaderinfo_menuflags: lua_pushinteger(L, header->menuflags); break; - /*case mapheaderinfo_automap: - lua_pushstring(L, header->selectheading); - break;*/ case mapheaderinfo_mobj_scale: lua_pushfixed(L, header->mobj_scale); break; - // TODO add support for reading numGradedMares and grades default: { // Read custom vars now // (note: don't include the "LUA." in your lua scripts!) - UINT8 j = 0; - for (;j < header->numCustomOptions && !fastcmp(lua_tostring(L, 2), header->customopts[j].option); ++j); + if (!header->numCustomOptions) { + lua_pushnil(L); + break; + } - if(j < header->numCustomOptions) + UINT8 j = 0; + const char *cusoptstr = lua_tostring(L, 2); + for (;j < header->numCustomOptions && !fastcmp(cusoptstr, header->customopts[j].option); ++j); + + if (j < header->numCustomOptions) lua_pushstring(L, header->customopts[j].value); else lua_pushnil(L); } } return 1; - } int LUA_MapLib(lua_State *L) diff --git a/src/lua_mobjlib.c b/src/lua_mobjlib.c index 45c3a9f19..9bd5f5203 100644 --- a/src/lua_mobjlib.c +++ b/src/lua_mobjlib.c @@ -475,7 +475,7 @@ int mobj_localskin_setter(lua_State *L) } else { - mo->localskin = 0; + mo->localskin = NULL; mo->skinlocal = false; } } diff --git a/src/lua_profile.cpp b/src/lua_profile.cpp new file mode 100644 index 000000000..d910c5d65 --- /dev/null +++ b/src/lua_profile.cpp @@ -0,0 +1,264 @@ +// DR. ROBOTNIK'S RING RACERS +//----------------------------------------------------------------------------- +// Copyright (C) 2025 by James Robert Roman +// Copyright (C) 2025 by Kart Krew +// +// This program is free software distributed under the +// terms of the GNU General Public License, version 2. +// See the 'LICENSE' file for more details. +//----------------------------------------------------------------------------- + +#include "screen.h" +#include +#include +#include +#include +#include +#include + +extern "C" { +#include "blua/lua.h" +}; + +#include "v_video.h" + +#include "command.h" +#include "doomtype.h" +#include "i_system.h" +#include "lua_profile.h" +#include "m_perfstats.h" + +extern "C" consvar_t cv_lua_profile; + +namespace +{ + +precise_t g_time_reference; +int g_tics_counted; + +double g_running_tic_time; +double g_avg_tic_time; + +bool g_invalid; + +}; // namespace + +struct lua_timer_t +{ + struct Stat + { + double calls = 0; + double time = 0.0; + }; + + Stat running, avg; +}; + +namespace +{ + +std::unordered_map g_tic_timers; + +}; // namespace + +lua_timer_t* LUA_BeginFunctionTimer(lua_State* L, int fn_idx, const char* name) +{ + lua_Debug ar; + + lua_pushvalue(L, fn_idx); + lua_getinfo(L, ">S", &ar); + + auto label = [&] + { + using sv = std::string_view; + sv view{ar.source}; + + switch (view.front()) + { + case '@': // file + if (std::size_t p = view.rfind('/'); p != sv::npos) // lump or base + { + return view.substr(p + 1); + } + break; + + case '=': // ?? + view.remove_prefix(1); + break; + } + + return view; + }; + + // i sure hope this std::string mess is fine... + auto [it, ins] = g_tic_timers.try_emplace(std::string(va("%s:%d (%s)", std::string(label()).c_str(), ar.linedefined, name))); + auto& [key, timer] = *it; + + g_time_reference = I_GetPreciseTime(); + + return &timer; +} + +void LUA_EndFunctionTimer(lua_timer_t* timer) +{ + precise_t t = I_GetPreciseTime() - g_time_reference; + double precision = I_GetPrecisePrecision(); + + timer->running.time += t / precision; + timer->running.calls += 1.0; +} + +void LUA_ResetTicTimers(void) +{ + if (cv_lua_profile.value <= 0) + { + return; + } + + if (g_tics_counted < cv_lua_profile.value) + { + g_tics_counted++; + + double precision = I_GetPrecisePrecision(); + g_running_tic_time += ps_prevtictime.value.p / precision; + } + else + { + double counted = g_tics_counted; + + for (auto& [key, timer] : g_tic_timers) + { + timer.avg = {timer.running.calls / counted, timer.running.time / counted}; + timer.running = {}; + } + + g_avg_tic_time = g_running_tic_time / counted; + g_running_tic_time = 0.0; + + g_tics_counted = 1; + + g_invalid = false; + } +} + +void LUA_RenderTimers(void) +{ + constexpr int kRowHeight = 4; + float row_y = kRowHeight; + + // pretty much what the whole srb2::Draw does lol + auto draw_row = [](float x, float y, INT32 flags, const char *str) + { + V_DrawSmallStringAtFixed( + FloatToFixed(x), + FloatToFixed(y), + V_MONOSPACE|V_ALLOWLOWERCASE|flags, + str + ); + }; + + draw_row(0.f, 0.f, 0, va("-- AVERAGES PER TIC (over %d tics) --", cv_lua_profile.value)); + + if (g_invalid) + { + draw_row(0.f, row_y, V_GRAYMAP, " "); + return; + } + + std::vector view; + view.reserve(g_tic_timers.size()); + + auto color_flag = [](double t) + { + if (t < 10.0) + { + return V_GRAYMAP; + } + else if (t >= 100.0) + { + return V_YELLOWMAP; + } + else + { + return 0; + } + }; + + { + double cum = 0.0; + + for (auto it = g_tic_timers.begin(); it != g_tic_timers.end(); ++it) + { + auto& [key, timer] = *it; + + cum += timer.avg.time; + + if (timer.avg.time > 0.0) + { + view.push_back(it); + } + } + + { + const INT32 tally_flags = color_flag(cum * 1'000'000.0); + + draw_row(0.f, row_y, tally_flags, va("%8.2f us - TOTAL", cum * 1'000'000.0)); + draw_row(0.f, row_y + kRowHeight, tally_flags, va("%8.2f ms", cum * 1000.0)); + + // dont need to show this if we didnt capture over time + // this would just show nan or inf anyways + if (std::fpclassify(g_avg_tic_time) != FP_ZERO) + { + draw_row(0.f, row_y + kRowHeight * 2, tally_flags, va( + "%8.2f%% overhead (%.2f / %.2f) <-- not counting rendering time", + (cum / g_avg_tic_time) * 100.0, + (cum * (double)TICRATE), + (g_avg_tic_time * (double)TICRATE) + )); + } + } + + row_y += kRowHeight * 4; + } + + std::sort( + view.rbegin(), + view.rend(), + [](auto a, auto b) + { + auto& [k1, t1] = *a; + auto& [k2, t2] = *b; + return t1.avg.time < t2.avg.time; + } + ); + + for (auto it : view) + { + auto& [key, timer] = *it; + + double t = timer.avg.time * 1'000'000.0; + + draw_row(0.f, row_y, color_flag(t), va( + "%8.2f us %8.2f calls - %s", + t, + timer.avg.calls, + key.c_str() + )); + + row_y += kRowHeight; + + // FIXME this is all ugly and sucks + if (row_y >= BASEVIDHEIGHT) + break; + } +} + +extern "C" void lua_profile_OnChange(void) +{ + g_invalid = true; + + if (cv_lua_profile.value == 0) + { + g_tic_timers = {}; + } +} diff --git a/src/lua_profile.h b/src/lua_profile.h new file mode 100644 index 000000000..80475613d --- /dev/null +++ b/src/lua_profile.h @@ -0,0 +1,38 @@ +// DR. ROBOTNIK'S RING RACERS +//----------------------------------------------------------------------------- +// Copyright (C) 2025 by James Robert Roman +// Copyright (C) 2025 by Kart Krew +// +// This program is free software distributed under the +// terms of the GNU General Public License, version 2. +// See the 'LICENSE' file for more details. +//----------------------------------------------------------------------------- + +#ifndef lua_profile_h +#define lua_profile_h + +#include "blua/lua.h" +#include "doomtype.h" +//#include "typedef.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct lua_timer_t; +typedef struct lua_timer_t lua_timer_t; + +void LUA_ResetTicTimers(void); + +lua_timer_t *LUA_BeginFunctionTimer(lua_State *L, int fn_idx, const char *name); +void LUA_EndFunctionTimer(lua_timer_t *timer); + +void LUA_RenderTimers(void); + +void lua_profile_OnChange(void); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif/*lua_profile_h*/ diff --git a/src/lua_script.c b/src/lua_script.c index 96ce94a22..0db0bd1e0 100644 --- a/src/lua_script.c +++ b/src/lua_script.c @@ -45,20 +45,20 @@ int hook_defrosting = 0; // List of internal libraries to load from SRB2 static lua_CFunction liblist[] = { - LUA_EnumLib, // global metatable for enums - LUA_SOCLib, // A_Action functions, freeslot - LUA_BaseLib, // string concatination by +, CONS_Printf, p_local.h stuff (P_InstaThrust, P_Move), etc. - LUA_MathLib, // fixed_t and angle_t math functions - LUA_HookLib, // hookAdd and hook-calling functions - LUA_ConsoleLib, // console command/variable functions and structs - LUA_InfoLib, // info.h stuff: mobjinfo_t, mobjinfo[], state_t, states[] - LUA_MobjLib, // mobj_t, mapthing_t - LUA_PlayerLib, // player_t - LUA_SkinLib, // skin_t, skins[] - LUA_ThinkerLib, // thinker_t - LUA_MapLib, // line_t, side_t, sector_t, subsector_t - LUA_BlockmapLib, // blockmap stuff - LUA_HudLib, // HUD stuff + LUA_EnumLib, // global metatable for enums + LUA_SOCLib, // A_Action functions, freeslot + LUA_BaseLib, // string concatination by +, CONS_Printf, p_local.h stuff (P_InstaThrust, P_Move), etc. + LUA_MathLib, // fixed_t and angle_t math functions + LUA_HookLib, // hookAdd and hook-calling functions + LUA_ConsoleLib, // console command/variable functions and structs + LUA_InfoLib, // info.h stuff: mobjinfo_t, mobjinfo[], state_t, states[] + LUA_MobjLib, // mobj_t, mapthing_t + LUA_PlayerLib, // player_t + LUA_SkinLib, // skin_t, skins[] + LUA_ThinkerLib, // thinker_t + LUA_MapLib, // line_t, side_t, sector_t, subsector_t + LUA_BlockmapLib, // blockmap stuff + LUA_HudLib, // HUD stuff NULL }; @@ -66,12 +66,8 @@ static lua_CFunction liblist[] = { static void *LUA_Alloc(void *ud, void *ptr, size_t osize, size_t nsize) { (void)ud; - if (nsize == 0) { - if (osize != 0) - Z_Free(ptr); - return NULL; - } else - return Z_Realloc(ptr, nsize, PU_LUA, NULL); + (void)osize; + return Z_Realloc(ptr, nsize, PU_LUA, NULL); } // Panic function Lua calls when there's an unprotected error. @@ -213,7 +209,8 @@ void LUA_ClearState(void) lua_setfield(L, LUA_REGISTRYINDEX, LREG_VALID); // open srb2 libraries - for(i = 0; liblist[i]; i++) { + for (i = 0; liblist[i]; i++) + { lua_pushcfunction(L, liblist[i]); lua_call(L, 0, 0); } @@ -280,20 +277,19 @@ void LUA_LoadLump(UINT16 wad, UINT16 lump) if (wadfiles[wad]->type == RET_LUA) { - name = malloc(len+1); - strcpy(name, wadfiles[wad]->filename); + name = malloc(len + 1); + snprintf(name, len + 1, "%s", wadfiles[wad]->filename); } else // If it's not a .lua file, copy the lump name in too. { lumpinfo_t *lump_p = &wadfiles[wad]->lumpinfo[lump]; len += 1 + strlen(lump_p->fullname); // length of file name, '|', and lump name - name = malloc(len+1); + name = malloc(len + 1); if (!name) I_Error("LUA_LoadLump: Out of memory!\n"); - sprintf(name, "%s|%s", wadfiles[wad]->filename, lump_p->fullname); - name[len] = '\0'; + snprintf(name, len + 1, "%s|%s", wadfiles[wad]->filename, lump_p->fullname); } LUA_LoadFile(&f, name); // actually load file! @@ -595,6 +591,7 @@ void LUA_InvalidateLevel(void) for (i = 0; i < numsubsectors; i++) LUA_InvalidateUserdata(&subsectors[i]); + for (i = 0; i < numsectors; i++) { LUA_InvalidateUserdata(§ors[i]); @@ -615,6 +612,7 @@ void LUA_InvalidateLevel(void) for (i = 0; i < numsides; i++) LUA_InvalidateUserdata(&sides[i]); + for (i = 0; i < numvertexes; i++) LUA_InvalidateUserdata(&vertexes[i]); @@ -625,6 +623,10 @@ void LUA_InvalidateLevel(void) LUA_InvalidateUserdata(&slope->o); LUA_InvalidateUserdata(&slope->d); } + + // We invalidated a lot of userdata objects, a lot of them probably ended up unreachable so they can be + // GC'd right away + lua_gc(gL, LUA_GCCOLLECT, 0); } void LUA_InvalidateMapthings(void) @@ -716,9 +718,12 @@ static UINT8 GetUserdataArchType(int index) static UINT8 ArchiveValue(UINT8 **p, int TABLESINDEX, int myindex) { + int type = lua_type(gL, myindex); + if (myindex < 0) myindex = lua_gettop(gL)+1+myindex; - switch (lua_type(gL, myindex)) + + switch (type) { case LUA_TNONE: case LUA_TNIL: @@ -728,8 +733,12 @@ static UINT8 ArchiveValue(UINT8 **p, int TABLESINDEX, int myindex) case LUA_TLIGHTUSERDATA: case LUA_TTHREAD: case LUA_TFUNCTION: + { + const char *typestr = (type == LUA_TLIGHTUSERDATA ? "light userdata" : (type == LUA_TTHREAD ? "thread" : (type == LUA_TFUNCTION ? "function" : "??"))); + CONS_Alert(CONS_ERROR, M_GetText("Archived an invalid value! (%s)\n"), typestr); WRITEUINT8(*p, ARCH_NULL); return 2; + } case LUA_TBOOLEAN: WRITEUINT8(*p, ARCH_BOOLEAN); WRITEUINT8(*p, lua_toboolean(gL, myindex)); @@ -982,7 +991,7 @@ static void ArchiveExtVars(UINT8 **p, void *pointer, const char *ptype) if (!gL) { - if (fastcmp(ptype,"player")) // players must always be included, even if no vars + if (fastcmp(ptype, "player")) // players must always be included, even if no vars WRITEUINT16(*p, 0); return; } @@ -998,7 +1007,7 @@ static void ArchiveExtVars(UINT8 **p, void *pointer, const char *ptype) if (!lua_istable(gL, -1)) { // no extra values table lua_pop(gL, 1); - if (fastcmp(ptype,"player")) // players must always be included, even if no vars + if (fastcmp(ptype, "player")) // players must always be included, even if no vars WRITEUINT16(*p, 0); return; } @@ -1010,13 +1019,13 @@ static void ArchiveExtVars(UINT8 **p, void *pointer, const char *ptype) // skip anything that has an empty table and isn't a player. if (i == 0) { - if (fastcmp(ptype,"player")) // always include players even if they have no extra variables + if (fastcmp(ptype, "player")) // always include players even if they have no extra variables WRITEUINT16(*p, 0); lua_pop(gL, 1); return; } - if (fastcmp(ptype,"mobj")) // mobjs must write their mobjnum as a header + if (fastcmp(ptype, "mobj")) // mobjs must write their mobjnum as a header WRITEUINT32(*p, ((mobj_t *)pointer)->mobjnum); WRITEUINT16(*p, i); @@ -1064,9 +1073,14 @@ static void ArchiveTables(UINT8 **p) { // Write key e = ArchiveValue(p, TABLESINDEX, -2); // key should be either a number or a string, ArchiveValue can handle this. - if (e == 2) // invalid key type (function, thread, lightuserdata, or anything we don't recognise) + if (e == 1) + n++; // the table contained a new table we'll have to archive. :( + else if (e == 2) // invalid key type (function, thread, lightuserdata, or anything we don't recognise) { - CONS_Alert(CONS_ERROR, "Index '%s' (%s) of table %d could not be archived!\n", lua_tostring(gL, -2), luaL_typename(gL, -2), i); + lua_pushvalue(gL, -2); // copy key for error message (lua_tostring may mutate it which confuses lua_next) + CONS_Alert(CONS_ERROR, "Index '%s' (%s) of table %d could not be archived!\n", lua_tostring(gL, -1), luaL_typename(gL, -1), i); + lua_pop(gL, 2); // pop key copy and value + continue; } else if (e == 3) // nil key due to invalid userdata. NOT an error. { @@ -1077,16 +1091,17 @@ static void ArchiveTables(UINT8 **p) // Write value e = ArchiveValue(p, TABLESINDEX, -1); if (e == 1) - { n++; // the table contained a new table we'll have to archive. :( - } else if (e == 2) // invalid value type { - CONS_Alert(CONS_ERROR, "Type of value for table %d entry '%s' (%s) could not be archived!\n", i, lua_tostring(gL, -2), luaL_typename(gL, -1)); + lua_pushvalue(gL, -2); // copy key for error message (same as above) + CONS_Alert(CONS_ERROR, "Type of value for table %d entry '%s' (%s) could not be archived!\n", i, lua_tostring(gL, -1), luaL_typename(gL, -2)); + lua_pop(gL, 1); // pop key copy } lua_pop(gL, 1); } + lua_pop(gL, 1); WRITEUINT8(*p, ARCH_TEND); } @@ -1276,13 +1291,21 @@ static void UnArchiveTables(UINT8 **p, boolean network) UINT8 ret; ret = UnArchiveValue(p, TABLESINDEX, network); - if (ret == 3) + if (ret == 1) // End of table + break; + else if (ret == 2) // Key contains a new table + n++; + else if (ret == 3) { //CONS_Alert(CONS_WARNING,"Couldn't read mobj_t\n"); lua_pushnil(gL); } - else if (ret == 1) // read key - break; + + if (lua_isnil(gL, -1)) // If key is nil, skip this entry + { + lua_pop(gL, 1); + continue; + } ret = UnArchiveValue(p, TABLESINDEX, network); if (ret == 1) @@ -1291,21 +1314,15 @@ static void UnArchiveTables(UINT8 **p, boolean network) lua_pop(gL, 1); // Pop key break; } + else if (ret == 2) // read value + n++; else if (ret == 3) { //CONS_Alert(CONS_WARNING,"Couldn't read mobj_t\n"); lua_pushnil(gL); } - else if (ret == 2) // read value - n++; - if (lua_isnil(gL, -2)) // if key is nil (if a function etc was accidentally saved) - { - CONS_Alert(CONS_ERROR, "A nil key in table %d was found! (Invalid key type or corrupted save?)\n", i); - lua_pop(gL, 2); // pop key and value instead of setting them in the table, to prevent Lua panic errors - } - else - lua_rawset(gL, -3); + lua_rawset(gL, -3); } lua_pop(gL, 1); diff --git a/src/lzf.h b/src/lzf.h index 85daf255e..995e4ebd6 100644 --- a/src/lzf.h +++ b/src/lzf.h @@ -13,6 +13,10 @@ #define LZF_H #include +#ifdef __cplusplus +extern "C" { +#endif + /*********************************************************************** ** ** lzf -- an extremely fast/free compression/decompression-method @@ -71,5 +75,9 @@ size_t lzf_decompress (const void *const in_data, size_t in_len, void *out_data, size_t out_len); +#ifdef __cplusplus +} // extern "C" +#endif + #endif diff --git a/src/m_aatree.c b/src/m_aatree.c index f78355eaf..7fb847aab 100644 --- a/src/m_aatree.c +++ b/src/m_aatree.c @@ -49,17 +49,19 @@ aatree_t *M_AATreeAlloc(UINT32 flags) return aatree; } -static void M_AATreeFree_Node(aatree_node_t *node) +static void M_AATreeFree_Node(aatree_node_t *node, bool is_string) { - if (node->left) M_AATreeFree_Node(node->left); - if (node->right) M_AATreeFree_Node(node->right); + if (node->left) M_AATreeFree_Node(node->left, is_string); + if (node->right) M_AATreeFree_Node(node->right, is_string); + if (is_string) + Z_Free(node->value); Z_Free(node); } void M_AATreeFree(aatree_t *aatree) { if (aatree->root) - M_AATreeFree_Node(aatree->root); + M_AATreeFree_Node(aatree->root, (aatree->flags & AATREE_STRING) == AATREE_STRING); Z_Free(aatree); } diff --git a/src/m_anigif.c b/src/m_anigif.c index a8cc21bcf..c9cda476e 100644 --- a/src/m_anigif.c +++ b/src/m_anigif.c @@ -556,7 +556,7 @@ static void GIF_framewrite(void) } else if (gif_dynamicdelay ==(UINT8) 1) { - float delayf = ceil(100.0f/NEWTICRATE); + float delayf = ceilf(100.0f/NEWTICRATE); delay = (UINT16)((I_GetPreciseTime() - gif_prevframetime)) / (I_GetPrecisePrecision() / 1000000) /10/1000; @@ -695,16 +695,13 @@ INT32 GIF_close(void) fclose(gif_out); gif_out = NULL; - if (gifbwr_buf) - Z_Free(gifbwr_buf); + Z_Free(gifbwr_buf); gifbwr_buf = gifbwr_cur = NULL; - if (gifframe_data) - Z_Free(gifframe_data); + Z_Free(gifframe_data); gifframe_data = NULL; - if (giflzw_hashTable) - Z_Free(giflzw_hashTable); + Z_Free(giflzw_hashTable); giflzw_hashTable = NULL; Z_Free(scrbuf_screens); diff --git a/src/m_cheat.c b/src/m_cheat.c index 2890c7196..0360ecc56 100644 --- a/src/m_cheat.c +++ b/src/m_cheat.c @@ -80,7 +80,7 @@ static UINT8 cheatf_warp(void) if (success) { G_SaveGameData(true); //G_SetGameModified(false); - S_StartSound(0, sfx_kc42); + S_StartSound(NULL, sfx_kc42); } // Refresh secrets menu existing. @@ -117,13 +117,13 @@ static UINT8 cheatf_devmode(void) #endif static cheatseq_t cheat_warp = { - 0, cheatf_warp, + NULL, cheatf_warp, //{ SCRAMBLE('r'), SCRAMBLE('e'), SCRAMBLE('d'), SCRAMBLE('x'), SCRAMBLE('v'), SCRAMBLE('i'), 0xff } { SCRAMBLE('b'), SCRAMBLE('a'), SCRAMBLE('n'), SCRAMBLE('a'), SCRAMBLE('n'), SCRAMBLE('a'), 0xff } }; static cheatseq_t cheat_warp_joy = { - 0, cheatf_warp, + NULL, cheatf_warp, /*{ SCRAMBLE(KEY_LEFTARROW), SCRAMBLE(KEY_LEFTARROW), SCRAMBLE(KEY_UPARROW), SCRAMBLE(KEY_RIGHTARROW), SCRAMBLE(KEY_RIGHTARROW), SCRAMBLE(KEY_UPARROW), SCRAMBLE(KEY_LEFTARROW), SCRAMBLE(KEY_UPARROW), @@ -136,7 +136,7 @@ static cheatseq_t cheat_warp_joy = { #ifdef DEVELOP static cheatseq_t cheat_devmode = { - 0, cheatf_devmode, + NULL, cheatf_devmode, { SCRAMBLE('d'), SCRAMBLE('e'), SCRAMBLE('v'), SCRAMBLE('m'), SCRAMBLE('o'), SCRAMBLE('d'), SCRAMBLE('e'), 0xff } }; #endif @@ -249,9 +249,6 @@ boolean cht_Responder(event_t *ev) #define REQUIRE_SINGLEPLAYER if (netgame || multiplayer)\ { CONS_Printf(M_GetText("This only works in single player.\n")); return; } -#define REQUIRE_NOULTIMATE if (ultimatemode)\ -{ CONS_Printf(M_GetText("You're too good to be cheating!\n")); return; } - // command that can be typed at the console! void Command_CheatNoClip_f(void) { @@ -259,7 +256,6 @@ void Command_CheatNoClip_f(void) REQUIRE_INLEVEL; REQUIRE_SINGLEPLAYER; - REQUIRE_NOULTIMATE; plyr = &players[consoleplayer]; plyr->pflags ^= PF_NOCLIP; @@ -274,7 +270,6 @@ void Command_CheatGod_f(void) REQUIRE_INLEVEL; REQUIRE_SINGLEPLAYER; - REQUIRE_NOULTIMATE; plyr = &players[consoleplayer]; plyr->pflags ^= PF_GODMODE; @@ -289,7 +284,6 @@ void Command_CheatNoTarget_f(void) REQUIRE_INLEVEL; REQUIRE_SINGLEPLAYER; - REQUIRE_NOULTIMATE; plyr = &players[consoleplayer]; plyr->pflags ^= PF_INVIS; @@ -301,7 +295,7 @@ void Command_CheatNoTarget_f(void) void Command_Scale_f(void) { const double scaled = atof(COM_Argv(1)); - fixed_t scale = FLOAT_TO_FIXED(scaled); + fixed_t scale = DoubleToFixed(scaled); REQUIRE_DEVMODE; REQUIRE_INLEVEL; @@ -593,7 +587,6 @@ void Command_Devmode_f(void) #ifndef _DEBUG REQUIRE_SINGLEPLAYER; #endif - REQUIRE_NOULTIMATE; if (COM_Argc() > 1) { @@ -773,7 +766,7 @@ boolean OP_FreezeObjectplace(void) if (!objectplacing) return false; - if ((maptol & TOL_NIGHTS) && (players[consoleplayer].pflags & PF_NIGHTSMODE)) + if (nightsmode && nightsplayer(&players[consoleplayer])) return false; return true; @@ -1048,7 +1041,6 @@ void Command_ObjectPlace_f(void) { REQUIRE_INLEVEL; REQUIRE_SINGLEPLAYER; - REQUIRE_NOULTIMATE; G_SetGameModified(multiplayer, true); @@ -1057,7 +1049,7 @@ void Command_ObjectPlace_f(void) { objectplacing = true; - if ((players[0].pflags & PF_NIGHTSMODE)) + if (nightsplayer(&players[0])) return; if (!COM_CheckParm("-silent")) @@ -1128,7 +1120,7 @@ void Command_ObjectPlace_f(void) // Don't touch the NiGHTS Objectplace stuff. // ... or if the mo mysteriously vanished. - if (!players[0].mo || (players[0].pflags & PF_NIGHTSMODE)) + if (!players[0].mo || nightsplayer(&players[0])) return; // If still in dummy state, get out of it. diff --git a/src/m_cheat.h b/src/m_cheat.h index f2944c27c..aaf038436 100644 --- a/src/m_cheat.h +++ b/src/m_cheat.h @@ -29,7 +29,6 @@ void Command_ObjectPlace_f(void); void Command_Writethings_f(void); extern consvar_t cv_opflags, cv_mapthingnum, cv_speed; -//extern consvar_t cv_snapto, cv_grid; extern boolean objectplacing; extern mobjtype_t op_currentthing; @@ -48,18 +47,10 @@ void Command_CheatNoClip_f(void); void Command_CheatGod_f(void); void Command_CheatNoTarget_f(void); void Command_Savecheckpoint_f(void); -/*void Command_Getallemeralds_f(void); -void Command_Resetemeralds_f(void); -void Command_Setrings_f(void); -void Command_Setlives_f(void); -void Command_Setcontinues_f(void);*/ void Command_Devmode_f(void); void Command_Scale_f(void); void Command_Gravflip_f(void); void Command_Hurtme_f(void); -/*void Command_JumpToAxis_f(void); -void Command_Charability_f(void); -void Command_Charspeed_f(void);*/ void Command_Teleport_f(void); void Command_RTeleport_f(void); void Command_Skynum_f(void); diff --git a/src/m_cond.c b/src/m_cond.c index acf78e6ef..85c0b5ee2 100644 --- a/src/m_cond.c +++ b/src/m_cond.c @@ -235,7 +235,7 @@ void M_AddRawCondition(UINT8 set, UINT8 id, conditiontype_t c, INT32 r, INT16 x1 wnum = conditionSets[set - 1].numconditions; num = ++conditionSets[set - 1].numconditions; - conditionSets[set - 1].condition = Z_Realloc(conditionSets[set - 1].condition, sizeof(condition_t)*num, PU_STATIC, 0); + conditionSets[set - 1].condition = Z_Realloc(conditionSets[set - 1].condition, sizeof(condition_t)*num, PU_STATIC, NULL); cond = conditionSets[set - 1].condition; @@ -248,12 +248,9 @@ void M_AddRawCondition(UINT8 set, UINT8 id, conditiontype_t c, INT32 r, INT16 x1 void M_ClearConditionSet(UINT8 set) { - if (conditionSets[set - 1].numconditions) - { - Z_Free(conditionSets[set - 1].condition); - conditionSets[set - 1].condition = NULL; - conditionSets[set - 1].numconditions = 0; - } + Z_Free(conditionSets[set - 1].condition); + conditionSets[set - 1].condition = NULL; + conditionSets[set - 1].numconditions = 0; conditionSets[set - 1].achieved = false; } @@ -482,32 +479,13 @@ UINT8 M_CheckLevelEmblems(void) // Update Score, Time, Rings emblems for (i = 0; i < numemblems; ++i) { - if (emblemlocations[i].type <= ET_SKIN || emblemlocations[i].collected) + // Requires time on map <= x + if (emblemlocations[i].type != ET_TIME || emblemlocations[i].collected) continue; levelnum = emblemlocations[i].level; valToReach = emblemlocations[i].var; - - switch (emblemlocations[i].type) - { - /*case ET_SCORE: // Requires score on map >= x - res = (G_GetBestScore(levelnum) >= (unsigned)valToReach); - break;*/ - case ET_TIME: // Requires time on map <= x - res = (G_GetBestTime(levelnum) <= (unsigned)valToReach); - break; - /*case ET_RINGS: // Requires rings on map >= x - res = (G_GetBestRings(levelnum) >= valToReach); - break; - case ET_NGRADE: // Requires NiGHTS grade on map >= x - res = (G_GetBestNightsGrade(levelnum, 0) >= valToReach); - break; - case ET_NTIME: // Requires NiGHTS time on map <= x - res = (G_GetBestNightsTime(levelnum, 0) <= (unsigned)valToReach); - break;*/ - default: // unreachable but shuts the compiler up. - continue; - } + res = (G_GetBestTime(levelnum) <= (unsigned)valToReach); emblemlocations[i].collected = res; if (res) diff --git a/src/m_cond.h b/src/m_cond.h index 06bf30faf..48ff8b9c5 100644 --- a/src/m_cond.h +++ b/src/m_cond.h @@ -27,21 +27,11 @@ typedef enum UC_MATCHESPLAYED, // SRB2Kart: MATCHESPLAYED [x played] UC_GAMECLEAR, // GAMECLEAR UC_ALLEMERALDS, // ALLEMERALDS - //UC_ULTIMATECLEAR, // ULTIMATECLEAR - //UC_OVERALLSCORE, // OVERALLSCORE [score to beat] UC_OVERALLTIME, // OVERALLTIME [time to beat, tics] - //UC_OVERALLRINGS, // OVERALLRINGS [rings to beat] UC_MAPVISITED, // MAPVISITED [map number] UC_MAPBEATEN, // MAPBEATEN [map number] UC_MAPALLEMERALDS, // MAPALLEMERALDS [map number] - //UC_MAPULTIMATE, // MAPULTIMATE [map number] - //UC_MAPPERFECT, // MAPPERFECT [map number] - //UC_MAPSCORE, // MAPSCORE [map number] [score to beat] UC_MAPTIME, // MAPTIME [map number] [time to beat, tics] - //UC_MAPRINGS, // MAPRINGS [map number] [rings to beat] - //UC_NIGHTSSCORE, // NIGHTSSCORE [map number] [score to beat] - //UC_NIGHTSTIME, // NIGHTSTIME [map number] [time to beat, tics] - //UC_NIGHTSGRADE, // NIGHTSGRADE [map number] [grade] UC_TRIGGER, // TRIGGER [trigger number] UC_TOTALEMBLEMS, // TOTALEMBLEMS [number of emblems] UC_EMBLEM, // EMBLEM [emblem number] diff --git a/src/m_curl.c b/src/m_curl.c index 77588a3fb..f7ff29955 100644 --- a/src/m_curl.c +++ b/src/m_curl.c @@ -11,7 +11,7 @@ #include "m_curl.h" #include "doomtype.h" -#include "i_system.h" // I_OutputMsg +#include "doomdef.h" // I_OutputMsg #include "m_argv.h" // M_CheckParm, M_GetNextParm static boolean curl_args_init = false; diff --git a/src/m_emotes.cpp b/src/m_emotes.cpp index 515799af3..fe90c9a11 100644 --- a/src/m_emotes.cpp +++ b/src/m_emotes.cpp @@ -278,7 +278,7 @@ void M_DrawScaledEmote(fixed_t x, fixed_t y, fixed_t scale, emote_t *emote, INT3 static void Command_ListEmotes_f(void) { const int EMOTES_PER_PAGE = 24; - const int NUMPAGES = std::max(emotes.size()/EMOTES_PER_PAGE, 1); + const int NUMPAGES = emotes.size()/EMOTES_PER_PAGE + (emotes.size() % EMOTES_PER_PAGE != 0 ? 1 : 0); int page = 1; if (COM_Argc() > 1) diff --git a/src/m_emotes.h b/src/m_emotes.h index 594e219f8..d87dd438f 100644 --- a/src/m_emotes.h +++ b/src/m_emotes.h @@ -12,14 +12,14 @@ #ifndef __M_EMOTES__ #define __M_EMOTES__ -#ifdef __cplusplus -extern "C" { -#endif - #include "doomdef.h" #include "m_fixed.h" #include "command.h" +#ifdef __cplusplus +extern "C" { +#endif + extern consvar_t cv_emotes; #define MAXEMOTENAME 32 diff --git a/src/m_fixed.c b/src/m_fixed.c index d7aa13254..3bab22815 100644 --- a/src/m_fixed.c +++ b/src/m_fixed.c @@ -62,6 +62,9 @@ FUNCMATH fixed_t FixedHypot(fixed_t x, fixed_t y) angle_t angle; fixed_t dist; + I_Assert(x != INT32_MIN); + I_Assert(y != INT32_MIN); + x = abs(x); y = abs(y); @@ -77,6 +80,10 @@ FUNCMATH fixed_t FixedHypot(fixed_t x, fixed_t y) if (!y) return x; + // prevent underflow + if (y == INT32_MIN) + return INT32_MAX; + angle = (tantoangle[FixedDiv(y, x)>>DBITS] + ANGLE_90) >> ANGLETOFINESHIFT; // use as cosine diff --git a/src/m_fixed.h b/src/m_fixed.h index c0afae941..894e2b1cc 100644 --- a/src/m_fixed.h +++ b/src/m_fixed.h @@ -265,35 +265,6 @@ FUNCMATH FUNCINLINE static ATTRINLINE fixed_t FixedRound(fixed_t x) return INT32_MAX; } -/** \brief The xs_CRoundToInt function - - \param val double number - - \return Round toward nearest, but ties round toward even -*/ -#if defined(SRB2_BIG_ENDIAN) - #define _xs_iexp_ 0 - #define _xs_iman_ 1 -#else - #define _xs_iexp_ 1 //intel is little endian - #define _xs_iman_ 0 -#endif //BigEndian_ - -typedef double real64; - -typedef union _xs_doubleints -{ - real64 val; - unsigned ival[2]; -} _xs_doubleints; - -FUNCMATH FUNCINLINE static ATTRINLINE int xs_CRoundToInt(real64 val) -{ - _xs_doubleints uval; - uval.val = val + 6755399441055744.0; - return uval.ival[_xs_iman_]; -} - typedef struct { fixed_t x; diff --git a/src/m_menu.c b/src/m_menu.c index bfe2372bf..4a8344b3d 100644 --- a/src/m_menu.c +++ b/src/m_menu.c @@ -12,6 +12,8 @@ /// \file m_menu.c /// \brief XMOD's extremely revamped menu system. +#include "screen.h" +#include "tables.h" #ifdef __GNUC__ #include #endif @@ -23,6 +25,7 @@ #include "d_netcmd.h" #include "d_clisrv.h" #include "i_net.h" +#include "i_system.h" #include "console.h" #include "r_fps.h" #include "r_local.h" @@ -147,13 +150,8 @@ M_waiting_mode_t m_waiting_mode = M_NOT_WAITING; const char *quitmsg[NUM_QUITMESSAGES] = {}; -// Stuff for customizing the player select screen Tails 09-22-2003 -description_t description[MAXSKINS] = {}; - INT32 mapwads[NUMMAPS] = {}; -boolean browselocalskins = false; - boolean menuactive = false; boolean fromlevelselect = false; @@ -184,8 +182,8 @@ static INT16 itemOn = 1; // menu item skull is on, Hack by Tails 09-18-2002 static INT16 skullAnimCounter = 10; // skull animation counter static boolean interpTimerHackAllow = 0; -static UINT8 setupcontrolplayer; -static INT32 (*setupcontrols)[2]; // pointer to the gamecontrols of the player being edited +static UINT8 setupcontrolplayer; +static INT32 (*setupcontrols)[2]; // pointer to the gamecontrols of the player being edited // shhh... what am I doing... nooooo! static INT32 vidm_testingmode = 0; @@ -199,8 +197,8 @@ static char setupm_ip[64]; static textinput_t setupm_input_ip; -static fixed_t multi_tics; -static state_t *multi_state; +static fixed_t multi_tics; +static state_t *multi_state; // this is set before entering the MultiPlayer setup menu, // for either player 1 or 2 @@ -215,12 +213,19 @@ static INT32 setupm_fakeskin; static INT32 setupm_fakecolor; static UINT8 setupm_pselect = 1; -//variables used for other skin select menus +// variables used for other skin select menus static UINT8 setupm_skinypos; static INT32 setupm_skinselect; static boolean setupm_skinlockedselect; -static UINT8 setupm_playernum; //brap +static UINT8 setupm_playernum; // brap + +// Addons Menu: Local mode +static void M_LocalAddons(INT32 choice); +static boolean addons_localmode = false; + +#define LOCALMODE_KEY (KEY_RALT) +#define AUTOLOAD_KEY (KEY_END) // // PROTOTYPES @@ -272,6 +277,8 @@ static void M_ConfirmTeamChange(INT32 choice); static void M_ConfirmSpectateChange(INT32 choice); static void M_QuitSRB2(INT32 choice); +static void M_SaturnReportIssue(INT32 choice); + // Single Player static void M_TimeAttack(INT32 choice); static boolean M_QuitTimeAttackMenu(void); @@ -326,7 +333,6 @@ static void M_EraseData(INT32 choice); static void M_AddonsInternal(); static void M_Addons(INT32 choice); -static void M_LocalSkins(INT32 choice); static void M_AddonsOptions(INT32 choice); #define addonmenusize 9 // number of items actually displayed in the addons menu view, formerly (2*numaddonsshown + 1) #define numaddonsshown 4 // number of items to each side of the currently selected item, unless at top/bottom ends of directory @@ -410,6 +416,7 @@ static INT32 M_GetFirstLevelInList(void); // crap to force hud to show when in saturns hud options boolean forceshowhud = false; +boolean forceshowchat = false; // smol text indicating if game is modified // so ppl dont wonder where their ra times went and stuff @@ -448,13 +455,13 @@ consvar_t cv_showallmaps = {"showallmaps", "No", CV_SAVE, CV_YesNo, NULL, 0, NUL consvar_t cv_showmusicfilename = {"showmusicfilename", "No", CV_SAVE, CV_YesNo, NULL, 0, NULL, NULL, 0, 0, NULL}; static CV_PossibleValue_t serversort_cons_t[] = { - {0,"Ping"}, - {1,"Modified State"}, - {2,"Most Players"}, - {3,"Least Players"}, - {4,"Max Player Slots"}, - {5,"Gametype"}, - {0,NULL} + {0, "Ping"}, + {1, "Modified State"}, + {2, "Most Players"}, + {3, "Least Players"}, + {4, "Max Player Slots"}, + {5, "Gametype"}, + {0, NULL} }; consvar_t cv_serversort = {"serversort", "Ping", CV_CALL, serversort_cons_t, M_SortServerList, 0, NULL, NULL, 0, 0, NULL}; @@ -497,32 +504,6 @@ static consvar_t cv_dummystaff = {"dummystaff", "0", CV_HIDEN|CV_CALL, dummystaf // all the menu definitions and onchanges reside in here now #include "m_menudefs.c" -static INT32 M_ShiftChar(INT32 ch) -{ - if (I_UseNativeKeyboard()) - return ch; - - if (cv_keyboardlayout.value == 3) - { - if (ch >= 32 && ch <= 141) - { - if (shiftdown) - ch = shiftxform[ch]; - else if (altdown & 0x2) - ch = french_altgrxform[ch]; - else - ch = HU_FallBackFrSpecialLetter(ch); - } - } - else - { - if (shiftdown && ch >= 32 && ch <= 127) - ch = shiftxform[ch]; - } - - return ch; -} - // // M_GetGametypeColor // @@ -635,7 +616,7 @@ void Nextmap_OnChange(void) if (!gpath) return; - sprintf(gpath,"%s"PATHSEP"replay"PATHSEP"%s"PATHSEP"%s", srb2home, timeattackfolder, G_BuildMapName(cv_nextmap.value)); + snprintf(gpath, glen, "%s"PATHSEP"replay"PATHSEP"%s"PATHSEP"%s", srb2home, timeattackfolder, G_BuildMapName(cv_nextmap.value)); CV_StealthSetValue(&cv_dummystaff, 0); @@ -729,7 +710,7 @@ static void Dummystaff_OnChange(void) dummystaffname[0] = '\0'; - if ((l = W_CheckNumForName(va("%sS01",G_BuildMapName(cv_nextmap.value)))) == LUMPERROR) + if ((l = W_CheckNumForName(va("%sS01", G_BuildMapName(cv_nextmap.value)))) == LUMPERROR) { CV_StealthSetValue(&cv_dummystaff, 0); return; @@ -738,7 +719,7 @@ static void Dummystaff_OnChange(void) { char *temp = dummystaffname; UINT8 numstaff = 1; - while (numstaff < 99 && (l = W_CheckNumForName(va("%sS%02u",G_BuildMapName(cv_nextmap.value),numstaff+1))) != LUMPERROR) + while (numstaff < 99 && (l = W_CheckNumForName(va("%sS%02u", G_BuildMapName(cv_nextmap.value), numstaff+1))) != LUMPERROR) numstaff++; if (cv_dummystaff.value < 1) @@ -746,7 +727,7 @@ static void Dummystaff_OnChange(void) else if (cv_dummystaff.value > numstaff) CV_StealthSetValue(&cv_dummystaff, 1); - if ((l = W_CheckNumForName(va("%sS%02u",G_BuildMapName(cv_nextmap.value), cv_dummystaff.value))) == LUMPERROR) + if ((l = W_CheckNumForName(va("%sS%02u", G_BuildMapName(cv_nextmap.value), cv_dummystaff.value))) == LUMPERROR) return; // shouldn't happen but might as well check... G_UpdateStaffGhostName(l); @@ -754,7 +735,7 @@ static void Dummystaff_OnChange(void) while (*temp) temp++; - sprintf(temp, " - %d", cv_dummystaff.value); + snprintf(temp, sizeof(dummystaffname) - (size_t)(temp - dummystaffname), " - %d", cv_dummystaff.value); } } @@ -831,7 +812,8 @@ static void M_ChangeCvar(INT32 choice) CV_SetValue(cv,skins[skinno].prefcolor); return; } - CV_Set(cv,cv->defaultvalue); + + CV_Set(cv, cv->defaultvalue); return; } @@ -843,7 +825,8 @@ static void M_ChangeCvar(INT32 choice) float increment; increment = FIXED_TO_FLOAT(cv->value)+(choice)*((currentMenu->menuitems[itemOn].status & IT_CV_BIGFLOAT) ? 0.5f : (1.0f/16.0f)); - sprintf(s,"%ld%s",(long)increment,M_Ftrim(increment)); + snprintf(s, sizeof(s), "%ld%s", (long)increment, M_Ftrim(increment)); + CV_Set(cv, s); } else @@ -980,6 +963,7 @@ static void Command_Manual_f(void) { if (modeattacking) return; + M_StartControlPanel(); M_Manual(INT32_MAX); itemOn = 0; @@ -1022,9 +1006,9 @@ boolean M_Responder(event_t *ev) //case KEY_JOY1 + 2: ch = KEY_ENTER; break; - /*case KEY_JOY1 + 3: // Brake can function as 'n' for message boxes now. - ch = 'n'; - break;*/ + /*case KEY_JOY1 + 3: // Brake can function as 'n' for message boxes now. + ch = 'n'; + break;*/ case KEY_MOUSE1 + 1: //case KEY_JOY1 + 1: ch = KEY_BACKSPACE; @@ -1041,6 +1025,24 @@ boolean M_Responder(event_t *ev) case KEY_HAT1 + 3: ch = KEY_RIGHTARROW; break; + //Local Addon Mode + case LOCALMODE_KEY: + { + if (!(server || IsPlayerAdmin(consoleplayer))) + break; + + if (!addons_localmode) + { + S_StartSound(NULL, sfx_ding); + addons_localmode = true; + } + else + { + S_StartSound(NULL, sfx_jshard); + addons_localmode = false; + } + } + break; } } else if (menuactive) @@ -1052,11 +1054,12 @@ boolean M_Responder(event_t *ev) const INT32 jxdeadzone = ((JOYAXISRANGE-1) * max(cv_xdeadzone[0].value, FRACUNIT/2)) >> FRACBITS; const INT32 jydeadzone = ((JOYAXISRANGE-1) * max(cv_ydeadzone[0].value, FRACUNIT/2)) >> FRACBITS; INT32 accelaxis = abs(cv_moveaxis[0].value); + if (ev->data1 == 0) { if (ev->data3 != INT32_MAX) { - if (Joystick[0].bGamepadStyle || abs(ev->data3) > jydeadzone) + if (DigitalGamepadStyle(0) || abs(ev->data3) > jydeadzone) { if (joywaity < thistime && (pjoyy == 0 || (ev->data3 < 0) != (pjoyy < 0))) // no previous direction OR change direction @@ -1072,7 +1075,7 @@ boolean M_Responder(event_t *ev) if (ev->data2 != INT32_MAX && joywaitx < thistime) { - if (Joystick[0].bGamepadStyle || abs(ev->data2) > jxdeadzone) + if (DigitalGamepadStyle(0) || abs(ev->data2) > jxdeadzone) { if (joywaitx < thistime && (pjoyx == 0 || (ev->data2 < 0) != (pjoyx < 0))) // no previous direction OR change direction @@ -1091,19 +1094,22 @@ boolean M_Responder(event_t *ev) // The following borrows heavily from Joy1Axis. const boolean xmode = (accelaxis%2); INT32 retaxis = 0; + if (!xmode) accelaxis--; accelaxis /= 2; + if (ev->data1 == accelaxis) { const INT32 jacceldeadzone = xmode ? jxdeadzone : jydeadzone; retaxis = xmode ? ev->data2 : ev->data3; + if (retaxis != INT32_MAX) { if (cv_moveaxis[0].value < 0) retaxis = -retaxis; - if (Joystick[0].bGamepadStyle || retaxis > jacceldeadzone) + if (DigitalGamepadStyle(0) || retaxis > jacceldeadzone) { if (joywaitaccel < thistime && retaxis > pjoyaccel) // only on upwards event { @@ -1251,7 +1257,7 @@ boolean M_Responder(event_t *ev) // Handle menuitems which need a specific key handling if (routine && (currentMenu->menuitems[itemOn].status & IT_TYPE) == IT_KEYHANDLER) { - ch = M_ShiftChar(ch); + ch = CON_ShiftChar(ch); routine(ch); return true; } @@ -1281,6 +1287,7 @@ boolean M_Responder(event_t *ev) void (*otherroutine)(event_t *sev) = currentMenu->menuitems[itemOn].itemaction; otherroutine(ev); //Alam: what a hack } + return true; } } @@ -1303,12 +1310,21 @@ boolean M_Responder(event_t *ev) { playback_last_menu_interaction_leveltime = leveltime; // Flip left/right with up/down for the playback menu, since it's a horizontal icon row. + switch (ch) { - case KEY_LEFTARROW: ch = KEY_UPARROW; break; - case KEY_UPARROW: ch = KEY_RIGHTARROW; break; - case KEY_RIGHTARROW: ch = KEY_DOWNARROW; break; - case KEY_DOWNARROW: ch = KEY_LEFTARROW; break; + case KEY_LEFTARROW: + ch = KEY_UPARROW; + break; + case KEY_UPARROW: + ch = KEY_RIGHTARROW; + break; + case KEY_RIGHTARROW: + ch = KEY_DOWNARROW; + break; + case KEY_DOWNARROW: + ch = KEY_LEFTARROW; + break; // arbitrary keyboard shortcuts because fuck you @@ -1359,7 +1375,8 @@ boolean M_Responder(event_t *ev) G_AdjustView(4, 1, true); break; - default: break; + default: + break; } } @@ -1484,6 +1501,7 @@ boolean M_Responder(event_t *ev) } return false; + break; default: CON_Responder(ev); @@ -1590,11 +1608,16 @@ static boolean ShouldDrawMenuBG(void) if (forceshowhud) return false; + if (forceshowchat) + return false; + // camera options stuff, only do when in level if (gamestate == GS_LEVEL && - (currentMenu == &OP_CamOptionsDef || currentMenu == &OP_Player1CamOptionsDef - || currentMenu == &OP_Player2CamOptionsDef || currentMenu == &OP_Player3CamOptionsDef - || currentMenu == &OP_Player4CamOptionsDef)) + (currentMenu == &OP_CamOptionsDef || + currentMenu == &OP_Player1CamOptionsDef || + currentMenu == &OP_Player2CamOptionsDef || + currentMenu == &OP_Player3CamOptionsDef || + currentMenu == &OP_Player4CamOptionsDef)) return false; return true; @@ -1610,7 +1633,9 @@ void M_Drawer(void) if (currentMenu == &MessageDef) menuactive = true; + // pain and suffering forceshowhud = (gamestate == GS_LEVEL && menuactive && (currentMenu == &OP_SaturnHudDef || currentMenu == &OP_HudOffsetDef || currentMenu == &OP_NametagDef || currentMenu == &OP_DriftGaugeDef)); // holy fuick + forceshowchat = (gamestate == GS_LEVEL && menuactive && currentMenu == &OP_ChatOptionsDef && (!OLDCHAT) && (itemOn == op_chat_boxwidth || itemOn == op_chat_boxheight || itemOn == op_chat_xoffs || itemOn == op_chat_yoffs || itemOn == op_chat_charlmt)); // man i dont gaf anymore lmao if (menuactive) { @@ -1729,19 +1754,16 @@ void M_StartControlPanel(void) MPauseMenu[mpause_switchteam].status = IT_DISABLED; MPauseMenu[mpause_switchspectate].status = IT_DISABLED; MPauseMenu[mpause_psetup].status = IT_DISABLED; + MPauseMenu[mpause_localaddons].status = IT_STRING | IT_CALL; + MISC_ChangeTeamMenu[0].status = IT_DISABLED; MISC_ChangeSpectateMenu[0].status = IT_DISABLED; - MPauseMenu[mpause_addlocalskins].status = IT_STRING | IT_CALL; MPauseMenu[mpause_localskin].status = IT_STRING | IT_CALL; // Reset these in case splitscreen messes things up MPauseMenu[mpause_addons].alphaKey = 8; - - if (IsPlayerAdmin(consoleplayer)) - MPauseMenu[mpause_addlocalskins].alphaKey = 16; - else - MPauseMenu[mpause_addlocalskins].alphaKey = 24; + MPauseMenu[mpause_localaddons].alphaKey = 24; MPauseMenu[mpause_scramble].alphaKey = 8; MPauseMenu[mpause_switchmap].alphaKey = 24; @@ -1759,14 +1781,13 @@ void M_StartControlPanel(void) { MPauseMenu[mpause_switchmap].status = IT_STRING | IT_CALL; MPauseMenu[mpause_addons].status = IT_STRING | IT_CALL; - + MPauseMenu[mpause_localaddons].status = IT_DISABLED; if (G_GametypeHasTeams()) MPauseMenu[mpause_scramble].status = IT_STRING | IT_SUBMENU; } if (server || (!cv_showlocalskinmenus.value)) { - MPauseMenu[mpause_addlocalskins].status = IT_DISABLED; MPauseMenu[mpause_localskin].status = IT_DISABLED; MPauseMenu[mpause_options].alphaKey = 64; @@ -1774,7 +1795,6 @@ void M_StartControlPanel(void) MPauseMenu[mpause_quit].alphaKey = 88; } - if (splitscreen) { MPauseMenu[mpause_psetupsplit].status = MPauseMenu[mpause_psetupsplit2].status = IT_STRING | IT_CALL; @@ -1983,8 +2003,6 @@ void M_Ticker(void) // void M_Init(void) { - UINT8 i; - COM_AddCommand("manual", Command_Manual_f); CV_RegisterVar(&cv_nextmap); @@ -2030,15 +2048,6 @@ void M_Init(void) quitmsg[QUIT3MSG5] = M_GetText("You'll be back to play soon, though...\n...right?\n\n(Press 'Y' to quit)"); quitmsg[QUIT3MSG6] = M_GetText("Aww, is Eggman's Nightclub too\ndifficult for you?\n\n(Press 'Y' to quit)"); - // Setup PlayerMenu table - for (i = 0; i < MAXSKINS; i++) - { - PlayerMenu[i].status = (i == 0 ? IT_CALL : IT_DISABLED); - PlayerMenu[i].patch = PlayerMenu[i].text = NULL; - PlayerMenu[i].itemaction = M_ChoosePlayer; - PlayerMenu[i].alphaKey = 0; - } - #ifdef HWRENDER // Permanently hide some options based on render mode if (rendermode == render_soft) @@ -2062,7 +2071,6 @@ void M_Init(void) OP_OpenGLOptionsMenu[op_gl_shader].status = IT_GRAYEDOUT; OP_OpenGLOptionsMenu[op_gl_lightdither].status = IT_GRAYEDOUT; OP_OpenGLOptionsMenu[op_gl_palrender].status = IT_GRAYEDOUT; - OP_OpenGLOptionsMenu[op_gl_flashpal].status = IT_GRAYEDOUT; OP_ExpOptionsMenu[op_exp_paldepth].status = IT_GRAYEDOUT; } @@ -2094,55 +2102,6 @@ void M_Init(void) M_TextInputInit(&menuinput, menu_text_input_buf, sizeof menu_text_input_buf); } -void M_InitCharacterTables(void) -{ - UINT8 i; - - // Setup PlayerMenu table - for (i = 0; i < MAXSKINS; i++) - { - PlayerMenu[i].status = (i < 4 ? IT_CALL : IT_DISABLED); - PlayerMenu[i].patch = PlayerMenu[i].text = NULL; - PlayerMenu[i].itemaction = M_ChoosePlayer; - PlayerMenu[i].alphaKey = 0; - } - - // Setup description table - for (i = 0; i < MAXSKINS; i++) - { - if (i == 0) - { - strcpy(description[i].notes, "\x82Sonic\x80 is the fastest of the three, but also the hardest to control. Beginners beware, but experts will find Sonic very powerful.\n\n\x82""Ability:\x80 Speed Thok\nDouble jump to zoom forward with a huge burst of speed.\n\n\x82Tip:\x80 Simply letting go of forward does not slow down in SRB2. To slow down, hold the opposite direction."); - strcpy(description[i].picname, ""); - strcpy(description[i].skinname, "sonic"); - } - else if (i == 1) - { - strcpy(description[i].notes, "\x82Tails\x80 is the most mobile of the three, but has the slowest speed. Because of his mobility, he's well-\nsuited to beginners.\n\n\x82""Ability:\x80 Fly\nDouble jump to start flying for a limited time. Repetitively hit the jump button to ascend.\n\n\x82Tip:\x80 To quickly descend while flying, hit the spin button."); - strcpy(description[i].picname, ""); - strcpy(description[i].skinname, "tails"); - } - else if (i == 2) - { - strcpy(description[i].notes, "\x82Knuckles\x80 is well-\nrounded and can destroy breakable walls simply by touching them, but he can't jump as high as the other two.\n\n\x82""Ability:\x80 Glide & Climb\nDouble jump to glide in the air as long as jump is held. Glide into a wall to climb it.\n\n\x82Tip:\x80 Press spin while climbing to jump off the wall; press jump instead to jump off\nand face away from\nthe wall."); - strcpy(description[i].picname, ""); - strcpy(description[i].skinname, "knuckles"); - } - else if (i == 3) - { - strcpy(description[i].notes, "\x82Sonic & Tails\x80 team up to take on Dr. Eggman!\nControl Sonic while Tails desperately struggles to keep up.\n\nPlayer 2 can control Tails directly by setting the controls in the options menu.\nTails's directional controls are relative to Player 1's camera.\n\nTails can pick up Sonic while flying and carry him around."); - strcpy(description[i].picname, "CHRS&T"); - strcpy(description[i].skinname, "sonic&tails"); - } - else - { - strcpy(description[i].notes, "???"); - strcpy(description[i].picname, ""); - strcpy(description[i].skinname, ""); - } - } -} - // ========================================================================== // SPECIAL MENU OPTION DRAW ROUTINES GO HERE // ========================================================================== @@ -2868,8 +2827,9 @@ static void M_DrawCenteredMenu(void) static inline size_t M_StringHeight(const char *string) { size_t h = 8, i; + const size_t strlength = strlen(string); - for (i = 0; i < strlen(string); i++) + for (i = 0; i < strlength; i++) if (string[i] == '\n') h += 8; @@ -2933,7 +2893,7 @@ static void M_PrepareLevelSelect(void) boolean M_CanShowLevelInList(INT32 mapnum, INT32 gt) { // invalid mapnum - if (mapnum < -1) + if (mapnum < -1 || mapnum >= NUMMAPS) return false; // Random map! @@ -3379,14 +3339,14 @@ static void M_AddonsInternal(void) static void M_Addons(INT32 choice) { (void)choice; - browselocalskins = false; + addons_localmode = false; M_AddonsInternal(); } -static void M_LocalSkins(INT32 choice) +static void M_LocalAddons(INT32 choice) { (void)choice; - browselocalskins = true; + addons_localmode = true; M_AddonsInternal(); } @@ -3555,8 +3515,8 @@ static void M_DrawAddons(void) if (Playing()) { - if (browselocalskins) - V_DrawCenteredString(BASEVIDWIDTH/2, 5, V_ALLOWLOWERCASE, "Load \x83local skins\x80 from addons!"); + if (addons_localmode) // Draw notice that you're adding locally + V_DrawCenteredString(BASEVIDWIDTH/2, 5, V_ALLOWLOWERCASE, "Load addons or \x83local skins\x80 locally!"); else V_DrawCenteredString(BASEVIDWIDTH/2, 5, warningflags, "Adding files mid-game may cause problems."); } @@ -3719,7 +3679,10 @@ static void M_DrawAddons(void) //m = numwadfiles-(mainwads+2+1); //V_DrawCenteredString(BASEVIDWIDTH/2, y+24, (majormods ? highlightflags : V_TRANSLUCENT), va("%d ADD-ON%s LOADED", (int)m, (m == 1) ? "" : "S")); //+2 for music, sounds, +1 for main.kart - V_DrawThinString(0, BASEVIDHEIGHT-10, V_SNAPTOBOTTOM|V_SNAPTOLEFT|V_TRANSLUCENT|V_ALLOWLOWERCASE, ("END Key - Add addon to autoload")); + V_DrawThinString(0, BASEVIDHEIGHT-10, V_SNAPTOBOTTOM|V_SNAPTOLEFT|V_TRANSLUCENT|V_ALLOWLOWERCASE, va("%s Key - Add addon to autoload", G_KeynumToString(AUTOLOAD_KEY))); + + if (Playing() && (server || IsPlayerAdmin(consoleplayer))) + V_DrawThinString(0, BASEVIDHEIGHT-20, V_SNAPTOBOTTOM|V_SNAPTOLEFT|V_TRANSLUCENT|V_ALLOWLOWERCASE, va("%s Key - Switch to local addon mode", G_KeynumToString(LOCALMODE_KEY))); } static void M_AddonExec(INT32 ch) @@ -3741,7 +3704,7 @@ static void M_AddonAutoLoad(INT32 ch) FILE *autoloadconfigfile; // check our controls // - if (ch != 'y' && ch != KEY_ENTER && ch != KEY_END) + if (ch != 'y' && ch != KEY_ENTER && ch != AUTOLOAD_KEY) { S_StartSound(NULL, sfx_s26d); return; @@ -3755,7 +3718,7 @@ static void M_AddonAutoLoad(INT32 ch) switch (dirmenu[dir_on[menudepthleft]][DIR_TYPE]) { case EXT_FOLDER: - M_StartMessage(va("%c%s\x80\nAutoloading folders is not supported as of yet. \n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), dirmenu[dir_on[menudepthleft]]+DIR_STRING),NULL,MM_NOTHING); + M_StartMessage(va("%c%s\x80\nAutoloading folders is not supported as of yet. \n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), dirmenu[dir_on[menudepthleft]]+DIR_STRING), NULL, MM_NOTHING); break; case EXT_TXT: case EXT_CFG: @@ -3896,7 +3859,7 @@ static void M_HandleAddons(INT32 choice) } break; case EXT_TXT: - M_StartMessage(va("%c%s\x80\nThis file may not be a console script.\nAttempt to run anyways? \n\n(Press 'Y' to confirm)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), dirmenu[dir_on[menudepthleft]]+DIR_STRING),M_AddonExec,MM_YESNO); + M_StartMessage(va("%c%s\x80\nThis file may not be a console script.\nAttempt to run anyways? \n\n(Press 'Y' to confirm)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), dirmenu[dir_on[menudepthleft]]+DIR_STRING), M_AddonExec, MM_YESNO); break; case EXT_CFG: M_AddonExec(KEY_ENTER); @@ -3909,30 +3872,40 @@ static void M_HandleAddons(INT32 choice) case EXT_KART: #endif case EXT_PK3: - if (browselocalskins) { - if (DumbStartsWith("KC_", dirmenu[dir_on[menudepthleft]]+DIR_STRING) || DumbStartsWith("kc_", dirmenu[dir_on[menudepthleft]]+DIR_STRING)) { - M_StartMessage(va("%c%s\x80\nYou are loading a local skin.\nLocal skins will not be usable\nafter going back from\nthe title screen.\n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), dirmenu[dir_on[menudepthleft]]+DIR_STRING),NULL,MM_NOTHING); - COM_BufAddText(va("addfilelocal \"%s%s\"", menupath, dirmenu[dir_on[menudepthleft]]+DIR_STRING)); + const char *addonname = dirmenu[dir_on[menudepthleft]]+DIR_STRING; + + if (addons_localmode) + { + if (DumbStartsWith("KC_", addonname) || DumbStartsWith("kc_", addonname)) + { + M_StartMessage(va("%c%s\x80\nYou are loading a local skin.\nLocal skins will not be usable\nafter going back from\nthe title screen.\n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), addonname), NULL, MM_NOTHING); + } + else if (DumbStartsWith("KCL_", addonname) || DumbStartsWith("kcl_", addonname)) // skins with lua + { + M_StartMessage(va("%c%s\x80\nYou are loading a local skin with lua.\nBeware that this may cause issues like crashes or desyncs in some cases!\nLocal skins will not be usable\nafter going back from\nthe title screen.\n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), addonname), NULL, MM_NOTHING); + } + // no need to account for KRC cases + + COM_BufAddText(va("addfilelocal \"%s%s\"", menupath, addonname)); } else - S_StartSound(NULL, sfx_s26d); - } - else - { - COM_BufAddText(va("addfile \"%s%s\"", menupath, dirmenu[dir_on[menudepthleft]]+DIR_STRING)); + { + COM_BufAddText(va("addfile \"%s%s\"", menupath, addonname)); + } } break; default: S_StartSound(NULL, sfx_s26d); } } + if (refresh) refreshdirmenu |= REFRESHDIR_NORMAL; } break; - case KEY_END: + case AUTOLOAD_KEY: { boolean refresh = true; if (!dirmenu[dir_on[menudepthleft]]) @@ -3999,6 +3972,8 @@ static void M_HandleAddons(INT32 choice) M_SetupNextMenu(currentMenu->prevMenu); else M_ClearMenus(true); + + addons_localmode = false; //Exiting this menu, disable addons_localmode already. } } @@ -4013,16 +3988,16 @@ boolean replaynamesloaded = false; #ifdef HAVE_THREADS I_mutex replayquerymutex; -// g_in_exiting_signal_handler is an evil hack +// I_In_Exiting_Signal_Handler is an evil hack // to avoid infinite SIGABRT recursion in the signal handler // due to poisoned locks or mach-o kernel not supporting locks in signals // or something like that. idk -# define Lock_search_state() if (!g_in_exiting_signal_handler) { I_lock_mutex(&replayquerymutex); } -# define Unlock_search_state() if (!g_in_exiting_signal_handler) { I_unlock_mutex(replayquerymutex); } -#else/*HAVE_THREADS*/ +# define Lock_search_state() if (!I_In_Exiting_Signal_Handler()) { I_lock_mutex(&replayquerymutex); } +# define Unlock_search_state() if (!I_In_Exiting_Signal_Handler()) { I_unlock_mutex(replayquerymutex); } +#else /*HAVE_THREADS*/ # define Lock_search_state() # define Unlock_search_state() -#endif/*HAVE_THREADS*/ +#endif /*HAVE_THREADS*/ #define MAXREPLAYQUERY 37 @@ -4110,6 +4085,9 @@ static void AddCheckedReplay(void) // Check up to maxnum replays if they match with query static void M_HutCheckReplays(size_t maxnum) { + // Stripped of color codes + char demo_title[sizeof(demolist_all[0].title)]; + if (!replaynamesloaded) return; @@ -4142,7 +4120,9 @@ static void M_HutCheckReplays(size_t maxnum) case MD_NOTLOADED: case MD_OUTDATED: case MD_LOADED: - if (demolist_all[replayquerycheck].title[0] && strcasestr(demolist_all[replayquerycheck].title, replayqueryinput.buffer) != NULL) + StripColors(demo_title, demolist_all[replayquerycheck].title, sizeof(demo_title)); + + if (demolist_all[replayquerycheck].title[0] && strcasestr(demo_title, replayqueryinput.buffer) != NULL) AddCheckedReplay(); // It matches, add it! else replayquerycheck++; // Doesn't match, moving on... @@ -4206,12 +4186,12 @@ static void PrepReplayList(boolean reset) if (dirmenu[i][DIR_TYPE] == EXT_UP) { demolist_all[i].type = MD_SUBDIR; - sprintf(demolist_all[i].title, "UP"); + snprintf(demolist_all[i].title, sizeof(demolist_all[i].title), "UP"); } else if (dirmenu[i][DIR_TYPE] == EXT_FOLDER) { demolist_all[i].type = MD_SUBDIR; - strncpy(demolist_all[i].title, dirmenu[i] + DIR_STRING, 64); + snprintf(demolist_all[i].title, sizeof(demolist_all[i].title), "%s", dirmenu[i] + DIR_STRING); } else { @@ -4219,7 +4199,7 @@ static void PrepReplayList(boolean reset) snprintf(demolist_all[i].filepath, sizeof(demolist_all[i].filepath), // 255 = UINT8 limit. dirmenu entries are restricted to this length (see DIR_LEN). "%s%.255s", menupath, dirmenu[i] + DIR_STRING); - sprintf(demolist_all[i].title, "....."); + snprintf(demolist_all[i].title, sizeof(demolist_all[i].title), "....."); } } @@ -4271,6 +4251,14 @@ static boolean M_HandleReplayHutQuery(INT32 choice) char tmp[MAXREPLAYQUERY+1]; memcpy(tmp, replayqueryinput_buffer, MAXREPLAYQUERY+1); + Lock_search_state(); + if (!replaynamesloaded) + { + Unlock_search_state(); + return false; + } + Unlock_search_state(); + if (M_TextInputHandle(&replayqueryinput, choice)) { S_StartSound(NULL, sfx_menu1); @@ -4716,7 +4704,7 @@ static void M_DrawReplayHut(void) if (y > scaledviewheight-80) { V_DrawFill(BASEVIDWIDTH-4, 75, 4, scaledviewheight-80, V_SNAPTOTOP|V_SNAPTORIGHT|239); - V_DrawFill(BASEVIDWIDTH-3, 76 + (scaledviewheight-80) * replayhutmenuy / y, 2, (((scaledviewheight-80) * (scaledviewheight-80))-1) / y - 1, V_SNAPTOTOP|V_SNAPTORIGHT|229); + V_DrawFill(BASEVIDWIDTH-3, 76 + (scaledviewheight-80) * replayhutmenuy / y, 2, max((((scaledviewheight-80) * (scaledviewheight-80))-1) / y - 1, 1), V_SNAPTOTOP|V_SNAPTORIGHT|229); } // Draw the cursor @@ -4902,6 +4890,7 @@ static void M_HutStartReplay(INT32 choice) demo.loadfiles = (itemOn == 0); demo.ignorefiles = (itemOn != 0); + CONS_Printf(M_GetText("Playing back demo '%s'.\n"), demolist[dir_on[menudepthleft]].filepath); G_DoPlayDemo(demolist[dir_on[menudepthleft]].filepath); } @@ -5353,7 +5342,7 @@ void M_PopupMasterServerRules(void) { firstDismissedRulesThisBoot = false; M_StartMessage(va("%s\n(press any key)", rules), NULL, MM_NOTHING); - Z_Free(rules); + free(rules); } } #endif @@ -5384,7 +5373,7 @@ void M_SlotCvarIntoModMenu(consvar_t* cvar, const char* category, const char* na { CONS_Printf("custom settings menu initiation\n"); for (CVARSETUP = 0; CVARSETUP < MAXMENUCCVARS; ++CVARSETUP) - OP_CustomCvarMenu[CVARSETUP] = (menuitem_t){IT_DISABLED, NULL, "", 0, INT16_MAX}; + OP_CustomCvarMenu[CVARSETUP] = (menuitem_t){IT_DISABLED, NULL, "", NULL, INT16_MAX}; } if (category && ((ccvarposition == 0 && category[0] != '\0') || !fasticmp(category, OP_CustomCvarMenu[ccvarlaststheader].text))) @@ -5399,7 +5388,7 @@ void M_SlotCvarIntoModMenu(consvar_t* cvar, const char* category, const char* na } if (cvar->flags & CV_NETVAR) - OP_CustomCvarMenu[ccvarposition] = (menuitem_t){ IT_STRING | IT_CVAR , NULL, Z_StrDup(va("\x85 %s", name)), cvar, ccvaralphakey }; + OP_CustomCvarMenu[ccvarposition] = (menuitem_t){ IT_STRING | IT_CVAR, NULL, Z_StrDup(va("\x85 %s", name)), cvar, ccvaralphakey }; else OP_CustomCvarMenu[ccvarposition] = (menuitem_t){ IT_STRING | IT_CVAR, NULL, Z_StrDup(name), cvar, ccvaralphakey }; @@ -5519,7 +5508,6 @@ static void M_DrawChecklist(void) if (conditionSets[unlockables[i].conditionset - 1].numconditions) { - c = 0; lastid = -1; for (c = 0; c < conditionSets[unlockables[i].conditionset - 1].numconditions; c++) @@ -5679,9 +5667,6 @@ static void M_DrawMusicTest(void) { INT32 x, y, i; - x = 90<title[0] ? def->title : def->source; size_t namelength = strlen(songname); +#define MAXLENGTH 34 char buf[MAXLENGTH+1]; if (t == st_sel && namelength > MAXLENGTH) @@ -5804,11 +5790,14 @@ static void M_DrawMusicTest(void) strlcpy(buf, songname, MAXLENGTH); V_DrawString(x, y, (t == st_sel ? V_YELLOWMAP : 0)|V_ALLOWLOWERCASE|V_MONOSPACE, buf); + if (curplaying == def) { V_DrawFill(20+280-9, y-4, 8, 16, 230); } +#undef MAXLENGTH } + t++; y += 16; } @@ -5995,7 +5984,8 @@ static void M_DrawStatsMaps(void) V_DrawString(20, 42, highlightflags|MENUCAPS, "Combined time records:"); - sprintf(beststr, "%i:%02i:%02i.%02i", G_TicsToHours(besttime), G_TicsToMinutes(besttime, false), G_TicsToSeconds(besttime), G_TicsToCentiseconds(besttime)); + snprintf(beststr, sizeof(beststr), "%i:%02i:%02i.%02i", G_TicsToHours(besttime), G_TicsToMinutes(besttime, false), G_TicsToSeconds(besttime), G_TicsToCentiseconds(besttime)); + V_DrawRightAlignedString(BASEVIDWIDTH-16, 42, (mapsunfinished ? warningflags : 0), beststr); if (mapsunfinished) @@ -6461,13 +6451,13 @@ static void M_ChooseTimeAttack(INT32 choice) else G_RecordDemo(nameofdemo); - G_DeferedInitNew(false, mapname, (UINT8)(cv_chooseskin.value-1), 0, false); + G_DeferedInitNew(false, mapname, (skinnum_t)(cv_chooseskin.value-1), 0, false); } static void M_HandleStaffReplay(INT32 choice) { boolean exitmenu = false; // exit to previous menu - lumpnum_t l = W_CheckNumForName(va("%sS%02u",G_BuildMapName(cv_nextmap.value),cv_dummystaff.value)); + lumpnum_t l = W_CheckNumForName(va("%sS%02u", G_BuildMapName(cv_nextmap.value), cv_dummystaff.value)); switch (choice) { @@ -6497,7 +6487,7 @@ static void M_HandleStaffReplay(INT32 choice) M_ClearMenus(true); modeattacking = ATTACKING_RECORD; demo.loadfiles = false; demo.ignorefiles = true; // Just assume that record attack replays have the files needed - G_DoPlayDemo(va("%sS%02u",G_BuildMapName(cv_nextmap.value),cv_dummystaff.value)); + G_DoPlayDemo(va("%sS%02u", G_BuildMapName(cv_nextmap.value), cv_dummystaff.value)); break; default: break; @@ -6557,17 +6547,22 @@ static void M_EraseGuest(INT32 choice) static void M_OverwriteGuest(const char *which) { - char *rguest = Z_StrDup(va("%s"PATHSEP"replay"PATHSEP"%s"PATHSEP"%s-guest.lmp", srb2home, timeattackfolder, G_BuildMapName(cv_nextmap.value))); + char *rguest; UINT8 *buf; size_t len; len = FIL_ReadFile(va("%s"PATHSEP"replay"PATHSEP"%s"PATHSEP"%s-%s-%s.lmp", srb2home, timeattackfolder, G_BuildMapName(cv_nextmap.value), cv_chooseskin.string, which), &buf); - if (!len) { + + if (!len) return; - } - if (FIL_FileExists(rguest)) { + + rguest = Z_StrDup(va("%s"PATHSEP"replay"PATHSEP"%s"PATHSEP"%s-guest.lmp", srb2home, timeattackfolder, G_BuildMapName(cv_nextmap.value))); + + if (FIL_FileExists(rguest)) + { M_StopMessage(0); remove(rguest); } + FIL_WriteFile(rguest, buf, len); Z_Free(rguest); @@ -7157,7 +7152,7 @@ static void M_CheckMODVersion(int id) if (updatecheck) { - sprintf(updatestring, UPDATE_ALERT_STRING, VERSIONSTRING, updatecheck); + snprintf(updatestring, sizeof(updatestring), UPDATE_ALERT_STRING, VERSIONSTRING, updatecheck); #ifdef HAVE_THREADS I_lock_mutex(&m_menu_mutex); #endif @@ -7493,7 +7488,7 @@ static void M_DrawLevelSelectOnly(boolean leftfade, boolean rightfade) if ((lumpnum = W_CheckNumForName(va("%sE", mapname))) != LUMPERROR) mappingforencore = (patch_t *)W_CachePatchNum(lumpnum, PU_PATCH);*/ - V_DrawFixedPatch((x+w)<prevMenu) - M_SetupNextMenu (currentMenu->prevMenu); + M_SetupNextMenu(currentMenu->prevMenu); else M_ClearMenus(true); } @@ -7899,7 +7894,7 @@ static void M_HandleConnectIP(INT32 choice) if (exitmenu) { if (currentMenu->prevMenu) - M_SetupNextMenu (currentMenu->prevMenu); + M_SetupNextMenu(currentMenu->prevMenu); else M_ClearMenus(true); } @@ -7934,24 +7929,24 @@ static void M_DrawSetupMultiPlayerMenu(void) INT32 tw = 0; spritedef_t *sprdef; spriteframe_t *sprframe; - patch_t *statbg = (patch_t *)W_CachePatchName("K_STATBG", PU_PATCH); - patch_t *statlr = (patch_t *)W_CachePatchName("K_STATLR", PU_PATCH); - patch_t *statud = (patch_t *)W_CachePatchName("K_STATUD", PU_PATCH); - patch_t *statdot = (patch_t *)W_CachePatchName("K_SDOT0", PU_PATCH); patch_t *patch; - UINT8 frame; - UINT8 speed; - UINT8 weight; - UINT8 i; - UINT8 s, w; - const UINT8 *flashcol = V_GetStringColormap(highlightflags); + UINT16 frame; + UINT16 speed; + UINT16 weight; + UINT16 i; + UINT16 s, w; + INT32 skinnum = 0; INT32 statx, staty; UINT32 speenframe; INT32 sltw, actw, hetw; - UINT8 skintodisplay; + skinnum_t skintodisplay; INT32 nameboxaddy = 0; - int statoffset = 0; - int gridyoffset = 0; + + const UINT8 *flashcol = V_GetStringColormap(highlightflags); + patch_t *statbg = (patch_t *)W_CachePatchName("K_STATBG", PU_PATCH); + patch_t *statlr = (patch_t *)W_CachePatchName("K_STATLR", PU_PATCH); + patch_t *statud = (patch_t *)W_CachePatchName("K_STATUD", PU_PATCH); + patch_t *statdot = (patch_t *)W_CachePatchName("K_SDOT0" , PU_PATCH); mx = MP_PlayerSetupDef.x; my = MP_PlayerSetupDef.y; @@ -7966,8 +7961,6 @@ static void M_DrawSetupMultiPlayerMenu(void) switch (cv_skinselectmenu.value) { case SKINMENUTYPE_EXTENDED: - nameboxaddy = 6; - break; case SKINMENUTYPE_GRID: nameboxaddy = 6; break; @@ -7983,48 +7976,27 @@ static void M_DrawSetupMultiPlayerMenu(void) else M_DrawTextInput(mx + 40, my + nameboxaddy, &setupm_input, 0); +#define GETSELECTEDSKINNAME (itemOn == 1 && setupm_skinselect < numskins ? skins[skinsorted[setupm_skinselect]].realname : skins[setupm_fakeskin].realname) +#define GETSELECTEDSPEED (itemOn == 1 && setupm_skinselect < numskins ? skins[skinsorted[setupm_skinselect]].kartspeed : skins[setupm_fakeskin].kartspeed) +#define GETSELECTEDWEIGHT (itemOn == 1 && setupm_skinselect < numskins ? skins[skinsorted[setupm_skinselect]].kartweight : skins[setupm_fakeskin].kartweight) + // draw skin string st = V_StringWidth(skins[setupm_fakeskin].realname, 0); switch (cv_skinselectmenu.value) { case SKINMENUTYPE_EXTENDED: -#define GETSELECTEDSKINNAME (itemOn == 1 && setupm_skinselect < numskins ? skins[skinsorted[setupm_skinselect]].realname : skins[setupm_fakeskin].realname) -#define GETSELECTEDSPEED (itemOn == 1 && setupm_skinselect < numskins ? skins[skinsorted[setupm_skinselect]].kartspeed : skins[setupm_fakeskin].kartspeed) -#define GETSELECTEDWEIGHT (itemOn == 1 && setupm_skinselect < numskins ? skins[skinsorted[setupm_skinselect]].kartweight : skins[setupm_fakeskin].kartweight) - - statoffset = 0; - tw = V_StringWidth("Character", 0);//V_StringWidth(GETSELECTEDSKINNAME, 0); - st = V_StringWidth(GETSELECTEDSKINNAME, 0); - - INT32 selectedskin = (itemOn == 1 && setupm_skinselect < numskins ? skinsorted[setupm_skinselect] : setupm_fakeskin); - speed = skins[selectedskin].kartspeed; - weight = skins[selectedskin].kartweight; - - V_DrawString((mx+(tw/2)) - (st/2), my + 37, - ((MP_PlayerSetupMenu[2].status & IT_TYPE) == IT_SPACE ? V_TRANSLUCENT : 0) | highlightflags | V_ALLOWLOWERCASE, - GETSELECTEDSKINNAME); - if (statdp == true) - statoffset = 50; - else - statoffset = 113; - - V_DrawString(statx - statoffset, staty - 10, V_6WIDTHSPACE, va("\x84%dS \x87%dW", GETSELECTEDSPEED, GETSELECTEDWEIGHT)); -#undef GETSELECTEDSKINNAME -#undef GETSELECTEDSPEED -#undef GETSELECTEDWEIGHT - break; + V_DrawString(statx - (statdp ? 50 : 113), staty - 10, V_6WIDTHSPACE, va("\x84%dS \x87%dW", GETSELECTEDSPEED, GETSELECTEDWEIGHT)); + /* FALLTHRU */ case SKINMENUTYPE_GRID: -#define GETSELECTEDSKINNAME (itemOn == 1 && setupm_skinselect < numskins ? skins[skinsorted[setupm_skinselect]].realname : skins[setupm_fakeskin].realname) - tw = V_StringWidth("Character", 0);//V_StringWidth(GETSELECTEDSKINNAME, 0); + tw = V_StringWidth("Character", 0); st = V_StringWidth(GETSELECTEDSKINNAME, 0); V_DrawString((mx+(tw/2)) - (st/2), my + 37, ((MP_PlayerSetupMenu[2].status & IT_TYPE) == IT_SPACE ? V_TRANSLUCENT : 0) | highlightflags | V_ALLOWLOWERCASE, GETSELECTEDSKINNAME); -#undef GETSELECTEDSKINNAME break; case SKINMENUTYPE_2D: - skintodisplay = setupm_fakeskin; + skintodisplay = (skinnum_t)setupm_fakeskin; if (setupm_skinlockedselect) //show the skin we are trying to select skintodisplay = skinstats[setupm_skinxpos][setupm_skinypos][setupm_skinselect]; else if (skinstatscount[setupm_skinxpos][setupm_skinypos] && itemOn == 1) @@ -8098,8 +8070,6 @@ static void M_DrawSetupMultiPlayerMenu(void) break; } -#define GRIDSTATOFFSET 0 - switch (cv_skinselectmenu.value) { case SKINMENUTYPE_EXTENDED: @@ -8111,9 +8081,6 @@ static void M_DrawSetupMultiPlayerMenu(void) if (itemOn == 1) V_DrawSmallString(statx+101, staty-37, V_6WIDTHSPACE|highlightflags, "BS: change"); -#define GETSELECTEDSPEED (itemOn == 1 && setupm_skinselect < numskins ? skins[skinsorted[setupm_skinselect]].kartspeed : skins[setupm_fakeskin].kartspeed) -#define GETSELECTEDWEIGHT (itemOn == 1 && setupm_skinselect < numskins ? skins[skinsorted[setupm_skinselect]].kartweight : skins[setupm_fakeskin].kartweight) - if (statdp == true) { //Background @@ -8143,22 +8110,19 @@ static void M_DrawSetupMultiPlayerMenu(void) } } -#undef GETSELECTEDSPEED -#undef GETSELECTEDWEIGHT - break; case SKINMENUTYPE_GRID: // SRB2Kart: draw the stat backer // labels - V_DrawSmallString(statx+12+GRIDSTATOFFSET, staty+67, V_6WIDTHSPACE|highlightflags, "Acceleration"); - V_DrawSmallString(statx+76+GRIDSTATOFFSET, staty+67, V_6WIDTHSPACE|highlightflags, "Max Speed"); - V_DrawSmallString(statx+14+GRIDSTATOFFSET, staty+75, V_6WIDTHSPACE|highlightflags, "Handling"); - V_DrawSmallString(statx+21+GRIDSTATOFFSET, staty+108, V_6WIDTHSPACE|highlightflags, "Weight"); + V_DrawSmallString(statx+12, staty+67, V_6WIDTHSPACE|highlightflags, "Acceleration"); + V_DrawSmallString(statx+76, staty+67, V_6WIDTHSPACE|highlightflags, "Max Speed"); + V_DrawSmallString(statx+14, staty+75, V_6WIDTHSPACE|highlightflags, "Handling"); + V_DrawSmallString(statx+21, staty+108, V_6WIDTHSPACE|highlightflags, "Weight"); // label arrows - V_DrawFixedPatch(((statx+61+GRIDSTATOFFSET)<>1), (staty+67)<>1, 0, statlr, flashcol); - V_DrawFixedPatch((statx+40+GRIDSTATOFFSET)<>1, 0, statud, flashcol); + V_DrawFixedPatch(((statx+61)<>1), (staty+67)<>1, 0, statlr, flashcol); + V_DrawFixedPatch((statx+40)<>1, 0, statud, flashcol); // bg - V_DrawFixedPatch(((statx+48+GRIDSTATOFFSET)<>1), (staty+73)<>1, 0, statbg, 0); + V_DrawFixedPatch(((statx+48)<>1), (staty+73)<>1, 0, statbg, NULL); for (i = 0; i < numskins; i++) // draw the stat dots { @@ -8166,7 +8130,7 @@ static void M_DrawSetupMultiPlayerMenu(void) { speed = skins[i].kartspeed; weight = skins[i].kartweight; - V_DrawFixedPatch((((statx+46+GRIDSTATOFFSET) + (speed*4))<>1), (((staty+71) + (weight*4))<>1, 0, statdot, NULL); + V_DrawFixedPatch((((statx+46) + (speed*4))<>1), (((staty+71) + (weight*4))<>1, 0, statdot, NULL); } } @@ -8192,9 +8156,9 @@ static void M_DrawSetupMultiPlayerMenu(void) #define TEXTVERTSHIFT 10 DRAWSLOW(statx - sltw - 2, staty); - DRAWSLOW(statx - sltw - 2, staty - TEXTVERTSHIFT+ (9 * 18) - 11); + DRAWSLOW(statx - sltw - 2, staty - TEXTVERTSHIFT + (9 * 18) - 11); DRAWFAST(statx + (9 * 18), staty); - DRAWFAST(statx + (9 * 18), staty - TEXTVERTSHIFT+ (9 * 18) - 11); + DRAWFAST(statx + (9 * 18), staty - TEXTVERTSHIFT + (9 * 18) - 11); DRAWACCEL(statx - actw - 2, staty + TEXTVERTSHIFT); DRAWACCEL(statx + (9 * 18), staty + TEXTVERTSHIFT); DRAWHEAVY(statx - hetw - 2, staty + (9 * 18) - 11); @@ -8217,7 +8181,7 @@ static void M_DrawSetupMultiPlayerMenu(void) V_DrawFixedPatch((statx+64)<>3), 0, cursor, NULL); + UINT8 cursorframe = (I_GetTime() / 4) % 7; + cursor = (patch_t *)W_CachePatchName(va("K_CHILI%d", cursorframe + 1), PU_PATCH); + V_DrawFixedPatch((curx << FRACBITS) - (FRACUNIT), (cury << FRACBITS) - (FRACUNIT), FRACUNIT+(FRACUNIT>>3), 0, cursor, NULL); } break; @@ -8309,14 +8275,12 @@ static void M_DrawSetupMultiPlayerMenu(void) if (setupm_skinselect < numskins) { UINT8 *cmap = R_GetTranslationColormap(setupm_skinselect, setupm_fakecolor, GTC_MENUCACHE); - cursor = facewantprefix[skinsorted[setupm_skinselect]]; V_DrawFixedPatch(((curx-8) << FRACBITS), ((cury-8) << FRACBITS), FRACUNIT, 0, cursor, cmap); } else { UINT8 cursorframe = (I_GetTime() / 4) % 7; - cursor = (patch_t *)W_CachePatchName(va("K_CHILI%d", cursorframe + 1), PU_PATCH); V_DrawFixedPatch((curx << FRACBITS) - (FRACUNIT), (cury << FRACBITS) - (FRACUNIT), FRACUNIT+(FRACUNIT>>3), 0, cursor, NULL); } @@ -8328,13 +8292,13 @@ static void M_DrawSetupMultiPlayerMenu(void) weight = skins[selectedskin].kartweight; statdot = (patch_t *)W_CachePatchName("K_SDOT1", PU_PATCH); if (skullAnimCounter < 4) // SRB2Kart: we draw this dot later so that it's not covered if there's multiple skins with the same stats - V_DrawFixedPatch((((statx+46+GRIDSTATOFFSET) + (speed*4))<>1), (((staty+71) + (weight*4))<>1, 0, statdot, flashcol); + V_DrawFixedPatch((((statx+46) + (speed*4))<>1), (((staty+71) + (weight*4))<>1, 0, statdot, flashcol); else - V_DrawFixedPatch((((statx+46+GRIDSTATOFFSET) + (speed*4))<>1), (((staty+71) + (weight*4))<>1, 0, statdot, NULL); + V_DrawFixedPatch((((statx+46) + (speed*4))<>1), (((staty+71) + (weight*4))<>1, 0, statdot, NULL); statdot = (patch_t *)W_CachePatchName("K_SDOT2", PU_PATCH); // coloured center if (setupm_fakecolor) - V_DrawFixedPatch((((statx+46+GRIDSTATOFFSET) + (speed*4))<>1), (((staty+71) + (weight*4))<>1, 0, statdot, R_GetTranslationColormap(0, setupm_fakecolor, GTC_MENUCACHE)); + V_DrawFixedPatch((((statx+46) + (speed*4))<>1), (((staty+71) + (weight*4))<>1, 0, statdot, R_GetTranslationColormap(0, setupm_fakecolor, GTC_MENUCACHE)); } break; case SKINMENUTYPE_2D: @@ -8380,13 +8344,11 @@ static void M_DrawSetupMultiPlayerMenu(void) else { UINT8 cursorframe = (I_GetTime() / 4) % 7; - cursor = (patch_t *)W_CachePatchName(va("K_CHILI%d", cursorframe + 1), PU_PATCH); V_DrawFixedPatch((curx << FRACBITS) - (FRACUNIT), (cury << FRACBITS) - (FRACUNIT), FRACUNIT+(FRACUNIT>>3), 0, cursor, NULL); } } break; -#undef GRIDSTATOFFSET #undef SKINXSHIFT default: speed = skins[setupm_fakeskin].kartspeed; @@ -8414,7 +8376,7 @@ static void M_DrawSetupMultiPlayerMenu(void) colwidth = colwidth - 10; INT32 j = -colwidth; - INT16 col = setupm_fakecolor - colwidth; + INT32 col = setupm_fakecolor - colwidth; INT32 x = mx; INT32 cw = indexwidth; UINT8 ch; @@ -8442,7 +8404,7 @@ static void M_DrawSetupMultiPlayerMenu(void) { const INT32 icons = 4; INT32 k = -icons; - INT16 col = setupm_fakeskin - icons; + INT32 col = setupm_fakeskin - icons; INT32 x = BASEVIDWIDTH/2 - ((icons+1)*24) - 4; fixed_t scale = FRACUNIT/2; INT32 offx = 8, offy = 8; @@ -8505,7 +8467,7 @@ static void M_DrawSetupMultiPlayerMenu(void) switch (cv_skinselectmenu.value) { case SKINMENUTYPE_2D: - skintodisplay = setupm_fakeskin; + skintodisplay = (skinnum_t)setupm_fakeskin; if (setupm_skinlockedselect) // show the skin we are trying to select skintodisplay = skinstats[setupm_skinxpos][setupm_skinypos][setupm_skinselect]; else if (skinstatscount[setupm_skinxpos][setupm_skinypos] && itemOn == 1) @@ -8513,19 +8475,22 @@ static void M_DrawSetupMultiPlayerMenu(void) break; case SKINMENUTYPE_EXTENDED: case SKINMENUTYPE_GRID: - skintodisplay = (itemOn == 1 && setupm_skinselect < numskins ? skinsorted[setupm_skinselect] : setupm_fakeskin); + skintodisplay = ((itemOn == 1 && (setupm_skinselect < numskins)) ? skinsorted[setupm_skinselect] : (skinnum_t)setupm_fakeskin); break; default: - skintodisplay = setupm_fakeskin; + skintodisplay = (skinnum_t)setupm_fakeskin; break; } - const INT32 skinnum = R_SkinAvailable(skins[skintodisplay].name); + if (skintodisplay >= MAXSKINS) + skintodisplay = 0; - if (skinnum != -1) - sprdef = &skins[skinnum].spritedef; - else - sprdef = &skins[0].spritedef; + skinnum = R_SkinAvailable(skins[skintodisplay].name); + + if (skinnum < 0 || skinnum >= MAXSKINS) + skinnum = 0; + + sprdef = &skins[skinnum].spritedef; if (!sprdef->numframes) // No frames ?? return; // Can't render! @@ -8534,37 +8499,59 @@ static void M_DrawSetupMultiPlayerMenu(void) if (frame >= sprdef->numframes) // Walking animation missing frame = 0; // Try to use standing frame - sprframe = &sprdef->spriteframes[frame]; - - // minenice's speen css, it's a piece of shit but hey - speenframe = (I_GetTime()*cv_skinselectspin.value/TICRATE + 1)%8; - - // this is a very shitty solution for checking if a sprite needs flipping - // but it works - if ((speenframe > 4) && (sprframe->lumppat[speenframe] == sprframe->lumppat[8-speenframe])) - flags = V_FLIP; // This sprite is left/right flipped! - - patch = (patch_t *)W_CachePatchNum(sprframe->lumppat[speenframe], PU_PATCH); - // draw box around guy V_DrawFill(mx + 36 - (charw/2), my+65, charw, 84, 239); +#undef charw // draw player sprite if (setupm_fakecolor) // inverse should never happen { UINT8 *colormap = R_GetTranslationColormap(skintodisplay, setupm_fakecolor, GTC_MENUCACHE); - - if (skins[skintodisplay].flags & SF_HIRES) +#ifdef HWRENDER + md2_t *md2 = &md2_playermodels[skinnum]; +#endif + mx += 36; + my += 131; +#ifdef HWRENDER + // if we have 3d models enabled and a model exists + // try to show it instead of the sprite + if (rendermode == render_opengl && cv_glmdls.value + && !md2->error && !md2->notfound) { - V_DrawFixedPatch((mx+36)<spriteframes[frame]; + + // minenice's speen css, it's a piece of shit but hey + speenframe = (I_GetTime()*cv_skinselectspin.value/TICRATE + 1)%8; + + // this is a very shitty solution for checking if a sprite needs flipping + // but it works + if ((speenframe > 4) && (sprframe->lumppat[speenframe] == sprframe->lumppat[8-speenframe])) + { + flags = V_FLIP; // This sprite is left/right flipped! + } + + patch = (patch_t *)W_CachePatchNum(sprframe->lumppat[speenframe], PU_PATCH); + + if (skins[skintodisplay].flags & SF_HIRES) + { + V_DrawFixedPatch(mx<string)) { // remove trailing whitespaces - for (l = strlen(setupm_name)-1; - (signed)l >= 0 && setupm_name[l] ==' '; l--) - setupm_name[l] =0; - COM_BufAddText(va("%s \"%s\"\n",setupm_cvname->name,setupm_name)); + l = strlen(setupm_name)-1; + for (;(signed)l >= 0 && setupm_name[l] ==' '; l--) + setupm_name[l] = 0; + COM_BufAddText(va("%s \"%s\"\n", setupm_cvname->name, setupm_name)); } // you know what? always putting these in the buffer won't hurt anything. - COM_BufAddText(va("%s \"%s\"\n",setupm_cvskin->name,skins[setupm_fakeskin].name)); - COM_BufAddText(va("%s %d\n",setupm_cvcolor->name,setupm_fakecolor)); + COM_BufAddText(va("%s \"%s\"\n", setupm_cvskin->name, skins[setupm_fakeskin].name)); + COM_BufAddText(va("%s %d\n", setupm_cvcolor->name, setupm_fakecolor)); return true; } @@ -9358,29 +9345,32 @@ static void M_SetupControlsMenu(UINT8 pnum) break; } + OP_AllControlsMenu[4].itemaction = &cv_litesteer[pnum]; + OP_AllControlsMenu[5].itemaction = &cv_turnsmooth[pnum]; + if (pnum > 0) { // Hide P1-only controls - OP_AllControlsMenu[15].status = IT_GRAYEDOUT2; // Chat - OP_AllControlsMenu[16].status = IT_GRAYEDOUT2; // Rankings - OP_AllControlsMenu[17].status = IT_GRAYEDOUT2; // Pause - OP_AllControlsMenu[18].status = IT_GRAYEDOUT2; // Screenshot - OP_AllControlsMenu[19].status = IT_GRAYEDOUT2; // GIF - OP_AllControlsMenu[20].status = IT_GRAYEDOUT2; // System Menu - OP_AllControlsMenu[21].status = IT_GRAYEDOUT2; // Console - OP_AllControlsMenu[37].status = IT_GRAYEDOUT2; // Director + OP_AllControlsMenu[19].status = IT_GRAYEDOUT2; // Chat + OP_AllControlsMenu[10].status = IT_GRAYEDOUT2; // Rankings + OP_AllControlsMenu[21].status = IT_GRAYEDOUT2; // Pause + OP_AllControlsMenu[22].status = IT_GRAYEDOUT2; // Screenshot + OP_AllControlsMenu[23].status = IT_GRAYEDOUT2; // GIF + OP_AllControlsMenu[24].status = IT_GRAYEDOUT2; // System Menu + OP_AllControlsMenu[25].status = IT_GRAYEDOUT2; // Console + OP_AllControlsMenu[41].status = IT_GRAYEDOUT2; // Director } else { // Unhide P1-only controls - OP_AllControlsMenu[15].status = IT_CONTROL; // Chat - OP_AllControlsMenu[16].status = IT_CONTROL; // Rankings - OP_AllControlsMenu[17].status = IT_CONTROL; // Pause - OP_AllControlsMenu[18].status = IT_CONTROL; // Screenshot - OP_AllControlsMenu[19].status = IT_CONTROL; // GIF - OP_AllControlsMenu[20].status = IT_CONTROL; // System Menu - OP_AllControlsMenu[21].status = IT_CONTROL; // Console - OP_AllControlsMenu[37].status = IT_CONTROL; // Director + OP_AllControlsMenu[19].status = IT_CONTROL; // Chat + OP_AllControlsMenu[10].status = IT_CONTROL; // Rankings + OP_AllControlsMenu[21].status = IT_CONTROL; // Pause + OP_AllControlsMenu[22].status = IT_CONTROL; // Screenshot + OP_AllControlsMenu[23].status = IT_CONTROL; // GIF + OP_AllControlsMenu[24].status = IT_CONTROL; // System Menu + OP_AllControlsMenu[25].status = IT_CONTROL; // Console + OP_AllControlsMenu[41].status = IT_CONTROL; // Director } M_SetupNextMenu(&OP_AllControlsDef); @@ -9494,12 +9484,36 @@ static void M_DrawControl(void) else if ((currentMenu->menuitems[i].status == IT_HEADER) && (i != max-1)) V_DrawString(19, y+6, highlightflags|V_ALLOWLOWERCASE, currentMenu->menuitems[i].text); else if (currentMenu->menuitems[i].status & IT_STRING) + { V_DrawString(x, y, ((i == itemOn) ? highlightflags|V_ALLOWLOWERCASE : V_ALLOWLOWERCASE), currentMenu->menuitems[i].text); + if (currentMenu->menuitems[i].status & IT_CVAR) + { + consvar_t *cv = (consvar_t *)currentMenu->menuitems[i].itemaction; + + // IT_HEADER matches IT_CVAR, for some reason... + if (cv) + { + INT32 w = V_StringWidth(cv->string, 0); + V_DrawString(BASEVIDWIDTH - x - w, y, + ((cv->flags & CV_CHEAT) && !CV_IsSetToDefault(cv) ? warningflags : highlightflags)|MENUCAPS, cv->string); + if (i == itemOn) + { + V_DrawCharacter(BASEVIDWIDTH - x - 10 - w - (skullAnimCounter/5), y, + '\x1C' | highlightflags, false); // left arrow + V_DrawCharacter(BASEVIDWIDTH - x + 2 + (skullAnimCounter/5), y, + '\x1D' | highlightflags, false); // right arrow + } + } + } + } + y += SMALLLINEHEIGHT; } V_DrawScaledPatch(currentMenu->x - 20, cursory, 0, (patch_t *)W_CachePatchName("M_CURSOR", PU_PATCH)); + + M_DoToolTips(currentMenu); } #undef controlheight @@ -9587,11 +9601,13 @@ static void M_ChangecontrolResponse(event_t *ev) menu_t *prev = currentMenu->prevMenu; if (controltochange == gc_pause) - sprintf(tmp, M_GetText("The \x82Pause Key \x80is enabled, but \nyou may select another key. \n\nHit another key for\n%s\nESC for Cancel"), - controltochangetext); + { + snprintf(tmp, sizeof(tmp), M_GetText("The \x82Pause Key \x80is enabled, but \nyou may select another key. \n\nHit another key for\n%s\nESC for Cancel"), controltochangetext); + } else - sprintf(tmp, M_GetText("The \x82Pause Key \x80is enabled, but \nit is not configurable. \n\nHit another key for\n%s\nESC for Cancel"), - controltochangetext); + { + snprintf(tmp, sizeof(tmp), M_GetText("The \x82Pause Key \x80is enabled, but \nit is not configurable. \n\nHit another key for\n%s\nESC for Cancel"), controltochangetext); + } M_StartMessage(tmp, M_ChangecontrolResponse, MM_EVENTHANDLER); currentMenu->prevMenu = prev; @@ -9612,8 +9628,7 @@ static void M_ChangeControl(INT32 choice) static char tmp[68]; controltochange = currentMenu->menuitems[choice].alphaKey; - sprintf(tmp, M_GetText("Hit the new key for\n%s\nESC for Cancel"), - currentMenu->menuitems[choice].text); + snprintf(tmp, sizeof(tmp), M_GetText("Hit the new key for\n%s\nESC for Cancel"), currentMenu->menuitems[choice].text); strlcpy(controltochangetext, currentMenu->menuitems[choice].text, 33); M_StartMessage(tmp, M_ChangecontrolResponse, MM_EVENTHANDLER); @@ -9838,7 +9853,7 @@ static void M_DrawLocalSkinMenu(void) spriteframe_t *sprframe; patch_t *patch; UINT8 frame; - INT16 skintodisplay; + INT32 skintodisplay = 0; UINT32 speenframe; skin_t displayskin; @@ -9869,12 +9884,12 @@ static void M_DrawLocalSkinMenu(void) // skin 0 is default player sprite skintodisplay = R_AnySkinAvailable(cv_fakelocalskin.string); - if (skintodisplay == -1) + if (skintodisplay < 0) { // ATTEMPT TO FIND REAL SKIN skintodisplay = R_AnySkinAvailable(cv_skin.string); - if (skintodisplay == -1) // STILL NOTHIN? use sonic instead + if (skintodisplay < 0) // STILL NOTHIN? use sonic instead { skintodisplay = 0; } @@ -9891,24 +9906,10 @@ static void M_DrawLocalSkinMenu(void) if (frame >= sprdef->numframes) // Walking animation missing frame = 0; // Try to use standing frame - sprframe = &sprdef->spriteframes[frame]; - - //minenice's speen css, it's a piece of shit but hey - //patch = (patch_t *)W_CachePatchNum(sprframe->lumppat[1], PU_PATCH); - speenframe = (I_GetTime()*cv_skinselectspin.value/TICRATE + 1)%8; - - //this is a very shitty solution for checking if a sprite needs flipping - //but it works - if ((speenframe > 4) && (sprframe->lumppat[speenframe] == sprframe->lumppat[8-speenframe])) - { - flags = V_FLIP; // This sprite is left/right flipped! - } - patch = (patch_t *)W_CachePatchNum(sprframe->lumppat[speenframe], PU_PATCH); - // draw box around guy V_DrawFill(mx + 220 - (charw/2), my+54, charw, 84, 239); +#undef charw - // draw player sprite UINT8 *colormap = R_GetLocalTranslationColormap(&skins[displayskin.localnum], (displayskin.localskin ? &localskins[displayskin.localnum] : NULL), cv_playercolor.value, GTC_MENUCACHE, displayskin.localskin); V_DrawMappedPatch(mx, my+50, 0, (patch_t *)W_CachePatchName(displayskin.facewant, PU_PATCH), colormap); @@ -9921,13 +9922,48 @@ static void M_DrawLocalSkinMenu(void) else V_DrawString(mx+20, my+118, V_ALLOWLOWERCASE|highlightflags, displayskin.realname); - if (displayskin.flags & SF_HIRES) + // draw player sprite + mx += 220; + my += 120; + +#ifdef HWRENDER + md2_t *md2 = (displayskin.localskin ? &md2_localplayermodels[skintodisplay] : &md2_playermodels[skintodisplay]); + + // if we have 3d models enabled and a model exists + // try to show it instead of the sprite + if (rendermode == render_opengl && cv_glmdls.value + && !md2->error && !md2->notfound) { - V_DrawFixedPatch((mx+220)<spriteframes[frame]; + + // minenice's speen css, it's a piece of shit but hey + speenframe = (I_GetTime()*cv_skinselectspin.value/TICRATE + 1)%8; + + // this is a very shitty solution for checking if a sprite needs flipping + // but it works + if ((speenframe > 4) && (sprframe->lumppat[speenframe] == sprframe->lumppat[8-speenframe])) + { + flags = V_FLIP; // This sprite is left/right flipped! + } + + patch = (patch_t *)W_CachePatchNum(sprframe->lumppat[speenframe], PU_PATCH); + + if (displayskin.flags & SF_HIRES) + { + V_DrawFixedPatch(mx< 1) ? "s" : "")); M_CentreText(OP_VideoModeDef.y + 158, "or press ESC to return"); - } else { @@ -10025,7 +10060,7 @@ static void M_DrawColorMenu(void) for (max = currentMenu->numitems; max > 0; max--) { - if (currentMenu->menuitems[max].status != IT_DISABLED && currentMenu->menuitems[max-1].alphaKey*2 + tempcentery <= (currentMenu->y + 2*scrollareaheight)) + if (currentMenu->menuitems[max-1].status != IT_DISABLED && currentMenu->menuitems[max-1].alphaKey*2 + tempcentery <= (currentMenu->y + 2*scrollareaheight)) break; } @@ -10561,6 +10596,20 @@ static void M_QuitSRB2(INT32 choice) M_StartMessage(quitmsg[M_RandomKey(NUM_QUITMESSAGES)], M_QuitResponse, MM_YESNO); } +// =========== +// SATURN MENU +// =========== + +static void M_SaturnReportIssue(INT32 choice) +{ + (void)choice; + int url = I_OpenURL(SATURNISSUEPAGE); + + // SDL_OpenURL unsupported or failed + if (url == -1) + M_StartMessage(M_GetText("Failed to Open Web Page.\nPlease open the following page in your web browser:\n\n" SATURNISSUEPAGE "\n\n(Press a key)\n"), NULL, MM_NOTHING); +} + #ifdef HAVE_DISCORDRPC // ===================================================================== diff --git a/src/m_menu.h b/src/m_menu.h index 62f66f177..2089900e3 100644 --- a/src/m_menu.h +++ b/src/m_menu.h @@ -26,7 +26,7 @@ extern "C" { #include "mserv.h" #include "r_things.h" // for SKINNAMESIZE -extern boolean forceshowhud; +extern boolean forceshowhud, forceshowchat; // // MENUS @@ -50,9 +50,6 @@ void M_Drawer(void); // Called by D_SRB2Main, loads the config file. void M_Init(void); -// Called by D_SRB2Main also, sets up the playermenu and description tables. -void M_InitCharacterTables(void); - // Called by intro code to force menu up upon a keypress, // does nothing if menu is already up. void M_StartControlPanel(void); @@ -84,11 +81,6 @@ typedef enum } menumessagetype_t; void M_StartMessage(const char *string, void *routine, menumessagetype_t itemtype); -extern boolean DPADUPSCROLL; -extern boolean DPADDOWNSCROLL; -extern boolean DPADLEFTSCROLL; -extern boolean DPADRIGHTSCROLL; - typedef enum { M_NOT_WAITING, @@ -168,8 +160,6 @@ boolean M_CanShowLevelInList(INT32 mapnum, INT32 gt); #define MAXMENUCCVARS 999 -#define MAXTOOLTIPS 255 - typedef union { struct menu_s *submenu; // IT_SUBMENU @@ -195,8 +185,6 @@ typedef struct menuitem_s UINT16 alphaKey; } menuitem_t; -extern menuitem_t PlayerMenu[MAXSKINS]; - typedef struct menu_s { const char *menutitlepic; @@ -227,14 +215,6 @@ extern menu_t SP_LoadDef; void M_SetupJoystickMenu(INT32 choice); extern menu_t OP_JoystickSetDef; -// Stuff for customizing the player select screen -typedef struct -{ - char notes[441]; - char picname[8]; - char skinname[SKINNAMESIZE*2+2]; // skin&skin\0 -} description_t; - // mode descriptions for video mode menu typedef struct { @@ -250,8 +230,8 @@ typedef struct char levelname[32]; UINT8 actnum; UINT8 skincolor; - UINT8 skinnum; - UINT8 botskin; + skinnum_t skinnum; + skinnum_t botskin; UINT8 botcolor; UINT8 numemeralds; INT32 lives; @@ -262,8 +242,6 @@ typedef struct extern INT32 mapwads[NUMMAPS]; -extern description_t description[MAXSKINS]; - extern consvar_t cv_replaysearchrate; extern consvar_t cv_showfocuslost; extern consvar_t cv_newgametype, cv_nextmap, cv_chooseskin, cv_serversort; @@ -398,7 +376,7 @@ void M_SlotCvarIntoModMenu(consvar_t* cvar, const char* category, const char* na NULL\ } -#define CONTROLMENUSTYLE(source, prev)\ +#define CONTROLMENUSTYLE(source, prev, tooltip)\ {\ "M_CONTRO",\ sizeof (source)/sizeof (menuitem_t),\ @@ -409,7 +387,7 @@ void M_SlotCvarIntoModMenu(consvar_t* cvar, const char* category, const char* na 26, 40,\ 0,\ NULL,\ - NULL\ + tooltip\ } #define IMAGEDEF(source)\ diff --git a/src/m_menudefs.c b/src/m_menudefs.c index 3d8d9549a..4a00f3020 100644 --- a/src/m_menudefs.c +++ b/src/m_menudefs.c @@ -36,6 +36,7 @@ static menu_t SP_TimeAttackDef, SP_ReplayDef, SP_GuestReplayDef, SP_GhostDef; menu_t OP_ControlsDef, OP_AllControlsDef; menu_t OP_MouseOptionsDef; menu_t OP_Joystick1Def, OP_Joystick2Def, OP_Joystick3Def, OP_Joystick4Def; +menu_t OP_Joystick1RumbleDef, OP_Joystick2RumbleDef, OP_Joystick3RumbleDef, OP_Joystick4RumbleDef; // Custom cvar menu menu_t OP_CustomCvarMenuDef; @@ -208,7 +209,7 @@ typedef enum static menuitem_t MPauseMenu[] = { {IT_STRING | IT_CALL, NULL, "Addons...", M_Addons, 8}, - {IT_STRING | IT_CALL, NULL, "Add local skins...", M_LocalSkins, 16}, + {IT_STRING | IT_CALL, NULL, "Local Add-ons...", M_LocalAddons, 8}, {IT_STRING | IT_SUBMENU, NULL, "Scramble Teams...", &MISC_ScrambleTeamDef, 24}, {IT_STRING | IT_CALL, NULL, "Switch Map..." , M_MapChange, 32}, @@ -238,7 +239,7 @@ static menuitem_t MPauseMenu[] = typedef enum { mpause_addons = 0, - mpause_addlocalskins, + mpause_localaddons, mpause_scramble, mpause_switchmap, #ifdef HAVE_DISCORDRPC @@ -446,25 +447,25 @@ enum static menuitem_t SP_ReplayMenu[] = { - {IT_WHITESTRING|IT_CALL, NULL, "Replay Best Time", M_ReplayTimeAttack, 90}, - {IT_WHITESTRING|IT_CALL, NULL, "Replay Best Lap", M_ReplayTimeAttack, 98}, + {IT_WHITESTRING|IT_CALL, NULL, "Replay Best Time", M_ReplayTimeAttack, 90}, + {IT_WHITESTRING|IT_CALL, NULL, "Replay Best Lap", M_ReplayTimeAttack, 98}, - {IT_WHITESTRING|IT_CALL, NULL, "Replay Last", M_ReplayTimeAttack, 106}, - {IT_WHITESTRING|IT_CALL, NULL, "Replay Guest", M_ReplayTimeAttack, 114}, - {IT_WHITESTRING|IT_KEYHANDLER, NULL, "Replay Staff",M_HandleStaffReplay,122}, + {IT_WHITESTRING|IT_CALL, NULL, "Replay Last", M_ReplayTimeAttack, 106}, + {IT_WHITESTRING|IT_CALL, NULL, "Replay Guest", M_ReplayTimeAttack, 114}, + {IT_WHITESTRING|IT_KEYHANDLER, NULL, "Replay Staff",M_HandleStaffReplay, 122}, - {IT_WHITESTRING|IT_SUBMENU, NULL, "Back", &SP_TimeAttackDef, 130} + {IT_WHITESTRING|IT_SUBMENU, NULL, "Back", &SP_TimeAttackDef, 130} }; static menuitem_t SP_GuestReplayMenu[] = { - {IT_WHITESTRING|IT_CALL, NULL, "Save Best Time as Guest", M_SetGuestReplay, 94}, - {IT_WHITESTRING|IT_CALL, NULL, "Save Best Lap as Guest", M_SetGuestReplay,102}, - {IT_WHITESTRING|IT_CALL, NULL, "Save Last as Guest", M_SetGuestReplay,110}, + {IT_WHITESTRING|IT_CALL, NULL, "Save Best Time as Guest", M_SetGuestReplay, 94}, + {IT_WHITESTRING|IT_CALL, NULL, "Save Best Lap as Guest", M_SetGuestReplay, 102}, + {IT_WHITESTRING|IT_CALL, NULL, "Save Last as Guest", M_SetGuestReplay, 110}, - {IT_WHITESTRING|IT_CALL, NULL, "Delete Guest Replay", M_SetGuestReplay,120}, + {IT_WHITESTRING|IT_CALL, NULL, "Delete Guest Replay", M_SetGuestReplay, 120}, - {IT_WHITESTRING|IT_SUBMENU, NULL, "Back", &SP_TimeAttackDef, 130} + {IT_WHITESTRING|IT_SUBMENU, NULL, "Back", &SP_TimeAttackDef, 130} }; static menuitem_t SP_GhostMenu[] = @@ -495,12 +496,6 @@ static menuitem_t SP_LevelStatsMenu[] = {IT_KEYHANDLER | IT_NOTHING, NULL, "", M_HandleLevelStats, '\0'}, // dummy menuitem for the control func }; -// A rare case. -// External files modify this menu, so we can't call it static. -// And I'm too lazy to go through and rename it everywhere. ARRGH! -#define M_ChoosePlayer NULL -menuitem_t PlayerMenu[MAXSKINS]; - // ----------------------------------- // Multiplayer and all of its submenus // ----------------------------------- @@ -561,10 +556,10 @@ static menuitem_t MP_PlayerSetupMenu[] = static menuitem_t MP_ConnectMenu[] = { - {IT_STRING | IT_CVAR, NULL, "Sort By", &cv_serversort, 0}, - {IT_STRING | IT_KEYHANDLER, NULL, "Page", M_HandleServerPage, 8}, - {IT_STRING | IT_CALL, NULL, "Refresh", M_Refresh, 16}, - {IT_STRING | IT_KEYHANDLER, NULL, "", M_HandleServerSearch,25}, + {IT_STRING | IT_CVAR, NULL, "Sort By", &cv_serversort, 0}, + {IT_STRING | IT_KEYHANDLER, NULL, "Page", M_HandleServerPage, 8}, + {IT_STRING | IT_CALL, NULL, "Refresh", M_Refresh, 16}, + {IT_STRING | IT_KEYHANDLER, NULL, "", M_HandleServerSearch, 25}, {IT_STRING | IT_SPACE, NULL, "", M_Connect, 48}, {IT_STRING | IT_SPACE, NULL, "", M_Connect, 60}, @@ -648,17 +643,6 @@ static menuitem_t OP_ControlsMenu[] = {IT_SUBMENU | IT_STRING, NULL, "Mouse Options...", &OP_MouseOptionsDef, 55}, {IT_STRING | IT_CVAR, NULL, "Controls per key", &cv_controlperkey, 75}, - - {IT_STRING | IT_CVAR, NULL, "Digital turn easing (P1)", &cv_turnsmooth[0], 85}, - {IT_STRING | IT_CVAR, NULL, "Digital turn easing (P2)", &cv_turnsmooth[1], 95}, - {IT_STRING | IT_CVAR, NULL, "Digital turn easing (P3)", &cv_turnsmooth[2], 105}, - {IT_STRING | IT_CVAR, NULL, "Digital turn easing (P4)", &cv_turnsmooth[3], 115}, - - // i hate our menus sincerly - {IT_STRING | IT_CVAR, NULL, "Lite Steer (P1)", &cv_litesteer[0], 135}, - {IT_STRING | IT_CVAR, NULL, "Lite Steer (P2)", &cv_litesteer[1], 145}, - {IT_STRING | IT_CVAR, NULL, "Lite Steer (P3)", &cv_litesteer[2], 155}, - {IT_STRING | IT_CVAR, NULL, "Lite Steer (P4)", &cv_litesteer[3], 165}, }; static const char* OP_ControlsTooltips[] = @@ -669,15 +653,6 @@ static const char* OP_ControlsTooltips[] = "Setup player 4 controls.", "Options for mouse control.", "Allowed amount of controls per key.", - "Turn smoothing for non-analog turning (Player 1).", - "Turn smoothing for non-analog turning (Player 2).", - "Turn smoothing for non-analog turning (Player 3).", - "Turn smoothing for non-analog turning (Player 4).", - - "Hold DOWN on d-pad/keyboard for shallow turns (Player 1).", - "Hold DOWN on d-pad/keyboard for shallow turns (Player 2).", - "Hold DOWN on d-pad/keyboard for shallow turns (Player 3).", - "Hold DOWN on d-pad/keyboard for shallow turns (Player 4).", }; static menuitem_t OP_AllControlsMenu[] = @@ -685,6 +660,13 @@ static menuitem_t OP_AllControlsMenu[] = {IT_SUBMENU|IT_STRING, NULL, "Gamepad Options...", &OP_Joystick1Def, 0}, {IT_CALL|IT_STRING, NULL, "Reset to defaults", M_ResetControls, 8}, + {IT_HEADER, NULL, "Control Options", NULL, 0}, + {IT_SPACE, NULL, NULL, NULL, 0}, + + // Cvars are set in M_SetupControlsMenu + {IT_STRING|IT_CVAR, NULL, "Lite Steer", &cv_litesteer[0], 18}, + {IT_STRING|IT_CVAR, NULL, "Digital turn easing", &cv_turnsmooth[0], 26}, + //{IT_SPACE, NULL, NULL, NULL, 0}, {IT_HEADER, NULL, "Gameplay Controls", NULL, 0}, {IT_SPACE, NULL, NULL, NULL, 0}, @@ -733,29 +715,47 @@ static menuitem_t OP_AllControlsMenu[] = {IT_CONTROL, NULL, "Custom Action 3", M_ChangeControl, gc_custom3 }, }; -#define OP_JOYMENU(pnum) \ - {IT_HEADER, NULL, "Gameplay Controls", NULL, 7}, \ - {IT_STRING | IT_CVAR, NULL, "Aim Forward/Back" , &cv_aimaxis[pnum] , 15}, \ - {IT_STRING | IT_CVAR, NULL, "Turn Left/Right" , &cv_turnaxis[pnum] , 20}, \ - {IT_STRING | IT_CVAR, NULL, "Accelerate" , &cv_moveaxis[pnum] , 25}, \ - {IT_STRING | IT_CVAR, NULL, "Brake" , &cv_brakeaxis[pnum] , 30}, \ - {IT_STRING | IT_CVAR, NULL, "Drift" , &cv_driftaxis[pnum] , 35}, \ - {IT_STRING | IT_CVAR, NULL, "Use Item" , &cv_fireaxis[pnum] , 40}, \ - {IT_STRING | IT_CVAR, NULL, "Look Backward" , &cv_lookbackaxis[pnum] , 45}, \ - {IT_STRING | IT_CVAR, NULL, "Custom Button 1" , &cv_custom1axis[pnum] , 50}, \ - {IT_STRING | IT_CVAR, NULL, "Custom Button 2" , &cv_custom2axis[pnum] , 55}, \ - {IT_STRING | IT_CVAR, NULL, "Custom Button 3" , &cv_custom3axis[pnum] , 60}, \ - {IT_HEADER, NULL, "Camera Controls", NULL, 67}, \ - {IT_STRING | IT_CVAR, NULL, "Look Up/Down" , &cv_lookaxis[pnum] , 75}, \ - {IT_STRING | IT_CVAR, NULL, "Turn Left/Right" , &cv_camturnaxis[pnum] , 80}, \ - {IT_STRING | IT_CVAR, NULL, "Strafe Left/Right" , &cv_camstrafeaxis[pnum] , 85}, \ - {IT_HEADER, NULL, "Deadzones", NULL, 92}, \ - {IT_STRING | IT_CVAR, NULL, "X deadzone" , &cv_xdeadzone[pnum] , 100}, \ - {IT_STRING | IT_CVAR, NULL, "Y deadzone" , &cv_ydeadzone[pnum] , 105}, \ - {IT_HEADER, NULL, "Miscellaneous", NULL, 112}, \ - {IT_STRING | IT_CVAR, NULL, "Controller Rumble" , &cv_rumble[pnum] , 120}, \ - {IT_STRING | IT_CVAR, NULL, "Controller Rumble Strength" , &cv_rumblestrength[pnum] , 125}, \ - {IT_STRING | IT_CVAR, NULL, "Set LED to Player color" , &cv_gamepadled[pnum] , 130}, +// Has to be same length as OP_AllControlsMenu, but otherwise its mostly empty +static const char* OP_AllControlsTooltips[sizeof(OP_AllControlsMenu)/sizeof(OP_AllControlsMenu[0])] = { + NULL, + NULL, + NULL, + NULL, + "Hold DOWN on d-pad/keyboard for shallow turns.", + "Turn smoothing for non-analog turning.", + // The rest is null, for now +}; + +// i really do not feel like messing with setup routines +// and macro preprocessor cannot eval maths for string shit like this :chaosleep: +#define RUMBDEF_0 OP_Joystick1RumbleDef +#define RUMBDEF_1 OP_Joystick2RumbleDef +#define RUMBDEF_2 OP_Joystick3RumbleDef +#define RUMBDEF_3 OP_Joystick4RumbleDef +#define RUMBDEF(x) RUMBDEF_##x + +#define OP_JOYMENU(pnum) \ + {IT_HEADER, NULL, "Gameplay Controls", NULL, 7}, \ + {IT_STRING | IT_CVAR, NULL, "Aim Forward/Back" , &cv_aimaxis[pnum] , 15}, \ + {IT_STRING | IT_CVAR, NULL, "Turn Left/Right" , &cv_turnaxis[pnum] , 20}, \ + {IT_STRING | IT_CVAR, NULL, "Accelerate" , &cv_moveaxis[pnum] , 25}, \ + {IT_STRING | IT_CVAR, NULL, "Brake" , &cv_brakeaxis[pnum] , 30}, \ + {IT_STRING | IT_CVAR, NULL, "Drift" , &cv_driftaxis[pnum] , 35}, \ + {IT_STRING | IT_CVAR, NULL, "Use Item" , &cv_fireaxis[pnum] , 40}, \ + {IT_STRING | IT_CVAR, NULL, "Look Backward" , &cv_lookbackaxis[pnum] , 45}, \ + {IT_STRING | IT_CVAR, NULL, "Custom Button 1" , &cv_custom1axis[pnum] , 50}, \ + {IT_STRING | IT_CVAR, NULL, "Custom Button 2" , &cv_custom2axis[pnum] , 55}, \ + {IT_STRING | IT_CVAR, NULL, "Custom Button 3" , &cv_custom3axis[pnum] , 60}, \ + {IT_HEADER, NULL, "Camera Controls", NULL, 67}, \ + {IT_STRING | IT_CVAR, NULL, "Look Up/Down" , &cv_lookaxis[pnum] , 75}, \ + {IT_STRING | IT_CVAR, NULL, "Turn Left/Right" , &cv_camturnaxis[pnum] , 80}, \ + {IT_STRING | IT_CVAR, NULL, "Strafe Left/Right" , &cv_camstrafeaxis[pnum] , 85}, \ + {IT_HEADER, NULL, "Deadzones", NULL, 92}, \ + {IT_STRING | IT_CVAR, NULL, "X deadzone" , &cv_xdeadzone[pnum] , 100}, \ + {IT_STRING | IT_CVAR, NULL, "Y deadzone" , &cv_ydeadzone[pnum] , 105}, \ + {IT_HEADER, NULL, "Miscellaneous", NULL, 112}, \ + {IT_SUBMENU|IT_STRING, NULL, "Rumble Options..." , &RUMBDEF(pnum) , 120}, \ + {IT_STRING | IT_CVAR, NULL, "Set LED to Player color" , &cv_gamepadled[pnum] , 125}, static menuitem_t OP_Joystick1Menu[] = { @@ -781,6 +781,46 @@ static menuitem_t OP_Joystick4Menu[] = OP_JOYMENU(3) }; +#undef RUMBDEF +#undef RUMBDEF_0 +#undef RUMBDEF_1 +#undef RUMBDEF_2 +#undef RUMBDEF_3 + +// FIXME: stair jank rumble should be greyed out if its disabled, but menus suck butt! +#define OP_JOYRUMBLEMENU(pnum) \ + {IT_HEADER, NULL, "Global", NULL, 7}, \ + {IT_STRING | IT_CVAR, NULL, "Controller Rumble" , &cv_rumble[pnum] , 15}, \ + {IT_STRING | IT_CVAR, NULL, "Controller Rumble Strength" , &cv_rumble_strength[pnum] , 20}, \ + {IT_HEADER, NULL, "Rumble Types", NULL, 27}, \ + {IT_STRING | IT_CVAR, NULL, "Spinout" , &cv_rumble_spinout[pnum] , 35}, \ + {IT_STRING | IT_CVAR, NULL, "Sneaker Boost" , &cv_rumble_sneakerboost[pnum] , 40}, \ + {IT_STRING | IT_CVAR, NULL, "Offroad" , &cv_rumble_offroad[pnum] , 45}, \ + {IT_STRING | IT_CVAR, NULL, "Banana Dragging" , &cv_rumble_bananadrag[pnum] , 50}, \ + {IT_STRING | IT_CVAR, NULL, "Stair Jank" , &cv_rumble_stairjank[pnum] , 55}, \ + {IT_STRING | IT_CVAR, NULL, "Brake Drift" , &cv_rumble_brakedrift[pnum] , 60}, \ + {IT_STRING | IT_CVAR, NULL, "Drift Charge" , &cv_rumble_driftcharge[pnum] , 65}, \ + +static menuitem_t OP_Joystick1RumbleMenu[] = +{ + OP_JOYRUMBLEMENU(0) +}; + +static menuitem_t OP_Joystick2RumbleMenu[] = +{ + OP_JOYRUMBLEMENU(1) +}; + +static menuitem_t OP_Joystick3RumbleMenu[] = +{ + OP_JOYRUMBLEMENU(2) +}; + +static menuitem_t OP_Joystick4RumbleMenu[] = +{ + OP_JOYRUMBLEMENU(3) +}; + static menuitem_t OP_JoystickSetMenu[] = { {IT_CALL | IT_NOTHING, "None", NULL, M_AssignJoystick, LINEHEIGHT+5}, @@ -797,10 +837,9 @@ static menuitem_t OP_JoystickSetMenu[] = static menuitem_t OP_MouseOptionsMenu[] = { {IT_STRING | IT_CVAR, NULL, "Use Mouse", &cv_usemouse, 10}, - {IT_STRING | IT_CVAR, NULL, "Mouse Turning", &cv_mouseturn, 20}, {IT_STRING | IT_CVAR, NULL, "Invert Mouse", &cv_invertmouse, 30}, - {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Mouse X Speed", &cv_mousexsens, 40}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Mouse X Speed", &cv_mousexsens, 40}, {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Mouse Y Speed", &cv_mouseysens, 50}, }; @@ -869,7 +908,6 @@ static const char* OP_VideoTooltips[] = "Advanced graphical options.", }; - enum { op_video_res = 0, @@ -953,24 +991,25 @@ static menuitem_t OP_ExpOptionsMenu[] = //{IT_STRING | IT_CVAR, NULL, "Randomized Directional Light", &cv_randomdirlight, 45}, // should this ever come back {IT_STRING | IT_CVAR, NULL, "Skyboxes", &cv_skybox, 40}, + {IT_STRING | IT_CVAR, NULL, "Skydome", &cv_skydome, 45}, - {IT_STRING | IT_CVAR, NULL, "Precache Level Textures", &cv_precachetextures, 50}, + {IT_STRING | IT_CVAR, NULL, "Precache Level Textures", &cv_precachetextures, 55}, - {IT_STRING | IT_CVAR, NULL, "FPS counter sampling", &cv_accuratefps, 60}, + {IT_STRING | IT_CVAR, NULL, "FPS counter sampling", &cv_accuratefps, 65}, - {IT_STRING | IT_CVAR, NULL, "Frameskip", &cv_frameskip, 70}, + {IT_STRING | IT_CVAR, NULL, "Frameskip", &cv_frameskip, 75}, - {IT_STRING | IT_CVAR, NULL, "Votescreen Scaling", &cv_votebgscaling, 80}, + {IT_STRING | IT_CVAR, NULL, "Votescreen Scaling", &cv_votebgscaling, 85}, #ifdef HWRENDER - {IT_STRING | IT_CVAR, NULL, "Screen Textures", &cv_glscreentextures, 90}, + {IT_STRING | IT_CVAR, NULL, "Screen Textures", &cv_glscreentextures, 95}, #ifdef USE_FBO_OGL - {IT_STRING | IT_CVAR, NULL, "FBO Downsampling support", &cv_glframebuffer, 95}, - {IT_STRING | IT_CVAR, NULL, "Palette Depth", &cv_glpalettedepth, 105}, - {IT_DISABLED, NULL, "", NULL, 115}, // dummy text + {IT_STRING | IT_CVAR, NULL, "FBO Downsampling support", &cv_glframebuffer, 100}, + {IT_STRING | IT_CVAR, NULL, "Palette Depth", &cv_glpalettedepth, 110}, + {IT_DISABLED, NULL, "", NULL, 120}, // dummy text #else - {IT_STRING | IT_CVAR, NULL, "Palette Depth", &cv_glpalettedepth, 100}, - {IT_DISABLED, NULL, "", NULL, 110}, // dummy text + {IT_STRING | IT_CVAR, NULL, "Palette Depth", &cv_glpalettedepth, 110}, + {IT_DISABLED, NULL, "", NULL, 120}, // dummy text #endif #endif }; @@ -983,12 +1022,13 @@ static const char* OP_ExpTooltips[] = "Sets minimum sector brightness, useful for dark areas.", //"Should the directional lightning be randomized each map?\nTakes effect on next map load.", "Toggle being able to see the sky.", + "Toggle skydome.", // idk man someone give a better description of this "Preload all level textures on level load.\nMassively reduces texture related stuttering during gameplay\nat the cost of longer level loading times.\nDisable this if you experience timeouts during level switches.", "Change the FPS counter sampling method\nInaccurate updates slower\nand might miss sudden framerate changes and drops,\nproviding a more averaged result.\nAccurate updates faster, but might be less readable.", // how to ingles?? "Skips rendering frames if game logic takes too long\npreventing gameplay issues during performance drops.", // idk im shit as describing things "Different methods of scaling the votescreen backgrounds.", #ifdef HWRENDER - "Should the game do Screen Textures? Provides a good boost to frames\nat the cost of some visual effects not working when disabled.", + "Disabling Screen Textures may result in a performance boost\nbut will break certain effects.\nScreen textures are required at resolutions lower than your desktop resolution!", #ifdef USE_FBO_OGL "Allows the game to downsample from a higher resolution\nthan your display in OpenGL renderer mode.\nRequires a GPU with atleast OpenGL 2.1 support.", #endif @@ -1004,6 +1044,7 @@ enum op_exp_secbright, //op_exp_dirlight, op_exp_skybox, + op_exp_skydome, op_exp_texcache, op_exp_accuratefps, op_exp_frameskip, @@ -1017,7 +1058,6 @@ enum #endif }; - #ifdef HWRENDER static menuitem_t OP_OpenGLOptionsMenu[] = { @@ -1025,20 +1065,18 @@ static menuitem_t OP_OpenGLOptionsMenu[] = {IT_STRING | IT_CVAR, NULL, "Fallback Player 3D Model", &cv_glfallbackplayermodel, 20}, {IT_STRING | IT_CVAR, NULL, "Shaders", &cv_glshaders, 25}, {IT_STRING | IT_CVAR, NULL, "Palette Rendering", &cv_glpaletterendering, 30}, - {IT_STRING | IT_CVAR, NULL, "Palette Rendering Flashpals",&cv_glflashpal, 35}, - //{IT_STRING | IT_CVAR, NULL, "Min Shader Brightness", &cv_glsecbright, 40}, - {IT_STRING | IT_CVAR, NULL, "Texture Quality", &cv_gltexturedepth, 45}, - {IT_STRING | IT_CVAR, NULL, "Texture Filter", &cv_glfiltermode, 50}, - {IT_STRING | IT_CVAR, NULL, "Anisotropic", &cv_glanisotropicmode, 55}, - {IT_STRING | IT_CVAR, NULL, "Visual Portals", &cv_glportals, 60}, + {IT_STRING | IT_CVAR, NULL, "Texture Quality", &cv_gltexturedepth, 40}, + {IT_STRING | IT_CVAR, NULL, "Texture Filter", &cv_glfiltermode, 45}, + {IT_STRING | IT_CVAR, NULL, "Anisotropic", &cv_glanisotropicmode, 50}, + {IT_STRING | IT_CVAR, NULL, "Visual Portals", &cv_glportals, 55}, - {IT_STRING | IT_CVAR, NULL, "Wall Contrast Style", &cv_glfakecontrast, 70}, - {IT_STRING | IT_CVAR, NULL, "Slope Contrast", &cv_glslopecontrast, 75}, - {IT_STRING | IT_CVAR, NULL, "Dithered Lightning", &cv_gllightdither, 80}, - {IT_STRING | IT_CVAR, NULL, "Sprite Billboarding", &cv_glspritebillboarding, 85}, - {IT_STRING | IT_CVAR, NULL, "Software Perspective", &cv_glshearing, 90}, - {IT_STRING | IT_CVAR, NULL, "Rendering Distance", &cv_glrenderdistance, 95}, + {IT_STRING | IT_CVAR, NULL, "Wall Contrast Style", &cv_glfakecontrast, 65}, + {IT_STRING | IT_CVAR, NULL, "Slope Contrast", &cv_glslopecontrast, 70}, + {IT_STRING | IT_CVAR, NULL, "Dithered Lightning", &cv_gllightdither, 75}, + {IT_STRING | IT_CVAR, NULL, "Sprite Billboarding", &cv_glspritebillboarding, 80}, + {IT_STRING | IT_CVAR, NULL, "Software Perspective", &cv_glshearing, 85}, + {IT_STRING | IT_CVAR, NULL, "Rendering Distance", &cv_glrenderdistance, 90}, }; static const char* OP_OpenGLTooltips[] = @@ -1047,7 +1085,6 @@ static const char* OP_OpenGLTooltips[] = "Fallback 3D model for characters that don't have any.", "Graphical Shaders.", "Recreates the look of software mode.", - "Flash palettes for palette rendering.", "Bit-depth of textures.", "Filter to use on textures.", "Anisotropic filtering.", @@ -1066,7 +1103,6 @@ enum op_gl_falbckmdls, op_gl_shader, op_gl_palrender, - op_gl_flashpal, op_gl_scrdepth, op_gl_filter, op_gl_anis, @@ -1078,7 +1114,6 @@ enum op_gl_shearing, op_gl_renderdist, }; - #endif static menuitem_t OP_SoundOptionsMenu[] = @@ -1089,8 +1124,7 @@ static menuitem_t OP_SoundOptionsMenu[] = {IT_STRING|IT_CVAR|IT_CV_NOPRINT, NULL, "Music", &cv_gamedigimusic, 30}, {IT_STRING|IT_CVAR|IT_CV_SLIDER, NULL, "Music Volume", &cv_digmusicvolume, 38}, -//#ifndef NO_MIDI -#if 0 +#if 0 //#ifndef NO_MIDI {IT_STRING|IT_CVAR|IT_CV_SLIDER, NULL, "MIDI Volume", &cv_midimusicvolume, 46}, {IT_STRING|IT_CVAR, NULL, "Reverse L/R Channels", &stereoreverse, 60}, @@ -1125,8 +1159,7 @@ static const char* OP_SoundTooltips[] = "Volume of Sound effects.", "Turn Music on or off.", "Volume of Music.", -//#ifndef NO_MIDI -#if 0 +#if 0 //#ifndef NO_MIDI "Volume of Midi Music.", #endif "Reverse left and right channels of audio.", @@ -1186,7 +1219,7 @@ static const char* OP_SoundAdvancedTooltips[] = "Should the Grow music be on or off?", "Should the Invulnerability music be on or off?", "Should music be kept when restarting the map?", - "Should the Intro fanfare be skipped\nand map music be played on map start?", + "Should the Intro fanfare be skipped\nand map music be played on map start?\nNote that this WILL skip sounds played by the map before round start as well!", "Controls Sound effects caching.\nKeep will retain previously played sound effects in cache." // man idk how to describe this in a non awful way lmao "\nOn will preload all sound effects.\nEliminates sound-related lag and stutters but increases memory usage.", "Size of the Audio Buffer\nreducing it will result in less sound latency\nbut may cause issues such as crackling or distorted Sound.", @@ -1197,16 +1230,20 @@ static menuitem_t OP_FocusOptionsMenu[] = { {IT_HEADER, NULL, "Game Focus Options", NULL, 0}, - {IT_STRING|IT_CVAR, NULL, "Play Music While Unfocused", &cv_playmusicifunfocused, 30}, - {IT_STRING|IT_CVAR, NULL, "Play SFX While Unfocused", &cv_playsoundifunfocused, 40}, + {IT_STRING|IT_CVAR, NULL, "Play Music While Unfocused", &cv_playmusicifunfocused, 10}, + {IT_STRING|IT_CVAR, NULL, "Play SFX While Unfocused", &cv_playsoundifunfocused, 20}, - {IT_STRING|IT_CVAR, NULL, "Pause Game While Unfocused", &cv_pauseifunfocused, 60}, + {IT_STRING|IT_CVAR, NULL, "Pause Game While Unfocused", &cv_pauseifunfocused, 40}, - {IT_STRING|IT_CVAR, NULL, "Background FPS Cap", &cv_fpscapbg, 80}, + {IT_STRING|IT_CVAR, NULL, "Background FPS Cap", &cv_fpscapbg, 60}, - {IT_STRING|IT_CVAR, NULL, "Show \"FOCUS LOST\"", &cv_showfocuslost, 100}, + {IT_STRING|IT_CVAR, NULL, "Show \"FOCUS LOST\"", &cv_showfocuslost, 80}, - {IT_STRING|IT_CVAR, NULL, "Visible Mouse", &cv_mousevisible, 120}, + {IT_STRING|IT_CVAR, NULL, "Visible Mouse", &cv_mousevisible, 100}, + + {IT_STRING|IT_CVAR, NULL, "Gamepad Inputs While Unfocused", &cv_gamepadifunfocused, 120}, + {IT_STRING|IT_CVAR, NULL, "Gamepad LED Color While Unfocused ", &cv_gamepadledifunfocused, 130}, + {IT_STRING|IT_CVAR, NULL, "Gamepad Rumble While Unfocused", &cv_rumbleifunfocused, 140}, }; static const char* OP_FocusOptionsTooltips[] = @@ -1218,6 +1255,9 @@ static const char* OP_FocusOptionsTooltips[] = "Set manual framerate cap while the game is unfocused.", "Should the FOCUS LOST window appear\n while the game is unfocused?", "Displays the mouse cursor while the game is in focus.", + "Should gamepad still control the game when unfocused?", + "Should gamepad LED indicator change color when unfocused?", + "Should gamepad rumble apply when unfocused?", }; static menuitem_t OP_DataOptionsMenu[] = @@ -1310,29 +1350,29 @@ static menuitem_t OP_DiscordOptionsMenu[] = static menuitem_t OP_HUDOptionsMenu[] = { - {IT_STRING | IT_CVAR, NULL, "Show HUD (F3)", &cv_showhud, 10}, + {IT_STRING | IT_CVAR, NULL, "Show HUD (F3)", &cv_showhud, 10}, {IT_STRING | IT_CVAR | IT_CV_SLIDER, - NULL, "HUD Visibility", &cv_translucenthud, 20}, + NULL, "HUD Visibility", &cv_translucenthud, 20}, - {IT_STRING | IT_SUBMENU, NULL, "Online HUD options...", &OP_ChatOptionsDef, 35}, - {IT_STRING | IT_CVAR, NULL, "Background Glass", &cons_backcolor, 45}, + {IT_STRING | IT_SUBMENU, NULL, "Online HUD options...", &OP_ChatOptionsDef, 35}, + {IT_STRING | IT_CVAR, NULL, "Background Glass", &cons_backcolor, 45}, {IT_STRING | IT_CVAR | IT_CV_SLIDER, - NULL, "Minimap Visibility", &cv_kartminimap, 60}, - {IT_STRING | IT_CVAR, NULL, "Speedometer Display", &cv_kartspeedometer, 70}, - {IT_STRING | IT_CVAR, NULL, "Show \"CHECK\"", &cv_kartcheck, 80}, + NULL, "Minimap Visibility", &cv_kartminimap, 60}, + {IT_STRING | IT_CVAR, NULL, "Speedometer Display", &cv_kartspeedometer, 70}, + {IT_STRING | IT_CVAR, NULL, "Show \"CHECK\"", &cv_kartcheck, 80}, - {IT_STRING | IT_CVAR, NULL, "Menu Highlights", &cons_menuhighlight, 95}, + {IT_STRING | IT_CVAR, NULL, "Menu Highlights", &cons_menuhighlight, 95}, // highlight info - (GOOD HIGHLIGHT, WARNING HIGHLIGHT) - 110 (see M_DrawHUDOptions) - {IT_STRING | IT_CVAR, NULL, "Console Text Size", &cv_constextsize, 120}, - {IT_STRING | IT_CVAR, NULL, "Show Console Prints in Menu",&cons_consoleprintinmenu, 130}, + {IT_STRING | IT_CVAR, NULL, "Console Text Size", &cv_constextsize, 120}, + {IT_STRING | IT_CVAR, NULL, "Show Console Prints in Menu",&cons_consoleprintinmenu, 130}, - {IT_STRING | IT_CVAR, NULL, "Show Track Addon Name", &cv_showtrackaddon, 145}, + {IT_STRING | IT_CVAR, NULL, "Show Track Addon Name", &cv_showtrackaddon, 145}, - {IT_STRING | IT_CVAR, NULL, "Show All Maps", &cv_showallmaps, 155}, + {IT_STRING | IT_CVAR, NULL, "Show All Maps", &cv_showallmaps, 155}, - {IT_STRING | IT_CVAR, NULL, "2D character select", &cv_skinselectmenu, 165}, + {IT_STRING | IT_CVAR, NULL, "2D character select", &cv_skinselectmenu, 165}, }; static menuitem_t OP_CamOptionsMenu[] = @@ -1341,16 +1381,19 @@ static menuitem_t OP_CamOptionsMenu[] = {IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Field of View",&cv_fov, 30}, - {IT_STRING | IT_SUBMENU, NULL, "Player 1 Camera options...", &OP_Player1CamOptionsDef, 50}, - {IT_STRING | IT_SUBMENU, NULL, "Player 2 Camera options...", &OP_Player2CamOptionsDef, 60}, - {IT_STRING | IT_SUBMENU, NULL, "Player 3 Camera options...", &OP_Player3CamOptionsDef, 70}, - {IT_STRING | IT_SUBMENU, NULL, "Player 4 Camera options...", &OP_Player4CamOptionsDef, 80}, + {IT_STRING | IT_CVAR, NULL, "Flipcam Mode", &cv_flipcammode, 40}, + + {IT_STRING | IT_SUBMENU, NULL, "Player 1 Camera options...", &OP_Player1CamOptionsDef, 60}, + {IT_STRING | IT_SUBMENU, NULL, "Player 2 Camera options...", &OP_Player2CamOptionsDef, 70}, + {IT_STRING | IT_SUBMENU, NULL, "Player 3 Camera options...", &OP_Player3CamOptionsDef, 80}, + {IT_STRING | IT_SUBMENU, NULL, "Player 4 Camera options...", &OP_Player4CamOptionsDef, 90}, }; static const char* OP_CamOptionsTooltips[] = { NULL, "Player field of view.", + "Change flipcam mode.\nDisplayplayer - use currently viewed player option.\nLocal - use local flipcam toggle option.", NULL, NULL, NULL, @@ -1410,44 +1453,70 @@ static const char* OP_PlayerCamOptionsTooltips[] = static menuitem_t OP_ChatOptionsMenu[] = { // will ANYONE who doesn't know how to use the console want to touch this one? - {IT_STRING | IT_CVAR, NULL, "Chat Mode", &cv_consolechat, 5}, // nonetheless... + {IT_STRING | IT_CVAR, NULL, "Chat Mode", &cv_consolechat, 5}, // nonetheless... {IT_STRING | IT_CVAR | IT_CV_SLIDER, - NULL, "Chat Box Width", &cv_chatwidth, 20}, + NULL, "Chat Box Width", &cv_chatwidth, 10}, {IT_STRING | IT_CVAR | IT_CV_SLIDER, - NULL, "Chat Box Height", &cv_chatheight, 30}, - {IT_STRING | IT_CVAR, NULL, "Center Text in Chat", &cv_chatcentertext, 40}, + NULL, "Chat Box Height", &cv_chatheight, 15}, + {IT_STRING | IT_CVAR, NULL, "Chat Horizontal Offset", &cv_chat_xoffset, 20}, + {IT_STRING | IT_CVAR, NULL, "Chat Vertical Offset", &cv_chat_yoffset, 25}, - {IT_STRING | IT_CVAR, NULL, "Chat Background Tint", &cv_chatbacktint, 55}, - {IT_STRING | IT_CVAR, NULL, "Message Fadeout Time", &cv_chattime, 65}, - {IT_STRING | IT_CVAR, NULL, "Spam Protection", &cv_chatspamprotection, 75}, - {IT_STRING | IT_CVAR, NULL, "Max Chat Messages", &cv_chatlogsize, 85}, + {IT_STRING | IT_CVAR, NULL, "Center Text in Chat", &cv_chatcentertext, 35}, + {IT_STRING | IT_CVAR, NULL, "Chat Background Tint", &cv_chatbacktint, 40}, + {IT_STRING | IT_CVAR, NULL, "Message Fadeout Time", &cv_chattime, 45}, + {IT_STRING | IT_CVAR, NULL, "Spam Protection", &cv_chatspamprotection, 50}, + {IT_STRING | IT_CVAR, NULL, "Max Chat Messages", &cv_chatlogsize, 55}, + {IT_STRING | IT_CVAR, NULL, "Display Character Limit", &cv_chat_showlimit, 60}, - {IT_STRING | IT_CVAR, NULL, "Local ping display", &cv_showping, 105}, // shows ping above the framerate if we want to. - {IT_STRING | IT_CVAR, NULL, "Ping display style", &cv_pingstyle, 115}, - {IT_STRING | IT_CVAR, NULL, "Ping measurement", &cv_pingmeasurement, 125}, - {IT_STRING | IT_CVAR, NULL, "Ping icon", &cv_pingicon, 135}, + {IT_STRING | IT_CVAR, NULL, "Local ping display", &cv_showping, 70}, // shows ping above the framerate if we want to. + {IT_STRING | IT_CVAR, NULL, "Ping display style", &cv_pingstyle, 75}, + {IT_STRING | IT_CVAR, NULL, "Ping measurement", &cv_pingmeasurement, 80}, + {IT_STRING | IT_CVAR, NULL, "Ping icon", &cv_pingicon, 85}, - {IT_STRING | IT_CVAR, NULL, "Show IP address in playerlist", &cv_shownodeip, 145}, + {IT_STRING | IT_CVAR, NULL, "Show IP address in playerlist", &cv_shownodeip, 90}, }; static const char* OP_ChatOptionsTooltips[] = { "Chat mode used for in-game chat.", - "Width of chat box.", - "Height of chat box.", + "Width of the chat box.", + "Height of the chat box.", + "Horizontal Offset of the chat box.", + "Vertical Offset of the chat box.", "Center text in the chat message pop ups.", - "Chatbox background.", + "Background for the chat message pop ups.", "Fadeout time for new chat message.", "Spam protection for in-game chat.", "Maxiumum amount of chat messages to look back at.", + "Show how many characters you have left to type in the chat.", "Show player ping.", - "Choose the looks of the ping display.", // this is ass idk english lmao + "Choose the style of the ping display.", "Measurement used for ping.", "Visibility of ping icon.", "Should Player IP addresses be printed when using\nthe nodes or listplayers command?", }; +enum +{ + op_chat_mode, + op_chat_boxwidth, + op_chat_boxheight, + op_chat_yoffs, + op_chat_xoffs, + op_chat_centertxt, + op_chat_bgtint, + op_chat_fadetime, + op_chat_spamprotect, + op_chat_maxmsg, + op_chat_charlmt, + op_chat_showping, + op_chat_pingstyle, + op_chat_pingmeasr, + op_chat_pingico, + op_chat_nodeip, +}; + static menuitem_t OP_GameOptionsMenu[] = { {IT_STRING | IT_SUBMENU, NULL, "Random Item Toggles...", &OP_MonitorToggleDef, 10}, @@ -1632,13 +1701,10 @@ static menuitem_t OP_AccessibilityMenu[] = {IT_STRING|IT_CVAR|IT_CV_SLIDER, NULL, "Saturation", &cv_globalsaturation, 25}, {IT_SUBMENU|IT_STRING, NULL, "Video Color Settings...", &OP_ColorOptionsDef, 30}, - {IT_STRING|IT_CVAR, NULL, "Midnight Channel Flicker", &cv_lessflicker, 35}, + {IT_STRING|IT_CVAR, NULL, "Reduce Effects", &cv_reducevfx, 35}, + {IT_STRING|IT_CVAR, NULL, "Less Midnight Channel Flicker", &cv_lessflicker, 40}, // obsolete now? or still better be a seperate toggle? - {IT_STRING|IT_CVAR, NULL, "Minimum Sector Brightness", &cv_secbright, 40}, - -#ifdef HWRENDER - {IT_STRING|IT_CVAR, NULL, "Screen Textures", &cv_glscreentextures, 45}, -#endif + {IT_STRING|IT_CVAR, NULL, "Minimum Sector Brightness", &cv_secbright, 45}, {IT_STRING|IT_CVAR, NULL, "Water Surface Ripples", &cv_ripplewater, 50}, @@ -1646,12 +1712,19 @@ static menuitem_t OP_AccessibilityMenu[] = {IT_STRING|IT_CVAR, NULL, "Quake Screenshakes", &cv_screenquake, 60}, - {IT_CALL|IT_STRING, NULL, "Camera Options...", M_CameraMenu, 65}, + {IT_CALL|IT_STRING, NULL, "Camera Options...", M_CameraMenu, 65}, {IT_HEADER, NULL, "Audio", NULL, 75}, {IT_STRING|IT_CVAR, NULL, "Reverse L/R Channels", &stereoreverse, 85}, {IT_STRING|IT_CVAR, NULL, "Same Sound Limit", &cv_samesoundlimit, 90}, + + {IT_HEADER, NULL, "Controls", NULL, 100}, + + {IT_STRING|IT_CVAR, NULL, "Automatic Acceleration (P1)", &cv_autoaccel[0], 110}, + {IT_STRING|IT_CVAR, NULL, "Automatic Acceleration (P2)", &cv_autoaccel[1], 115}, + {IT_STRING|IT_CVAR, NULL, "Automatic Acceleration (P3)", &cv_autoaccel[2], 120}, + {IT_STRING|IT_CVAR, NULL, "Automatic Acceleration (P4)", &cv_autoaccel[3], 125}, }; static const char* OP_AccessibilityTooltips[] = @@ -1661,11 +1734,9 @@ static const char* OP_AccessibilityTooltips[] = "Gamma (brightness) of the game.", "Saturation of the game.", "Advanced color settings of the game.", + "Reduces or disables certain effects players might be sensitive to\nSuch as flashing, flickering, certain screen effects and more.", "Disables the flicker effect on Midnight Channel.", "Sets minimum sector brightness, useful for dark areas", -#ifdef HWRENDER - "Should the game do Screen Textures? Provides a good boost to frames\nat the cost of some visual effects not working when disabled.", -#endif "Toggles the ripple effect on water surfaces", "Fades other Players that are close to the camera in and out", "Toggles the screen shake effect during Earthquakes", @@ -1673,6 +1744,11 @@ static const char* OP_AccessibilityTooltips[] = NULL, "Reverse left and right channels of audio.", "Change how often the same Sound is allowed to play at once.", + NULL, + "Automatically hold acceleration button (Player 1).", + "Automatically hold acceleration button (Player 2).", + "Automatically hold acceleration button (Player 3).", + "Automatically hold acceleration button (Player 4).", }; static menuitem_t OP_SaturnMenu[] = @@ -1684,29 +1760,31 @@ static menuitem_t OP_SaturnMenu[] = {IT_STRING | IT_CVAR, NULL, "Minimum Input Delay", &cv_mindelay, 20}, {IT_STRING | IT_CVAR, NULL, "Gentlemens Ping", &cv_gentlemens, 25}, {IT_STRING | IT_CVAR, NULL, "Server Info Screen", &cv_serverinfoscreen, 30}, + {IT_STRING | IT_CVAR, NULL, "Server Addons Info", &cv_serveraddoninfo, 35}, - {IT_STRING | IT_CVAR, NULL, "Skin Select Spinning Speed", &cv_skinselectspin, 40}, + {IT_STRING | IT_CVAR, NULL, "Skin Select Spinning Speed", &cv_skinselectspin, 45}, - {IT_STRING | IT_CVAR, NULL, "Colorized Speedlines", &cv_coloredspeedlines, 50}, - {IT_STRING | IT_CVAR, NULL, "Colorized Sneakertrails", &cv_coloredsneakertrail, 55}, + {IT_STRING | IT_CVAR, NULL, "Colorized Speedlines", &cv_coloredspeedlines, 55}, + {IT_STRING | IT_CVAR, NULL, "Colorized Sneakertrails", &cv_coloredsneakertrail, 60}, - {IT_STRING | IT_CVAR, NULL, "Player Blendeffects", &cv_playerblendeffects, 65}, + {IT_STRING | IT_CVAR, NULL, "Player Blendeffects", &cv_playerblendeffects, 70}, - {IT_STRING | IT_CVAR, NULL, "Bananadrag Jitter", &cv_bananajitter, 75}, + {IT_STRING | IT_CVAR, NULL, "Bananadrag Jitter", &cv_bananajitter, 80}, - {IT_STRING | IT_CVAR, NULL, "Midair Driftsparks", &cv_airsparks, 85}, + {IT_STRING | IT_CVAR, NULL, "Midair Driftsparks", &cv_airsparks, 90}, - {IT_STRING | IT_CVAR, NULL, "Show Localskin Menus", &cv_showlocalskinmenus, 95}, + {IT_STRING | IT_CVAR, NULL, "Show Localskin Menus", &cv_showlocalskinmenus, 100}, - {IT_STRING | IT_CVAR, NULL, "Uppercase Menu", &cv_menucaps, 105}, + {IT_STRING | IT_CVAR, NULL, "Uppercase Menu", &cv_menucaps, 110}, - {IT_STRING | IT_CVAR, NULL, "Keyboard Layout", &cv_keyboardlayout, 115}, + {IT_STRING | IT_CVAR, NULL, "Keyboard Layout", &cv_keyboardlayout, 120}, - {IT_STRING | IT_CVAR, NULL, "Less Midnight Channel Flicker", &cv_lessflicker, 125}, + {IT_STRING | IT_CVAR, NULL, "Less Midnight Channel Flicker", &cv_lessflicker, 130}, - {IT_SUBMENU|IT_STRING, NULL, "Saturn Hud...", &OP_SaturnHudDef, 135}, - {IT_SUBMENU|IT_STRING, NULL, "Sprite Distortion...", &OP_PlayerDistortDef, 140}, - {IT_SUBMENU|IT_STRING, NULL, "Saturn Credits", &OP_SaturnCreditsDef, 145}, // uwu + {IT_SUBMENU|IT_STRING, NULL, "Saturn Hud...", &OP_SaturnHudDef, 140}, + {IT_SUBMENU|IT_STRING, NULL, "Sprite Distortion...", &OP_PlayerDistortDef, 145}, + {IT_SUBMENU|IT_STRING, NULL, "Saturn Credits", &OP_SaturnCreditsDef, 150}, // uwu + {IT_STRING|IT_CALL, NULL, "Report an Issue", M_SaturnReportIssue, 155} }; static const char* OP_SaturnTooltips[] = @@ -1716,6 +1794,7 @@ static const char* OP_SaturnTooltips[] = "Practice for online play! 0 = instant response.", "Simulate online input delay when hosting a server.\nValue choosen by Player with the lowest ping", "Show a screen before joining a server displaying important information about it", + "Show amount and types of addons that are loaded by server when joining", "How much speen do you want?", "Colourize the speedlines in your skincolor if you go fast enough!", "Colourize the sneaker flame trails in your skincolor!", @@ -1729,6 +1808,7 @@ static const char* OP_SaturnTooltips[] = "Options for Saturn specific HUD things.", "Options for sprite distortion effects.", "See the people who helped make this project possible!", + "Noticed a bug, have a Suggestion or other Feedback?\nFeel free to tell us!", }; enum @@ -1750,6 +1830,7 @@ enum sm_hud, sm_distortionmenu, sm_credits, + sm_issue, }; static menuitem_t OP_PlayerDistortMenu[] = @@ -1760,20 +1841,23 @@ static menuitem_t OP_PlayerDistortMenu[] = {IT_STRING | IT_CVAR, NULL, "Slope Rotation Distance", &cv_sloperolldist, 15}, {IT_STRING | IT_CVAR, NULL, "Rotate Players when Sliptiding", &cv_sliptideroll, 25}, - {IT_STRING | IT_CVAR, NULL, "Rotate Sparks and Boost Trails", &cv_sparkroll, 30}, - {IT_STRING | IT_CVAR, NULL, "Rotate Bananas on Throw", &cv_bananthrowroll, 35}, + {IT_STRING | IT_CVAR, NULL, "Stair Janking Effect", &cv_stairjank, 30}, + {IT_STRING | IT_CVAR, NULL, "Stair Janking Sound Effect", &cv_stairjanksfx, 35}, // idk if that should be here but i dont care atm - {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Player Stretch Factor", &cv_gravstretch, 45}, - {IT_STRING | IT_CVAR, NULL, "Squish Sound Effect", &cv_slamsound, 50}, + {IT_STRING | IT_CVAR, NULL, "Rotate Sparks and Boost Trails", &cv_sparkroll, 40}, + {IT_STRING | IT_CVAR, NULL, "Rotate Bananas on Throw", &cv_bananthrowroll, 45}, - {IT_STRING | IT_CVAR, NULL, "Saltyhop", &cv_saltyhop, 60}, - {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Saltyhop Height", &cv_saltyheight, 65}, - {IT_STRING | IT_CVAR, NULL, "Saltyhop Sound Effect", &cv_saltyhopsfx, 70}, - {IT_STRING | IT_CVAR, NULL, "Saltyhop Squish", &cv_saltysquish, 75}, - {IT_STRING | IT_CVAR, NULL, "Saltyhop Roll", &cv_saltyroll, 80}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Player Stretch Factor", &cv_gravstretch, 55}, + {IT_STRING | IT_CVAR, NULL, "Squish Sound Effect", &cv_slamsound, 60}, - {IT_STRING | IT_CVAR, NULL, "Squishdance", &cv_squishdance, 90}, - {IT_STRING | IT_CVAR, NULL, "Squishdance Speed", &cv_squishdancespeed, 96}, + {IT_STRING | IT_CVAR, NULL, "Saltyhop", &cv_saltyhop, 70}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Saltyhop Height", &cv_saltyheight, 75}, + {IT_STRING | IT_CVAR, NULL, "Saltyhop Sound Effect", &cv_saltyhopsfx, 80}, + {IT_STRING | IT_CVAR, NULL, "Saltyhop Squish", &cv_saltysquish, 85}, + {IT_STRING | IT_CVAR, NULL, "Saltyhop Roll", &cv_saltyroll, 90}, + + {IT_STRING | IT_CVAR, NULL, "Squishdance", &cv_squishdance, 100}, + {IT_STRING | IT_CVAR, NULL, "Squishdance Speed", &cv_squishdancespeed, 106}, // why is this offset by 6? idk cant remember lulul }; static const char* OP_PlayerDistortTooltips[] = @@ -1782,6 +1866,8 @@ static const char* OP_PlayerDistortTooltips[] = "Sprite rotation on slopes. Can either be just players or all objects.", "Distance object rotation should be visable.", "Player rotation when sliptiding.", + "Slightly tilt the player when driving over stairs or small bumps.", + "Sound effect when driving over stairs or small bumps.", "Rotation of a player's boost trails and drift sparks.", "Should banans rotate when thrown?\nAnd should they stay rotated when on the ground?", "Player squash and stretch.", @@ -1792,7 +1878,7 @@ static const char* OP_PlayerDistortTooltips[] = "Player hop squash and stretch.", "Should the player rotation be kept during player hop.", "Do a funny squishy dance when holding CUSTOM 3.", - "Speed of the Squishy dance in BPM.", + "Speed of the Squishy dance in SPM (Squishes Per Minute).", }; enum @@ -1801,6 +1887,8 @@ enum sloperotate, slrotatedist, sliptide, + stairjank, + stairjanksfx, sparkrotate, bananrotat, stretchyplayer, @@ -1818,47 +1906,51 @@ static menuitem_t OP_SaturnHudMenu[] = { {IT_HEADER, NULL, "Saturn Hud Options", NULL, 0}, - {IT_STRING|IT_CVAR, NULL, "Speedometer Style", &cv_newspeedometer, 10}, - {IT_STRING|IT_CVAR, NULL, "Battle Speedometer", &cv_battlespeedo, 15}, + {IT_STRING|IT_CVAR, NULL, "Speedometer Style", &cv_newspeedometer, 10}, + {IT_STRING|IT_CVAR, NULL, "Battle Speedometer", &cv_battlespeedo, 15}, - {IT_STRING|IT_CVAR, NULL, "Colourized HUD", &cv_colorizedhud, 25}, - {IT_STRING|IT_CVAR, NULL, "Colourized Itembox", &cv_colorizeditembox, 30}, - {IT_STRING|IT_CVAR, NULL, "Colourized HUD Color", &cv_colorizedhudcolor, 35}, + {IT_STRING|IT_CVAR, NULL, "Colourized HUD", &cv_colorizedhud, 25}, + {IT_STRING|IT_CVAR, NULL, "Colourized Itembox", &cv_colorizeditembox, 30}, + {IT_STRING|IT_CVAR, NULL, "Colourized HUD Color", &cv_colorizedhudcolor, 35}, - {IT_STRING|IT_CVAR, NULL, "Input Display", &cv_showinput, 45}, + {IT_STRING|IT_CVAR, NULL, "Input Display", &cv_showinput, 45}, - {IT_STRING|IT_CVAR, NULL, "Stat Display", &cv_showstats, 55}, + {IT_STRING|IT_CVAR, NULL, "Stat Display", &cv_showstats, 55}, + {IT_STRING|IT_CVAR, NULL, "Skin Name in Stat Display", &cv_showstats_skinname, 60}, - {IT_STRING|IT_CVAR, NULL, "Higher Resolution Portraits", &cv_highresportrait, 65}, + {IT_STRING|IT_CVAR, NULL, "Higher Resolution Portraits", &cv_highresportrait, 70}, - {IT_STRING|IT_CVAR, NULL, "Small Positionnumber", &cv_smallposnum, 75}, - {IT_STRING|IT_CVAR, NULL, "Positionnumber Animation", &cv_posanim, 80}, + {IT_STRING|IT_CVAR, NULL, "Small Positionnumber", &cv_smallposnum, 80}, + {IT_STRING|IT_CVAR, NULL, "Positionnumber Animation", &cv_posanim, 85}, - {IT_STRING|IT_CVAR, NULL, "Flash Lap Times", &cv_showlaptimes, 90}, + {IT_STRING|IT_CVAR, NULL, "Flash Lap Times", &cv_showlaptimes, 95}, - {IT_STRING|IT_CVAR, NULL, "Multi-Item icons", &cv_multiitemicon, 100}, - {IT_STRING|IT_CVAR, NULL, "Item Amount Number", &cv_huditemamount, 105}, - {IT_STRING|IT_CVAR, NULL, "Animated Roulette", &cv_fancyroulette, 110}, + {IT_STRING|IT_CVAR, NULL, "Multi-Item icons", &cv_multiitemicon, 105}, + {IT_STRING|IT_CVAR, NULL, "Item Amount Number", &cv_huditemamount, 110}, + {IT_STRING|IT_CVAR, NULL, "Animated Roulette", &cv_fancyroulette, 115}, - {IT_STRING|IT_CVAR, NULL, "Show Lap Emblem", &cv_showlapemblem, 120}, - {IT_STRING|IT_CVAR, NULL, "Show Cecho Messages", &cv_cechotoggle, 125}, + {IT_STRING|IT_CVAR, NULL, "Item Roulette Color", &cv_roulettecolor, 120}, - {IT_STRING|IT_CVAR, NULL, "Show Names on Minimap", &cv_showminimapnames, 135}, - {IT_STRING|IT_CVAR, NULL, "Small Minimap Players", &cv_minihead, 140}, - {IT_STRING|IT_CVAR, NULL, "Spin Minimap Icons", &cv_spinoutroll, 145}, - {IT_STRING|IT_CVAR, NULL, "Player Angle Visual", &cv_showminimapangle, 150}, + {IT_STRING|IT_CVAR, NULL, "Show Lap Emblem", &cv_showlapemblem, 130}, + {IT_STRING|IT_CVAR, NULL, "Show Cecho Messages", &cv_cechotoggle, 135}, - {IT_STRING|IT_CVAR, NULL, "Music Credits", &cv_songcredits, 160}, - {IT_STRING|IT_CVAR, NULL, "Music Credits on Pause", &cv_pausesongcredits, 165}, + {IT_STRING|IT_CVAR, NULL, "Show Names on Minimap", &cv_showminimapnames, 145}, + {IT_STRING|IT_CVAR, NULL, "Show Finished on Minimap", &cv_showminimapfinished, 150}, + {IT_STRING|IT_CVAR, NULL, "Small Minimap Players", &cv_minihead, 155}, + {IT_STRING|IT_CVAR, NULL, "Spin Minimap Icons", &cv_spinoutroll, 160}, + {IT_STRING|IT_CVAR, NULL, "Player Angle Visual", &cv_showminimapangle, 165}, - {IT_STRING|IT_CVAR, NULL, "Beta Intermissionscreen", &cv_betainterscreen, 175}, + {IT_STRING|IT_CVAR, NULL, "Music Credits", &cv_songcredits, 175}, + {IT_STRING|IT_CVAR, NULL, "Music Credits on Pause", &cv_pausesongcredits, 180}, - {IT_STRING|IT_CVAR, NULL, "Show Director Prompt", &cv_showdirectorhud, 185}, + {IT_STRING|IT_CVAR, NULL, "Beta Intermissionscreen", &cv_betainterscreen, 190}, - {IT_STRING|IT_SUBMENU, NULL, "Nametags...", &OP_NametagDef, 195}, - {IT_STRING|IT_SUBMENU, NULL, "Driftgauge...", &OP_DriftGaugeDef, 200}, + {IT_STRING|IT_CVAR, NULL, "Show Director Prompt", &cv_showdirectorhud, 200}, - {IT_SUBMENU|IT_STRING, NULL, "Hud Offsets...", &OP_HudOffsetDef, 210}, + {IT_STRING|IT_SUBMENU, NULL, "Nametags...", &OP_NametagDef, 210}, + {IT_STRING|IT_SUBMENU, NULL, "Driftgauge...", &OP_DriftGaugeDef, 215}, + + {IT_SUBMENU|IT_STRING, NULL, "Hud Offsets...", &OP_HudOffsetDef, 225}, }; static const char* OP_SaturnHudTooltips[] = @@ -1871,6 +1963,7 @@ static const char* OP_SaturnHudTooltips[] = "The color to use instead of the player color when\ncolourized hud is enabled.", "Displays the input display and lets you choose its style.", "Enable the stat display.", + "Show skin name in the stat display.", "Enable the use of the higher resolution want icons instead of rank\nfor some places.", "Make the Postionnumber half the size.", "Disable the animation of the Positionnumber\nwhen overtaking someone.", @@ -1878,9 +1971,11 @@ static const char* OP_SaturnHudTooltips[] = "Use extra graphics for multiple sneakers, bananas and jawz.", "Change when the item amount is to be displayed.\nMultiple will always display the number.\nWhen you have multiple of the same Item.\nAlways will always display the number regardless of Item amount.", "Enables an animation while the roulette is active.", + "Changes the way items are colorized in roulette.", "Show the big 'LAP' text on a lap change.", "Show the big Cecho Messages.", "Show player names on the minimap.", + "Show players that have finished already on the minimap.", "Minimize the player icons on the minimap.", "Erratically rotate player icons during spinouts.", "Visualize the player facing angle.", @@ -2480,12 +2575,17 @@ menu_t OP_MainDef = menu_t OP_ControlsDef = DEFAULTMENUSTYLE("M_CONTRO", OP_ControlsMenu, &OP_MainDef, 40, 15, OP_ControlsTooltips); //WTF menu_t OP_MouseOptionsDef = DEFAULTMENUSTYLE("M_CONTRO", OP_MouseOptionsMenu, &OP_ControlsDef, 60, 30, OP_MouseTooltips); -menu_t OP_AllControlsDef = CONTROLMENUSTYLE(OP_AllControlsMenu, &OP_ControlsDef); +menu_t OP_AllControlsDef = CONTROLMENUSTYLE(OP_AllControlsMenu, &OP_ControlsDef, OP_AllControlsTooltips); menu_t OP_Joystick1Def = DEFAULTSCROLLSTYLE("M_CONTRO", OP_Joystick1Menu, &OP_AllControlsDef, 30, 36, NULL); menu_t OP_Joystick2Def = DEFAULTSCROLLSTYLE("M_CONTRO", OP_Joystick2Menu, &OP_AllControlsDef, 30, 36, NULL); menu_t OP_Joystick3Def = DEFAULTSCROLLSTYLE("M_CONTRO", OP_Joystick3Menu, &OP_AllControlsDef, 30, 36, NULL); menu_t OP_Joystick4Def = DEFAULTSCROLLSTYLE("M_CONTRO", OP_Joystick4Menu, &OP_AllControlsDef, 30, 36, NULL); +menu_t OP_Joystick1RumbleDef = DEFAULTSCROLLSTYLE("M_CONTRO", OP_Joystick1RumbleMenu, &OP_Joystick1Def, 30, 36, NULL); +menu_t OP_Joystick2RumbleDef = DEFAULTSCROLLSTYLE("M_CONTRO", OP_Joystick2RumbleMenu, &OP_Joystick2Def, 30, 36, NULL); +menu_t OP_Joystick3RumbleDef = DEFAULTSCROLLSTYLE("M_CONTRO", OP_Joystick3RumbleMenu, &OP_Joystick3Def, 30, 36, NULL); +menu_t OP_Joystick4RumbleDef = DEFAULTSCROLLSTYLE("M_CONTRO", OP_Joystick4RumbleMenu, &OP_Joystick4Def, 30, 36, NULL); + menu_t OP_JoystickSetDef = { "M_CONTRO", @@ -2577,7 +2677,7 @@ menu_t OP_Player2CamOptionsDef = DEFAULTMENUSTYLE(NULL, OP_Player2CamOptionsMenu menu_t OP_Player3CamOptionsDef = DEFAULTMENUSTYLE(NULL, OP_Player3CamOptionsMenu, &OP_CamOptionsDef, 30, 30, OP_PlayerCamOptionsTooltips); menu_t OP_Player4CamOptionsDef = DEFAULTMENUSTYLE(NULL, OP_Player4CamOptionsMenu, &OP_CamOptionsDef, 30, 30, OP_PlayerCamOptionsTooltips); -menu_t OP_ChatOptionsDef = DEFAULTMENUSTYLE("M_HUD", OP_ChatOptionsMenu, &OP_HUDOptionsDef, 30, 30, OP_ChatOptionsTooltips); +menu_t OP_ChatOptionsDef = DEFAULTSCROLLSTYLE("M_HUD", OP_ChatOptionsMenu, &OP_HUDOptionsDef, 30, 25, OP_ChatOptionsTooltips); menu_t OP_SoundAdvancedDef = DEFAULTSCROLLSTYLE("M_SOUND", OP_SoundAdvancedMenu, &OP_SoundOptionsDef, 30, 30, OP_SoundAdvancedTooltips); @@ -2702,6 +2802,15 @@ void PDistort_menu_Onchange(void) OP_PlayerDistortMenu[slrotatedist].status = IT_GRAYEDOUT; OP_PlayerDistortMenu[saltroll].status = IT_GRAYEDOUT; } + + if (cv_stairjank.value) + { + OP_PlayerDistortMenu[stairjanksfx].status = IT_STRING | IT_CVAR; + } + else + { + OP_PlayerDistortMenu[stairjanksfx].status = IT_GRAYEDOUT; + } } void Bird_menu_Onchange(void) @@ -2760,6 +2869,5 @@ void M_UpdateOGLMenu(void) OP_OpenGLOptionsMenu[op_gl_lightdither].status = (!HWR_UseShader()) ? IT_GRAYEDOUT : IT_STRING | IT_CVAR; OP_OpenGLOptionsMenu[op_gl_palrender].status = (cv_glscreentextures.value != 2 || !HWR_UseShader()) ? IT_GRAYEDOUT : IT_STRING | IT_CVAR; - OP_OpenGLOptionsMenu[op_gl_flashpal].status = (!HWR_ShouldUsePaletteRendering()) ? IT_GRAYEDOUT : IT_STRING | IT_CVAR; } #endif diff --git a/src/m_misc.c b/src/m_misc.c index 655a28a24..a8dc0269d 100644 --- a/src/m_misc.c +++ b/src/m_misc.c @@ -515,8 +515,8 @@ static boolean M_BackupConfig(const char *filename) { char backupfile[MAX_WADPATH+4]; - snprintf(backupfile, sizeof backupfile, "%s.bak", filename); - backupfile[sizeof backupfile - 1] = '\0'; + snprintf(backupfile, sizeof(backupfile), "%s.bak", filename); + backupfile[sizeof(backupfile) - 1] = '\0'; FILE *config = fopen(filename, "r"); @@ -540,7 +540,7 @@ static boolean M_BackupConfig(const char *filename) void M_SaveConfig(const char *filename) { FILE *f; - char *filepath; + CLEANUP(Z_Pfree) char *filepath = NULL; // make sure not to write back the config until it's been correctly loaded if (!loaded_config) @@ -558,7 +558,7 @@ void M_SaveConfig(const char *filename) // append srb2home to beginning of filename // but check if srb2home isn't already there, first if (!strstr(filename, srb2home)) - filepath = va(pandf,srb2home, filename); + filepath = Z_StrDup(va(pandf, srb2home, filename)); else filepath = Z_StrDup(filename); @@ -766,32 +766,32 @@ static void M_PNGText(png_structp png_ptr, png_infop png_info_ptr, PNG_CONST png } if (gamestate == GS_LEVEL) - snprintf(maptext, 8, "%s", G_BuildMapName(gamemap)); + snprintf(maptext, sizeof(maptext), "%s", G_BuildMapName(gamemap)); else - snprintf(maptext, 8, "Unknown"); + snprintf(maptext, sizeof(maptext), "Unknown"); if (gamestate == GS_LEVEL && mapheaderinfo[gamemap-1]->lvlttl[0] != '\0') - snprintf(lvlttltext, 48, "%s%s%s", + snprintf(lvlttltext, sizeof(lvlttltext), "%s%s%s", mapheaderinfo[gamemap-1]->lvlttl, (strlen(mapheaderinfo[gamemap-1]->zonttl) > 0) ? va(" %s",mapheaderinfo[gamemap-1]->zonttl) : // SRB2kart ((mapheaderinfo[gamemap-1]->levelflags & LF_NOZONE) ? "" : " ZONE"), (strlen(mapheaderinfo[gamemap-1]->actnum) > 0) ? va(" %s",mapheaderinfo[gamemap-1]->actnum) : ""); else - snprintf(lvlttltext, 48, "Unknown"); + snprintf(lvlttltext, sizeof(lvlttltext), "Unknown"); if (gamestate == GS_LEVEL && players[displayplayers[0]].mo) - snprintf(locationtxt, 40, "X:%d Y:%d Z:%d A:%d", + snprintf(locationtxt, sizeof(locationtxt), "X:%d Y:%d Z:%d A:%d", players[displayplayers[0]].mo->x>>FRACBITS, players[displayplayers[0]].mo->y>>FRACBITS, players[displayplayers[0]].mo->z>>FRACBITS, FixedInt(AngleFixed(players[displayplayers[0]].mo->angle))); else - snprintf(locationtxt, 40, "Unknown"); + snprintf(locationtxt, sizeof(locationtxt), "Unknown"); - memset(png_infotext,0x00,sizeof (png_infotext)); + memset(png_infotext, 0x00, sizeof(png_infotext)); for (i = 0; i < SRB2PNGTXT; i++) - png_infotext[i].key = keytxt[i]; + png_infotext[i].key = keytxt[i]; png_infotext[0].text = titletxt; if (movie) @@ -804,9 +804,15 @@ static void M_PNGText(png_structp png_ptr, png_infop png_info_ptr, PNG_CONST png png_infotext[5].text = locationtxt; png_infotext[6].text = interfacetxt; png_infotext[7].text = rendermodetxt; - png_infotext[8].text = strncpy(ctrevision, comprevision, sizeof(ctrevision)-1); - png_infotext[9].text = strncpy(ctdate, compdate, sizeof(ctdate)-1); - png_infotext[10].text = strncpy(cttime, comptime, sizeof(cttime)-1); + strncpy(ctrevision, comprevision, sizeof(ctrevision)-1); + ctrevision[sizeof(ctrevision)-1] = '\0'; + png_infotext[8].text = ctrevision; + strncpy(ctdate, compdate, sizeof(ctdate)-1); + ctdate[sizeof(ctdate)-1] = '\0'; + png_infotext[9].text = ctdate; + strncpy(cttime, comptime, sizeof(cttime)-1); + cttime[sizeof(cttime)-1] = '\0'; + png_infotext[10].text = cttime; png_set_text(png_ptr, png_info_ptr, png_infotext, SRB2PNGTXT); #undef SRB2PNGTXT @@ -1247,7 +1253,6 @@ boolean M_ScreenshotResponder(event_t *ev) return true; } - void M_ScrollString(const char name[], size_t len, char result[], size_t maxlen, tic_t timer) { // How much should we scroll. Not sure why +1 is needed, but without it this function skips 2 @@ -1255,7 +1260,7 @@ void M_ScrollString(const char name[], size_t len, char result[], size_t maxlen, const size_t amount = len - maxlen + 1; // Note: anything above 17 will cause zero division - const size_t MAXSPEED = 6; + static const size_t MAXSPEED = 6; const tic_t t = timer / (35/min(amount, MAXSPEED)); const size_t state = (t / amount) % 4; @@ -1290,7 +1295,7 @@ void M_ScrollString(const char name[], size_t len, char result[], size_t maxlen, } // Technically not necessary, since it gets set again after function call, but just in case - result[maxlen] = 0; + result[maxlen-1] = '\0'; } void M_MinimapGenerate(void) @@ -1346,14 +1351,15 @@ void M_MinimapGenerate(void) minigen = AM_MinimapGenerate(mul); if (minigen == NULL || minigen->buf == NULL) - goto failure; + { + CONS_Alert(CONS_ERROR, M_GetText("Couldn't create %s\n"), filepath); + return; + } M_CreateScreenShotPalette(); ret = M_SavePNG(filepath, minigen->buf, minigen->w, minigen->h, screenshot_palette); -failure: - if (minigen->buf != NULL) - free(minigen->buf); + free(minigen->buf); if (ret) { @@ -1387,7 +1393,7 @@ char *va(const char *format, ...) static char string[1024]; va_start(argptr, format); - vsnprintf(string, 1024, format, argptr); + vsnprintf(string, sizeof(string), format, argptr); va_end(argptr); return string; @@ -1453,9 +1459,9 @@ INT32 axtoi(const char *hexStg) void CopyCaretColors(char *p, const char *s, int n) { - char *t; - int m; - int c; + gconst char *t; + int m; + int c; if (!n) return; @@ -1563,6 +1569,7 @@ char *M_GetToken(const char *inputString) { startPos = endPos; } + if (stringToUse == NULL) return NULL; @@ -1633,7 +1640,8 @@ char *M_GetToken(const char *inputString) } // If the end of the string is reached, no token is to be read - if (startPos == stringLength) { + if (startPos == stringLength) + { endPos = stringLength; return NULL; } @@ -1643,7 +1651,7 @@ char *M_GetToken(const char *inputString) || stringToUse[startPos] == '}') { endPos = startPos + 1; - texturesToken = (char *)Z_Malloc(2*sizeof(char),PU_STATIC,NULL); + texturesToken = (char *)Z_Malloc(2*sizeof(char), PU_STATIC, NULL); texturesToken[0] = stringToUse[startPos]; texturesToken[1] = '\0'; return texturesToken; @@ -1693,22 +1701,23 @@ char *M_GetToken(const char *inputString) } -const char * M_Ftrim (double f) +const char * M_Ftrim(double f) { static char dig[9];/* "0." + 6 digits (6 is printf's default) */ int i; + /* I know I said it's the default, but just in case... */ - sprintf(dig, "%.6f", fabs(modf(f, &f))); + snprintf(dig, sizeof(dig), "%.6f", fabs(modf(f, &f))); + /* trim trailing zeroes */ for (i = strlen(dig)-1; dig[i] == '0'; --i) ; + if (dig[i] == '.')/* :NOTHING: */ return ""; - else - { - dig[i + 1] = '\0'; - return &dig[1];/* skip the 0 */ - } + + dig[i + 1] = '\0'; + return &dig[1];/* skip the 0 */ } /** Count bits in a number. @@ -1726,6 +1735,7 @@ UINT8 M_CountBits(UINT32 num, UINT8 size) const char *GetRevisionString(void) { static char rev[9] = {0}; + if (rev[0]) return rev; @@ -1733,6 +1743,7 @@ const char *GetRevisionString(void) strncpy(rev, comprevision, 7); else snprintf(rev, 7, "r%s", comprevision); + rev[7] = '\0'; return rev; @@ -1804,35 +1815,35 @@ TMatrix *RotateZMatrix(angle_t rad) char *sizeu1(size_t num) { static char sizeu1_buf[28]; - sprintf(sizeu1_buf, "%"PRIdS, num); + snprintf(sizeu1_buf, sizeof(sizeu1_buf), "%" PRIdS, num); return sizeu1_buf; } char *sizeu2(size_t num) { static char sizeu2_buf[28]; - sprintf(sizeu2_buf, "%"PRIdS, num); + snprintf(sizeu2_buf, sizeof(sizeu2_buf), "%" PRIdS, num); return sizeu2_buf; } char *sizeu3(size_t num) { static char sizeu3_buf[28]; - sprintf(sizeu3_buf, "%"PRIdS, num); + snprintf(sizeu3_buf, sizeof(sizeu3_buf), "%" PRIdS, num); return sizeu3_buf; } char *sizeu4(size_t num) { static char sizeu4_buf[28]; - sprintf(sizeu4_buf, "%"PRIdS, num); + snprintf(sizeu4_buf, sizeof(sizeu4_buf), "%" PRIdS, num); return sizeu4_buf; } char *sizeu5(size_t num) { static char sizeu5_buf[28]; - sprintf(sizeu5_buf, "%"PRIdS, num); + snprintf(sizeu5_buf, sizeof(sizeu5_buf), "%" PRIdS, num); return sizeu5_buf; } @@ -1853,8 +1864,10 @@ int M_PathParts(const char *path) int n; const char *p; const char *t; + if (path == NULL) return 0; + for (n = 0, p = path ;; ++n) { t = p; @@ -1867,6 +1880,7 @@ int M_PathParts(const char *path) break; } } + return n; } @@ -1909,7 +1923,9 @@ void M_MkdirEachUntil(const char *cpath, int start, int end, int mode) if (!( p = strchr(p, PATHSEP[0]) )) return; } + p += strspn(p, PATHSEP); + for (;;) { if (end > 0 && !--end) @@ -1954,6 +1970,22 @@ UINT32 FNV1a_Hash(const char *message, size_t size) return hash; } +// Behaves like the old quickncasehash +// Stops either if it encounters null terminator +// or reaches size +UINT32 FNV1a_QuickCaseHash(const char *message, size_t size) +{ + UINT32 hash = FNV1A_OFFSET_BASIS; + + for (size_t i = 0; i < size && message[i]; i++) + { + hash ^= tolower(message[i]); + hash *= FNV1A_PRIME; + } + + return hash; +} + UINT32 FNV1a_HashString(const char *message) { UINT32 hash = FNV1A_OFFSET_BASIS; diff --git a/src/m_misc.h b/src/m_misc.h index ab7c8986f..813e8abf1 100644 --- a/src/m_misc.h +++ b/src/m_misc.h @@ -123,6 +123,7 @@ FUNCMATH UINT8 M_CountBits(UINT32 num, UINT8 size); // Hashes some message using FNV-1a UINT32 FNV1a_Hash(const char *message, size_t size); +UINT32 FNV1a_QuickCaseHash(const char *message, size_t size); UINT32 FNV1a_HashString(const char *message); UINT32 FNV1a_HashLowercaseString(const char *message); diff --git a/src/m_perfstats.c b/src/m_perfstats.c index 75aad72e2..ccc351094 100644 --- a/src/m_perfstats.c +++ b/src/m_perfstats.c @@ -47,6 +47,7 @@ struct perfstatrow { static ps_metric_t ps_frametime = {0}; ps_metric_t ps_tictime = {0}; +ps_metric_t ps_prevtictime = {0}; ps_metric_t ps_playerthink_time = {0}; ps_metric_t ps_thinkertime = {0}; @@ -110,12 +111,12 @@ perfstatrow_t rendertime_rows[] = { {"ui ", "UI render: ", &ps_uitime, PS_TIME}, {"finupdt", "I_FinishUpdate:", &ps_swaptime, PS_TIME}, - {0} + {} }; perfstatrow_t gamelogicbrief_row[] = { {"logic ", "Game logic: ", &ps_tictime, PS_TIME}, - {0} + {} }; perfstatrow_t commoncounter_rows[] = { @@ -123,20 +124,20 @@ perfstatrow_t commoncounter_rows[] = { {"sprites", "Sprites: ", &ps_numsprites, 0}, {"drwnode", "Drawnodes: ", &ps_numdrawnodes, 0}, {"plyobjs", "Polyobjects: ", &ps_numpolyobjects, 0}, - {0} + {} }; perfstatrow_t interpolation_rows[] = { {"intpfrc", "Interp frac: ", &ps_interp_frac, 0}, {"intplag", "Interp lag: ", &ps_interp_lag, 0}, - {0} + {} }; #ifdef HWRENDER perfstatrow_t batchcount_rows[] = { {"polygon", "Polygons: ", &ps_hw_numpolys, 0}, {"vertex ", "Vertices: ", &ps_hw_numverts, 0}, - {0} + {} }; perfstatrow_t batchcalls_rows[] = { @@ -145,7 +146,7 @@ perfstatrow_t batchcalls_rows[] = { {"texture", "Textures: ", &ps_hw_numtextures, 0}, {"polyflg", "Polyflags: ", &ps_hw_numpolyflags, 0}, {"colors ", "Colors: ", &ps_hw_numcolors, 0}, - {0} + {} }; #endif @@ -164,25 +165,25 @@ perfstatrow_t gamelogic_rows[] = { {" lthinkf", " LUAh_ThinkFrame:", &ps_lua_thinkframe_time, PS_TIME|PS_LEVEL}, {" lpostthinkf", " LUAh_PostThinkFrame:", &ps_lua_postthinkframe_time, PS_TIME|PS_LEVEL}, {" other ", " Other: ", &ps_otherlogictime, PS_TIME|PS_LEVEL}, - {0} + {} }; perfstatrow_t thinkercount_rows[] = { - {"thnkers", "Thinkers: ", &ps_thinkercount, PS_LEVEL}, - {" mobjs ", " Mobjs: ", &ps_mobjcount, PS_LEVEL}, + {"thnkers" , "Thinkers: ", &ps_thinkercount, PS_LEVEL}, + {" mobjs " , " Mobjs: ", &ps_mobjcount, PS_LEVEL}, {" regular", " Regular: ", &ps_regularcount, PS_LEVEL}, {" scenery", " Scenery: ", &ps_scenerycount, PS_LEVEL}, {" nothink", " Nothink: ", &ps_nothinkcount, PS_HIDE_ZERO|PS_LEVEL}, - {" precip ", " Precipitation: ", &ps_precipcount, PS_LEVEL}, - {" other ", " Other: ", &ps_otherthcount, PS_LEVEL}, - {" remove ", " Pending removal:", &ps_removecount, PS_LEVEL}, - {0} + {" precip " , " Precipitation: ", &ps_precipcount, PS_LEVEL}, + {" other " , " Other: ", &ps_otherthcount, PS_LEVEL}, + {" remove " , " Pending removal:", &ps_removecount, PS_LEVEL}, + {} }; perfstatrow_t misc_calls_rows[] = { {"lmhook", "Lua mobj hooks: ", &ps_lua_mobjhooks, PS_LEVEL}, {"chkpos", "P_CheckPosition:", &ps_checkposition_calls, PS_LEVEL}, - {0} + {} }; // Sample collection status for averaging. @@ -605,7 +606,9 @@ static void PS_CountThinkers(void) else if (thinker->function == (actionf_p1)P_MobjThinker) { mobj_t *mobj = (mobj_t*)thinker; + ps_mobjcount.value.i++; + if (mobj->flags & MF_NOTHINK) ps_nothinkcount.value.i++; else if (mobj->flags & MF_SCENERY) @@ -624,49 +627,17 @@ static void PS_CountThinkers(void) ps_precipcount.value.i++; } - - /*for (i = 0; i < NUM_THINKERLISTS; i++) - { - for (thinker = thlist[i].next; thinker != &thlist[i]; thinker = thinker->next) - { - ps_thinkercount.value.i++; - if (thinker->function == (actionf_p1)P_RemoveThinkerDelayed) - ps_removecount.value.i++; - else if (i == THINK_POLYOBJ) - ps_polythcount.value.i++; - else if (i == THINK_MAIN) - ps_mainthcount.value.i++; - else if (i == THINK_MOBJ) - { - if (thinker->function == (actionf_p1)P_MobjThinker) - { - mobj_t *mobj = (mobj_t*)thinker; - ps_mobjcount.value.i++; - if (mobj->flags & MF_NOTHINK) - ps_nothinkcount.value.i++; - else if (mobj->flags & MF_SCENERY) - ps_scenerycount.value.i++; - else - ps_regularcount.value.i++; - } - } - else if (i == THINK_DYNSLOPE) - ps_dynslopethcount.value.i++; - else if (i == THINK_PRECIP) - ps_precipcount.value.i++; - } - }*/ } // Update all metrics that are calculated on every tick. void PS_UpdateTickStats(void) { - if (cv_perfstats.value == 1 && cv_ps_samplesize.value > 1) + if (cv_perfstats.value == PS_RENDER && cv_ps_samplesize.value > 1) { PS_UpdateRowHistories(gamelogicbrief_row, false); } - if (cv_perfstats.value == 2) + if (cv_perfstats.value == PS_LOGIC) { if (PS_IsLevelActive()) { @@ -691,25 +662,25 @@ void PS_UpdateTickStats(void) if (cv_ps_samplesize.value > 1) { - if (cv_perfstats.value >= 3 && PS_IsLevelActive()) + if (cv_perfstats.value >= PS_THINKFRAME && PS_IsLevelActive()) { int i; switch (cv_perfstats.value) { - case 3: + case PS_THINKFRAME: for (i = 0; i < thinkframe_hooks_length; i++) { PS_UpdateMetricHistory(&thinkframe_hooks[i].time_taken, true, false); } break; - case 4: + case PS_PRETHINKFRAME: for (i = 0; i < prethinkframe_hooks_length; i++) { PS_UpdateMetricHistory(&prethinkframe_hooks[i].time_taken, true, false); } break; - case 5: + case PS_POSTTHINKFRAME: for (i = 0; i < postthinkframe_hooks_length; i++) { PS_UpdateMetricHistory(&postthinkframe_hooks[i].time_taken, true, false); @@ -719,6 +690,7 @@ void PS_UpdateTickStats(void) break; } } + if (cv_perfstats.value) { ps_tick_index++; @@ -749,7 +721,7 @@ static void PS_DrawDescriptorHeader(void) int samples_left = max(ps_frame_samples_left, ps_tick_samples_left); int x, y; - if (cv_perfstats.value >= 3) + if (cv_perfstats.value >= PS_THINKFRAME) { x = 2; y = 0; @@ -865,20 +837,19 @@ static void draw_think_frame_stats(int hook_length, ps_hookinfo_t *hook) last_mod_name[0] = '\0'; INT32 total = 0; - //Decide page length based and drawn text on choosen thinker type + // Decide page length based and drawn text on choosen thinker type switch (cv_perfstats.value) { - case 3: + case PS_THINKFRAME: { maxpage = thinkframe_hooks_length/PAGE_ENTRIES + 1; page = max(1, min(cv_ps_thinkframe_page.value, maxpage)); pagestart = min((page - 1)*PAGE_ENTRIES, thinkframe_hooks_length); pageend = min(pagestart + PAGE_ENTRIES, thinkframe_hooks_length); - V_DrawSmallString(MAX_X-50, MAX_Y+2*HEIGHT, V_MONOSPACE | V_GREENMAP, "ThinkFrame"); } break; - case 4: + case PS_PRETHINKFRAME: { maxpage = prethinkframe_hooks_length/PAGE_ENTRIES + 1; page = max(1, min(cv_ps_thinkframe_page.value, maxpage)); @@ -887,7 +858,7 @@ static void draw_think_frame_stats(int hook_length, ps_hookinfo_t *hook) V_DrawSmallString(MAX_X-60, MAX_Y+2*HEIGHT, V_MONOSPACE | V_GREENMAP, "PreThinkFrame"); } break; - case 5: + case PS_POSTTHINKFRAME: { maxpage = postthinkframe_hooks_length/PAGE_ENTRIES + 1; page = max(1, min(cv_ps_thinkframe_page.value, maxpage)); @@ -975,7 +946,22 @@ static void draw_think_frame_stats(int hook_length, ps_hookinfo_t *hook) void PS_ThinkFrame_Page_OnChange(void) { - int maxpage = thinkframe_hooks_length/PAGE_ENTRIES + 1; + int maxpage = 0; + + switch (cv_perfstats.value) + { + case PS_THINKFRAME: + maxpage = thinkframe_hooks_length/PAGE_ENTRIES + 1; + break; + case PS_PRETHINKFRAME: + maxpage = prethinkframe_hooks_length/PAGE_ENTRIES + 1; + break; + case PS_POSTTHINKFRAME: + maxpage = postthinkframe_hooks_length/PAGE_ENTRIES + 1; + break; + default: + break; + } if (cv_ps_thinkframe_page.value > maxpage) CV_StealthSetValue(&cv_ps_thinkframe_page, maxpage); @@ -1008,18 +994,18 @@ static void PS_DrawPostThinkFrameStats(void) void M_DrawPerfStats(void) { - if (cv_perfstats.value == 1) // rendering + if (cv_perfstats.value == PS_RENDER) // rendering { PS_UpdateFrameStats(); PS_DrawRenderStats(); } - else if (cv_perfstats.value == 2) // logic + else if (cv_perfstats.value == PS_LOGIC) // logic { // PS_UpdateTickStats is called in TryRunTics, since otherwise it would miss // tics when frame skips happen PS_DrawGameLogicStats(); } - else if (cv_perfstats.value >= 3) // lua thinkframe + else if (cv_perfstats.value >= PS_THINKFRAME) // lua thinkframe { if (!PS_IsLevelActive()) return; @@ -1036,13 +1022,13 @@ void M_DrawPerfStats(void) switch (cv_perfstats.value) { - case 3: + case PS_THINKFRAME: PS_DrawThinkFrameStats(); break; - case 4: + case PS_PRETHINKFRAME: PS_DrawPreThinkFrameStats(); break; - case 5: + case PS_POSTTHINKFRAME: PS_DrawPostThinkFrameStats(); break; default: diff --git a/src/m_perfstats.h b/src/m_perfstats.h index 083656d61..e7991b455 100644 --- a/src/m_perfstats.h +++ b/src/m_perfstats.h @@ -26,6 +26,16 @@ typedef struct void *history; } ps_metric_t; +typedef enum +{ + PS_OFF = 0, + PS_RENDER, + PS_LOGIC, + PS_THINKFRAME, + PS_PRETHINKFRAME, + PS_POSTTHINKFRAME +} ps_types_t; + typedef struct { ps_metric_t time_taken; @@ -36,6 +46,7 @@ typedef struct #define PS_STOP_TIMING(metric) metric.value.p = I_GetPreciseTime() - metric.value.p extern ps_metric_t ps_tictime; +extern ps_metric_t ps_prevtictime; extern ps_metric_t ps_playerthink_time; extern ps_metric_t ps_thinkertime; diff --git a/src/m_textinput.c b/src/m_textinput.c index 7d050dfc7..9e1819b6a 100644 --- a/src/m_textinput.c +++ b/src/m_textinput.c @@ -238,8 +238,8 @@ void M_TextInputClear(textinput_t *input) void M_TextInputSetString(textinput_t *input, const char *c) { - memset(input->buffer, 0, input->buffer_size); - strncpy(input->buffer, c, input->buffer_size); + strncpy(input->buffer, c, input->buffer_size-1); + input->buffer[input->buffer_size-1] = '\0'; input->cursor = input->select = input->length = strlen(input->buffer); } @@ -256,7 +256,7 @@ static boolean M_TextInputHandleBase(textinput_t *input, INT32 key, boolean emot return true; } - if ((cv_keyboardlayout.value != 3 && ctrldown) || (cv_keyboardlayout.value == 3 && ctrldown && !altdown)) + if (ctrldown && (cv_keyboardlayout.value != 3 || !altdown)) { if (key == 'x' || key == 'X') { @@ -381,10 +381,10 @@ static boolean M_TextInputHandleBase(textinput_t *input, INT32 key, boolean emot // allow people to use keypad in console (good for typing IP addresses) - Calum if (key >= KEY_KEYPAD7 && key <= KEY_KPADDEL) { - char keypad_translation[] = {'7','8','9','-', - '4','5','6','+', - '1','2','3', - '0','.'}; + const char keypad_translation[] = {'7','8','9','-', + '4','5','6','+', + '1','2','3', + '0', '.'}; key = keypad_translation[key - KEY_KEYPAD7]; } @@ -392,7 +392,7 @@ static boolean M_TextInputHandleBase(textinput_t *input, INT32 key, boolean emot key = '/'; // same capslock code as hu_stuff.c's HU_responder. Check there for details. - key = cv_keyboardlayout.value == 3 ? CON_ShitAndAltGrChar(key) : CON_ShiftChar(key); + key = CON_ShiftChar(key); // enter a char into the command prompt if (key < 32 || key > 127) diff --git a/src/m_textinput.h b/src/m_textinput.h index ce296ffde..f5846059e 100644 --- a/src/m_textinput.h +++ b/src/m_textinput.h @@ -44,7 +44,7 @@ boolean M_TextInputHandle(textinput_t *input, INT32 key); // If currently typing something that looks like an existing emote, return suggestions for it boolean M_TextInputHandleEmotes(textinput_t *input, INT32 key, emote_autocomplete_t *autocomplete); -#define M_DrawTextInput(x, y, input, flags) M_DrawTextInputScroll((x), (y), (input), (flags), ((input)->buffer_size-1)*8) +#define M_DrawTextInput(x, y, input, flags) M_DrawTextInputScroll((x), (y), (input), (flags), ((input)->buffer_size-2)*8) void M_DrawTextInputScroll(INT32 x, INT32 y, textinput_t *input, INT32 flags, INT32 MAXINPUTWIDTH); #endif diff --git a/src/md5.h b/src/md5.h index f09d865ab..85384c479 100644 --- a/src/md5.h +++ b/src/md5.h @@ -16,6 +16,10 @@ #ifndef _MD5_H #define _MD5_H 1 +#ifdef __cplusplus +extern "C" { +#endif + #include #if defined (HAVE_LIMITS_H) || (defined (_LIBC) && _LIBC) || defined (_WIN32) @@ -52,4 +56,8 @@ int md5_stream(FILE *stream, void *resblock) THROWFUNC; digest. */ extern void *md5_buffer(const char *buffer, size_t len, void *resblock) THROWFUNC; +#ifdef __cplusplus +} // extern "C" +#endif + #endif /* md5.h */ diff --git a/src/mserv.c b/src/mserv.c index f830cd6e2..25ff733cb 100644 --- a/src/mserv.c +++ b/src/mserv.c @@ -219,8 +219,9 @@ static void Get_masterserver_rules(boolean checkfirst) if (HMS_fetch_rules(rules, sizeof rules)) { Lock_state(); - Z_Free(MSRules); - MSRules = Z_StrDup(rules); + if (MSRules) + free(MSRules); + MSRules = strdup(rules); if (MSRegistered == true) { @@ -261,6 +262,7 @@ Finish_registration (void) { CONS_Printf("\n"); CONS_Alert(CONS_NOTICE, "%s\n", rules); + free(rules); } if (registered) @@ -507,7 +509,7 @@ char *GetMasterServerRules(void) char *rules; Lock_state(); - rules = MSRules ? Z_StrDup(MSRules) : NULL; + rules = MSRules ? strdup(MSRules) : NULL; Unlock_state(); return rules; @@ -597,9 +599,14 @@ Update_parameters (void) delayed = MSInProgress; if (delayed)/* do another update after the current one */ + { + registered = 0; MSUpdateAgain = true; + } else + { registered = MSRegistered; + } } Unlock_state(); diff --git a/src/p_enemy.c b/src/p_enemy.c index 76f1af9a0..013ae4705 100644 --- a/src/p_enemy.c +++ b/src/p_enemy.c @@ -250,7 +250,8 @@ boolean P_Move(mobj_t *actor, fixed_t speed) I_Assert(movedir < NUMDIRS); tryx = actor->x + FixedMul(speed*xspeed[movedir], actor->scale); - if (UNLIKELY(twodlevel || actor->flags2 & MF2_TWOD)) + + if (twodmo(actor)) tryy = actor->y; else tryy = actor->y + FixedMul(speed*yspeed[movedir], actor->scale); @@ -306,7 +307,6 @@ void P_NewChaseDir(mobj_t *actor) dirtype_t d[3]; dirtype_t tdir = DI_NODIR, olddir, turnaround; - I_Assert(actor->target != NULL); I_Assert(!P_MobjWasRemoved(actor->target)); olddir = actor->movedir; @@ -329,7 +329,7 @@ void P_NewChaseDir(mobj_t *actor) else d[1] = DI_NODIR; - if (twodlevel || actor->flags2 & MF2_TWOD) + if (twodmo(actor)) d[2] = DI_NODIR; if (deltay < -FixedMul(10*FRACUNIT, actor->scale)) d[2] = DI_SOUTH; @@ -619,7 +619,6 @@ void A_Chase(void *thing) if (LUA_CallAction(A_CHASE, actor)) return; - I_Assert(actor != NULL); I_Assert(!P_MobjWasRemoved(actor)); if (actor->reactiontime) @@ -874,7 +873,7 @@ void A_PointyThink(void *thing) TVector v; TVector *res; angle_t fa; - fixed_t radius = FixedMul(actor->info->radius*actor->info->reactiontime, actor->scale); + fixed_t radius; boolean firsttime = true; INT32 sign; @@ -932,6 +931,8 @@ void A_PointyThink(void *thing) if (!actor->tracer) // For some reason we do not have spike balls... return; + radius = FixedMul(actor->info->radius*actor->info->reactiontime, actor->scale); + // Position spike balls relative to the value of 'lastlook'. ball = actor->tracer; @@ -1531,10 +1532,7 @@ void A_LobShot(void *thing) if (!(actor->flags & MF_BOSS)) { - if (ultimatemode) - actor->reactiontime = actor->info->reactiontime*TICRATE; - else - actor->reactiontime = actor->info->reactiontime*TICRATE*2; + actor->reactiontime = actor->info->reactiontime*TICRATE*2; } } @@ -1570,10 +1568,7 @@ void A_FireShot(void *thing) if (!(actor->flags & MF_BOSS)) { - if (ultimatemode) - actor->reactiontime = actor->info->reactiontime*TICRATE; - else - actor->reactiontime = actor->info->reactiontime*TICRATE*2; + actor->reactiontime = actor->info->reactiontime*TICRATE*2; } } @@ -1613,10 +1608,7 @@ void A_SuperFireShot(void *thing) if (!(actor->flags & MF_BOSS)) { - if (ultimatemode) - actor->reactiontime = actor->info->reactiontime*TICRATE; - else - actor->reactiontime = actor->info->reactiontime*TICRATE*2; + actor->reactiontime = actor->info->reactiontime*TICRATE*2; } } @@ -2770,9 +2762,11 @@ void A_Invincibility(void *thing) if (P_IsLocalPlayer(player) && !player->powers[pw_super]) { S_StopMusic(); + if (mariomode) G_GhostAddColor((INT32) (player - players), GHC_INVINCIBLE); - S_ChangeMusicInternal((mariomode) ? "minvnc" : "invinc", false); + + S_ChangeMusicInternal(mariomode ? "minvnc" : "invinc", false); } } @@ -2870,12 +2864,6 @@ void A_ExtraLife(void *thing) if (actor->type == MT_1UPICO && !actor->tracer) actor->frame -= 2; // No lives icon for this player, use the default. - if (ultimatemode) //I don't THINK so! - { - S_StartSound(player->mo, sfx_lose); - return; - } - // In shooter gametypes, give the player 100 rings instead of an extra life. if (gametype != GT_COOP && gametype != GT_COMPETITION) P_GivePlayerRings(player, 100); @@ -3650,7 +3638,7 @@ static inline boolean PIT_GrenadeRing(mobj_t *thing) return true; if (thing->player && (thing->player->kartstuff[k_hyudorotimer] - || (G_BattleGametype() && thing->player && thing->player->kartstuff[k_bumper] <= 0 && thing->player->kartstuff[k_comebacktimer]))) + || (G_BattleGametype() && thing->player->kartstuff[k_bumper] <= 0 && thing->player->kartstuff[k_comebacktimer]))) return true; if ((gametype == GT_CTF || gametype == GT_TEAMMATCH) @@ -4015,26 +4003,13 @@ void A_JetChase(void *thing) } // chase towards player - if (ultimatemode) - P_Thrust(actor, actor->angle, FixedMul(actor->info->speed/2, actor->scale)); - else - P_Thrust(actor, actor->angle, FixedMul(actor->info->speed/4, actor->scale)); + P_Thrust(actor, actor->angle, FixedMul(actor->info->speed/4, actor->scale)); // must adjust height - if (ultimatemode) - { - if (actor->z < (actor->target->z + actor->target->height + FixedMul((64<scale))) - actor->momz += FixedMul(FRACUNIT/2, actor->scale); - else - actor->momz -= FixedMul(FRACUNIT/2, actor->scale); - } + if (actor->z < (actor->target->z + actor->target->height + FixedMul((32<scale))) + actor->momz += FixedMul(FRACUNIT/2, actor->scale); else - { - if (actor->z < (actor->target->z + actor->target->height + FixedMul((32<scale))) - actor->momz += FixedMul(FRACUNIT/2, actor->scale); - else - actor->momz -= FixedMul(FRACUNIT/2, actor->scale); - } + actor->momz -= FixedMul(FRACUNIT/2, actor->scale); } // Function: A_JetbThink @@ -4137,10 +4112,7 @@ void A_JetgShoot(void *thing) A_FaceTarget(actor); P_SpawnMissile(actor, actor->target, (mobjtype_t)actor->info->raisestate); - if (ultimatemode) - actor->reactiontime = actor->info->reactiontime*TICRATE; - else - actor->reactiontime = actor->info->reactiontime*TICRATE*2; + actor->reactiontime = actor->info->reactiontime*TICRATE*2; if (actor->info->attacksound) S_StartSound(actor, actor->info->attacksound); @@ -4388,7 +4360,7 @@ void A_MouseThink(void *thing) || (actor->eflags & MFE_VERTICALFLIP && actor->z + actor->height == actor->ceilingz)) && !actor->reactiontime) { - if (UNLIKELY(twodlevel || actor->flags2 & MF2_TWOD)) + if (twodmo(actor)) { if (P_RandomChance(FRACUNIT/2)) actor->angle += ANGLE_180; @@ -5301,7 +5273,7 @@ void A_MixUp(void *thing) if (playeringame[i] && players[i].mo && players[i].mo->health > 0 && players[i].playerstate == PST_LIVE && !players[i].exiting && !players[i].powers[pw_super]) { - if ((netgame || multiplayer) && players[i].spectator) // Ignore spectators + if (netgame && players[i].spectator) // Ignore spectators continue; numplayers++; @@ -5344,6 +5316,11 @@ void A_MixUp(void *thing) } } + // idk if we ever really end up here + // but bad things would happen if we do without this + if (one == -1) + return; + //get this done first! tempthing = players[one].mo->tracer; P_SetTarget(&players[one].mo->tracer, players[two].mo->tracer); @@ -5977,7 +5954,7 @@ void A_Boss7Chase(void *thing) if (actor->flags2 & MF2_FRET) { P_SetMobjState(actor, S_BLACKEGG_DESTROYPLAT1); - S_StartSound(0, sfx_s3k53); + S_StartSound(NULL, sfx_s3k53); actor->flags2 &= ~MF2_FRET; return; } @@ -6011,7 +5988,7 @@ void A_Boss7Chase(void *thing) { // Punch him! P_SetMobjState(actor, actor->info->meleestate); - S_StartSound(0, sfx_begrnd); // warning sound + S_StartSound(NULL, sfx_begrnd); // warning sound return; } } @@ -6057,7 +6034,7 @@ void A_Boss7Chase(void *thing) case 2: // Homing Missile A_FaceTarget(actor); P_SetMobjState(actor, actor->info->missilestate); - S_StartSound(0, sfx_beflap); + S_StartSound(NULL, sfx_beflap); break; } @@ -6458,12 +6435,8 @@ void A_BuzzFly(void *thing) // chase towards player { INT32 dist, realspeed; - const fixed_t mf = 5*(FRACUNIT/4); - if (ultimatemode) - realspeed = FixedMul(FixedMul(actor->info->speed,mf), actor->scale); - else - realspeed = FixedMul(actor->info->speed, actor->scale); + realspeed = FixedMul(actor->info->speed, actor->scale); dist = P_AproxDistance(P_AproxDistance(actor->target->x - actor->x, actor->target->y - actor->y), actor->target->z - actor->z); @@ -7918,7 +7891,7 @@ void A_ItemPop(void *thing) if (!(actor->target && actor->target->player)) { - if (cv_debug && !(actor->target && actor->target->player)) + if (cv_debug) CONS_Printf("ERROR: Powerup has no target!\n"); return; } @@ -8780,7 +8753,7 @@ void A_ReaperThinker(void *thing) actor->angle = R_PointToAngle2(actor->x, actor->y, actor->target->x, actor->target->y); // The player we should target if it's near us: - for (i = 0; iflags & MF_BOSS)) { - if (ultimatemode) - actor->reactiontime = actor->info->reactiontime*TICRATE; - else - actor->reactiontime = actor->info->reactiontime*TICRATE*2; + actor->reactiontime = actor->info->reactiontime*TICRATE*2; } } @@ -10739,7 +10709,7 @@ void A_BrakChase(void *thing) { actor->reactiontime--; if (actor->reactiontime == 0 && actor->type == MT_CYBRAKDEMON) - S_StartSound(0, sfx_bewar1 + P_RandomKey(4)); + S_StartSound(NULL, sfx_bewar1 + P_RandomKey(4)); } // modify target threshold @@ -10863,10 +10833,7 @@ void A_BrakFireShot(void *thing) if (!(actor->flags & MF_BOSS)) { - if (ultimatemode) - actor->reactiontime = actor->info->reactiontime*TICRATE; - else - actor->reactiontime = actor->info->reactiontime*TICRATE*2; + actor->reactiontime = actor->info->reactiontime*TICRATE*2; } } @@ -10912,10 +10879,7 @@ void A_BrakLobShot(void *thing) return; // Don't even bother if we've got nothing to aim at. // Look up actor's current gravity situation - if (actor->subsector->sector->gravity) - g = FixedMul(gravity,(FixedDiv(*actor->subsector->sector->gravity>>FRACBITS, 1000))); - else - g = gravity; + g = P_GetSectorGravity(actor->subsector->sector); // Look up distance between actor and its target x = P_AproxDistance(actor->target->x - actor->x, actor->target->y - actor->y); @@ -11030,10 +10994,7 @@ void A_NapalmScatter(void *thing) airtime = 16<subsector->sector->gravity) - g = FixedMul(gravity,(FixedDiv(*actor->subsector->sector->gravity>>FRACBITS, 1000))); - else - g = gravity; + g = P_GetSectorGravity(actor->subsector->sector); // vy = (g*(airtime-1))/2 vy = FixedMul(g,(airtime-(1<>1; diff --git a/src/p_floor.c b/src/p_floor.c index bd7a2655e..5417029e4 100644 --- a/src/p_floor.c +++ b/src/p_floor.c @@ -845,7 +845,7 @@ void T_BounceCheese(levelspecthink_t *bouncer) T_MovePlane(bouncer->sector, 0, bouncer->sector->ceilingheight, 0, 1, -1); // update things on ceiling T_MovePlane(bouncer->sector, 0, bouncer->sector->floorheight, 0, 0, -1); // update things on floor bouncer->sector->ceilingdata = NULL; - bouncer->sector->floordata = NULL;; + bouncer->sector->floordata = NULL; bouncer->sector->moved = true; P_RemoveThinker(&bouncer->thinker); // remove bouncer from actives } @@ -1107,14 +1107,13 @@ void T_SpikeSector(levelspecthink_t *spikes) if (affectsec == spikes->sector) // Applied to an actual sector { - fixed_t affectfloor = P_GetSpecialBottomZ(thing, affectsec, affectsec); - fixed_t affectceil = P_GetSpecialTopZ(thing, affectsec, affectsec); - if (affectsec->flags & SF_FLIPSPECIAL_FLOOR) { if (!(thing->eflags & MFE_VERTICALFLIP) && thing->momz > 0) continue; + fixed_t affectfloor = P_GetSpecialBottomZ(thing, affectsec, affectsec); + if (thing->z == affectfloor) dothepain = true; } @@ -1124,19 +1123,21 @@ void T_SpikeSector(levelspecthink_t *spikes) if ((thing->eflags & MFE_VERTICALFLIP) && thing->momz < 0) continue; + fixed_t affectceil = P_GetSpecialTopZ(thing, affectsec, affectsec); + if (thing->z + thing->height == affectceil) dothepain = true; } } else { - fixed_t affectfloor = P_GetSpecialBottomZ(thing, affectsec, spikes->sector); - fixed_t affectceil = P_GetSpecialTopZ(thing, affectsec, spikes->sector); if (affectsec->flags & SF_FLIPSPECIAL_FLOOR) { if (!(thing->eflags & MFE_VERTICALFLIP) && thing->momz > 0) continue; + fixed_t affectceil = P_GetSpecialTopZ(thing, affectsec, spikes->sector); + if (thing->z == affectceil) dothepain = true; } @@ -1146,6 +1147,8 @@ void T_SpikeSector(levelspecthink_t *spikes) if ((thing->eflags & MFE_VERTICALFLIP) && thing->momz < 0) continue; + fixed_t affectfloor = P_GetSpecialBottomZ(thing, affectsec, spikes->sector); + if (thing->z + thing->height == affectfloor) dothepain = true; } @@ -1652,6 +1655,7 @@ wegotit: static mobj_t *SearchMarioNode(msecnode_t *node) { mobj_t *thing = NULL; + for (; node; node = node->m_thinglist_next) { // Things which should NEVER be ejected from a MarioBlock, by type. @@ -1894,7 +1898,6 @@ void T_NoEnemiesSector(levelspecthink_t *nobaddies) { if (nobaddies->sector->lines[i]->special == 223) { - upperbound = nobaddies->sector->ceilingheight; lowerbound = nobaddies->sector->floorheight; @@ -2080,11 +2083,12 @@ void T_EachTimeThinker(levelspecthink_t *eachtime) continue; topheight = P_GetSpecialTopZ(players[j].mo, sec, targetsec); - bottomheight = P_GetSpecialBottomZ(players[j].mo, sec, targetsec); if (players[j].mo->z > topheight) continue; + bottomheight = P_GetSpecialBottomZ(players[j].mo, sec, targetsec); + if (players[j].mo->z + players[j].mo->height < bottomheight) continue; @@ -2334,7 +2338,7 @@ void T_RaiseSector(levelspecthink_t *raise) fixed_t origspeed = raise->vars[3]; // Slow down as you get closer to the bottom - raise->vars[3] = FixedMul(raise->vars[3],FixedDiv(raise->sector->ceilingheight - raise->vars[7], (raise->vars[5] - raise->vars[7])>>5)); + raise->vars[3] = FixedMul(raise->vars[3], FixedDiv(raise->sector->ceilingheight - raise->vars[7], (raise->vars[5] - raise->vars[7])>>5)); if (raise->vars[3] <= origspeed/16) raise->vars[3] = origspeed/16; @@ -2345,7 +2349,7 @@ void T_RaiseSector(levelspecthink_t *raise) { fixed_t origspeed = raise->vars[3]; // Slow down as you get closer to the top - raise->vars[3] = FixedMul(raise->vars[3],FixedDiv(raise->vars[5] - raise->sector->ceilingheight, (raise->vars[5] - raise->vars[7])>>5)); + raise->vars[3] = FixedMul(raise->vars[3], FixedDiv(raise->vars[5] - raise->sector->ceilingheight, (raise->vars[5] - raise->vars[7])>>5)); if (raise->vars[3] <= origspeed/16) raise->vars[3] = origspeed/16; diff --git a/src/p_inter.c b/src/p_inter.c index c95735506..e6f753b56 100644 --- a/src/p_inter.c +++ b/src/p_inter.c @@ -589,7 +589,7 @@ void P_TouchSpecialThing(mobj_t *special, mobj_t *toucher, boolean heightcheck) special->momx = special->momy = special->momz = 0; P_GivePlayerRings(player, 1); - if (UNLIKELY((maptol & TOL_NIGHTS) && special->type != MT_FLINGRING)) + if (nightsmode && special->type != MT_FLINGRING) P_DoNightsScore(player); break; @@ -601,7 +601,7 @@ void P_TouchSpecialThing(mobj_t *special, mobj_t *toucher, boolean heightcheck) special->momx = special->momy = 0; P_GivePlayerRings(player, 1); - if (UNLIKELY((maptol & TOL_NIGHTS) && special->type != MT_FLINGCOIN)) + if (nightsmode && special->type != MT_FLINGCOIN) P_DoNightsScore(player); break; case MT_BLUEBALL: @@ -617,7 +617,7 @@ void P_TouchSpecialThing(mobj_t *special, mobj_t *toucher, boolean heightcheck) else special->scalespeed = 4*FRACUNIT/5; - if (UNLIKELY(maptol & TOL_NIGHTS)) + if (nightsmode) P_DoNightsScore(player); break; case MT_AUTOPICKUP: @@ -831,7 +831,7 @@ void P_TouchSpecialThing(mobj_t *special, mobj_t *toucher, boolean heightcheck) { S_StartSound(toucher, special->info->seesound); - if (player->pflags & PF_NIGHTSMODE) + if (nightsplayer(player)) { player->bumpertime = TICRATE/2; if (special->threshold > 0) @@ -883,18 +883,20 @@ void P_TouchSpecialThing(mobj_t *special, mobj_t *toucher, boolean heightcheck) break; case MT_HOOPCOLLIDE: // This produces a kind of 'domino effect' with the hoop's pieces. - for (; special->hprev != NULL; special = special->hprev); // Move to the first sprite in the hoop - + for (; special != NULL && special->hprev != NULL; special = special->hprev); // Move to the first sprite in the hoop i = 0; - for (; special->hnext != NULL && special->type == MT_HOOP; special = special->hnext) + for (; special != NULL && special->type == MT_HOOP; special = special->hnext) { - if (!P_MobjWasRemoved(special->target)) + if (!P_MobjWasRemoved(special)) { special->fuse = 11; special->movedir = i; - special->extravalue1 = special->target->extravalue1; - special->extravalue2 = special->target->extravalue2; - special->target->threshold = 4242; + if (!P_MobjWasRemoved(special->target)) + { + special->extravalue1 = special->target->extravalue1; + special->extravalue2 = special->target->extravalue2; + special->target->threshold = 4242; + } } i++; } @@ -1131,7 +1133,7 @@ void P_TouchSpecialThing(mobj_t *special, mobj_t *toucher, boolean heightcheck) S_StartSound(toucher, special->info->painsound); return; } - else if (((player->pflags & PF_NIGHTSMODE) && (player->pflags & PF_DRILLING)) || (player->pflags & (PF_JUMPED|PF_SPINNING|PF_GLIDING)) + else if ((nightsplayer(player) && (player->pflags & PF_DRILLING)) || (player->pflags & (PF_JUMPED|PF_SPINNING|PF_GLIDING)) || player->powers[pw_invulnerability] || player->powers[pw_super]) // Do you possess the ability to subdue the object? { // Shatter the shield! @@ -1219,24 +1221,6 @@ void P_TouchSpecialThing(mobj_t *special, mobj_t *toucher, boolean heightcheck) case MT_EXTRALARGEBUBBLE: return; // SRB2kart - don't need bubbles mucking with the player - if ((player->powers[pw_shield] & SH_NOSTACK) == SH_ELEMENTAL) - return; - if (UNLIKELY(maptol & TOL_NIGHTS)) - return; - if (UNLIKELY(mariomode)) - return; - else if (toucher->eflags & MFE_VERTICALFLIP) - { - if (special->z+special->height < toucher->z + toucher->height / 3 - || special->z+special->height > toucher->z + (toucher->height*2/3)) - return; // Only go in the mouth - } - else if (special->z < toucher->z + toucher->height / 3 - || special->z > toucher->z + (toucher->height*2/3)) - return; // Only go in the mouth - - toucher->momx = toucher->momy = toucher->momz = 0; - break; case MT_WATERDROP: if (special->state == &states[special->info->spawnstate]) @@ -1480,49 +1464,11 @@ boolean P_CheckRacers(void) return false; } -/** Kills an object. - * - * \param target The victim. - * \param inflictor The attack weapon. May be NULL (environmental damage). - * \param source The attacker. May be NULL. - * \todo Cleanup, refactor, split up. - * \sa P_DamageMobj - */ -void P_KillMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source) +static void P_UpdateRemovedOrbital(mobj_t *target, mobj_t *inflictor, mobj_t *source) { - mobjtype_t item; - mobj_t *mo; - int ms; - - if (target->flags & (MF_ENEMY|MF_BOSS)) - target->momx = target->momy = target->momz = 0; - - // SRB2kart - if (target->type != MT_PLAYER && !(target->flags & MF_MONITOR) - && !(target->type == MT_ORBINAUT || target->type == MT_ORBINAUT_SHIELD - || target->type == MT_JAWZ || target->type == MT_JAWZ_DUD || target->type == MT_JAWZ_SHIELD - || target->type == MT_BANANA || target->type == MT_BANANA_SHIELD - || target->type == MT_EGGMANITEM || target->type == MT_EGGMANITEM_SHIELD - || target->type == MT_BALLHOG || target->type == MT_SPB)) // kart dead items - target->flags |= MF_NOGRAVITY; // Don't drop Tails 03-08-2000 - else - target->flags &= ~MF_NOGRAVITY; // lose it if you for whatever reason have it, I'm looking at you shields - // - - if (target->flags2 & MF2_NIGHTSPULL) - P_SetTarget(&target->tracer, NULL); - - // dead target is no more shootable - target->flags &= ~(MF_SHOOTABLE|MF_FLOAT|MF_SPECIAL); - target->flags2 &= ~(MF2_SKULLFLY|MF2_NIGHTSPULL); - target->health = 0; // This makes it easy to check if something's dead elsewhere. - - if (LUA_HookMobjDeath(target, inflictor, source) || P_MobjWasRemoved(target)) - return; - // SRB2kart // I wish I knew a better way to do this - if (target->target && target->target->player && target->target->player->mo) + if (!P_MobjWasRemovedCompat(target->target) && target->target->player && !P_MobjWasRemovedCompat(target->target->player->mo)) { if (target->target->player->kartstuff[k_eggmanheld] && target->type == MT_EGGMANITEM_SHIELD) target->target->player->kartstuff[k_eggmanheld] = 0; @@ -1535,7 +1481,7 @@ void P_KillMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source) { if (target->movedir != 0 && target->movedir < (UINT16)target->target->player->kartstuff[k_itemamount]) { - if (target->target->hnext) + if (!P_MobjWasRemovedCompat(target->target->hnext)) K_KillBananaChain(target->target->hnext, inflictor, source); target->target->player->kartstuff[k_itemamount] = 0; @@ -1564,14 +1510,60 @@ void P_KillMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source) P_SetTarget(&target->target->hnext, NULL); } } - // Above block does not clean up rocket sneakers when a player dies, so we need to do it here target->target is null when using rocket sneakers +} + + +/** Kills an object. + * + * \param target The victim. + * \param inflictor The attack weapon. May be NULL (environmental damage). + * \param source The attacker. May be NULL. + * \todo Cleanup, refactor, split up. + * \sa P_DamageMobj + */ +void P_KillMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source) +{ + mobjtype_t item; + mobj_t *mo; + int ms; + + if (target->flags & (MF_ENEMY|MF_BOSS)) + target->momx = target->momy = target->momz = 0; + + // SRB2kart + if (target->type != MT_PLAYER + && !(target->flags & MF_MONITOR) + && !(target->type == MT_ORBINAUT || target->type == MT_ORBINAUT_SHIELD + || target->type == MT_JAWZ || target->type == MT_JAWZ_DUD || target->type == MT_JAWZ_SHIELD + || target->type == MT_BANANA || target->type == MT_BANANA_SHIELD + || target->type == MT_EGGMANITEM || target->type == MT_EGGMANITEM_SHIELD + || target->type == MT_BALLHOG || target->type == MT_SPB)) // kart dead items + target->flags |= MF_NOGRAVITY; // Don't drop Tails 03-08-2000 + else + target->flags &= ~MF_NOGRAVITY; // lose it if you for whatever reason have it, I'm looking at you shields + // + + if (target->flags2 & MF2_NIGHTSPULL) + P_SetTarget(&target->tracer, NULL); + + // dead target is no more shootable + target->flags &= ~(MF_SHOOTABLE|MF_FLOAT|MF_SPECIAL); + target->flags2 &= ~(MF2_SKULLFLY|MF2_NIGHTSPULL); + target->health = 0; // This makes it easy to check if something's dead elsewhere. + + if (LUA_HookMobjDeath(target, inflictor, source) || P_MobjWasRemoved(target)) + return; + + P_UpdateRemovedOrbital(target, inflictor, source); + if (target->player) + { + // Above block does not clean up rocket sneakers when a player dies, so we need to do it here target->target is null when using rocket sneakers K_DropRocketSneaker(target->player); - // Let EVERYONE know what happened to a player! 01-29-2002 Tails - if (target->player && !target->player->spectator) - { - target->flags2 &= ~MF2_DONTDRAW; + // Let EVERYONE know what happened to a player! 01-29-2002 Tails + if (!target->player->spectator) + target->flags2 &= ~MF2_DONTDRAW; } // if killed by a player @@ -1581,6 +1573,7 @@ void P_KillMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source) { P_SetTarget(&target->target, source); source->player->numboxes++; + if (cv_itemrespawn.value && (netgame || multiplayer)) { target->fuse = cv_itemrespawntime.value*TICRATE + 2; // Random box generation @@ -1598,35 +1591,41 @@ void P_KillMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source) target->player->playerstate = PST_DEAD; - if (cv_fading.value && P_IsLocalPlayer(target->player)) + if (P_IsLocalPlayer(target->player)) { - if (netgame || multiplayer) - ms = cv_respawntime.value * 1000; - else - ms = 1000; + if (cv_fading.value) + { + if (netgame || multiplayer) + ms = cv_respawntime.value * 1000; + else + ms = 1000; - /* - If the time spent with the music paused is less than half - a second, continue playing the song (just mute it). - */ - if ((ms - cv_respawnfademusicout.value) < 500) - S_FadeMusic(0, cv_respawnfademusicout.value); - else - S_FadeOutStopMusic(cv_respawnfademusicout.value); - } + /* + * If the time spent with the music paused is less than half + * a second, continue playing the song (just mute it). + */ + if ((ms - cv_respawnfademusicout.value) < 500) + S_FadeMusic(0, cv_respawnfademusicout.value); + else + S_FadeOutStopMusic(cv_respawnfademusicout.value); + } - for (UINT8 i = 0; i <= splitscreen; i++) - { - if (target->player == P_GetLocalPlayerForNum(i)) + if (target->player == &players[consoleplayer]) { // don't die in auto map, // switch view prior to dying - if (i == 0 && automapactive) + if (automapactive) AM_Stop(); + } - // added : 22-02-98: recenter view for next life... - localaiming[i] = 0; - break; + for (UINT8 i = 0; i <= splitscreen; i++) + { + if (target->player == P_GetLocalPlayerForNum(i)) + { + // added : 22-02-98: recenter view for next life... + localaiming[i] = 0; + break; + } } } @@ -1642,7 +1641,7 @@ void P_KillMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source) // Drop stuff. // This determines the kind of object spawned // during the death frame of a thing. - if (!mariomode // Don't show birds, etc. in Mario Mode Tails 12-23-2001 + if (LIKELY(!mariomode) // Don't show birds, etc. in Mario Mode Tails 12-23-2001 && target->flags & MF_ENEMY) { if (cv_soniccd.value) @@ -1696,7 +1695,7 @@ void P_KillMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source) else prandom = P_RandomKey(5); // No placable object, just use a random number. - switch(prandom) + switch (prandom) { default: item = MT_BUNNY; break; case 1: item = MT_BIRD; break; @@ -1877,11 +1876,9 @@ void P_KillMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source) P_SetThingPosition(target); P_InstaThrust(target,target->angle,FixedMul(2*FRACUNIT, target->scale)); target->momz = FixedMul(7*FRACUNIT, target->scale); - if (flip) - target->momz = -target->momz; - if (flip) { + target->momz = -target->momz; target = P_SpawnMobj(x,y,z-FixedMul(12*FRACUNIT, target->scale),MT_SPIKE); target->eflags |= MFE_VERTICALFLIP; } @@ -2242,18 +2239,24 @@ boolean P_DamageMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 da return false; // well no clue but this may happen ig - if (!target || (target->health <= 0)) + if (P_MobjWasRemovedCompat(target)) + return false; + + if (target->health <= 0) return false; // Spectator handling if (netgame) { - if (damage == DMG_SPECTATOR && target->player && target->player->spectator) - damage = DMG_INSTAKILL; - else if (target->player && target->player->spectator) - return false; + if (target->player && target->player->spectator) + { + if (damage == DMG_SPECTATOR) + damage = DMG_INSTAKILL; + else + return false; + } - if (source && source->player && source->player->spectator) + if (!P_MobjWasRemovedCompat(source) && source->player && source->player->spectator) return false; } @@ -2347,16 +2350,17 @@ boolean P_DamageMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 da if (player->exiting) return false; - if (UNLIKELY(!(target->player->pflags & (PF_NIGHTSMODE|PF_NIGHTSFALL)) && (maptol & TOL_NIGHTS))) + if (UNLIKELY(!(target->player->pflags & (PF_NIGHTSMODE|PF_NIGHTSFALL)) && nightsmode)) return false; } - if (UNLIKELY(player->pflags & PF_NIGHTSMODE)) // NiGHTS damage handling + if (nightsplayer(player)) // NiGHTS damage handling { if (!force) { if (source == target) return false; // Don't hit yourself with your own paraloop, baka + if (source && source->player && !cv_friendlyfire.value && (gametype == GT_COOP || (G_GametypeHasTeams() && target->player->ctfteam == source->player->ctfteam))) @@ -2406,7 +2410,7 @@ boolean P_DamageMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 da else if (player->kartstuff[k_invincibilitytimer] > 0 || player->kartstuff[k_growshrinktimer] > 0 || player->powers[pw_flashing]) { - if (!force) // shoulddamage bypasses all of that. + if (!force) // shoulddamage bypasses all of that. { K_DoInstashield(player); return false; @@ -2420,7 +2424,6 @@ boolean P_DamageMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 da { player->kartstuff[k_sneakertimer] = 0; K_SpinPlayer(player, source, 1, inflictor, false); - damage = player->mo->health - 1; P_RingDamage(player, inflictor, source); P_PlayerRingBurst(player, 5); @@ -2596,7 +2599,7 @@ void P_PlayerRingBurst(player_t *player, INT32 num_rings) ns = FixedMul(((i*FRACUNIT)/16)+2*FRACUNIT, mo->scale); mo->momx = FixedMul(FINECOSINE(fa),ns); - if (LIKELY(!(twodlevel || (player->mo->flags2 & MF2_TWOD)))) + if (!twodmo(player->mo)) mo->momy = FixedMul(FINESINE(fa),ns); P_SetObjectMomZ(mo, 8*FRACUNIT, false); @@ -2620,7 +2623,7 @@ void P_PlayerRingBurst(player_t *player, INT32 num_rings) ns = FixedMul(momxy, mo->scale); mo->momx = FixedMul(FINECOSINE(fa),ns); - if (LIKELY(!(twodlevel || (player->mo->flags2 & MF2_TWOD)))) + if (!twodmo(player->mo)) mo->momy = FixedMul(FINESINE(fa),ns); ns = momz; @@ -2629,6 +2632,7 @@ void P_PlayerRingBurst(player_t *player, INT32 num_rings) if (i & 1) P_SetObjectMomZ(mo, ns, true); } + if (player->mo->eflags & MFE_VERTICALFLIP) mo->momz *= -1; } @@ -2727,7 +2731,7 @@ void P_PlayerWeaponPanelBurst(player_t *player) ns = FixedMul(3*FRACUNIT, mo->scale); mo->momx = FixedMul(FINECOSINE(fa),ns); - if (LIKELY(!(twodlevel || (player->mo->flags2 & MF2_TWOD)))) + if (!twodmo(player->mo)) mo->momy = FixedMul(FINESINE(fa),ns); P_SetObjectMomZ(mo, 4*FRACUNIT, false); @@ -2811,7 +2815,7 @@ void P_PlayerWeaponAmmoBurst(player_t *player) ns = FixedMul(2*FRACUNIT, mo->scale); mo->momx = FixedMul(FINECOSINE(fa), ns); - if (LIKELY(!(twodlevel || (player->mo->flags2 & MF2_TWOD)))) + if (!twodmo(player->mo)) mo->momy = FixedMul(FINESINE(fa),ns); P_SetObjectMomZ(mo, 3*FRACUNIT, false); @@ -2927,7 +2931,7 @@ void P_PlayerEmeraldBurst(player_t *player, boolean toss) momx = FixedMul(FINECOSINE(fa), ns); - if (LIKELY(!(twodlevel || (player->mo->flags2 & MF2_TWOD)))) + if (!twodmo(player->mo)) momy = FixedMul(FINESINE(fa),ns); else momy = 0; @@ -2984,7 +2988,7 @@ void P_PlayerFlagBurst(player_t *player, boolean toss) { angle_t fa = P_RandomByte()*FINEANGLES/256; flag->momx = FixedMul(FINECOSINE(fa), FixedMul(6*FRACUNIT, player->mo->scale)); - if (LIKELY(!(twodlevel || (player->mo->flags2 & MF2_TWOD)))) + if (!twodmo(player->mo)) flag->momy = FixedMul(FINESINE(fa), FixedMul(6*FRACUNIT, player->mo->scale)); } diff --git a/src/p_local.h b/src/p_local.h index 4d8e8032d..4f59246fc 100644 --- a/src/p_local.h +++ b/src/p_local.h @@ -14,10 +14,6 @@ #ifndef __P_LOCAL__ #define __P_LOCAL__ -#ifdef __cplusplus -extern "C" { -#endif - #include "command.h" #include "d_player.h" #include "d_think.h" @@ -28,9 +24,11 @@ extern "C" { #include "p_maputl.h" #include "doomstat.h" // MAXSPLITSCREENPLAYERS -#define FLOATSPEED (FRACUNIT*4) +#ifdef __cplusplus +extern "C" { +#endif -//#define VIEWHEIGHTS "41" +#define FLOATSPEED (FRACUNIT*4) // Maximum player score. #define MAXSCORE 999999990 @@ -61,8 +59,12 @@ extern "C" { #define AIMINGTOSLOPE(aiming) FINESINE((aiming>>ANGLETOFINESHIFT) & FINEMASK) -#define mariomode (maptol & TOL_MARIO) -#define twodlevel (maptol & TOL_2D) +// unused modes, kept for compat +#define nightsmode (UNLIKELY(maptol & TOL_NIGHTS)) +#define nightsplayer(player) (UNLIKELY((player)->pflags & PF_NIGHTSMODE)) +#define mariomode (UNLIKELY(maptol & TOL_MARIO)) +#define twodlevel (UNLIKELY(maptol & TOL_2D)) +#define twodmo(mobj) (UNLIKELY(twodlevel || ((mobj)->flags2 & MF2_TWOD))) // // P_TICK @@ -101,10 +103,6 @@ typedef struct camera_s // Hold up/down to pan the camera vertically SINT8 dpad_y_held; - // Things used by FS cameras. - fixed_t viewheight; - angle_t startangle; - // Camera demobjerization // Info for drawing: position. fixed_t x, y, z; @@ -123,8 +121,6 @@ typedef struct camera_s fixed_t radius; fixed_t height; - fixed_t relativex; - // Momentums, used to update position. fixed_t momx, momy, momz; @@ -214,7 +210,6 @@ mobj_t *P_SpawnGhostMobj(mobj_t *mobj); void P_GivePlayerRings(player_t *player, INT32 num_rings); void P_GivePlayerLives(player_t *player, INT32 numlives); UINT8 P_GetNextEmerald(void); -void P_GiveEmerald(boolean spawnObj); void P_ResetScore(player_t *player); boolean P_AutoPause(void); @@ -222,7 +217,6 @@ void P_DoJumpShield(player_t *player); void P_BlackOw(player_t *player); void P_ElementalFireTrail(player_t *player); -//void P_DoPityCheck(player_t *player); void P_PlayerThink(player_t *player); void P_PlayerAfterThink(player_t *player); void P_DoPlayerExit(player_t *player); @@ -239,14 +233,10 @@ void P_InstaThrustEvenIn2D(mobj_t *mo, angle_t angle, fixed_t move); boolean P_LookForEnemies(player_t *player); void P_NukeEnemies(mobj_t *inflictor, mobj_t *source, fixed_t radius); void P_HomingAttack(mobj_t *source, mobj_t *enemy); /// \todo doesn't belong in p_user -//boolean P_SuperReady(player_t *player); boolean P_AnalogMove(player_t *player); -/*boolean P_TransferToNextMare(player_t *player); -UINT8 P_FindLowestMare(void);*/ UINT8 P_FindLowestLap(void); UINT8 P_FindHighestLap(void); void P_FindEmerald(void); -//void P_TransferToAxis(player_t *player, INT32 axisnum); boolean P_PlayerMoving(INT32 pnum); void P_Telekinesis(player_t *player, fixed_t thrust, fixed_t range); @@ -272,6 +262,9 @@ extern consvar_t cv_gravity; void P_RespawnSpecials(void); +extern mobjtype_t g_doomednum_to_mobjtype[MAXDOOMEDNUM+1]; +void CalculateDoomednumToMobjtype(void); + mobj_t *P_AllocateMobj(void); mobj_t *P_SpawnMobj(fixed_t x, fixed_t y, fixed_t z, mobjtype_t type); @@ -284,7 +277,6 @@ void P_RemoveMobj(mobj_t *th); void P_RemoveSavegameMobj(mobj_t *th); boolean P_SetPlayerMobjState(mobj_t *mobj, statenum_t state); boolean P_SetMobjState(mobj_t *mobj, statenum_t state); -//void P_RunShields(void); void P_RunOverlays(void); void P_RunShadows(void); void P_MobjThinker(mobj_t *mobj); @@ -299,6 +291,17 @@ FUNCINLINE static ATTRINLINE boolean P_MobjWasRemoved(const mobj_t *mobj) return (!mobj || mobj->thinker.function != (actionf_p1)P_MobjThinker); } +// stupid, but kart allows mobjs that are marked to be removed to be accessed and modified in many cases +// so can only check if its not NULL in vanilla compat mode +FUNCINLINE static ATTRINLINE boolean P_MobjWasRemovedCompat(const mobj_t *mobj) +{ +#ifdef PHOBOS_BUILD + return P_MobjWasRemoved(mobj); +#else + return !mobj; +#endif +} + fixed_t P_MobjFloorZ(mobj_t *mobj, sector_t *sector, sector_t *boundsec, fixed_t x, fixed_t y, line_t *line, boolean lowest, boolean perfect); fixed_t P_MobjCeilingZ(mobj_t *mobj, sector_t *sector, sector_t *boundsec, fixed_t x, fixed_t y, line_t *line, boolean lowest, boolean perfect); #define P_GetFloorZ(mobj, sector, x, y, line) P_MobjFloorZ(mobj, sector, NULL, x, y, line, false, false) diff --git a/src/p_map.c b/src/p_map.c index e51930bef..9c974ce44 100644 --- a/src/p_map.c +++ b/src/p_map.c @@ -136,14 +136,17 @@ boolean P_DoSpring(mobj_t *spring, mobj_t *object) if (object->eflags & MFE_SPRUNG) // Object was already sprung this tic return false; - // Spectators don't trigger springs. - if (object->player && object->player->spectator) - return false; - - if (UNLIKELY(object->player && (object->player->pflags & PF_NIGHTSMODE))) + if (object->player) { - /*Someone want to make these work like bumpers?*/ - return false; + // Spectators don't trigger springs. + if (object->player->spectator) + return false; + + if (nightsplayer(object->player)) + { + /*Someone want to make these work like bumpers?*/ + return false; + } } object->standingslope = NULL; // Okay, now we can't return - no launching off at silly angles for you. @@ -160,10 +163,15 @@ boolean P_DoSpring(mobj_t *spring, mobj_t *object) if (spring->eflags & MFE_VERTICALFLIP) vertispeed *= -1; + // Vertical springs teleport you on TOP of them. if (vertispeed > 0) + { object->z = spring->z + spring->height + 1; + } else if (vertispeed < 0) + { object->z = spring->z - object->height - 1; + } else { // Horizontal springs teleport you in FRONT of them. @@ -189,12 +197,12 @@ boolean P_DoSpring(mobj_t *spring, mobj_t *object) } if (vertispeed) - object->momz = FixedMul(vertispeed,FixedSqrt(FixedMul(vscale, spring->scale))); + object->momz = FixedMul(vertispeed, FixedSqrt(FixedMul(vscale, spring->scale))); if (horizspeed) { if (!object->player) - P_InstaThrustEvenIn2D(object, spring->angle, FixedMul(horizspeed,FixedSqrt(FixedMul(hscale, spring->scale)))); + P_InstaThrustEvenIn2D(object, spring->angle, FixedMul(horizspeed, FixedSqrt(FixedMul(hscale, spring->scale)))); else { fixed_t finalSpeed = FixedDiv(horizspeed, hscale); @@ -203,7 +211,7 @@ boolean P_DoSpring(mobj_t *spring, mobj_t *object) if (pSpeed > finalSpeed) finalSpeed = pSpeed; - P_InstaThrustEvenIn2D(object, spring->angle, FixedMul(finalSpeed,FixedSqrt(FixedMul(hscale, spring->scale)))); + P_InstaThrustEvenIn2D(object, spring->angle, FixedMul(finalSpeed, FixedSqrt(FixedMul(hscale, spring->scale)))); } } @@ -215,7 +223,9 @@ boolean P_DoSpring(mobj_t *spring, mobj_t *object) if (object->player) { if (spring->flags & MF_ENEMY) // Spring shells + { P_SetTarget(&spring->target, object); + } if (horizspeed && object->player->cmd.forwardmove == 0 && object->player->cmd.sidemove == 0) { @@ -235,12 +245,12 @@ boolean P_DoSpring(mobj_t *spring, mobj_t *object) static void P_DoFanAndGasJet(mobj_t *spring, mobj_t *object) { - player_t *p = object->player; // will be NULL if not a player + player_t *player = object->player; // will be NULL if not a player fixed_t zdist; // distance between bottoms fixed_t speed = spring->info->mass; // conveniently, both fans and gas jets use this for the vertical thrust SINT8 flipval = P_MobjFlip(spring); // virtually everything here centers around the thruster's gravity, not the object's! - if (p && object->state == &states[object->info->painstate]) // can't use fans and gas jets when player is in pain! + if (player && object->state == &states[object->info->painstate]) // can't use fans and gas jets when player is in pain! return; // is object's top below thruster's position? if not, calculate distance between their bottoms @@ -266,7 +276,7 @@ static void P_DoFanAndGasJet(mobj_t *spring, mobj_t *object) break; if (flipval*object->momz >= FixedMul(speed, spring->scale)) // if object's already moving faster than your best, don't bother break; - if (p && (p->climbing || p->pflags & PF_GLIDING)) // doesn't affect Knux when he's using his abilities! + if (player && (player->climbing || player->pflags & PF_GLIDING)) // doesn't affect Knux when he's using his abilities! break; object->momz += flipval*FixedMul(speed/4, spring->scale); @@ -312,16 +322,16 @@ static boolean PIT_CheckThing(mobj_t *thing) if (thing == tmthing) return true; - // Ignore... things. - if (!tmthing || P_MobjWasRemoved(thing)) - return true; - I_Assert(!P_MobjWasRemoved(tmthing)); I_Assert(!P_MobjWasRemoved(thing)); + // Ignore... things. + if (P_MobjWasRemovedCompat(tmthing) || P_MobjWasRemoved(thing)) + return true; + // Ignore spectators if ((tmthing->player && tmthing->player->spectator) - || (thing->player && thing->player->spectator)) + || (thing->player && thing->player->spectator)) return true; #ifdef SEENAMES @@ -350,12 +360,13 @@ static boolean PIT_CheckThing(mobj_t *thing) } #endif - if (!(thing->flags & (MF_SOLID|MF_SPECIAL|MF_PAIN|MF_SHOOTABLE)) || (thing->flags & MF_NOCLIPTHING)) + if ((thing->flags & MF_NOCLIPTHING) || !(thing->flags & (MF_SOLID|MF_SPECIAL|MF_PAIN|MF_SHOOTABLE))) return true; // Don't collide with your buddies while NiGHTS-flying. - if (UNLIKELY(tmthing->player && thing->player && (maptol & TOL_NIGHTS) - && ((tmthing->player->pflags & PF_NIGHTSMODE) || (thing->player->pflags & PF_NIGHTSMODE)))) + if (nightsmode && + tmthing->player && thing->player && + (nightsplayer(tmthing->player) || nightsplayer(thing->player))) return true; blockdist = thing->radius + tmthing->radius; @@ -719,11 +730,11 @@ static boolean PIT_CheckThing(mobj_t *thing) if (thing->type != MT_PLAYER) return true; - if (thing->player && thing->player->powers[pw_flashing]) - return true; - - if (thing->type == MT_PLAYER && thing->player) + if (thing->player) { + if (thing->player->powers[pw_flashing]) + return true; + if (tmthing->state == &states[S_MINEEXPLOSION1]) K_ExplodePlayer(thing->player, tmthing->target, tmthing); else @@ -1077,6 +1088,7 @@ static boolean PIT_CheckThing(mobj_t *thing) thing->momy -= FixedMul(PUSHACCEL, thing->scale); tmthing->momy += FixedMul(PUSHACCEL, thing->scale); } + if (tmthing->momx > 0 && tmthing->momx > FixedMul(4*FRACUNIT, thing->scale) && tmthing->momx > thing->momx) { @@ -1094,6 +1106,7 @@ static boolean PIT_CheckThing(mobj_t *thing) thing->momx = FixedMul(thing->info->speed, thing->scale); else if (thing->momx < -FixedMul(thing->info->speed, thing->scale)) thing->momx = -FixedMul(thing->info->speed, thing->scale); + if (thing->momy > FixedMul(thing->info->speed, thing->scale)) thing->momy = FixedMul(thing->info->speed, thing->scale); else if (thing->momy < -FixedMul(thing->info->speed, thing->scale)) @@ -1105,6 +1118,7 @@ static boolean PIT_CheckThing(mobj_t *thing) tmthing->momx = FixedMul(4*FRACUNIT, thing->scale); else if (tmthing->momx < FixedMul(-4*FRACUNIT, thing->scale)) tmthing->momx = FixedMul(-4*FRACUNIT, thing->scale); + if (tmthing->momy > FixedMul(4*FRACUNIT, thing->scale)) tmthing->momy = FixedMul(4*FRACUNIT, thing->scale); else if (tmthing->momy < FixedMul(-4*FRACUNIT, thing->scale)) @@ -1126,6 +1140,7 @@ static boolean PIT_CheckThing(mobj_t *thing) P_TouchSpecialThing(thing, tmthing, true); // can remove thing return true; } + // check again for special pickup if (tmthing->flags & MF_SPECIAL && thing->player) { @@ -1509,14 +1524,14 @@ static boolean PIT_CheckThing(mobj_t *thing) // Adjusts tmfloorz and tmceilingz as lines are contacted - FOR CAMERA ONLY static boolean PIT_CheckCameraLine(line_t *ld) { - if (ld->polyobj && !(ld->polyobj->flags & POF_SOLID)) + if (tmbbox[BOXRIGHT] <= ld->bbox[BOXLEFT] || + tmbbox[BOXLEFT] >= ld->bbox[BOXRIGHT] || + tmbbox[BOXTOP] <= ld->bbox[BOXBOTTOM] || + tmbbox[BOXBOTTOM] >= ld->bbox[BOXTOP]) return true; - if (tmbbox[BOXRIGHT] <= ld->bbox[BOXLEFT] || tmbbox[BOXLEFT] >= ld->bbox[BOXRIGHT] - || tmbbox[BOXTOP] <= ld->bbox[BOXBOTTOM] || tmbbox[BOXBOTTOM] >= ld->bbox[BOXTOP]) - { + if (ld->polyobj && !(ld->polyobj->flags & POF_SOLID)) return true; - } if (P_BoxOnLineSide(tmbbox, ld) != -1) return true; @@ -1571,23 +1586,27 @@ static boolean PIT_CheckCameraLine(line_t *ld) // static boolean PIT_CheckLine(line_t *ld) { + if (tmbbox[BOXRIGHT] <= ld->bbox[BOXLEFT] || + tmbbox[BOXLEFT] >= ld->bbox[BOXRIGHT] || + tmbbox[BOXTOP] <= ld->bbox[BOXBOTTOM] || + tmbbox[BOXBOTTOM] >= ld->bbox[BOXTOP]) + return true; // didn't hit it + if (ld->polyobj && !(ld->polyobj->flags & POF_SOLID)) return true; - if (tmbbox[BOXRIGHT] <= ld->bbox[BOXLEFT] || tmbbox[BOXLEFT] >= ld->bbox[BOXRIGHT] - || tmbbox[BOXTOP] <= ld->bbox[BOXBOTTOM] || tmbbox[BOXBOTTOM] >= ld->bbox[BOXTOP]) - return true; - if (P_BoxOnLineSide(tmbbox, ld) != -1) - return true; + return true; // didn't hit it if (tmthing->flags & MF_PAPERCOLLISION) // Caution! Turning whilst up against a wall will get you stuck. You probably shouldn't give the player this flag. { fixed_t cosradius, sinradius; + cosradius = FixedMul(tmthing->radius, FINECOSINE(tmthing->angle>>ANGLETOFINESHIFT)); sinradius = FixedMul(tmthing->radius, FINESINE(tmthing->angle>>ANGLETOFINESHIFT)); + if (P_PointOnLineSide(tmx - cosradius, tmy - sinradius, ld) - == P_PointOnLineSide(tmx + cosradius, tmy + sinradius, ld)) + == P_PointOnLineSide(tmx + cosradius, tmy + sinradius, ld)) return true; // the line doesn't cross between collider's start or end } @@ -1809,14 +1828,14 @@ boolean P_CheckPosition(mobj_t *thing, fixed_t x, fixed_t y) delta1 = abs(thing->z - midheight); delta2 = abs(thingtop - midheight); - if (topheight > tmfloorz && delta1 < delta2 + if ((topheight > tmfloorz) && (delta1 < delta2) && !(rover->flags & FF_REVERSEPLATFORM)) { tmfloorz = tmdropoffz = topheight; tmfloorslope = *rover->t_slope; } - if (bottomheight < tmceilingz && delta1 >= delta2 + if ((bottomheight < tmceilingz) && (delta1 >= delta2) && !(rover->flags & FF_PLATFORM) && !(thing->type == MT_SKIM && (rover->flags & FF_SWIMMABLE))) { @@ -1871,8 +1890,7 @@ boolean P_CheckPosition(mobj_t *thing, fixed_t x, fixed_t y) po->validcount = validcount; - if (!P_BBoxInsidePolyobj(po, tmbbox) - || !(po->flags & POF_SOLID)) + if (!(po->flags & POF_SOLID) || !P_BBoxInsidePolyobj(po, tmbbox)) { plink = (polymaplink_t *)(plink->link.next); continue; @@ -2117,7 +2135,7 @@ static boolean P_CheckCameraPosition(fixed_t x, fixed_t y, camera_t *thiscam) po->validcount = validcount; - if (!P_PointInsidePolyobj(po, x, y) || !(po->flags & POF_SOLID)) + if (!(po->flags & POF_SOLID) || !P_PointInsidePolyobj(po, x, y)) { plink = (polymaplink_t *)(plink->link.next); continue; @@ -2367,8 +2385,11 @@ boolean P_TryMove(mobj_t *thing, fixed_t x, fixed_t y, boolean allowdropoff) fixed_t tryx = thing->x; fixed_t tryy = thing->y; fixed_t radius = thing->radius; - fixed_t thingtop ;//= thing->z + thing->height; + fixed_t thingtop;//= thing->z + thing->height; fixed_t startingonground = P_IsObjectOnGround(thing); + fixed_t stairjank = 0; + pslope_t *oldslope = thing->standingslope; + INT32 special = -1; floatok = false; if (radius < MAXRADIUS/2) @@ -2402,21 +2423,31 @@ boolean P_TryMove(mobj_t *thing, fixed_t x, fixed_t y, boolean allowdropoff) if (!(thing->flags & MF_NOCLIP)) { - //All things are affected by their scale. - fixed_t maxstep = FixedMul(MAXSTEPMOVE, mapobjectscale); - INT32 special = 0; + // All things are affected by their scale. + fixed_t maxstep; + + if (tmceilingz - tmfloorz < thing->height) + { + if (tmfloorthing) + tmhitthing = tmfloorthing; + + return false; // doesn't fit + } + + maxstep = FixedMul(MAXSTEPMOVE, mapobjectscale); if (thing->player) { - special = GETSECSPECIAL(R_PointInSubsector(x, y)->sector->special, 1); + if (special == -1) // this should use the target coords not the ones were started with, but cant fix that for compat reasons! + special = GETSECSPECIAL(R_PointInSubsector(x, y)->sector->special, 1); // If using type Section1:13, double the maxstep. - if (P_PlayerTouchingSectorSpecial(thing->player, 1, 13) || special == 13) + if (special == 13 || P_PlayerTouchingSectorSpecial(thing->player, 1, 13)) { maxstep <<= 1; } // If using type Section1:12, no maxstep. For ledges you don't want the player to climb! (see: Egg Zeppelin & SMK port walls) - else if (P_PlayerTouchingSectorSpecial(thing->player, 1, 12) || special == 12) + else if (special == 12 || P_PlayerTouchingSectorSpecial(thing->player, 1, 12)) { maxstep = 0; } @@ -2427,23 +2458,23 @@ boolean P_TryMove(mobj_t *thing, fixed_t x, fixed_t y, boolean allowdropoff) maxstep = 0; } - if (tmceilingz - tmfloorz < thing->height) - { - if (tmfloorthing) - tmhitthing = tmfloorthing; - - return false; // doesn't fit - } - floatok = true; thingtop = thing->z + thing->height; + const boolean flipped = + (thing->eflags & MFE_VERTICALFLIP) != 0; + // Step up if (thing->z < tmfloorz) { if (tmfloorz - thing->z <= maxstep) { + if (maxstep > 0 && !flipped) + { + stairjank = (tmfloorz - thing->z); + } + thing->z = thing->floorz = tmfloorz; thing->eflags |= MFE_JUSTSTEPPEDDOWN; } @@ -2456,6 +2487,11 @@ boolean P_TryMove(mobj_t *thing, fixed_t x, fixed_t y, boolean allowdropoff) { if (thingtop - tmceilingz <= maxstep) { + if (maxstep > 0 && flipped) + { + stairjank = (thingtop - tmceilingz); + } + thing->z = ( thing->ceilingz = tmceilingz ) - thing->height; thing->eflags |= MFE_JUSTSTEPPEDDOWN; } @@ -2465,18 +2501,28 @@ boolean P_TryMove(mobj_t *thing, fixed_t x, fixed_t y, boolean allowdropoff) } } else if (maxstep > 0 && !(thing->player && - (P_PlayerTouchingSectorSpecial(thing->player, 1, 14) || special == 14))) // Step down + (special == 14 || P_PlayerTouchingSectorSpecial(thing->player, 1, 14)))) // Step down { // If the floor difference is MAXSTEPMOVE or less, and the sector isn't Section1:14, ALWAYS // step down! Formerly required a Section1:13 sector for the full MAXSTEPMOVE, but no more. if (thingtop == thing->ceilingz && tmceilingz > thingtop && tmceilingz - thingtop <= maxstep) { + if (flipped) + { + stairjank = (tmceilingz - thingtop); + } + thing->z = (thing->ceilingz = tmceilingz) - thing->height; thing->eflags |= MFE_JUSTSTEPPEDDOWN; } else if (thing->z == thing->floorz && tmfloorz < thing->z && thing->z - tmfloorz <= maxstep) { + if (!flipped) + { + stairjank = (thing->z - tmfloorz); + } + thing->z = thing->floorz = tmfloorz; thing->eflags |= MFE_JUSTSTEPPEDDOWN; } @@ -2552,6 +2598,26 @@ boolean P_TryMove(mobj_t *thing, fixed_t x, fixed_t y, boolean allowdropoff) else // don't set standingslope if you're not going to clip against it thing->standingslope = NULL; + /* FIXME: slope step down (even up) has some false + positives, so just ignore them entirely. */ + if (stairjank && !oldslope && !thing->standingslope && thing->player && !thing->player->spectator) + { + /* use a shorter sound if not two tics have passed + * since the last step */ + //S_ReducedVFXSound(thing, (thing->player->stairjank >= 16 ? sfx_s23b : sfx_s268), NULL); + //S_StartSound(thing, (thing->player->stairjank >= 16 ? sfx_s23b : sfx_s268)); + // sound does not work out all that well for kart maps + + // best i can do... + if (cv_stairjank.value && cv_stairjanksfx.value) + S_StartSoundAtVolume(thing, (thing->player->stairjank >= 8 ? sfx_s23b : sfx_s268), 192); // dont blast this at full volume lul + + // Can't spawn things during P_TryMove, because global variables :) + + thing->player->stairjank = 9; + //thing->player->stairjank = 17; + } + thing->x = x; thing->y = y; @@ -2602,7 +2668,7 @@ boolean P_SceneryTryMove(mobj_t *thing, fixed_t x, fixed_t y) if (tmfloorz - thing->z > maxstep) return false; // too big a step up } - } while(tryx != x || tryy != y); + } while (tryx != x || tryy != y); // the move is ok, // so link the thing into its new position @@ -3097,6 +3163,9 @@ void P_SlideMove(mobj_t *mo, boolean forceslide) INT16 hitcount = 0; boolean success = false; + if (P_MobjWasRemovedCompat(mo)) + return; + if (tmhitthing && mo->z + mo->height > tmhitthing->z && mo->z < tmhitthing->z + tmhitthing->height) { // Don't mess with your momentum if it's a pushable object. Pushables do their own crazy things already. @@ -3133,6 +3202,9 @@ void P_SlideMove(mobj_t *mo, boolean forceslide) bestslideline = NULL; retry: + if (P_MobjWasRemovedCompat(mo)) + return; + if (++hitcount == 3) goto stairstep; // don't loop forever @@ -3181,7 +3253,13 @@ retry: // the move must have hit the middle, so stairstep stairstep: if (!P_TryMove(mo, mo->x, mo->y + mo->momy, true)) //Allow things to drop off. + { + if (P_MobjWasRemovedCompat(mo)) + return; + P_TryMove(mo, mo->x + mo->momx, mo->y, true); + } + return; } @@ -3193,7 +3271,12 @@ stairstep: newy = FixedMul(mo->momy, bestslidefrac); if (!P_TryMove(mo, mo->x + newx, mo->y + newy, true)) + { goto stairstep; + } + + if (P_MobjWasRemovedCompat(mo)) + return; } // Now continue along the wall. @@ -3212,7 +3295,7 @@ stairstep: if (bestslideline != NULL) P_HitSlideLine(bestslideline); // clip the moves - if (UNLIKELY((twodlevel || (mo->flags2 & MF2_TWOD)) && mo->player)) + if (twodmo(mo) && mo->player) { mo->momx = tmxmove; tmymove = 0; @@ -3264,8 +3347,11 @@ stairstep: goto retry; } + if (P_MobjWasRemovedCompat(mo)) + return; + success = true; - } while(tmxmove || tmymove); + } while (tmxmove || tmymove); } // @@ -3278,12 +3364,18 @@ void P_BouncePlayerMove(mobj_t *mo) { fixed_t leadx, leady; fixed_t trailx, traily; - fixed_t mmomx = 0, mmomy = 0; - fixed_t oldmomx = mo->momx, oldmomy = mo->momy; + fixed_t mmomx, mmomy; + fixed_t oldmomx, oldmomy; - if (!mo->player) + if (P_MobjWasRemovedCompat(mo)) return; + if (mo->player == NULL) + return; + + oldmomx = mo->momx; + oldmomy = mo->momy; + if (mo->player->spectator) { P_SlideMove(mo, true); @@ -3372,6 +3464,9 @@ void P_BouncePlayerMove(mobj_t *mo) if (!P_TryMove(mo, mo->x + tmxmove, mo->y + tmymove, true)) { + if (P_MobjWasRemovedCompat(mo)) + return; + P_TryMove(mo, mo->x - oldmomx, mo->y - oldmomy, true); } } @@ -3389,6 +3484,9 @@ void P_BounceMove(mobj_t *mo) INT32 hitcount; fixed_t mmomx = 0, mmomy = 0; + if (P_MobjWasRemovedCompat(mo)) + return; + if (mo->player) { P_BouncePlayerMove(mo); @@ -3405,6 +3503,9 @@ void P_BounceMove(mobj_t *mo) hitcount = 0; retry: + if (P_MobjWasRemovedCompat(mo)) + return; + if (++hitcount == 3) goto bounceback; // don't loop forever @@ -3463,7 +3564,12 @@ bounceback: newy = FixedMul(mmomy, bestslidefrac); if (!P_TryMove(mo, mo->x + newx, mo->y + newy, true)) + { + if (P_MobjWasRemovedCompat(mo)) + return; + goto bounceback; + } } // Now continue along the wall. @@ -3537,6 +3643,12 @@ static boolean PIT_RadiusAttack(mobj_t *thing) if (thing->flags & MF_MONITOR) return true; + if (thing->floorz > bombspot->z && bombspot->ceilingz < thing->z) + return true; + + if (thing->ceilingz < bombspot->z && bombspot->floorz > thing->z) + return true; + dx = abs(thing->x - bombspot->x); dy = abs(thing->y - bombspot->y); dz = abs(thing->z + (thing->height>>1) - bombspot->z); @@ -3550,14 +3662,9 @@ static boolean PIT_RadiusAttack(mobj_t *thing) if (dist >= bombdamage) return true; // out of range - if (thing->floorz > bombspot->z && bombspot->ceilingz < thing->z) - return true; - - if (thing->ceilingz < bombspot->z && bombspot->floorz > thing->z) - return true; - + // must be in direct path if (P_CheckSight(thing, bombspot)) - { // must be in direct path + { P_DamageMobj(thing, bombspot, bombsource, 1); // Tails 01-11-2001 } @@ -3659,7 +3766,7 @@ static boolean PIT_ChangeSector(mobj_t *thing, boolean realcrush) delta1 = abs(thing->z - midheight); delta2 = abs(thingtop - midheight); - if (bottomheight <= thing->ceilingz && delta1 >= delta2) + if ((bottomheight <= thing->ceilingz) && (delta1 >= delta2)) { if (thing->flags & MF_PUSHABLE) { @@ -4001,10 +4108,10 @@ static inline boolean PIT_GetSectors(line_t *ld) tmbbox[BOXBOTTOM] >= ld->bbox[BOXTOP]) return true; - if (P_BoxOnLineSide(tmbbox, ld) != -1) + if (ld->polyobj) // line belongs to a polyobject, don't add it return true; - if (ld->polyobj) // line belongs to a polyobject, don't add it + if (P_BoxOnLineSide(tmbbox, ld) != -1) return true; // This line crosses through the object. @@ -4117,7 +4224,7 @@ void P_CreateSecNodeList(mobj_t *thing, fixed_t x, fixed_t y) * Must clear tmthing at tic end, as it might contain a pointer to a removed thinker, or the level might have ended/been ended and we clear the objects it was pointing too. Hopefully we don't need to carry this between tics for sync. */ void P_MapStart(void) { - if (UNLIKELY(tmthing)) + if (tmthing) I_Error("P_MapStart: tmthing set!"); } @@ -4169,7 +4276,7 @@ fixed_t P_FloorzAtPos(fixed_t x, fixed_t y, fixed_t z, fixed_t height) delta1 = abs(z - midheight); delta2 = abs(thingtop - midheight); - if (topheight > floorz && delta1 < delta2) + if ((topheight > floorz) && (delta1 < delta2)) floorz = topheight; } } diff --git a/src/p_maputl.cpp b/src/p_maputl.cpp index 37b31c4ac..122311903 100644 --- a/src/p_maputl.cpp +++ b/src/p_maputl.cpp @@ -242,7 +242,7 @@ void P_CameraLineOpening(line_t *linedef) sector_t *back; fixed_t frontfloor, frontceiling, backfloor, backceiling; - if (linedef->sidenum[1] == 0xffff) + if (linedef->sidenum[1] == NO_INDEX) { // single sided line openrange = 0; @@ -326,7 +326,7 @@ void P_CameraLineOpening(line_t *linedef) { for (rover = front->ffloors; rover; rover = rover->next) { - fixed_t topheight, bottomheight; + fixed_t topheight, bottomheight, midheight; if (!(rover->flags & FF_BLOCKOTHERS) || !(rover->flags & FF_RENDERALL) || !(rover->flags & FF_EXISTS) || UNLIKELY(GETSECSPECIAL(rover->master->frontsector->special, 4) == 12)) continue; @@ -334,8 +334,10 @@ void P_CameraLineOpening(line_t *linedef) topheight = P_CameraGetFOFTopZ(mapcampointer, front, rover, tmx, tmy, linedef); bottomheight = P_CameraGetFOFBottomZ(mapcampointer, front, rover, tmx, tmy, linedef); - delta1 = abs(mapcampointer->z - (bottomheight + ((topheight - bottomheight)/2))); - delta2 = abs(thingtop - (bottomheight + ((topheight - bottomheight)/2))); + midheight = (bottomheight + ((topheight - bottomheight) / 2)); + + delta1 = abs(mapcampointer->z - midheight); + delta2 = abs(thingtop - midheight); if (bottomheight < lowestceiling && delta1 >= delta2) lowestceiling = bottomheight; @@ -354,7 +356,7 @@ void P_CameraLineOpening(line_t *linedef) { for (rover = back->ffloors; rover; rover = rover->next) { - fixed_t topheight, bottomheight; + fixed_t topheight, bottomheight, midheight; if (!(rover->flags & FF_BLOCKOTHERS) || !(rover->flags & FF_RENDERALL) || !(rover->flags & FF_EXISTS) || UNLIKELY(GETSECSPECIAL(rover->master->frontsector->special, 4) == 12)) continue; @@ -362,8 +364,10 @@ void P_CameraLineOpening(line_t *linedef) topheight = P_CameraGetFOFTopZ(mapcampointer, back, rover, tmx, tmy, linedef); bottomheight = P_CameraGetFOFBottomZ(mapcampointer, back, rover, tmx, tmy, linedef); - delta1 = abs(mapcampointer->z - (bottomheight + ((topheight - bottomheight)/2))); - delta2 = abs(thingtop - (bottomheight + ((topheight - bottomheight)/2))); + midheight = (bottomheight + ((topheight - bottomheight) / 2)); + + delta1 = abs(mapcampointer->z - midheight); + delta2 = abs(thingtop - midheight); if (bottomheight < lowestceiling && delta1 >= delta2) lowestceiling = bottomheight; @@ -398,7 +402,7 @@ void P_LineOpening(line_t *linedef, mobj_t *mobj) { sector_t *front, *back; - if (linedef->sidenum[1] == 0xffff) + if (linedef->sidenum[1] == NO_INDEX) { // single sided line openrange = 0; @@ -423,46 +427,46 @@ void P_LineOpening(line_t *linedef, mobj_t *mobj) // Set open and high/low values here fixed_t frontheight, backheight; - frontheight = P_GetCeilingZ(mobj, front, tmx, tmy, linedef); - backheight = P_GetCeilingZ(mobj, back, tmx, tmy, linedef); - - if (frontheight < backheight) - { - opentop = frontheight; - highceiling = backheight; - opentopslope = front->c_slope; - } - else - { - opentop = backheight; - highceiling = frontheight; - opentopslope = back->c_slope; - } - - frontheight = P_GetFloorZ(mobj, front, tmx, tmy, linedef); - backheight = P_GetFloorZ(mobj, back, tmx, tmy, linedef); - - if (frontheight > backheight) - { - openbottom = frontheight; - lowfloor = backheight; - openbottomslope = front->f_slope; - } - else - { - openbottom = backheight; - lowfloor = frontheight; - openbottomslope = back->f_slope; - } - if (mobj) { + frontheight = P_GetCeilingZ(mobj, front, tmx, tmy, linedef); + backheight = P_GetCeilingZ(mobj, back, tmx, tmy, linedef); + + if (frontheight < backheight) + { + opentop = frontheight; + highceiling = backheight; + opentopslope = front->c_slope; + } + else + { + opentop = backheight; + highceiling = frontheight; + opentopslope = back->c_slope; + } + + frontheight = P_GetFloorZ(mobj, front, tmx, tmy, linedef); + backheight = P_GetFloorZ(mobj, back, tmx, tmy, linedef); + + if (frontheight > backheight) + { + openbottom = frontheight; + lowfloor = backheight; + openbottomslope = front->f_slope; + } + else + { + openbottom = backheight; + lowfloor = frontheight; + openbottomslope = back->f_slope; + } + fixed_t thingtop = mobj->z + mobj->height; // Check for collision with front side's midtexture if Effect 4 is set if (linedef->flags & ML_EFFECT4 && !linedef->polyobj) // don't do anything for polyobjects! ...for now - { + { side_t *side = &sides[linedef->sidenum[0]]; fixed_t textop, texbottom, texheight; fixed_t texmid, delta1, delta2; @@ -524,7 +528,7 @@ void P_LineOpening(line_t *linedef, mobj_t *mobj) // Check for frontsector's fake floors for (rover = front->ffloors; rover; rover = rover->next) { - fixed_t topheight, bottomheight; + fixed_t topheight, bottomheight, midheight; if (!(rover->flags & FF_EXISTS)) continue; @@ -538,8 +542,10 @@ void P_LineOpening(line_t *linedef, mobj_t *mobj) topheight = P_GetFOFTopZ(mobj, front, rover, tmx, tmy, linedef); bottomheight = P_GetFOFBottomZ(mobj, front, rover, tmx, tmy, linedef); - delta1 = abs(mobj->z - (bottomheight + ((topheight - bottomheight)/2))); - delta2 = abs(thingtop - (bottomheight + ((topheight - bottomheight)/2))); + midheight = (bottomheight + ((topheight - bottomheight) / 2)); + + delta1 = abs(mobj->z - midheight); + delta2 = abs(thingtop - midheight); if (delta1 >= delta2 && !(rover->flags & FF_PLATFORM)) // thing is below FOF { @@ -567,7 +573,7 @@ void P_LineOpening(line_t *linedef, mobj_t *mobj) // Check for backsectors fake floors for (rover = back->ffloors; rover; rover = rover->next) { - fixed_t topheight, bottomheight; + fixed_t topheight, bottomheight, midheight; if (!(rover->flags & FF_EXISTS)) continue; @@ -580,8 +586,10 @@ void P_LineOpening(line_t *linedef, mobj_t *mobj) topheight = P_GetFOFTopZ(mobj, back, rover, tmx, tmy, linedef); bottomheight = P_GetFOFBottomZ(mobj, back, rover, tmx, tmy, linedef); - delta1 = abs(mobj->z - (bottomheight + ((topheight - bottomheight)/2))); - delta2 = abs(thingtop - (bottomheight + ((topheight - bottomheight)/2))); + midheight = (bottomheight + ((topheight - bottomheight) / 2)); + + delta1 = abs(mobj->z - midheight); + delta2 = abs(thingtop - midheight); if (delta1 >= delta2 && !(rover->flags & FF_PLATFORM)) // thing is below FOF { @@ -611,8 +619,10 @@ void P_LineOpening(line_t *linedef, mobj_t *mobj) { const sector_t *polysec = linedef->backsector; - delta1 = abs(mobj->z - (polysec->floorheight + ((polysec->ceilingheight - polysec->floorheight)/2))); - delta2 = abs(thingtop - (polysec->floorheight + ((polysec->ceilingheight - polysec->floorheight)/2))); + const fixed_t polymid = (polysec->floorheight + ((polysec->ceilingheight - polysec->floorheight) / 2)); + + delta1 = abs(mobj->z - polymid); + delta2 = abs(thingtop - polymid); if (polysec->floorheight < lowestceiling && delta1 >= delta2) { @@ -620,7 +630,9 @@ void P_LineOpening(line_t *linedef, mobj_t *mobj) ceilingslope = NULL; } else if (polysec->floorheight < highestceiling && delta1 >= delta2) + { highestceiling = polysec->floorheight; + } if (polysec->ceilingheight > highestfloor && delta1 < delta2) { @@ -628,7 +640,9 @@ void P_LineOpening(line_t *linedef, mobj_t *mobj) floorslope = NULL; } else if (polysec->ceilingheight > lowestfloor && delta1 < delta2) + { lowestfloor = polysec->ceilingheight; + } } if (highestceiling < highceiling) @@ -650,6 +664,43 @@ void P_LineOpening(line_t *linedef, mobj_t *mobj) lowfloor = lowestfloor; } } + else + { + // this is what P_LineOpening did before the addition of slopes + // so i´ll just use it as the fallback case + // not that we will ever likely hit this + frontheight = front->ceilingheight; + backheight = back->ceilingheight; + + if (frontheight < backheight) + { + opentop = frontheight; + highceiling = backheight; + opentopslope = front->c_slope; + } + else + { + opentop = backheight; + highceiling = frontheight; + opentopslope = back->c_slope; + } + + frontheight = front->floorheight; + backheight = back->floorheight; + + if (frontheight > backheight) + { + openbottom = frontheight; + lowfloor = backheight; + openbottomslope = front->f_slope; + } + else + { + openbottom = backheight; + lowfloor = frontheight; + openbottomslope = back->f_slope; + } + } openrange = opentop - openbottom; } @@ -668,7 +719,6 @@ void P_LineOpening(line_t *linedef, mobj_t *mobj) // void P_UnsetThingPosition(mobj_t *thing) { - I_Assert(thing != NULL); I_Assert(!P_MobjWasRemoved(thing)); if (!(thing->flags & MF_NOSECTOR)) @@ -772,7 +822,6 @@ void P_SetThingPosition(mobj_t *thing) sector_t *oldsec = NULL; fixed_t tfloorz, tceilz; - I_Assert(thing != NULL); I_Assert(!P_MobjWasRemoved(thing)); if (thing->player && thing->z <= thing->floorz && thing->subsector) @@ -807,7 +856,7 @@ void P_SetThingPosition(mobj_t *thing) // at sector_t->touching_thinglist) are broken. When a node is // added, new sector links are created. - P_CreateSecNodeList(thing,thing->x,thing->y); + P_CreateSecNodeList(thing, thing->x, thing->y); thing->touching_sectorlist = sector_list; // Attach to Thing's mobj_t sector_list = NULL; // clear for next time } @@ -823,16 +872,20 @@ void P_SetThingPosition(mobj_t *thing) // sector's floor is the same height. if (thing->player && oldsec != NULL && thing->subsector && oldsec != thing->subsector->sector) { - tfloorz = P_GetFloorZ(thing, ss->sector, thing->x, thing->y, NULL); - tceilz = P_GetCeilingZ(thing, ss->sector, thing->x, thing->y, NULL); - if (thing->eflags & MFE_VERTICALFLIP) { + tceilz = P_GetCeilingZ(thing, ss->sector, thing->x, thing->y, NULL); + if (thing->z + thing->height >= tceilz) thing->eflags |= MFE_JUSTSTEPPEDDOWN; } - else if (thing->z <= tfloorz) - thing->eflags |= MFE_JUSTSTEPPEDDOWN; + else + { + tfloorz = P_GetFloorZ(thing, ss->sector, thing->x, thing->y, NULL); + + if (thing->z <= tfloorz) + thing->eflags |= MFE_JUSTSTEPPEDDOWN; + } } } @@ -933,6 +986,10 @@ boolean P_BlockLinesIterator(INT32 x, INT32 y, boolean (*func)(line_t *)) // First index is really empty, so +1 it. for (list = blockmaplump + offset + 1; *list != -1; list++) { +#ifdef RANGECHECK + if (*list < 0 || (UINT32)*list >= numlines) + I_Error("P_BlockLinesIterator: index >= numlines"); +#endif ld = &lines[*list]; if (ld->validcount == validcount) @@ -961,11 +1018,13 @@ boolean P_BlockThingsIterator(INT32 x, INT32 y, boolean (*func)(mobj_t *)) for (mobj = blocklinks[y*bmapwidth + x]; mobj; mobj = bnext) { P_SetTarget(&bnext, mobj->bnext); // We want to note our reference to bnext here incase it is MF_NOTHINK and gets removed! + if (!func(mobj)) { P_SetTarget(&bnext, NULL); return false; } + if (P_MobjWasRemoved(tmthing) // func just popped our tmthing, cannot continue. || (bnext && P_MobjWasRemoved(bnext))) // func just broke blockmap chain, cannot continue. { @@ -973,6 +1032,7 @@ boolean P_BlockThingsIterator(INT32 x, INT32 y, boolean (*func)(mobj_t *)) return true; } } + P_SetTarget(&bnext, NULL); return true; } diff --git a/src/p_mobj.c b/src/p_mobj.c index fcc70ec8b..dbfe3d596 100644 --- a/src/p_mobj.c +++ b/src/p_mobj.c @@ -122,27 +122,6 @@ static void P_CycleMobjState(mobj_t *mobj) } } -// -// P_CycleMobjState for players. -// -static void P_CyclePlayerMobjState(mobj_t *mobj) -{ - // state animations - P_CycleStateAnimation(mobj); - - // cycle through states, - // calling action functions at transitions - if (mobj->tics != -1) - { - mobj->tics--; - - // you can cycle through multiple states in a tic - if (!mobj->tics && mobj->state) - if (!P_SetPlayerMobjState(mobj, mobj->state->nextstate)) - return; // freed itself - } -} - #define MAX_RECURSION 20 // @@ -193,7 +172,7 @@ boolean P_SetPlayerMobjState(mobj_t *mobj, statenum_t state) do { - if (UNLIKELY(state == S_NULL)) + if (state == S_NULL) { // Bad SOC! CONS_Alert(CONS_ERROR, "Cannot remove player mobj by setting its state to S_NULL.\n"); //P_RemoveMobj(mobj); @@ -243,11 +222,6 @@ boolean P_SetMobjState(mobj_t *mobj, statenum_t state) INT32 recursion = 0; -#ifdef PARANOIA - if (mobj->player != NULL) - I_Error("P_SetMobjState used for player mobj. Use P_SetPlayerMobjState instead!\n(State called: %d)", state); -#endif - if (mobj->player != NULL) return P_SetPlayerMobjState(mobj, state); @@ -335,7 +309,7 @@ static boolean P_SetPrecipMobjState(precipmobj_t *mobj, statenum_t state) mobj->tics = st->tics; mobj->sprite = st->sprite; mobj->frame = st->frame; - mobj->anim_duration = (UINT16)st->var2; // only used if FF_ANIMATE is set + //mobj->anim_duration = (UINT16)st->var2; // only used if FF_ANIMATE is set return true; } @@ -360,7 +334,6 @@ void P_ExplodeMissile(mobj_t *mo) { mobj_t *explodemo; - I_Assert(mo != NULL); I_Assert(!P_MobjWasRemoved(mo)); mo->momx = mo->momy = mo->momz = 0; @@ -374,7 +347,7 @@ void P_ExplodeMissile(mobj_t *mo) explodemo = P_SpawnMobj(mo->x, mo->y, mo->z, MT_EXPLODE); - if (explodemo) + if (!P_MobjWasRemovedCompat(explodemo)) { P_SetScale(explodemo, mo->scale); explodemo->destscale = mo->destscale; @@ -385,7 +358,7 @@ void P_ExplodeMissile(mobj_t *mo) explodemo = P_SpawnMobj(mo->x, mo->y, mo->z, MT_EXPLODE); - if (explodemo) + if (!P_MobjWasRemovedCompat(explodemo)) { P_SetScale(explodemo, mo->scale); explodemo->destscale = mo->destscale; @@ -396,7 +369,7 @@ void P_ExplodeMissile(mobj_t *mo) explodemo = P_SpawnMobj(mo->x, mo->y, mo->z, MT_EXPLODE); - if (explodemo) + if (!P_MobjWasRemovedCompat(explodemo)) { P_SetScale(explodemo, mo->scale); explodemo->destscale = mo->destscale; @@ -407,7 +380,7 @@ void P_ExplodeMissile(mobj_t *mo) explodemo = P_SpawnMobj(mo->x, mo->y, mo->z, MT_EXPLODE); - if (explodemo) + if (!P_MobjWasRemovedCompat(explodemo)) { P_SetScale(explodemo, mo->scale); explodemo->destscale = mo->destscale; @@ -441,14 +414,18 @@ boolean P_InsideANonSolidFFloor(mobj_t *mobj, ffloor_t *rover) if (!(rover->flags & FF_EXISTS)) return false; - if ((((rover->flags & FF_BLOCKPLAYER) && mobj->player) - || ((rover->flags & FF_BLOCKOTHERS) && !mobj->player))) + if ((((rover->flags & FF_BLOCKPLAYER) && mobj->player) || + ((rover->flags & FF_BLOCKOTHERS) && !mobj->player))) + return false; + + topheight = P_GetFFloorTopZAt(rover, mobj->x, mobj->y); + + if (mobj->z > topheight) return false; - topheight = P_GetFFloorTopZAt (rover, mobj->x, mobj->y); bottomheight = P_GetFFloorBottomZAt(rover, mobj->x, mobj->y); - if (mobj->z > topheight || (mobj->z + mobj->height < bottomheight)) + if (mobj->z + mobj->height < bottomheight) return false; return true; @@ -598,7 +575,7 @@ fixed_t P_MobjFloorZ(mobj_t *mobj, sector_t *sector, sector_t *boundsec, fixed_t return P_GetSlopeZAt(slope, testx, testy); // If boundsec is set, we're looking for specials. In that case, iterate over every line in this sector to find the TRUE highest/lowest point - if (perfect) + if (perfect && boundsec) { size_t i; line_t *ld; @@ -617,8 +594,10 @@ fixed_t P_MobjFloorZ(mobj_t *mobj, sector_t *sector, sector_t *boundsec, fixed_t fixed_t highline; ld = boundsec->lines[i]; - if (bbox[BOXRIGHT] <= ld->bbox[BOXLEFT] || bbox[BOXLEFT] >= ld->bbox[BOXRIGHT] - || bbox[BOXTOP] <= ld->bbox[BOXBOTTOM] || bbox[BOXBOTTOM] >= ld->bbox[BOXTOP]) + if (bbox[BOXRIGHT] <= ld->bbox[BOXLEFT] || + bbox[BOXLEFT] >= ld->bbox[BOXRIGHT] || + bbox[BOXTOP] <= ld->bbox[BOXBOTTOM] || + bbox[BOXBOTTOM] >= ld->bbox[BOXTOP]) continue; if (P_BoxOnLineSide(bbox, ld) != -1) @@ -685,7 +664,7 @@ fixed_t P_MobjCeilingZ(mobj_t *mobj, sector_t *sector, sector_t *boundsec, fixed return P_GetSlopeZAt(slope, testx, testy); // If boundsec is set, we're looking for specials. In that case, iterate over every line in this sector to find the TRUE highest/lowest point - if (perfect) + if (perfect && boundsec) { size_t i; line_t *ld; @@ -704,8 +683,10 @@ fixed_t P_MobjCeilingZ(mobj_t *mobj, sector_t *sector, sector_t *boundsec, fixed fixed_t highline; ld = boundsec->lines[i]; - if (bbox[BOXRIGHT] <= ld->bbox[BOXLEFT] || bbox[BOXLEFT] >= ld->bbox[BOXRIGHT] - || bbox[BOXTOP] <= ld->bbox[BOXBOTTOM] || bbox[BOXBOTTOM] >= ld->bbox[BOXTOP]) + if (bbox[BOXRIGHT] <= ld->bbox[BOXLEFT] || + bbox[BOXLEFT] >= ld->bbox[BOXRIGHT] || + bbox[BOXTOP] <= ld->bbox[BOXBOTTOM] || + bbox[BOXBOTTOM] >= ld->bbox[BOXTOP]) continue; if (P_BoxOnLineSide(bbox, ld) != -1) @@ -773,7 +754,7 @@ fixed_t P_CameraFloorZ(camera_t *mobj, sector_t *sector, sector_t *boundsec, fix return P_GetSlopeZAt(slope, testx, testy); // If boundsec is set, we're looking for specials. In that case, iterate over every line in this sector to find the TRUE highest/lowest point - if (perfect) + if (perfect && boundsec) { size_t i; line_t *ld; @@ -792,8 +773,10 @@ fixed_t P_CameraFloorZ(camera_t *mobj, sector_t *sector, sector_t *boundsec, fix fixed_t highline; ld = boundsec->lines[i]; - if (bbox[BOXRIGHT] <= ld->bbox[BOXLEFT] || bbox[BOXLEFT] >= ld->bbox[BOXRIGHT] - || bbox[BOXTOP] <= ld->bbox[BOXBOTTOM] || bbox[BOXBOTTOM] >= ld->bbox[BOXTOP]) + if (bbox[BOXRIGHT] <= ld->bbox[BOXLEFT] || + bbox[BOXLEFT] >= ld->bbox[BOXRIGHT] || + bbox[BOXTOP] <= ld->bbox[BOXBOTTOM] || + bbox[BOXBOTTOM] >= ld->bbox[BOXTOP]) continue; if (P_BoxOnLineSide(bbox, ld) != -1) @@ -860,7 +843,7 @@ fixed_t P_CameraCeilingZ(camera_t *mobj, sector_t *sector, sector_t *boundsec, f return P_GetSlopeZAt(slope, testx, testy); // If boundsec is set, we're looking for specials. In that case, iterate over every line in this sector to find the TRUE highest/lowest point - if (perfect) + if (perfect && boundsec) { size_t i; line_t *ld; @@ -879,8 +862,10 @@ fixed_t P_CameraCeilingZ(camera_t *mobj, sector_t *sector, sector_t *boundsec, f fixed_t highline; ld = boundsec->lines[i]; - if (bbox[BOXRIGHT] <= ld->bbox[BOXLEFT] || bbox[BOXLEFT] >= ld->bbox[BOXRIGHT] - || bbox[BOXTOP] <= ld->bbox[BOXBOTTOM] || bbox[BOXBOTTOM] >= ld->bbox[BOXTOP]) + if (bbox[BOXRIGHT] <= ld->bbox[BOXLEFT] || + bbox[BOXLEFT] >= ld->bbox[BOXRIGHT] || + bbox[BOXTOP] <= ld->bbox[BOXBOTTOM] || + bbox[BOXBOTTOM] >= ld->bbox[BOXTOP]) continue; if (P_BoxOnLineSide(bbox, ld) != -1) @@ -911,6 +896,7 @@ fixed_t P_CameraCeilingZ(camera_t *mobj, sector_t *sector, sector_t *boundsec, f else // Well, that makes it easy. Just get the ceiling height return sector->ceilingheight; } + static void P_PlayerFlip(mobj_t *mo) { if (!mo->player) @@ -919,7 +905,7 @@ static void P_PlayerFlip(mobj_t *mo) G_GhostAddFlip((INT32) (mo->player - players)); // Flip aiming to match! - if (UNLIKELY(mo->player->pflags & PF_NIGHTSMODE)) // NiGHTS doesn't use flipcam + if (nightsplayer(mo->player)) // NiGHTS doesn't use flipcam { if (mo->tracer) mo->tracer->eflags ^= MFE_VERTICALFLIP; @@ -961,7 +947,6 @@ fixed_t P_GetMobjGravity(mobj_t *mo) boolean goopgravity = false; boolean wasflip; - I_Assert(mo != NULL); I_Assert(!P_MobjWasRemoved(mo)); wasflip = (mo->eflags & MFE_VERTICALFLIP) != 0; @@ -984,8 +969,7 @@ fixed_t P_GetMobjGravity(mobj_t *mo) if (!(rover->master->frontsector->gravity)) continue; - gravityadd = -FixedMul(gravity, - (FixedDiv(*rover->master->frontsector->gravity>>FRACBITS, 1000))); + gravityadd = -P_GetSectorGravity(rover->master->frontsector); if (rover->master->frontsector->verticalflip && gravityadd > 0) mo->eflags |= MFE_VERTICALFLIP; @@ -997,11 +981,7 @@ fixed_t P_GetMobjGravity(mobj_t *mo) if (no3dfloorgrav) { - if (mo->subsector->sector->gravity) - gravityadd = -FixedMul(gravity, - (FixedDiv(*mo->subsector->sector->gravity>>FRACBITS, 1000))); - else - gravityadd = -gravity; + gravityadd = -P_GetSectorGravity(mo->subsector->sector); if (mo->subsector->sector->verticalflip && gravityadd > 0) mo->eflags |= MFE_VERTICALFLIP; @@ -1013,7 +993,7 @@ fixed_t P_GetMobjGravity(mobj_t *mo) if (mo->player) { - if (UNLIKELY(mo->player->climbing || (mo->player->pflags & PF_NIGHTSMODE))) + if (UNLIKELY(mo->player->climbing || nightsplayer(mo->player))) return 0; if (!(mo->flags2 & MF2_OBJECTFLIP) != !(mo->player->powers[pw_gravityboots])) // negated to turn numeric into bool - would be double negated, but not needed if both would be @@ -1021,8 +1001,10 @@ fixed_t P_GetMobjGravity(mobj_t *mo) gravityadd = -gravityadd; mo->eflags ^= MFE_VERTICALFLIP; } + if (wasflip == !(mo->eflags & MFE_VERTICALFLIP)) // note!! == ! is not equivalent to != here - turns numeric into bool this way P_PlayerFlip(mo); + if (mo->player->kartstuff[k_pogospring]) gravityadd = (5*gravityadd)/2; } @@ -1032,12 +1014,17 @@ fixed_t P_GetMobjGravity(mobj_t *mo) if (mo->flags2 & MF2_OBJECTFLIP) { mo->eflags |= MFE_VERTICALFLIP; + if (mo->z + mo->height >= mo->ceilingz) + { gravityadd = 0; + } else if (gravityadd < 0) // Don't sink, only rise up - gravityadd *= -1; + { + gravityadd = -gravityadd; + } } - else //Otherwise, sort through the other exceptions. + else // Otherwise, sort through the other exceptions. { switch (mo->type) { @@ -1098,7 +1085,9 @@ fixed_t P_GetMobjGravity(mobj_t *mo) // Goop has slower, reversed gravity if (goopgravity) + { gravityadd = -gravityadd/5; + } gravityadd = FixedMul(gravityadd, mo->scale); @@ -1134,13 +1123,10 @@ void P_CheckGravity(mobj_t *mo, boolean affect) // static void P_SceneryXYFriction(mobj_t *mo, fixed_t oldx, fixed_t oldy) { - I_Assert(mo != NULL); I_Assert(!P_MobjWasRemoved(mo)); - const fixed_t fric_scale = FixedMul(FRACUNIT/32, mo->scale); - - if (abs(mo->momx) < fric_scale - && abs(mo->momy) < fric_scale) + if (abs(mo->momx) < FixedMul(FRACUNIT/32, mo->scale) + && abs(mo->momy) < FixedMul(FRACUNIT/32, mo->scale)) { mo->momx = 0; mo->momy = 0; @@ -1178,7 +1164,6 @@ static void P_XYFriction(mobj_t *mo, fixed_t oldx, fixed_t oldy) { player_t *player; - I_Assert(mo != NULL); I_Assert(!P_MobjWasRemoved(mo)); player = mo->player; @@ -1194,13 +1179,16 @@ static void P_XYFriction(mobj_t *mo, fixed_t oldx, fixed_t oldy) } else if (abs(player->rmomx) < mo->scale && abs(player->rmomy) < mo->scale - && (!(player->cmd.forwardmove && !(twodlevel || mo->flags2 & MF2_TWOD)) && !player->cmd.sidemove && !(player->pflags & PF_SPINNING)) + && (!(player->cmd.forwardmove && !twodmo(mo)) && !player->cmd.sidemove && !(player->pflags & PF_SPINNING)) && !(player->mo->standingslope && (!(player->mo->standingslope->flags & SL_NOPHYSICS)) && (abs(player->mo->standingslope->zdelta) >= FRACUNIT/2)) ) { // if in a walking frame, stop moving if (player->panim == PA_WALK && player->kartstuff[k_spinouttimer] == 0) + { P_SetPlayerMobjState(mo, S_KART_STND1); // SRB2kart - was S_PLAY_STND + } + mo->momx = player->cmomx; mo->momy = player->cmomy; } @@ -1221,7 +1209,9 @@ static void P_XYFriction(mobj_t *mo, fixed_t oldx, fixed_t oldy) } } else + { P_SceneryXYFriction(mo, oldx, oldy); + } } static void P_PushableCheckBustables(mobj_t *mo) @@ -1230,7 +1220,6 @@ static void P_PushableCheckBustables(mobj_t *mo) fixed_t oldx; fixed_t oldy; - I_Assert(mo != NULL); I_Assert(!P_MobjWasRemoved(mo)); if (netgame && mo->player && mo->player->spectator) @@ -1246,15 +1235,15 @@ static void P_PushableCheckBustables(mobj_t *mo) for (node = mo->touching_sectorlist; node; node = node->m_sectorlist_next) { + ffloor_t *rover; + fixed_t topheight, bottomheight; + if (!node->m_sector) break; if (!node->m_sector->ffloors) continue; - ffloor_t *rover; - fixed_t topheight, bottomheight; - for (rover = node->m_sector->ffloors; rover; rover = rover->next) { if (!(rover->flags & FF_EXISTS) || !(rover->flags & FF_BUSTUP)) @@ -1267,7 +1256,6 @@ static void P_PushableCheckBustables(mobj_t *mo) if (rover->master->frontsector->crumblestate) continue; - topheight = P_GetFOFTopZ(mo, node->m_sector, rover, mo->x, mo->y, NULL); bottomheight = P_GetFOFBottomZ(mo, node->m_sector, rover, mo->x, mo->y, NULL); // Height checks @@ -1279,29 +1267,34 @@ static void P_PushableCheckBustables(mobj_t *mo) if (mo->z+mo->height > bottomheight) continue; } - else if (rover->flags & FF_SPINBUST) - { - if (mo->z+mo->momz > topheight) - continue; - - if (mo->z+mo->height < bottomheight) - continue; - } - else if (rover->flags & FF_SHATTER) - { - if (mo->z+mo->momz > topheight) - continue; - - if (mo->z+mo->momz + mo->height < bottomheight) - continue; - } else { - if (mo->z >= topheight) - continue; + topheight = P_GetFOFTopZ(mo, node->m_sector, rover, mo->x, mo->y, NULL); - if (mo->z+mo->height < bottomheight) - continue; + if (rover->flags & FF_SPINBUST) + { + if (mo->z+mo->momz > topheight) + continue; + + if (mo->z+mo->height < bottomheight) + continue; + } + else if (rover->flags & FF_SHATTER) + { + if (mo->z+mo->momz > topheight) + continue; + + if (mo->z+mo->momz + mo->height < bottomheight) + continue; + } + else + { + if (mo->z >= topheight) + continue; + + if (mo->z+mo->height < bottomheight) + continue; + } } EV_CrumbleChain(node->m_sector, rover); @@ -1336,6 +1329,29 @@ static boolean P_CheckSkyHit(mobj_t *mo) return false; } +// +// P_SkullFlyReset +// +// Resets the Skull Fly to its spawn state after it collides with something. +// +static boolean P_SkullFlyReset(mobj_t *mo) +{ + if (!mo->momx && !mo->momy && (mo->flags2 & MF2_SKULLFLY)) + { + // the skull slammed into something + mo->flags2 &= ~MF2_SKULLFLY; + mo->momx = mo->momy = mo->momz = 0; + + // set in 'search new direction' state? + if (mo->type != MT_EGGMOBILE) + P_SetMobjState(mo, mo->info->spawnstate); + + return true; + } + + return false; +} + // // P_XYMovement // @@ -1349,27 +1365,15 @@ void P_XYMovement(mobj_t *mo) vector3_t slopemom = {0, 0, 0}; fixed_t predictedz = 0; - I_Assert(mo != NULL); I_Assert(!P_MobjWasRemoved(mo)); // if it's stopped - if (!mo->momx && !mo->momy) + if (P_SkullFlyReset(mo)) { - if (mo->flags2 & MF2_SKULLFLY) - { - // the skull slammed into something - mo->flags2 &= ~MF2_SKULLFLY; - mo->momx = mo->momy = mo->momz = 0; - - // set in 'search new direction' state? - if (mo->type != MT_EGGMOBILE) - P_SetMobjState(mo, mo->info->spawnstate); - - return; - } + return; } - player = mo->player; //valid only if player avatar + player = mo->player; // valid only if player avatar xmove = mo->momx; ymove = mo->momy; @@ -1427,12 +1431,14 @@ void P_XYMovement(mobj_t *mo) } } //} - if (!P_TryMove(mo, mo->x + xmove, mo->y + ymove, true) && !(mo->eflags & MFE_SPRUNG)) + + if (!P_TryMove(mo, mo->x + xmove, mo->y + ymove, true) + && !(P_MobjWasRemovedCompat(mo) || mo->eflags & MFE_SPRUNG)) { // blocked move moved = false; - if (player && player->bot) + if (UNLIKELY(player && player->bot)) { B_MoveBlocked(player); } @@ -1467,24 +1473,24 @@ void P_XYMovement(mobj_t *mo) else fx->eflags &= ~MFE_VERTICALFLIP; fx->scale = mo->scale; - } - if (mo->type == MT_ORBINAUT) // Orbinaut speed decreasing - { - if (mo->health > 1) + if (mo->type == MT_ORBINAUT) // Orbinaut speed decreasing { - S_StartSound(mo, mo->info->attacksound); - mo->health--; - mo->threshold = 0; - } - else if (mo->health == 1) - { - // This Item Damage - S_StartSound(mo, mo->info->deathsound); - P_KillMobj(mo, NULL, NULL); + if (mo->health > 1) + { + S_StartSound(mo, mo->info->attacksound); + mo->health--; + mo->threshold = 0; + } + else if (mo->health == 1) + { + // This Item Damage + S_StartSound(mo, mo->info->deathsound); + P_KillMobj(mo, NULL, NULL); - P_SetObjectMomZ(mo, 8*FRACUNIT, false); - P_InstaThrust(mo, R_PointToAngle2(mo->x, mo->y, mo->x, mo->y)+ANGLE_90, 16*FRACUNIT); + P_SetObjectMomZ(mo, 8*FRACUNIT, false); + P_InstaThrust(mo, R_PointToAngle2(mo->x, mo->y, mo->x, mo->y)+ANGLE_90, 16*FRACUNIT); + } } } //} @@ -1553,29 +1559,6 @@ void P_XYMovement(mobj_t *mo) return; } - // draw damage on wall - //SPLAT TEST ---------------------------------------------------------- -#ifdef WALLSPLATS - if (blockingline && mo->type != MT_REDRING && mo->type != MT_FIREBALL - && !(mo->flags2 & (MF2_AUTOMATIC|MF2_RAILRING|MF2_BOUNCERING|MF2_EXPLOSION|MF2_SCATTER))) - // set by last P_TryMove() that failed - { - divline_t divl; - divline_t misl; - fixed_t frac; - - P_MakeDivline(blockingline, &divl); - misl.x = mo->x; - misl.y = mo->y; - misl.dx = mo->momx; - misl.dy = mo->momy; - frac = P_InterceptVector(&divl, &misl); - R_AddWallSplat(blockingline, P_PointOnLineSide(mo->x,mo->y,blockingline), - "A_DMG3", mo->z, frac, SPLATDRAWMODE_SHADE); - } -#endif - // --------------------------------------------------------- SPLAT TEST - P_ExplodeMissile(mo); return; } @@ -1588,50 +1571,53 @@ void P_XYMovement(mobj_t *mo) if (P_MobjWasRemoved(mo)) // MF_SPECIAL touched a player! O_o;; return; - if (moved && oldslope) // Check to see if we ran off + if (moved) { - if (oldslope != mo->standingslope) // First, compare different slopes + if (oldslope) // Check to see if we ran off { - angle_t oldangle, newangle; - angle_t moveangle = R_PointToAngle2(0, 0, mo->momx, mo->momy); + if (oldslope != mo->standingslope) // First, compare different slopes + { + angle_t oldangle, newangle; + angle_t moveangle = R_PointToAngle2(0, 0, mo->momx, mo->momy); - oldangle = FixedMul((signed)oldslope->zangle, FINECOSINE((moveangle - oldslope->xydirection) >> ANGLETOFINESHIFT)); + oldangle = FixedMul((signed)oldslope->zangle, FINECOSINE((moveangle - oldslope->xydirection) >> ANGLETOFINESHIFT)); - if (mo->standingslope) - newangle = FixedMul((signed)mo->standingslope->zangle, FINECOSINE((moveangle - mo->standingslope->xydirection) >> ANGLETOFINESHIFT)); - else - newangle = 0; + if (mo->standingslope) + newangle = FixedMul((signed)mo->standingslope->zangle, FINECOSINE((moveangle - mo->standingslope->xydirection) >> ANGLETOFINESHIFT)); + else + newangle = 0; - // Now compare the Zs of the different quantizations - if (oldangle-newangle > ANG30 && oldangle-newangle < ANGLE_180) // Allow for a bit of sticking - this value can be adjusted later + // Now compare the Zs of the different quantizations + if (oldangle-newangle > ANG30 && oldangle-newangle < ANGLE_180) // Allow for a bit of sticking - this value can be adjusted later + { + mo->standingslope = oldslope; + P_SlopeLaunch(mo); + } + } + else if (predictedz-mo->z > abs(slopemom.z/2) // Sryder 2018-11-26: Don't launch here if it's a slope without physics, we stick to those like glue anyway + && !(mo->standingslope->flags & SL_NOPHYSICS)) // Now check if we were supposed to stick to this slope { - mo->standingslope = oldslope; P_SlopeLaunch(mo); } } - else if (predictedz-mo->z > abs(slopemom.z/2) // Sryder 2018-11-26: Don't launch here if it's a slope without physics, we stick to those like glue anyway - && !(mo->standingslope->flags & SL_NOPHYSICS)) // Now check if we were supposed to stick to this slope + else if (mo->standingslope && predictedz) { - P_SlopeLaunch(mo); - } - } - else if (moved && mo->standingslope && predictedz) - { - angle_t moveangle = R_PointToAngle2(0, 0, mo->momx, mo->momy); - angle_t newangle = FixedMul((signed)mo->standingslope->zangle, FINECOSINE((moveangle - mo->standingslope->xydirection) >> ANGLETOFINESHIFT)); + angle_t moveangle = R_PointToAngle2(0, 0, mo->momx, mo->momy); + angle_t newangle = FixedMul((signed)mo->standingslope->zangle, FINECOSINE((moveangle - mo->standingslope->xydirection) >> ANGLETOFINESHIFT)); - if (ANGLE_MAX-newangle > ANG30 && newangle > ANGLE_180) - { - mo->momz = P_MobjFlip(mo)*FRACUNIT/2; - mo->z = predictedz + P_MobjFlip(mo); - mo->standingslope = NULL; + if (ANGLE_MAX-newangle > ANG30 && newangle > ANGLE_180) + { + mo->momz = P_MobjFlip(mo)*FRACUNIT/2; + mo->z = predictedz + P_MobjFlip(mo); + mo->standingslope = NULL; + } } } // Check the gravity status. P_CheckGravity(mo, false); - if (UNLIKELY(player && !moved && player->pflags & PF_NIGHTSMODE && mo->target)) + if (player && !moved && nightsplayer(player) && mo->target) { angle_t fa; @@ -1670,19 +1656,6 @@ void P_XYMovement(mobj_t *mo) if (mo->flags & MF_NOCLIPHEIGHT) return; // no frictions for objects that can pass through floors - if (mo->flags & MF_MISSILE || mo->flags2 & MF2_SKULLFLY || mo->type == MT_SHELL || mo->type == MT_VULTURE) - return; // no friction for missiles ever - - if (player && player->homing) // no friction for homing - return; - - if (UNLIKELY(player && player->pflags & PF_NIGHTSMODE)) - return; // no friction for NiGHTS players - - if ((mo->type == MT_BIGTUMBLEWEED || mo->type == MT_LITTLETUMBLEWEED) - && (mo->standingslope && abs(mo->standingslope->zdelta) > FRACUNIT>>8)) // Special exception for tumbleweeds on slopes - return; - //{ SRB2kart stuff if (mo->type == MT_ORBINAUT || mo->type == MT_JAWZ_DUD || mo->type == MT_JAWZ || mo->type == MT_BALLHOG) //(mo->type == MT_JAWZ && !mo->tracer)) return; @@ -1691,6 +1664,22 @@ void P_XYMovement(mobj_t *mo) return; //} + if (mo->flags & MF_MISSILE || mo->flags2 & MF2_SKULLFLY || mo->type == MT_SHELL || mo->type == MT_VULTURE) + return; // no friction for missiles ever + + if (player) + { + if (player->homing) // no friction for homing + return; + + if (nightsplayer(player)) + return; // no friction for NiGHTS players + } + + if ((mo->type == MT_BIGTUMBLEWEED || mo->type == MT_LITTLETUMBLEWEED) + && (mo->standingslope && abs(mo->standingslope->zdelta) > FRACUNIT>>8)) // Special exception for tumbleweeds on slopes + return; + if (((!(mo->eflags & MFE_VERTICALFLIP) && mo->z > mo->floorz) || (mo->eflags & MFE_VERTICALFLIP && mo->z+mo->height < mo->ceilingz)) && !(player && player->pflags & PF_SLIDING)) return; // no friction when airborne @@ -1700,7 +1689,6 @@ void P_XYMovement(mobj_t *mo) static void P_RingXYMovement(mobj_t *mo) { - I_Assert(mo != NULL); I_Assert(!P_MobjWasRemoved(mo)); if (!P_SceneryTryMove(mo, mo->x + mo->momx, mo->y + mo->momy)) @@ -1711,7 +1699,6 @@ static void P_SceneryXYMovement(mobj_t *mo) { fixed_t oldx, oldy; // reducing bobbing/momentum on ice when up against walls - I_Assert(mo != NULL); I_Assert(!P_MobjWasRemoved(mo)); oldx = mo->x; @@ -1720,6 +1707,9 @@ static void P_SceneryXYMovement(mobj_t *mo) if (!P_SceneryTryMove(mo, mo->x + mo->momx, mo->y + mo->momy)) P_SlideMove(mo, false); + if (P_MobjWasRemovedCompat(mo)) + return; + if ((!(mo->eflags & MFE_VERTICALFLIP) && mo->z > mo->floorz) || (mo->eflags & MFE_VERTICALFLIP && mo->z+mo->height < mo->ceilingz)) return; // no friction when airborne @@ -1747,9 +1737,8 @@ static void P_AdjustMobjFloorZ_FFloors(mobj_t *mo, sector_t *sector, UINT8 motyp { ffloor_t *rover; fixed_t delta1, delta2, thingtop; - fixed_t topheight, bottomheight; + fixed_t topheight, bottomheight, midheight; - I_Assert(mo != NULL); I_Assert(!P_MobjWasRemoved(mo)); thingtop = mo->z + mo->height; @@ -1793,18 +1782,19 @@ static void P_AdjustMobjFloorZ_FFloors(mobj_t *mo, sector_t *sector, UINT8 motyp } } - const fixed_t mid = (bottomheight + ((topheight - bottomheight) / 2)); + midheight = (bottomheight + ((topheight - bottomheight) / 2)); - delta1 = abs(mo->z - mid); - delta2 = abs(thingtop - mid); + delta1 = abs(mo->z - midheight); + delta2 = abs(thingtop - midheight); - if (topheight > mo->floorz && delta1 < delta2 + if (topheight > mo->floorz && (delta1 < delta2) && !(rover->flags & FF_REVERSEPLATFORM) && ((P_MobjFlip(mo)*mo->momz >= 0) || (!(rover->flags & FF_PLATFORM)))) // In reverse gravity, only clip for FOFs that are intangible from their bottom (the "top" you're falling through) if you're coming from above ("below" in your frame of reference) { mo->floorz = topheight; } - if (bottomheight < mo->ceilingz && delta1 >= delta2 + + if (bottomheight < mo->ceilingz && (delta1 >= delta2) && !(rover->flags & FF_PLATFORM) && ((P_MobjFlip(mo)*mo->momz >= 0) || (!(rover->flags & FF_REVERSEPLATFORM)))) // In normal gravity, only clip for FOFs that are intangible from the top if you're coming from below { @@ -1824,9 +1814,8 @@ static void P_AdjustMobjFloorZ_PolyObjs(mobj_t *mo, subsector_t *subsec) polyobj_t *po = subsec->polyList; sector_t *polysec; fixed_t delta1, delta2, thingtop; - fixed_t polytop, polybottom; + fixed_t polytop, polybottom, polymid; - I_Assert(mo != NULL); I_Assert(!P_MobjWasRemoved(mo)); thingtop = mo->z + mo->height; @@ -1853,15 +1842,15 @@ static void P_AdjustMobjFloorZ_PolyObjs(mobj_t *mo, subsector_t *subsec) polybottom = INT32_MIN; } - const fixed_t mid = polybottom + ((polytop - polybottom) / 2); + polymid = (polybottom + ((polytop - polybottom) / 2)); - delta1 = abs(mo->z - mid); - delta2 = abs(thingtop - mid); + delta1 = abs(mo->z - polymid); + delta2 = abs(thingtop - polymid); - if (polytop > mo->floorz && delta1 < delta2) + if (polytop > mo->floorz && (delta1 < delta2)) mo->floorz = polytop; - if (polybottom < mo->ceilingz && delta1 >= delta2) + if (polybottom < mo->ceilingz && (delta1 >= delta2)) mo->ceilingz = polybottom; po = (polyobj_t *)(po->link.next); @@ -1870,7 +1859,6 @@ static void P_AdjustMobjFloorZ_PolyObjs(mobj_t *mo, subsector_t *subsec) static void P_RingZMovement(mobj_t *mo) { - I_Assert(mo != NULL); I_Assert(!P_MobjWasRemoved(mo)); // Intercept the stupid 'fall through 3dfloors' bug @@ -1905,30 +1893,37 @@ static void P_RingZMovement(mobj_t *mo) boolean P_CheckDeathPitCollide(mobj_t *mo) { - I_Assert(mo != NULL); I_Assert(!P_MobjWasRemoved(mo)); const INT32 secspecial = GETSECSPECIAL(mo->subsector->sector->special, 1); - if (((mo->z <= mo->subsector->sector->floorheight - && !(mo->eflags & MFE_VERTICALFLIP) && (mo->subsector->sector->flags & SF_FLIPSPECIAL_FLOOR)) - || (mo->z + mo->height >= mo->subsector->sector->ceilingheight - && (mo->eflags & MFE_VERTICALFLIP) && (mo->subsector->sector->flags & SF_FLIPSPECIAL_CEILING))) - && (secspecial == 6 || secspecial == 7)) - return true; + // Death Pit + if (secspecial == 6 || secspecial == 7) + { + const boolean flipped = (mo->eflags & MFE_VERTICALFLIP); + + if (!flipped && (mo->subsector->sector->flags & SF_FLIPSPECIAL_FLOOR)) + return (mo->z <= mo->subsector->sector->floorheight); + + if (flipped && (mo->subsector->sector->flags & SF_FLIPSPECIAL_CEILING)) + return (mo->z + mo->height >= mo->subsector->sector->ceilingheight); + } return false; } boolean P_CheckSolidLava(mobj_t *mo, ffloor_t *rover) { - I_Assert(mo != NULL); I_Assert(!P_MobjWasRemoved(mo)); - if (rover->flags & FF_SWIMMABLE && GETSECSPECIAL(rover->master->frontsector->special, 1) == 3 - && !(rover->master->flags & ML_BLOCKMONSTERS) - && ((rover->master->flags & ML_EFFECT3) || mo->z-mo->momz > P_GetFFloorTopZAt(rover, mo->x, mo->y) - FixedMul(16*FRACUNIT, mo->scale))) + if (rover->flags & FF_SWIMMABLE && GETSECSPECIAL(rover->master->frontsector->special, 1) == 3) + { + if (!(rover->master->flags & ML_BLOCKMONSTERS) && + ((rover->master->flags & ML_EFFECT3) || mo->z-mo->momz > P_GetFFloorTopZAt(rover, mo->x, mo->y) - FixedMul(16*FRACUNIT, mo->scale))) + { return true; + } + } return false; } @@ -1941,7 +1936,6 @@ static boolean P_ZMovement(mobj_t *mo) { fixed_t dist, delta; - I_Assert(mo != NULL); I_Assert(!P_MobjWasRemoved(mo)); // Intercept the stupid 'fall through 3dfloors' bug @@ -2138,13 +2132,12 @@ static boolean P_ZMovement(mobj_t *mo) if (mo->type == MT_JETJAW && mo->z + mo->height > mo->watertop) mo->z = mo->watertop - mo->height; } - } // clip movement if (((mo->z <= mo->floorz && !(mo->eflags & MFE_VERTICALFLIP)) || (mo->z + mo->height >= mo->ceilingz && mo->eflags & MFE_VERTICALFLIP)) - && !(mo->flags & MF_NOCLIPHEIGHT)) + && !(mo->flags & MF_NOCLIPHEIGHT)) { vector3_t mom; mom.x = mo->momx; @@ -2163,6 +2156,10 @@ static boolean P_ZMovement(mobj_t *mo) } P_CheckPosition(mo, mo->x, mo->y); // Sets mo->standingslope correctly + + if (P_MobjWasRemovedCompat(mo)) // mobjs can be removed by P_CheckPosition -- Monster Iestyn 31/07/21 + return false; + if (((mo->eflags & MFE_VERTICALFLIP) ? tmceilingslope : tmfloorslope) && (mo->type != MT_STEAM)) { mo->standingslope = (mo->eflags & MFE_VERTICALFLIP) ? tmceilingslope : tmfloorslope; @@ -2200,6 +2197,7 @@ static boolean P_ZMovement(mobj_t *mo) // Otherwise bounce up at half speed. else mom.z = -mom.z/2; + S_StartSound(mo, mo->info->activesound); } } @@ -2241,7 +2239,7 @@ static boolean P_ZMovement(mobj_t *mo) || mo->type == MT_CANNONBALLDECOR || mo->type == MT_FALLINGROCK) { - if (UNLIKELY(maptol & TOL_NIGHTS)) + if (nightsmode) mom.z = -FixedDiv(mom.z, 10*FRACUNIT); else mom.z = -FixedMul(mom.z, FixedDiv(17*FRACUNIT,20*FRACUNIT)); @@ -2317,7 +2315,9 @@ static boolean P_ZMovement(mobj_t *mo) || tmfloorthing->flags2 & MF2_STANDONME || tmfloorthing->type == MT_PLAYER)) mom.z = tmfloorthing->momz; - if (mo->standingslope) { // MT_STEAM will never have a standingslope, see above. + // MT_STEAM will never have a standingslope, see above. + if (mo->standingslope) + { P_QuantizeMomentumToSlope(&mom, mo->standingslope); } @@ -2338,7 +2338,7 @@ static boolean P_ZMovement(mobj_t *mo) if (((mo->z + mo->height > mo->ceilingz && !(mo->eflags & MFE_VERTICALFLIP)) || (mo->z < mo->floorz && mo->eflags & MFE_VERTICALFLIP)) - && !(mo->flags & MF_NOCLIPHEIGHT)) + && !(mo->flags & MF_NOCLIPHEIGHT)) { if (mo->eflags & MFE_VERTICALFLIP) mo->z = mo->floorz; @@ -2379,11 +2379,9 @@ static boolean P_ZMovement(mobj_t *mo) { if (mo->flags2 & MF2_SKULLFLY) // the skull slammed into something mo->momz = -mo->momz; - else - // Flags bounce - if (UNLIKELY(mo->type == MT_REDFLAG || mo->type == MT_BLUEFLAG)) + else if (UNLIKELY(mo->type == MT_REDFLAG || mo->type == MT_BLUEFLAG)) // Flags bounce { - if (UNLIKELY(maptol & TOL_NIGHTS)) + if (nightsmode) mo->momz = -FixedDiv(mo->momz, 10*FRACUNIT); else mo->momz = -FixedMul(mo->momz, FixedDiv(17*FRACUNIT,20*FRACUNIT)); @@ -2396,9 +2394,105 @@ static boolean P_ZMovement(mobj_t *mo) return true; } +// Check for "Mario" blocks to hit and bounce them +static void P_CheckMarioBlocks(mobj_t *mo) +{ + msecnode_t *node; + + // Only let the player punch + if (netgame && mo->player->spectator) + return; + + // Search the touching sectors, from side-to-side... + for (node = mo->touching_sectorlist; node; node = node->m_sectorlist_next) + { + ffloor_t *rover; + + if (!node->m_sector->ffloors) + continue; + + for (rover = node->m_sector->ffloors; rover; rover = rover->next) + { + if (!(rover->flags & FF_EXISTS)) + continue; + + // Come on, it's time to go... + if (!(rover->flags & FF_MARIO)) + continue; + + if (mo->eflags & MFE_VERTICALFLIP) + continue; // if you were flipped, your head isn't actually hitting your ceilingz is it? + + if (*rover->bottomheight != mo->ceilingz) + continue; // The player's head hit the bottom! + + // DO THE MARIO! + EV_MarioBlock(rover->master->frontsector, node->m_sector, *rover->topheight, mo); + } + } // Ugly ugly billions of braces! Argh! +} + +// Check if we're on a polyobject that triggers a linedef executor. +static boolean P_PlayerPolyObjectZMovement(mobj_t *mo) +{ + msecnode_t *node; + boolean stopmovecut = false; + + // no polyobjects on the map + if (!numPolyObjects) + { + return false; + } + + for (node = mo->touching_sectorlist; node; node = node->m_sectorlist_next) + { + sector_t *sec = node->m_sector; + subsector_t *newsubsec; + size_t i; + + for (i = 0; i < numsubsectors; i++) + { + polyobj_t *po; + sector_t *polysec; + newsubsec = &subsectors[i]; + + if (newsubsec->sector != sec) + continue; + + for (po = newsubsec->polyList; po; po = (polyobj_t *)(po->link.next)) + { + if (!(po->flags & POF_SOLID)) + continue; + + if (!P_MobjInsidePolyobj(po, mo)) + continue; + + // We're inside it! Yess... + polysec = po->lines[0]->backsector; + + // Moving polyobjects should act like conveyors if the player lands on one. (I.E. none of the momentum cut thing below) -Red + if ((mo->z == polysec->ceilingheight || mo->z + mo->height == polysec->floorheight) && po->thinker) + stopmovecut = true; + + if (!(po->flags & POF_LDEXEC)) + continue; + + if (mo->z != polysec->ceilingheight) + continue; + + // We're landing on a PO, so check for + // a linedef executor. + // Trigger tags are 32000 + the PO's ID number. + P_LinedefExecute((INT16)(32000 + po->id), mo, NULL); + } + } + } + + return stopmovecut; +} + static void P_PlayerZMovement(mobj_t *mo) { - I_Assert(mo != NULL); I_Assert(!P_MobjWasRemoved(mo)); if (!mo->player) @@ -2430,8 +2524,8 @@ static void P_PlayerZMovement(mobj_t *mo) mo->z += mo->momz; // Have player fall through floor? - if (mo->player->playerstate == PST_DEAD - || mo->player->playerstate == PST_REBORN) + if (mo->player->playerstate == PST_DEAD || + mo->player->playerstate == PST_REBORN) return; if (mo->standingslope) @@ -2446,15 +2540,21 @@ static void P_PlayerZMovement(mobj_t *mo) if (P_IsObjectOnGround(mo) && !(mo->flags & MF_NOCLIPHEIGHT)) { if (mo->eflags & MFE_VERTICALFLIP) - mo->z = mo->ceilingz - mo->height; - else - mo->z = mo->floorz; - - if (UNLIKELY(mo->player->pflags & PF_NIGHTSMODE)) { + mo->z = mo->ceilingz - mo->height; + } + else + { + mo->z = mo->floorz; + } + + if (nightsplayer(mo->player)) + { + const boolean flipped = (mo->eflags & MFE_VERTICALFLIP); + // bounce off floor if you were flying towards it - if ((mo->eflags & MFE_VERTICALFLIP && mo->player->flyangle > 0 && mo->player->flyangle < 180) - || (!(mo->eflags & MFE_VERTICALFLIP) && mo->player->flyangle > 180 && mo->player->flyangle <= 359)) + if ((flipped && mo->player->flyangle > 0 && mo->player->flyangle < 180) || + (!flipped && mo->player->flyangle > 180 && mo->player->flyangle <= 359)) { if (mo->player->flyangle < 90 || mo->player->flyangle >= 270) mo->player->flyangle += P_MobjFlip(mo)*90; @@ -2462,19 +2562,26 @@ static void P_PlayerZMovement(mobj_t *mo) mo->player->flyangle -= P_MobjFlip(mo)*90; mo->player->speed = FixedMul(mo->player->speed, 4*FRACUNIT/5); } + goto nightsdone; } + // Get up if you fell. if ((mo->state == &states[mo->info->painstate] || mo->state == &states[S_KART_SPIN]) && mo->player->kartstuff[k_spinouttimer] == 0 && mo->player->kartstuff[k_squishedtimer] == 0) // SRB2kart + { P_SetPlayerMobjState(mo, S_KART_STND1); + } - if (!mo->standingslope && (mo->eflags & MFE_VERTICALFLIP ? tmceilingslope : tmfloorslope)) { +#if 1 // praying that removing this dupe wont cause any issues... + if (!mo->standingslope && (mo->eflags & MFE_VERTICALFLIP ? tmceilingslope : tmfloorslope)) + { // Handle landing on slope during Z movement P_HandleSlopeLanding(mo, (mo->eflags & MFE_VERTICALFLIP ? tmceilingslope : tmfloorslope)); } - - if (!mo->standingslope && (mo->eflags & MFE_VERTICALFLIP ? tmceilingslope : tmfloorslope)) { +#endif + if (!mo->standingslope && (mo->eflags & MFE_VERTICALFLIP ? tmceilingslope : tmfloorslope)) + { // Handle landing on slope during Z movement P_HandleSlopeLanding(mo, (mo->eflags & MFE_VERTICALFLIP ? tmceilingslope : tmfloorslope)); } @@ -2483,88 +2590,28 @@ static void P_PlayerZMovement(mobj_t *mo) { mo->pmomz = 0; // We're on a new floor, don't keep doing platform movement. - if (!tmfloorthing || tmfloorthing->flags & (MF_PUSHABLE|MF_MONITOR) - || tmfloorthing->flags2 & MF2_STANDONME || tmfloorthing->type == MT_PLAYER) // Spin Attack + if (!tmfloorthing || tmfloorthing->flags & (MF_PUSHABLE|MF_MONITOR) || + tmfloorthing->flags2 & MF2_STANDONME || tmfloorthing->type == MT_PLAYER) // Spin Attack { mo->eflags |= MFE_JUSTHITFLOOR; // Spin Attack if (mo->eflags & MFE_JUSTHITFLOOR) { - // Check if we're on a polyobject - // that triggers a linedef executor. - msecnode_t *node; - boolean stopmovecut = false; - - if (numPolyObjects) + if (!P_PlayerPolyObjectZMovement(mo)) { - for (node = mo->touching_sectorlist; node; node = node->m_sectorlist_next) - { - sector_t *sec = node->m_sector; - subsector_t *newsubsec; - size_t i; - - for (i = 0; i < numsubsectors; i++) - { - newsubsec = &subsectors[i]; - - if (newsubsec->sector != sec) - continue; - - if (!newsubsec->polyList) - continue; - - polyobj_t *po = newsubsec->polyList; - sector_t *polysec; - - while(po) - { - if (!P_MobjInsidePolyobj(po, mo) || !(po->flags & POF_SOLID)) - { - po = (polyobj_t *)(po->link.next); - continue; - } - - // We're inside it! Yess... - polysec = po->lines[0]->backsector; - - // Moving polyobjects should act like conveyors if the player lands on one. (I.E. none of the momentum cut thing below) -Red - if ((mo->z == polysec->ceilingheight || mo->z+mo->height == polysec->floorheight) && po->thinker) - stopmovecut = true; - - if (!(po->flags & POF_LDEXEC)) - { - po = (polyobj_t *)(po->link.next); - continue; - } - - if (mo->z == polysec->ceilingheight) - { - // We're landing on a PO, so check for - // a linedef executor. - // Trigger tags are 32000 + the PO's ID number. - P_LinedefExecute((INT16)(32000 + po->id), mo, NULL); - } - - po = (polyobj_t *)(po->link.next); - } - } - } - } - - if (!stopmovecut) - - // Cut momentum in half when you hit the ground and - // aren't pressing any controls. - if (!(mo->player->cmd.forwardmove || mo->player->cmd.sidemove) && !mo->player->cmomx && !mo->player->cmomy - && !(mo->player->kartstuff[k_spinouttimer])) - { - mo->momx = mo->momx/2; - mo->momy = mo->momy/2; - - if (mo->player->cmd.buttons & BT_BRAKE && !(mo->player->cmd.forwardmove)) // FURTHER slowdown if you're braking. + // Cut momentum in half when you hit the ground and + // aren't pressing any controls. + if (!(mo->player->cmd.forwardmove || mo->player->cmd.sidemove) && !mo->player->cmomx && !mo->player->cmomy + && !(mo->player->kartstuff[k_spinouttimer])) { mo->momx = mo->momx/2; mo->momy = mo->momy/2; + + if (mo->player->cmd.buttons & BT_BRAKE && !(mo->player->cmd.forwardmove)) // FURTHER slowdown if you're braking. + { + mo->momx = mo->momx/2; + mo->momy = mo->momy/2; + } } } } @@ -2640,16 +2687,19 @@ nightsdone: else mo->z = mo->ceilingz - mo->height; - if (UNLIKELY(mo->player->pflags & PF_NIGHTSMODE)) + if (nightsplayer(mo->player)) { + const boolean flipped = (mo->eflags & MFE_VERTICALFLIP); + // bounce off ceiling if you were flying towards it - if ((mo->eflags & MFE_VERTICALFLIP && mo->player->flyangle > 180 && mo->player->flyangle <= 359) - || (!(mo->eflags & MFE_VERTICALFLIP) && mo->player->flyangle > 0 && mo->player->flyangle < 180)) + if ((flipped && mo->player->flyangle > 180 && mo->player->flyangle <= 359) + || (!flipped && mo->player->flyangle > 0 && mo->player->flyangle < 180)) { if (mo->player->flyangle < 90 || mo->player->flyangle >= 270) mo->player->flyangle -= P_MobjFlip(mo)*90; else mo->player->flyangle += P_MobjFlip(mo)*90; + mo->player->flyangle %= 360; mo->player->speed = FixedMul(mo->player->speed, 4*FRACUNIT/5); } @@ -2658,34 +2708,11 @@ nightsdone: // Check for "Mario" blocks to hit and bounce them if (P_MobjFlip(mo)*mo->momz > 0) { - msecnode_t *node; - - if (CheckForMarioBlocks && !(netgame && mo->player->spectator)) // Only let the player punch - { - // Search the touching sectors, from side-to-side... - for (node = mo->touching_sectorlist; node; node = node->m_sectorlist_next) - { - ffloor_t *rover; - if (!node->m_sector->ffloors) - continue; - - for (rover = node->m_sector->ffloors; rover; rover = rover->next) - { - if (!(rover->flags & FF_EXISTS)) - continue; - - // Come on, it's time to go... - if (rover->flags & FF_MARIO - && !(mo->eflags & MFE_VERTICALFLIP) // if you were flipped, your head isn't actually hitting your ceilingz is it? - && *rover->bottomheight == mo->ceilingz) // The player's head hit the bottom! - // DO THE MARIO! - EV_MarioBlock(rover->master->frontsector, node->m_sector, *rover->topheight, mo); - } - } // Ugly ugly billions of braces! Argh! - } + if (CheckForMarioBlocks) + P_CheckMarioBlocks(mo); // hit the ceiling - if (UNLIKELY(mariomode)) + if (mariomode) S_StartSound(mo, sfx_mario1); if (!mo->player->climbing) @@ -2744,6 +2771,7 @@ static boolean P_SceneryZMovement(mobj_t *mo) P_RemoveMobj(mo); return false; } + if ((!(mo->eflags & MFE_VERTICALFLIP) && mo->z <= mo->floorz) || (mo->eflags & MFE_VERTICALFLIP && mo->z+mo->height >= mo->ceilingz)) // Hit the floor, so split! { @@ -2781,6 +2809,7 @@ static boolean P_SceneryZMovement(mobj_t *mo) P_RemoveMobj(mo); return false; } + // Soniccd seed turns into a flower! if ((!(mo->eflags & MFE_VERTICALFLIP) && mo->z <= mo->floorz) || (mo->eflags & MFE_VERTICALFLIP && mo->z+mo->height >= mo->ceilingz)) @@ -2806,19 +2835,17 @@ static boolean P_SceneryZMovement(mobj_t *mo) } // Fix for any silly pushables like the egg statues that are also scenery for some reason -- Monster Iestyn - if (P_CheckDeathPitCollide(mo)) + if ((mo->flags & MF_PUSHABLE) && + P_CheckDeathPitCollide(mo)) { - if (mo->flags & MF_PUSHABLE) - { - P_RemoveMobj(mo); - return false; - } + P_RemoveMobj(mo); + return false; } // clip movement if (((mo->z <= mo->floorz && !(mo->eflags & MFE_VERTICALFLIP)) || (mo->z + mo->height >= mo->ceilingz && mo->eflags & MFE_VERTICALFLIP)) - && !(mo->flags & MF_NOCLIPHEIGHT)) + && !(mo->flags & MF_NOCLIPHEIGHT)) { if (mo->eflags & MFE_VERTICALFLIP) mo->z = mo->ceilingz - mo->height; @@ -2848,7 +2875,7 @@ static boolean P_SceneryZMovement(mobj_t *mo) if (((mo->z + mo->height > mo->ceilingz && !(mo->eflags & MFE_VERTICALFLIP)) || (mo->z < mo->floorz && mo->eflags & MFE_VERTICALFLIP)) - && !(mo->flags & MF_NOCLIPHEIGHT)) + && !(mo->flags & MF_NOCLIPHEIGHT)) { if (mo->eflags & MFE_VERTICALFLIP) mo->z = mo->floorz; @@ -2875,7 +2902,10 @@ void P_MobjCheckWater(mobj_t *mobj) fixed_t thingtop = mobj->z + mobj->height; // especially for players, infotable height does not neccessarily match actual height sector_t *sector = mobj->subsector->sector; ffloor_t *rover; - player_t *p = mobj->player; // Will just be null if not a player. + player_t *player = mobj->player; // Will just be null if not a player. + + const fixed_t moheight = FixedMul(mobj->info->height, mobj->scale); + const fixed_t mohalfheight = FixedMul(mobj->info->height/2, mobj->scale); // Default if no water exists. mobj->watertop = mobj->waterbottom = mobj->z - 1000*FRACUNIT; @@ -2886,42 +2916,50 @@ void P_MobjCheckWater(mobj_t *mobj) for (rover = sector->ffloors; rover; rover = rover->next) { fixed_t topheight, bottomheight; - if (!(rover->flags & FF_EXISTS) || !(rover->flags & FF_SWIMMABLE) - || (((rover->flags & FF_BLOCKPLAYER) && mobj->player) - || ((rover->flags & FF_BLOCKOTHERS) && !mobj->player))) - continue; + fixed_t topcheck, bottomcheck; - topheight = P_GetFFloorTopZAt(rover, mobj->x, mobj->y); - bottomheight = P_GetFFloorBottomZAt(rover, mobj->x, mobj->y); + if (!(rover->flags & FF_EXISTS) || !(rover->flags & FF_SWIMMABLE) + || (((rover->flags & FF_BLOCKPLAYER) && player) + || ((rover->flags & FF_BLOCKOTHERS) && !player))) + continue; if (mobj->eflags & MFE_VERTICALFLIP) { - if (topheight < (thingtop - FixedMul(mobj->info->height/2, mobj->scale)) - || bottomheight > thingtop) - continue; + topcheck = (thingtop - mohalfheight); + bottomcheck = thingtop; } else { - if (topheight < mobj->z - || bottomheight > (mobj->z + FixedMul(mobj->info->height/2, mobj->scale))) - continue; + topcheck = mobj->z; + bottomcheck = (mobj->z + mohalfheight); } + topheight = P_GetFFloorTopZAt(rover, mobj->x, mobj->y); + + if (topheight < topcheck) + continue; + + bottomheight = P_GetFFloorBottomZAt(rover, mobj->x, mobj->y); + + if (bottomheight > bottomcheck) + continue; + // Set the watertop and waterbottom mobj->watertop = topheight; mobj->waterbottom = bottomheight; // Just touching the water? - if (((mobj->eflags & MFE_VERTICALFLIP) && thingtop - FixedMul(mobj->info->height, mobj->scale) < bottomheight) - || (!(mobj->eflags & MFE_VERTICALFLIP) && mobj->z + FixedMul(mobj->info->height, mobj->scale) > topheight)) + if (((mobj->eflags & MFE_VERTICALFLIP) && thingtop - moheight < bottomheight) || + (!(mobj->eflags & MFE_VERTICALFLIP) && mobj->z + moheight > topheight)) { mobj->eflags |= MFE_TOUCHWATER; if (rover->flags & FF_GOOWATER && !(mobj->flags & MF_NOGRAVITY)) mobj->eflags |= MFE_GOOWATER; } + // Actually in the water? - if (((mobj->eflags & MFE_VERTICALFLIP) && thingtop - FixedMul(mobj->info->height/2, mobj->scale) > bottomheight) - || (!(mobj->eflags & MFE_VERTICALFLIP) && mobj->z + FixedMul(mobj->info->height/2, mobj->scale) < topheight)) + if (((mobj->eflags & MFE_VERTICALFLIP) && thingtop - mohalfheight > bottomheight) || + (!(mobj->eflags & MFE_VERTICALFLIP) && mobj->z + mohalfheight < topheight)) { mobj->eflags |= MFE_UNDERWATER; if (rover->flags & FF_GOOWATER && !(mobj->flags & MF_NOGRAVITY)) @@ -2930,18 +2968,19 @@ void P_MobjCheckWater(mobj_t *mobj) } // Specific things for underwater players - if (p && (mobj->eflags & MFE_UNDERWATER) == MFE_UNDERWATER) + if (player && (mobj->eflags & MFE_UNDERWATER) == MFE_UNDERWATER) { - if (!((p->powers[pw_super]) || (p->powers[pw_invulnerability]))) + if (!((player->powers[pw_super]) || (player->powers[pw_invulnerability]))) { - if ((p->powers[pw_shield] & SH_NOSTACK) == SH_ATTRACT) + if ((player->powers[pw_shield] & SH_NOSTACK) == SH_ATTRACT) { // Water removes attract shield. - p->powers[pw_shield] = p->powers[pw_shield] & SH_STACK; - P_FlashPal(p, PAL_WHITE, 1); + player->powers[pw_shield] = player->powers[pw_shield] & SH_STACK; + P_FlashPal(player, PAL_WHITE, 1); } } + // Can't drown. - p->powers[pw_underwater] = 0; + player->powers[pw_underwater] = 0; } // The rest of this code only executes on a water state change. @@ -2949,23 +2988,24 @@ void P_MobjCheckWater(mobj_t *mobj) return; // Spectators and dead players also don't count. - if (p && (p->spectator || p->playerstate != PST_LIVE)) + if (player && (player->spectator || player->playerstate != PST_LIVE)) return; - if ((p) // Players + if (player // Players || (mobj->flags & MF_PUSHABLE) // Pushables || ((mobj->info->flags & MF_PUSHABLE) && mobj->fuse) // Previously pushable, might be moving still ) { // Check to make sure you didn't just cross into a sector to jump out of // that has shallower water than the block you were originally in. - if (!(mobj->eflags & MFE_VERTICALFLIP) && mobj->watertop-mobj->floorz <= FixedMul(mobj->info->height, mobj->scale)>>1) + if (!(mobj->eflags & MFE_VERTICALFLIP) && mobj->watertop-mobj->floorz <= moheight>>1) return; - if ((mobj->eflags & MFE_VERTICALFLIP) && mobj->ceilingz-mobj->waterbottom <= FixedMul(mobj->info->height, mobj->scale)>>1) + if ((mobj->eflags & MFE_VERTICALFLIP) && mobj->ceilingz-mobj->waterbottom <= moheight>>1) return; - if ((mobj->eflags & MFE_GOOWATER || wasingoo)) { // Decide what happens to your momentum when you enter/leave goopy water. + if ((mobj->eflags & MFE_GOOWATER || wasingoo)) // Decide what happens to your momentum when you enter/leave goopy water. + { if (P_MobjFlip(mobj)*mobj->momz < 0) // You are entering the goo? mobj->momz = FixedMul(mobj->momz, FixedDiv(2*FRACUNIT, 5*FRACUNIT)); // kill momentum significantly, to make the goo feel thick. } @@ -2974,12 +3014,13 @@ void P_MobjCheckWater(mobj_t *mobj) if (P_MobjFlip(mobj)*mobj->momz < 0) { - if ((mobj->eflags & MFE_VERTICALFLIP && thingtop-(FixedMul(mobj->info->height, mobj->scale)>>1)-mobj->momz <= mobj->waterbottom) - || (!(mobj->eflags & MFE_VERTICALFLIP) && mobj->z+(FixedMul(mobj->info->height, mobj->scale)>>1)-mobj->momz >= mobj->watertop)) + if (((mobj->eflags & MFE_VERTICALFLIP) && thingtop-(moheight>>1)-mobj->momz <= mobj->waterbottom) || + (!(mobj->eflags & MFE_VERTICALFLIP) && mobj->z+(moheight>>1)-mobj->momz >= mobj->watertop)) { // Spawn a splash mobj_t *splish; - if (mobj->eflags & MFE_VERTICALFLIP) + + if ((mobj->eflags & MFE_VERTICALFLIP)) { splish = P_SpawnMobj(mobj->x, mobj->y, mobj->waterbottom-FixedMul(mobjinfo[MT_SPLISH].height, mobj->scale), MT_SPLISH); splish->flags2 |= MF2_OBJECTFLIP; @@ -2987,14 +3028,15 @@ void P_MobjCheckWater(mobj_t *mobj) } else splish = P_SpawnMobj(mobj->x, mobj->y, mobj->watertop, MT_SPLISH); + splish->destscale = mobj->scale; P_SetScale(splish, mobj->scale); } // skipping stone! - if (p && p->kartstuff[k_waterskip] < 2 - && ((p->speed/3 > abs(mobj->momz)) // Going more forward than horizontal, so you can skip across the water. - || (p->speed > K_GetKartSpeed(p,false)/3 && p->kartstuff[k_waterskip])) // Already skipped once, so you can skip once more! + if (player && player->kartstuff[k_waterskip] < 2 + && ((player->speed/3 > abs(mobj->momz)) // Going more forward than horizontal, so you can skip across the water. + || (player->speed > K_GetKartSpeed(player, false)/3 && player->kartstuff[k_waterskip])) // Already skipped once, so you can skip once more! && ((!(mobj->eflags & MFE_VERTICALFLIP) && thingtop - mobj->momz > mobj->watertop) || ((mobj->eflags & MFE_VERTICALFLIP) && mobj->z - mobj->momz < mobj->waterbottom))) { @@ -3007,23 +3049,23 @@ void P_MobjCheckWater(mobj_t *mobj) if (!(mobj->eflags & MFE_VERTICALFLIP) && mobj->momz < FixedMul(min, mobj->scale)) mobj->momz = FixedMul(min, mobj->scale); - else if (mobj->eflags & MFE_VERTICALFLIP && mobj->momz > FixedMul(-min, mobj->scale)) + else if ((mobj->eflags & MFE_VERTICALFLIP) && mobj->momz > FixedMul(-min, mobj->scale)) mobj->momz = FixedMul(-min, mobj->scale); - p->kartstuff[k_waterskip]++; + player->kartstuff[k_waterskip]++; } } else if (P_MobjFlip(mobj)*mobj->momz > 0) { - if (((mobj->eflags & MFE_VERTICALFLIP && thingtop-(FixedMul(mobj->info->height, mobj->scale)>>1)-mobj->momz > mobj->waterbottom) - || (!(mobj->eflags & MFE_VERTICALFLIP) && mobj->z+(FixedMul(mobj->info->height, mobj->scale)>>1)-mobj->momz < mobj->watertop)) + if ((((mobj->eflags & MFE_VERTICALFLIP) && thingtop-(moheight>>1)-mobj->momz > mobj->waterbottom) + || (!(mobj->eflags & MFE_VERTICALFLIP) && mobj->z+(moheight>>1)-mobj->momz < mobj->watertop)) && !(mobj->eflags & MFE_UNDERWATER)) // underwater check to prevent splashes on opposite side { // Spawn a splash mobj_t *splish; - if (mobj->eflags & MFE_VERTICALFLIP) + if ((mobj->eflags & MFE_VERTICALFLIP)) { splish = P_SpawnMobj(mobj->x, mobj->y, mobj->waterbottom-FixedMul(mobjinfo[MT_SPLISH].height, mobj->scale), MT_SPLISH); splish->flags2 |= MF2_OBJECTFLIP; @@ -3112,11 +3154,14 @@ static void P_SceneryCheckWater(mobj_t *mobj) if (!(rover->flags & FF_EXISTS) || !(rover->flags & FF_SWIMMABLE) || rover->flags & FF_BLOCKOTHERS) continue; - topheight = P_GetFFloorTopZAt(rover, mobj->x, mobj->y); + topheight = P_GetFFloorTopZAt(rover, mobj->x, mobj->y); + + if (topheight <= mobj->z) + continue; + bottomheight = P_GetFFloorBottomZAt(rover, mobj->x, mobj->y); - if (topheight <= mobj->z - || bottomheight > (mobj->z + FixedMul(mobj->info->height >> 1, mobj->scale))) + if (bottomheight > (mobj->z + FixedMul(mobj->info->height >> 1, mobj->scale))) continue; if (mobj->z + FixedMul(mobj->info->height, mobj->scale) > topheight) @@ -3210,34 +3255,25 @@ static boolean P_CameraCheckWater(camera_t *thiscam) return false; } -void P_DestroyRobots(void) -{ - // Search through all the thinkers for enemies. - mobj_t *mo; - thinker_t *think; - - for (think = thinkercap.next; think != &thinkercap; think = think->next) - { - if (think->function != (actionf_p1)P_MobjThinker) - continue; // not a mobj thinker - - mo = (mobj_t *)think; - - if (mo->health <= 0 || !(mo->flags & MF_ENEMY || mo->flags & MF_BOSS)) - continue; // not a valid enemy - - if (mo->type == MT_PLAYER) // Don't chase after other players! - continue; - - // Found a target enemy - P_KillMobj(mo, players[consoleplayer].mo, players[consoleplayer].mo); - } -} - // the below is chasecam only, if you're curious. check out P_CalcPostImg in p_user.c for first person void P_CalcChasePostImg(player_t *player, camera_t *thiscam) { - const boolean flipcam = (player->pflags & PF_FLIPCAM && !(player->pflags & PF_NIGHTSMODE) && player->mo->eflags & MFE_VERTICALFLIP); + boolean player_flipcam = false; + + if (cv_flipcammode.value == 0) + player_flipcam = player->pflags & PF_FLIPCAM; + else + { + INT32 pnum = P_GetLocalPlayerNumForPlayer(player); + + // Shouldn't happen but just in case + if (pnum == -1) + pnum = 0; + + player_flipcam = cv_flipcam[pnum].value; + } + + const boolean flipcam = (player_flipcam && player->mo->eflags & MFE_VERTICALFLIP && !nightsplayer(player)); UINT8 postimgtype = 0; if (encoremode) @@ -3383,18 +3419,121 @@ boolean P_CameraThinker(player_t *player, camera_t *thiscam, boolean resetcalled return false; } +static void P_CheckCrumblingPlatforms(mobj_t *mobj) +{ + msecnode_t *node; + + if (netgame && mobj->player->spectator) + return; + + for (node = mobj->touching_sectorlist; node; node = node->m_sectorlist_next) + { + ffloor_t *rover; + + for (rover = node->m_sector->ffloors; rover; rover = rover->next) + { + if (!(rover->flags & FF_EXISTS)) + continue; + + if (!(rover->flags & FF_CRUMBLE)) + continue; + + if (mobj->eflags & MFE_VERTICALFLIP) + { + if (P_GetSpecialBottomZ(mobj, sectors + rover->secnum, node->m_sector) != mobj->z + mobj->height) // You nut. + continue; + } + else + { + if (P_GetSpecialTopZ(mobj, sectors + rover->secnum, node->m_sector) != mobj->z) + continue; + } + + EV_StartCrumble(rover->master->frontsector, rover, (rover->flags & FF_FLOATBOB), mobj->player, rover->alpha, !(rover->flags & FF_NORETURN)); + } + } +} + +static boolean P_MobjTouchesSectorWithWater(mobj_t *mobj) +{ + msecnode_t *node; + + for (node = mobj->touching_sectorlist; node; node = node->m_sectorlist_next) + { + ffloor_t *rover; + + if (!node->m_sector->ffloors) + continue; + + for (rover = node->m_sector->ffloors; rover; rover = rover->next) + { + if (!(rover->flags & FF_EXISTS)) + continue; + + if (!(rover->flags & FF_SWIMMABLE)) // Is there water? + continue; + + return true; + } + } + + return false; +} + +// Check for floating water platforms and bounce them +static void P_CheckFloatbobPlatforms(mobj_t *mobj) +{ + msecnode_t *node; + + // Can't land on anything if you're not moving downwards + if (P_MobjFlip(mobj)*mobj->momz >= 0) + return; + + if (!P_MobjTouchesSectorWithWater(mobj)) + return; + + for (node = mobj->touching_sectorlist; node; node = node->m_sectorlist_next) + { + ffloor_t *rover; + + if (!node->m_sector->ffloors) + continue; + + for (rover = node->m_sector->ffloors; rover; rover = rover->next) + { + if (!(rover->flags & FF_EXISTS)) + continue; + + if (!(rover->flags & FF_FLOATBOB)) + continue; + + + if (mobj->eflags & MFE_VERTICALFLIP) + { + if (abs(*rover->bottomheight - (mobj->z + mobj->height)) > abs(mobj->momz)) + continue; + } + else + { + if (abs(*rover->topheight - mobj->z) > abs(mobj->momz)) // The player is landing on the cheese! + continue; + } + + // Initiate a 'bouncy' elevator function which slowly diminishes. + EV_BounceSector(rover->master->frontsector, -mobj->momz, rover->master); + } + } // Ugly ugly billions of braces! Argh! +} + // // P_PlayerMobjThinker // static void P_PlayerMobjThinker(mobj_t *mobj) { - msecnode_t *node; - - I_Assert(mobj != NULL); I_Assert(mobj->player != NULL); I_Assert(!P_MobjWasRemoved(mobj)); - if (!mobj) + if (P_MobjWasRemovedCompat(mobj)) return; P_MobjCheckWater(mobj); @@ -3405,20 +3544,23 @@ static void P_PlayerMobjThinker(mobj_t *mobj) mobj->eflags &= ~MFE_JUSTSTEPPEDDOWN; // Zoom tube - if (UNLIKELY(mobj->tracer && mobj->tracer->type == MT_TUBEWAYPOINT)) + if (mobj->tracer) { - P_UnsetThingPosition(mobj); - mobj->x += mobj->momx; - mobj->y += mobj->momy; - mobj->z += mobj->momz; - P_SetThingPosition(mobj); - P_CheckPosition(mobj, mobj->x, mobj->y); - goto animonly; - } - else if (UNLIKELY(mobj->player->pflags & PF_MACESPIN && mobj->tracer)) - { - P_CheckPosition(mobj, mobj->x, mobj->y); - goto animonly; + if (mobj->tracer->type == MT_TUBEWAYPOINT) + { + P_UnsetThingPosition(mobj); + mobj->x += mobj->momx; + mobj->y += mobj->momy; + mobj->z += mobj->momz; + P_SetThingPosition(mobj); + P_CheckPosition(mobj, mobj->x, mobj->y); + goto animonly; + } + else if (mobj->player->pflags & PF_MACESPIN) + { + P_CheckPosition(mobj, mobj->x, mobj->y); + goto animonly; + } } // Needed for gravity boots @@ -3434,78 +3576,11 @@ static void P_PlayerMobjThinker(mobj_t *mobj) else P_TryMove(mobj, mobj->x, mobj->y, true); - if (LIKELY(!(netgame && mobj->player->spectator))) - { - // Crumbling platforms - for (node = mobj->touching_sectorlist; node; node = node->m_sectorlist_next) - { - fixed_t topheight, bottomheight; - ffloor_t *rover; + // Crumbling platforms + P_CheckCrumblingPlatforms(mobj); - for (rover = node->m_sector->ffloors; rover; rover = rover->next) - { - if (!(rover->flags & FF_EXISTS) || !(rover->flags & FF_CRUMBLE)) - continue; - - topheight = P_GetSpecialTopZ(mobj, sectors + rover->secnum, node->m_sector); - bottomheight = P_GetSpecialBottomZ(mobj, sectors + rover->secnum, node->m_sector); - - if ((topheight == mobj->z && !(mobj->eflags & MFE_VERTICALFLIP)) - || (bottomheight == mobj->z + mobj->height && mobj->eflags & MFE_VERTICALFLIP)) // You nut. - EV_StartCrumble(rover->master->frontsector, rover, (rover->flags & FF_FLOATBOB), mobj->player, rover->alpha, !(rover->flags & FF_NORETURN)); - } - } - } - - // Check for floating water platforms and bounce them - if (CheckForFloatBob && P_MobjFlip(mobj)*mobj->momz < 0) - { - boolean thereiswater = false; - - for (node = mobj->touching_sectorlist; node; node = node->m_sectorlist_next) - { - if (!node->m_sector->ffloors) - continue; - - ffloor_t *rover; - // Get water boundaries first - for (rover = node->m_sector->ffloors; rover; rover = rover->next) - { - if (!(rover->flags & FF_EXISTS)) - continue; - - if (rover->flags & FF_SWIMMABLE) // Is there water? - { - thereiswater = true; - break; - } - } - } - - if (thereiswater) - { - for (node = mobj->touching_sectorlist; node; node = node->m_sectorlist_next) - { - if (!node->m_sector->ffloors) - continue; - - ffloor_t *rover; - for (rover = node->m_sector->ffloors; rover; rover = rover->next) - { - if (!(rover->flags & FF_EXISTS) || !(rover->flags & FF_FLOATBOB)) - continue; - - if ((!(mobj->eflags & MFE_VERTICALFLIP) && abs(*rover->topheight-mobj->z) <= abs(mobj->momz)) // The player is landing on the cheese! - || (mobj->eflags & MFE_VERTICALFLIP && abs(*rover->bottomheight-(mobj->z+mobj->height)) <= abs(mobj->momz))) - { - // Initiate a 'bouncy' elevator function - // which slowly diminishes. - EV_BounceSector(rover->master->frontsector, -mobj->momz, rover->master); - } - } - } - } // Ugly ugly billions of braces! Argh! - } + if (CheckForFloatBob) + P_CheckFloatbobPlatforms(mobj); // always do the gravity bit now, that's simpler // BUT CheckPosition only if wasn't done before. @@ -3522,7 +3597,7 @@ static void P_PlayerMobjThinker(mobj_t *mobj) } else { - if (LIKELY(!(mobj->player->pflags & PF_NIGHTSMODE))) // "jumping" is used for drilling + if (!nightsplayer(mobj->player)) // "jumping" is used for drilling mobj->player->jumping = 0; mobj->player->pflags &= ~PF_JUMPED; @@ -3554,11 +3629,9 @@ animonly: static void P_CalculatePrecipFloor(precipmobj_t *mobj) { // recalculate floorz each time - const sector_t *sec; + const sector_t *sec = (mobj && mobj->subsector) ? mobj->subsector->sector : NULL; - if (mobj && mobj->subsector && mobj->subsector->sector) - sec = mobj->subsector->sector; - else + if (!sec) return; mobj->floorz = P_GetSectorFloorZAt(sec, mobj->x, mobj->y); @@ -3591,10 +3664,10 @@ static void P_CalculatePrecipFloor(precipmobj_t *mobj) // Just the identification of a precip thinker. The thinker // should never actually be called! // -void P_NullPrecipThinker(precipmobj_t *mobj) +FUNCNORETURN void P_NullPrecipThinker(precipmobj_t *mobj) { (void)mobj; - I_Assert("P_NullPrecipThinker should not be called" == 0); + I_Error("P_NullPrecipThinker should not be called"); } boolean P_PrecipThinker(precipmobj_t *mobj) @@ -3605,7 +3678,7 @@ boolean P_PrecipThinker(precipmobj_t *mobj) mobj->lastThink = leveltime; R_ResetPrecipitationMobjInterpolationState(mobj); - P_CycleStateAnimation((mobj_t *)mobj); + //P_CycleStateAnimation((mobj_t *)mobj); // if we ever want animated precip, readd a specific function which does not need casting if (mobj->state == &states[S_RAINRETURN]) { @@ -3652,8 +3725,10 @@ boolean P_PrecipThinker(precipmobj_t *mobj) return true; // only recalc this twice a second (doubt anyone will notice this lulul) - if ((leveltime % 17) == 0) + if ((leveltime % (TICRATE/2)) == 0) + { P_CalculatePrecipFloor(mobj); + } // adjust height if ((mobj->z += mobj->momz) <= mobj->floorz) @@ -3997,7 +4072,7 @@ static void P_Boss3Thinker(mobj_t *mobj) if ((UINT32)mobj->extravalue1 + TICRATE*2 < leveltime) { mobj->extravalue1 = (INT32)leveltime; - S_StartSound(0, sfx_buzz1); + S_StartSound(NULL, sfx_buzz1); } // If in the center, check to make sure @@ -4316,7 +4391,7 @@ static void P_Boss4PopSpikeballs(mobj_t *mobj) { mobj_t *base = mobj->tracer, *seg, *next; P_SetTarget(&mobj->tracer, NULL); - while(base) + while (base) { next = base->tracer; P_SetTarget(&base->tracer, NULL); @@ -4616,7 +4691,7 @@ static void P_Boss7Thinker(mobj_t *mobj) if (mobj->health > 0) mobj->health--; - S_StartSound(0, (mobj->health) ? sfx_behurt : sfx_bedie2); + S_StartSound(NULL, (mobj->health) ? sfx_behurt : sfx_bedie2); mobj->reactiontime /= 3; @@ -4655,7 +4730,7 @@ static void P_Boss7Thinker(mobj_t *mobj) INT32 i; mobj->state->nextstate = mobj->info->painstate; // Reset - S_StartSound(0, sfx_bedeen); + S_StartSound(NULL, sfx_bedeen); for (i = 0; i < MAXPLAYERS; i++) { @@ -4679,7 +4754,7 @@ static void P_Boss7Thinker(mobj_t *mobj) mobj->state->nextstate = mobj->info->spawnstate; // Laugh - S_StartSound(0, sfx_bewar1 + P_RandomKey(4)); + S_StartSound(NULL, sfx_bewar1 + P_RandomKey(4)); } } } @@ -4699,7 +4774,7 @@ static void P_Boss7Thinker(mobj_t *mobj) var2 = 2*TICRATE + (80<<16); A_LobShot(mobj); - S_StartSound(0, sfx_begoop); + S_StartSound(NULL, sfx_begoop); } } else if (mobj->state == &states[S_BLACKEGG_SHOOT2]) @@ -4723,7 +4798,7 @@ static void P_Boss7Thinker(mobj_t *mobj) S_StopSound(missile); if (leveltime & 1) - S_StartSound(0, sfx_beshot); + S_StartSound(NULL, sfx_beshot); } else if (mobj->state == &states[S_BLACKEGG_JUMP1] && mobj->tics == 1) { @@ -4856,7 +4931,7 @@ static void P_Boss7Thinker(mobj_t *mobj) fixed_t x,y,z; mobj_t *mo2; - S_StartSound(0, sfx_befall); + S_StartSound(NULL, sfx_befall); z = mobj->floorz; for (j = 0; j < 2; j++) @@ -4895,13 +4970,13 @@ static void P_Boss7Thinker(mobj_t *mobj) P_DamageMobj(players[i].mo, mobj, mobj, 1); // Laugh - S_StartSound(0, sfx_bewar1 + P_RandomKey(4)); + S_StartSound(NULL, sfx_bewar1 + P_RandomKey(4)); } P_SetMobjState(mobj, mobj->info->spawnstate); } else if (mobj->state == &states[mobj->info->deathstate] && mobj->tics == mobj->state->tics) - S_StartSound(0, sfx_bedie1 + (P_RandomFixed() & 1)); + S_StartSound(NULL, sfx_bedie1 + (P_RandomFixed() & 1)); } // Metal Sonic battle boss @@ -5174,9 +5249,9 @@ static void P_Boss9Thinker(mobj_t *mobj) { // Stunned after vector form if (mobj->movedir > ANGLE_180) - mobj->angle -= FixedAngle(FixedMul(AngleFixed(InvAngle(mobj->movedir)),FixedDiv(mobj->reactiontime<angle -= FixedAngle(FixedMul(AngleFixed(InvAngle(mobj->movedir)), FixedDiv(mobj->reactiontime<angle += FixedAngle(FixedMul(AngleFixed(mobj->movedir),FixedDiv(mobj->reactiontime<angle += FixedAngle(FixedMul(AngleFixed(mobj->movedir), FixedDiv(mobj->reactiontime<reactiontime--; @@ -5218,99 +5293,99 @@ static void P_Boss9Thinker(mobj_t *mobj) // It's time to attack! What are we gonna do?! switch(mobj->movecount) { - case 0: - default: - // Fly up and prepare for an attack! - // We have to charge up first, so let's go up into the air - P_SetMobjState(mobj, mobj->info->raisestate); - if (mobj->floorz >= mobj->target->floorz) - mobj->watertop = mobj->floorz + 256*FRACUNIT; - else - mobj->watertop = mobj->target->floorz + 256*FRACUNIT; - break; - - case 1: - { - // Okay, we're up? Good, time to gather energy... - if (mobj->health > mobj->info->damage) - { // No more bubble if we're broken (pinch phase) - mobj_t *shield = P_SpawnMobj(mobj->x, mobj->y, mobj->z, MT_MSSHIELD_FRONT); - P_SetTarget(&mobj->tracer, shield); - P_SetTarget(&shield->target, mobj); - } - else - P_LinedefExecute(LE_PINCHPHASE, mobj, NULL); - mobj->fuse = 4*TICRATE; - mobj->flags |= MF_PAIN; - if (mobj->info->attacksound) - S_StartSound(mobj, mobj->info->attacksound); - A_FaceTarget(mobj); - break; - } - - case 2: - // We're all charged and ready now! Unleash the fury!! - if (mobj->health > mobj->info->damage) - { - mobj_t *removemobj = mobj->tracer; - P_SetTarget(&mobj->tracer, mobj->hnext); - P_RemoveMobj(removemobj); - } - if (mobj->health <= mobj->info->damage) - { - // Attack 1: Pinball dash! - if (mobj->health == 1) - mobj->movedir = 0; + case 0: + default: + // Fly up and prepare for an attack! + // We have to charge up first, so let's go up into the air + P_SetMobjState(mobj, mobj->info->raisestate); + if (mobj->floorz >= mobj->target->floorz) + mobj->watertop = mobj->floorz + 256*FRACUNIT; else - mobj->movedir = 2; - if (mobj->info->seesound) - S_StartSound(mobj, mobj->info->seesound); - P_SetMobjState(mobj, mobj->info->seestate); - if (mobj->movedir == 2) - mobj->threshold = 16; // bounce 16 times - else - mobj->threshold = 32; // bounce 32 times - mobj->watertop = mobj->target->floorz + 16*FRACUNIT; - P_LinedefExecute(LE_PINCHPHASE, mobj, NULL); - } - else + mobj->watertop = mobj->target->floorz + 256*FRACUNIT; + break; + + case 1: { - // Attack 2: Energy shot! - mobj->movedir = 1; - - if (mobj->health >= 8) - mobj->extravalue1 = 0; - else if (mobj->health >= 5) - mobj->extravalue1 = 2; - else if (mobj->health >= 4) - mobj->extravalue1 = 1; - else - mobj->extravalue1 = 3; - - switch(mobj->extravalue1) - { - case 0: // shoot once - case 2: // spread-shot - default: - mobj->threshold = 2; - break; - case 1: // shoot 3 times - mobj->threshold = 3*2; - break; - case 3: // shoot like a goddamn machinegun - mobj->threshold = 8*2; - break; + // Okay, we're up? Good, time to gather energy... + if (mobj->health > mobj->info->damage) + { // No more bubble if we're broken (pinch phase) + mobj_t *shield = P_SpawnMobj(mobj->x, mobj->y, mobj->z, MT_MSSHIELD_FRONT); + P_SetTarget(&mobj->tracer, shield); + P_SetTarget(&shield->target, mobj); } + else + P_LinedefExecute(LE_PINCHPHASE, mobj, NULL); + mobj->fuse = 4*TICRATE; + mobj->flags |= MF_PAIN; + if (mobj->info->attacksound) + S_StartSound(mobj, mobj->info->attacksound); + A_FaceTarget(mobj); + break; } - break; - case 3: - // Return to idle. - mobj->watertop = mobj->target->floorz + 32*FRACUNIT; - P_SetMobjState(mobj, mobj->info->spawnstate); - mobj->flags &= ~MF_PAIN; - mobj->fuse = 10*TICRATE; - break; + case 2: + // We're all charged and ready now! Unleash the fury!! + if (mobj->health > mobj->info->damage) + { + mobj_t *removemobj = mobj->tracer; + P_SetTarget(&mobj->tracer, mobj->hnext); + P_RemoveMobj(removemobj); + } + if (mobj->health <= mobj->info->damage) + { + // Attack 1: Pinball dash! + if (mobj->health == 1) + mobj->movedir = 0; + else + mobj->movedir = 2; + if (mobj->info->seesound) + S_StartSound(mobj, mobj->info->seesound); + P_SetMobjState(mobj, mobj->info->seestate); + if (mobj->movedir == 2) + mobj->threshold = 16; // bounce 16 times + else + mobj->threshold = 32; // bounce 32 times + mobj->watertop = mobj->target->floorz + 16*FRACUNIT; + P_LinedefExecute(LE_PINCHPHASE, mobj, NULL); + } + else + { + // Attack 2: Energy shot! + mobj->movedir = 1; + + if (mobj->health >= 8) + mobj->extravalue1 = 0; + else if (mobj->health >= 5) + mobj->extravalue1 = 2; + else if (mobj->health >= 4) + mobj->extravalue1 = 1; + else + mobj->extravalue1 = 3; + + switch (mobj->extravalue1) + { + case 0: // shoot once + case 2: // spread-shot + default: + mobj->threshold = 2; + break; + case 1: // shoot 3 times + mobj->threshold = 3*2; + break; + case 3: // shoot like a goddamn machinegun + mobj->threshold = 8*2; + break; + } + } + break; + + case 3: + // Return to idle. + mobj->watertop = mobj->target->floorz + 32*FRACUNIT; + P_SetMobjState(mobj, mobj->info->spawnstate); + mobj->flags &= ~MF_PAIN; + mobj->fuse = 10*TICRATE; + break; } mobj->movecount++; mobj->movecount %= 4; @@ -5328,6 +5403,7 @@ static void P_Boss9Thinker(mobj_t *mobj) // Face your target angle = R_PointToAngle2(mobj->x, mobj->y, mobj->target->x, mobj->target->y); // absolute angle angle = (angle-mobj->angle); // relative angle + if (angle < ANGLE_180) mobj->angle += angle/8; else @@ -5339,18 +5415,19 @@ static void P_Boss9Thinker(mobj_t *mobj) || mobj->target->player->powers[pw_invulnerability] || mobj->target->player->powers[pw_super])) danger = false; - if (mobj->target->x+mobj->target->radius+abs(mobj->target->momx*2) < mobj->x-mobj->radius) + else if (mobj->target->x+mobj->target->radius+abs(mobj->target->momx*2) < mobj->x-mobj->radius) danger = false; - if (mobj->target->x-mobj->target->radius-abs(mobj->target->momx*2) > mobj->x+mobj->radius) + else if (mobj->target->x-mobj->target->radius-abs(mobj->target->momx*2) > mobj->x+mobj->radius) danger = false; - if (mobj->target->y+mobj->target->radius+abs(mobj->target->momy*2) < mobj->y-mobj->radius) + else if (mobj->target->y+mobj->target->radius+abs(mobj->target->momy*2) < mobj->y-mobj->radius) danger = false; - if (mobj->target->y-mobj->target->radius-abs(mobj->target->momy*2) > mobj->y+mobj->radius) + else if (mobj->target->y-mobj->target->radius-abs(mobj->target->momy*2) > mobj->y+mobj->radius) danger = false; - if (mobj->target->z+mobj->target->height+mobj->target->momz*2 < mobj->z) + else if (mobj->target->z+mobj->target->height+mobj->target->momz*2 < mobj->z) danger = false; - if (mobj->target->z+mobj->target->momz*2 > mobj->z+mobj->height) + else if (mobj->target->z+mobj->target->momz*2 > mobj->z+mobj->height) danger = false; + if (danger) { // An incoming attack is detected! What should we do?! @@ -5358,21 +5435,27 @@ static void P_Boss9Thinker(mobj_t *mobj) mobj->movedir = ANGLE_11hh - FixedAngle(FixedMul(AngleFixed(ANGLE_11hh), FixedDiv((mobj->info->spawnhealth - mobj->health)<info->spawnhealth-1)<movedir = InvAngle(mobj->movedir); + mobj->threshold = 6 + (FixedMul(24<info->spawnhealth - mobj->health)<info->spawnhealth-1)<>FRACBITS); + if (mobj->info->activesound) S_StartSound(mobj, mobj->info->activesound); if (mobj->info->painchance) P_SetMobjState(mobj, mobj->info->painchance); + return; } // Move normally: Approach the player using normal thrust and simulated friction. dist = P_AproxDistance(mobj->x-mobj->target->x, mobj->y-mobj->target->y); + P_Thrust(mobj, R_PointToAngle2(0, 0, mobj->momx, mobj->momy), -3*FRACUNIT/8); + if (dist < 64*FRACUNIT) P_Thrust(mobj, mobj->angle, -4*FRACUNIT); else if (dist > 180*FRACUNIT) P_Thrust(mobj, mobj->angle, FRACUNIT); + mobj->momz += P_AproxDistance(mobj->momx, mobj->momy)/12; // Move up higher the faster you're going. } } @@ -5627,7 +5710,7 @@ void P_SetScale(mobj_t *mobj, fixed_t newscale) player_t *player; fixed_t oldscale; - if (!mobj) + if (P_MobjWasRemovedCompat(mobj)) return; oldscale = mobj->scale; //keep for adjusting stuff below @@ -5650,13 +5733,15 @@ void P_SetScale(mobj_t *mobj, fixed_t newscale) void P_Attract(mobj_t *source, mobj_t *dest, boolean nightsgrab) // Home in on your target { fixed_t dist, ndist, speedmul; - fixed_t tx = dest->x; - fixed_t ty = dest->y; - fixed_t tz = dest->z + (dest->height/2); // Aim for center + fixed_t tx, ty, tz; if (!dest || dest->health <= 0 || !dest->player || !source->tracer) return; + tx = dest->x; + ty = dest->y; + tz = dest->z + (dest->height/2); // Aim for center + // change slope dist = P_AproxDistance(P_AproxDistance(tx - source->x, ty - source->y), tz - source->z); @@ -6864,11 +6949,9 @@ static boolean P_MobjDeadThink(mobj_t *mobj) case MT_BANANA: if (cv_bananthrowroll.value) { - //mobj->angle -= spin; - if (cv_bananthrowroll.value == 1 && K_CheckSlopeRollDist(mobj)) - mobj->sloperoll += (angle_t)FixedMul(FixedDiv(abs(mobj->momz), 8 * mobj->scale), ANGLE_67h); // im lazy but this makes sure the banan goes back to upright when it lands lmao - else if (cv_bananthrowroll.value == 2) - mobj->rollangle += (angle_t)FixedMul(FixedDiv(abs(mobj->momz), 8 * mobj->scale), ANGLE_67h); + const angle_t speen = (angle_t)FixedMul(FixedDiv(abs(mobj->momz), 8 * mobj->scale), ANGLE_67h); + //mobj->angle -= speen; + mobj->rollangle += speen; } /* FALLTHRU */ case MT_ORBINAUT: @@ -6971,7 +7054,7 @@ static boolean P_MobjDeadThink(mobj_t *mobj) fixed_t ns; mobj_t *mo2; - i = P_RandomByte(); + i = P_RandomByte(); // grrrrrr z = mobj->subsector->sector->floorheight + ((P_RandomByte()&63)*FRACUNIT); for (j = 0; j < 2; j++) @@ -7058,7 +7141,7 @@ static boolean P_MobjRegularThink(mobj_t *mobj) } P_InstaThrust(mobj, mobj->angle, finalspeed); - + if (grounded) { sector_t *sec2 = P_ThingOnSpecial3DFloor(mobj); @@ -7178,32 +7261,42 @@ static boolean P_MobjRegularThink(mobj_t *mobj) } case MT_BANANA: case MT_EGGMANITEM: - if (cv_bananthrowroll.value && !P_IsObjectOnGround(mobj)) + { + boolean grounded = P_IsObjectOnGround(mobj); + + // rotate thrown eggboxes and bananas mid air! + if (cv_bananthrowroll.value && !grounded) { // tilt n tumble - //mobj->angle += spin; - - if (cv_bananthrowroll.value == 1 && K_CheckSlopeRollDist(mobj)) - mobj->sloperoll -= (angle_t)FixedMul(FixedDiv(mobj->momz, 8 * mobj->scale), ANGLE_67h); // im lazy but this makes sure the banan goes back to upright when it lands lmao - else if (cv_bananthrowroll.value == 2) - mobj->rollangle -= (angle_t)FixedMul(FixedDiv(mobj->momz, 8 * mobj->scale), ANGLE_67h); + const angle_t speen = (angle_t)FixedMul(FixedDiv(abs(mobj->momz), 8 * mobj->scale), ANGLE_67h); + //mobj->angle += speen; + mobj->rollangle -= speen; } mobj->friction = ORIG_FRICTION/4; + if (mobj->momx || mobj->momy) P_SpawnGhostMobj(mobj); - if (P_IsObjectOnGround(mobj) && mobj->health > 1) + + if (grounded && mobj->health > 1) { S_StartSound(mobj, mobj->info->activesound); mobj->momx = mobj->momy = 0; mobj->health = 1; } - P_RollPitchMobj(mobj); + // do not rotate eggman items on slopes + // they are meant to deceive the player + // having them rotated makes them stand out a lot more + // since random items do not roll´n pitch on slopes! + if (mobj->type == MT_BANANA) + P_RollPitchMobj(mobj); if (mobj->threshold > 0) mobj->threshold--; + break; + } case MT_SPB: indirectitemcooldown = 20*TICRATE; /* FALLTHRU */ @@ -8538,7 +8631,7 @@ static boolean P_MobjRegularThink(mobj_t *mobj) if (mobj->tracer && mobj->tracer->player) { - if (!(mobj->tracer->player->pflags & PF_NIGHTSMODE)) + if (!nightsplayer(mobj->tracer->player)) { mobj->flags &= ~MF_NOGRAVITY; mobj->flags2 &= ~MF2_DONTDRAW; @@ -8562,7 +8655,7 @@ static boolean P_MobjRegularThink(mobj_t *mobj) P_SetTarget(&mobj->target, NULL); } - if (mobj->tracer->player->pflags & PF_NIGHTSMODE) + if (nightsplayer(mobj->tracer->player)) { if (mobj->tracer->player->bonustime) { @@ -8674,14 +8767,15 @@ static boolean P_MobjRegularThink(mobj_t *mobj) { const angle_t fa = (i*FINEANGLES/16) & FINEMASK; ns = FixedMul(64 * FRACUNIT, mobj->scale); - x = mobj->x + FixedMul(FINESINE(fa),ns); - y = mobj->y + FixedMul(FINECOSINE(fa),ns); + x = mobj->x + FixedMul(FINESINE(fa), ns); + y = mobj->y + FixedMul(FINECOSINE(fa), ns); mo2 = P_SpawnMobj(x, y, z, MT_EXPLODE); ns = FixedMul(16 * FRACUNIT, mobj->scale); - mo2->momx = FixedMul(FINESINE(fa),ns); - mo2->momy = FixedMul(FINECOSINE(fa),ns); + mo2->momx = FixedMul(FINESINE(fa), ns); + mo2->momy = FixedMul(FINECOSINE(fa), ns); } + z -= FixedMul(32*FRACUNIT, mobj->scale); } P_SetMobjState(mobj, mobj->info->deathstate); @@ -8875,9 +8969,9 @@ static void P_IceBlockFuseThink(mobj_t *mobj) for (i = 0; i < 5; i++) { mobj_t *debris = P_SpawnMobj(mobj->x, mobj->y, mobj->z, MT_SMK_ICEBLOCK_DEBRIS); - debris->angle = FixedAngle(P_RandomRange(0,360)<angle, P_RandomRange(3,18)*(FRACUNIT/4)); - debris->momz = P_RandomRange(4,8)<angle = FixedAngle(P_RandomRange(0, 360)<angle, P_RandomRange(3, 18)*(FRACUNIT/4)); + debris->momz = P_RandomRange(4, 8)<flags & MF_NOTHINK)) + if (mobj->flags & MF_NOTHINK) return; // Remove dead target/tracer. @@ -9057,15 +9150,17 @@ void P_MobjThinker(mobj_t *mobj) tmfloorthing = tmhitthing = NULL; - const sector_t *sec1 = mobj->subsector ? mobj->subsector->sector : NULL; - - // 970 allows ANY mobj to trigger a linedef exec - if (UNLIKELY(!mobj->islocal && sec1 && GETSECSPECIAL(sec1->special, 2) == 8)) // BEWARE: islocal does not exist in vanilla + // do NOT trigger linedef executors for "local" mobjs + if (!mobj->islocal) { - sector_t *sec2; - sec2 = P_ThingOnSpecial3DFloor(mobj); - if (sec2 && GETSECSPECIAL(sec2->special, 2) == 1) - P_LinedefExecute(sec2->tag, mobj, sec2); + // 970 allows ANY mobj to trigger a linedef exec + if (mobj->subsector && GETSECSPECIAL(mobj->subsector->sector->special, 2) == 8) + { + sector_t *sec2; + sec2 = P_ThingOnSpecial3DFloor(mobj); + if (sec2 && GETSECSPECIAL(sec2->special, 2) == 1) + P_LinedefExecute(sec2->tag, mobj, sec2); + } } if (mobj->scale != mobj->destscale) @@ -9077,7 +9172,7 @@ void P_MobjThinker(mobj_t *mobj) mobj->frame = (mobj->frame & ~FF_TRANSMASK) | (((NUMTRANSMAPS-1) - mobj->fuse / 2) << FF_TRANSSHIFT); // Special thinker for scenery objects - if (mobj->flags & MF_SCENERY) + if (mobj->flags & MF_SCENERY && !mobj->player) { P_MobjSceneryThink(mobj); return; @@ -9126,7 +9221,7 @@ void P_MobjThinker(mobj_t *mobj) if (mobj->flags2 & MF2_FIRING && mobj->target && mobj->health > 0) P_FiringThink(mobj); - if (UNLIKELY(mobj->flags & MF_AMBIENT)) + if (mobj->flags & MF_AMBIENT) { if (leveltime % mobj->health) return; @@ -9139,7 +9234,6 @@ void P_MobjThinker(mobj_t *mobj) if (mobj->fuse && !P_FuseThink(mobj)) return; - I_Assert(mobj != NULL); I_Assert(!P_MobjWasRemoved(mobj)); if (mobj->momx || mobj->momy || (mobj->flags2 & MF2_SKULLFLY)) @@ -9170,7 +9264,8 @@ void P_MobjThinker(mobj_t *mobj) mobj->eflags &= ~MFE_JUSTHITFLOOR; } - if (mobj->type == MT_FALLINGROCK + // Sliding physics for slidey mobjs! + if ( mobj->type == MT_FALLINGROCK || mobj->type == MT_LITTLETUMBLEWEED || mobj->type == MT_BIGTUMBLEWEED || mobj->type == MT_FLINGRING @@ -9180,11 +9275,15 @@ void P_MobjThinker(mobj_t *mobj) || P_WeaponOrPanel(mobj->type)) { P_TryMove(mobj, mobj->x, mobj->y, true); // Sets mo->standingslope correctly + + if (P_MobjWasRemovedCompat(mobj)) // anything that calls checkposition can be lethal + return; + P_ButteredSlope(mobj); } - if (UNLIKELY(mobj->flags & (MF_ENEMY|MF_BOSS) && mobj->health - && P_CheckDeathPitCollide(mobj))) // extra pit check in case these didn't have momz + if (mobj->flags & (MF_ENEMY|MF_BOSS) && mobj->health + && P_CheckDeathPitCollide(mobj)) // extra pit check in case these didn't have momz { P_KillMobj(mobj, NULL, NULL); return; @@ -9193,10 +9292,7 @@ void P_MobjThinker(mobj_t *mobj) // Crush enemies! if (mobj->ceilingz - mobj->floorz < mobj->height) { - if (UNLIKELY(( - (mobj->flags & (MF_ENEMY|MF_BOSS) - && mobj->flags & MF_SHOOTABLE) - || mobj->type == MT_EGGSHIELD)) + if (((mobj->flags & (MF_ENEMY|MF_BOSS) && mobj->flags & MF_SHOOTABLE) || mobj->type == MT_EGGSHIELD) && !(mobj->flags & MF_NOCLIPHEIGHT) && mobj->health > 0) { @@ -9205,30 +9301,33 @@ void P_MobjThinker(mobj_t *mobj) } } + if (P_MobjWasRemovedCompat(mobj)) + return; // obligatory paranoia check + // Can end up here if a player dies. - if (mobj->player) - P_CyclePlayerMobjState(mobj); - else - P_CycleMobjState(mobj); + P_CycleMobjState(mobj); if (P_MobjWasRemoved(mobj)) return; - if (UNLIKELY(P_WeaponOrPanel(mobj->type))) + if ((mobj->health == 0) && // Fading tile + (mobj->type == MT_BOUNCEPICKUP + || mobj->type == MT_RAILPICKUP + || mobj->type == MT_AUTOPICKUP + || mobj->type == MT_EXPLODEPICKUP + || mobj->type == MT_SCATTERPICKUP + || mobj->type == MT_GRENADEPICKUP)) { - if (mobj->health == 0) // Fading tile - { - INT32 value = mobj->info->damage/10; - value = mobj->fuse/value; - value = 10-value; - value--; + INT32 value = mobj->info->damage/10; + value = mobj->fuse/value; + value = 10-value; + value--; - if (value <= 0) - value = 1; + if (value <= 0) + value = 1; - mobj->frame &= ~FF_TRANSMASK; - mobj->frame |= value << FF_TRANSSHIFT; - } + mobj->frame &= ~FF_TRANSMASK; + mobj->frame |= value << FF_TRANSSHIFT; } } @@ -9238,7 +9337,6 @@ boolean P_RailThinker(mobj_t *mobj) { fixed_t x, y, z; - I_Assert(mobj != NULL); I_Assert(!P_MobjWasRemoved(mobj)); x = mobj->x, y = mobj->y, z = mobj->z; @@ -9264,28 +9362,31 @@ void P_PushableThinker(mobj_t *mobj) { sector_t *sec; - I_Assert(mobj != NULL); I_Assert(!P_MobjWasRemoved(mobj)); - if (!mobj) - return; - - sec = mobj->subsector->sector; - - if (mobj->z == sec->floorheight && GETSECSPECIAL(sec->special, 2) == 1) - P_LinedefExecute(sec->tag, mobj, sec); + // do NOT trigger linedef executors for "local" mobjs + if (!mobj->islocal) { - sector_t *sec2; + sec = mobj->subsector->sector; - sec2 = P_ThingOnSpecial3DFloor(mobj); - if (sec2 && GETSECSPECIAL(sec2->special, 2) == 1) - P_LinedefExecute(sec2->tag, mobj, sec2); + if (mobj->z == sec->floorheight && GETSECSPECIAL(sec->special, 2) == 1) + P_LinedefExecute(sec->tag, mobj, sec); + { + sector_t *sec2; + + sec2 = P_ThingOnSpecial3DFloor(mobj); + if (sec2 && GETSECSPECIAL(sec2->special, 2) == 1) + P_LinedefExecute(sec2->tag, mobj, sec2); + } } // it has to be pushable RIGHT NOW for this part to happen if (mobj->flags & MF_PUSHABLE && !(mobj->momx || mobj->momy)) P_TryMove(mobj, mobj->x, mobj->y, true); + if (P_MobjWasRemovedCompat(mobj)) + return; + if (mobj->fuse == 1) // it would explode in the MobjThinker code { mobj_t *spawnmo; @@ -9302,15 +9403,17 @@ void P_PushableThinker(mobj_t *mobj) x = mobj->spawnpoint->x << FRACBITS; y = mobj->spawnpoint->y << FRACBITS; - ss = R_PointInSubsector(x, y); - if (mobj->spawnpoint->z != 0) z = mobj->spawnpoint->z << FRACBITS; else + { + ss = R_PointInSubsector(x, y); z = ss->sector->floorheight; + } spawnmo = P_SpawnMobj(x, y, z, mobj->type); - if (spawnmo) + + if (!P_MobjWasRemovedCompat(spawnmo)) { spawnmo->spawnpoint = mobj->spawnpoint; P_UnsetThingPosition(spawnmo); @@ -10019,7 +10122,7 @@ static precipmobj_t *P_SpawnPrecipMobj(fixed_t x, fixed_t y, fixed_t z, mobjtype mobj->x = x; mobj->y = y; - mobj->flags = info->flags; + //mobj->flags = info->flags; // do not set the state with P_SetMobjState, // because action routines can not be called yet @@ -10029,7 +10132,7 @@ static precipmobj_t *P_SpawnPrecipMobj(fixed_t x, fixed_t y, fixed_t z, mobjtype mobj->tics = st->tics; mobj->sprite = st->sprite; mobj->frame = st->frame; // FF_FRAMEMASK for frame, and other bits.. - mobj->anim_duration = (UINT16)st->var2; // only used if FF_ANIMATE is set + //mobj->anim_duration = (UINT16)st->var2; // only used if FF_ANIMATE is set // set subsector and/or block links P_SetPrecipitationThingPosition(mobj); @@ -10099,14 +10202,14 @@ void P_RemoveMobj(mobj_t *mobj) } } // Rings only, please! - else if (UNLIKELY(mobj->spawnpoint && + else if (mobj->spawnpoint && !(mobj->flags2 & MF2_DONTRESPAWN) && (mobj->type == MT_RING || mobj->type == MT_COIN || mobj->type == MT_BLUEBALL || mobj->type == MT_REDTEAMRING || mobj->type == MT_BLUETEAMRING - || P_WeaponOrPanel(mobj->type)))) + || P_WeaponOrPanel(mobj->type))) { itemrespawnque[iquehead] = mobj->spawnpoint; itemrespawntime[iquehead] = leveltime; @@ -10288,7 +10391,7 @@ void P_SpawnPrecipitation(void) if (curWeather == PRECIP_BLANK) rainmo->precipflags |= PCF_INVISIBLE; - floorz = rainmo->floorz >> FRACBITS; + floorz = rainmo->floorz >> FRACBITS; ceilingz = rainmo->ceilingz >> FRACBITS; if (floorz < ceilingz) @@ -10355,8 +10458,6 @@ void P_PrecipitationEffects(void) return; } - boolean sounds_rain = ((cv_drawdist_precip.value != 0) && rainsfx && (!leveltime || leveltime % 80 == 1)); - // Currently thunderstorming with lightning, and we're sounding the thunder... // and where there's thunder, there's gotta be lightning! if (effects_lightning && lightningStrike) @@ -10378,6 +10479,8 @@ void P_PrecipitationEffects(void) if (sound_disabled) return; // Sound off? D'aw, no fun. + const boolean sounds_rain = ((cv_drawdist_precip.value != 0) && rainsfx && (!leveltime || leveltime % 80 == 1)); + if (!sounds_rain && !sounds_thunder) return; // no need to calculate volume at ALL @@ -10448,6 +10551,24 @@ void P_PrecipitationEffects(void) } } +mobjtype_t g_doomednum_to_mobjtype[MAXDOOMEDNUM+1] = {}; + +void CalculateDoomednumToMobjtype(void) +{ + memset(g_doomednum_to_mobjtype, MT_NULL, sizeof(g_doomednum_to_mobjtype)); + + for (size_t i = 0; i < NUMMOBJTYPES; i++) + { + const INT32 doomednum = mobjinfo[i].doomednum; + + if (doomednum > 0 && doomednum <= MAXDOOMEDNUM) + { + if (g_doomednum_to_mobjtype[doomednum] == MT_NULL) + g_doomednum_to_mobjtype[doomednum] = (mobjtype_t)i; + } + } +} + // // P_RespawnSpecials // @@ -10521,17 +10642,15 @@ void P_RespawnSpecials(void) if (mthing) { - mobjtype_t i; + mobjtype_t i = MT_NULL; x = mthing->x << FRACBITS; y = mthing->y << FRACBITS; ss = R_PointInSubsector(x, y); // find which type to spawn - for (i = 0; i < NUMMOBJTYPES; i++) - if (mthing->type == mobjinfo[i].doomednum) - break; + i = g_doomednum_to_mobjtype[mthing->type]; - if (i == NUMMOBJTYPES) // prevent creation of objects with this type -- Monster Iestyn 17/12/17 + if (i <= MT_NULL || i >= NUMMOBJTYPES) // prevent creation of objects with this type -- Monster Iestyn 17/12/17 { // 3D Mode start Thing is unlikely to be added to the que, // so don't bother checking for that specific type @@ -10680,7 +10799,7 @@ void P_SpawnPlayer(INT32 playernum) // the dead body mobj retains the skin through the 'spritedef' override). mobj->skin = &skins[p->skin]; - mobj->localskin = (p->localskin ? K_GetPlayerSkin(p) : 0); + mobj->localskin = (p->localskin ? K_GetPlayerSkin(p) : NULL); mobj->skinlocal = p->skinlocal; mobj->health = p->health; @@ -10959,7 +11078,7 @@ INT32 numhuntemeralds = 0; // void P_SpawnMapThing(mapthing_t *mthing) { - mobjtype_t i; + mobjtype_t i = MT_NULL; mobj_t *mobj; fixed_t x, y, z; subsector_t *ss; @@ -10972,11 +11091,9 @@ void P_SpawnMapThing(mapthing_t *mthing) if (objectplacing) { // find which type to spawn - for (i = 0; i < NUMMOBJTYPES; i++) - if (mthing->type == mobjinfo[i].doomednum) - break; + i = g_doomednum_to_mobjtype[mthing->type]; - if (i == NUMMOBJTYPES) + if (i <= MT_NULL || i >= NUMMOBJTYPES) { if (mthing->type == 3328) // 3D Mode start Thing return; @@ -11044,13 +11161,9 @@ void P_SpawnMapThing(mapthing_t *mthing) } // find which type to spawn - for (i = 0; i < NUMMOBJTYPES; i++) - { - if (mthing->type == mobjinfo[i].doomednum) - break; - } + i = g_doomednum_to_mobjtype[mthing->type]; - if (i == NUMMOBJTYPES) + if (i <= MT_NULL || i >= NUMMOBJTYPES) { if (mthing->type == 3328) // 3D Mode start Thing return; @@ -11093,8 +11206,6 @@ void P_SpawnMapThing(mapthing_t *mthing) { if (!cv_powerstones.value || !G_BattleGametype()) return; - - runemeraldmanager = true; } if (!G_RaceGametype()) // No enemies in match or CTF modes @@ -11186,16 +11297,7 @@ void P_SpawnMapThing(mapthing_t *mthing) } } - if (ultimatemode) - { - if (i == MT_PITYTV || i == MT_GREENTV || i == MT_YELLOWTV || i == MT_BLUETV || i == MT_BLACKTV || i == MT_WHITETV) - return; // No shields in Ultimate mode - - if (i == MT_SUPERRINGBOX) - return; // No rings in Ultimate mode (except special stages) - } - - if (i == MT_EMMY && (gametype != GT_COOP || ultimatemode || tokenbits == 30 || tokenlist & (1 << tokenbits++))) + if (i == MT_EMMY && (gametype != GT_COOP || tokenbits == 30 || tokenlist & (1 << tokenbits++))) return; // you already got this token, or there are too many, or the gametype's not right // Objectplace landing point @@ -11743,32 +11845,32 @@ ML_NOCLIMB : Direction not controllable if (mobj->flags & MF_MONITOR) { // flag for strong/weak random boxes - if (mthing->type == mobjinfo[MT_SUPERRINGBOX].doomednum || mthing->type == mobjinfo[MT_PRUP].doomednum || - mthing->type == mobjinfo[MT_SNEAKERTV].doomednum || mthing->type == mobjinfo[MT_INV].doomednum || - mthing->type == mobjinfo[MT_WHITETV].doomednum || mthing->type == mobjinfo[MT_GREENTV].doomednum || - mthing->type == mobjinfo[MT_YELLOWTV].doomednum || mthing->type == mobjinfo[MT_BLUETV].doomednum || - mthing->type == mobjinfo[MT_BLACKTV].doomednum || mthing->type == mobjinfo[MT_PITYTV].doomednum || - mthing->type == mobjinfo[MT_RECYCLETV].doomednum || mthing->type == mobjinfo[MT_MIXUPBOX].doomednum) + if (i == MT_SUPERRINGBOX || i == MT_PRUP || + i == MT_SNEAKERTV || i == MT_INV || + i == MT_WHITETV || i == MT_GREENTV || + i == MT_YELLOWTV || i == MT_BLUETV || + i == MT_BLACKTV || i == MT_PITYTV || + i == MT_RECYCLETV || i == MT_MIXUPBOX) mobj->flags2 |= MF2_AMBUSH; } - - else if (mthing->type != mobjinfo[MT_AXIS].doomednum && - mthing->type != mobjinfo[MT_AXISTRANSFER].doomednum && - mthing->type != mobjinfo[MT_AXISTRANSFERLINE].doomednum && - mthing->type != mobjinfo[MT_NIGHTSBUMPER].doomednum && - mthing->type != mobjinfo[MT_STARPOST].doomednum) + else if ( + i != MT_AXIS && + i != MT_AXISTRANSFER && + i != MT_AXISTRANSFERLINE && + i != MT_NIGHTSBUMPER && + i != MT_STARPOST) mobj->flags2 |= MF2_AMBUSH; } if (mthing->options & MTF_OBJECTSPECIAL) { // flag for strong/weak random boxes - if (mthing->type == mobjinfo[MT_SUPERRINGBOX].doomednum || mthing->type == mobjinfo[MT_PRUP].doomednum || - mthing->type == mobjinfo[MT_SNEAKERTV].doomednum || mthing->type == mobjinfo[MT_INV].doomednum || - mthing->type == mobjinfo[MT_WHITETV].doomednum || mthing->type == mobjinfo[MT_GREENTV].doomednum || - mthing->type == mobjinfo[MT_YELLOWTV].doomednum || mthing->type == mobjinfo[MT_BLUETV].doomednum || - mthing->type == mobjinfo[MT_BLACKTV].doomednum || mthing->type == mobjinfo[MT_PITYTV].doomednum || - mthing->type == mobjinfo[MT_RECYCLETV].doomednum || mthing->type == mobjinfo[MT_MIXUPBOX].doomednum) + if (i == MT_SUPERRINGBOX || i == MT_PRUP || + i == MT_SNEAKERTV || i == MT_INV || + i == MT_WHITETV || i == MT_GREENTV || + i == MT_YELLOWTV || i == MT_BLUETV || + i == MT_BLACKTV || i == MT_PITYTV || + i == MT_RECYCLETV || i == MT_MIXUPBOX) mobj->flags2 |= MF2_STRONGBOX; // Requires you to be in bonus time to activate @@ -11867,8 +11969,6 @@ void P_SpawnHoops(mapthing_t *mthing) x = mthing->x << FRACBITS; y = mthing->y << FRACBITS; - sec = R_PointInSubsector(x, y)->sector; - // Save our flags! if (mthing->type == 1713) z = (mthing->options >> ZSHIFT) << FRACBITS; @@ -11880,6 +11980,8 @@ void P_SpawnHoops(mapthing_t *mthing) if (P_MobjWasRemoved(hoopcenter)) return; + sec = R_PointInSubsector(x, y)->sector; + hoopcenter->spawnpoint = mthing; z += P_GetSectorFloorZAt(sec, x, y); @@ -12329,8 +12431,9 @@ mobj_t *P_SPMAngle(mobj_t *source, mobjtype_t type, angle_t angle, UINT8 allowai // void P_FlashPal(player_t *pl, UINT16 type, UINT16 duration) { - if (!pl) + if (!pl || cv_reducevfx.value) // no palette flashing with reducevfx return; + pl->flashcount = duration; pl->flashpal = type; } diff --git a/src/p_mobj.h b/src/p_mobj.h index 38bbe2e37..face77ed2 100644 --- a/src/p_mobj.h +++ b/src/p_mobj.h @@ -113,7 +113,7 @@ typedef enum // Don't use the blocklinks (inert but displayable) MF_NOBLOCKMAP = 1<<4, // Thin, paper-like collision bound (for visual equivalent, see FF_PAPERSPRITE) - MF_PAPERCOLLISION = 1<<5, + MF_PAPERCOLLISION = 1<<5, // You can push this object. It can activate switches and things by pushing it on top. MF_PUSHABLE = 1<<6, // Object is a boss. @@ -298,6 +298,7 @@ typedef struct mobj_s angle_t angle, pitch, roll; // orientation angle_t old_angle, old_pitch, old_roll; // orientation interpolation angle_t rollangle; + angle_t temprollangle; // same as rollangle but resets each tic, idk either man. // cba exposing this to lua either spritenum_t sprite; // used to find patch_t and flip value UINT32 frame; // frame number, plus bits see p_pspr.h UINT16 anim_duration; // for FF_ANIMATE states @@ -421,10 +422,6 @@ typedef struct mobj_s // // For precipitation // -// Sometimes this is casted to a mobj_t, -// so please keep the start of the -// structure the same. -// typedef struct precipmobj_s { // List: thinker links. @@ -444,12 +441,10 @@ typedef struct precipmobj_s // More drawing info: to determine current sprite. spritenum_t sprite; // used to find patch_t and flip value UINT32 frame; // frame number, plus bits see p_pspr.h - UINT16 anim_duration; // for FF_ANIMATE states + //UINT16 anim_duration; // for FF_ANIMATE states INT16 lightlevel; // Add to sector lightlevel, -255 - 255 - struct mprecipsecnode_s *touching_sectorlist; // a linked list of sectors where this object appears - struct subsector_s *subsector; // Subsector the mobj resides in. // The closest interval over all contacted sectors (or things). @@ -458,11 +453,10 @@ typedef struct precipmobj_s // Momentums, used to update position. fixed_t momx, momy, momz; - fixed_t precipflags; // fixed_t so it uses the same spot as "pmomz" even as we use precipflags_t for it + precipflag_t precipflags; state_t *state; INT32 tics; // state tic counter - UINT32 flags; // flags from mobjinfo tables tic_t lastThink; } precipmobj_t; @@ -502,7 +496,6 @@ void P_SpawnPrecipitation(void); void P_SpawnParaloop(fixed_t x, fixed_t y, fixed_t z, fixed_t radius, INT32 number, mobjtype_t type, statenum_t nstate, angle_t rotangle, boolean spawncenter); boolean P_BossTargetPlayer(mobj_t *actor, boolean closest); boolean P_SupermanLook4Players(mobj_t *actor); -void P_DestroyRobots(void); boolean P_PrecipThinker(precipmobj_t *mobj); void P_NullPrecipThinker(precipmobj_t *mobj); void P_FreePrecipMobj(precipmobj_t *mobj); @@ -513,7 +506,6 @@ void P_EmeraldManager(void); #define MAXHUNTEMERALDS 64 extern mapthing_t *huntemeralds[MAXHUNTEMERALDS]; extern INT32 numhuntemeralds; -extern boolean runemeraldmanager; extern INT32 numstarposts; #ifdef __cplusplus diff --git a/src/p_polyobj.c b/src/p_polyobj.c index 7b5135c9e..94c808b22 100644 --- a/src/p_polyobj.c +++ b/src/p_polyobj.c @@ -1385,8 +1385,7 @@ static void Polyobj_rotateThings(polyobj_t *po, vector2_t origin, angle_t delta, if (mo->player) { - angle_t localangle = P_GetLocalAngle(mo->player); - P_ForceLocalAngle(mo->player, localangle + delta); + P_ForceLocalAngle(mo->player, P_GetLocalAngle(mo->player) + delta); } } } diff --git a/src/p_saveg.c b/src/p_saveg.c index 0dcac2083..cde5765c4 100644 --- a/src/p_saveg.c +++ b/src/p_saveg.c @@ -69,7 +69,7 @@ FUNCINLINE static ATTRINLINE void P_ArchivePlayer(savebuffer_t *save) pllives = 3; // has less than that. WRITEUINT8(save->p, player->skincolor); - WRITEUINT8(save->p, player->skin); + WRITESKIN(save->p, player->skin); WRITEUINT32(save->p, player->score); WRITEINT32(save->p, pllives); @@ -77,7 +77,7 @@ FUNCINLINE static ATTRINLINE void P_ArchivePlayer(savebuffer_t *save) if (botskin) { - WRITEUINT8(save->p, botskin); + WRITESKIN(save->p, botskin); WRITEUINT8(save->p, botcolor); } } @@ -88,7 +88,7 @@ FUNCINLINE static ATTRINLINE void P_ArchivePlayer(savebuffer_t *save) FUNCINLINE static ATTRINLINE void P_UnArchivePlayer(savebuffer_t *save) { savedata.skincolor = READUINT8(save->p); - savedata.skin = READUINT8(save->p); + savedata.skin = READSKIN(save->p); savedata.score = READINT32(save->p); savedata.lives = READINT32(save->p); @@ -96,9 +96,11 @@ FUNCINLINE static ATTRINLINE void P_UnArchivePlayer(savebuffer_t *save) if (savedata.botcolor) { - savedata.botskin = READUINT8(save->p); + savedata.botskin = READSKIN(save->p); + if (savedata.botskin-1 >= numskins) savedata.botskin = 0; + savedata.botcolor = READUINT8(save->p); } else @@ -117,7 +119,9 @@ static void P_NetArchivePlayers(savebuffer_t *save, boolean resending) for (i = 0; i < MAXPLAYERS; i++) { +#ifndef PHOBOS_BUILD if (resending) +#endif WRITESINT8(save->p, (SINT8)adminplayers[i]); if (!playeringame[i]) @@ -127,7 +131,9 @@ static void P_NetArchivePlayers(savebuffer_t *save, boolean resending) // no longer send ticcmds +#ifndef PHOBOS_BUILD if (resending) +#endif WRITESTRINGN(save->p, player_names[i], MAXPLAYERNAME); const player_t *player = &players[i]; @@ -156,11 +162,16 @@ static void P_NetArchivePlayers(savebuffer_t *save, boolean resending) WRITEUINT16(save->p, player->flashpal); WRITEUINT16(save->p, player->flashcount); +#ifdef PHOBOS_BUILD + WRITEUINT8(save->p, player->skincolor); + WRITEINT32(save->p, player->skin); +#else if (resending) { WRITEUINT8(save->p, player->skincolor); WRITEINT32(save->p, player->skin); } +#endif WRITEUINT32(save->p, player->score); WRITEFIXED(save->p, player->dashspeed); @@ -309,7 +320,9 @@ static void P_NetUnArchivePlayers(savebuffer_t *save, boolean reloading) for (i = 0; i < MAXPLAYERS; i++) { +#ifndef PHOBOS_BUILD if (reloading) +#endif adminplayers[i] = (INT32)READSINT8(save->p); // Do NOT memset player struct to 0 @@ -320,7 +333,9 @@ static void P_NetUnArchivePlayers(savebuffer_t *save, boolean reloading) // NOTE: sending tics should (hopefully) no longer be necessary +#ifndef PHOBOS_BUILD if (reloading) +#endif READSTRINGN(save->p, player_names[i], MAXPLAYERNAME); player_t *player = &players[i]; @@ -349,11 +364,16 @@ static void P_NetUnArchivePlayers(savebuffer_t *save, boolean reloading) player->flashpal = READUINT16(save->p); player->flashcount = READUINT16(save->p); +#ifdef PHOBOS_BUILD + player->skincolor = READUINT8(save->p); + player->skin = READINT32(save->p); +#else if (reloading) { player->skincolor = READUINT8(save->p); player->skin = READINT32(save->p); } +#endif player->score = READUINT32(save->p); player->dashspeed = READFIXED(save->p); // dashing speed @@ -691,7 +711,7 @@ static void ArchiveLines(savebuffer_t *save) if (spawnli->special == 321 || spawnli->special == 322) // only reason li->callcount would be non-zero is if either of these are involved diff |= LD_CLLCOUNT; - if (li->sidenum[0] != 0xffff) + if (li->sidenum[0] != NO_INDEX) { si = &sides[li->sidenum[0]]; spawnsi = &spawnsides[li->sidenum[0]]; @@ -706,7 +726,8 @@ static void ArchiveLines(savebuffer_t *save) if (si->midtexture != spawnsi->midtexture) diff |= LD_S1MIDTEX; } - if (li->sidenum[1] != 0xffff) + + if (li->sidenum[1] != NO_INDEX) { si = &sides[li->sidenum[1]]; spawnsi = &spawnsides[li->sidenum[1]]; @@ -786,6 +807,7 @@ static void UnArchiveFFloors(savebuffer_t *save, const sector_t *ss) I_Error("Sector does not have any ffloors!"); fflr_i = READUINT16(save->p); // get first modified ffloor's number ready + for (;;) // for some reason the usual for (rover = x; ...) thing doesn't work here? { if (fflr_i == 0xffff) // end of modified ffloors list, let's stop already @@ -1106,7 +1128,11 @@ static void SaveMobjThinker(savebuffer_t *save, const thinker_t *th, const UINT8 diff2 = 0; // not the default but the most probable +#ifdef PHOBOS_BUILD + if (mobj->momx != 0 || mobj->momy != 0 || mobj->momz != 0 || mobj->pmomz !=0) +#else if (mobj->momx != 0 || mobj->momy != 0 || mobj->momz != 0) +#endif diff |= MD_MOM; if (mobj->radius != mobj->info->radius) diff |= MD_RADIUS; @@ -1234,6 +1260,9 @@ static void SaveMobjThinker(savebuffer_t *save, const thinker_t *th, const UINT8 WRITEFIXED(save->p, mobj->momx); WRITEFIXED(save->p, mobj->momy); WRITEFIXED(save->p, mobj->momz); +#ifdef PHOBOS_BUILD + WRITEFIXED(save->p, mobj->pmomz); +#endif } if (diff & MD_RADIUS) WRITEFIXED(save->p, mobj->radius); @@ -1295,7 +1324,7 @@ static void SaveMobjThinker(savebuffer_t *save, const thinker_t *th, const UINT8 if (diff2 & MD2_CVMEM) WRITEINT32(save->p, mobj->cvmem); if (diff2 & MD2_SKIN) - WRITEUINT8(save->p, (UINT8)((skin_t *)mobj->skin - skins)); + WRITESKIN(save->p, (skinnum_t)((skin_t *)mobj->skin - skins)); if (diff2 & MD2_COLOR) WRITEUINT8(save->p, mobj->color); if (diff2 & MD2_EXTVAL1) @@ -1965,21 +1994,6 @@ FUNCINLINE static ATTRINLINE player_t *LoadPlayer(UINT32 player) // Loads a mobj_t from a save game // -static mobjtype_t g_doomednum_to_mobjtype[UINT16_MAX]; - -static void CalculateDoomednumToMobjtype(void) -{ - memset(g_doomednum_to_mobjtype, MT_NULL, sizeof(g_doomednum_to_mobjtype)); - - for (size_t i = MT_NULL+1; i < NUMMOBJTYPES; i++) - { - if (mobjinfo[i].doomednum > 0 && mobjinfo[i].doomednum <= UINT16_MAX) - { - g_doomednum_to_mobjtype[ mobjinfo[i].doomednum ] = i; - } - } -} - static void LoadMobjThinker(savebuffer_t *save, actionf_p1 thinker) { mobj_t *mobj; @@ -2068,6 +2082,9 @@ static void LoadMobjThinker(savebuffer_t *save, actionf_p1 thinker) mobj->momx = READFIXED(save->p); mobj->momy = READFIXED(save->p); mobj->momz = READFIXED(save->p); +#ifdef PHOBOS_BUILD + mobj->pmomz = READFIXED(save->p); +#endif } // otherwise they're zero, and the memset took care of it if (diff & MD_RADIUS) @@ -2168,7 +2185,7 @@ static void LoadMobjThinker(savebuffer_t *save, actionf_p1 thinker) if (diff2 & MD2_CVMEM) mobj->cvmem = READINT32(save->p); if (diff2 & MD2_SKIN) - mobj->skin = &skins[READUINT8(save->p)]; + mobj->skin = &skins[READSKIN(save->p)]; if (diff2 & MD2_COLOR) mobj->color = READUINT8(save->p); if (diff2 & MD2_EXTVAL1) @@ -2879,10 +2896,6 @@ static void P_NetUnArchiveThinkers(savebuffer_t *save) if (READUINT32(save->p) != ARCHIVEBLOCK_THINKERS) I_Error("Bad $$$.sav at archive block Thinkers"); - // Pre-calculate this lookup, because it was wasting - // a shit ton of time loading mobj thinkers. - CalculateDoomednumToMobjtype(); - // remove all the current thinkers for (currentthinker = thinkercap.next; currentthinker != &thinkercap; currentthinker = next) { @@ -3076,7 +3089,7 @@ static void P_NetUnArchiveThinkers(savebuffer_t *save) break; default: - I_Error("P_UnarchiveSpecials: Unknown tclass %d in savegame", tclass); + I_Error("P_NetUnArchiveThinkers: Unknown tclass %d in savegame", tclass); } } @@ -3187,7 +3200,7 @@ FUNCINLINE static ATTRINLINE void P_UnArchivePolyObjects(savebuffer_t *save) numSavedPolys = READINT32(save->p); if (numSavedPolys != numPolyObjects) - I_Error("P_UnArchivePolyObjects: polyobj count inconsistency\n"); + I_Error("P_UnArchivePolyObjects: polyobj count inconsistency (expected %d, got %d)\n", numPolyObjects, numSavedPolys); for (i = 0; i < numSavedPolys; ++i) P_UnArchivePolyObj(save, &PolyObjects[i]); @@ -3327,8 +3340,6 @@ FUNCINLINE static ATTRINLINE void P_ArchiveMisc(savebuffer_t *save) else WRITEINT16(save->p, gamemap); - lastmapsaved = gamemap; - WRITEUINT16(save->p, (botskin ? (emeralds|(1<<10)) : emeralds)+357); WRITESTRINGN(save->p, timeattackfolder, sizeof(timeattackfolder)); } @@ -3352,8 +3363,6 @@ FUNCINLINE static ATTRINLINE void P_UnArchiveSPGame(savebuffer_t *save, INT16 ma if (!mapheaderinfo[gamemap-1]) P_AllocMapHeader(gamemap-1); - lastmapsaved = gamemap; - tokenlist = 0; token = 0; @@ -3533,7 +3542,7 @@ static void P_ReloadSaveLevelData(void) li->firsttag = spawnli->firsttag; li->nexttag = spawnli->nexttag; - if (li->sidenum[0] != 0xffff) + if (li->sidenum[0] != NO_INDEX) { si = &sides[li->sidenum[0]]; spawnsi = &spawnsides[li->sidenum[0]]; @@ -3544,7 +3553,7 @@ static void P_ReloadSaveLevelData(void) si->midtexture = spawnsi->midtexture; } - if (li->sidenum[1] != 0xffff) + if (li->sidenum[1] != NO_INDEX) { si = &sides[li->sidenum[1]]; spawnsi = &spawnsides[li->sidenum[1]]; @@ -3611,8 +3620,11 @@ FUNCINLINE static ATTRINLINE boolean P_NetUnArchiveMisc(savebuffer_t *save, bool if (!P_SetupLevel(true, reloading)) { CONS_Alert(CONS_ERROR, M_GetText("Can't load the level!\n")); + P_FreeCorruptMapWarnings(); return false; } + + P_PrintCorruptMapWarnings(); } else { diff --git a/src/p_saveg.h b/src/p_saveg.h index 9a0e26c39..5aaece4e9 100644 --- a/src/p_saveg.h +++ b/src/p_saveg.h @@ -24,8 +24,8 @@ typedef struct { UINT8 skincolor; - UINT8 skin; - UINT8 botskin; + skinnum_t skin; + skinnum_t botskin; UINT8 botcolor; INT32 score; INT32 lives; diff --git a/src/p_setup.c b/src/p_setup.c index b7b8f03d5..2201c0b9f 100644 --- a/src/p_setup.c +++ b/src/p_setup.c @@ -117,6 +117,7 @@ line_t *spawnlines = NULL; side_t *spawnsides = NULL; INT32 numstarposts = 0; boolean levelloading = false; +UINT8 levelfadecol = 120; virtres_t *curmapvirt = NULL; @@ -179,7 +180,7 @@ FUNCNORETURN static ATTRNORETURN void CorruptMapError(const char *msg) // don't use va() because the calling function probably uses it char mapnum[10]; - sprintf(mapnum, "%hd", gamemap); + snprintf(mapnum, sizeof(mapnum), "%hd", gamemap); CON_LogMessage("Map "); CON_LogMessage(mapnum); CON_LogMessage(" is corrupt: "); @@ -188,6 +189,57 @@ FUNCNORETURN static ATTRNORETURN void CorruptMapError(const char *msg) I_Error("Invalid or corrupt map.\nLook in log file or text console for technical details."); } +static char **mapwarnings = NULL; +static size_t nummapwarnings = 0; + +// collect map errors we can fix clientside +// we then can print em when the map finishes loading +// so they actually appear and raise awareness shits fucked +// see G_DoLoadLevel as to why :chaosleep: +static void CorruptMapWarning(const char *msg) +{ +#ifdef PARANOIA + // just error out + I_Error("%sThis WILL crash Vanilla clients!\n", msg); +#endif + nummapwarnings++; + mapwarnings = Z_Realloc(mapwarnings, nummapwarnings * sizeof(*mapwarnings), PU_STATIC, NULL); + mapwarnings[nummapwarnings-1] = Z_StrDup(msg); +} + +void P_PrintCorruptMapWarnings(void) +{ + size_t i; + + if (!nummapwarnings) + return; + + for (i = 0; i < nummapwarnings; i++) + { + CONS_Alert(CONS_ERROR, "%sAttempting to fix... This WILL crash Vanilla clients!\n", mapwarnings[i]); + } + + P_FreeCorruptMapWarnings(); +} + +void P_FreeCorruptMapWarnings(void) +{ + size_t i; + + if (!nummapwarnings) + return; + + for (i = 0; i < nummapwarnings; i++) + { + Z_Free(mapwarnings[i]); + mapwarnings[i] = NULL; + } + + Z_Free(mapwarnings); + mapwarnings = NULL; + nummapwarnings = 0; +} + #define NUMLAPS_DEFAULT 3 static void P_ClearMapHeaderLighting(mapheader_lighting_t *lighting) @@ -214,12 +266,10 @@ static void P_ClearSingleMapHeaderInfo(INT16 i) mapheaderinfo[num]->actnum[0] = '\0'; mapheaderinfo[num]->typeoflevel = 0; mapheaderinfo[num]->nextlevel = (INT16)(i + 1); - snprintf(mapheaderinfo[num]->musname, 7, "%sM", G_BuildMapName(i)); - mapheaderinfo[num]->musname[6] = 0; + snprintf(mapheaderinfo[num]->musname, sizeof(mapheaderinfo[num]->musname), "%sM", G_BuildMapName(i)); + mapheaderinfo[num]->musname[sizeof(mapheaderinfo[num]->musname)-1] = 0; mapheaderinfo[num]->mustrack = 0; mapheaderinfo[num]->muspos = 0; - mapheaderinfo[num]->musinterfadeout = 0; - mapheaderinfo[num]->musintername[0] = '\0'; mapheaderinfo[num]->forcecharacter[0] = '\0'; mapheaderinfo[num]->weather = 0; mapheaderinfo[num]->skynum = 1; @@ -237,16 +287,10 @@ static void P_ClearSingleMapHeaderInfo(INT16 i) mapheaderinfo[num]->numlaps = NUMLAPS_DEFAULT; mapheaderinfo[num]->unlockrequired = -1; mapheaderinfo[num]->levelselect = 0; - mapheaderinfo[num]->bonustype = 0; - mapheaderinfo[num]->saveoverride = SAVE_DEFAULT; mapheaderinfo[num]->levelflags = 0; mapheaderinfo[num]->menuflags = (mainwads ? 0 : LF2_EXISTSHACK); // see p_setup.c - prevents replacing maps in addons with easier versions - // TODO grades support for delfile (pfft yeah right) - P_DeleteGrades(num); - // SRB2Kart - //mapheaderinfo[num]->automap = false; mapheaderinfo[num]->mobj_scale = FRACUNIT; mapheaderinfo[num]->customopts = NULL; @@ -266,121 +310,23 @@ void P_AllocMapHeader(INT16 i) if (!mapheaderinfo[i]) { mapheaderinfo[i] = Z_Malloc(sizeof(mapheader_t), PU_STATIC, NULL); - mapheaderinfo[i]->grades = NULL; } P_ClearSingleMapHeaderInfo(i + 1); } -/** NiGHTS Grades are a special structure, - * we initialize them here. - * - * \param i Index of header to allocate grades for - * \param mare The mare we're adding grades for - * \param grades the string from DeHackEd, we work with it ourselves - */ -void P_AddGradesForMare(INT16 i, UINT8 mare, char *gtext) -{ - INT32 g; - char *spos = gtext; - - CONS_Debug(DBG_SETUP, "Map %d Mare %d: ", i+1, (UINT16)mare+1); - - if (mapheaderinfo[i]->numGradedMares < mare+1) - { - mapheaderinfo[i]->numGradedMares = mare+1; - mapheaderinfo[i]->grades = Z_Realloc(mapheaderinfo[i]->grades, sizeof(nightsgrades_t) * mapheaderinfo[i]->numGradedMares, PU_STATIC, NULL); - } - - for (g = 0; g < 6; ++g) - { - // Allow "partial" grading systems - if (spos != NULL) - { - mapheaderinfo[i]->grades[mare].grade[g] = atoi(spos); - CONS_Debug(DBG_SETUP, "%u ", atoi(spos)); - // Grab next comma - spos = strchr(spos, ','); - if (spos) - ++spos; - } - else - { - // Grade not reachable - mapheaderinfo[i]->grades[mare].grade[g] = UINT32_MAX; - } - } - - CONS_Debug(DBG_SETUP, "\n"); -} - -/** And this removes the grades safely. - * - * \param i The header to remove grades from - */ -void P_DeleteGrades(INT16 i) -{ - if (mapheaderinfo[i]->grades) - Z_Free(mapheaderinfo[i]->grades); - - mapheaderinfo[i]->grades = NULL; - mapheaderinfo[i]->numGradedMares = 0; -} - -/** And this fetches the grades - * - * \param pscore The player's score. - * \param map The game map. - * \param mare The mare to test. - */ -UINT8 P_GetGrade(UINT32 pscore, INT16 map, UINT8 mare) -{ - INT32 i; - - // Determining the grade - if (mapheaderinfo[map-1] && mapheaderinfo[map-1]->grades && mapheaderinfo[map-1]->numGradedMares >= mare + 1) - { - INT32 pgrade = 0; - for (i = 0; i < 6; ++i) - { - if (pscore >= mapheaderinfo[map-1]->grades[mare].grade[i]) - ++pgrade; - } - - return (UINT8)pgrade; - } - - return 0; -} - -UINT8 P_HasGrades(INT16 map, UINT8 mare) -{ - // Determining the grade - // Mare 0 is treated as overall and is true if ANY grades exist - return (mapheaderinfo[map-1] && mapheaderinfo[map-1]->grades - && (mare == 0 || mapheaderinfo[map-1]->numGradedMares >= mare)); -} - -UINT32 P_GetScoreForGrade(INT16 map, UINT8 mare, UINT8 grade) -{ - // Get the score for the grade... if it exists - if (grade == GRADE_F || grade > GRADE_S || !P_HasGrades(map, mare)) return 0; - - return mapheaderinfo[map-1]->grades[mare].grade[grade-1]; -} - // Loads the vertexes for a level. FUNCINLINE static ATTRINLINE void P_LoadVertices(UINT8 *data) { - mapvertex_t *ml = (mapvertex_t *)data; - vertex_t *li = vertexes; + mapvertex_t *mv = (mapvertex_t *)data; + vertex_t *v = vertexes; size_t i; // Copy and convert vertex coordinates, internal representation as fixed. - for (i = 0; i < numvertexes; i++, li++, ml++) + for (i = 0; i < numvertexes; i++, v++, mv++) { - li->x = SHORT(ml->x)<y = SHORT(ml->y)<x = SHORT(mv->x)<y = SHORT(mv->y)<v1->x - li->v2->x), (li->v1->y - li->v2->y)) - ANGLE_90; light = FixedMul(FINECOSINE(liAngle >> ANGLETOFINESHIFT), FINECOSINE(maplighting.angle >> ANGLETOFINESHIFT)) - + FixedMul(FINESINE(liAngle >> ANGLETOFINESHIFT), FINESINE(maplighting.angle >> ANGLETOFINESHIFT)); + + FixedMul(FINESINE(liAngle >> ANGLETOFINESHIFT), FINESINE(maplighting.angle >> ANGLETOFINESHIFT)); light = (light + FRACUNIT) / 2; } else @@ -511,10 +457,10 @@ static void P_SetupDirectionalLight(void) if (gamemap != oldmap || encoremode != oldencore || reinitmaplight) { - lighting->light_contrast = M_RandomRange(0, 58); + lighting->light_contrast = (UINT8)M_RandomRange(0, 58); lighting->sprite_backlight = 0; - lighting->use_light_angle = M_RandomRange(0, 1); // either on or off - lighting->light_angle = M_RandomRange(-382, 382); + lighting->use_light_angle = (boolean)M_RandomRange(0, 1); // either on or off + lighting->light_angle = (angle_t)M_RandomRange(-382, 382); reinitmaplight = false; } @@ -533,44 +479,128 @@ static void P_SetupDirectionalLight(void) static void P_LoadSegs(UINT8 *data) { INT32 rawlinedef, rawside; - mapseg_t *ml = (mapseg_t*)data; - seg_t *li = segs; + mapseg_t *ms = (mapseg_t*)data; + seg_t *seg = segs; line_t *ldef; size_t i; // Set map lighting settings. P_SetupDirectionalLight(); - for (i = 0; i < numsegs; i++, li++, ml++) + for (i = 0; i < numsegs; i++, seg++, ms++) { - li->v1 = &vertexes[SHORT(ml->v1)]; - li->v2 = &vertexes[SHORT(ml->v2)]; + INT16 v1, v2; + + v1 = SHORT(ms->v1); + v2 = SHORT(ms->v2); + + // e6y + // moved down for additional checks to avoid overflow + // if wrong vertexe's indexes are in SEGS lump + // see below for more detailed information + + seg->angle = (SHORT(ms->angle)) << FRACBITS; + seg->offset = (SHORT(ms->offset)) << FRACBITS; + + rawlinedef = SHORT(ms->linedef); + + //e6y: check for wrong indexes + if ((unsigned)rawlinedef >= numlines) + { + I_Error("P_LoadSegs: seg %s references a non-existent linedef %d", sizeu1(i), (unsigned)rawlinedef); + } + + ldef = &lines[rawlinedef]; + seg->linedef = ldef; + rawside = SHORT(ms->side); + + //e6y: fix wrong side index + if (rawside != 0 && rawside != 1) + { + CorruptMapWarning(va("P_LoadSegs: seg %s contains wrong side index %d.\n", sizeu1(i), rawside)); + rawside = 1; + } + + //e6y: check for wrong indexes + if (ldef->sidenum[rawside] >= numsides) + { + I_Error("P_LoadSegs: linedef %d for seg %s references a non-existent sidedef %d", rawlinedef, sizeu1(i), ldef->sidenum[rawside]); + } + + seg->side = rawside; + + seg->sidedef = &sides[ldef->sidenum[rawside]]; + + /* cph 2006/09/30 - our frontsector can be the second side of the + * linedef, so must check for NO_INDEX in case we are incorrectly + * referencing the back of a 1S line */ + if (ldef->sidenum[rawside] == NO_INDEX) + { + CorruptMapWarning(va("P_LoadSegs: front of seg %s has no sidedef\n", sizeu1(i))); + seg->frontsector = NULL; + } + else + { + seg->frontsector = sides[ldef->sidenum[rawside]].sector; + } + + if (ldef->flags & ML_TWOSIDED) + { + if (ldef->sidenum[rawside^1] == NO_INDEX) + { + CorruptMapWarning(va("P_LoadSegs: back of seg %s has no sidedef while being marked as double sided\n", sizeu1(i))); + seg->backsector = NULL; + } + else + { + seg->backsector = sides[ldef->sidenum[rawside^1]].sector; + } + } + + // e6y + // check and fix wrong references to non-existent vertexes + // see e1m9 @ NIVELES.WAD + // http://www.doomworld.com/idgames/index.php?id=12647 + if ((unsigned)v1 >= numvertexes || (unsigned)v2 >= numvertexes) + { + if ((unsigned)v1 >= numvertexes) + CorruptMapWarning(va("P_LoadSegs: seg %s references a non-existent vertex %d\n", sizeu1(i), v1)); + if ((unsigned)v2 >= numvertexes) + CorruptMapWarning(va("P_LoadSegs: seg %s references a non-existent vertex %d\n", sizeu1(i), v2)); + + if (seg->sidedef == &sides[seg->linedef->sidenum[0]]) + { + seg->v1 = lines[ms->linedef].v1; + seg->v2 = lines[ms->linedef].v2; + } + else + { + seg->v1 = lines[ms->linedef].v2; + seg->v2 = lines[ms->linedef].v1; + } + } + else + { + seg->v1 = &vertexes[v1]; + seg->v2 = &vertexes[v2]; + } + #ifdef HWRENDER if (rendermode == render_opengl) { - li->fv1.x = FixedToFloat(li->v1->x); - li->fv1.y = FixedToFloat(li->v1->y); - //li->fv1.z = FixedToFloat(li->v1->z); // z is unused in gl + seg->fv1.x = FixedToFloat(seg->v1->x); + seg->fv1.y = FixedToFloat(seg->v1->y); + //seg->fv1.z = FixedToFloat(seg->v1->z); // z is unused in gl - li->fv2.x = FixedToFloat(li->v2->x); - li->fv2.y = FixedToFloat(li->v2->y); - //li->fv2.z = FixedToFloat(li->v2->z); + seg->fv2.x = FixedToFloat(seg->v2->x); + seg->fv2.y = FixedToFloat(seg->v2->y); + //seg->fv2.z = FixedToFloat(seg->v2->z); } #endif - li->length = P_SegLength(li); - li->angle = (SHORT(ml->angle))<offset = (SHORT(ml->offset))<linedef); - ldef = &lines[rawlinedef]; - li->linedef = ldef; - li->side = rawside = SHORT(ml->side); - li->sidedef = &sides[ldef->sidenum[rawside]]; - li->frontsector = sides[ldef->sidenum[rawside]].sector; - if (ldef->flags & ML_TWOSIDED) - li->backsector = sides[ldef->sidenum[rawside^1]].sector; + seg->length = P_SegLength(seg); - P_UpdateSegLightOffset(li); + P_UpdateSegLightOffset(seg); } } @@ -588,10 +618,6 @@ FUNCINLINE static ATTRINLINE void P_LoadSubsectors(void *data) } } -// -// P_LoadSectors -// - // // levelflats // @@ -643,13 +669,17 @@ static void P_CheckCyanFlat(levelflat_t *levelflat) const char *flatname = W_CheckNameForNum(levelflat->lumpnum); // hack for gba rainbow roads cyan floors - if (UNLIKELY(memcmp(flatname, "GBA_RRF5", 8) == 0 && flatname[8] == 0)) + if (UNLIKELY(flatname && memcmp(flatname, "GBA_RRF5", 8) == 0 && flatname[8] == 0)) { levelflat->cyan = false; return; } const UINT8 *flat = R_GetFlat(levelflat->lumpnum); + + if (!flat) + return; + const size_t size = W_LumpLength(levelflat->lumpnum); for (size_t steppy = 0; steppy < size; steppy++) @@ -769,6 +799,10 @@ INT32 P_CheckLevelFlat(const char *flatname) return (INT32)i; } +// +// P_LoadSectors +// + static const sector_t sector_default = { .nexttag = -1, .firsttag = -1, @@ -844,7 +878,33 @@ static void P_LoadNodes(UINT8 *data) for (j = 0; j < 2; j++) { - no->children[j] = SHORT(mn->children[j]); + UINT16 child; + + child = SHORT(mn->children[j]); + + if (child & NF_SUBSECTOR) + { + // Convert to extended type + child &= ~NF_SUBSECTOR; + + // haleyjd 11/06/10: check for invalid subsector reference + if (child >= numsubsectors) + { + CorruptMapWarning(va("P_LoadNodes: BSP tree %s references invalid subsector %d\n", sizeu1(i), child)); + child = 0; + } + + child |= NF_SUBSECTOR; + } + else if (child >= numnodes) + { + CorruptMapWarning(va("P_LoadNodes: BSP node %s references invalid node.\n", sizeu1(i))); + //I_Error("P_LoadNodes: BSP node %d references invalid node %d.\n", sizeu1(i), Index(((node_t *)no->children[j]))); + child = 0; + } + + no->children[j] = child; + for (k = 0; k < 4; k++) no->bbox[j][k] = SHORT(mn->bbox[j][k])<x<y<z<type) + if (mt->type == 1700 || // MT_AXIS + mt->type == 1701 || // MT_AXISTRANSFER + mt->type == 1702) // MT_AXISTRANSFERLINE { - case 1700: // MT_AXIS - case 1701: // MT_AXISTRANSFER - case 1702: // MT_AXISTRANSFERLINE - mt->mobj = NULL; - P_SpawnMapThing(mt); - break; - default: - break; + mt->mobj = NULL; + P_SpawnMapThing(mt); } } for (i = 0, mt = mapthings; i < nummapthings; i++, mt++) { - sector_t *mtsector = R_PointInSubsector((mt->x << FRACBITS), (mt->y << FRACBITS))->sector; + sector_t *mtsector; + + // srb2kart - ignore rings, coins and item patterns! + if (mt->type == 300 || mt->type == 308 || mt->type == 309 || + (mt->type >= 600 && mt->type <= 609) || + mt->type == 1706 || mt->type == 1800) + { + mt->mobj = NULL; + continue; + } + + mtsector = R_PointInSubsector((mt->x << FRACBITS), (mt->y << FRACBITS))->sector; // Z for objects mt->z = (INT16)(P_GetSectorFloorZAt(mtsector, (mt->x << FRACBITS), (mt->y << FRACBITS))) >> FRACBITS; - if (mt->type == 1700 // MT_AXIS - || mt->type == 1701 // MT_AXISTRANSFER - || mt->type == 1702) // MT_AXISTRANSFERLINE + if (mt->type == 1700 || // MT_AXIS + mt->type == 1701 || // MT_AXISTRANSFER + mt->type == 1702) // MT_AXISTRANSFERLINE + { continue; // These were already spawned + } + + mt->mobj = NULL; + + // spawn hoops + if (mt->type == 1705 || mt->type == 1713) + { + // Check for spawnhoops here so the hoops don't spawn ghost variants for players joining a netgame mid-level + // ...It's a long story. + if (spawnhoops) + { + // Z for objects Tails 05-26-2002 + mt->z = (INT16)(mtsector->floorheight >> FRACBITS); + + P_SpawnHoops(mt); + } + + continue; + } if (mt->type == mobjinfo[MT_RANDOMITEM].doomednum) nummapboxes++; - mt->mobj = NULL; + // Everything else P_SpawnMapThing(mt); } // random emeralds for hunt if (numhuntemeralds) - { - INT32 emer1, emer2, emer3; - INT32 timeout = 0; // keeps from getting stuck - - emer1 = emer2 = emer3 = 0; - - //increment spawn numbers because zero is valid. - emer1 = (P_RandomKey(numhuntemeralds)) + 1; - while (timeout++ < 100) - { - emer2 = (P_RandomKey(numhuntemeralds)) + 1; - - if (emer2 != emer1) - break; - } - - timeout = 0; - while (timeout++ < 100) - { - emer3 = (P_RandomKey(numhuntemeralds)) + 1; - - if (emer3 != emer2 && emer3 != emer1) - break; - } - - //decrement spawn values to the actual number because zero is valid. - if (emer1) - P_SpawnMobj(huntemeralds[emer1 - 1]->x<y<z<x<y<z<x<y<z<type == 300 || mt->type == 308 || mt->type == 309 - || mt->type == 1706 || (mt->type >= 600 && mt->type <= 609) - || mt->type == 1705 || mt->type == 1713 || mt->type == 1800) - { - mt->mobj = NULL; - - // Z for objects Tails 05-26-2002 - mt->z = (INT16)(R_PointInSubsector(mt->x << FRACBITS, mt->y << FRACBITS)->sector->floorheight>>FRACBITS); - - P_SpawnHoops(mt); - } - } + P_SpawnEmeraldHunt(); } static void P_SpawnEmblems(boolean loademblems) @@ -987,22 +1059,22 @@ static void P_SpawnEmblems(boolean loademblems) for (i = 0; i < numemblems; i++) { - if (emblemlocations[i].level != gamemap || emblemlocations[i].type > ET_SKIN) + const emblem_t *emblemlocation = &emblemlocations[i]; + + if (emblemlocation->level != gamemap || emblemlocation->type > ET_SKIN) continue; - emblemmobj = P_SpawnMobj(emblemlocations[i].x<x<y<z<= 'A' && emblemlocations[i].sprite <= 'Z'); - P_SetMobjStateNF(emblemmobj, emblemmobj->info->spawnstate + (emblemlocations[i].sprite - 'A')); + I_Assert(emblemlocation->sprite >= 'A' && emblemlocation->sprite <= 'Z'); + P_SetMobjStateNF(emblemmobj, emblemmobj->info->spawnstate + (emblemlocation->sprite - 'A')); emblemmobj->health = i+1; color = M_GetEmblemColor(&emblemlocations[i]); emblemmobj->color = (UINT8)color; - if (emblemlocations[i].collected - || (emblemlocations[i].type == ET_SKIN && emblemlocations[i].var != players[0].skin)) + if (emblemlocation->collected || (emblemlocation->type == ET_SKIN && emblemlocation->var != players[0].skin)) { P_UnsetThingPosition(emblemmobj); emblemmobj->flags |= MF_NOCLIP; @@ -1022,7 +1094,7 @@ void P_WriteThings(lumpnum_t lumpnum) size_t i, length; mapthing_t *mt; UINT8 *data; - savebuffer_t save = {0}; + savebuffer_t save = {}; INT16 temp; data = W_CacheLumpNum(lumpnum, PU_LEVEL); @@ -1107,9 +1179,9 @@ static void P_InitializeLinedef(line_t *ld) // cph 2002/07/20 - these errors are fatal if not fixed, so apply them for (j = 0; j < 2; j++) { - if (ld->sidenum[j] != 0xffff && ld->sidenum[j] >= (UINT16)numsides) + if (ld->sidenum[j] != NO_INDEX && ld->sidenum[j] >= (UINT16)numsides) { - ld->sidenum[j] = 0xffff; + ld->sidenum[j] = NO_INDEX; CONS_Debug(DBG_SETUP, "P_InitializeLinedef: Linedef %s has out-of-range sidedef number\n", sizeu1((size_t)(ld - lines))); } } @@ -1117,23 +1189,24 @@ static void P_InitializeLinedef(line_t *ld) ld->firsttag = ld->nexttag = -1; // killough 11/98: fix common wad errors (missing sidedefs): - if (ld->sidenum[0] == 0xffff) + if (ld->sidenum[0] == NO_INDEX) { ld->sidenum[0] = 0; // Substitute dummy sidedef for missing right side // cph - print a warning about the bug CONS_Debug(DBG_SETUP, "P_InitializeLinedef: Linedef %s missing first sidedef\n", sizeu1((size_t)(ld - lines))); } - if ((ld->sidenum[1] == 0xffff) && (ld->flags & ML_TWOSIDED)) + if ((ld->sidenum[1] == NO_INDEX) && (ld->flags & ML_TWOSIDED)) { ld->flags &= ~ML_TWOSIDED; // Clear 2s flag for missing left side // cph - print a warning about the bug CONS_Debug(DBG_SETUP, "P_InitializeLinedef: Linedef %s has two-sided flag set, but no second sidedef\n", sizeu1((size_t)(ld - lines))); } - if (ld->sidenum[0] != 0xffff && ld->special) + // killough 4/4/98: support special sidedef interpretation below + if (ld->sidenum[0] != NO_INDEX && ld->special) sides[ld->sidenum[0]].special = ld->special; - if (ld->sidenum[1] != 0xffff && ld->special) + if (ld->sidenum[1] != NO_INDEX && ld->special) sides[ld->sidenum[1]].special = ld->special; } @@ -1166,10 +1239,10 @@ static void P_LoadLineDefs2(void) for (; i--; ld++) { ld->frontsector = sides[ld->sidenum[0]].sector; //e6y: Can't be -1 here - ld->backsector = ld->sidenum[1] != 0xffff ? sides[ld->sidenum[1]].sector : 0; + ld->backsector = ld->sidenum[1] != NO_INDEX ? sides[ld->sidenum[1]].sector : NULL; // Repeat count for midtexture - if ((ld->flags & ML_EFFECT5) && (ld->sidenum[1] != 0xffff)) + if ((ld->flags & ML_EFFECT5) && (ld->sidenum[1] != NO_INDEX)) { sides[ld->sidenum[0]].repeatcnt = (INT16)(((unsigned)sides[ld->sidenum[0]].textureoffset >> FRACBITS) >> 12); sides[ld->sidenum[0]].textureoffset = (((unsigned)sides[ld->sidenum[0]].textureoffset >> FRACBITS) & 2047) << FRACBITS; @@ -1185,13 +1258,13 @@ static void P_LoadLineDefs2(void) { size_t len = strlen(sides[ld->sidenum[0]].text)+1; - if (ld->sidenum[1] != 0xffff && sides[ld->sidenum[1]].text) + if (ld->sidenum[1] != NO_INDEX && sides[ld->sidenum[1]].text) len += strlen(sides[ld->sidenum[1]].text); ld->text = Z_Malloc(len, PU_LEVEL, NULL); memcpy(ld->text, sides[ld->sidenum[0]].text, strlen(sides[ld->sidenum[0]].text)+1); - if (ld->sidenum[1] != 0xffff && sides[ld->sidenum[1]].text) + if (ld->sidenum[1] != NO_INDEX && sides[ld->sidenum[1]].text) memcpy(ld->text+strlen(ld->text)+1, sides[ld->sidenum[1]].text, strlen(sides[ld->sidenum[1]].text)+1); } break; @@ -1321,14 +1394,14 @@ static void P_LoadSideChangeMusic(boolean firstside, mapsidedef_t *msd, side_t * if (msd->bottomtexture[0] != '-' || msd->bottomtexture[1] != '\0') { - memcpy(process,msd->bottomtexture,8); + memcpy(process, msd->bottomtexture, 8); process[8] = '\0'; sd->bottomtexture = get_number(process); } if (!(msd->midtexture[0] == '-' && msd->midtexture[1] == '\0') || msd->midtexture[1] != '\0') { - memcpy(process,msd->midtexture,8); + memcpy(process, msd->midtexture, 8); process[8] = '\0'; sd->midtexture = get_number(process); } @@ -1338,7 +1411,7 @@ static void P_LoadSideChangeMusic(boolean firstside, mapsidedef_t *msd, side_t * if (firstside || msd->toptexture[0] != '-' || msd->toptexture[1] != '\0') { - memcpy(process,msd->toptexture,8); + memcpy(process, msd->toptexture, 8); process[8] = '\0'; // If they type in O_ or D_ and their music name, just shrug, @@ -1378,7 +1451,7 @@ static void P_LoadSidedefs(void *data) // Colormaps! switch (sd->special) { - case 63: // variable colormap via 242 linedef + case 63: // variable colormap via 242 linedef case 606: //SoM: 4/4/2000: Just colormap transfer // SoM: R_CreateColormap will only create a colormap in software mode... // Perhaps we should just call it instead of doing the calculations here. @@ -1394,26 +1467,26 @@ static void P_LoadSidedefs(void *data) if (msd->toptexture[0] != '-' || msd->toptexture[1] != '\0') { char process[8+1]; - memcpy(process,msd->toptexture,8); + memcpy(process, msd->toptexture, 8); process[8] = '\0'; sd->toptexture = get_number(process); } break; } - case 9: // Mace parameters - case 14: // Bustable block parameters - case 15: // Fan particle spawner parameters + case 9: // Mace parameters + case 14: // Bustable block parameters + case 15: // Fan particle spawner parameters case 425: // Calls P_SetMobjState on calling mobj case 434: // Custom Power case 442: // Calls P_SetMobjState on mobjs of a given type in the tagged sectors { char process[8*3+1]; - memset(process,0,8*3+1); + memset(process, 0, 8*3+1); sd->toptexture = sd->midtexture = sd->bottomtexture = 0; if (msd->toptexture[0] == '-' && msd->toptexture[1] == '\0') break; else - memcpy(process,msd->toptexture,8); + memcpy(process, msd->toptexture, 8); if (msd->midtexture[0] != '-' || msd->midtexture[1] != '\0') memcpy(process+strlen(process), msd->midtexture, 8); if (msd->bottomtexture[0] != '-' || msd->bottomtexture[1] != '\0') @@ -1425,12 +1498,12 @@ static void P_LoadSidedefs(void *data) case 443: // Calls a named Lua function { char process[8*3+1]; - memset(process,0,8*3+1); + memset(process, 0, 8*3+1); sd->toptexture = sd->midtexture = sd->bottomtexture = 0; if (msd->toptexture[0] == '-' && msd->toptexture[1] == '\0') break; else - memcpy(process,msd->toptexture,8); + memcpy(process,msd->toptexture, 8); if (msd->midtexture[0] != '-' || msd->midtexture[1] != '\0') memcpy(process+strlen(process), msd->midtexture, 8); if (msd->bottomtexture[0] != '-' || msd->bottomtexture[1] != '\0') @@ -1731,6 +1804,80 @@ static void P_CreateBlockMap(void) } } +// +// P_VerifyBlockMap +// +// haleyjd 03/04/10: do verification on validity of blockmap. +// +static boolean P_VerifyBlockMap(INT32 count) +{ + // FIXME: should any of this shit be unsinged? + INT32 x, y; + INT32 *maxoffs = blockmaplump + count; + + //skipblstart = true; + + for (y = 0; y < bmapheight; y++) + { + for (x = 0; x < bmapwidth; x++) + { + INT32 offset; + INT32 *list, *tmplist; + INT32 *blockoffset; + + offset = y * bmapwidth + x; + blockoffset = blockmaplump + offset + 4; + + // check that block offset is in bounds + if (blockoffset >= maxoffs) + { + CONS_Alert(CONS_ERROR, "P_VerifyBlockMap: block offset overflow\n"); + return false; + } + + offset = *blockoffset; + + // check that list offset is in bounds + if (offset < 4 || offset >= count) + { + CONS_Alert(CONS_ERROR, "P_VerifyBlockMap: list offset overflow\n"); + return false; + } + + list = blockmaplump + offset; + + //if (*list != 0) + //skipblstart = false; + + // scan forward for a -1 terminator before maxoffs + for (tmplist = list; ; tmplist++) + { + // we have overflowed the lump? + if (tmplist >= maxoffs) + { + CONS_Alert(CONS_ERROR, "P_VerifyBlockMap: open blocklist\n"); + return false; + } + + if (*tmplist == -1) // found -1 + break; + } + + // scan the list for out-of-range linedef indicies in list + for (tmplist = list; *tmplist != -1; tmplist++) + { + if (*tmplist < 0 || *tmplist >= (INT32)numlines) + { + CONS_Alert(CONS_ERROR, "P_VerifyBlockMap: index >= numlines\n"); + return false; + } + } + } + } + + return true; +} + // Split from P_LoadBlockMap for convenience // -- Monster Iestyn 08/01/18 static void P_ReadBlockMapLump(INT16 *wadblockmaplump, size_t count) @@ -1759,7 +1906,7 @@ static void P_ReadBlockMapLump(INT16 *wadblockmaplump, size_t count) // because making both the WAD and PK3 loading code use // the same functions is trickier than it looks for blockmap // -- Monster Iestyn 09/01/18 -static boolean P_LoadRawBlockMap(UINT8 *data, size_t count) +static boolean P_LoadBlockMap(UINT8 *data, size_t count) { if (!count || count >= 0x20000) return false; @@ -1772,9 +1919,20 @@ static boolean P_LoadRawBlockMap(UINT8 *data, size_t count) bmaporgx = blockmaplump[0]<firstline >= numsegs) + { CorruptMapError(va("P_GroupLines: ss->firstline invalid " "(subsector %s, firstline refers to %d of %s)", sizeu1(i), ss->firstline, sizeu2(numsegs))); + } + seg = &segs[ss->firstline]; sidei = (size_t)(seg->sidedef - sides); + if (!seg->sidedef) + { CorruptMapError(va("P_GroupLines: seg->sidedef is NULL " "(subsector %s, firstline is %d)", sizeu1(i), ss->firstline)); + } + if (seg->sidedef - sides < 0 || seg->sidedef - sides > (UINT16)numsides) + { CorruptMapError(va("P_GroupLines: seg->sidedef refers to sidedef %s of %s " "(subsector %s, firstline is %d)", sizeu1(sidei), sizeu2(numsides), sizeu3(i), ss->firstline)); + } + if (!seg->sidedef->sector) + { CorruptMapError(va("P_GroupLines: seg->sidedef->sector is NULL " "(subsector %s, firstline is %d, sidedef is %s)", sizeu1(i), ss->firstline, sizeu1(sidei))); + } + ss->sector = seg->sidedef->sector; } @@ -1886,20 +2057,36 @@ static void P_GroupLines(void) } } - // PK3 version // -- Monster Iestyn 09/01/18 -static void P_LoadReject(UINT8 *data, size_t count) +static void P_LoadReject(UINT8 *data, size_t rejectsize) { - if (!count) // zero length, someone probably used ZDBSP + const size_t neededsize = (numsectors * numsectors + 7) >> 3; + size_t allocsize = rejectsize; + + if (!rejectsize) // zero length, someone probably used ZDBSP { rejectmatrix = NULL; CONS_Debug(DBG_SETUP, "P_LoadReject: REJECT lump has size 0, will not be loaded\n"); } else { - rejectmatrix = Z_Malloc(count, PU_LEVEL, NULL); // allocate memory for the reject matrix - memcpy(rejectmatrix, data, count); // copy the data into it + if (rejectsize < neededsize) + { + CorruptMapWarning(va("P_LoadReject: REJECT is %s byte%s too small. REJECT might be invalid!\n", sizeu1(neededsize - rejectsize), (neededsize - rejectsize) == 1 ? "" : "s")); +#ifdef PHOBOS_BUILD + rejectmatrix = NULL; + return; +#else + // we can pad this and somewhat prevent desyncs + // probs not cool if the reject is from a completely different map + // but whatever + allocsize = neededsize; +#endif + } + + rejectmatrix = Z_Calloc(allocsize, PU_LEVEL, NULL); // allocate memory for the reject matrix + memcpy(rejectmatrix, data, rejectsize); // copy the data into it } } @@ -1916,7 +2103,7 @@ static void P_LoadMapBSP(const virtres_t* virt) if (numsubsectors <= 0) I_Error("Level has no subsectors (did you forget to run it through a nodesbuilder?)"); if (numnodes <= 0) - I_Error("Level has no nodes"); + I_Error("Level has no nodes (does your map have at least 2 sectors?)"); if (numsegs <= 0) I_Error("Level has no segs"); @@ -1937,11 +2124,15 @@ static void P_LoadMapLUT(const virtres_t* virt) // Lookup tables if (virtreject) + { P_LoadReject(virtreject->data, virtreject->size); + } else + { rejectmatrix = NULL; + } - if (!(virtblockmap && P_LoadRawBlockMap(virtblockmap->data, virtblockmap->size))) + if (!(virtblockmap && P_LoadBlockMap(virtblockmap->data, virtblockmap->size))) P_CreateBlockMap(); } @@ -2014,7 +2205,7 @@ void P_SetupLevelSky(INT32 skynum, boolean global) { char skytexname[12]; - sprintf(skytexname, "SKY%d", skynum); + snprintf(skytexname, sizeof(skytexname), "SKY%d", skynum); skytexture = R_TextureNumForName(skytexname); levelskynum = skynum; @@ -2049,7 +2240,6 @@ static void P_LevelInitStuff(boolean reloadinggamestate) // special stage tokens, emeralds, and ring total tokenbits = 0; - runemeraldmanager = false; nummaprings = nummapboxes = numgotboxes = 0; // emerald hunt @@ -2079,10 +2269,10 @@ static void P_LevelInitStuff(boolean reloadinggamestate) stagefailed = false; // earthquake camera - memset(&quake,0,sizeof(struct quake)); + memset(&quake, 0, sizeof(struct quake)); // song credit init - memset(&cursongcredit,0,sizeof(struct cursongcredit)); + memset(&cursongcredit, 0, sizeof(struct cursongcredit)); cursongcredit.trans = NUMTRANSMAPS; for (i = 0; i < MAXPLAYERS; i++) @@ -2176,14 +2366,14 @@ static INT32 P_MakeBufferMD5(const char *buffer, size_t len, void *resblock) memset(resblock, 0x00, 16); return 1; #else - tic_t t = I_GetTime(); + precise_t t = I_GetPreciseTime(); CONS_Debug(DBG_SETUP, "Making MD5\n"); if (md5_buffer(buffer, len, resblock) == NULL) return 1; - CONS_Debug(DBG_SETUP, "MD5 calc took %f seconds\n", (float)(I_GetTime() - t)/NEWTICRATE); + CONS_Debug(DBG_SETUP, "MD5 calc took %f seconds\n", (float)(I_GetPreciseTime() - t)/I_GetPrecisePrecision()); return 0; #endif @@ -2205,10 +2395,10 @@ static void P_MakeMapMD5(virtres_t *virt, void *dest) virtlump_t* virtmthings = vres_Find(virt, "THINGS"); virtlump_t* virtsides = vres_Find(virt, "SIDEDEFS"); - P_MakeBufferMD5((char*)virtlines->data, virtlines->size, linemd5); - P_MakeBufferMD5((char*)virtsectors->data, virtsectors->size, sectormd5); - P_MakeBufferMD5((char*)virtmthings->data, virtmthings->size, thingmd5); - P_MakeBufferMD5((char*)virtsides->data, virtsides->size, sidedefmd5); + P_MakeBufferMD5((char*)virtlines->data, virtlines->size, linemd5); + P_MakeBufferMD5((char*)virtsectors->data, virtsectors->size, sectormd5); + P_MakeBufferMD5((char*)virtmthings->data, virtmthings->size, thingmd5); + P_MakeBufferMD5((char*)virtsides->data, virtsides->size, sidedefmd5); for (i = 0; i < 16; i++) resmd5[i] = (linemd5[i] + sectormd5[i] + thingmd5[i] + sidedefmd5[i]) & 0xFF; @@ -2235,7 +2425,8 @@ static void P_RunLevelScript(const char *scriptname) lumpnum_t lumpnum; char newname[9]; - strlcpy(newname, scriptname, sizeof(newname)); + strncpy(newname, scriptname, sizeof(newname)-1); + newname[sizeof(newname)-1] = '\0'; lumpnum = W_CheckNumForName(newname); @@ -2245,7 +2436,7 @@ static void P_RunLevelScript(const char *scriptname) return; } - COM_BufInsertText(W_CacheLumpNum(lumpnum, PU_CACHE)); + COM_BufInsertTextEx(W_CacheLumpNum(lumpnum, PU_CACHE), W_LumpLength(lumpnum)); } else { @@ -2260,23 +2451,26 @@ static void P_ForceCharacter(const char *forcecharskin) if (netgame) { char skincmd[33]; + if (splitscreen) { - sprintf(skincmd, "skin2 %s\n", forcecharskin); + snprintf(skincmd, sizeof(skincmd), "skin2 %s\n", forcecharskin); CV_Set(&cv_skin2, forcecharskin); + if (splitscreen > 1) { - sprintf(skincmd, "skin3 %s\n", forcecharskin); + snprintf(skincmd, sizeof(skincmd), "skin3 %s\n", forcecharskin); CV_Set(&cv_skin3, forcecharskin); + if (splitscreen > 2) { - sprintf(skincmd, "skin4 %s\n", forcecharskin); + snprintf(skincmd, sizeof(skincmd), "skin4 %s\n", forcecharskin); CV_Set(&cv_skin4, forcecharskin); } } } - sprintf(skincmd, "skin %s\n", forcecharskin); + snprintf(skincmd, sizeof(skincmd), "skin %s\n", forcecharskin); COM_BufAddText(skincmd); } else @@ -2331,7 +2525,9 @@ static void P_LoadRecordGhosts(void) if (!gpath) return; - sprintf(gpath,"%s"PATHSEP"replay"PATHSEP"%s"PATHSEP"%s", srb2home, timeattackfolder, G_BuildMapName(gamemap)); + const char *mapname = G_BuildMapName(gamemap); + + snprintf(gpath, glen, "%s"PATHSEP"replay"PATHSEP"%s"PATHSEP"%s", srb2home, timeattackfolder, mapname); // Best Time ghost if (cv_ghost_besttime.value) @@ -2381,9 +2577,10 @@ static void P_LoadRecordGhosts(void) { lumpnum_t l; UINT8 j = 1; - while (j <= 99 && (l = W_CheckNumForName(va("%sS%02u",G_BuildMapName(gamemap),j))) != LUMPERROR) + + while (j <= 99 && (l = W_CheckNumForName(va("%sS%02u", mapname, j))) != LUMPERROR) { - G_AddGhost(va("%sS%02u",G_BuildMapName(gamemap),j)); + G_AddGhost(va("%sS%02u", mapname, j)); j++; } } @@ -2391,6 +2588,31 @@ static void P_LoadRecordGhosts(void) free(gpath); } +static void P_ResetSpawnpoints(void) +{ + UINT8 i; + + numdmstarts = numredctfstarts = numbluectfstarts = 0; + + // reset the player starts + for (i = 0; i < MAXPLAYERS; i++) + { + playerstarts[i] = NULL; + redctfstarts[i] = NULL; + bluectfstarts[i] = NULL; + } + + for (i = 0; i < MAX_DM_STARTS; i++) + { + deathmatchstarts[i] = NULL; + } + + for (i = 0; i < 2; i++) + { + skyboxmo[i] = NULL; + } +} + static void P_InitCamera(void) { INT32 i; @@ -2400,6 +2622,7 @@ static void P_InitCamera(void) for (i = 0; i <= splitscreen; i++) { + camera[i].postimg = 0; P_SetupCamera(&camera[i]); } @@ -2425,10 +2648,12 @@ static void P_InitMinimapInfo(void) Patch_Free(minimapinfo.minimap_pic); minimapinfo.minimap_pic = NULL; - lumpnum = W_CheckNumForName(va("%sR", G_BuildMapName(gamemap))); + const char *mapname = G_BuildMapName(gamemap); + + lumpnum = W_CheckNumForName(va("%sR", mapname)); if (lumpnum != LUMPERROR) - minimapinfo.minimap_pic = W_CachePatchName(va("%sR", G_BuildMapName(gamemap)), PU_PATCH); + minimapinfo.minimap_pic = W_CachePatchName(va("%sR", mapname), PU_PATCH); minimapinfo.min_x = bsp->bbox[0][BOXLEFT]; minimapinfo.max_x = bsp->bbox[0][BOXRIGHT]; @@ -2497,10 +2722,14 @@ static boolean P_RunSpecialWipe(boolean reloadinggamestate) { // Cancel all d_main.c fadeouts (keep fade in though). if (reloadinggamestate) + { wipegamestate = gamestate; // Don't fade if reloading the gamestate + return false; + } + // Encore mode fade to pink to white // This is handled BEFORE sounds are stopped. - else if (encoremode && !prevencoremode && !demo.rewinding) + if (encoremode && !prevencoremode && !demo.rewinding) { tic_t locstarttime, endtime, nowtime; @@ -2534,6 +2763,8 @@ static boolean P_RunSpecialWipe(boolean reloadinggamestate) // Hold on white for extra effect. while (nowtime < endtime) { + I_HandleInterrupt(); + // wait loop while (!((nowtime = I_GetTime()) - lastwipetic)) { @@ -2556,6 +2787,69 @@ static boolean P_RunSpecialWipe(boolean reloadinggamestate) return false; } +static void P_InitTagGametype(void) +{ + UINT8 i; + INT32 realnumplayers = 0; + INT32 playersactive[MAXPLAYERS]; + + //I just realized how problematic this code can be. + //D_NumPlayers() will not always cover the scope of the netgame. + //What if one player is node 0 and the other node 31? + //The solution? Make a temp array of all players that are currently playing and pick from them. + //Future todo? When a player leaves, shift all nodes down so D_NumPlayers() can be used as intended? + //Also, you'd never have to loop through all 32 players slots to find anything ever again. + for (i = 0; i < MAXPLAYERS; i++) + { + if (playeringame[i] && !players[i].spectator) + { + playersactive[realnumplayers] = i; //stores the player's node in the array. + realnumplayers++; + } + } + + if (!realnumplayers) // this should also fix the dedicated crash bug. You only pick a player if one exists to be picked. + { + CONS_Printf(M_GetText("No player currently available to become IT. Awaiting available players.\n")); + return; + } + + i = P_RandomKey(realnumplayers); + players[playersactive[i]].pflags |= PF_TAGIT; //choose our initial tagger before map starts. + + // Taken and modified from G_DoReborn() + // Remove the player so he can respawn elsewhere. + // first dissasociate the corpse + if (players[playersactive[i]].mo) + P_RemoveMobj(players[playersactive[i]].mo); + + G_SpawnPlayer(playersactive[i], false); //respawn the lucky player in his dedicated spawn location. +} + +static void P_InitGametype(void) +{ + if (modeattacking == ATTACKING_RECORD && !demo.playback) + P_LoadRecordGhosts(); + + if (G_RaceGametype() && server) + { + INT32 numLaps; + const mapheader_t *mapheader = mapheaderinfo[gamemap - 1]; + + if ((netgame || multiplayer) && cv_basenumlaps.value && + (!(mapheader->levelflags & LF_SECTIONRACE) || (mapheader->numlaps > cv_basenumlaps.value))) + numLaps = cv_basenumlaps.value; + else + numLaps = mapheader->numlaps; + + CV_StealthSetValue(&cv_numlaps, numLaps); + } + else if (G_TagGametype()) + { + P_InitTagGametype(); + } +} + static void P_SetupPlayer(void) { INT32 i; @@ -2569,76 +2863,28 @@ static void P_SetupPlayer(void) // Start players with pity shields if possible players[i].pity = -1; + players[i].mo = NULL; + if (!G_RaceGametype()) { - players[i].mo = NULL; G_DoReborn(i); } else // gametype is GT_COOP or GT_RACE { - players[i].mo = NULL; G_SpawnPlayer(i, (players[i].starposttime)); } } } - if (modeattacking == ATTACKING_RECORD && !demo.playback) - P_LoadRecordGhosts(); - - if (G_TagGametype()) - { - INT32 realnumplayers = 0; - INT32 playersactive[MAXPLAYERS]; - - //I just realized how problematic this code can be. - //D_NumPlayers() will not always cover the scope of the netgame. - //What if one player is node 0 and the other node 31? - //The solution? Make a temp array of all players that are currently playing and pick from them. - //Future todo? When a player leaves, shift all nodes down so D_NumPlayers() can be used as intended? - //Also, you'd never have to loop through all 32 players slots to find anything ever again. - for (i = 0; i < MAXPLAYERS; i++) - { - if (playeringame[i] && !players[i].spectator) - { - playersactive[realnumplayers] = i; //stores the player's node in the array. - realnumplayers++; - } - } - - if (realnumplayers) // this should also fix the dedicated crash bug. You only pick a player if one exists to be picked. - { - i = P_RandomKey(realnumplayers); - players[playersactive[i]].pflags |= PF_TAGIT; //choose our initial tagger before map starts. - - // Taken and modified from G_DoReborn() - // Remove the player so he can respawn elsewhere. - // first dissasociate the corpse - if (players[playersactive[i]].mo) - P_RemoveMobj(players[playersactive[i]].mo); - - G_SpawnPlayer(playersactive[i], false); //respawn the lucky player in his dedicated spawn location. - } - else - CONS_Printf(M_GetText("No player currently available to become IT. Awaiting available players.\n")); - - } - else if (G_RaceGametype() && server) - { - INT32 numLaps = ((netgame || multiplayer) && cv_basenumlaps.value - && (!(mapheaderinfo[gamemap - 1]->levelflags & LF_SECTIONRACE) - || (mapheaderinfo[gamemap - 1]->numlaps > cv_basenumlaps.value))) - ? cv_basenumlaps.value - : mapheaderinfo[gamemap - 1]->numlaps; - - CV_StealthSetValue(&cv_numlaps, numLaps); - } + P_InitGametype(); // Start recording replay in multiplayer with a temp filename // Ensure dedis only record a replay if there is a player at the start of the map, otherwise we get invalid replays! if (!demo.playback && multiplayer && D_NumPlayers()) { static char buf[256]; - sprintf(buf, "replay"PATHSEP"online"PATHSEP"%d-%s", (int) (time(NULL)), G_BuildMapName(gamemap)); + + snprintf(buf, sizeof(buf), "replay"PATHSEP"online"PATHSEP"%d-%s", (int)(time(NULL)), G_BuildMapName(gamemap)); I_mkdir(va("%s"PATHSEP"replay", srb2home), 0755); I_mkdir(va("%s"PATHSEP"replay"PATHSEP"online", srb2home), 0755); @@ -2693,7 +2939,8 @@ void P_FreeLevelState(void) } // Clear pointers that would be left dangling by the purge - R_FlushTranslationColormapCache(); + // Pointers are now PU_STATIC so they won't be freed :) + //R_FlushTranslationColormapCache(); #ifdef HWRENDER // Free GPU textures before freeing patches. @@ -2741,7 +2988,7 @@ boolean P_SetupLevel(boolean fromnetsave, boolean reloadinggamestate) INT32 i; boolean ranspecialwipe = false; lumpnum_t encoreLump = LUMPERROR; - UINT8 levelfadecol; + const mapheader_t *mapheader = mapheaderinfo[gamemap - 1]; midgamejoin = fromnetsave; // makes dynslopes run in P_Ticker to avoid synch issues and other stuff @@ -2749,7 +2996,7 @@ boolean P_SetupLevel(boolean fromnetsave, boolean reloadinggamestate) levelloading = true; // This is needed. Don't touch. - maptol = mapheaderinfo[gamemap-1]->typeoflevel; + maptol = mapheader->typeoflevel; CON_Drawer(); // let the user know what we are going to do I_FinishUpdate(); // page flip or blit buffer @@ -2760,17 +3007,17 @@ boolean P_SetupLevel(boolean fromnetsave, boolean reloadinggamestate) // Clear CECHO messages HU_ClearCEcho(); - if (mapheaderinfo[gamemap-1]->runsoc[0] != '#') - P_RunSOC(mapheaderinfo[gamemap-1]->runsoc); + if (mapheader->runsoc[0] != '#') + P_RunSOC(mapheader->runsoc); - if (cv_runscripts.value && mapheaderinfo[gamemap-1]->scriptname[0] != '#') - P_RunLevelScript(mapheaderinfo[gamemap-1]->scriptname); + if (cv_runscripts.value && mapheader->scriptname[0] != '#') + P_RunLevelScript(mapheader->scriptname); P_LevelInitStuff(reloadinggamestate); - if (mapheaderinfo[gamemap-1]->forcecharacter[0] != '\0' - && atoi(mapheaderinfo[gamemap-1]->forcecharacter) != 255) - P_ForceCharacter(mapheaderinfo[gamemap-1]->forcecharacter); + if (mapheader->forcecharacter[0] != '\0' + && atoi(mapheader->forcecharacter) != 255) + P_ForceCharacter(mapheader->forcecharacter); // Initial height of PointOfView // will be set by player think. @@ -2819,11 +3066,11 @@ boolean P_SetupLevel(boolean fromnetsave, boolean reloadinggamestate) // Don't include these in the fade! char tx[64]; V_DrawSmallString(1, 191, V_ALLOWLOWERCASE, M_GetText("Speeding off to...")); - snprintf(tx, 63, "%s%s%s", - mapheaderinfo[gamemap-1]->lvlttl, - (strlen(mapheaderinfo[gamemap-1]->zonttl) > 0) ? va(" %s",mapheaderinfo[gamemap-1]->zonttl) : // SRB2kart - ((mapheaderinfo[gamemap-1]->levelflags & LF_NOZONE) ? "" : " Zone"), - (strlen(mapheaderinfo[gamemap-1]->actnum) > 0) ? va(", Act %s",mapheaderinfo[gamemap-1]->actnum) : ""); + snprintf(tx, sizeof(tx)-1, "%s%s%s", + mapheader->lvlttl, + (strlen(mapheader->zonttl) > 0) ? va(" %s",mapheader->zonttl) : // SRB2kart + ((mapheader->levelflags & LF_NOZONE) ? "" : " Zone"), + (strlen(mapheader->actnum) > 0) ? va(", Act %s",mapheader->actnum) : ""); V_DrawSmallString(1, 195, V_ALLOWLOWERCASE, tx); I_UpdateNoVsync(); }*/ @@ -2842,26 +3089,26 @@ boolean P_SetupLevel(boolean fromnetsave, boolean reloadinggamestate) curmapvirt = vres_GetMap(lastloadedmaplumpnum); encoreLump = W_CheckNumForName(va("%s%c", maplumpname, (encoremode ? 'E' : 'T'))); - R_ReInitColormaps(mapheaderinfo[gamemap-1]->palette, encoreLump); + R_ReInitColormaps(mapheader->palette, encoreLump); CON_SetupBackColormap(); // SRB2 determines the sky texture to be used depending on the map header. - P_SetupLevelSky(mapheaderinfo[gamemap-1]->skynum, true); + P_SetupLevelSky(mapheader->skynum, true); - numdmstarts = numredctfstarts = numbluectfstarts = 0; + P_ResetSpawnpoints(); - // reset the player starts - memset(playerstarts, 0, sizeof(playerstarts)); - memset(skyboxmo, 0, sizeof(skyboxmo)); - - P_MapStart(); + P_MapStart(); // tmthing can be used starting from this point P_LoadMapFromFile(); P_ResetDynamicSlopes(); - P_SpawnMapThings(); + // Pre-calculate this lookup, because it was wasting + // a shit ton of time loading mobj thinkers. + CalculateDoomednumToMobjtype(); + + P_SpawnMapThings(!fromnetsave); P_SpawnEmblems(!fromnetsave); @@ -2871,7 +3118,7 @@ boolean P_SetupLevel(boolean fromnetsave, boolean reloadinggamestate) if (!playerstarts[numcoopstarts]) break; - globalweather = mapheaderinfo[gamemap-1]->weather; + globalweather = mapheader->weather; // set up world state P_SpawnSpecials(fromnetsave, reloadinggamestate); @@ -2918,7 +3165,7 @@ boolean P_SetupLevel(boolean fromnetsave, boolean reloadinggamestate) // clear special respawning que iquehead = iquetail = 0; - P_MapEnd(); + P_MapEnd(); // tmthing is no longer needed from this point onwards // Remove the loading shit from the screen if (rendermode != render_none && !reloadinggamestate) @@ -2949,9 +3196,15 @@ boolean P_SetupLevel(boolean fromnetsave, boolean reloadinggamestate) savedata.lives = 0; } - // assume the skybox is visible on level load. - skyVisible = true; - memset(skyVisiblePerPlayer, true, sizeof(skyVisiblePerPlayer)); + if (!reloadinggamestate) + { + // assume the skybox is visible on level load. + skyVisible = true; + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) + { + skyVisiblePerPlayer[i] = true; + } + } if (!fromnetsave) // uglier hack { // to make a newly loaded level start on the second frame. @@ -2971,14 +3224,18 @@ boolean P_SetupLevel(boolean fromnetsave, boolean reloadinggamestate) LUA_HookInt(gamemap, HOOK(MapLoad)); } - if (rendermode != render_none && !reloadinggamestate) + // reloading gamestate, stop here. + if (reloadinggamestate) + return true; + + G_AddMapToBuffer(gamemap-1); + + if (rendermode != render_none) { R_ResetViewInterpolation(0); R_UpdateMobjInterpolators(); } - G_AddMapToBuffer(gamemap-1); - G_ResetDeviceLED(); return true; @@ -3029,7 +3286,7 @@ static size_t sreplaces = 0, mreplaces = 0, digmreplaces = 0; static boolean P_CheckSoundReplacements(UINT16 wadnum, char *name, size_t i) { size_t j; - lumpnum_t lumpnum = (i|(wadnum<<16)); + lumpnum_t lumpnum = (i | (wadnum<<16)); if (name[0] == 'D') { @@ -3037,8 +3294,8 @@ static boolean P_CheckSoundReplacements(UINT16 wadnum, char *name, size_t i) { for (j = 1; j < NUMSFX; j++) { - if (S_sfx[j].name && !strnicmp(S_sfx[j].name, name + 2, 6) - && (S_sfx[j].lumpnum != lumpnum) && (S_sfx[j].lumpnum != LUMPERROR)) + if ((S_sfx[j].lumpnum != lumpnum) && (S_sfx[j].lumpnum != LUMPERROR) && + S_sfx[j].name && !strnicmp(S_sfx[j].name, name + 2, 6)) { // the sound will be reloaded when needed, // since sfx->data will be NULL @@ -3159,6 +3416,17 @@ UINT16 P_PartialAddWadFile(const char *wadfilename, boolean local) sreplaces = mreplaces = digmreplaces = 0; + if (local) + { + // check if someone tries to load maps locally lol + // do this here so we can skip loading the file anyways + if (W_CheckAutoLoadContainsMap(wadfilename)) + { + CONS_Alert(CONS_WARNING, "addilelocal: locally added file %s contains map data, this WILL cause crashes and desynchs! not added.\n", wadfilename); + return UINT16_MAX; + } + } + if ((numlumps = W_InitFile(wadfilename, local, false)) == INT16_MAX) { refreshdirmenu |= REFRESHDIR_NOTLOADED; @@ -3189,12 +3457,15 @@ UINT16 P_PartialAddWadFile(const char *wadfilename, boolean local) allvotereplaced = true; } - if (!devparm && sreplaces) - CONS_Printf(M_GetText("%s sounds replaced\n"), sizeu1(sreplaces)); - if (!devparm && mreplaces) - CONS_Printf(M_GetText("%s midi musics ignored\n"), sizeu1(mreplaces)); - if (!devparm && digmreplaces) - CONS_Printf(M_GetText("%s digital musics replaced\n"), sizeu1(digmreplaces)); + if (!devparm) + { + if (sreplaces) + CONS_Printf(M_GetText("%s sounds replaced\n"), sizeu1(sreplaces)); + if (mreplaces) + CONS_Printf(M_GetText("%s midi musics ignored\n"), sizeu1(mreplaces)); + if (digmreplaces) + CONS_Printf(M_GetText("%s digital musics replaced\n"), sizeu1(digmreplaces)); + } if (!mapsadded) CONS_Printf(M_GetText("No maps added\n")); diff --git a/src/p_setup.h b/src/p_setup.h index 7827ebbe6..166c0ec2e 100644 --- a/src/p_setup.h +++ b/src/p_setup.h @@ -35,6 +35,7 @@ extern mapthing_t *deathmatchstarts[MAX_DM_STARTS]; extern INT32 numdmstarts, numcoopstarts, numredctfstarts, numbluectfstarts; extern boolean levelloading; +extern UINT8 levelfadecol; extern lumpnum_t lastloadedmaplumpnum; // for comparative savegame extern virtres_t *curmapvirt; @@ -114,12 +115,8 @@ size_t P_PrecacheLevelFlats(void); void P_AllocMapHeader(INT16 i); -// Needed for NiGHTS -void P_DeleteGrades(INT16 i); -void P_AddGradesForMare(INT16 i, UINT8 mare, char *gtext); -UINT8 P_GetGrade(UINT32 pscore, INT16 map, UINT8 mare); -UINT8 P_HasGrades(INT16 map, UINT8 mare); -UINT32 P_GetScoreForGrade(INT16 map, UINT8 mare, UINT8 grade); +void P_PrintCorruptMapWarnings(void); +void P_FreeCorruptMapWarnings(void); #ifdef __cplusplus } // extern "C" diff --git a/src/p_sight.c b/src/p_sight.c index b02ffd786..3eb4788b0 100644 --- a/src/p_sight.c +++ b/src/p_sight.c @@ -31,8 +31,6 @@ typedef struct { fixed_t bbox[4]; } los_t; -static INT32 sightcounts[2]; - typedef INT32 (*divlinefunc)(fixed_t x, fixed_t y, const divline_t *node); typedef INT32 (*divlinecrossfunc)(fixed_t x1, fixed_t y1, fixed_t x2, fixed_t y2, const divline_t *node); @@ -73,7 +71,7 @@ static inline INT32 P_DivlineCrossedFast(fixed_t x1, fixed_t y1, fixed_t x2, fix return (P_DivlineSideFast(x1, y1, node) == P_DivlineSideFast(x2, y2, node)); } -static boolean P_CrossSubsecPolyObj(polyobj_t *po, register los_t *los) +static boolean P_CrossSubsecPolyObj(polyobj_t *po, register los_t *los, boolean fast) { size_t i; sector_t *polysec; @@ -81,6 +79,8 @@ static boolean P_CrossSubsecPolyObj(polyobj_t *po, register los_t *los) if (!(po->flags & POF_RENDERALL)) return true; // the polyobject isn't visible, so we can ignore it + const divlinecrossfunc divlinecrossFunc = fast ? P_DivlineCrossedFast : P_DivlineCrossed; + polysec = po->lines[0]->backsector; for (i = 0; i < po->numLines; ++i) @@ -108,21 +108,21 @@ static boolean P_CrossSubsecPolyObj(polyobj_t *po, register los_t *los) v2 = line->v2; // line isn't crossed? - if (P_DivlineCrossed(v1->x, v1->y, v2->x, v2->y, &los->strace)) + if (divlinecrossFunc(v1->x, v1->y, v2->x, v2->y, &los->strace)) continue; divl.dx = v2->x - (divl.x = v1->x); divl.dy = v2->y - (divl.y = v1->y); // line isn't crossed? - if (P_DivlineCrossed(los->strace.x, los->strace.y, los->t2x, los->t2y, &divl)) + if (divlinecrossFunc(los->strace.x, los->strace.y, los->t2x, los->t2y, &divl)) continue; frac = P_InterceptVector(&los->strace, &divl); // get slopes of top and bottom of this polyobject line - topslope = FixedDiv(polysec->ceilingheight - los->sightzstart , frac); - bottomslope = FixedDiv(polysec->floorheight - los->sightzstart , frac); + topslope = FixedDiv(polysec->ceilingheight - los->sightzstart, frac); + bottomslope = FixedDiv(polysec->floorheight - los->sightzstart, frac); if (topslope >= los->topslope && bottomslope <= los->bottomslope) return false; // view completely blocked @@ -147,6 +147,8 @@ static boolean P_CrossSubsector(size_t num, register los_t *los, boolean fast) I_Error("P_CrossSubsector: ss %s with numss = %s\n", sizeu1(num), sizeu2(numsubsectors)); #endif + const divlinecrossfunc divlinecrossFunc = fast ? P_DivlineCrossedFast : P_DivlineCrossed; + // haleyjd 02/23/06: this assignment should be after the above check seg = segs + subsectors[num].firstline; @@ -158,15 +160,13 @@ static boolean P_CrossSubsector(size_t num, register los_t *los, boolean fast) if (po->validcount != validcount) { po->validcount = validcount; - if (!P_CrossSubsecPolyObj(po, los)) + if (!P_CrossSubsecPolyObj(po, los, fast)) return false; } po = (polyobj_t *)(po->link.next); } } - const divlinecrossfunc divlinecrossFunc = fast ? P_DivlineCrossedFast : P_DivlineCrossed; - for (count = subsectors[num].numlines; --count >= 0; seg++) // check lines { line_t *line = seg->linedef; @@ -214,14 +214,17 @@ static boolean P_CrossSubsector(size_t num, register los_t *los, boolean fast) front = seg->frontsector; back = seg->backsector; + // calculate position at intercept fracx = los->strace.x + FixedMul(los->strace.dx, frac); fracy = los->strace.y + FixedMul(los->strace.dy, frac); + // calculate sector heights frontf = P_GetSectorFloorZAt (front, fracx, fracy); frontc = P_GetSectorCeilingZAt(front, fracx, fracy); backf = P_GetSectorFloorZAt (back , fracx, fracy); backc = P_GetSectorCeilingZAt(back , fracx, fracy); + // crosses a two sided line // no wall to block sight with? if (frontf == backf && frontc == backc @@ -262,6 +265,7 @@ static boolean P_CrossSubsector(size_t num, register los_t *los, boolean fast) ffloor_t *rover; fixed_t topslope, bottomslope; fixed_t topz, bottomz; + // check front sector's FOFs first for (rover = front->ffloors; rover; rover = rover->next) { @@ -275,9 +279,11 @@ static boolean P_CrossSubsector(size_t num, register los_t *los, boolean fast) bottomz = P_GetFFloorBottomZAt(rover, fracx, fracy); topslope = FixedDiv( topz - los->sightzstart, frac); bottomslope = FixedDiv(bottomz - los->sightzstart, frac); + if (topslope >= los->topslope && bottomslope <= los->bottomslope) return false; // view completely blocked } + // check back sector's FOFs as well for (rover = back->ffloors; rover; rover = rover->next) { @@ -291,6 +297,7 @@ static boolean P_CrossSubsector(size_t num, register los_t *los, boolean fast) bottomz = P_GetFFloorBottomZAt(rover, fracx, fracy); topslope = FixedDiv( topz - los->sightzstart, frac); bottomslope = FixedDiv(bottomz - los->sightzstart, frac); + if (topslope >= los->topslope && bottomslope <= los->bottomslope) return false; // view completely blocked } @@ -315,10 +322,10 @@ static boolean P_CrossBSPNode(INT32 bspnum, register los_t *los, boolean fast) while (!(bspnum & NF_SUBSECTOR)) { - register node_t *bsp = nodes + bspnum; + register const node_t *bsp = nodes + bspnum; - INT32 side = divlineFunc(los->strace.x, los->strace.y, (divline_t *)bsp) & 1; - INT32 side2 = divlineFunc(los->t2x, los->t2y, (divline_t *) bsp); + INT32 side = divlineFunc(los->strace.x, los->strace.y, (const divline_t *)bsp) & 1; + INT32 side2 = divlineFunc(los->t2x, los->t2y, (const divline_t *)bsp); if (side == side2) { @@ -357,8 +364,10 @@ boolean P_CheckSight2(mobj_t *t1, mobj_t *t2, boolean fast) I_Assert(!P_MobjWasRemoved(t2)); if (!t1->subsector || !t2->subsector - || !t1->subsector->sector || !t2->subsector->sector) + || !t1->subsector->sector || !t2->subsector->sector) + { return false; + } s1 = t1->subsector->sector; s2 = t2->subsector->sector; @@ -368,7 +377,9 @@ boolean P_CheckSight2(mobj_t *t1, mobj_t *t2, boolean fast) { // Check in REJECT table. if (rejectmatrix[pnum>>3] & (1 << (pnum&7))) // can't possibly be connected + { return false; + } } // killough 11/98: shortcut for melee situations @@ -376,11 +387,9 @@ boolean P_CheckSight2(mobj_t *t1, mobj_t *t2, boolean fast) // haleyjd 02/23/06: can't do this if there are polyobjects in the subsec if (!t1->subsector->polyList && t1->subsector == t2->subsector) + { return true; - - // An unobstructed LOS is possible. - // Now look from eyes of t1 to any part of t2. - sightcounts[1]++; + } validcount++; @@ -423,21 +432,30 @@ boolean P_CheckSight2(mobj_t *t1, mobj_t *t2, boolean fast) continue; } - topz1 = P_GetFFloorTopZAt (rover, t1->x, t1->y); + // Check for blocking floors here. + topz2 = P_GetFFloorTopZAt (rover, t2->x, t2->y); bottomz1 = P_GetFFloorBottomZAt(rover, t1->x, t1->y); + + if (los.sightzstart < bottomz1 && t2->z >= topz2) + { + // no way to see through that + return false; + } + + topz1 = P_GetFFloorTopZAt (rover, t1->x, t1->y); bottomz2 = P_GetFFloorBottomZAt(rover, t2->x, t2->y); - // Check for blocking floors here. - if ((los.sightzstart < bottomz1 && t2->z >= topz2) - || (los.sightzstart >= topz1 && t2->z + t2->height < bottomz2)) + if (los.sightzstart >= topz1 && t2->z + t2->height < bottomz2) { // no way to see through that return false; } if (rover->flags & FF_SOLID) + { continue; // shortcut since neither mobj can be inside the 3dfloor + } if (rover->flags & FF_BOTHPLANES || !(rover->flags & FF_INVERTPLANES)) { diff --git a/src/p_slopes.c b/src/p_slopes.c index b3f4592d6..52a262785 100644 --- a/src/p_slopes.c +++ b/src/p_slopes.c @@ -76,8 +76,8 @@ static void P_UpdateSlopeLightOffset(pslope_t *slope) */ light = FixedMul(nX, FINECOSINE(maplighting.angle >> ANGLETOFINESHIFT)) - + FixedMul(nY, FINESINE(maplighting.angle >> ANGLETOFINESHIFT)); - light = (light + FRACUNIT) / 2; + + FixedMul(nY, FINESINE(maplighting.angle >> ANGLETOFINESHIFT)); + light = (light + FRACUNIT) / 2; } else { @@ -166,7 +166,8 @@ static void P_ReconfigureVertexSlope(pslope_t *slope) slope->real_xydirection = R_PointToAngle2(0, 0, slope->d.x, slope->d.y)+ANGLE_180; slope->real_zangle = InvAngle(R_PointToAngle2(0, 0, FRACUNIT, slope->zdelta)); - if (slope->normal.x == 0 && slope->normal.y == 0) // Set some defaults for a non-sloped "slope" + // Set some defaults for a non-sloped "slope" + if (slope->normal.x == 0 && slope->normal.y == 0) { slope->zangle = slope->xydirection = 0; slope->zdelta = slope->d.x = slope->d.y = 0; @@ -663,8 +664,10 @@ static pslope_t *P_NewVertexSlope(INT16 tag1, INT16 tag2, INT16 tag3, UINT8 flag for (i = 0; i < 3; i++) { mt = ret->vertices[i]; + if (!mt) // If a vertex wasn't found, it's game over. There's nothing you can do to recover (except maybe try and kill the slope instead - TODO?) I_Error("P_NewVertexSlope: Slope vertex %s (for linedef tag %d) not found!", sizeu1(i), tag1); + if (mt->extrainfo) mt->z = mt->options; else @@ -898,6 +901,11 @@ void P_SlopeLaunch(mobj_t *mo) //CONS_Printf("Launched off of slope.\n"); mo->standingslope = NULL; + + if (mo->player) + { + mo->player->stairjank = 0; // fuck you + } } // Function to help handle landing on slopes diff --git a/src/p_spec.c b/src/p_spec.c index 66901d234..8b526798e 100644 --- a/src/p_spec.c +++ b/src/p_spec.c @@ -538,6 +538,7 @@ static sector_t *getNextSector(line_t *line, sector_t *sec) else return NULL; } + return line->frontsector; } @@ -568,6 +569,7 @@ fixed_t P_FindLowestFloorSurrounding(sector_t *sec) if (other->floorheight < floorh) floorh = other->floorheight; } + return floorh; } @@ -881,7 +883,7 @@ static boolean PolyDoor(line_t *line) pdd.polyObjNum = line->tag; // polyobject id - switch(line->special) + switch (line->special) { case 480: // Polyobj_DoorSlide pdd.doorType = POLY_DOOR_SLIDE; @@ -889,7 +891,7 @@ static boolean PolyDoor(line_t *line) pdd.angle = line->angle; // angle of motion pdd.distance = sides[line->sidenum[0]].rowoffset; - if (line->sidenum[1] != 0xffff) + if (line->sidenum[1] != NO_INDEX) pdd.delay = sides[line->sidenum[1]].textureoffset >> FRACBITS; // delay in tics else pdd.delay = 0; @@ -899,7 +901,7 @@ static boolean PolyDoor(line_t *line) pdd.speed = sides[line->sidenum[0]].textureoffset >> FRACBITS; // angular speed pdd.distance = sides[line->sidenum[0]].rowoffset >> FRACBITS; // angular distance - if (line->sidenum[1] != 0xffff) + if (line->sidenum[1] != NO_INDEX) pdd.delay = sides[line->sidenum[1]].textureoffset >> FRACBITS; // delay in tics else pdd.delay = 0; @@ -1180,7 +1182,7 @@ INT32 P_FindMinSurroundingLight(sector_t *sector, INT32 max) for (i = 0; i < sector->linecount; i++) { line = sector->lines[i]; - check = getNextSector(line,sector); + check = getNextSector(line, sector); if (!check) continue; @@ -1234,7 +1236,6 @@ static void P_AddExecutorDelay(line_t *line, mobj_t *mobj, sector_t *sector) boolean P_RunTriggerLinedef(line_t *triggerline, mobj_t *actor, sector_t *caller) { sector_t *ctlsector; - fixed_t dist = P_AproxDistance(triggerline->dx, triggerline->dy)>>FRACBITS; size_t i, linecnt, sectori; INT16 specialtype = triggerline->special; //fromlapexec = false; @@ -1272,6 +1273,8 @@ boolean P_RunTriggerLinedef(line_t *triggerline, mobj_t *actor, sector_t *caller rings = actor->health-1; } + const fixed_t dist = P_AproxDistance(triggerline->dx, triggerline->dy)>>FRACBITS; + if (triggerline->flags & ML_NOCLIMB) { if (rings > dist) @@ -1293,7 +1296,6 @@ boolean P_RunTriggerLinedef(line_t *triggerline, mobj_t *actor, sector_t *caller msecnode_t *node; mobj_t *mo; INT32 numpush = 0; - INT32 numneeded = dist; if (!caller) return false; // we need a calling sector to find pushables in, silly! @@ -1308,6 +1310,8 @@ boolean P_RunTriggerLinedef(line_t *triggerline, mobj_t *actor, sector_t *caller node = node->m_thinglist_next; } + const fixed_t numneeded = P_AproxDistance(triggerline->dx, triggerline->dy)>>FRACBITS; + if (triggerline->flags & ML_NOCLIMB) // Need at least or more { if (numpush < numneeded) @@ -1336,6 +1340,7 @@ boolean P_RunTriggerLinedef(line_t *triggerline, mobj_t *actor, sector_t *caller else if (secspecial == 7) // SRB2Kart: reusing for Race Lap executor { UINT8 lap; + INT32 targlap; if (actor && actor->player && triggerline->flags & ML_EFFECT4) { @@ -1346,19 +1351,21 @@ boolean P_RunTriggerLinedef(line_t *triggerline, mobj_t *actor, sector_t *caller lap = P_FindLowestLap(); } + targlap = (INT32)(sides[triggerline->sidenum[0]].textureoffset >> FRACBITS); + if (triggerline->flags & ML_NOCLIMB) // Need higher than or equal to { - if (lap < (sides[triggerline->sidenum[0]].textureoffset >> FRACBITS)) + if (lap < targlap) return false; } else if (triggerline->flags & ML_BLOCKMONSTERS) // Need lower than or equal to { - if (lap > (sides[triggerline->sidenum[0]].textureoffset >> FRACBITS)) + if (lap > targlap) return false; } else // Need equal to { - if (lap != (sides[triggerline->sidenum[0]].textureoffset >> FRACBITS)) + if (lap != targlap) return false; } @@ -1450,6 +1457,7 @@ boolean P_RunTriggerLinedef(line_t *triggerline, mobj_t *actor, sector_t *caller if (triggerline->flags & ML_EFFECT5) // disregard order for efficiency { for (i = 0; i < linecnt; i++) + { if (ctlsector->lines[i]->special >= 400 && ctlsector->lines[i]->special < 500) { @@ -1458,6 +1466,7 @@ boolean P_RunTriggerLinedef(line_t *triggerline, mobj_t *actor, sector_t *caller else P_ProcessLineSpecial(ctlsector->lines[i], actor, caller); } + } } else // walk around the sector in a defined order { @@ -1465,11 +1474,13 @@ boolean P_RunTriggerLinedef(line_t *triggerline, mobj_t *actor, sector_t *caller size_t j, masterlineindex = (size_t)-1; for (i = 0; i < linecnt; i++) + { if (ctlsector->lines[i] == triggerline) { masterlineindex = i; break; } + } #ifdef PARANOIA if (masterlineindex == (size_t)-1) @@ -1488,11 +1499,13 @@ boolean P_RunTriggerLinedef(line_t *triggerline, mobj_t *actor, sector_t *caller { if (i == j) continue; + if (ctlsector->lines[i]->v1 == ctlsector->lines[j]->v2) { i = j; break; } + if (ctlsector->lines[i]->v1 == ctlsector->lines[j]->v1) { i = j; @@ -1500,6 +1513,7 @@ boolean P_RunTriggerLinedef(line_t *triggerline, mobj_t *actor, sector_t *caller break; } } + if (j == linecnt) { const size_t vertexei = (size_t)(ctlsector->lines[i]->v1 - vertexes); @@ -1514,11 +1528,13 @@ boolean P_RunTriggerLinedef(line_t *triggerline, mobj_t *actor, sector_t *caller { if (i == j) continue; + if (ctlsector->lines[i]->v2 == ctlsector->lines[j]->v1) { i = j; break; } + if (ctlsector->lines[i]->v2 == ctlsector->lines[j]->v2) { i = j; @@ -1595,19 +1611,21 @@ void P_LinedefExecute(INT16 tag, mobj_t *actor, sector_t *caller) if (lines[masterline].tag != tag) continue; + const INT16 specialtype = lines[masterline].special; + // "No More Enemies" and "Level Load" take care of themselves. - if (lines[masterline].special == 313 - || lines[masterline].special == 399 - || lines[masterline].special == 328 - || lines[masterline].special == 323 + if (specialtype == 313 + || specialtype == 399 + || specialtype == 328 + || specialtype == 323 // Each-time executors handle themselves, too - || lines[masterline].special == 301 // Each time - || lines[masterline].special == 306 // Character ability - Each time - || lines[masterline].special == 310 // CTF Red team - Each time - || lines[masterline].special == 312 // CTF Blue team - Each time - || lines[masterline].special == 322 // Trigger on X calls - Each Time - || lines[masterline].special < 300 - || lines[masterline].special > 399) + || specialtype == 301 // Each time + || specialtype == 306 // Character ability - Each time + || specialtype == 310 // CTF Red team - Each time + || specialtype == 312 // CTF Blue team - Each time + || specialtype == 322 // Trigger on X calls - Each Time + || specialtype < 300 + || specialtype > 399) continue; if (!P_RunTriggerLinedef(&lines[masterline], actor, caller)) @@ -1702,7 +1720,7 @@ void P_SwitchWeather(INT32 weathernum) precipmobj->type = type; // proper set the type precipmobj->info = &mobjinfo[type]; - precipmobj->flags = mobjinfo[type].flags; + //precipmobj->flags = mobjinfo[type].flags; st = &states[mobjinfo[type].spawnstate+z]; @@ -1973,8 +1991,8 @@ static void P_ProcessLineSpecial(line_t *line, mobj_t *mo, sector_t *callsec) INT32 position = (INT32)max(sides[line->sidenum[0]].midtexture, 0); UINT32 prefadems = (UINT32)max(sides[line->sidenum[0]].textureoffset >> FRACBITS, 0); UINT32 postfadems = (UINT32)max(sides[line->sidenum[0]].rowoffset >> FRACBITS, 0); - UINT8 fadetarget = (UINT8)max((line->sidenum[1] != 0xffff) ? sides[line->sidenum[1]].textureoffset >> FRACBITS : 0, 0); - INT16 fadesource = (INT16)max((line->sidenum[1] != 0xffff) ? sides[line->sidenum[1]].rowoffset >> FRACBITS : -1, -1); + UINT8 fadetarget = (UINT8)max((line->sidenum[1] != NO_INDEX) ? sides[line->sidenum[1]].textureoffset >> FRACBITS : 0, 0); + INT16 fadesource = (INT16)max((line->sidenum[1] != NO_INDEX) ? sides[line->sidenum[1]].rowoffset >> FRACBITS : -1, -1); // Seek offset from current song position if (line->flags & ML_EFFECT1) @@ -2082,7 +2100,7 @@ static void P_ProcessLineSpecial(line_t *line, mobj_t *mo, sector_t *callsec) ffloor_t *rover; boolean foundit = false; - for(rover = mo->subsector->sector->ffloors; rover; rover = rover->next) + for (rover = mo->subsector->sector->ffloors; rover; rover = rover->next) { if (rover->master->frontsector->tag != line->tag) continue; @@ -2143,7 +2161,7 @@ static void P_ProcessLineSpecial(line_t *line, mobj_t *mo, sector_t *callsec) newname[1] = 'C'; newname[2] = 'R'; - scrnum = sides[line->sidenum[0]].textureoffset>>FRACBITS; + scrnum = sides[line->sidenum[0]].textureoffset >> FRACBITS; if (scrnum < 0 || scrnum > 999) { scrnum = 0; @@ -2151,9 +2169,9 @@ static void P_ProcessLineSpecial(line_t *line, mobj_t *mo, sector_t *callsec) } else { - newname[5] = (char)('0' + (char)((scrnum/100))); - newname[6] = (char)('0' + (char)((scrnum%100)/10)); - newname[7] = (char)('0' + (char)(scrnum%10)); + newname[5] = (char)('0' + (char)((scrnum / 100))); + newname[6] = (char)('0' + (char)((scrnum % 100) / 10)); + newname[7] = (char)('0' + (char)(scrnum % 10)); } newname[8] = '\0'; @@ -2166,14 +2184,7 @@ static void P_ProcessLineSpecial(line_t *line, mobj_t *mo, sector_t *callsec) else { // W_CacheLumpNum may not have null terminator, so we need to do this :blobcatgooglyholditsheadinitshands: - size_t len = W_LumpLength(lumpnum); - char *script = Z_Malloc(len+1, PU_STATIC, NULL); - memcpy(script, W_CacheLumpNum(lumpnum, PU_CACHE), len); - script[len] = 0; - - COM_BufInsertText(script); - - Z_Free(script); + COM_BufInsertTextEx(W_CacheLumpNum(lumpnum, PU_CACHE), W_LumpLength(lumpnum)); } } break; @@ -2419,7 +2430,8 @@ static void P_ProcessLineSpecial(line_t *line, mobj_t *mo, sector_t *callsec) P_SetPlayerMobjState(mo, S_KART_STND1); // SRB2kart - was S_PLAY_STND // Reset bot too. - if (bot) { + if (bot) + { if (line->flags & ML_NOCLIMB) P_SetOrigin(bot, mo->x, mo->y, mo->z); bot->momx = bot->momy = bot->momz = 1; @@ -2487,7 +2499,7 @@ static void P_ProcessLineSpecial(line_t *line, mobj_t *mo, sector_t *callsec) var1 = sides[line->sidenum[0]].toptexture; //(line->dx>>FRACBITS)-1; - if (line->sidenum[1] != 0xffff && line->flags & ML_BLOCKMONSTERS) // read power from back sidedef + if (line->sidenum[1] != NO_INDEX && line->flags & ML_BLOCKMONSTERS) // read power from back sidedef var2 = sides[line->sidenum[1]].toptexture; else if (line->flags & ML_NOCLIMB) // 'Infinite' var2 = UINT16_MAX; @@ -2502,6 +2514,7 @@ static void P_ProcessLineSpecial(line_t *line, mobj_t *mo, sector_t *callsec) P_SetTarget(&dummy->target, bot); A_CustomPower(dummy); } + P_RemoveMobj(dummy); } break; @@ -2565,11 +2578,15 @@ static void P_ProcessLineSpecial(line_t *line, mobj_t *mo, sector_t *callsec) if (mo && mo->player) { UINT16 fractime = (UINT16)(sides[line->sidenum[0]].textureoffset>>FRACBITS); + if (fractime < 1) fractime = 1; //instantly wears off upon leaving + if (line->flags & ML_NOCLIMB) fractime |= 1<<15; //more crazy &ing, as if music stuff wasn't enough + mo->player->powers[pw_nocontrol] = fractime; + if (bot) bot->player->powers[pw_nocontrol] = fractime; } @@ -2579,8 +2596,10 @@ static void P_ProcessLineSpecial(line_t *line, mobj_t *mo, sector_t *callsec) if (mo) { mo->destscale = FixedDiv(P_AproxDistance(line->dx, line->dy), 100<destscale < FRACUNIT/100) mo->destscale = FRACUNIT/100; + if (mo->player && bot) bot->destscale = mo->destscale; } @@ -2609,7 +2628,7 @@ static void P_ProcessLineSpecial(line_t *line, mobj_t *mo, sector_t *callsec) if (always || this->bottomtexture) this->bottomtexture = set->bottomtexture; - if (lines[linenum].sidenum[1] == 0xffff) + if (lines[linenum].sidenum[1] == NO_INDEX) continue; // One-sided stops here. // Back side @@ -2658,16 +2677,18 @@ static void P_ProcessLineSpecial(line_t *line, mobj_t *mo, sector_t *callsec) sector_t *sec; mobj_t *thing; - if (line->sidenum[1] != 0xffff) + if (line->sidenum[1] != NO_INDEX) state = (statenum_t)sides[line->sidenum[1]].toptexture; while ((secnum = P_FindSectorFromLineTag(line, secnum)) >= 0) { boolean tryagain; sec = sectors + secnum; + do { tryagain = false; for (thing = sec->thinglist; thing; thing = thing->snext) + { if (thing->type == type) { if (state != NUMSTATES) @@ -2684,6 +2705,7 @@ static void P_ProcessLineSpecial(line_t *line, mobj_t *mo, sector_t *callsec) break; } } + } } while (tryagain); } break; @@ -2961,10 +2983,10 @@ sector_t *P_PlayerTouchingSectorSpecial(player_t *player, INT32 section, INT32 n { fixed_t topheight, bottomheight; - if (GETSECSPECIAL(rover->master->frontsector->special, section) != number) + if (!(rover->flags & FF_EXISTS)) continue; - if (!(rover->flags & FF_EXISTS)) + if (GETSECSPECIAL(rover->master->frontsector->special, section) != number) continue; topheight = P_GetSpecialTopZ(player->mo, sectors + rover->secnum, player->mo->subsector->sector); @@ -3161,11 +3183,6 @@ void P_ProcessSpecialSector(player_t *player, sector_t *sector, sector_t *rovers INT32 section1, section2, section3, section4; INT32 special; - section1 = GETSECSPECIAL(sector->special, 1); - section2 = GETSECSPECIAL(sector->special, 2); - section3 = GETSECSPECIAL(sector->special, 3); - section4 = GETSECSPECIAL(sector->special, 4); - // Ignore spectators if (player->spectator) return; @@ -3176,6 +3193,11 @@ void P_ProcessSpecialSector(player_t *player, sector_t *sector, sector_t *rovers if (player->playerstate == PST_DEAD) return; + section1 = GETSECSPECIAL(sector->special, 1); + section2 = GETSECSPECIAL(sector->special, 2); + section3 = GETSECSPECIAL(sector->special, 3); + section4 = GETSECSPECIAL(sector->special, 4); + // Conveyor stuff if (section3 == 2 || section3 == 4) player->onconveyor = section3; @@ -3259,6 +3281,7 @@ void P_ProcessSpecialSector(player_t *player, sector_t *sector, sector_t *rovers case 3: // Linedef executor requires all players present // Trigger Linedef Exec (Floor Touch, All Players) /// \todo check continues for proper splitscreen support? for (i = 0; i < MAXPLAYERS; i++) + { if (playeringame[i] && !players[i].bot && players[i].mo && (gametype != GT_COOP || players[i].lives > 0)) { if (roversector) @@ -3312,6 +3335,7 @@ void P_ProcessSpecialSector(player_t *player, sector_t *sector, sector_t *rovers goto DoneSection2; } } + } /* FALLTHRU */ case 4: // Linedef executor that doesn't require touching floor // Trigger Linedef Exec (Anywhere in Sector) case 5: // Linedef executor // Trigger Linedef Exec (Floor Touch) @@ -3385,14 +3409,16 @@ DoneSection2: { const fixed_t hscale = mapobjectscale + (mapobjectscale - player->mo->scale); const fixed_t minspeed = 24*hscale; - angle_t pushangle = FixedHypot(player->mo->momx, player->mo->momy) ? R_PointToAngle2(0, 0, player->mo->momx, player->mo->momy) : player->mo->angle; - // if we have no speed for SOME REASON, use the player's angle, otherwise we'd be forcefully thrusted to what I can only assume is angle 0 if (player->mo->eflags & MFE_SPRUNG) break; if (player->speed < minspeed) // Push forward to prevent getting stuck + { + // if we have no speed for SOME REASON, use the player's angle, otherwise we'd be forcefully thrusted to what I can only assume is angle 0 + const angle_t pushangle = FixedHypot(player->mo->momx, player->mo->momy) ? R_PointToAngle2(0, 0, player->mo->momx, player->mo->momy) : player->mo->angle; P_InstaThrust(player->mo, pushangle, minspeed); + } player->kartstuff[k_pogospring] = 1; K_DoPogoSpring(player->mo, 0, 1); @@ -3408,16 +3434,22 @@ DoneSection2: const fixed_t hscale = mapobjectscale + (mapobjectscale - player->mo->scale); const fixed_t minspeed = 24*hscale; const fixed_t maxspeed = 28*hscale; - angle_t pushangle = FixedHypot(player->mo->momx, player->mo->momy) ? R_PointToAngle2(0, 0, player->mo->momx, player->mo->momy) : player->mo->angle; - // if we have no speed for SOME REASON, use the player's angle, otherwise we'd be forcefully thrusted to what I can only assume is angle 0 if (player->mo->eflags & MFE_SPRUNG) break; if (player->speed > maxspeed) // Prevent overshooting jumps + { + // if we have no speed for SOME REASON, use the player's angle, otherwise we'd be forcefully thrusted to what I can only assume is angle 0 + const angle_t pushangle = FixedHypot(player->mo->momx, player->mo->momy) ? R_PointToAngle2(0, 0, player->mo->momx, player->mo->momy) : player->mo->angle; P_InstaThrust(player->mo, pushangle, maxspeed); + } else if (player->speed < minspeed) // Push forward to prevent getting stuck + { + // if we have no speed for SOME REASON, use the player's angle, otherwise we'd be forcefully thrusted to what I can only assume is angle 0 + const angle_t pushangle = FixedHypot(player->mo->momx, player->mo->momy) ? R_PointToAngle2(0, 0, player->mo->momx, player->mo->momy) : player->mo->angle; P_InstaThrust(player->mo, pushangle, minspeed); + } player->kartstuff[k_pogospring] = 2; K_DoPogoSpring(player->mo, 0, 1); @@ -3436,11 +3468,14 @@ DoneSection2: if (i != -1) { + INT32 sfxnum; angle_t lineangle; fixed_t linespeed; - lineangle = lines[i].angle; - linespeed = P_AproxDistance(lines[i].v2->x-lines[i].v1->x, lines[i].v2->y-lines[i].v1->y); + const line_t *line = &lines[i]; + + lineangle = line->angle; + linespeed = P_AproxDistance(line->v2->x-line->v1->x, line->v2->y-line->v1->y); player->mo->angle = lineangle; @@ -3454,7 +3489,7 @@ DoneSection2: P_ForceLocalAngle(player, player->mo->angle); } - if (!(lines[i].flags & ML_EFFECT4)) + if (!(line->flags & ML_EFFECT4)) { P_UnsetThingPosition(player->mo); if (roversector) // make FOF speed pads work @@ -3476,7 +3511,14 @@ DoneSection2: player->kartstuff[k_drift] = 0; player->kartstuff[k_driftcharge] = 0; player->kartstuff[k_pogospring] = 0; - S_StartSound(player->mo, sfx_spdpad); + + sfxnum = sides[line->sidenum[0]].toptexture; + + // none or invalid sound? + if (sfxnum <= sfx_None || sfxnum >= NUMSFX) + sfxnum = sfx_spdpad; // use the zippy sound then! + + S_StartSound(player->mo, sfxnum); { sfxenum_t pick = P_RandomKey(2); // Gotta roll the RNG every time this is called for sync reasons @@ -3525,21 +3567,25 @@ DoneSection2: P_DoPlayerExit(player); P_SetupSignExit(player); - // important: use sector->tag on next line instead of player->mo->subsector->tag - // this part is different from in P_PlayerThink, this is what was causing - // FOF custom exits not to work. - lineindex = P_FindSpecialLineFromTag(2, sector->tag, -1); - if (gametype == GT_COOP && lineindex != -1) // Custom exit! + if (gametype == GT_COOP) { - // Special goodies with the block monsters flag depending on emeralds collected - if ((lines[lineindex].flags & ML_BLOCKMONSTERS) && ALL7EMERALDS(emeralds)) - nextmapoverride = (INT16)(lines[lineindex].frontsector->ceilingheight>>FRACBITS); - else - nextmapoverride = (INT16)(lines[lineindex].frontsector->floorheight>>FRACBITS); + // important: use sector->tag on next line instead of player->mo->subsector->tag + // this part is different from in P_PlayerThink, this is what was causing + // FOF custom exits not to work. + lineindex = P_FindSpecialLineFromTag(2, sector->tag, -1); - if (lines[lineindex].flags & ML_NOCLIMB) - skipstats = true; + if (lineindex != -1) // Custom exit!) + { + // Special goodies with the block monsters flag depending on emeralds collected + if ((lines[lineindex].flags & ML_BLOCKMONSTERS) && ALL7EMERALDS(emeralds)) + nextmapoverride = (INT16)(lines[lineindex].frontsector->ceilingheight>>FRACBITS); + else + nextmapoverride = (INT16)(lines[lineindex].frontsector->floorheight>>FRACBITS); + + if (lines[lineindex].flags & ML_NOCLIMB) + skipstats = true; + } } } break; @@ -3645,7 +3691,6 @@ DoneSection2: thinker_t *th; mobj_t *waypoint = NULL; mobj_t *mo2; - angle_t an; if (player->mo->tracer && player->mo->tracer->type == MT_TUBEWAYPOINT) break; @@ -3693,10 +3738,13 @@ DoneSection2: CONS_Debug(DBG_GAMELOGIC, "Waypoint %d found in sequence %d - speed = %d\n", waypoint->health, sequence, speed); } - an = R_PointToAngle2(player->mo->x, player->mo->y, waypoint->x, waypoint->y) - player->mo->angle; + if (!(lines[lineindex].flags & ML_EFFECT4)) + { + const angle_t an = R_PointToAngle2(player->mo->x, player->mo->y, waypoint->x, waypoint->y) - player->mo->angle; - if (an > ANGLE_90 && an < ANGLE_270 && !(lines[lineindex].flags & ML_EFFECT4)) - break; // behind back + if (an > ANGLE_90 && an < ANGLE_270) + break; // behind back + } P_SetTarget(&player->mo->tracer, waypoint); player->speed = speed; @@ -3718,7 +3766,6 @@ DoneSection2: thinker_t *th; mobj_t *waypoint = NULL; mobj_t *mo2; - angle_t an; if (player->mo->tracer && player->mo->tracer->type == MT_TUBEWAYPOINT) break; @@ -3766,10 +3813,13 @@ DoneSection2: CONS_Debug(DBG_GAMELOGIC, "Waypoint %d found in sequence %d - speed = %d\n", waypoint->health, sequence, speed); } - an = R_PointToAngle2(player->mo->x, player->mo->y, waypoint->x, waypoint->y) - player->mo->angle; + if (!(lines[lineindex].flags & ML_EFFECT4)) + { + const angle_t an = R_PointToAngle2(player->mo->x, player->mo->y, waypoint->x, waypoint->y) - player->mo->angle; - if (an > ANGLE_90 && an < ANGLE_270 && !(lines[lineindex].flags & ML_EFFECT4)) - break; // behind back + if (an > ANGLE_90 && an < ANGLE_270) + break; // behind back + } P_SetTarget(&player->mo->tracer, waypoint); player->speed = speed; @@ -3783,10 +3833,13 @@ DoneSection2: case 10: // Finish Line // SRB2kart - 150117 - if (G_RaceGametype() && (player->starpostnum >= (numstarposts - (numstarposts/2)) || player->exiting)) + if (!G_RaceGametype()) + break; + + if (player->starpostnum >= (numstarposts - (numstarposts/2)) || player->exiting) player->kartstuff[k_starpostwp] = player->kartstuff[k_waypoint] = 0; // - if (G_RaceGametype() && !player->exiting) + if (!player->exiting) { if (player->starpostnum >= (numstarposts - (numstarposts/2))) // srb2kart: must have touched *enough* starposts (was originally "(player->starpostnum == numstarposts)") { @@ -3820,7 +3873,7 @@ DoneSection2: player->kartstuff[k_lapanimation] = 80; - if (UNLIKELY(player->pflags & PF_NIGHTSMODE)) + if (nightsplayer(player)) player->drillmeter += 48*20; if (netgame && player->laps >= (UINT8)cv_numlaps.value) @@ -4381,8 +4434,6 @@ static void P_PlayerOnSpecial3DFloor(player_t *player, sector_t *sector) } } -#define VDOORSPEED (FRACUNIT*2) - // // P_RunSpecialSectorCheck // @@ -4401,7 +4452,7 @@ static void P_RunSpecialSectorCheck(player_t *player, sector_t *sector) // The list of specials that activate without floor touch // Check Section 1 - switch(GETSECSPECIAL(sector->special, 1)) + switch (GETSECSPECIAL(sector->special, 1)) { //case 2: // Damage (water) case 8: // Instant kill @@ -4412,7 +4463,7 @@ static void P_RunSpecialSectorCheck(player_t *player, sector_t *sector) } // Check Section 2 - switch(GETSECSPECIAL(sector->special, 2)) + switch (GETSECSPECIAL(sector->special, 2)) { case 2: // Linedef executor (All players needed) case 4: // Linedef executor @@ -4423,7 +4474,7 @@ static void P_RunSpecialSectorCheck(player_t *player, sector_t *sector) } // Check Section 4 - switch(GETSECSPECIAL(sector->special, 4)) + switch (GETSECSPECIAL(sector->special, 4)) { case 2: // Level Exit / GOAL Sector / Flag Return case 1: // Starpost activator @@ -4443,12 +4494,13 @@ static void P_RunSpecialSectorCheck(player_t *player, sector_t *sector) } f_affectpoint = P_GetSpecialBottomZ(player->mo, sector, sector); - c_affectpoint = P_GetSpecialTopZ(player->mo, sector, sector); // Only go further if on the ground if ((sector->flags & SF_FLIPSPECIAL_FLOOR) && !(sector->flags & SF_FLIPSPECIAL_CEILING) && player->mo->z != f_affectpoint) return; + c_affectpoint = P_GetSpecialTopZ(player->mo, sector, sector); + if ((sector->flags & SF_FLIPSPECIAL_CEILING) && !(sector->flags & SF_FLIPSPECIAL_FLOOR) && player->mo->z + player->mo->height != c_affectpoint) return; @@ -4504,37 +4556,23 @@ void P_PlayerInSpecialSector(player_t *player) #undef TELEPORTED -/** Animate planes, scroll walls, etc. and keeps track of level timelimit and exits if time is up. - * - * \sa P_CheckTimeLimit, P_CheckPointLimit - */ -void P_UpdateSpecials(void) +static void P_UpdateAnimFlats(void) { anim_t *anim; INT32 i; - INT32 pic; size_t j; - levelflat_t *foundflats; // for flat animation - // LEVEL TIMER - P_CheckTimeLimit(); - - // POINT LIMIT - P_CheckPointLimit(); - - // Dynamic slopeness - if (!midgamejoin) // run here when not joined midgame to prevent any potential issues that may arise - P_RunDynamicSlopes(); - // ANIMATE TEXTURES for (anim = anims; anim < lastanim; anim++) { for (i = 0; i < anim->numpics; i++) { - pic = anim->basepic + ((leveltime/anim->speed + i) % anim->numpics); if (anim->istexture) - texturetranslation[anim->basepic+i] = pic; + { + texturetranslation[anim->basepic+i] = anim->basepic + + ((leveltime/anim->speed + i) % anim->numpics); + } } } @@ -4554,15 +4592,40 @@ void P_UpdateSpecials(void) } } +/** Animate planes, scroll walls, etc. and keeps track of level timelimit and exits if time is up. + * + * \sa P_CheckTimeLimit, P_CheckPointLimit + */ +void P_UpdateSpecials(void) +{ + // LEVEL TIMER + P_CheckTimeLimit(); + + // POINT LIMIT + P_CheckPointLimit(); + +#ifndef PHOBOS_BUILD + // Dynamic slopeness + // we run this here only when not joined midrace + // for vanilla compat reasons :chaosleep: + if (!midgamejoin) + P_RunDynamicSlopes(); +#endif + + P_UpdateAnimFlats(); +} + static inline ffloor_t *P_GetFFloorBySec(sector_t *sec, sector_t *sec2) { ffloor_t *rover; if (!sec->ffloors) return NULL; + for (rover = sec->ffloors; rover; rover = rover->next) if (rover->secnum == (size_t)(sec2 - sectors)) return rover; + return NULL; } @@ -4579,8 +4642,8 @@ static inline void P_AddFFloorToList(sector_t *sec, ffloor_t *ffloor) if (!sec->ffloors) { sec->ffloors = ffloor; - ffloor->next = 0; - ffloor->prev = 0; + ffloor->next = NULL; + ffloor->prev = NULL; return; } @@ -4588,7 +4651,7 @@ static inline void P_AddFFloorToList(sector_t *sec, ffloor_t *ffloor) rover->next = ffloor; ffloor->prev = rover; - ffloor->next = 0; + ffloor->next = NULL; } /** Adds a 3Dfloor. @@ -4613,6 +4676,7 @@ static ffloor_t *P_AddFakeFloor(sector_t *sec, sector_t *sec2, line_t *master, f if (sec == sec2) return NULL; //Don't need a fake floor on a control sector. + if ((ffloor = (P_GetFFloorBySec(sec, sec2)))) return ffloor; // If this ffloor already exists, return it @@ -4629,8 +4693,8 @@ static ffloor_t *P_AddFakeFloor(sector_t *sec, sector_t *sec2, line_t *master, f if (sec2->numattached == 0) { - sec2->attached = Z_Malloc(sizeof (*sec2->attached) * sec2->maxattached, PU_STATIC, NULL); - sec2->attachedsolid = Z_Malloc(sizeof (*sec2->attachedsolid) * sec2->maxattached, PU_STATIC, NULL); + sec2->attached = Z_Malloc(sizeof(*sec2->attached) * sec2->maxattached, PU_STATIC, NULL); + sec2->attachedsolid = Z_Malloc(sizeof(*sec2->attachedsolid) * sec2->maxattached, PU_STATIC, NULL); sec2->attached[0] = sec - sectors; sec2->numattached = 1; sec2->attachedsolid[0] = (flags & FF_SOLID); @@ -4644,8 +4708,8 @@ static ffloor_t *P_AddFakeFloor(sector_t *sec, sector_t *sec2, line_t *master, f if (sec2->numattached >= sec2->maxattached) { sec2->maxattached *= 2; - sec2->attached = Z_Realloc(sec2->attached, sizeof (*sec2->attached) * sec2->maxattached, PU_STATIC, NULL); - sec2->attachedsolid = Z_Realloc(sec2->attachedsolid, sizeof (*sec2->attachedsolid) * sec2->maxattached, PU_STATIC, NULL); + sec2->attached = Z_Realloc(sec2->attached, sizeof(*sec2->attached) * sec2->maxattached, PU_STATIC, NULL); + sec2->attachedsolid = Z_Realloc(sec2->attachedsolid, sizeof(*sec2->attachedsolid) * sec2->maxattached, PU_STATIC, NULL); } sec2->attached[sec2->numattached] = sec - sectors; sec2->attachedsolid[sec2->numattached] = (flags & FF_SOLID); @@ -4653,7 +4717,7 @@ static ffloor_t *P_AddFakeFloor(sector_t *sec, sector_t *sec2, line_t *master, f } // Add the floor - ffloor = Z_Calloc(sizeof (*ffloor), PU_LEVEL, NULL); + ffloor = Z_Calloc(sizeof(*ffloor), PU_LEVEL, NULL); ffloor->secnum = sec2 - sectors; ffloor->target = sec; ffloor->bottomheight = &sec2->floorheight; @@ -4719,7 +4783,7 @@ static ffloor_t *P_AddFakeFloor(sector_t *sec, sector_t *sec2, line_t *master, f P_AddSpikeThinker(sec, (INT32)sec2num); } // Should this FOF have friction? - else if(th->function == (actionf_p1)T_Friction) + else if (th->function == (actionf_p1)T_Friction) { f = (friction_t *)th; @@ -4727,7 +4791,7 @@ static ffloor_t *P_AddFakeFloor(sector_t *sec, sector_t *sec2, line_t *master, f Add_Friction(f->friction, f->movefactor, (INT32)(sec-sectors), f->affectee); } // Should this FOF have wind/current/pusher? - else if(th->function == (actionf_p1)T_Pusher) + else if (th->function == (actionf_p1)T_Pusher) { p = (pusher_t *)th; @@ -5165,11 +5229,18 @@ void T_LaserFlash(laserthink_t *flash) if (thing->health <= 0) continue; + // thing is neither shootable nor an egg guard shield + if (!(thing->flags & MF_SHOOTABLE) && (thing->type != MT_EGGSHIELD)) + continue; + top = P_GetSpecialTopZ(thing, sourcesec, sector); + + if (thing->z >= top) + continue; + bottom = P_GetSpecialBottomZ(thing, sourcesec, sector); - if (thing->z >= top - || thing->z + thing->height <= bottom) + if (thing->z + thing->height <= bottom) continue; if (thing->flags & MF_SHOOTABLE) @@ -5224,6 +5295,18 @@ static void P_RunLevelLoadExecutors(void) } } +static fixed_t P_GetSectorGravityFactor(sector_t *sec) +{ + return FixedDiv(*sec->gravity >> FRACBITS, 1000); +} + +fixed_t P_GetSectorGravity(sector_t *sec) +{ + if (sec && sec->gravity) + return FixedMul(gravity, P_GetSectorGravityFactor(sec)); + return gravity; +} + /** After the map has loaded, scans for specials that spawn 3Dfloors and * thinkers. * @@ -5263,7 +5346,7 @@ void P_SpawnSpecials(INT32 fromnetsave, boolean reloadinggamestate) continue; // Process Section 1 - switch(GETSECSPECIAL(sector->special, 1)) + switch (GETSECSPECIAL(sector->special, 1)) { case 5: // Spikes P_AddSpikeThinker(sector, (INT32)(sector-sectors)); @@ -5275,7 +5358,7 @@ void P_SpawnSpecials(INT32 fromnetsave, boolean reloadinggamestate) } // Process Section 2 - switch(GETSECSPECIAL(sector->special, 2)) + switch (GETSECSPECIAL(sector->special, 2)) { case 10: // Time for special stage sstimer = (sector->floorheight>>FRACBITS) * TICRATE + 6; // Time to finish @@ -5288,7 +5371,7 @@ void P_SpawnSpecials(INT32 fromnetsave, boolean reloadinggamestate) } // Process Section 4 - switch(GETSECSPECIAL(sector->special, 4)) + switch (GETSECSPECIAL(sector->special, 4)) { case 10: // Circuit finish line if (G_RaceGametype()) @@ -5324,11 +5407,13 @@ void P_SpawnSpecials(INT32 fromnetsave, boolean reloadinggamestate) // Allocate each list, and then zero the count so we can use it to track // the end of the list as we add the thinkers for (i = 0; i < numsectors; i++) - if(secthinkers[i].count > 0) + { + if (secthinkers[i].count > 0) { secthinkers[i].thinkers = Z_Malloc(secthinkers[i].count * sizeof(thinker_t *), PU_STATIC, NULL); secthinkers[i].count = 0; } + } // Finally, populate the lists. for (th = thinkercap.next; th != &thinkercap; th = th->next) @@ -5408,6 +5493,7 @@ void P_SpawnSpecials(INT32 fromnetsave, boolean reloadinggamestate) if ((lines[i].flags & (ML_NOSONIC|ML_NOTAILS)) != (ML_NOSONIC|ML_NOTAILS)) // If you can do something... { angle_t flatangle = InvAngle(lines[i].angle); + fixed_t xoffs; fixed_t yoffs; @@ -5468,7 +5554,6 @@ void P_SpawnSpecials(INT32 fromnetsave, boolean reloadinggamestate) break; case 10: // Vertical culling plane for sprites and FOFs - sec = sides[*lines[i].sidenum].sector - sectors; for (s = -1; (s = P_FindSectorFromLineTag(lines + i, s)) >= 0 ;) sectors[s].cullheight = &lines[i]; // This allows it to change in realtime! break; @@ -5981,7 +6066,7 @@ void P_SpawnSpecials(INT32 fromnetsave, boolean reloadinggamestate) break; case 259: // Make-Your-Own FOF! - if (lines[i].sidenum[1] != 0xffff) + if (lines[i].sidenum[1] != NO_INDEX) { UINT8 *data; UINT16 b; @@ -5989,7 +6074,7 @@ void P_SpawnSpecials(INT32 fromnetsave, boolean reloadinggamestate) if (!virt) virt = vres_GetMap(lastloadedmaplumpnum); - data = (UINT8*) vres_Find(virt, "SIDEDEFS")->data; + data = (UINT8*)vres_Find(virt, "SIDEDEFS")->data; for (b = 0; b < (INT16)numsides; b++) { @@ -6221,8 +6306,7 @@ void P_SpawnSpecials(INT32 fromnetsave, boolean reloadinggamestate) // Allocate each list for (i = 0; i < numsectors; i++) - if(secthinkers[i].thinkers) - Z_Free(secthinkers[i].thinkers); + Z_Free(secthinkers[i].thinkers); Z_Free(secthinkers); @@ -6429,15 +6513,19 @@ void T_Scroll(scroll_t *s) if (thing->flags2 & MF2_PUSHED) // Already pushed this tic by an exclusive pusher. continue; - height = P_GetSpecialBottomZ(thing, sec, psec); - if (!(thing->flags & MF_NOCLIP)) // Thing must be clipped - if (!(thing->flags & MF_NOGRAVITY || thing->z+thing->height != height)) // Thing must a) be non-floating and have z+height == height { - // Move objects only if on floor - // non-floating, and clipped. - P_DoScrollMove(thing, dx, dy, s->exclusive); + height = P_GetSpecialBottomZ(thing, sec, psec); + + if (!(thing->flags & MF_NOGRAVITY || thing->z+thing->height != height)) // Thing must a) be non-floating and have z+height == height + { + // Move objects only if on floor + // non-floating, and clipped. + P_DoScrollMove(thing, dx, dy, s->exclusive); + } + } + } // end of for loop through touching_thinglist } // end of loop through sectors } @@ -6451,14 +6539,16 @@ void T_Scroll(scroll_t *s) if (thing->flags2 & MF2_PUSHED) continue; - height = P_GetSpecialBottomZ(thing, sec, sec); - - if (!(thing->flags & MF_NOCLIP) && - (!(thing->flags & MF_NOGRAVITY || thing->z > height))) + if (!(thing->flags & MF_NOCLIP)) // Thing must be clipped { - // Move objects only if on floor or underwater, - // non-floating, and clipped. - P_DoScrollMove(thing, dx, dy, s->exclusive); + height = P_GetSpecialBottomZ(thing, sec, sec); + + if (!(thing->flags & MF_NOGRAVITY || thing->z > height)) + { + // Move objects only if on floor or underwater, + // non-floating, and clipped. + P_DoScrollMove(thing, dx, dy, s->exclusive); + } } } } @@ -6504,14 +6594,16 @@ void T_Scroll(scroll_t *s) if (thing->flags2 & MF2_PUSHED) continue; - height = P_GetSpecialTopZ(thing, sec, psec); - if (!(thing->flags & MF_NOCLIP)) // Thing must be clipped - if (!(thing->flags & MF_NOGRAVITY || thing->z != height))// Thing must a) be non-floating and have z == height { - // Move objects only if on floor or underwater, - // non-floating, and clipped. - P_DoScrollMove(thing, dx, dy, s->exclusive); + height = P_GetSpecialTopZ(thing, sec, psec); + + if (!(thing->flags & MF_NOGRAVITY || thing->z != height))// Thing must a) be non-floating and have z == height + { + // Move objects only if on floor or underwater, + // non-floating, and clipped. + P_DoScrollMove(thing, dx, dy, s->exclusive); + } } } // end of for loop through touching_thinglist } // end of loop through sectors @@ -6526,14 +6618,16 @@ void T_Scroll(scroll_t *s) if (thing->flags2 & MF2_PUSHED) continue; - height = P_GetSpecialTopZ(thing, sec, sec); - - if (!(thing->flags & MF_NOCLIP) && - (!(thing->flags & MF_NOGRAVITY || thing->z+thing->height < height))) + if (!(thing->flags & MF_NOCLIP)) // Thing must be clipped { - // Move objects only if on floor or underwater, - // non-floating, and clipped. - P_DoScrollMove(thing, dx, dy, s->exclusive); + height = P_GetSpecialTopZ(thing, sec, sec); + + if (!(thing->flags & MF_NOGRAVITY || thing->z+thing->height < height)) + { + // Move objects only if on floor or underwater, + // non-floating, and clipped. + P_DoScrollMove(thing, dx, dy, s->exclusive); + } } } } @@ -6701,7 +6795,7 @@ static void P_SpawnScrollers(void) case 506: s = lines[i].sidenum[1]; - if (s != 0xffff) + if (s != NO_INDEX) Add_Scroller(sc_side, -sides[s].textureoffset, sides[s].rowoffset, -1, lines[i].sidenum[0], accel, 0); else CONS_Debug(DBG_GAMELOGIC, "Line special 506 (line #%s) missing 2nd side!\n", sizeu1(i)); @@ -6912,6 +7006,7 @@ static void P_SpawnFriction(void) INT32 movefactor; // applied to each player move to simulate inertia for (i = 0; i < numlines; i++, l++) + { if (l->special == 540) { //length = P_AproxDistance(l->dx, l->dy)>>FRACBITS; @@ -6945,6 +7040,7 @@ static void P_SpawnFriction(void) for (s = -1; (s = P_FindSectorFromLineTag(l, s)) >= 0 ;) Add_Friction(friction, movefactor, s, -1); } + } } /* @@ -6993,9 +7089,10 @@ static void Add_Pusher(pushertype_e type, fixed_t x_mag, fixed_t y_mag, mobj_t * // "The right triangle of the square of the length of the hypotenuse is equal to the sum of the squares of the lengths of the other two sides." // "Bah! Stupid brains! Don't you know anything besides the Pythagorean Theorem?" - Earthworm Jim if (type == p_downcurrent || type == p_upcurrent || type == p_upwind || type == p_downwind) - p->magnitude = P_AproxDistance(p->x_mag,p->y_mag)<<(FRACBITS-PUSH_FACTOR); + p->magnitude = P_AproxDistance(p->x_mag, p->y_mag)<<(FRACBITS-PUSH_FACTOR); else - p->magnitude = P_AproxDistance(p->x_mag,p->y_mag); + p->magnitude = P_AproxDistance(p->x_mag, p->y_mag); + if (source) // point source exist? { // where force goes to zero @@ -7034,7 +7131,7 @@ static inline boolean PIT_PushThing(mobj_t *thing) return false; // Allow this to affect pushable objects at some point? - if (thing->player && (!(thing->flags & (MF_NOGRAVITY | MF_NOCLIP)) || UNLIKELY(thing->player->pflags & PF_NIGHTSMODE))) + if (thing->player && (!(thing->flags & (MF_NOGRAVITY | MF_NOCLIP)) || nightsplayer(thing->player))) { INT32 dist; INT32 speed; @@ -7046,15 +7143,14 @@ static inline boolean PIT_PushThing(mobj_t *thing) // don't fade wrt Z if health & 2 (mapthing has multi flag) if (tmpusher->source->health & 2) - dist = P_AproxDistance(thing->x - sx,thing->y - sy); + dist = P_AproxDistance(thing->x - sx, thing->y - sy); else { // Make sure the Z is in range if (thing->z < sz - tmpusher->radius || thing->z > sz + tmpusher->radius) return false; - dist = P_AproxDistance(P_AproxDistance(thing->x - sx, thing->y - sy), - thing->z - sz); + dist = P_AproxDistance(P_AproxDistance(thing->x - sx, thing->y - sy), thing->z - sz); } speed = (tmpusher->magnitude - ((dist>>FRACBITS)>>1))<<(FRACBITS - PUSH_FACTOR - 1); @@ -7065,7 +7161,7 @@ static inline boolean PIT_PushThing(mobj_t *thing) // Written with bits and pieces of P_HomingAttack if ((speed > 0) && (P_CheckSight(thing, tmpusher->source))) { - if (LIKELY(!(thing->player->pflags & PF_NIGHTSMODE))) + if (!nightsplayer(thing->player)) { // only push wrt Z if health & 1 (mapthing has ambush flag) if (tmpusher->source->health & 1) @@ -7217,7 +7313,6 @@ void T_Pusher(pusher_t *p) if (p->type == p_push) { - // Seek out all pushable things within the force radius of this // point pusher. Crosses sectors, so use blockmap. @@ -7260,13 +7355,16 @@ void T_Pusher(pusher_t *p) if (thing->flags2 & MF2_PUSHED) continue; - if (thing->player && thing->player->pflags & PF_ROPEHANG) - continue; + if (thing->player) + { + if (thing->player->pflags & PF_ROPEHANG) + continue; - if (thing->player && (thing->state == &states[thing->info->painstate]) - && (thing->player->powers[pw_flashing] > (K_GetKartFlashing(thing->player)/4)*3 - && thing->player->powers[pw_flashing] <= K_GetKartFlashing(thing->player))) - continue; + if ((thing->state == &states[thing->info->painstate]) + && (thing->player->powers[pw_flashing] > (K_GetKartFlashing(thing->player)/4)*3 + && thing->player->powers[pw_flashing] <= K_GetKartFlashing(thing->player))) + continue; + } inFOF = touching = moved = false; @@ -7396,7 +7494,7 @@ void T_Pusher(pusher_t *p) if (p->slider && thing->player) { boolean jumped = (thing->player->pflags & PF_JUMPED); - P_ResetPlayer (thing->player); + P_ResetPlayer(thing->player); if (jumped) thing->player->pflags |= PF_JUMPED; @@ -7464,16 +7562,17 @@ static void P_SpawnPushers(void) mobj_t *thing; for (i = 0; i < numlines; i++, l++) + { switch (l->special) { case 541: // wind for (s = -1; (s = P_FindSectorFromLineTag(l, s)) >= 0 ;) Add_Pusher(p_wind, l->dx, l->dy, NULL, s, -1, l->flags & ML_NOCLIMB, l->flags & ML_EFFECT4); - break; + break; case 544: // current for (s = -1; (s = P_FindSectorFromLineTag(l, s)) >= 0 ;) Add_Pusher(p_current, l->dx, l->dy, NULL, s, -1, l->flags & ML_NOCLIMB, l->flags & ML_EFFECT4); - break; + break; case 547: // push/pull for (s = -1; (s = P_FindSectorFromLineTag(l, s)) >= 0 ;) { @@ -7485,20 +7584,21 @@ static void P_SpawnPushers(void) case 545: // current up for (s = -1; (s = P_FindSectorFromLineTag(l, s)) >= 0 ;) Add_Pusher(p_upcurrent, l->dx, l->dy, NULL, s, -1, l->flags & ML_NOCLIMB, l->flags & ML_EFFECT4); - break; + break; case 546: // current down for (s = -1; (s = P_FindSectorFromLineTag(l, s)) >= 0 ;) Add_Pusher(p_downcurrent, l->dx, l->dy, NULL, s, -1, l->flags & ML_NOCLIMB, l->flags & ML_EFFECT4); - break; + break; case 542: // wind up for (s = -1; (s = P_FindSectorFromLineTag(l, s)) >= 0 ;) Add_Pusher(p_upwind, l->dx, l->dy, NULL, s, -1, l->flags & ML_NOCLIMB, l->flags & ML_EFFECT4); - break; + break; case 543: // wind down for (s = -1; (s = P_FindSectorFromLineTag(l, s)) >= 0 ;) Add_Pusher(p_downwind, l->dx, l->dy, NULL, s, -1, l->flags & ML_NOCLIMB, l->flags & ML_EFFECT4); - break; + break; } + } } void P_StartQuake(tic_t time, fixed_t intensity, fixed_t radius) diff --git a/src/p_spec.h b/src/p_spec.h index 7b763c498..679ee65dc 100644 --- a/src/p_spec.h +++ b/src/p_spec.h @@ -56,6 +56,8 @@ sector_t *P_PlayerTouchingSectorSpecial(player_t *player, INT32 section, INT32 n void P_PlayerInSpecialSector(player_t *player); void P_ProcessSpecialSector(player_t *player, sector_t *sector, sector_t *roversector); +fixed_t P_GetSectorGravity(sector_t *sec); + fixed_t P_FindLowestFloorSurrounding(sector_t *sec); fixed_t P_FindHighestFloorSurrounding(sector_t *sec); diff --git a/src/p_tick.c b/src/p_tick.c index 88e8fb2fd..645d7dd31 100644 --- a/src/p_tick.c +++ b/src/p_tick.c @@ -38,6 +38,8 @@ #include "i_video.h" // rendermode #include "m_perfstats.h" +#include "lua_profile.h" + // Object place #include "m_cheat.h" @@ -611,8 +613,19 @@ void P_Ticker(boolean run) #ifdef DEMO_COMPAT_100 } #endif + + // Lookback is normally handled inside G_BuildTiccmd, which isn't called in replays so we're doing that manually + // idk if this is best place to handle this tho... + for (i = 0; i <= splitscreen; ++i) + { + const boolean usejoystick = cv_usejoystick[i].value; + INT32 axis = JoyAxis(AXISLOOKBACK, i+1); + camspin[i] = (InputDown(gc_lookback, i+1) || (usejoystick && axis > 0)); + } } + LUA_ResetTicTimers(); + ps_lua_mobjhooks.value.i = 0; ps_checkposition_calls.value.i = 0; @@ -620,6 +633,7 @@ void P_Ticker(boolean run) LUA_HookPreThinkFrame(); PS_STOP_TIMING(ps_lua_prethinkframe_time); + // OK! Now that we got all of that sorted, players can think! PS_START_TIMING(ps_playerthink_time); for (i = 0; i < MAXPLAYERS; i++) { @@ -637,7 +651,9 @@ void P_Ticker(boolean run) if (run) { // Dynamic slopeness +#ifndef PHOBOS_BUILD if (midgamejoin) // only run here if we joined midgame to fix some desynchs +#endif P_RunDynamicSlopes(); PS_START_TIMING(ps_thinkertime); @@ -664,6 +680,7 @@ void P_Ticker(boolean run) PS_STOP_TIMING(ps_lua_thinkframe_time); } + // Run shield positioning P_RunOverlays(); P_RunShadows(); @@ -706,6 +723,7 @@ void P_Ticker(boolean run) if (indirectitemcooldown > 0) indirectitemcooldown--; + if (hyubgone > 0) hyubgone--; @@ -713,8 +731,7 @@ void P_Ticker(boolean run) { K_UpdateSpectateGrief(); } - - if (G_BattleGametype()) + else if (G_BattleGametype()) { if (wantedcalcdelay && --wantedcalcdelay <= 0) K_CalculateBattleWanted(); @@ -728,11 +745,12 @@ void P_Ticker(boolean run) if (cv_recordmultiplayerdemos.value) { - const INT32 axis = JoyAxis(AXISLOOKBACK, 1); - if (demo.savemode == DSM_NOTSAVING || demo.savemode == DSM_WILLAUTOSAVE) - if (demo.savebutton && demo.savebutton + 3*TICRATE < leveltime && (InputDown(gc_lookback, 1) || (cv_usejoystick[0].value && axis > 0))) + { + const INT32 axis = cv_usejoystick[0].value ? JoyAxis(AXISLOOKBACK, 1) : -1; + if (demo.savebutton && demo.savebutton + 3*TICRATE < leveltime && (InputDown(gc_lookback, 1) || (axis > 0))) demo.savemode = DSM_TITLEENTRY; + } // if there are no players left at all, stop demo recording // Demos that that dont have any players crash during playback, which can happen with dedicated servers @@ -784,7 +802,7 @@ void P_Ticker(boolean run) if (!player->mo) continue; - const boolean skybox = (skyboxmo[0] && cv_skybox.value); + const boolean skybox = (skyboxmo[0] && cv_skybox.value); // True if there's a skybox object and skyboxes are on if (skyVisiblePerPlayer[i] && skybox) { diff --git a/src/p_tick.h b/src/p_tick.h index a903be0fd..e0fcd899c 100644 --- a/src/p_tick.h +++ b/src/p_tick.h @@ -20,6 +20,10 @@ #pragma interface #endif +#ifdef __cplusplus +extern "C" { +#endif + extern tic_t leveltime; // Called by G_Ticker. Carries out all thinking of enemies and players. @@ -38,6 +42,10 @@ mobj_t *P_SetTarget2(mobj_t **mo, mobj_t *target #endif ); +#ifdef __cplusplus +} +#endif + #ifdef PARANOIA #define P_SetTarget(...) P_SetTarget2(__VA_ARGS__, __FILE__, __LINE__) #else diff --git a/src/p_user.c b/src/p_user.c index 2a3ccc300..42b206830 100644 --- a/src/p_user.c +++ b/src/p_user.c @@ -74,7 +74,7 @@ void P_Thrust(mobj_t *mo, angle_t angle, fixed_t move) mo->momx += FixedMul(move, FINECOSINE(angle)); - if (LIKELY(!(twodlevel || (mo->flags2 & MF2_TWOD)))) + if (!twodmo(mo)) mo->momy += FixedMul(move, FINESINE(angle)); } @@ -90,7 +90,7 @@ void P_InstaThrust(mobj_t *mo, angle_t angle, fixed_t move) mo->momx = FixedMul(move, FINECOSINE(angle)); - if (LIKELY(!(twodlevel || (mo->flags2 & MF2_TWOD)))) + if (!twodmo(mo)) mo->momy = FixedMul(move,FINESINE(angle)); } @@ -157,6 +157,7 @@ void P_CalcHeight(player_t *player) if (player->viewz > mo->ceilingz - FixedMul(FRACUNIT, mo->scale)) player->viewz = mo->ceilingz - FixedMul(FRACUNIT, mo->scale); } + return; } @@ -220,32 +221,6 @@ UINT8 P_GetNextEmerald(void) return (UINT8)(gamemap - sstage_start); } -// -// P_GiveEmerald -// -// Award an emerald upon completion -// of a special stage. -// -void P_GiveEmerald(boolean spawnObj) -{ - INT32 i; - UINT8 em; - - S_StartSound(NULL, sfx_cgot); // Got the emerald! - em = P_GetNextEmerald(); - emeralds |= (1 << em); - - if (spawnObj) - { - for (i = 0; i < MAXPLAYERS; i++) - { - if (playeringame[i]) - P_SetMobjState(P_SpawnMobj(players[i].mo->x, players[i].mo->y, players[i].mo->z + players[i].mo->info->height, MT_GOTEMERALD), - mobjinfo[MT_GOTEMERALD].spawnstate + em); - } - } -} - // // P_ResetScore // @@ -500,7 +475,7 @@ void P_PlayLivesJingle(player_t *player) if (UNLIKELY(use1upSound)) S_StartSound(NULL, sfx_oneup); - else if (UNLIKELY(mariomode)) + else if (mariomode) S_StartSound(NULL, sfx_marioa); else { @@ -528,7 +503,7 @@ void P_PlayRinglossSound(mobj_t *source, mobj_t *damager) S_StartSound(NULL, sfx); } else - S_StartSound(source, UNLIKELY(mariomode) ? sfx_mario8 : sfx_khurt1 + key); + S_StartSound(source, mariomode ? sfx_mario8 : sfx_khurt1 + key); } else S_StartSound(source, sfx_slip); @@ -650,15 +625,23 @@ boolean P_EndingMusic(player_t *player) } if (G_RaceGametype() && bestlocalpos == MAXPLAYERS+1) - sprintf(buffer, "k*fail"); // F-Zero death results theme + { + snprintf(buffer, sizeof(buffer), "k*fail"); // F-Zero death results theme + } else { if (bestlocalpos == 1) - sprintf(buffer, "k*win"); + { + snprintf(buffer, sizeof(buffer), "k*win"); + } else if (isPlayerLosing(bestlocalplayer)) - sprintf(buffer, "k*lose"); + { + snprintf(buffer, sizeof(buffer), "k*lose"); + } else - sprintf(buffer, "k*ok"); + { + snprintf(buffer, sizeof(buffer), "k*ok"); + } } S_SpeedMusic(1.0f); @@ -800,7 +783,7 @@ boolean P_IsObjectInGoop(mobj_t *mo) // boolean P_IsObjectOnGround(mobj_t *mo) { - if (UNLIKELY(P_IsObjectInGoop(mo))) + if (P_IsObjectInGoop(mo)) { // but I don't want you to ever 'stand' while submerged in goo. // You're in constant vertical momentum, even if you get stuck on something. @@ -1147,22 +1130,26 @@ void P_SpawnShieldOrb(player_t *player) P_SetTarget(&ov->target, shieldobj); P_SetMobjState(ov, shieldobj->info->seestate); } + if (shieldobj->info->meleestate) { ov = P_SpawnMobj(shieldobj->x, shieldobj->y, shieldobj->z, MT_OVERLAY); P_SetTarget(&ov->target, shieldobj); P_SetMobjState(ov, shieldobj->info->meleestate); } + if (shieldobj->info->missilestate) { ov = P_SpawnMobj(shieldobj->x, shieldobj->y, shieldobj->z, MT_OVERLAY); P_SetTarget(&ov->target, shieldobj); P_SetMobjState(ov, shieldobj->info->missilestate); } + if (player->powers[pw_shield] & SH_FORCE) { //Copy and pasted from P_ShieldLook in p_mobj.c shieldobj->movecount = (player->powers[pw_shield] & 0xFF); + if (shieldobj->movecount < 1) { if (shieldobj->info->painstate) @@ -1226,8 +1213,8 @@ mobj_t *P_SpawnGhostMobj(mobj_t *mobj) ghost->pitch = mobj->pitch; ghost->roll = mobj->roll; - ghost->sloperoll = mobj->sloperoll; ghost->rollangle = mobj->rollangle; + ghost->temprollangle = mobj->temprollangle; ghost->sloperoll = mobj->sloperoll; ghost->slopepitch = mobj->slopepitch; @@ -1419,7 +1406,8 @@ static void P_CheckBustableBlocks(player_t *player) for (rover = node->m_sector->ffloors; rover; rover = rover->next) { - if (!(rover->flags & FF_EXISTS)) continue; + if (!(rover->flags & FF_EXISTS)) + continue; if ((rover->flags & FF_BUSTUP)/* && !rover->master->frontsector->crumblestate*/) { @@ -1539,11 +1527,12 @@ static void P_CheckBouncySectors(player_t *player) continue; // this sector type is required for FOFs to be bouncy topheight = P_GetFOFTopZ(player->mo, node->m_sector, rover, player->mo->x, player->mo->y, NULL); - bottomheight = P_GetFOFBottomZ(player->mo, node->m_sector, rover, player->mo->x, player->mo->y, NULL); if (player->mo->z > topheight) continue; + bottomheight = P_GetFOFBottomZ(player->mo, node->m_sector, rover, player->mo->x, player->mo->y, NULL); + if (player->mo->z + player->mo->height < bottomheight) continue; @@ -1593,10 +1582,12 @@ static void P_CheckBouncySectors(player_t *player) newmom = -8*FRACUNIT; } - if (newmom > P_GetPlayerHeight(player)/2) - newmom = P_GetPlayerHeight(player)/2; - else if (newmom < -P_GetPlayerHeight(player)/2) - newmom = -P_GetPlayerHeight(player)/2; + const fixed_t halfpheight = P_GetPlayerHeight(player)/2; + + if (newmom > halfpheight) + newmom = halfpheight; + else if (newmom < -halfpheight) + newmom = -halfpheight; momentum.z = newmom*2; @@ -1742,7 +1733,7 @@ static void P_DoBubbleBreath(player_t *player) else zh = player->mo->z + FixedDiv(player->mo->height,5*(FRACUNIT/4)); - if (!(player->mo->eflags & MFE_UNDERWATER) || player->spectator || ((player->powers[pw_shield] & SH_NOSTACK) == SH_ELEMENTAL && !(player->pflags & PF_NIGHTSMODE))) + if (!(player->mo->eflags & MFE_UNDERWATER) || player->spectator || ((player->powers[pw_shield] & SH_NOSTACK) == SH_ELEMENTAL && !nightsplayer(player))) return; if (P_RandomChance(FRACUNIT/16)) @@ -1822,7 +1813,6 @@ void P_DoJumpShield(player_t *player) player->pflags &= ~PF_JUMPED; //P_DoJump(player, false); - player->pflags &= ~PF_JUMPED; player->secondjump = 0; player->jumping = 0; player->pflags |= PF_THOKKED; @@ -1860,6 +1850,9 @@ void P_Telekinesis(player_t *player, fixed_t thrust, fixed_t range) if (!((mo2->flags & MF_SHOOTABLE && mo2->flags & MF_ENEMY) || mo2->type == MT_EGGGUARD || mo2->player)) continue; + if (mo2->health <= 0) + continue; + dist = P_AproxDistance(P_AproxDistance(player->mo->x-mo2->x, player->mo->y-mo2->y), player->mo->z-mo2->z); if (range < dist) @@ -1868,15 +1861,12 @@ void P_Telekinesis(player_t *player, fixed_t thrust, fixed_t range) if (!P_CheckSight(player->mo, mo2)) continue; // if your psychic powers can't "see" it don't bother - if (mo2->health > 0) - { - an = R_PointToAngle2(player->mo->x, player->mo->y, mo2->x, mo2->y); + an = R_PointToAngle2(player->mo->x, player->mo->y, mo2->x, mo2->y); - P_Thrust(mo2, an, thrust); + P_Thrust(mo2, an, thrust); - if (mo2->type == MT_GOLDBUZZ || mo2->type == MT_REDBUZZ) - mo2->tics += 8; - } + if (mo2->type == MT_GOLDBUZZ || mo2->type == MT_REDBUZZ) + mo2->tics += 8; } //P_SpawnThokMobj(player); @@ -1894,7 +1884,6 @@ static void P_3dMovement(player_t *player) ticcmd_t *cmd; angle_t movepushangle, movepushsideangle; // Analog fixed_t movepushforward = 0, movepushside = 0; - angle_t dangle; // replaces old quadrants bits boolean analogmove = false; fixed_t oldMagnitude, newMagnitude; vector3_t totalthrust; @@ -1952,15 +1941,6 @@ static void P_3dMovement(player_t *player) // Calculates player's speed based on distance-of-a-line formula player->speed = R_PointToDist2(0, 0, player->rmomx, player->rmomy); - // Monster Iestyn - 04-11-13 - // Quadrants are stupid, excessive and broken, let's do this a much simpler way! - // Get delta angle from rmom angle and player angle first - dangle = R_PointToAngle2(0,0, player->rmomx, player->rmomy) - player->mo->angle; - if (dangle > ANGLE_180) //flip to keep to one side - { - dangle = InvAngle(dangle); - } - // When sliding, don't allow forward/back if (player->pflags & PF_SLIDING) cmd->forwardmove = 0; @@ -2003,20 +1983,23 @@ static void P_3dMovement(player_t *player) K_MomentumToFacing(player); } + const fixed_t kartspd = K_GetKartSpeed(player, true); + // Sideways movement if (cmd->sidemove != 0 && !((player->exiting || mapreset) || player->kartstuff[k_spinouttimer])) { if (cmd->sidemove > 0) - movepushside = (cmd->sidemove * FRACUNIT/128) + FixedDiv(player->speed, K_GetKartSpeed(player, true)); + movepushside = (cmd->sidemove * FRACUNIT/128) + FixedDiv(player->speed, kartspd); else - movepushside = (cmd->sidemove * FRACUNIT/128) - FixedDiv(player->speed, K_GetKartSpeed(player, true)); + movepushside = (cmd->sidemove * FRACUNIT/128) - FixedDiv(player->speed, kartspd); totalthrust.x += P_ReturnThrustX(player->mo, movepushsideangle, movepushside); totalthrust.y += P_ReturnThrustY(player->mo, movepushsideangle, movepushside); } if ((totalthrust.x || totalthrust.y) - && player->mo->standingslope && (!(player->mo->standingslope->flags & SL_NOPHYSICS)) && abs(player->mo->standingslope->zdelta) > FRACUNIT/2) { + && player->mo->standingslope && (!(player->mo->standingslope->flags & SL_NOPHYSICS)) && abs(player->mo->standingslope->zdelta) > FRACUNIT/2) + { // Factor thrust to slope, but only for the part pushing up it! // The rest is unaffected. angle_t thrustangle = R_PointToAngle2(0, 0, totalthrust.x, totalthrust.y)-player->mo->standingslope->xydirection; @@ -2052,11 +2035,11 @@ static void P_3dMovement(player_t *player) // -Shadow Hog newMagnitude = R_PointToDist2(player->mo->momx - player->cmomx, player->mo->momy - player->cmomy, 0, 0); - if (newMagnitude > K_GetKartSpeed(player, true)) //topspeed) + if (newMagnitude > kartspd) //topspeed) { fixed_t tempmomx, tempmomy; - if (oldMagnitude > K_GetKartSpeed(player, true) && onground) // SRB2Kart: onground check for air speed cap + if (oldMagnitude > kartspd && onground) // SRB2Kart: onground check for air speed cap { if (newMagnitude > oldMagnitude) { @@ -2069,8 +2052,8 @@ static void P_3dMovement(player_t *player) } else { - tempmomx = FixedMul(FixedDiv(player->mo->momx - player->cmomx, newMagnitude), K_GetKartSpeed(player, true)); //topspeed) - tempmomy = FixedMul(FixedDiv(player->mo->momy - player->cmomy, newMagnitude), K_GetKartSpeed(player, true)); //topspeed) + tempmomx = FixedMul(FixedDiv(player->mo->momx - player->cmomx, newMagnitude), kartspd); //topspeed) + tempmomy = FixedMul(FixedDiv(player->mo->momy - player->cmomy, newMagnitude), kartspd); //topspeed) player->mo->momx = tempmomx + player->cmomx; player->mo->momy = tempmomy + player->cmomy; } @@ -2144,7 +2127,6 @@ void P_ElementalFireTrail(player_t *player) INT32 i; I_Assert(player != NULL); - I_Assert(player->mo != NULL); I_Assert(!P_MobjWasRemoved(player->mo)); if (player->mo->eflags & MFE_VERTICALFLIP) @@ -2306,7 +2288,8 @@ static void P_MovePlayer(player_t *player) } //CONS_Printf("applied turn: %d\n", angle_diff); - if (add_delta) { + if (add_delta) + { player->mo->angle += angle_diff << TICCMD_REDUCE; player->mo->angle &= ~0xFFFF; // Try to keep the turning somewhat similar to how it was before? //CONS_Printf("leftover turn (%s): %5d or %4d%%\n", @@ -2323,7 +2306,7 @@ static void P_MovePlayer(player_t *player) P_3dMovement(player); } - if (UNLIKELY(maptol & TOL_2D)) // psure this doesent even work at all + if (twodlevel) // psure this doesent even work at all runspd = FixedMul(runspd, 2*FRACUNIT/3); ///////////////////////// @@ -2387,7 +2370,7 @@ static void P_MovePlayer(player_t *player) if (onground && leveltime % 50 == 0 && player->kartstuff[k_drift] != 0) S_StartSound(player->mo, sfx_drift); // Leveltime being 50 might take a while at times. We'll start it up once, isntantly. - else if (onground && !S_SoundPlaying(player->mo, sfx_drift) && player->kartstuff[k_drift] != 0) + else if (onground && player->kartstuff[k_drift] != 0 && !S_SoundPlaying(player->mo, sfx_drift)) S_StartSound(player->mo, sfx_drift); // Ok, we'll stop now. else if (player->kartstuff[k_drift] == 0 || !onground) @@ -2428,15 +2411,18 @@ static void P_MovePlayer(player_t *player) { mobj_t *water = P_SpawnMobj(player->mo->x, player->mo->y, ((player->mo->eflags & MFE_VERTICALFLIP) ? player->mo->waterbottom - FixedMul(mobjinfo[MT_SPLISH].height, player->mo->scale) : player->mo->watertop), MT_SPLISH); + if (player->mo->eflags & MFE_GOOWATER) S_StartSound(water, sfx_ghit); else S_StartSound(water, sfx_wslap); + if (player->mo->eflags & MFE_VERTICALFLIP) { water->flags2 |= MF2_OBJECTFLIP; water->eflags |= MFE_VERTICALFLIP; } + water->destscale = player->mo->scale; P_SetScale(water, player->mo->scale); } @@ -2485,9 +2471,10 @@ static void P_MovePlayer(player_t *player) const fixed_t runnyspeed = 20*FRACUNIT; speed = R_PointToDist2(player->rmomx, player->rmomy, 0, 0); + const fixed_t kartspd = K_GetKartSpeed(player, false); - if (speed > K_GetKartSpeed(player, false)-(5< kartspd-(5<= runnyspeed) player->fovadd = speed-runnyspeed; @@ -2764,16 +2751,16 @@ boolean P_LookForEnemies(player_t *player) || ((mo->z+mo->height < player->mo->z+player->mo->height-FixedMul(MAXSTEPMOVE, mapobjectscale)) && (player->mo->eflags & MFE_VERTICALFLIP))) // Reverse gravity check - Flame. continue; // Don't home upwards! - if (P_AproxDistance(P_AproxDistance(player->mo->x-mo->x, player->mo->y-mo->y), - player->mo->z-mo->z) > FixedMul(RING_DIST, player->mo->scale)) + const fixed_t modist = P_AproxDistance(P_AproxDistance(player->mo->x-mo->x, player->mo->y-mo->y), player->mo->z-mo->z); + + if (modist > FixedMul(RING_DIST, player->mo->scale)) continue; // out of range - if (UNLIKELY((twodlevel || player->mo->flags2 & MF2_TWOD) - && abs(player->mo->y-mo->y) > player->mo->radius)) + + if (twodmo(player->mo) && abs(player->mo->y-mo->y) > player->mo->radius) continue; // not in your 2d plane - if (closestmo && P_AproxDistance(P_AproxDistance(player->mo->x-mo->x, player->mo->y-mo->y), - player->mo->z-mo->z) > P_AproxDistance(P_AproxDistance(player->mo->x-closestmo->x, + if (closestmo && modist > P_AproxDistance(P_AproxDistance(player->mo->x-closestmo->x, player->mo->y-closestmo->y), player->mo->z-closestmo->z)) continue; @@ -3137,19 +3124,16 @@ void P_ToggleDemoCamera(UINT8 viewnum) return; } - if (!cam->freecam) // toggle on + if (!cam->freecam) // toggle on { cam->freecam = true; cam->button_a_held = 2; cam->reset_aiming = true; // get rid of some hud elements - if (displayplayers[0] != consoleplayer) - { - displayplayers[0] = consoleplayer; - } + displayplayers[0] = consoleplayer; } - else // toggle off + else // toggle off { cam->freecam = false; G_FixCamera(viewnum+1); @@ -3180,8 +3164,8 @@ static ticcmd_t *P_CameraCmd(camera_t *cam, UINT8 num) cmd->angleturn = (INT16)(lang >> TICCMD_REDUCE); cmd->aiming = G_ClipAimingPitch(&laim); - const boolean analogjoystickmove = cv_usejoystick[num].value && !Joystick[num].bGamepadStyle; - const boolean gamepadjoystickmove = cv_usejoystick[num].value && Joystick[num].bGamepadStyle; + const boolean analogjoystickmove = cv_usejoystick[num].value && !DigitalGamepadStyle(num); + const boolean gamepadjoystickmove = cv_usejoystick[num].value && DigitalGamepadStyle(num); usejoystick = (analogjoystickmove || gamepadjoystickmove); @@ -3515,8 +3499,6 @@ void P_ResetCamera(player_t *player, camera_t *thiscam) } } - thiscam->relativex = 0; - thiscam->subsector = R_PointInSubsectorFast(thiscam->x, thiscam->y); thiscam->radius = 20*FRACUNIT; @@ -3534,7 +3516,7 @@ static boolean P_CheckNoclipCameraPosition(player_t *player, camera_t *thiscam, boolean cameranoclip; mobj_t *mo = player->mo; - cameranoclip = ((player->pflags & (PF_NOCLIP|PF_NIGHTSMODE)) + cameranoclip = (nightsplayer(player) || (mo->flags & (MF_NOCLIP|MF_NOCLIPHEIGHT)) // Noclipping player camera noclips too!! || (leveltime < introtime)); // Kart intro cam @@ -3766,7 +3748,7 @@ boolean P_MoveChaseCamera(player_t *player, camera_t *thiscam, boolean resetcall fixed_t f1, f2; // We probably shouldn't move the camera if there is no player or player mobj somehow - if (!player || !player->mo) + if (!player || P_MobjWasRemoved(player->mo)) return true; // This can happen when joining @@ -4009,9 +3991,12 @@ boolean P_MoveChaseCamera(player_t *player, camera_t *thiscam, boolean resetcall { fixed_t panmax = (dist/5); const INT32 sparkval = K_GetKartDriftSparkValue(player); + pan = FixedDiv(FixedMul(min((fixed_t)player->kartstuff[k_driftcharge], sparkval), panmax), sparkval); + if (pan > panmax) pan = panmax; + if (player->kartstuff[k_drift] < 0) pan *= -1; } @@ -4063,7 +4048,7 @@ boolean P_MoveChaseCamera(player_t *player, camera_t *thiscam, boolean resetcall if (timeover) thiscam->angle = angle; - else if (!camstill && !resetcalled && !paused && timeover != 1) + else if (!camstill && !resetcalled && !paused) thiscam->angle = R_PointToAngle2(thiscam->x, thiscam->y, viewpointx, viewpointy); if (timeover == 1) @@ -4120,7 +4105,7 @@ boolean P_MoveChaseCamera(player_t *player, camera_t *thiscam, boolean resetcall angle -= (angle - thiscam->pitch)/2; } - if (player->playerstate != PST_DEAD && !((player->pflags & PF_NIGHTSMODE) && player->exiting)) + if (player->playerstate != PST_DEAD && !(nightsplayer(player) && player->exiting)) angle += (focusaiming < ANGLE_180 ? focusaiming/2 : InvAngle(InvAngle(focusaiming)/2)); // overcomplicated version of '((signed)focusaiming)/2;' if (!camstill && !timeover) // Keep the view still... @@ -4186,16 +4171,18 @@ void P_ResetLocalCamAiming(player_t *player) boolean P_SpectatorJoinGame(player_t *player) { + const boolean islocalplayer = P_IsLocalPlayer(player); + // Team changing isn't allowed. if (!cv_allowteamchange.value) { - if (P_IsLocalPlayer(player)) + if (islocalplayer) CONS_Printf(M_GetText("Server does not allow team change.\n")); } // Team changing in Team Match and CTF // Pressing fire assigns you to a team that needs players if allowed. // Partial code reproduction from p_tick.c autobalance code. - else if (UNLIKELY(G_GametypeHasTeams())) + else if (G_GametypeHasTeams()) { INT32 changeto = 0; INT32 z, numplayersred = 0, numplayersblue = 0; @@ -4237,7 +4224,7 @@ boolean P_SpectatorJoinGame(player_t *player) P_ResetLocalCamAiming(player); //Reset away view - if (P_IsLocalPlayer(player) && displayplayers[0] != consoleplayer) + if (islocalplayer && displayplayers[0] != consoleplayer) displayplayers[0] = consoleplayer; if (changeto == 1) @@ -4264,7 +4251,7 @@ boolean P_SpectatorJoinGame(player_t *player) P_ResetLocalCamAiming(player); //Reset away view - if (P_IsLocalPlayer(player) && displayplayers[0] != consoleplayer) + if (islocalplayer && displayplayers[0] != consoleplayer) displayplayers[0] = consoleplayer; HU_AddChatText(va(M_GetText("\x82*%s entered the game."), player_names[player-players]), false); @@ -4464,7 +4451,7 @@ static INT32 Quaketilt(player_t *player) lowb = FixedMul(lowb, player->mo->scale); moma = FixedMul(FixedDiv(delta, ANGLE_90), tilt); - speed = abs( player->mo->momx + player->mo->momy ); + speed = abs(player->mo->momx + player->mo->momy); if (speed < lowb) { @@ -4595,7 +4582,7 @@ void P_PlayerThink(player_t *player) } #ifdef SEENAMES - if (netgame && player == &players[displayplayers[0]] && !(leveltime % (TICRATE/5)) && !splitscreen) + if (netgame && !splitscreen && player == &players[displayplayers[0]] && !(leveltime % (TICRATE/5))) { seenplayer = NULL; @@ -4608,6 +4595,7 @@ void P_PlayerThink(player_t *player) { short int i; mo->flags |= MF_NOCLIPHEIGHT; + for (i = 0; i < 32; i++) { // Debug drawing @@ -4786,6 +4774,7 @@ void P_PlayerThink(player_t *player) player->mo->flags2 |= MF2_SHADOW; else player->mo->flags2 &= ~MF2_SHADOW; + P_DeathThink(player); LUA_HookPlayer(player, HOOK(PlayerThink)); return; @@ -4890,7 +4879,7 @@ void P_PlayerThink(player_t *player) // Even if not NiGHTS, pull in nearby objects when walking around as John Q. Elliot. if (UNLIKELY(!objectplacing && !((netgame || multiplayer) && player->spectator) - && maptol & TOL_NIGHTS && (!(player->pflags & PF_NIGHTSMODE) || player->powers[pw_nights_helper]))) + && nightsmode && (!nightsplayer(player) || player->powers[pw_nights_helper]))) { thinker_t *th; mobj_t *mo2; @@ -4992,7 +4981,7 @@ void P_PlayerThink(player_t *player) #endif // check for use - if (LIKELY(!(player->pflags & PF_NIGHTSMODE))) + if (!nightsplayer(player)) { if (cmd->buttons & BT_BRAKE) player->pflags |= PF_USEDOWN; @@ -5109,6 +5098,11 @@ void P_PlayerThink(player_t *player) player->squishdance.time = 0; } + if (player->stairjank > 0) + { + player->stairjank--; + } + // Flash player after being hit. if (!(player->kartstuff[k_hyudorotimer] // SRB2kart - fixes Hyudoro not flashing when it should. || player->kartstuff[k_growshrinktimer] > 0 // Grow doesn't flash either. @@ -5178,7 +5172,7 @@ void P_PlayerAfterThink(player_t *player) } } - if (UNLIKELY(player->pflags & PF_NIGHTSMODE)) + if (nightsplayer(player)) { player->powers[pw_gravityboots] = 0; } diff --git a/src/r_bsp.cpp b/src/r_bsp.cpp index 55a475c9d..b118e8e84 100644 --- a/src/r_bsp.cpp +++ b/src/r_bsp.cpp @@ -221,8 +221,9 @@ sector_t *R_FakeFlat(sector_t *sec, sector_t *tempsec, INT32 *floorlightlevel, tempsec->floorheight = s->floorheight; tempsec->ceilingheight = s->ceilingheight; - if ((underwater && (tempsec-> floorheight = sec->floorheight, - tempsec->ceilingheight = s->floorheight - 1, !back)) || viewz <= s->floorheight) + if ((underwater && (tempsec->floorheight = sec->floorheight, + tempsec->ceilingheight = s->floorheight - 1, !back)) || + viewz <= s->floorheight) { // head-below-floor hack tempsec->floorpic = s->floorpic; tempsec->floor_xoffs = s->floor_xoffs; @@ -258,8 +259,8 @@ sector_t *R_FakeFlat(sector_t *sec, sector_t *tempsec, INT32 *floorlightlevel, *ceilinglightlevel = s->ceilinglightsec == -1 ? s->lightlevel : sectors[s->ceilinglightsec].lightlevel; } - else if (heightsec != -1 && viewz >= sectors[heightsec].ceilingheight - && sec->ceilingheight > s->ceilingheight) + else if (heightsec != -1 && viewz >= sectors[heightsec].ceilingheight && + sec->ceilingheight > s->ceilingheight) { // Above-ceiling hack tempsec->ceilingheight = s->ceilingheight; tempsec->floorheight = s->ceilingheight + 1; @@ -296,7 +297,8 @@ sector_t *R_FakeFlat(sector_t *sec, sector_t *tempsec, INT32 *floorlightlevel, *ceilinglightlevel = s->ceilinglightsec == -1 ? s->lightlevel : sectors[s->ceilinglightsec].lightlevel; } - sec = tempsec; + + sec = tempsec; // Use other sector } return sec; @@ -318,13 +320,20 @@ static void R_AddLine(seg_t *line) INT32 x1, x2; angle_t angle1, angle2, span, tspan; static sector_t tempsec; - boolean bothfloorssky = false; + boolean bothfloorssky = false; + fixed_t v1x, v1y, v2x, v2y; // the seg's vertexes as fixed_t g_portal = NULL; + v1x = line->v1->x; + v1y = line->v1->y; + + v2x = line->v2->x; + v2y = line->v2->y; + // big room fix - angle1 = R_PointToAngle64(line->v1->x, line->v1->y); - angle2 = R_PointToAngle64(line->v2->x, line->v2->y); + angle1 = R_PointToAngle64(v1x, v1y); + angle2 = R_PointToAngle64(v2x, v2y); curline = line; @@ -386,7 +395,7 @@ static void R_AddLine(seg_t *line) // Find the other side! INT32 line2 = P_FindSpecialLineFromTag(PORTALSPECIAL, line->linedef->tag, -1); - if (line->linedef == &lines[line2]) + if (line2 >= 0 && line->linedef == &lines[line2]) line2 = P_FindSpecialLineFromTag(PORTALSPECIAL, line->linedef->tag, line2); if (line2 >= 0) // found it! @@ -517,6 +526,7 @@ static boolean R_CheckBBox(const fixed_t *bspcoord) angle_t angle1, angle2; INT32 sx1, sx2; const INT32* check; + fixed_t x1, y1, x2, y2; // Find the corners of the box // that define the edges from current viewpoint. @@ -530,9 +540,14 @@ static boolean R_CheckBBox(const fixed_t *bspcoord) check = checkcoord[boxpos]; + x1 = bspcoord[check[0]]; + y1 = bspcoord[check[1]]; + x2 = bspcoord[check[2]]; + y2 = bspcoord[check[3]]; + // big room fix - angle1 = R_PointToAngle64(bspcoord[check[0]], bspcoord[check[1]]) - viewangle; - angle2 = R_PointToAngle64(bspcoord[check[2]], bspcoord[check[3]]) - viewangle; + angle1 = R_PointToAngle64(x1, y1) - viewangle; + angle2 = R_PointToAngle64(x2, y2) - viewangle; // cph - replaced old code, which was unclear and badly commented // Much more efficient code now @@ -991,7 +1006,6 @@ static void R_Subsector(size_t num) visffloor[numffloors].height = polysec->floorheight; visffloor[numffloors].polyobj = po; visffloor[numffloors].slope = NULL; -// visffloor[numffloors].ffloor = rover; po->visplane = visffloor[numffloors].plane; numffloors++; } diff --git a/src/r_data.c b/src/r_data.c index 386f0e700..507696925 100644 --- a/src/r_data.c +++ b/src/r_data.c @@ -37,44 +37,6 @@ // Not sure if this is necessary, but it was in w_wad.c, so I'm putting it here too -Shadow Hog #include -// -// Texture definition. -// Each texture is composed of one or more patches, -// with patches being lumps stored in the WAD. -// The lumps are referenced by number, and patched -// into the rectangular texture space using origin -// and possibly other attributes. -// -typedef struct -{ - INT16 originx, originy; - INT16 patch, stepdir, colormap; -} ATTRPACK mappatch_t; - -// -// Texture definition. -// An SRB2 wall texture is a list of patches -// which are to be combined in a predefined order. -// -typedef struct -{ - char name[8]; - INT32 masked; - INT16 width; - INT16 height; - INT32 columndirectory; // FIXTHIS: OBSOLETE - INT16 patchcount; - mappatch_t patches[1]; -} ATTRPACK maptexture_t; - -// Store lists of lumps for F_START/F_END etc. -typedef struct -{ - UINT16 wadfile; - UINT16 firstlump; - size_t numlumps; -} lumplist_t; - // // Graphics. // SRB2 graphics for walls and sprites @@ -622,7 +584,7 @@ Rloadtextures (INT32 i, INT32 w) // Set texture properties. memcpy(texture->name, W_CheckNameForNumPwad(wadnum, lumpnum), sizeof(texture->name)); - texture->hash = quickncasehash(texture->name, 8); + texture->hash = FNV1a_QuickCaseHash(texture->name, 8); texture->width = SHORT(patchlump.width); texture->height = SHORT(patchlump.height); @@ -836,11 +798,7 @@ static texpatch_t *R_ParsePatch(boolean actuallyLoadPatch) } else { - if (patchName != NULL) - { - Z_Free(patchName); - } - + Z_Free(patchName); patchName = (char *)Z_Malloc((texturesTokenLength+1)*sizeof(char),PU_STATIC,NULL); memcpy(patchName,texturesToken,texturesTokenLength*sizeof(char)); patchName[texturesTokenLength] = '\0'; @@ -1066,7 +1024,7 @@ static texture_t *R_ParseTexture(boolean actuallyLoadTexture) // Allocate memory for a zero-patch texture. Obviously, we'll be adding patches momentarily. resultTexture = (texture_t *)Z_Calloc(sizeof(texture_t), PU_STATIC, NULL); memcpy(resultTexture->name, newTextureName, 8); - resultTexture->hash = quickncasehash(newTextureName, 8); + resultTexture->hash = FNV1a_QuickCaseHash(newTextureName, 8); resultTexture->width = newTextureWidth; resultTexture->height = newTextureHeight; resultTexture->type = TEXTURETYPE_COMPOSITE; @@ -1366,7 +1324,7 @@ void R_ReInitColormaps(UINT16 num, lumpnum_t newencoremap) colormap_p = colormap_p2 = colormaps; colormap_p += COLORMAP_REMAPOFFSET; - for (p = 0; p < 32; p++) + for (p = 0; p < LIGHTLEVELS; p++) { for (i = 0; i < 256; i++) { @@ -1588,7 +1546,7 @@ INT32 R_CreateColormap(char *p1, char *p2, char *p3) // Calculate the palette index for each palette index, for each light level // (as well as the two unused colormap lines we inherited from Doom) - for (p = 0; p < 32; p++) + for (p = 0; p < LIGHTLEVELS; p++) { for (i = 0; i < 256; i++) { @@ -1622,7 +1580,7 @@ INT32 R_CreateColormap(char *p1, char *p2, char *p3) { lighttable_t *colormap_p2 = extra_colormaps[mapnum].colormap; - for (p = 0; p < 32; p++) + for (p = 0; p < LIGHTLEVELS; p++) { for (i = 0; i < 256; i++) { @@ -1720,8 +1678,7 @@ void R_InitData(void) void R_ClearTextureNumCache(boolean btell) { - if (tidcache) - Z_Free(tidcache); + Z_Free(tidcache); tidcache = NULL; if (btell) CONS_Debug(DBG_SETUP, "Fun Fact: There are %d textures used in this map.\n", tidcachelen); @@ -1756,7 +1713,7 @@ INT32 R_CheckTextureNumForName(const char *name) if (name[0] == '-') return 0; - hash = quickncasehash(name, 8); + hash = FNV1a_QuickCaseHash(name, 8); for (i = 0; i < tidcachelen; i++) if (tidcache[i].hash == hash && !strncasecmp(tidcache[i].name, name, 8)) diff --git a/src/r_data.h b/src/r_data.h index 090c363ed..168f72bf0 100644 --- a/src/r_data.h +++ b/src/r_data.h @@ -45,9 +45,6 @@ enum TEXTURETYPE_COMPOSITE, }; -// A maptexturedef_t describes a rectangular texture, -// which is composed of one or more mappatch_t structures -// that arrange graphic patches. typedef struct { // Keep name for switch changing, etc. diff --git a/src/r_defs.h b/src/r_defs.h index e6c5866c6..680a8a9cc 100644 --- a/src/r_defs.h +++ b/src/r_defs.h @@ -430,7 +430,7 @@ typedef struct line_s INT16 tag; // Visual appearance: sidedefs. - UINT16 sidenum[2]; // sidenum[1] will be 0xffff if one-sided + UINT16 sidenum[2]; // sidenum[1] will be NO_INDEX if one-sided fixed_t alpha; // translucency UINT8 blendmode; // blendmode @@ -531,11 +531,10 @@ typedef struct seg_s vertex_t *v1; vertex_t *v2; - INT32 side; - - fixed_t offset; - - angle_t angle; +#ifdef HWRENDER + floatvertex_t fv1; // v1 in floats - precalculated + floatvertex_t fv2; // v2 in floats - precalculated +#endif side_t *sidedef; line_t *linedef; @@ -545,11 +544,13 @@ typedef struct seg_s sector_t *frontsector; sector_t *backsector; + INT32 side; + fixed_t length; // precalculated seg length -#ifdef HWRENDER - floatvertex_t fv1; // v1 in floats - precalculated - floatvertex_t fv2; // v2 in floats - precalculated -#endif + fixed_t offset; + + angle_t angle; + polyobj_t *polyseg; // Fake contrast calculated on level load diff --git a/src/r_draw.cpp b/src/r_draw.cpp index 639107daa..24073a4d4 100644 --- a/src/r_draw.cpp +++ b/src/r_draw.cpp @@ -400,7 +400,7 @@ static UINT8* RGetTranslationColormap(INT32 skinnum, skincolors_t color, UINT8 f case TC_ALLWHITE: skintableindex = ALLWHITE_TT_CACHE_INDEX; break; case TC_RAINBOW: skintableindex = RAINBOW_TT_CACHE_INDEX; break; case TC_BLINK: skintableindex = BLINK_TT_CACHE_INDEX; break; - default: skintableindex = skinnum; break; + default: skintableindex = skinnum; break; } } @@ -419,7 +419,7 @@ static UINT8* RGetTranslationColormap(INT32 skinnum, skincolors_t color, UINT8 f // Generate the colormap if necessary if (!ret) { - ret = static_cast(Z_Malloc(NUM_PALETTE_ENTRIES, (flags & GTC_CACHE) ? PU_LEVEL : PU_STATIC, NULL)); + ret = static_cast(Z_Malloc(NUM_PALETTE_ENTRIES, PU_STATIC, NULL)); K_GenerateKartColormap(ret, skinnum, color, local); //R_GenerateTranslationColormap(ret, skinnum, color); // SRB2kart // Cache the colormap if desired @@ -437,8 +437,7 @@ UINT8* R_GetTranslationColormap(INT32 skinnum, skincolors_t color, UINT8 flags) UINT8* R_GetLocalTranslationColormap(skin_t *skin, skin_t *localskin, skincolors_t color, UINT8 flags, boolean local) { - const INT32 skinnum = localskin ? (localskin - K_GetSkinArray(local)) : (skin - skins); - return RGetTranslationColormap(skinnum, color, flags, (localskin && local)); + return RGetTranslationColormap(K_GetMobjLocalSkinNum(skin, localskin, local), color, flags, (localskin && local)); } patch_t* R_GetSkinFaceRank(player_t* ply) @@ -488,6 +487,10 @@ patch_t* R_GetSkinFaceMini(player_t* ply) \return void */ + +/* There seems to be no reason to free cached colormaps tho? Not like they can change :ChonkBunckle: */ + +/* void R_FlushTranslationColormapCache(void) { INT32 i; @@ -500,6 +503,7 @@ void R_FlushTranslationColormapCache(void) if (localtranslationtablecache[i]) memset(localtranslationtablecache[i], 0, MAXTRANSLATIONS * sizeof(UINT8**)); } +*/ // ========================================================================== // COMMON DRAWER FOR 8 AND 16 BIT COLOR MODES @@ -511,8 +515,6 @@ void R_FlushTranslationColormapCache(void) // in reality, the few routines that can work for either mode, are // put here -enum columncontext_e columncontext = COLUMNCONTEXT_DIRECT; - enum ColumnFlushType { FLUSH_NONE = 0x0000, @@ -530,9 +532,12 @@ typedef struct drawcolumndata_temp_s // e6y: resolution limitation is removed UINT8 *buf; - INT32 startx; - ColumnFlushType type; - INT32 commontop, commonbot; + INT32 startx; + + ColumnFlushType type; + + INT32 commontop, commonbot; + UINT8 *transmap; // SoM 7-28-04: Fix the fuzz problem. UINT8 *translation; @@ -560,8 +565,8 @@ FUNCNORETURN static ATTRNORETURN void R_QuadFlushError(void) } static void (*R_FlushWholeColumns)(void) = R_FlushWholeError; -static void (*R_FlushHTColumns)(void) = R_FlushHTError; -static void (*R_FlushQuadColumn)(void) = R_QuadFlushError; +static void (*R_FlushHTColumns)(void) = R_FlushHTError; +static void (*R_FlushQuadColumn)(void) = R_QuadFlushError; static void R_FlushColumns(void) { @@ -593,8 +598,8 @@ void R_ResetColumnBuffer(void) temp_dc.type = FLUSH_NONE; R_FlushWholeColumns = R_FlushWholeError; - R_FlushHTColumns = R_FlushHTError; - R_FlushQuadColumn = R_QuadFlushError; + R_FlushHTColumns = R_FlushHTError; + R_FlushQuadColumn = R_QuadFlushError; } /** \brief The R_InitViewBuffer function diff --git a/src/r_draw.h b/src/r_draw.h index a472b5537..a1d451fb4 100644 --- a/src/r_draw.h +++ b/src/r_draw.h @@ -105,7 +105,6 @@ enum columncontext_e COLUMNCONTEXT_FLUSH, }; -extern enum columncontext_e columncontext; void R_SetColumnContext(enum columncontext_e _columncontext); void R_ResetColumnBuffer(void); @@ -124,6 +123,8 @@ enum COLDRAWFUNC_TRANSTRANS, COLDRAWFUNC_TWOSMULTIPATCH, COLDRAWFUNC_TWOSMULTIPATCHTRANS, + COLDRAWFUNC_TWOSMULTIPATCH_DIRECT, + COLDRAWFUNC_TWOSMULTIPATCHTRANS_DIRECT, COLDRAWFUNC_FOG, COLDRAWFUNC_MAX diff --git a/src/r_draw_column.cpp b/src/r_draw_column.cpp index 67dbf94e3..526e136eb 100644 --- a/src/r_draw_column.cpp +++ b/src/r_draw_column.cpp @@ -204,7 +204,7 @@ static void R_DrawColumnTemplate(drawcolumndata_t *dc) intptr_t frac; // Looks familiar. const intptr_t fracstep = dc->iscale; - const intptr_t heightmask = dc->sourcelength-1; // CPhipps - specify type + intptr_t heightmask = dc->sourcelength-1; // CPhipps - specify type constexpr INT32 npow2min = -1; const INT32 npow2max = dc->sourcelength; @@ -237,10 +237,10 @@ static void R_DrawColumnTemplate(drawcolumndata_t *dc) // Determine scaling, which is the only mapping to be done. frac = (dc->texturemid + FixedMul((dc->yl << FRACBITS) - centeryfrac, fracstep)); - switch (heightmask) + switch (dc->sourcelength) { - case 255: - case 127: + case 256: + case 128: { while (count--) { @@ -251,7 +251,7 @@ static void R_DrawColumnTemplate(drawcolumndata_t *dc) } } break; - case npow2min: + case 0: { if (frac < 0) // adjust in case we underread @@ -269,42 +269,22 @@ static void R_DrawColumnTemplate(drawcolumndata_t *dc) break; default: { - if (!(dc->sourcelength & heightmask)) // power of 2 -- killough + if (dc->sourcelength & heightmask) // not a power of 2 -- killough { - while ((count -= 2) >= 0) // texture height is a power of 2 -- killough - { - *dest = R_DrawColumnPixel(dc, dest, (frac>>FRACBITS) & heightmask, source, colormap); - - dest += stride; - frac += fracstep; - - *dest = R_DrawColumnPixel(dc, dest, (frac>>FRACBITS) & heightmask, source, colormap); - - dest += stride; - frac += fracstep; - } - - if (count & 1) - { - *dest = R_DrawColumnPixel(dc, dest, (frac>>FRACBITS) & heightmask, source, colormap); - } - } - else - { - const intptr_t fixed_heightmask = dc->texheight << FRACBITS; + heightmask = dc->texheight << FRACBITS; if (frac < 0) { - while ((frac += fixed_heightmask) < 0) + while ((frac += heightmask) < 0) { ; } } else { - while (frac >= fixed_heightmask) + while (frac >= heightmask) { - frac -= fixed_heightmask; + frac -= heightmask; } } @@ -324,7 +304,7 @@ static void R_DrawColumnTemplate(drawcolumndata_t *dc) // Avoid overflow. if (fracstep > 0x7FFFFFFF - frac) { - frac += fracstep - fixed_heightmask; + frac += fracstep - heightmask; } else #endif @@ -332,13 +312,33 @@ static void R_DrawColumnTemplate(drawcolumndata_t *dc) frac += fracstep; } - while (frac >= fixed_heightmask) + while (frac >= heightmask) { - frac -= fixed_heightmask; + frac -= heightmask; } } while (--count); } + else + { + while ((count -= 2) >= 0) // texture height is a power of 2 -- killough + { + *dest = R_DrawColumnPixel(dc, dest, ((frac>>FRACBITS) & heightmask), source, colormap); + + dest += stride; + frac += fracstep; + + *dest = R_DrawColumnPixel(dc, dest, ((frac>>FRACBITS) & heightmask), source, colormap); + + dest += stride; + frac += fracstep; + } + + if (count & 1) + { + *dest = R_DrawColumnPixel(dc, dest, ((frac>>FRACBITS) & heightmask), source, colormap); + } + } } break; } diff --git a/src/r_fps.cpp b/src/r_fps.cpp index 7ccebf8e5..b96c9de23 100644 --- a/src/r_fps.cpp +++ b/src/r_fps.cpp @@ -387,10 +387,10 @@ void R_InterpolatePrecipMobjState(precipmobj_t *mobj, fixed_t frac, interpmobjst return; } - out->x = R_LerpFixed(mobj->old_x, mobj->x, frac); - out->y = R_LerpFixed(mobj->old_y, mobj->y, frac); - out->z = R_LerpFixed(mobj->old_z, mobj->z, frac); - out->scale = mapobjectscale; + out->x = R_LerpFixed(mobj->old_x, mobj->x, frac); + out->y = R_LerpFixed(mobj->old_y, mobj->y, frac); + out->z = R_LerpFixed(mobj->old_z, mobj->z, frac); + out->scale = mapobjectscale; } static levelinterpolator_t *CreateInterpolator(levelinterpolator_type_e type, thinker_t *thinker) @@ -757,6 +757,45 @@ void R_UpdateMobjInterpolators(void) } } +// reset banan and eggbox rollangle when they´re on the ground +// if not cv_bananthrowroll option "+Onground" +static void R_ResetBananaRollangle(mobj_t* mobj) +{ + if (!mobj->rollangle) + return; + + if (mobj->type != MT_BANANA && mobj->type != MT_EGGMANITEM) // always reset eggboxes + return; + + // keep banans "rotated" if we want them to + if (mobj->type == MT_BANANA && cv_bananthrowroll.value == 2) + return; + + // only reset if on ground + if (!P_IsObjectOnGround(mobj)) + return; + + mobj->rollangle = 0; +} + +// Reset our Sprite scales and offsets +// at the start of the tic +// this is just to make things simpler +// as we dont have to reset it ourselves after use +// done at the start so lua can still overwrite everything +static void R_ResetMobjSpriteStuff(mobj_t *mobj) +{ + mobj->spritexscale = mobj->realxscale; + mobj->spriteyscale = mobj->realyscale; + mobj->spritexoffset = mobj->realxoffset; + mobj->spriteyoffset = mobj->realyoffset; + + mobj->temprollangle = 0; + + // kinda stupid but idk where else to put this + R_ResetBananaRollangle(mobj); +} + // // P_ResetMobjInterpolationState // @@ -795,18 +834,9 @@ void R_ResetMobjInterpolationState(mobj_t *mobj) mobj->player->old_frameangle = mobj->player->frameangle; } - // Reset our Sprite scales and offsets - // at the start of the tic - // this is just to make things simpler - // as we dont have to reset it ourselves after use - // done at the start so lua can still overwrite everything - // technically not interpolation related // but this saves us another thinkerloop and multiple checks lel - mobj->spritexscale = mobj->realxscale; - mobj->spriteyscale = mobj->realyscale; - mobj->spritexoffset = mobj->realxoffset; - mobj->spriteyoffset = mobj->realyoffset; + R_ResetMobjSpriteStuff(mobj); mobj->resetinterp = false; } diff --git a/src/r_fps.h b/src/r_fps.h index 89efc6cfb..bf3f48362 100644 --- a/src/r_fps.h +++ b/src/r_fps.h @@ -15,16 +15,16 @@ #ifndef __R_FPS_H__ #define __R_FPS_H__ -#ifdef __cplusplus -extern "C" { -#endif - #include "m_fixed.h" #include "p_local.h" #include "r_state.h" #include "r_things.h" #include "m_perfstats.h" +#ifdef __cplusplus +extern "C" { +#endif + extern consvar_t cv_fpscap, cv_fpscapbg; extern ps_metric_t ps_interp_frac; diff --git a/src/r_main.cpp b/src/r_main.cpp index 1ad8e8be9..ad8f1aa0a 100644 --- a/src/r_main.cpp +++ b/src/r_main.cpp @@ -182,9 +182,13 @@ consvar_t cv_flipcam[MAXSPLITSCREENPLAYERS] = { {"flipcam4", "No", CV_SAVE|CV_CALL|CV_NOINIT, CV_YesNo, FlipCam4_OnChange, 0, NULL, NULL, 0, 0, NULL} }; +static CV_PossibleValue_t flipcammode_cons_t[] = {{0, "Displayplayer"}, {1, "Local"}, {0, NULL}}; +consvar_t cv_flipcammode = {"flipcammode", "Displayplayer", CV_SAVE, flipcammode_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; + consvar_t cv_shadow = {"shadow", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_shadowoffs = {"offsetshadows", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_skybox = {"skybox", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_skydome = {"skydome", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_ffloorclip = {"r_ffloorclip", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_spriteclip = {"r_spriteclip", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_softcyancut = {"softwarecyancut", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; @@ -277,22 +281,22 @@ static void Fov_OnChange(void) static void FlipCam_OnChange(void) { - SendWeaponPref(); + SendWeaponPref(0); } static void FlipCam2_OnChange(void) { - SendWeaponPref2(); + SendWeaponPref(1); } static void FlipCam3_OnChange(void) { - SendWeaponPref3(); + SendWeaponPref(2); } static void FlipCam4_OnChange(void) { - SendWeaponPref4(); + SendWeaponPref(3); } static void Precipstuff_OnChange(void) @@ -339,14 +343,14 @@ angle_t R_PointToAngle64(INT64 x, INT64 y) return (y -= viewy, (x -= viewx) || y) ? x >= 0 ? y >= 0 ? - (x > y) ? tantoangle[SlopeDivEx(y,x)] : // octant 0 - ANGLE_90-tantoangle[SlopeDivEx(x,y)] : // octant 1 - x > (y = -y) ? 0-tantoangle[SlopeDivEx(y,x)] : // octant 8 - ANGLE_270+tantoangle[SlopeDivEx(x,y)] : // octant 7 + (x > y) ? tantoangle[SlopeDivEx(y,x)] : // octant 0 + ANGLE_90-tantoangle[SlopeDivEx(x,y)] : // octant 1 + x > (y = -y) ? 0-tantoangle[SlopeDivEx(y,x)] : // octant 8 + ANGLE_270+tantoangle[SlopeDivEx(x,y)] : // octant 7 y >= 0 ? (x = -x) > y ? ANGLE_180-tantoangle[SlopeDivEx(y,x)] : // octant 3 - ANGLE_90 + tantoangle[SlopeDivEx(x,y)] : // octant 2 + ANGLE_90 + tantoangle[SlopeDivEx(x,y)] : // octant 2 (x = -x) > (y = -y) ? ANGLE_180+tantoangle[SlopeDivEx(y,x)] : // octant 4 - ANGLE_270-tantoangle[SlopeDivEx(x,y)] : // octant 5 + ANGLE_270-tantoangle[SlopeDivEx(x,y)] : // octant 5 0; } @@ -407,7 +411,7 @@ angle_t R_PlayerSliptideAngle(player_t *player) if (!sprframe) return 0; - if (sprframe->rotate != SRF_SINGLE || (mo->frame & FF_PAPERSPRITE)) + if (sprframe->rotate != SRF_SINGLE || R_ThingIsPaperSprite(mo)) ang = R_PointToAngle(mo->x, mo->y) - mo->angle; return FixedMul(FINECOSINE((ang) >> ANGLETOFINESHIFT), mo->player->sliproll * mo->player->kartstuff[k_aizdriftstrat]); @@ -922,11 +926,11 @@ void R_ExecuteSetViewSize(void) viewheight = vid.height; if (splitscreen) + { viewheight >>= 1; - if (splitscreen > 1) - { - viewwidth >>= 1; + if (splitscreen > 1) + viewwidth >>= 1; } centerx = viewwidth/2; @@ -953,13 +957,9 @@ void R_ExecuteSetViewSize(void) screenheightarray[i] = (INT16)viewheight; } - if (ds_su) - Z_Free(ds_su); - if (ds_sv) - Z_Free(ds_sv); - if (ds_sz) - Z_Free(ds_sz); - + Z_Free(ds_su); + Z_Free(ds_sv); + Z_Free(ds_sz); ds_su = ds_sv = ds_sz = NULL; memset(scalelight, 0xFF, sizeof(scalelight)); @@ -1015,8 +1015,8 @@ static void R_InitViewMapping(void) for (INT32 i = 0; i < j; i++) { - fixed_t dy = (i - viewheight*8)<numlines; i++) if (P_PointOnLineSide(x, y, segs[ret->firstline + i].linedef) != segs[ret->firstline + i].side) - return 0; + return NULL; return ret; } @@ -1389,6 +1389,21 @@ void R_RenderPlayerView(player_t *player) maskcount_t* masks = static_cast(malloc(sizeof(maskcount_t))); const boolean skybox = (skyboxmo[0] && cv_skybox.value); + // Only do it if it's the first screen being rendered + if (cv_homremoval.value && viewssnum == 0) + { + if (cv_homremoval.value == 1) + { + // Clear the software screen buffer to remove HOM + memset(vid.screens[0], 31, vid.width * vid.height); + } + else if (cv_homremoval.value == 2) + { + //'development' HOM removal -- makes it blindingly obvious if HOM is spotted. + memset(vid.screens[0], 32+(timeinmap&15), vid.width * vid.height); + } + } + // load previous saved value of skyVisible for the player skyVisible = skyVisiblePerPlayer[viewssnum]; @@ -1455,10 +1470,12 @@ void R_RenderPlayerView(player_t *player) NetUpdate(); R_SetColumnContext(COLUMNCONTEXT_FLUSH); + ps_numbspcalls.value.i = ps_numpolyobjects.value.i = ps_numdrawnodes.value.i = 0; PS_START_TIMING(ps_bsptime); R_RenderViewpoint(&masks[nummasks - 1], true); PS_STOP_TIMING(ps_bsptime); + PS_START_TIMING(ps_sw_spritecliptime); R_ClipSprites(drawsegs, NULL); PS_STOP_TIMING(ps_sw_spritecliptime); @@ -1466,8 +1483,8 @@ void R_RenderPlayerView(player_t *player) ps_numsprites.value.i = numvisiblesprites; - PS_START_TIMING(ps_sw_portaltime); // Portal rendering. Hijacks the BSP traversal. + PS_START_TIMING(ps_sw_portaltime); if (portal_base) { portal_t *portal; @@ -1508,8 +1525,7 @@ void R_RenderPlayerView(player_t *player) R_SetColumnContext(COLUMNCONTEXT_DIRECT); PS_START_TIMING(ps_sw_planetime); - if (!skybox) - R_DrawSkyPlanes(); + R_DrawSkyPlanes(); R_DrawPlanes(); PS_STOP_TIMING(ps_sw_planetime); // draw mid texture and sprite @@ -1517,6 +1533,7 @@ void R_RenderPlayerView(player_t *player) PS_START_TIMING(ps_sw_maskedtime); R_DrawMasked(masks, nummasks); PS_STOP_TIMING(ps_sw_maskedtime); + free(masks); // Check for new console commands. @@ -1546,6 +1563,8 @@ void R_RegisterEngineStuff(void) CV_RegisterVar(&cv_flipcam[i]); } + CV_RegisterVar(&cv_flipcammode); + // Enough for dedicated server if (dedicated) return; @@ -1563,6 +1582,7 @@ void R_RegisterEngineStuff(void) CV_RegisterVar(&cv_shadow); CV_RegisterVar(&cv_shadowoffs); CV_RegisterVar(&cv_skybox); + CV_RegisterVar(&cv_skydome); CV_RegisterVar(&cv_ffloorclip); CV_RegisterVar(&cv_spriteclip); CV_RegisterVar(&cv_secbright); @@ -1597,7 +1617,8 @@ void R_RegisterEngineStuff(void) CV_RegisterVar(&cv_sliptideroll); CV_RegisterVar(&cv_sloperolldist); CV_RegisterVar(&cv_sparkroll); - CV_RegisterVar(&cv_spinoutroll); + CV_RegisterVar(&cv_stairjank); + CV_RegisterVar(&cv_stairjanksfx); CV_RegisterVar(&cv_showhud); CV_RegisterVar(&cv_translucenthud); diff --git a/src/r_main.h b/src/r_main.h index 36c8756f8..3699822a3 100644 --- a/src/r_main.h +++ b/src/r_main.h @@ -14,14 +14,14 @@ #ifndef __R_MAIN__ #define __R_MAIN__ -#ifdef __cplusplus -extern "C" { -#endif - #include "d_player.h" #include "r_data.h" #include "m_perfstats.h" +#ifdef __cplusplus +extern "C" { +#endif + // // POV related. // @@ -205,6 +205,7 @@ extern consvar_t cv_showhud, cv_translucenthud, cv_uncappedhud; extern consvar_t cv_homremoval; extern consvar_t cv_chasecam[MAXSPLITSCREENPLAYERS]; extern consvar_t cv_flipcam[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_flipcammode; extern consvar_t cv_shadow, cv_shadowoffs; extern consvar_t cv_ffloorclip, cv_spriteclip; extern consvar_t cv_softcyancut; @@ -212,6 +213,7 @@ extern consvar_t cv_translucency; extern consvar_t cv_drawdist, cv_drawdist_precip, cv_lessprecip; extern consvar_t cv_fov, cv_fovchange; extern consvar_t cv_skybox; +extern consvar_t cv_skydome; extern consvar_t cv_tailspickup; extern consvar_t cv_maxinterpdist; extern consvar_t cv_playerfade; diff --git a/src/r_patch.cpp b/src/r_patch.cpp index 60d4acb98..c7c49b827 100644 --- a/src/r_patch.cpp +++ b/src/r_patch.cpp @@ -161,7 +161,7 @@ static void R_ParseSpriteInfo(boolean spr2) if (i == NUMSPRITES) I_Error("Error parsing SPRTINFO lump: Unknown sprite name \"%s\"", newSpriteName); - if (!memcmp(newSpriteName,sprnames[i], 4)) + if (!memcmp(newSpriteName, sprnames[i], 4)) { sprnum = static_cast(i); break; @@ -289,7 +289,7 @@ void R_ParseSPRTINFOLump(UINT16 wadNum, UINT16 lumpNum) sprinfoLumpLength = W_LumpLengthPwad(wadNum, lumpNum); sprinfoText = (char *)Z_Malloc((sprinfoLumpLength+1)*sizeof(char),PU_STATIC,NULL); // Now move the contents of the lump into this new location. - memmove(sprinfoText,sprinfoLump,sprinfoLumpLength); + memmove(sprinfoText, sprinfoLump, sprinfoLumpLength); // Make damn well sure the last character in our new memory location is \0. sprinfoText[sprinfoLumpLength] = '\0'; // Finally, free up the memory from the first data load, because we really @@ -405,10 +405,8 @@ static void Patch_FreeData(patch_t *patch) }*/ #endif - if (patch->columnofs) - Z_Free(patch->columnofs); - if (patch->columns) - Z_Free(patch->columns); + Z_Free(patch->columnofs); + Z_Free(patch->columns); } void Patch_Free(patch_t *patch) @@ -445,6 +443,7 @@ void *Patch_AllocateHardwarePatch(patch_t *patch) GLPatch_t *glPatch = static_cast(Z_Calloc(sizeof(GLPatch_t), PU_HWRPATCHINFO, &patch->hardware)); glPatch->mipmap = static_cast(Z_Calloc(sizeof(GLMipmap_t), PU_HWRPATCHINFO, &glPatch->mipmap)); } + return (void *)(patch->hardware); } diff --git a/src/r_plane.cpp b/src/r_plane.cpp index b2d30185d..df289faa0 100644 --- a/src/r_plane.cpp +++ b/src/r_plane.cpp @@ -57,8 +57,11 @@ visffloor_t visffloor[MAXFFLOORS] = {}; INT32 numffloors = 0; //SoM: 3/23/2000: Boom visplane hashing routine. -#define visplane_hash(picnum,lightlevel,height) \ - ((unsigned)((picnum)*3+(lightlevel)+(height)*7) & VISPLANEHASHMASK) +constexpr unsigned int visplane_hash(const unsigned int picnum, const unsigned int lightlevel, + const unsigned int height) +{ + return ((picnum * 3) + lightlevel + (height * 7)) & VISPLANEHASHMASK; +} // // Clip values are the solid pixel bounding the range. @@ -136,7 +139,7 @@ void R_AllocPlaneMemory(void) } yslopetab = static_cast(Z_Realloc(yslopetab, sizeof(*yslopetab) * (viewheight * 16), PU_STATIC, NULL)); - spanstart = static_cast(Z_Realloc(spanstart, sizeof(*spanstart) * viewheight, PU_STATIC, NULL)); + spanstart = static_cast(Z_Realloc(spanstart, sizeof(*spanstart) * viewheight, PU_STATIC, NULL)); } // @@ -451,7 +454,7 @@ visplane_t *R_FindPlane(fixed_t height, INT32 picnum, INT32 lightlevel, } } - hash = visplane_hash(picnum, lightlevel, height); + hash = visplane_hash(picnum, lightlevel, height >> FRACBITS); for (check = visplanes[hash]; check; check = check->next) { @@ -562,7 +565,7 @@ visplane_t *R_CheckPlane(visplane_t *pl, INT32 start, INT32 stop) } else { - unsigned hash = visplane_hash(pl->picnum, pl->lightlevel, pl->height); + unsigned hash = visplane_hash(pl->picnum, pl->lightlevel, pl->height >> FRACBITS); new_pl = new_visplane(hash); } @@ -782,6 +785,8 @@ static void R_DrawSkyPlane(visplane_t *pl, void(*skycolfunc)(drawcolumndata_t*), drawcolumndata_t dc = {}; const INT32 texture = texturetranslation[skytexture]; + const boolean skydome = cv_skydome.value != 0; + // Reset column drawer function (note: couldn't we just call colfuncs[BASEDRAWFUNC] directly?) // (that is, unless we'll need to switch drawers in future for some reason) R_SetColumnFunc(BASEDRAWFUNC); @@ -827,8 +832,8 @@ static void R_DrawSkyPlane(visplane_t *pl, void(*skycolfunc)(drawcolumndata_t*), INT32 angle = (pl->viewangle + xtoviewangle[x + i])>>ANGLETOSKYSHIFT; angle -= (skytextureoffset >> FRACBITS); - - dc.iscale = FixedMul(skyscale, FINECOSINE(xtoviewangle[x + i]>>ANGLETOFINESHIFT)); + if (skydome) + dc.iscale = FixedMul(skyscale, FINECOSINE(xtoviewangle[x + i]>>ANGLETOFINESHIFT)); dc.x = x + i; dc.source = R_GetColumn(texture, -angle); // get negative of angle for each column to display sky correct way round! --Monster Iestyn 27/01/18 @@ -863,7 +868,8 @@ static void R_DrawSkyPlane(visplane_t *pl, void(*skycolfunc)(drawcolumndata_t*), INT32 angle = (pl->viewangle + xtoviewangle[x])>>ANGLETOSKYSHIFT; angle -= (skytextureoffset >> FRACBITS); - dc.iscale = FixedMul(skyscale, FINECOSINE(xtoviewangle[x]>>ANGLETOFINESHIFT)); + if (skydome) + dc.iscale = FixedMul(skyscale, FINECOSINE(xtoviewangle[x]>>ANGLETOFINESHIFT)); dc.x = x; dc.source = R_GetColumn(texturetranslation[skytexture], -angle); // get negative of angle for each column to display sky correct way round! --Monster Iestyn 27/01/18 @@ -920,12 +926,12 @@ static void R_SetSlopePlane(drawspandata_t* ds, pslope_t *slope, fixed_t xpos, f // m is the v direction vector in view space ang = ANG2RAD(ANGLE_180 - (angle + plangle)); - m->x = cos(ang); - m->z = sin(ang); + m->x = cosf(ang); + m->z = sinf(ang); // n is the u direction vector in view space - n->x = sin(ang); - n->z = -cos(ang); + n->x = sinf(ang); + n->z = -cosf(ang); plangle >>= ANGLETOFINESHIFT; temp = P_GetSlopeZAt(slope, xpos + FINESINE(plangle), ypos + FINECOSINE(plangle)); @@ -1279,10 +1285,7 @@ void R_DrawSinglePlane(drawspandata_t* ds, visplane_t *pl, boolean allow_paralle else { // Don't mess with angle on slopes! We'll handle this ourselves later - if (viewangle != pl->viewangle + pl->plangle) - { - viewangle = pl->viewangle + pl->plangle; - } + viewangle = pl->viewangle + pl->plangle; ds->planeheight = abs(pl->height - pl->viewz); ds->planezlight = zlight[light]; diff --git a/src/r_portal.c b/src/r_portal.c index 661034a3f..f403c17c7 100644 --- a/src/r_portal.c +++ b/src/r_portal.c @@ -246,7 +246,6 @@ static boolean TrimVisplaneBounds(const visplane_t* plane, INT16* start, INT16* if (!(*start < *end)) return true; - /** Trims a visplane's horizontal gap to match its render area. * * Visplanes' minx/maxx may sometimes exceed the area they're @@ -273,7 +272,7 @@ static boolean TrimVisplaneBounds(const visplane_t* plane, INT16* start, INT16* * Applies the necessary offsets and rotation to give * a depth illusion to the skybox. */ -void Portal_AddSkybox(const visplane_t* plane) +static void Portal_AddSkybox(const visplane_t* plane) { INT16 start, end; mapheader_t *mh; @@ -334,10 +333,13 @@ void Portal_AddSkyboxPortals(void) INT32 i; UINT16 count = 0; - for (i = 0; i < MAXVISPLANES; i++, pl++) + for (i = 0; i < MAXVISPLANES; i++) { for (pl = visplanes[i]; pl; pl = pl->next) { + if (pl->minx >= pl->maxx) + continue; + if (pl->picnum == skyflatnum) { Portal_AddSkybox(pl); diff --git a/src/r_portal.h b/src/r_portal.h index 223dd83be..4c4583903 100644 --- a/src/r_portal.h +++ b/src/r_portal.h @@ -58,7 +58,6 @@ void Portal_Add2Lines (const INT32 line1, const INT32 line2, const INT32 x1, con void Portal_ClipApply (const portal_t* portal); -void Portal_AddSkybox(const visplane_t* plane); void Portal_AddSkyboxPortals(void); #ifdef __cplusplus diff --git a/src/r_segs.cpp b/src/r_segs.cpp index c0aab2bfc..3f6b9d449 100644 --- a/src/r_segs.cpp +++ b/src/r_segs.cpp @@ -15,6 +15,9 @@ #include "r_local.h" #include "r_sky.h" +#include +#include + #include "r_portal.h" #include "r_splats.h" #include "r_fps.h" // newview @@ -308,6 +311,7 @@ static void R_RenderMaskedSegLoop(drawcolumndata_t* dc, drawseg_t *drawseg, INT3 { rw_scalestep = drawseg->scalestep; spryscale = drawseg->scale1 + (x1 - drawseg->x1)*rw_scalestep; + if (dc->numlights) { // reset all lights to their starting heights for (i = 0; i < dc->numlights; i++) @@ -432,6 +436,7 @@ static void R_RenderMaskedSegLoop(drawcolumndata_t* dc, drawseg_t *drawseg, INT3 windowtop = windowbottom + 1; set_colormap_below_light(); } + windowbottom = realbot; if (windowtop < windowbottom) colfunc_2s(dc, col); @@ -708,16 +713,11 @@ void R_RenderThickSideRange(drawseg_t *drawseg, INT32 x1, INT32 x2, ffloor_t *pf rw_scalestep = drawseg->scalestep; spryscale = drawseg->scale1 + (x1 - drawseg->x1)*rw_scalestep; -#define CLAMPMAX INT32_MAX -#define CLAMPMIN (-INT32_MAX) // This is not INT32_MIN on purpose! INT32_MIN makes the drawers freak out. auto overflow_clamp = [&](INT64 overflow_test) { - return (overflow_test > (INT64)CLAMPMAX) ? CLAMPMAX : - (overflow_test > (INT64)CLAMPMIN) ? (fixed_t)overflow_test : - CLAMPMIN; + // This is not INT32_MIN on purpose! INT32_MIN makes the drawers freak out. + return (fixed_t)std::clamp(overflow_test, (-INT32_MAX), INT32_MAX); }; -#undef CLAMPMAX -#undef CLAMPMIN dc->numlights = 0; if (frontsector->numlights) @@ -1164,6 +1164,37 @@ static inline void R_ExpandPlaneY(visplane_t *pl, INT32 x, INT16 top, INT16 bott // CALLED: CORE LOOPING ROUTINE. // +static std::vector holecol(256); + +// used for R_DrawWallColumn +// convert "holey" columns into contigous columns +// filled with cyan in place of holes +static UINT8 *R_GetHoleColumn(drawcolumndata_t* dc) +{ + column_t *col = (column_t *)(dc->source - 3); + + const INT32 texheight = dc->texheight; + holecol.resize(texheight); + + // fill in everything with cyan so we can skip it + memset(holecol.data(), TRANSPARENTPIXEL, texheight); + + // shamelessly copy pasted from R_GenerateTexture + INT32 topdelta, prevdelta = -1; + while (col->topdelta != 0xff) + { + topdelta = col->topdelta; + if (topdelta <= prevdelta) + topdelta += prevdelta; + prevdelta = topdelta; + + memcpy(holecol.data() + topdelta, (UINT8*)col + 4, col->length); + col = (column_t *)((UINT8*)col + col->length + 4); + } + + return holecol.data(); +} + static void R_DrawWallColumn(drawcolumndata_t* dc, INT32 yl, INT32 yh, fixed_t mid, fixed_t texturecolumn, INT32 texture, boolean remap) { const INT32 itexturecolumn = texturecolumn >> FRACBITS; @@ -1173,13 +1204,35 @@ static void R_DrawWallColumn(drawcolumndata_t* dc, INT32 yl, INT32 yh, fixed_t m dc->source = R_GetColumn(texture, itexturecolumn); dc->texheight = textureheight[texture] >> FRACBITS; dc->sourcelength = dc->texheight; + R_SetColumnFunc(colfunctype); coldrawfunc_t* colfunccopy = colfunc; + + if (textures[texture]->holes) + { + dc->source = R_GetHoleColumn(dc); + + if (cv_softcyancut.value) + { + // need to use multipatch drawers to cut cyan pixels + if (R_CheckColumnFunc(COLDRAWFUNC_FUZZY) == true) + { + colfunccopy = colfuncs[COLDRAWFUNC_TWOSMULTIPATCHTRANS_DIRECT]; + } + else + { + colfunccopy = colfuncs[COLDRAWFUNC_TWOSMULTIPATCH_DIRECT]; + } + } + } + drawcolumndata_t dc_copy = *dc; + if (remap) { dc_copy.colormap += COLORMAP_REMAPOFFSET; } + colfunccopy(const_cast(&dc_copy)); } @@ -1220,6 +1273,15 @@ static void R_RenderSegLoop(drawcolumndata_t* dc) if (yl < top) yl = top; + // insanely shitty hack to fix flickering on some maps + // for god knows why, on secret slide the renderer assumes some double sided linedefs have insanely tall walls + // since such tall walls are effectively nonsense in any case + // just skip them + if (yl > FRACUNIT*3) + { + continue; + } + if (markceiling) { bottom = yl > floorclip[rw_x] ? floorclip[rw_x] : yl; @@ -1379,7 +1441,7 @@ static void R_RenderSegLoop(drawcolumndata_t* dc) // calculate lighting pindex = FixedMul(rw_scale, LIGHTRESOLUTIONFIX)>>LIGHTSCALESHIFT; - if (pindex >= MAXLIGHTSCALE) + if (pindex >= MAXLIGHTSCALE) pindex = MAXLIGHTSCALE-1; dc->colormap = walllights[pindex]; @@ -1414,7 +1476,7 @@ static void R_RenderSegLoop(drawcolumndata_t* dc) pindex = FixedMul(rw_scale, LIGHTRESOLUTIONFIX)>>LIGHTSCALESHIFT; - if (pindex >= MAXLIGHTSCALE) + if (pindex >= MAXLIGHTSCALE) pindex = MAXLIGHTSCALE-1; if (dc->lightlist[i].extra_colormap) @@ -1820,7 +1882,7 @@ void R_StoreWallRange(INT32 start, INT32 stop) // big room fix if (longboi) - rw_distance = (fixed_t)R_CalcSegDist(curline,viewx,viewy); + rw_distance = (fixed_t)R_CalcSegDist(curline, viewx, viewy); ds_p->x1 = rw_x = start; ds_p->x2 = stop; @@ -2139,7 +2201,7 @@ void R_StoreWallRange(INT32 start, INT32 stop) topremap = (encoremap && !(curline->linedef->flags & ML_TFERLINE)); if ((linedef->flags & (ML_DONTPEGTOP) && (linedef->flags & ML_DONTPEGBOTTOM)) - && linedef->sidenum[1] != 0xffff) + && linedef->sidenum[1] != NO_INDEX) { // Special case... use offsets from 2nd side but only if it has a texture. side_t *def = &sides[linedef->sidenum[1]]; @@ -2229,12 +2291,12 @@ void R_StoreWallRange(INT32 start, INT32 stop) lowcutslope = std::max(worldbottomslope, worldlowslope) + viewz; highcutslope = std::min(worldtopslope, worldhighslope) + viewz; - auto check_fof_offscreen = [&](ffloor_t* rover, INT32 bottom, INT32 bottomslope, INT32 top, INT32 topslope) + auto check_fof_offscreen = [&](ffloor_t* rrover, INT32 bottom, INT32 bottomslope, INT32 top, INT32 topslope) { - return ((P_GetFFloorTopZAt (rover, segleft .x, segleft .y) <= bottom + viewz - && P_GetFFloorTopZAt (rover, segright.x, segright.y) <= bottomslope + viewz) - || ( P_GetFFloorBottomZAt (rover, segleft .x, segleft .y) >= top + viewz - && P_GetFFloorBottomZAt (rover, segright.x, segright.y) >= topslope + viewz)); + return ((P_GetFFloorTopZAt (rrover, segleft .x, segleft .y) <= bottom + viewz + && P_GetFFloorTopZAt (rrover, segright.x, segright.y) <= bottomslope + viewz) + || ( P_GetFFloorBottomZAt (rrover, segleft .x, segleft .y) >= top + viewz + && P_GetFFloorBottomZAt (rrover, segright.x, segright.y) >= topslope + viewz)); }; if (frontsector->ffloors && backsector->ffloors) @@ -2537,69 +2599,91 @@ void R_StoreWallRange(INT32 start, INT32 stop) if (linedef->special == HORIZONSPECIAL) // HORIZON LINES { topstep = bottomstep = 0; - topfrac = bottomfrac = (centeryfrac>>4); + topfrac = bottomfrac = (centeryfrac >> 4); topfrac++; // Prevent 1px HOM } else { + topstep = -FixedMul(rw_scalestep, worldtop); + topfrac = (centeryfrac >> 4) - FixedMul(worldtop, rw_scale); + // for anyone that sees this // dont. // this is absolute shit-tier hacks // but i just cant determine this in any sane way // but this checks a shitton of things to make software handle skies better - auto set_topstep_normal = [&] - { - topstep = -FixedMul (rw_scalestep, worldtop); - topfrac = (centeryfrac>>4) - FixedMul (worldtop, rw_scale); - }; - // untextured seg - if (!segtextured && !curline->polyseg) + if (!segtextured && !curline->polyseg) // not for polyobjects..... { - const bool tophigh = (worldhigh <= worldtop && worldhighslope <= worldtopslope); + const boolean nofrontsky = (frontsector->floorpic != skyflatnum && frontsector->ceilingpic != skyflatnum); + const boolean inskybox = (skyboxmo[0] && cv_skybox.value && newview->sky); // dont mess with skyVisible within skybox rendering! - // if we cant see the goddamn skyplane, well there wont be any skybox - // we could kill skyVisible instead, but i want to keep the performance improvemnts it yields - // so we do this absolute trash - if ((tophigh - && (frontsector->floorpic != skyflatnum && frontsector->ceilingpic != skyflatnum)) // try to guess if its a "window" - && ((!backsector) // single sided - || ((backsector && (worldhigh != worldtop || worldhighslope != worldtopslope)) - && (backsector->floorheight >= frontsector->ceilingheight || backsector->ceilingheight <= frontsector->floorheight)))) // check if there is a "thok" sector behind it - skyVisible = true; - - // this is an attempt to fix issues with textureless single sided lines drawing nothing where they should just draw sky instead - if (tophigh && !backsector && frontsector->ceilingpic == skyflatnum) + // single sided line + if (!backsector) { - topstep = -FixedMul (rw_scalestep, worldbottom); - topfrac = (centeryfrac>>4) - FixedMul (worldbottom, rw_scale); + // this is an attempt to fix issues with textureless single sided lines drawing nothing where they should just draw sky instead - // account for slopes to try and get rid of sharp edges from the black void - if (frontsector->f_slope || (backsector && backsector->f_slope)) + // there is a sky flat on the ceiling + // so we can assume this is supposed to draw the sky + if (frontsector->ceilingpic == skyflatnum) { - topstep = -FixedMul (rw_scalestep, worldbottomslope); - topfrac = (centeryfrac>>4) - FixedMul (worldbottomslope, rw_scale); + // just draw sky from top to bottom! + if (frontsector->f_slope) + { + topstep = -FixedMul(rw_scalestep, worldbottomslope); + topfrac = (centeryfrac >> 4) - FixedMul(worldbottomslope, rw_scale); + } + else + { + topstep = -FixedMul(rw_scalestep, worldbottom); + topfrac = (centeryfrac >> 4) - FixedMul(worldbottom, rw_scale); + } + } + else if (nofrontsky && !inskybox) + { + // completely empty wall without sky flats, just assume skybox is visible then + skyVisible = true; } } - else - set_topstep_normal(); - } - else - set_topstep_normal(); + else if (nofrontsky && !inskybox) // if there was a skyflat, drawplane would already set skyvisible + { + // "thok walls" are double sided + // so we need to check a few things here + // to be rather conservative + // as skyrendering is pretty costly! - bottomstep = -FixedMul (rw_scalestep, worldbottom); - bottomfrac = (centeryfrac>>4) - FixedMul (worldbottom, rw_scale); + // ideally we´d just dont care and always draw the skytexture + // or skybox at any time, like gl does + // wonder if there would be a fast way to draw atleast just the texture? + + // gotta shift those here for proper comparisons + const INT32 whigh = worldhigh >> 4; + const INT32 whslope = worldhighslope >> 4; + + // check if there is a window to force skybox to draw + if ((whigh <= worldtop && whslope <= worldtopslope) && (backsector->ceilingpic == skyflatnum)) // backsector has a skyflat? + skyVisible = true; + // otherwise check for thokwalls + else if ((whigh != worldtop || whslope != worldtopslope) && // FIXME: i forgor what this was for lol + (backsector->floorheight >= frontsector->ceilingheight || // thok walls usually are set up like that... + frontsector->floorheight >= backsector->ceilingheight)) // floor higher than the other sides ceiling + skyVisible = true; + } + } + + bottomstep = -FixedMul(rw_scalestep, worldbottom); + bottomfrac = (centeryfrac >> 4) - FixedMul(worldbottom, rw_scale); if (frontsector->c_slope) { - fixed_t topfracend = (centeryfrac>>4) - FixedMul (worldtopslope, ds_p->scale2); + fixed_t topfracend = (centeryfrac >> 4) - FixedMul(worldtopslope, ds_p->scale2); topstep = (topfracend-topfrac)/(range); } if (frontsector->f_slope) { - fixed_t bottomfracend = (centeryfrac>>4) - FixedMul (worldbottomslope, ds_p->scale2); + fixed_t bottomfracend = (centeryfrac >> 4) - FixedMul(worldbottomslope, ds_p->scale2); bottomstep = (bottomfracend-bottomfrac)/(range); } } @@ -2637,12 +2721,13 @@ void R_StoreWallRange(INT32 start, INT32 stop) if (leftheight < worldbottom && rightheight < worldbottomslope) continue; - if (leftheight > worldtop && rightheight > worldtopslope && i+1 < dc.numlights && frontsector->lightlist[i+1].height > frontsector->ceilingheight) + if ((leftheight > worldtop) && (rightheight > worldtopslope) && + (i+1 < dc.numlights) && (frontsector->lightlist[i+1].height > frontsector->ceilingheight)) continue; } - rlight->height = (centeryfrac>>4) - FixedMul(leftheight, rw_scale); - rlight->heightstep = (centeryfrac>>4) - FixedMul(rightheight, ds_p->scale2); + rlight->height = (centeryfrac >> 4) - FixedMul(leftheight, rw_scale); + rlight->heightstep = (centeryfrac >> 4) - FixedMul(rightheight, ds_p->scale2); rlight->heightstep = (rlight->heightstep-rlight->height)/(range); rlight->flags = static_cast(light->flags); @@ -2661,10 +2746,9 @@ void R_StoreWallRange(INT32 start, INT32 stop) leftheight >>= 4; rightheight >>= 4; - rlight->botheight = (centeryfrac>>4) - FixedMul(leftheight, rw_scale); - rlight->botheightstep = (centeryfrac>>4) - FixedMul(rightheight, ds_p->scale2); + rlight->botheight = (centeryfrac >> 4) - FixedMul(leftheight, rw_scale); + rlight->botheightstep = (centeryfrac >> 4) - FixedMul(rightheight, ds_p->scale2); rlight->botheightstep = (rlight->botheightstep-rlight->botheight)/(range); - } rlight->lightlevel = *light->lightlevel; @@ -2685,13 +2769,14 @@ void R_StoreWallRange(INT32 start, INT32 stop) if (linedef->special == HORIZONSPECIAL) // Horizon lines extend FOFs in contact with them too. { visffloor[i].f_step = 0; - visffloor[i].f_frac = (centeryfrac>>4); + visffloor[i].f_frac = (centeryfrac >> 4); topfrac++; // Prevent 1px HOM } else { - visffloor[i].f_frac = (centeryfrac>>4) - FixedMul(visffloor[i].f_pos, rw_scale); - visffloor[i].f_step = ((centeryfrac>>4) - FixedMul(visffloor[i].f_pos_slope, ds_p->scale2) - visffloor[i].f_frac)/(range); + visffloor[i].f_frac = (centeryfrac >> 4) - FixedMul(visffloor[i].f_pos, rw_scale); + visffloor[i].f_step = (centeryfrac >> 4) - FixedMul(visffloor[i].f_pos_slope, ds_p->scale2); + visffloor[i].f_step = (visffloor[i].f_step - visffloor[i].f_frac)/(range); } } } @@ -2705,9 +2790,8 @@ void R_StoreWallRange(INT32 start, INT32 stop) if (toptexture) { - fixed_t topfracend = (centeryfrac>>4) - FixedMul(worldhighslope, ds_p->scale2); - - pixhigh = (centeryfrac>>4) - FixedMul (worldhigh, rw_scale); + fixed_t topfracend = (centeryfrac >> 4) - FixedMul(worldhighslope, ds_p->scale2); + pixhigh = (centeryfrac >> 4) - FixedMul(worldhigh, rw_scale); pixhighstep = (topfracend-pixhigh)/(range); // If the lowest part of a ceiling stretching down covers the entire screen @@ -2717,9 +2801,8 @@ void R_StoreWallRange(INT32 start, INT32 stop) if (bottomtexture) { - fixed_t bottomfracend = (centeryfrac>>4) - FixedMul (worldlowslope, ds_p->scale2); - - pixlow = (centeryfrac>>4) - FixedMul (worldlow, rw_scale); + fixed_t bottomfracend = (centeryfrac >> 4) - FixedMul(worldlowslope, ds_p->scale2); + pixlow = (centeryfrac >> 4) - FixedMul(worldlow, rw_scale); pixlowstep = (bottomfracend-pixlow)/(range); // If the highest part of a floor stretching up covers the entire screen @@ -2878,7 +2961,7 @@ void R_StoreWallRange(INT32 start, INT32 stop) if (markceiling) { if (ceilingplane) //SoM: 3/29/2000: Check for null ceiling planes - ceilingplane = R_CheckPlane (ceilingplane, rw_x, rw_stopx-1); + ceilingplane = R_CheckPlane(ceilingplane, rw_x, rw_stopx-1); else markceiling = false; @@ -2892,7 +2975,7 @@ void R_StoreWallRange(INT32 start, INT32 stop) if (markfloor) { if (floorplane) //SoM: 3/29/2000: Check for null planes - floorplane = R_CheckPlane (floorplane, rw_x, rw_stopx-1); + floorplane = R_CheckPlane(floorplane, rw_x, rw_stopx-1); else markfloor = false; @@ -2980,6 +3063,7 @@ void R_StoreWallRange(INT32 start, INT32 stop) ds_p->silhouette |= SIL_BOTTOM; ds_p->bsilheight = backsector->f_slope ? INT32_MAX : backsector->floorheight; } + if (!(ds_p->silhouette & SIL_TOP)) { ds_p->silhouette |= SIL_TOP; diff --git a/src/r_skins.c b/src/r_skins.c index 538b8c38a..a8496c7f5 100644 --- a/src/r_skins.c +++ b/src/r_skins.c @@ -42,8 +42,8 @@ INT32 numallskins = 0; INT32 numlocalskins = 0; skin_t skins[MAXSKINS]; -UINT8 skinstats[9][9][MAXSKINS]; -UINT8 skinstatscount[9][9] = { +skinnum_t skinstats[9][9][MAXSKINS]; +skinnum_t skinstatscount[9][9] = { {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, @@ -55,7 +55,7 @@ UINT8 skinstatscount[9][9] = { {0, 0, 0, 0, 0, 0, 0, 0, 0} }; -UINT8 skinsorted[MAXSKINS] = {}; +skinnum_t skinsorted[MAXSKINS] = {}; skin_t localskins[MAXLOCALSKINS] = {}; skin_t allskins[MAXSKINS+MAXLOCALSKINS] = {}; @@ -302,7 +302,7 @@ void SetLocalPlayerSkin(INT32 playernum, const char *skinname, consvar_t *cvar) if (player->mo) { - player->mo->localskin = 0; + player->mo->localskin = NULL; player->mo->skinlocal = false; } } @@ -398,8 +398,8 @@ static UINT16 W_CheckForSkinMarkerInPwad(UINT16 wadid, UINT16 startlump) static int skinSortFunc(const void *a, const void *b) // tbh i have no clue what the naming conventions for local functions are { int diff = 0; - const UINT8 val_a = *(const UINT8 *)a; - const UINT8 val_b = *(const UINT8 *)b; + const skinnum_t val_a = *(const skinnum_t *)a; + const skinnum_t val_b = *(const skinnum_t *)b; const skin_t *in1 = &skins[val_a]; const skin_t *in2 = &skins[val_b]; @@ -474,7 +474,7 @@ static int skinSortFunc(const void *a, const void *b) // tbh i have no clue what void sortSkinGrid(void) { //CONS_Printf("Sorting skin list (%d)...\n", cv_skinselectgridsort.value); - qs22j(skinsorted, numskins, sizeof(UINT8), skinSortFunc); + qs22j(skinsorted, numskins, sizeof(skinnum_t), skinSortFunc); } // @@ -712,7 +712,7 @@ void R_AddSkins(UINT16 wadnum, boolean local) // skip to end of this skin's frames lastlump = lump; - while (W_CheckNameForNumPwad(wadnum, lastlump) && memcmp(W_CheckNameForNumPwad(wadnum, lastlump), csprname,4)==0) + while (W_CheckNameForNumPwad(wadnum, lastlump) && memcmp(W_CheckNameForNumPwad(wadnum, lastlump), csprname, 4) == 0) lastlump++; // allocate (or replace) sprite frames, and set spritedef @@ -774,7 +774,7 @@ void R_AddSkins(UINT16 wadnum, boolean local) // So just let the function in the while loop take care of it for us. } - R_FlushTranslationColormapCache(); + //R_FlushTranslationColormapCache(); CONS_Printf(M_GetText("Added skin '%s'\n"), skin->name); #ifdef SKINVALUES @@ -817,7 +817,6 @@ void R_AddSkins(UINT16 wadnum, boolean local) } #undef lnumskins - //sortSkinGrid(); return; } diff --git a/src/r_skins.h b/src/r_skins.h index 6231e8a18..d3e196827 100644 --- a/src/r_skins.h +++ b/src/r_skins.h @@ -71,9 +71,9 @@ extern INT32 numskins; extern INT32 numlocalskins; extern INT32 numallskins; extern skin_t skins[MAXSKINS]; -extern UINT8 skinstats[9][9][MAXSKINS]; -extern UINT8 skinstatscount[9][9]; -extern UINT8 skinsorted[MAXSKINS]; +extern skinnum_t skinstats[9][9][MAXSKINS]; +extern skinnum_t skinstatscount[9][9]; +extern skinnum_t skinsorted[MAXSKINS]; extern skin_t localskins[MAXLOCALSKINS]; extern skin_t allskins[MAXSKINS+MAXLOCALSKINS]; @@ -92,6 +92,7 @@ INT32 R_LocalSkinAvailable(const char *name, boolean local); // had to move those here Zzz... INT32 K_GetSkinNum(player_t *player); INT32 K_GetMobjSkinNum(const skin_t *skin, boolean local); +INT32 K_GetMobjLocalSkinNum(const skin_t *skin, const skin_t *localskin, boolean local); skin_t *K_GetPlayerSkin(player_t *player); skin_t *K_GetMobjSkin(const mobj_t *mobj); patch_t *K_GetFacePrefix(player_t *player, INT32 skinnum); diff --git a/src/r_splats.c b/src/r_splats.c index bcef8cf24..5560477ba 100644 --- a/src/r_splats.c +++ b/src/r_splats.c @@ -131,7 +131,7 @@ void R_AddWallSplat(line_t *wallline, INT16 sectorside, const char *patchname, f // set the splat splat->patch = W_GetNumForName(patchname); sectorside ^= 1; - if (wallline->sidenum[sectorside] != 0xffff) + if (wallline->sidenum[sectorside] != NO_INDEX) { backsector = sides[wallline->sidenum[sectorside]].sector; diff --git a/src/r_state.h b/src/r_state.h index 0431525e7..5e226103b 100644 --- a/src/r_state.h +++ b/src/r_state.h @@ -90,7 +90,7 @@ extern side_t *sides; extern fixed_t viewx, viewy, viewz; extern angle_t viewangle, aimingangle, viewroll; extern UINT8 viewssnum; // splitscreen view number -extern boolean viewsky, skyVisible; +extern boolean skyVisible; extern boolean skyVisiblePerPlayer[MAXSPLITSCREENPLAYERS]; // saved values of skyVisible of each splitscreen player extern sector_t *viewsector; extern player_t *viewplayer; diff --git a/src/r_things.cpp b/src/r_things.cpp index 489ce8911..79c280ee5 100644 --- a/src/r_things.cpp +++ b/src/r_things.cpp @@ -70,7 +70,7 @@ INT16 *screenheightarray = NULL; typedef struct drawseg_xrange_item_s { - INT16 x1, x2; + INT32 x1, x2; drawseg_t *user; } drawseg_xrange_item_t; @@ -87,6 +87,8 @@ static drawseg_xrange_item_t *drawsegs_xrange; static size_t drawsegs_xrange_size = 0; static INT32 drawsegs_xrange_count = 0; +#define CLIP_UNDEF -2 + // // Sprite rotation 0 is facing the viewer, // rotation 1 is one angle turn CLOCKWISE around the axis. @@ -166,11 +168,13 @@ static void R_InstallSpriteLump(UINT16 wad, // graphics patch CONS_Debug(DBG_SETUP, "R_InitSprites: Sprite %s frame %c has rotations and a rot = 0 lump\n", spritename, cn); sprtemp[frame].rotate = SRF_SINGLE; + for (r = 0; r < 8; r++) { sprtemp[frame].lumppat[r] = lumppat; sprtemp[frame].lumpid[r] = lumpid; } + sprtemp[frame].flip = flipped ? UINT8_MAX : 0; // 11111111 in binary return; } @@ -180,15 +184,14 @@ static void R_InstallSpriteLump(UINT16 wad, // graphics patch UINT8 rightfactor = ((rotation == ROT_R) ? 4 : 0); // the lump should be used for half of all rotations - if (sprtemp[frame].rotate == SRF_SINGLE) + if (sprtemp[frame].rotate == SRF_NONE) + sprtemp[frame].rotate = SRF_SINGLE; + else if (sprtemp[frame].rotate == SRF_SINGLE) CONS_Debug(DBG_SETUP, "R_InitSprites: Sprite %s frame %c has L/R rotations and a rot = 0 lump\n", spritename, cn); else if (sprtemp[frame].rotate == SRF_3D) CONS_Debug(DBG_SETUP, "R_InitSprites: Sprite %s frame %c has both L/R and 1-8 rotations\n", spritename, cn); // Let's not complain about multiple L/R rotations. It's not worth the effort. - if (sprtemp[frame].rotate == SRF_NONE) - sprtemp[frame].rotate = SRF_SINGLE; - sprtemp[frame].rotate |= ((rotation == ROT_R) ? SRF_RIGHT : SRF_LEFT); if (sprtemp[frame].rotate == (SRF_3D|SRF_2D)) @@ -231,6 +234,7 @@ static void R_InstallSpriteLump(UINT16 wad, // graphics patch // when using sprites in pwad : the lumppat points the new graphics sprtemp[frame].lumppat[rotation] = lumppat; sprtemp[frame].lumpid[rotation] = lumpid; + if (flipped) sprtemp[frame].flip |= (1<numframes) // (then spriteframes is not null) { // copy the already defined sprite frames - memcpy(sprtemp, spritedef->spriteframes, - spritedef->numframes * sizeof (spriteframe_t)); + memcpy(sprtemp, spritedef->spriteframes, spritedef->numframes * sizeof (spriteframe_t)); maxframe = spritedef->numframes - 1; } @@ -288,7 +293,7 @@ boolean R_AddSingleSpriteDef(const char *sprname, spritedef_t *spritedef, UINT16 if (frame >= 64 || !(R_ValidSpriteAngle(rotation))) // Give an actual NAME error -_-... { - CONS_Alert(CONS_WARNING, M_GetText("Bad sprite name: %s\n"), W_CheckNameForNumPwad(wadnum,l)); + CONS_Alert(CONS_WARNING, M_GetText("Bad sprite name: %s\n"), W_CheckNameForNumPwad(wadnum, l)); continue; } @@ -314,6 +319,15 @@ boolean R_AddSingleSpriteDef(const char *sprname, spritedef_t *spritedef, UINT16 { frame = R_Char2Frame(lumpinfo[l].name[6]); rotation = (UINT8)(lumpinfo[l].name[7] - '0'); + + /* + if (frame >= 64 || !(R_ValidSpriteAngle(rotation))) // Give an actual NAME error -_-... + { + CONS_Alert(CONS_WARNING, M_GetText("Bad sprite name: %s\n"), W_CheckNameForNumPwad(wadnum, l)); + continue; + } + */ + R_InstallSpriteLump(wadnum, l, numspritelumps, frame, rotation, 1); } @@ -362,38 +376,39 @@ boolean R_AddSingleSpriteDef(const char *sprname, spritedef_t *spritedef, UINT16 switch (sprtemp[frame].rotate) { case SRF_NONE: - // no rotations were found for that frame at all - I_Error("R_AddSingleSpriteDef: No patches found for %.4s frame %c", sprname, R_Frame2Char(frame)); - break; + // no rotations were found for that frame at all + I_Error("R_AddSingleSpriteDef: No patches found for %.4s frame %c", sprname, R_Frame2Char(frame)); + break; case SRF_SINGLE: - // only the first rotation is needed - break; + // only the first rotation is needed + break; case SRF_2D: // both Left and Right rotations // we test to see whether the left and right slots are present if ((sprtemp[frame].lumppat[2] == LUMPERROR) || (sprtemp[frame].lumppat[6] == LUMPERROR)) I_Error("R_AddSingleSpriteDef: Sprite %s frame %c is missing rotations", sprname, R_Frame2Char(frame)); - break; + break; default: - // must have all 8 frames - for (rotation = 0; rotation < 8; rotation++) - // we test the patch lump, or the id lump whatever - // if it was not loaded the two are LUMPERROR - if (sprtemp[frame].lumppat[rotation] == LUMPERROR) - I_Error("R_AddSingleSpriteDef: Sprite %.4s frame %c is missing rotations", - sprname, R_Frame2Char(frame)); - break; + // must have all 8 frames + for (rotation = 0; rotation < 8; rotation++) + { + // we test the patch lump, or the id lump whatever + // if it was not loaded the two are LUMPERROR + if (sprtemp[frame].lumppat[rotation] == LUMPERROR) + I_Error("R_AddSingleSpriteDef: Sprite %.4s frame %c is missing rotations", + sprname, R_Frame2Char(frame)); + } + break; } } // allocate space for the frames present and copy sprtemp to it if (spritedef->numframes && // has been allocated - spritedef->numframes < maxframe) // more frames are defined ? + spritedef->numframes < maxframe) // more frames are defined ? { - Z_Free(spritedef->spriteframes); spritedef->spriteframes = NULL; } @@ -450,12 +465,10 @@ void R_AddSpriteDefs(UINT16 wadnum) // for (i = 0; i < numsprites; i++) { - spritename = sprnames[i]; - - if (spritename[4] && wadnum >= (UINT16)spritename[4]) + if (sprnames[i][4] && wadnum >= (UINT16)sprnames[i][4]) continue; - if (R_AddSingleSpriteDef(spritename, &sprites[i], wadnum, start, end)) + if (R_AddSingleSpriteDef(sprnames[i], &sprites[i], wadnum, start, end)) { #ifdef HWRENDER if (rendermode == render_opengl) @@ -463,9 +476,7 @@ void R_AddSpriteDefs(UINT16 wadnum) #endif // if a new sprite was added (not just replaced) addsprites++; -#ifndef ZDEBUG - CONS_Debug(DBG_SETUP, "sprite %s set in pwad %d\n", spritename, wadnum); -#endif + CONS_Debug(DBG_SETUP, "sprite %s set in pwad %d\n", sprnames[i], wadnum); } } @@ -489,8 +500,8 @@ void R_InitSprites(void) for (angle = 1; angle < ROTANGLES; angle++) { fa = ANG2RAD(FixedAngle((ROTANGDIFF * angle)<> VISSPRITECHUNKBITS] = {0}; -static INT16 *vissprite_cliptop[MAXVISSPRITES >> VISSPRITECHUNKBITS] = {0}; +static INT16 *vissprite_clipbot[MAXVISSPRITES >> VISSPRITECHUNKBITS] = {}; +static INT16 *vissprite_cliptop[MAXVISSPRITES >> VISSPRITECHUNKBITS] = {}; static void R_AllocVisSpriteChunkMemory(UINT32 chunk) { @@ -658,7 +669,7 @@ void R_DrawMaskedColumn(drawcolumndata_t* dc, column_t *column) dc->texturemid = basetexturemid; } -INT32 lengthcol; // column->length : for flipped column function pointers and multi-patch on 2sided wall = texture->height +INT32 lengthcol = 0; // column->length : for flipped column function pointers and multi-patch on 2sided wall = texture->height static void R_DrawFlippedMaskedColumn(drawcolumndata_t* dc, column_t *column) { @@ -772,6 +783,7 @@ static void R_DrawVisSprite(vissprite_t *vis) R_SetColumnFunc(BASEDRAWFUNC); // hack: this isn't resetting properly somewhere. dc.colormap = vis->colormap; + if ((vis->mobj->flags & MF_BOSS) && (vis->mobj->flags2 & MF2_FRET) && (leveltime & 1)) // Bosses "flash" { R_SetColumnFunc(COLDRAWFUNC_TRANS); // translate certain pixels to white @@ -824,6 +836,7 @@ static void R_DrawVisSprite(vissprite_t *vis) else dc.colormap = &vis->extra_colormap->colormap[dc.colormap - colormaps]; } + if (!dc.colormap) dc.colormap = colormaps; @@ -848,6 +861,7 @@ static void R_DrawVisSprite(vissprite_t *vis) vis->xiscale = FixedDiv(vis->xiscale, this_scale); vis->isScaled = true; } + dc.texturemid = FixedDiv(dc.texturemid, this_scale); } @@ -1147,7 +1161,7 @@ fixed_t R_GetSpriteDirectionalLighting(angle_t angle) fixed_t extralight = 0; light = FixedMul(FINECOSINE(angle >> ANGLETOFINESHIFT), FINECOSINE(maplighting.angle >> ANGLETOFINESHIFT)) - + FixedMul(FINESINE(angle >> ANGLETOFINESHIFT), FINESINE(maplighting.angle >> ANGLETOFINESHIFT)); + + FixedMul(FINESINE(angle >> ANGLETOFINESHIFT), FINESINE(maplighting.angle >> ANGLETOFINESHIFT)); light = (light + FRACUNIT) / 2; light = FixedMul(light, FRACUNIT - FSIN(abs(AngleDeltaSigned(angle, maplighting.angle)) / 2)); @@ -1229,9 +1243,9 @@ static void R_ProjectSprite(mobj_t *thing) return; const boolean mirrored = thing->mirrored; - const boolean vflip = (thing->eflags & MFE_VERTICALFLIP); - const boolean hflip = (!(thing->frame & FF_HORIZONTALFLIP) != !mirrored); - const boolean papersprite = (thing->frame & FF_PAPERSPRITE); + const boolean vflip = R_ThingVerticallyFlipped(thing); + const boolean hflip = (!R_ThingHorizontallyFlipped(thing) != !mirrored); + const boolean papersprite = R_ThingIsPaperSprite(thing); // transform the origin point tr_x = interp.x - viewx; @@ -1264,7 +1278,7 @@ static void R_ProjectSprite(mobj_t *thing) #ifdef ROTSPRITE // determine here if sprite should rotate for optimization const boolean sliprollrotate = (cv_sliptideroll.value && (thing->player && thing->player->sliproll)); - const boolean shouldrotate = (interp.sloperoll || interp.slopepitch || interp.roll || interp.pitch || thing->rollangle || sliprollrotate); + const boolean shouldrotate = (interp.sloperoll || interp.slopepitch || interp.roll || interp.pitch || thing->rollangle || thing->temprollangle || sliprollrotate); #endif sprskin = K_GetMobjSkin(thing); @@ -1356,24 +1370,26 @@ static void R_ProjectSprite(mobj_t *thing) I_Assert(lump < max_spritelumps); - spr_width = spritecachedinfo[lump].width; - spr_height = spritecachedinfo[lump].height; - spr_offset = spritecachedinfo[lump].offset; + spr_width = spritecachedinfo[lump].width; + spr_height = spritecachedinfo[lump].height; + spr_offset = spritecachedinfo[lump].offset; spr_topoffset = spritecachedinfo[lump].topoffset; #ifdef ROTSPRITE if (shouldrotate) { + const fixed_t thingrollangle = (thing->rollangle - thing->temprollangle); + if (papersprite) { if (ang >= ANGLE_180) { // Makes Software act much more sane like OpenGL - rollangle = InvAngle(thing->rollangle); + rollangle = InvAngle(thingrollangle); } else { - rollangle = thing->rollangle; + rollangle = thingrollangle; } } else @@ -1381,7 +1397,7 @@ static void R_ProjectSprite(mobj_t *thing) // this is very messy, but it on-the-fly calculates rotations for all the // pitch and roll variables pitchnroll = R_RotationAngle(ang, camang, &interp); - rollangle = thing->rollangle; + rollangle = thingrollangle; } if (rollangle || pitchnroll || sliprollrotate) @@ -1399,10 +1415,10 @@ static void R_ProjectSprite(mobj_t *thing) if (rotsprite != NULL) { - spr_width = rotsprite->width << FRACBITS; - spr_height = rotsprite->height << FRACBITS; - spr_offset = rotsprite->leftoffset << FRACBITS; - spr_topoffset = rotsprite->topoffset << FRACBITS; + spr_width = rotsprite->width << FRACBITS; + spr_height = rotsprite->height << FRACBITS; + spr_offset = rotsprite->leftoffset << FRACBITS; + spr_topoffset = rotsprite->topoffset << FRACBITS; spr_topoffset += FEETADJUST; // flip -> rotate, not rotate -> flip @@ -1577,7 +1593,7 @@ static void R_ProjectSprite(mobj_t *thing) else blendmode = thing->blendmode; - if (thing->flags2 & MF2_SHADOW || thing->flags2 & MF2_SHADOW) // actually only the player should use this (temporary invisibility) + if (thing->flags2 & MF2_SHADOW) // actually only the player should use this (temporary invisibility) trans = tr_trans80; // because now the translucency is set through FF_TRANSMASK else if (thing->frame & FF_TRANSMASK) { @@ -1588,8 +1604,15 @@ static void R_ProjectSprite(mobj_t *thing) else trans = 0; - if (cv_playerfade.value && thing->player) - trans = static_cast(R_GetThingTransTable(R_DoPlayerFade(thing), static_cast(trans))); + if (thing->player) + { + // make hyu´d players translucent with reducevfx, could be done better, but im lazy as crap + if (cv_reducevfx.value && thing->player->kartstuff[k_hyudorotimer] > 0) + trans = static_cast(R_GetThingTransTable(FRACUNIT/2, static_cast(trans))); + + if (cv_playerfade.value) + trans = static_cast(R_GetThingTransTable(R_DoPlayerFade(thing), static_cast(trans))); + } //SoM: 3/17/2000: Disregard sprites that are out of view.. if (vflip) @@ -1655,7 +1678,7 @@ static void R_ProjectSprite(mobj_t *thing) if (thing->frame & FF_ABSOLUTELIGHTLEVEL) { - const UINT8 n = R_ThingLightLevel(thing); + const UINT8 n = static_cast(R_ThingLightLevel(thing)); // n = uint8 aka 0 - 255, so the shift will always be 0 - LIGHTLEVELS - 1 lights_array = scalelight[n >> LIGHTSEGSHIFT]; } @@ -1848,9 +1871,6 @@ static void R_ProjectSprite(mobj_t *thing) if (thing->subsector->sector->numlights) R_SplitSprite(vis); - - // Debug - ++objectsdrawn; } static void R_ProjectPrecipitationSprite(precipmobj_t *thing) @@ -2203,6 +2223,7 @@ static void R_SortVisSprites(vissprite_t* vsprsortedhead, UINT32 start, UINT32 e best = ds; } } + if (best) { best->next->prev = best->prev; @@ -2611,7 +2632,7 @@ static void R_ClipVisSprite(vissprite_t *spr, INT32 x1, INT32 x2, portal_t* port for (x = x1; x <= x2; x++) { - spr->clipbot[x] = spr->cliptop[x] = -2; + spr->clipbot[x] = spr->cliptop[x] = CLIP_UNDEF; } // Scan drawsegs from end to start for obscuring segs. @@ -2640,29 +2661,26 @@ static void R_ClipVisSprite(vissprite_t *spr, INT32 x1, INT32 x2, portal_t* port ds = curr->user; - if (ds->portalpass != 66) // unused? + if (ds->portalpass > 0 && ds->portalpass <= portalrender) + continue; // is a portal + + if (ds->scale1 > ds->scale2) { - if (ds->portalpass > 0 && ds->portalpass <= portalrender) - continue; // is a portal + lowscale = ds->scale2; + scale = ds->scale1; + } + else + { + lowscale = ds->scale1; + scale = ds->scale2; + } - if (ds->scale1 > ds->scale2) - { - lowscale = ds->scale2; - scale = ds->scale1; - } - else - { - lowscale = ds->scale1; - scale = ds->scale2; - } - - if (scale < spr->sortscale || - (lowscale < spr->sortscale && - !R_PointOnSegSide(spr->gx, spr->gy, ds->curline))) - { - // seg is behind sprite - continue; - } + if (scale < spr->sortscale || + (lowscale < spr->sortscale && + !R_PointOnSegSide(spr->gx, spr->gy, ds->curline))) + { + // seg is behind sprite + continue; } r1 = ds->x1 < x1 ? x1 : ds->x1; @@ -2681,14 +2699,14 @@ static void R_ClipVisSprite(vissprite_t *spr, INT32 x1, INT32 x2, portal_t* port { // bottom sil for (x = r1; x <= r2; x++) - if (spr->clipbot[x] == -2) + if (spr->clipbot[x] == CLIP_UNDEF) spr->clipbot[x] = ds->sprbottomclip[x]; } else if (silhouette == SIL_TOP) { // top sil for (x = r1; x <= r2; x++) - if (spr->cliptop[x] == -2) + if (spr->cliptop[x] == CLIP_UNDEF) spr->cliptop[x] = ds->sprtopclip[x]; } else if (silhouette == (SIL_TOP|SIL_BOTTOM)) @@ -2696,9 +2714,9 @@ static void R_ClipVisSprite(vissprite_t *spr, INT32 x1, INT32 x2, portal_t* port // both for (x = r1; x <= r2; x++) { - if (spr->clipbot[x] == -2) + if (spr->clipbot[x] == CLIP_UNDEF) spr->clipbot[x] = ds->sprbottomclip[x]; - if (spr->cliptop[x] == -2) + if (spr->cliptop[x] == CLIP_UNDEF) spr->cliptop[x] = ds->sprtopclip[x]; } } @@ -2717,13 +2735,13 @@ static void R_ClipVisSprite(vissprite_t *spr, INT32 x1, INT32 x2, portal_t* port if (mh <= 0 || (phs != -1 && viewz > sectors[phs].floorheight)) { // clip bottom for (x = x1; x <= x2; x++) - if (spr->clipbot[x] == -2 || h < spr->clipbot[x]) + if (spr->clipbot[x] == CLIP_UNDEF || h < spr->clipbot[x]) spr->clipbot[x] = (INT16)h; } else // clip top { for (x = x1; x <= x2; x++) - if (spr->cliptop[x] == -2 || h > spr->cliptop[x]) + if (spr->cliptop[x] == CLIP_UNDEF || h > spr->cliptop[x]) spr->cliptop[x] = (INT16)h; } } @@ -2735,13 +2753,13 @@ static void R_ClipVisSprite(vissprite_t *spr, INT32 x1, INT32 x2, portal_t* port if (phs != -1 && viewz >= sectors[phs].ceilingheight) { // clip bottom for (x = x1; x <= x2; x++) - if (spr->clipbot[x] == -2 || h < spr->clipbot[x]) + if (spr->clipbot[x] == CLIP_UNDEF || h < spr->clipbot[x]) spr->clipbot[x] = (INT16)h; } else // clip top { for (x = x1; x <= x2; x++) - if (spr->cliptop[x] == -2 || h > spr->cliptop[x]) + if (spr->cliptop[x] == CLIP_UNDEF || h > spr->cliptop[x]) spr->cliptop[x] = (INT16)h; } } @@ -2751,10 +2769,10 @@ static void R_ClipVisSprite(vissprite_t *spr, INT32 x1, INT32 x2, portal_t* port { for (x = x1; x <= x2; x++) { - if (spr->cliptop[x] == -2 || spr->szt > spr->cliptop[x]) + if (spr->cliptop[x] == CLIP_UNDEF || spr->szt > spr->cliptop[x]) spr->cliptop[x] = spr->szt; - if (spr->clipbot[x] == -2 || spr->sz < spr->clipbot[x]) + if (spr->clipbot[x] == CLIP_UNDEF || spr->sz < spr->clipbot[x]) spr->clipbot[x] = spr->sz; } } @@ -2762,7 +2780,7 @@ static void R_ClipVisSprite(vissprite_t *spr, INT32 x1, INT32 x2, portal_t* port { for (x = x1; x <= x2; x++) { - if (spr->cliptop[x] == -2 || spr->szt > spr->cliptop[x]) + if (spr->cliptop[x] == CLIP_UNDEF || spr->szt > spr->cliptop[x]) spr->cliptop[x] = spr->szt; } } @@ -2770,7 +2788,7 @@ static void R_ClipVisSprite(vissprite_t *spr, INT32 x1, INT32 x2, portal_t* port { for (x = x1; x <= x2; x++) { - if (spr->clipbot[x] == -2 || spr->sz < spr->clipbot[x]) + if (spr->clipbot[x] == CLIP_UNDEF || spr->sz < spr->clipbot[x]) spr->clipbot[x] = spr->sz; } } @@ -2780,21 +2798,13 @@ static void R_ClipVisSprite(vissprite_t *spr, INT32 x1, INT32 x2, portal_t* port // check for unclipped columns for (x = x1; x <= x2; x++) { - if (spr->clipbot[x] == -2) + if (spr->clipbot[x] == CLIP_UNDEF) spr->clipbot[x] = (INT16)viewheight; - if (spr->cliptop[x] == -2) + if (spr->cliptop[x] == CLIP_UNDEF) spr->cliptop[x] = -1; } - // Check if it'll be visible - // Not done for floorsprites. - if (cv_spriteclip.value) - { - if (!R_CheckSpriteVisible(spr, x1, x2)) - spr->cut = static_cast(spr->cut | SC_NOTVISIBLE); - } - if (portal) { INT32 start_index = std::max(portal->start, x1); @@ -2805,6 +2815,7 @@ static void R_ClipVisSprite(vissprite_t *spr, INT32 x1, INT32 x2, portal_t* port spr->clipbot[x] = -1; spr->cliptop[x] = -1; } + for (x = start_index; x <= end_index; x++) { if (spr->clipbot[x] > portal->floorclip[x - portal->start]) @@ -2812,12 +2823,21 @@ static void R_ClipVisSprite(vissprite_t *spr, INT32 x1, INT32 x2, portal_t* port if (spr->cliptop[x] < portal->ceilingclip[x - portal->start]) spr->cliptop[x] = portal->ceilingclip[x - portal->start]; } + for (x = end_index + 1; x <= x2; x++) { spr->clipbot[x] = -1; spr->cliptop[x] = -1; } } + + // Check if it'll be visible + // Not done for floorsprites. + if (cv_spriteclip.value) + { + if (!R_CheckSpriteVisible(spr, x1, x2)) + spr->cut = static_cast(spr->cut | SC_NOTVISIBLE); + } } void R_ClipSprites(drawseg_t* dsstart, portal_t* portal) @@ -2890,8 +2910,9 @@ void R_ClipSprites(drawseg_t* dsstart, portal_t* portal) { vissprite_t *spr = R_GetVisSprite(clippedvissprites); - if (cv_spriteclip.value - && (spr->szt > vid.height || spr->sz < 0)) + if (cv_spriteclip.value && + (spr->szt > vid.height || spr->sz < 0) && + !spr->scalestep) { spr->cut = static_cast(spr->cut | SC_NOTVISIBLE); continue; @@ -2923,16 +2944,16 @@ void R_ClipSprites(drawseg_t* dsstart, portal_t* portal) /* Check if thing may be drawn from our current view. */ boolean R_ThingVisible(mobj_t *thing) { - if (UNLIKELY((thing->sprite == SPR_NULL) || (thing->flags2 & MF2_DONTDRAW))) + if ((thing->sprite == SPR_NULL) || (thing->flags2 & MF2_DONTDRAW)) return false; - if (UNLIKELY(splitscreen)) + if (splitscreen) { - if ((viewssnum == 0 && (thing->eflags & MFE_DRAWONLYFORP1)) - || (viewssnum == 1 && (thing->eflags & MFE_DRAWONLYFORP2)) - || (viewssnum == 2 && (thing->eflags & MFE_DRAWONLYFORP2)) - || (viewssnum == 3 && (thing->eflags & MFE_DRAWONLYFORP4))) - return true; + if (((thing->eflags & MFE_DRAWONLYFORP1) && viewssnum != 0) + || ((thing->eflags & MFE_DRAWONLYFORP2) && viewssnum != 1) + || ((thing->eflags & MFE_DRAWONLYFORP3) && viewssnum != 2) + || ((thing->eflags & MFE_DRAWONLYFORP4) && viewssnum != 3)) + return false; } return true; @@ -2956,21 +2977,24 @@ fixed_t R_DoPlayerFade(mobj_t *thing) fixed_t fadealpha = FRACUNIT; static constexpr tic_t countdownstarttime = (15 * TICRATE) / 4; // starttime - (3*TICRATE) - if (thing->player == viewplayer || viewplayer->exiting || camera[R_GetViewNumber()].freecam || leveltime < countdownstarttime) + if (thing->player == viewplayer || viewplayer->exiting || viewplayer->spectator || camera[R_GetViewNumber()].freecam || leveltime < countdownstarttime) return fadealpha; - const INT32 playerdist = (FixedMul((thing->x - viewx), viewcos) + FixedMul((thing->y - viewy), viewsin)) >> FRACBITS; - const INT32 viewplayerdist = (FixedMul((viewplayer->mo->x - viewx), viewcos) + FixedMul((viewplayer->mo->y - viewy), viewsin)) >> FRACBITS; + const INT32 otherplayerdist = (FixedMul((thing->x - viewx), viewcos) + FixedMul((thing->y - viewy), viewsin)) >> FRACBITS; + const INT32 viewplayerdist = (FixedMul((viewplayer->mo->x - viewx), viewcos) + FixedMul((viewplayer->mo->y - viewy), viewsin)) >> FRACBITS; - if (playerdist < viewplayerdist) + if (viewplayerdist < 2) + return fadealpha; // avoid zero division + + if (otherplayerdist < viewplayerdist) { - if (playerdist < viewplayerdist / 2) // stronger fade when very close + if (otherplayerdist < viewplayerdist / 2) // stronger fade when very close { - fadealpha = (playerdist * FRACUNIT) / (viewplayerdist / 2) / 3; + fadealpha = (otherplayerdist * FRACUNIT) / (viewplayerdist / 2) / 3; } else { - fadealpha = (playerdist * FRACUNIT) / viewplayerdist; + fadealpha = (otherplayerdist * FRACUNIT) / viewplayerdist; } } @@ -3001,11 +3025,37 @@ boolean R_CheckMobjInterpDist(mobj_t *thing) return R_CheckInterpDist(thing); } -boolean R_ThingIsFullBright(mobj_t *thing) +boolean R_ThingHorizontallyFlipped(mobj_t *thing) +{ + return (thing->frame & FF_HORIZONTALFLIP); +} + +boolean R_ThingVerticallyFlipped(mobj_t *thing) +{ + return (thing->eflags & MFE_VERTICALFLIP); //(thing->frame & FF_VERTICALFLIP); +} + +boolean R_ThingIsPaperSprite(mobj_t *thing) +{ + return (thing->frame & FF_PAPERSPRITE); +} + +template +static boolean R_ThingIsFullBrightT(T *thing) { return ((thing->frame & FF_BRIGHTMASK) == FF_FULLBRIGHT); } +boolean R_PrecipThingIsFullBright(precipmobj_t *thing) +{ + return R_ThingIsFullBrightT(thing); +} + +boolean R_ThingIsFullBright(mobj_t *thing) +{ + return R_ThingIsFullBrightT(thing); +} + boolean R_ThingIsSemiBright(mobj_t *thing) { return ((thing->frame & FF_BRIGHTMASK) == FF_SEMIBRIGHT); @@ -3086,7 +3136,7 @@ static void R_DrawMaskedList(drawnode_t* head) void R_DrawMasked(maskcount_t* masks, INT32 nummasks) { INT32 i; - drawnode_t *heads; /**< Drawnode lists; as many as number of views/portals. */ + drawnode_t *heads = NULL; /**< Drawnode lists; as many as number of views/portals. */ heads = static_cast(calloc(nummasks, sizeof(drawnode_t))); diff --git a/src/r_things.h b/src/r_things.h index c8195891a..bde0ad592 100644 --- a/src/r_things.h +++ b/src/r_things.h @@ -50,7 +50,7 @@ extern fixed_t windowtop; extern fixed_t windowbottom; extern INT32 lengthcol; -FUNCINLINE static ATTRINLINE INT32 R_ThingLightLevel(mobj_t* thing) +FUNCINLINE static ATTRINLINE INT32 R_ThingLightLevel(const mobj_t* thing) { return (INT32)thing->lightlevel; } @@ -88,6 +88,11 @@ boolean R_CheckPrecipMobjInterpDist(precipmobj_t *thing); boolean R_CheckMobjInterpDist(mobj_t *thing); fixed_t R_DoPlayerFade(mobj_t *thing); +boolean R_ThingHorizontallyFlipped(mobj_t *thing); +boolean R_ThingVerticallyFlipped(mobj_t *thing); +boolean R_ThingIsPaperSprite(mobj_t *thing); + +boolean R_PrecipThingIsFullBright(precipmobj_t *thing); boolean R_ThingIsFullBright(mobj_t *thing); boolean R_ThingIsSemiBright(mobj_t *thing); boolean R_ThingIsFullDark(mobj_t *thing); diff --git a/src/s_sound.c b/src/s_sound.c index 5bc830252..278c87853 100644 --- a/src/s_sound.c +++ b/src/s_sound.c @@ -116,9 +116,7 @@ consvar_t cv_skipintromusic = {"skipintromusic", "No", CV_SAVE, CV_YesNo, NULL, boolean keepmapmusic = false; // keep the current music on map restart boolean skipintromus = false; // skip the intro fanfare -static boolean resumekeepmusic = false; static music_t keepmusic; -static void S_SetKeepMusResume(void); #ifdef HAVE_OPENMPT openmpt_module *openmpt_mhandle = NULL; @@ -336,7 +334,7 @@ lumpnum_t S_GetSfxLumpNum(sfxinfo_t *sfx) char namebuf[9]; lumpnum_t sfxlump; - sprintf(namebuf, "ds%s", sfx->name); + snprintf(namebuf, sizeof(namebuf), "ds%s", sfx->name); sfxlump = W_CheckNumForName(namebuf); if (sfxlump != LUMPERROR) @@ -435,7 +433,7 @@ static boolean S_CheckSameSoundLimit(sfxenum_t sfx_id) return true; for (cnum = 0; cnum < numofchannels; cnum++) - if ((size_t)(channels[cnum].sfxinfo - S_sfx) == (size_t)sfx_id) + if (channels[cnum].sfxinfo == &S_sfx[sfx_id]) scount++; //CONS_Printf("same sound count: %d for sfx: %d\n", scount, sfx_id); @@ -473,12 +471,16 @@ void S_StartSoundAtVolume(const void *origin_p, sfxenum_t sfx_id, INT32 volume) return; memset(listener, 0, sizeof(listener)); + memset(listenmobj, 0, sizeof(listenmobj)); for (i = 0; i <= splitscreen; i++) { player_t *player = &players[displayplayers[i]]; - listenmobj[i] = NULL; + if (!player) + { + continue; + } if (player->awayviewtics) { @@ -538,79 +540,84 @@ void S_StartSoundAtVolume(const void *origin_p, sfxenum_t sfx_id, INT32 volume) i = 0; // sensible default + // Check to see if it is audible, and if not, modify the params + if (origin && !itsUs) { - // Check to see if it is audible, and if not, modify the params - if (origin && !itsUs) + boolean audible = false; + + if (splitscreen > 0) { - boolean audible = false; - if (splitscreen > 0) - { - fixed_t recdist = INT32_MAX; - UINT8 j = 0; + fixed_t recdist = INT32_MAX; + UINT8 j = 0; - for (; j <= splitscreen; j++) + for (; j <= splitscreen; j++) + { + fixed_t thisdist = INT32_MAX; + + if (!listenmobj[j]) { - fixed_t thisdist = INT32_MAX; - - if (!listenmobj[j]) - { - continue; - } - - thisdist = P_AproxDistance(listener[j].x - origin->x, listener[j].y - origin->y); - - if (thisdist >= recdist) - { - continue; - } - - recdist = thisdist; - i = j; + continue; } - } - if (listenmobj[i]) - { - audible = S_AdjustSoundParams(listenmobj[i], origin, &volume, &sep, sfx); - } + thisdist = P_AproxDistance(listener[j].x - origin->x, listener[j].y - origin->y); - if (!audible) - { - return; + if (thisdist >= recdist) + { + continue; + } + + recdist = thisdist; + i = j; } } - // This is supposed to handle the loading/caching. - // For some odd reason, the caching is done nearly - // each time the sound is needed? + if (listenmobj[i]) + { + audible = S_AdjustSoundParams(listenmobj[i], origin, &volume, &sep, sfx); + } + + if (!audible) + { + return; + } + } + + // This is supposed to handle the loading/caching. + // For some odd reason, the caching is done nearly + // each time the sound is needed? + + // cache data if necessary + // NOTE: set sfx->data NULL sfx->lump -1 to force a reload + if (!sfx->data) + { + sfx->data = I_GetSfx(sfx); - // cache data if necessary - // NOTE: set sfx->data NULL sfx->lump -1 to force a reload if (!sfx->data) { - sfx->data = I_GetSfx(sfx); + CONS_Alert(CONS_WARNING, "Tried to load invalid sfx_%s\n", sfx->name); + return; /* don't play it */ } - - // Avoid channel reverse if surround - if (reverse) - { - sep = (~sep) & 255; - } - - // At this point it is determined that a sound can and should be played, so find a free channel to play it on - cnum = S_getChannel(origin, sfx); - - if (cnum < 0) - { - return; // If there's no free channels, there won't be any for anymore players either - } - - // Now that we know we are going to play a sound, fill out this info - channels[cnum].sfxinfo = sfx; - channels[cnum].origin = origin; - channels[cnum].volume = initial_volume; - channels[cnum].handle = I_StartSound(sfx_id, volume, sep, cnum); } + + // Avoid channel reverse if surround + if (reverse) + { + sep = (~sep) & 255; + } + + // At this point it is determined that a sound can and should be played, so find a free channel to play it on + cnum = S_getChannel(origin, sfx); + + if (cnum < 0) + { + return; // If there's no free channels, there won't be any for anymore players either + } + + // Now that we know we are going to play a sound, fill out this info + channels[cnum].sfxinfo = sfx; + channels[cnum].origin = origin; + channels[cnum].volume = initial_volume; + channels[cnum].handle = I_StartSound(sfx_id, volume, sep, cnum); } void S_StartSound(const void *origin, sfxenum_t sfx_id) @@ -725,11 +732,16 @@ void S_UpdateSounds(void) if (dedicated || sound_disabled) return; + memset(listenmobj, 0, sizeof(listenmobj)); + for (i = 0; i <= splitscreen; i++) { player_t *player = &players[displayplayers[i]]; - listenmobj[i] = NULL; + if (!player) + { + continue; + } if (player->awayviewtics) { @@ -764,84 +776,83 @@ void S_UpdateSounds(void) { c = &channels[cnum]; - if (c->sfxinfo) + if (c->sfxinfo == NULL) + continue; + + // if channel is allocated but sound has stopped, free it + if (!I_SoundIsPlaying(c->handle)) { - if (I_SoundIsPlaying(c->handle)) + S_StopChannel(cnum); + continue; + } + + if (c->origin == NULL) + continue; + + // initialize parameters + volume = c->volume; // 8 bits internal volume precision + sep = NORM_SEP; + + // check non-local sounds for distance clipping + // or modify their params + boolean itsUs = false; + + for (i = splitscreen; i >= 0; i--) + { + if (camera[i].freecam) + continue; + + if (c->origin != listenmobj[i]) + continue; + + itsUs = true; + } + + if (itsUs == false) + { + const mobj_t *origin = c->origin; + + i = 0; + + if (splitscreen > 0) { - // initialize parameters - volume = c->volume; // 8 bits internal volume precision - sep = NORM_SEP; + fixed_t recdist = INT32_MAX; + UINT8 j = 0; - // check non-local sounds for distance clipping - // or modify their params - if (c->origin) + for (; j <= splitscreen; j++) { - boolean itsUs = false; + fixed_t thisdist = INT32_MAX; - for (i = splitscreen; i >= 0; i--) + if (!listenmobj[j]) { - if (camera[i].freecam) - continue; - - if (c->origin != listenmobj[i]) - continue; - - itsUs = true; + continue; } - if (itsUs == false) + thisdist = P_AproxDistance(listener[j].x - origin->x, listener[j].y - origin->y); + + if (thisdist >= recdist) { - const mobj_t *origin = c->origin; - - i = 0; - - if (splitscreen > 0) - { - fixed_t recdist = INT32_MAX; - UINT8 j = 0; - - for (; j <= splitscreen; j++) - { - fixed_t thisdist = INT32_MAX; - - if (!listenmobj[j]) - { - continue; - } - - thisdist = P_AproxDistance(listener[j].x - origin->x, listener[j].y - origin->y); - - if (thisdist >= recdist) - { - continue; - } - - recdist = thisdist; - i = j; - } - } - - if (listenmobj[i]) - { - audible = S_AdjustSoundParams( - listenmobj[i], c->origin, - &volume, &sep, - c->sfxinfo - ); - } - - if (audible) - I_UpdateSoundParams(c->handle, volume, sep); - else - S_StopChannel(cnum); + continue; } + + recdist = thisdist; + i = j; } } - else + + if (listenmobj[i]) { - // if channel is allocated but sound has stopped, free it - S_StopChannel(cnum); + audible = S_AdjustSoundParams( + listenmobj[i], c->origin, + &volume, &sep, + c->sfxinfo + ); } + + if (audible) + I_UpdateSoundParams(c->handle, volume, sep); + else + S_StopChannel(cnum); } } @@ -853,23 +864,22 @@ void S_SetSfxVolume(INT32 volume) if (volume < 0 || volume > 31) CONS_Alert(CONS_WARNING, "sfxvolume should be between 0-31\n"); - CV_SetValue(&cv_soundvolume, volume&0x1F); + CV_SetValue(&cv_soundvolume, volume & 0x1F); actualsfxvolume = cv_soundvolume.value; // check for change of var // now hardware volume - I_SetSfxVolume(volume&0x1F); + I_SetSfxVolume(volume & 0x1F); } void S_ClearSfx(void) { size_t i; for (i = 1; i < NUMSFX; i++) - I_FreeSfx(S_sfx + i); + I_FreeSfx(&S_sfx[i]); } static void S_StopChannel(INT32 cnum) { - INT32 i; channel_t *c = &channels[cnum]; if (c->sfxinfo) @@ -878,13 +888,7 @@ static void S_StopChannel(INT32 cnum) if (I_SoundIsPlaying(c->handle)) I_StopSound(c->handle); - // check to see - // if other channels are playing the sound - for (i = 0; i < numofchannels; i++) - if (cnum != i && c->sfxinfo == channels[i].sfxinfo) - break; - - c->sfxinfo = 0; + c->sfxinfo = NULL; } c->origin = NULL; @@ -933,6 +937,7 @@ static boolean S_AdjustSoundParams(const mobj_t *listener, const mobj_t *source, listener_t listensource; INT32 i; + // e6y if (!listener) return false; @@ -1049,41 +1054,46 @@ static boolean S_AdjustSoundParams(const mobj_t *listener, const mobj_t *source, INT32 S_OriginPlaying(void *origin) { INT32 cnum; + if (!origin) return false; for (cnum = 0; cnum < numofchannels; cnum++) if (channels[cnum].origin == origin) return 1; + return 0; } // Searches through the channels and checks if a given id // is playing anywhere. -INT32 S_IdPlaying(sfxenum_t id) +INT32 S_IdPlaying(sfxenum_t sfx_id) { INT32 cnum; for (cnum = 0; cnum < numofchannels; cnum++) - if ((size_t)(channels[cnum].sfxinfo - S_sfx) == (size_t)id) + if (channels[cnum].sfxinfo == &S_sfx[sfx_id]) return 1; + return 0; } // Searches through the channels and checks for // origin x playing sound id y. -INT32 S_SoundPlaying(void *origin, sfxenum_t id) +INT32 S_SoundPlaying(void *origin, sfxenum_t sfx_id) { INT32 cnum; + if (!origin) return 0; for (cnum = 0; cnum < numofchannels; cnum++) { - if (channels[cnum].origin == origin - && (size_t)(channels[cnum].sfxinfo - S_sfx) == (size_t)id) + if (channels[cnum].origin == origin && + channels[cnum].sfxinfo == &S_sfx[sfx_id]) return 1; } + return 0; } @@ -1096,6 +1106,7 @@ static sfxenum_t newsounds[MAXNEWSOUNDS] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; void S_StartSoundName(void *mo, const char *soundname) { INT32 i, soundnum = 0; + // Search existing sounds... for (i = sfx_None + 1; i < NUMSFX; i++) { @@ -1271,7 +1282,7 @@ static musicdef_t *S_AddMusicCredit(void) return &musicdefs[chunk][i]; } -struct cursongcredit cursongcredit = {0}; // Currently displayed song credit info +struct cursongcredit cursongcredit = {}; // Currently displayed song credit info static boolean ReadMusicDefFields(UINT16 wadnum, int line, char *stoken, musicdef_t **defp) { @@ -1286,10 +1297,9 @@ static boolean ReadMusicDefFields(UINT16 wadnum, int line, char *stoken, musicde if (!value) { - CONS_Alert(CONS_WARNING, - "MUSICDEF: Field '%s' is missing name. (file %s, line %d)\n", - stoken, wadfiles[wadnum]->filename, line); - goto skip_lump; + CONS_Alert(CONS_WARNING, "MUSICDEF: Field '%s' is missing name. (file %s, line %d)\n", stoken, wadfiles[wadnum]->filename, line); + (void)strtok(NULL, " "); + return true; } else { @@ -1302,15 +1312,11 @@ static boolean ReadMusicDefFields(UINT16 wadnum, int line, char *stoken, musicde STRBUFCPY(def->name, value); strlwr(def->name); - def->hash = quickncasehash (def->name, 6); + def->hash = FNV1a_QuickCaseHash(def->name, 6); } (*defp) = def; } - -skip_lump: - stoken = strtok(NULL, " "); - line++; } else { @@ -1324,10 +1330,9 @@ skip_lump: if (!value) { - CONS_Alert(CONS_WARNING, - "MUSICDEF: Field '%s' is missing value. (file %s, line %d)\n", - stoken, wadfiles[wadnum]->filename, line); - goto skip_field; + CONS_Alert(CONS_WARNING, "MUSICDEF: Field '%s' is missing value. (file %s, line %d)\n", stoken, wadfiles[wadnum]->filename, line); + (void)strtok(NULL, " "); + return true; } else { @@ -1335,9 +1340,7 @@ skip_lump: if (!def) { - CONS_Alert(CONS_ERROR, - "MUSICDEF: No music definition before field '%s'. (file %s, line %d)\n", - stoken, wadfiles[wadnum]->filename, line); + CONS_Alert(CONS_ERROR, "MUSICDEF: No music definition before field '%s'. (file %s, line %d)\n", stoken, wadfiles[wadnum]->filename, line); return false; } @@ -1349,11 +1352,19 @@ skip_lump: textline = value; -// turn _ into spaces. -#define ADDDEF(field)\ - STRBUFCPY(def->field, textline);\ - for (textline = def->field; *textline; textline++)\ - if (*textline == '_') *textline = ' '; +// turn _ into spaces while also removing trailing whitespaces. +#define ADDDEF(field) \ + int err = 0; \ + STRBUFCPY(def->field, textline); \ + size_t len = strlen(def->field); \ + while (len > 0 && (def->field[len-1] == ' ')) { \ + def->field[len-1] = 0; \ + len--; \ + } \ + for (textline = def->field; *textline; textline++) { \ + if (err == 0 && *textline == ' ') {err = 1; CONS_Alert(CONS_WARNING, "MUSICDEF: Erroneous whitespace detected in field '%s': '%s'.\n(file %s, line %d) Musicdef might not work correctly!\n", stoken, value, wadfiles[wadnum]->filename, line);} \ + if (*textline == '_') *textline = ' '; \ + } if (fasticmp(stoken, "usage")) { @@ -1365,7 +1376,6 @@ skip_lump: } else if (fasticmp(stoken, "title")) { - def->use_info = true; ADDDEF(title); } else if (fasticmp(stoken, "alttitle")) @@ -1379,10 +1389,6 @@ skip_lump: else CONS_Alert(CONS_WARNING, "MUSICDEF: Invalid field '%s'. (file %s, line %d)\n", stoken, wadfiles[wadnum]->filename, line); #undef ADDDEF - -skip_field: - stoken = strtok(NULL, "= "); - line++; } } @@ -1407,7 +1413,8 @@ void S_LoadMusicDefs(UINT16 wadnum) for (int k = 0; k < 2; k++) { - lumpnum = W_CheckNumForNamePwad((k == 1 ? "MUSCINFO" : "MUSICDEF") , wadnum, 0); //check for MUSCINFO lump on 2nd iteration + const char *lumpname = (k == 1 ? "MUSCINFO" : "MUSICDEF"); //check for MUSCINFO lump on 2nd iteration + lumpnum = W_CheckNumForNamePwad(lumpname, wadnum, 0); if (lumpnum == INT16_MAX) continue; @@ -1433,13 +1440,13 @@ void S_LoadMusicDefs(UINT16 wadnum) nlf = 1; else nlf = 0; - *lf++ = '\0';/* now we can delimit to here */ + *lf++ = '\0'; /* now we can delimit to here */ } stoken = strtok(stoken, " "); if (stoken) { - if (! ReadMusicDefFields(wadnum, line, stoken, &def)) + if (!ReadMusicDefFields(wadnum, line, stoken, &def)) break; } @@ -1455,10 +1462,10 @@ void S_LoadMusicDefs(UINT16 wadnum) } while (nlf || ncr) ; - stoken = lf;/* now the next nonempty line */ + stoken = lf; /* now the next nonempty line */ } else - break;/* EOF */ + break; /* EOF */ } free(musdeftext); @@ -1484,13 +1491,16 @@ void S_InitMusicDefs(void) // musicdef_t *S_FindMusicCredit(const char *musname) { - UINT32 hash = quickncasehash(musname, 6); + UINT32 hash = FNV1a_QuickCaseHash(musname, 6); musicdef_t *def; for (INT32 i = 0; i < nummusicdefs; ++i) { def = S_GetMusicCredit(i); + if (!def) + continue; + if (hash != def->hash) continue; @@ -1701,7 +1711,7 @@ static void S_UnloadMusic(void) music.flags = 0; music.looping = false; - music_refade_cv = 0; + music_refade_cv = NULL; } static boolean S_PlayMusic(boolean looping, UINT32 fadeinms) @@ -1846,8 +1856,6 @@ void S_StopMusic(void) mapmusic.resume = (cv_resume.value && fasticmp(music.name, mapmusic.name)) ? I_GetSongPosition() : 0; - S_SetKeepMusResume(); - if (I_SongPaused()) I_ResumeSong(); @@ -1974,17 +1982,6 @@ void S_ResetKeepAndSpecialMus(void) keepmapmusic = skipintromus = false; } -// saves the current song position everytime a song stops -// so we can resume it in some cases -static void S_SetKeepMusResume(void) -{ - keepmusic.resume = 0; - - if (fasticmp(music.name, mapmusic.name)) - { - keepmusic.resume = I_GetSongPosition(); - } -} // determine if we should keep the music on a map restart // this gets called BEFORE the level gets loaded in G_DoLoadLevel @@ -1993,7 +1990,7 @@ void S_KeepMusic(void) static INT16 oldmap = -1; static boolean oldencore = false; - keepmapmusic = resumekeepmusic = false; + keepmapmusic = false; if (!cv_keepmusic.value) { @@ -2007,9 +2004,7 @@ void S_KeepMusic(void) if (oldmap == gamemap && oldencore == encoremode) { - const boolean musicchanged = S_CheckMusicException(); - resumekeepmusic = (musicchanged && keepmusic.resume); - keepmapmusic = (!musicchanged || resumekeepmusic); + keepmapmusic = (S_CheckMusicException() == false); } oldencore = encoremode; @@ -2045,6 +2040,10 @@ static boolean S_SkipIntroMusic(void) if (!cv_skipintromusic.value) return false; + // dont skip if we disabled music, weird? but this would skip sounds that play on map start as well otherwise + if (music_disabled) + return false; + // check if menu music is playing, otherwise it may continue playing if (fasticmp(music.name, "titles")) return false; @@ -2056,6 +2055,11 @@ static boolean S_SkipIntroMusic(void) return false; } + // without sound there wont be any intro playing + if (sound_disabled) + return true; + // yes i sometimes play with only music but no sound + return true; } @@ -2070,12 +2074,6 @@ void S_InitMapMusic(void) if (keepmapmusic) { - // this is kinda silly, but we can use it to fade back into the map song at the saved point, should the current music be different from the map music - if (resumekeepmusic) - { - S_ChangeMusicEx(mapmusic.name, mapmusic.flags, true, keepmusic.resume, 0, 500); - } - return; } @@ -2195,7 +2193,7 @@ static void Command_Tunes_f(void) track = (UINT16)atoi(COM_Argv(2))-1; if (tunenum) - snprintf(mapmusic.name, 7, "%sM", G_BuildMapName(tunenum)); + snprintf(mapmusic.name, sizeof(mapmusic.name), "%sM", G_BuildMapName(tunenum)); else strlcpy(mapmusic.name, tunearg, sizeof(mapmusic.name)); diff --git a/src/s_sound.h b/src/s_sound.h index 9e0296d2b..5d9d9949f 100644 --- a/src/s_sound.h +++ b/src/s_sound.h @@ -186,7 +186,6 @@ typedef struct musicdef_s char title[256]; char alttitle[256]; char authors[256]; - boolean use_info; size_t num; } musicdef_t; @@ -253,9 +252,9 @@ void S_ChangeMusicEx(const char *mmusic, UINT16 mflags, boolean looping, UINT32 void S_ChangeMusicSpecial (const char *mmusic); -void S_SetRestoreMusicFadeInCvar (consvar_t *cvar); +void S_SetRestoreMusicFadeInCvar(consvar_t *cvar); #define S_ClearRestoreMusicFadeInCvar() \ - S_SetRestoreMusicFadeInCvar(0) + S_SetRestoreMusicFadeInCvar(NULL) int S_GetRestoreMusicFadeIn (void); // Stops the music. @@ -287,8 +286,8 @@ void S_SetSfxVolume(INT32 volume); void S_SetMusicVolume(INT32 volume); INT32 S_OriginPlaying(void *origin); -INT32 S_IdPlaying(sfxenum_t id); -INT32 S_SoundPlaying(void *origin, sfxenum_t id); +INT32 S_IdPlaying(sfxenum_t sfx_id); +INT32 S_SoundPlaying(void *origin, sfxenum_t sfx_id); void S_StartSoundName(void *mo, const char *soundname); diff --git a/src/screen.c b/src/screen.c index b292c646d..67b7e0bf3 100644 --- a/src/screen.c +++ b/src/screen.c @@ -120,6 +120,10 @@ static void SCR_SetDrawFuncs(enum columncontext_e _columncontext) colfuncs[COLDRAWFUNC_TWOSMULTIPATCHTRANS] = R_Draw2sMultiPatchTranslucentColumn; } + // gotta keep a copy of those for R_DrawWallColumn..... + colfuncs[COLDRAWFUNC_TWOSMULTIPATCH_DIRECT] = R_Draw2sMultiPatchColumn; + colfuncs[COLDRAWFUNC_TWOSMULTIPATCHTRANS_DIRECT] = R_Draw2sMultiPatchTranslucentColumn; + colfuncs[COLDRAWFUNC_FOG] = R_DrawFogColumn; R_SetColumnFunc(BASEDRAWFUNC); @@ -154,7 +158,6 @@ void SCR_SetMode(void) // effectively adding massive overhead due to excessive flushing, so we draw our masked thing directly to screen instead void R_SetColumnContext(enum columncontext_e _columncontext) { - columncontext = _columncontext; SCR_SetDrawFuncs(_columncontext); // set our column drawers } @@ -274,6 +277,7 @@ void SCR_Recalc(void) // vid.recalc lasts only for the next refresh... con_recalc = true; am_recalc = true; + intermissionbginit = false; } // Check for screen cmd-line parms: to force a resolution. @@ -526,6 +530,6 @@ void SCR_DisplayLocalPing(void) if (cv_showping.value == 1 || (cv_showping.value == 2 && ping > servermaxping)) // only show 2 (warning) if our ping is at a bad level { INT32 dispy = (cv_ticrate.value == 1) ? 165 : ((cv_ticrate.value == 2 || cv_ticrate.value == 4) ? 172 : ((cv_ticrate.value == 3) ? 163 : 181)); // absolute buttpain - HU_drawPlayerPing(308, dispy, consoleplayer, pingflags); // consoleplayer's ping is everyone's ping in a splitnetgame :P + HU_drawLocalPlayerPing(308, dispy, pingflags); // consoleplayer's ping is everyone's ping in a splitnetgame :P } } diff --git a/src/screen.h b/src/screen.h index 0a912e97a..bc42e4cd3 100644 --- a/src/screen.h +++ b/src/screen.h @@ -63,6 +63,7 @@ typedef struct viddef_s INT32 dup; // scale 1, 2, 3 value for menus & overlays INT32 fdup; // same as dup, but exact value when aspect ratio isn't 320/200 + INT32 udup; // same as dup but does not account for highreshudscale UINT8 smalldup; // factor for a little bit of scaling UINT8 meddup; // factor for moderate, but not full, scaling diff --git a/src/sdl/CMakeLists.txt b/src/sdl/CMakeLists.txt index e4b0d4f37..664010072 100644 --- a/src/sdl/CMakeLists.txt +++ b/src/sdl/CMakeLists.txt @@ -32,7 +32,7 @@ set(SRB2_SDL2_SOURCES hwsym_sdl.c i_main.c i_net.c - i_system.c + i_system.cpp i_ttf.c i_video.c i_threads.c @@ -123,8 +123,6 @@ if(${SDL2_FOUND}) set(MACOSX_BUNDLE_ICON_FILE Srb2mac.icns) set_source_files_properties(macosx/Srb2mac.icns PROPERTIES MACOSX_PACKAGE_LOCATION "Resources") set(SRB2_SDL2_MAC_SOURCES - macosx/mac_alert.c - macosx/mac_alert.h macosx/mac_resources.c macosx/mac_resources.h macosx/Srb2mac.icns @@ -167,13 +165,22 @@ if(${SDL2_FOUND}) ${DISCORDRPC_LIBRARIES} ) + if(${SRB2_HAVE_LIBBACKTRACE}) + target_link_libraries(SRB2SDL2 PRIVATE ${LIBBACKTRACE_LIBRARIES}) + endif() + if(${CMAKE_SYSTEM} MATCHES Linux) target_link_libraries(SRB2SDL2 PRIVATE m rt + pthread ) endif() + if("${CMAKE_SYSTEM_NAME}" MATCHES "OpenBSD") + target_link_libraries(SRB2SDL2 PRIVATE pthread execinfo) + endif() + if(${CMAKE_SYSTEM} MATCHES Windows AND ${CMAKE_C_COMPILER_ID} MATCHES "GNU" AND ${SRB2_SYSTEM_BITS} EQUAL 32) target_link_libraries(SRB2SDL2 PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../../libs/drmingw/lib/win32/libexchndl.a" @@ -226,6 +233,24 @@ if(${SDL2_FOUND}) -DHAVE_THREADS ) + if(SRB2_CONFIG_LTO AND NOT SRB2_CONFIG_DEBUGMODE) + set_property(TARGET SRB2SDL2 PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE) + endif() + + if(SRB2_CONFIG_ASAN) + target_compile_options(SRB2SDL2 PRIVATE -fsanitize=address) + target_link_options(SRB2SDL2 PRIVATE -fsanitize=address) + endif() + + if(SRB2_CONFIG_UBSAN) + target_compile_options(SRB2SDL2 PRIVATE -fsanitize=undefined) + target_link_options(SRB2SDL2 PRIVATE -fsanitize=undefined) + endif() + + if(NOT SRB2_CONFIG_MUMBLE) + target_compile_options(SRB2SDL2 PRIVATE -DNOMUMBLE) + endif() + ## strip debug symbols into separate file when using gcc # if(CMAKE_COMPILER_IS_GNUCC) # if(${CMAKE_BUILD_TYPE} MATCHES Debug) @@ -292,7 +317,7 @@ if(${SDL2_FOUND}) else() find_library(SRB2_SDL2_DLL_${dllname} "${defaultname}") list(APPEND win_extra_dll_list ${SRB2_SDL2_DLL_${dllname}}) - endif() + endif() endmacro() getwinlib(SDL2 "SDL2.dll") if(${SRB2_CONFIG_SDL2_USEMIXER}) diff --git a/src/sdl/SDL_main/SDL_openxdk_main.c b/src/sdl/SDL_main/SDL_openxdk_main.c deleted file mode 100644 index 63db8da2d..000000000 --- a/src/sdl/SDL_main/SDL_openxdk_main.c +++ /dev/null @@ -1,7 +0,0 @@ -/* Include the SDL main definition header */ -#include "SDL_main.h" - -void XBoxStartup() -{ - SDL_main(0, NULL); /// \todo ? -} diff --git a/src/sdl/SRB2Pandora/Makefile.cfg b/src/sdl/SRB2Pandora/Makefile.cfg deleted file mode 100644 index c7f0f8449..000000000 --- a/src/sdl/SRB2Pandora/Makefile.cfg +++ /dev/null @@ -1,39 +0,0 @@ -# Quick Pandora target to make a compliant SRB2 PND file. - -PNDNAME=SRB2.pnd -PNDDIR=$(BIN)/pnd -ICON=sdl/SRB2Pandora/icon.png -PXML=sdl/SRB2Pandora/PXML.xml - -SED=sed -CAT=cat -CP=cp -XARGS=xargs -FOR=for -WGET=wget -P $(PNDDIR) -c -nc - -SHXARGS:=$(XARGS) -SHSED:=$(SED) - -ifndef ECHO - CP:=@$(CP) - CAT:=@$(CAT) - SED:=@$(SED) - XARGS:=@$(XARGS) - FOR:=@(FOR) -endif - -$(BIN)/$(PNDNAME): $(BIN)/$(EXENAME) - @echo Linking $(PNDNAME)... - $(MKDIR) $(PNDDIR) - $(CP) $(BIN)/$(EXENAME) $(PNDDIR) - $(CP) $(ICON) $(PNDDIR) - $(CP) $(PXML) $(PNDDIR) -ifdef WITHDATA - $(FOR) datafile in $(shell echo $(D_FILES) | $(SHSED) 's/\.srb/\.wad/' | $(SHXARGS) -n 1 basename); do \ - $(WGET) http://alam.srb2.org/SRB2/2.0.6-Final/Resources/$$datafile; \ - done -endif - $(MKISOFS) -l -r -o $@ $(PNDDIR) - $(CAT) $(PXML) >> $@ - $(REMOVE) -r $(PNDDIR) diff --git a/src/sdl/SRB2Pandora/PXML.xml b/src/sdl/SRB2Pandora/PXML.xml deleted file mode 100644 index 33a9587db..000000000 --- a/src/sdl/SRB2Pandora/PXML.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - Sonic Robo Blast 2 - ソニック・ロボ・ブラスト・2 - A 3D Sonic fangame with a huge fanbase developing custom content, including characters, levels, and even large-scale modifications - - - - - - - - - - - diff --git a/src/sdl/SRB2Pandora/icon.png b/src/sdl/SRB2Pandora/icon.png deleted file mode 100644 index 63af73ac3..000000000 Binary files a/src/sdl/SRB2Pandora/icon.png and /dev/null differ diff --git a/src/sdl/Srb2SDL.dsp b/src/sdl/Srb2SDL.dsp deleted file mode 100644 index 96d3e8418..000000000 --- a/src/sdl/Srb2SDL.dsp +++ /dev/null @@ -1,1035 +0,0 @@ -# Microsoft Developer Studio Project File - Name="Srb2SDL" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 6.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Console Application" 0x0103 - -CFG=Srb2SDL - Win32 Debug -!MESSAGE This is not a valid makefile. To build this project using NMAKE, -!MESSAGE use the Export Makefile command and run -!MESSAGE -!MESSAGE NMAKE /f "Srb2SDL.mak". -!MESSAGE -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "Srb2SDL.mak" CFG="Srb2SDL - Win32 Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "Srb2SDL - Win32 Release" (based on "Win32 (x86) Console Application") -!MESSAGE "Srb2SDL - Win32 Debug" (based on "Win32 (x86) Console Application") -!MESSAGE - -# Begin Project -# PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "" -# PROP Scc_LocalPath "" -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "Srb2SDL - Win32 Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "Release" -# PROP BASE Intermediate_Dir "Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "..\..\bin\VC\Release\SDL" -# PROP Intermediate_Dir "..\..\objs\VC\Release\SDL" -# PROP Ignore_Export_Lib 0 -# PROP Target_Dir "" -MTL=midl.exe -# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 -# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 -# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /G5 /W3 /GX /Zi /Ot /Og /Oi /Op /Oy /Ob1 /I "..\..\libs\libpng-src" /I "..\..\libs\zlib" /D "NDEBUG" /D "SDLMAIN" /D "NO_STDIO_REDIRECT" /D "USE_WGL_SWAP" /D "HAVE_SDL" /D "HWRENDER" /D "HAVE_FILTER" /D "HAVE_MIXER" /D "USEASM" /D "HAVE_PNG" /FR /FD /GF /c -# ADD BASE RSC /l 0x409 /d "NDEBUG" -# ADD RSC /l 0x409 /d "NDEBUG" -# SUBTRACT RSC /x -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo /o"..\..\objs\SDL\Release\SRB2.bsc" -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /machine:I386 -# ADD LINK32 SDL.lib SDL_mixer.lib user32.lib advapi32.lib ws2_32.lib /nologo /subsystem:windows /pdb:"C:\srb2demo2\srb2sdl.pdb" /debug /machine:I386 /out:"C:\srb2demo2\srb2sdl.exe" -# SUBTRACT LINK32 /profile /pdb:none /incremental:yes - -!ELSEIF "$(CFG)" == "Srb2SDL - Win32 Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "Debug" -# PROP BASE Intermediate_Dir "Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "..\..\bin\VC\Debug\SDL" -# PROP Intermediate_Dir "..\..\objs\VC\Debug\SDL" -# PROP Ignore_Export_Lib 0 -# PROP Target_Dir "" -MTL=midl.exe -# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c -# ADD CPP /nologo /G6 /W4 /WX /Gm /GX /ZI /Od /Op /I "..\..\libs\libpng-src" /I "..\..\libs\zlib" /D "_DEBUG" /D "USE_WGL_SWAP" /D "HAVE_SDL" /D "HWRENDER" /D "HAVE_FILTER" /D "HAVE_MIXER" /D "USEASM" /D "HAVE_PNG" /FR /FD /GZ /c -# SUBTRACT CPP /YX -# ADD BASE RSC /l 0x409 /d "_DEBUG" -# ADD RSC /l 0x409 /d "_DEBUG" -# SUBTRACT RSC /x -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo /o"..\..\objs\SDL\Debug\SRB2.bsc" -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept -# ADD LINK32 SDL.lib SDL_mixer.lib user32.lib advapi32.lib ws2_32.lib /nologo /subsystem:console /pdb:"C:\srb2demo2\srb2sdldebug.pdb" /debug /machine:I386 /out:"C:\srb2demo2\srb2sdldebug.exe" /pdbtype:sept -# SUBTRACT LINK32 /pdb:none - -!ENDIF - -# Begin Target - -# Name "Srb2SDL - Win32 Release" -# Name "Srb2SDL - Win32 Debug" -# Begin Group "SDLapp" - -# PROP Default_Filter "" -# Begin Group "filter" - -# PROP Default_Filter "" -# Begin Source File - -SOURCE=.\filter\filters.c -# End Source File -# Begin Source File - -SOURCE=.\filter\filters.h -# End Source File -# Begin Source File - -SOURCE=.\filter\hq2x.c -# End Source File -# Begin Source File - -SOURCE=.\filter\hq2x.h -# End Source File -# Begin Source File - -SOURCE=.\filter\interp.h -# End Source File -# Begin Source File - -SOURCE=.\filter\lq2x.c -# End Source File -# Begin Source File - -SOURCE=.\filter\lq2x.h -# End Source File -# End Group -# Begin Source File - -SOURCE=.\dosstr.c -# End Source File -# Begin Source File - -SOURCE=.\endtxt.c -# End Source File -# Begin Source File - -SOURCE=.\endtxt.h -# End Source File -# Begin Source File - -SOURCE=..\filesrch.c -# End Source File -# Begin Source File - -SOURCE=..\filesrch.h -# End Source File -# Begin Source File - -SOURCE=.\hwsym_sdl.c -# End Source File -# Begin Source File - -SOURCE=.\hwsym_sdl.h -# End Source File -# Begin Source File - -SOURCE=.\i_cdmus.c -# End Source File -# Begin Source File - -SOURCE=.\i_main.c -# End Source File -# Begin Source File - -SOURCE=.\i_net.c -# End Source File -# Begin Source File - -SOURCE=.\i_sound.c -# End Source File -# Begin Source File - -SOURCE=.\i_system.c -# End Source File -# Begin Source File - -SOURCE=.\i_video.c -# End Source File -# Begin Source File - -SOURCE=.\IMG_xpm.c -# PROP Exclude_From_Build 1 -# End Source File -# Begin Source File - -SOURCE=.\ogl_sdl.c -# End Source File -# Begin Source File - -SOURCE=.\ogl_sdl.h -# End Source File -# Begin Source File - -SOURCE=..\hardware\r_opengl\r_opengl.c -# End Source File -# Begin Source File - -SOURCE=..\hardware\r_opengl\r_opengl.h -# End Source File -# Begin Source File - -SOURCE=.\SDL_icon.xpm -# End Source File -# Begin Source File - -SOURCE=.\SDL_main\SDL_win32_main.c - -!IF "$(CFG)" == "Srb2SDL - Win32 Release" - -!ELSEIF "$(CFG)" == "Srb2SDL - Win32 Debug" - -# PROP Exclude_From_Build 1 - -!ENDIF - -# End Source File -# Begin Source File - -SOURCE=.\sdlmain.h -# End Source File -# Begin Source File - -SOURCE=..\win32\Srb2win.rc -# End Source File -# Begin Source File - -SOURCE=..\win32\win_dbg.c -# End Source File -# Begin Source File - -SOURCE=..\win32\win_dbg.h -# End Source File -# Begin Source File - -SOURCE=..\win32\win_main.h -# End Source File -# End Group -# Begin Group "A_Asm" - -# PROP Default_Filter "" -# Begin Source File - -SOURCE=..\p5prof.h -# End Source File -# Begin Source File - -SOURCE=..\tmap.nas - -!IF "$(CFG)" == "Srb2SDL - Win32 Release" - -# PROP Ignore_Default_Tool 1 -# Begin Custom Build - Compiling $(InputName).nas with NASM... -IntDir=.\..\..\objs\VC\Release\SDL -InputPath=..\tmap.nas -InputName=tmap - -"$(IntDir)/$(InputName).obj" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" - nasm -g -o $(IntDir)/$(InputName).obj -f win32 $(InputPath) - -# End Custom Build - -!ELSEIF "$(CFG)" == "Srb2SDL - Win32 Debug" - -# PROP Ignore_Default_Tool 1 -# Begin Custom Build - Compiling $(InputName).nas with NASM... -IntDir=.\..\..\objs\VC\Debug\SDL -InputPath=..\tmap.nas -InputName=tmap - -"$(IntDir)/$(InputName).obj" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" - nasm -g -o $(IntDir)/$(InputName).obj -f win32 $(InputPath) - -# End Custom Build - -!ENDIF - -# End Source File -# Begin Source File - -SOURCE=..\tmap_mmx.nas - -!IF "$(CFG)" == "Srb2SDL - Win32 Release" - -# PROP Ignore_Default_Tool 1 -# Begin Custom Build - Compiling $(InputName).nas with NASM... -IntDir=.\..\..\objs\VC\Release\SDL -InputPath=..\tmap_mmx.nas -InputName=tmap_mmx - -"$(IntDir)/$(InputName).obj" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" - nasm -g -o $(IntDir)/$(InputName).obj -f win32 $(InputPath) - -# End Custom Build - -!ELSEIF "$(CFG)" == "Srb2SDL - Win32 Debug" - -# PROP Ignore_Default_Tool 1 -# Begin Custom Build - Compiling $(InputName).nas with NASM... - -IntDir=.\..\..\objs\VC\Debug\SDL -InputPath=..\tmap_mmx.nas -InputName=tmap_mmx - -"$(IntDir)/$(InputName).obj" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" - nasm -g -o $(IntDir)/$(InputName).obj -f win32 $(InputPath) - -# End Custom Build - -!ENDIF - -# End Source File -# Begin Source File - -SOURCE=..\tmap_vc.nas - -!IF "$(CFG)" == "Srb2SDL - Win32 Release" - -# Begin Custom Build - Compiling $(InputName).nas with NASM... -IntDir=.\..\..\objs\VC\Release\SDL -InputPath=..\tmap_vc.nas -InputName=tmap_vc - -"$(IntDir)/$(InputName).obj" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" - nasm -g -o $(IntDir)/$(InputName).obj -f win32 $(InputPath) - -# End Custom Build - -!ELSEIF "$(CFG)" == "Srb2SDL - Win32 Debug" - -# Begin Custom Build - Compiling $(InputName).nas with NASM... -IntDir=.\..\..\objs\VC\Debug\SDL -InputPath=..\tmap_vc.nas -InputName=tmap_vc - -"$(IntDir)/$(InputName).obj" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" - nasm -g -o $(IntDir)/$(InputName).obj -f win32 $(InputPath) - -# End Custom Build - -!ENDIF - -# End Source File -# End Group -# Begin Group "D_Doom" - -# PROP Default_Filter "" -# Begin Source File - -SOURCE=..\comptime.c -# End Source File -# Begin Source File - -SOURCE=..\d_clisrv.c -# End Source File -# Begin Source File - -SOURCE=..\d_clisrv.h -# End Source File -# Begin Source File - -SOURCE=..\d_event.h -# End Source File -# Begin Source File - -SOURCE=..\d_main.c -# End Source File -# Begin Source File - -SOURCE=..\d_main.h -# End Source File -# Begin Source File - -SOURCE=..\d_net.c -# End Source File -# Begin Source File - -SOURCE=..\d_net.h -# End Source File -# Begin Source File - -SOURCE=..\d_netcmd.c -# End Source File -# Begin Source File - -SOURCE=..\d_netcmd.h -# End Source File -# Begin Source File - -SOURCE=..\d_netfil.c -# End Source File -# Begin Source File - -SOURCE=..\d_netfil.h -# End Source File -# Begin Source File - -SOURCE=..\d_player.h -# End Source File -# Begin Source File - -SOURCE=..\d_think.h -# End Source File -# Begin Source File - -SOURCE=..\d_ticcmd.h -# End Source File -# Begin Source File - -SOURCE=..\dehacked.c -# End Source File -# Begin Source File - -SOURCE=..\dehacked.h -# End Source File -# Begin Source File - -SOURCE=..\doomdata.h -# End Source File -# Begin Source File - -SOURCE=..\doomdef.h -# End Source File -# Begin Source File - -SOURCE=..\doomstat.h -# End Source File -# Begin Source File - -SOURCE=..\doomtype.h -# End Source File -# Begin Source File - -SOURCE=..\z_zone.c -# End Source File -# Begin Source File - -SOURCE=..\z_zone.h -# End Source File -# End Group -# Begin Group "F_Frame" - -# PROP Default_Filter "" -# Begin Source File - -SOURCE=..\f_finale.c -# End Source File -# Begin Source File - -SOURCE=..\f_finale.h -# End Source File -# Begin Source File - -SOURCE=..\f_wipe.c -# End Source File -# End Group -# Begin Group "G_Game" - -# PROP Default_Filter "" -# Begin Source File - -SOURCE=..\g_game.c -# End Source File -# Begin Source File - -SOURCE=..\g_game.h -# End Source File -# Begin Source File - -SOURCE=..\g_input.c -# End Source File -# Begin Source File - -SOURCE=..\g_input.h -# End Source File -# Begin Source File - -SOURCE=..\g_state.h -# End Source File -# End Group -# Begin Group "H_Hud" - -# PROP Default_Filter "" -# Begin Source File - -SOURCE=..\am_map.c -# End Source File -# Begin Source File - -SOURCE=..\am_map.h -# End Source File -# Begin Source File - -SOURCE=..\command.c -# End Source File -# Begin Source File - -SOURCE=..\command.h -# End Source File -# Begin Source File - -SOURCE=..\console.c -# End Source File -# Begin Source File - -SOURCE=..\console.h -# End Source File -# Begin Source File - -SOURCE=..\hu_stuff.c -# End Source File -# Begin Source File - -SOURCE=..\hu_stuff.h -# End Source File -# Begin Source File - -SOURCE=..\st_stuff.c -# End Source File -# Begin Source File - -SOURCE=..\st_stuff.h -# End Source File -# Begin Source File - -SOURCE=..\y_inter.c -# End Source File -# Begin Source File - -SOURCE=..\y_inter.h -# End Source File -# End Group -# Begin Group "Hw_Hardware" - -# PROP Default_Filter "" -# Begin Source File - -SOURCE=..\hardware\hw_bsp.c -# End Source File -# Begin Source File - -SOURCE=..\hardware\hw_cache.c -# End Source File -# Begin Source File - -SOURCE=..\hardware\hw_data.h -# End Source File -# Begin Source File - -SOURCE=..\hardware\hw_defs.h -# End Source File -# Begin Source File - -SOURCE=..\hardware\hw_dll.h -# End Source File -# Begin Source File - -SOURCE=..\hardware\hw_draw.c -# End Source File -# Begin Source File - -SOURCE=..\hardware\hw_gl.h -# End Source File -# Begin Source File - -SOURCE=..\hardware\hw_glob.h -# End Source File -# Begin Source File - -SOURCE=..\hardware\hw_main.c -# End Source File -# Begin Source File - -SOURCE=..\hardware\hw_main.h -# End Source File -# Begin Source File - -SOURCE=..\hardware\hw_md2.c -# End Source File -# Begin Source File - -SOURCE=..\hardware\hw_md2.h -# End Source File -# Begin Source File - -# PROP Default_Filter "" -# Begin Source File - -SOURCE=..\byteptr.h -# End Source File -# Begin Source File - -SOURCE=..\i_joy.h -# End Source File -# Begin Source File - -SOURCE=..\i_net.h -# End Source File -# Begin Source File - -SOURCE=..\i_sound.h -# End Source File -# Begin Source File - -SOURCE=..\i_system.h -# End Source File -# Begin Source File - -SOURCE=..\i_tcp.c -# End Source File -# Begin Source File - -SOURCE=..\i_tcp.h -# End Source File -# Begin Source File - -SOURCE=..\i_video.h -# End Source File -# Begin Source File - -SOURCE=..\keys.h -# End Source File -# Begin Source File - -SOURCE=..\mserv.c -# End Source File -# Begin Source File - -SOURCE=..\mserv.h -# End Source File -# End Group -# Begin Group "M_Misc" - -# PROP Default_Filter "" -# Begin Source File - -SOURCE=..\m_argv.c -# End Source File -# Begin Source File - -SOURCE=..\m_argv.h -# End Source File -# Begin Source File - -SOURCE=..\m_bbox.c -# End Source File -# Begin Source File - -SOURCE=..\m_bbox.h -# End Source File -# Begin Source File - -SOURCE=..\m_cheat.c -# End Source File -# Begin Source File - -SOURCE=..\m_cheat.h -# End Source File -# Begin Source File - -SOURCE=..\m_dllist.h -# End Source File -# Begin Source File - -SOURCE=..\m_fixed.c -# End Source File -# Begin Source File - -SOURCE=..\m_fixed.h -# End Source File -# Begin Source File - -SOURCE=..\m_menu.c -# End Source File -# Begin Source File - -SOURCE=..\m_menu.h -# End Source File -# Begin Source File - -SOURCE=..\m_misc.c -# End Source File -# Begin Source File - -SOURCE=..\m_misc.h -# End Source File -# Begin Source File - -SOURCE=..\m_queue.c -# End Source File -# Begin Source File - -SOURCE=..\m_queue.h -# End Source File -# Begin Source File - -SOURCE=..\m_random.c -# End Source File -# Begin Source File - -SOURCE=..\m_random.h -# End Source File -# Begin Source File - -SOURCE=..\m_swap.h -# End Source File -# Begin Source File - -SOURCE=..\string.c -# End Source File -# End Group -# Begin Group "P_Play" - -# PROP Default_Filter "" -# Begin Source File - -SOURCE=..\info.c -# End Source File -# Begin Source File - -SOURCE=..\info.h -# End Source File -# Begin Source File - -SOURCE=..\p_ceilng.c -# End Source File -# Begin Source File - -SOURCE=..\p_enemy.c -# End Source File -# Begin Source File - -SOURCE=..\p_fab.c -# End Source File -# Begin Source File - -SOURCE=..\p_floor.c -# End Source File -# Begin Source File - -SOURCE=..\p_inter.c -# End Source File -# Begin Source File - -SOURCE=..\p_lights.c -# End Source File -# Begin Source File - -SOURCE=..\p_local.h -# End Source File -# Begin Source File - -SOURCE=..\p_map.c -# End Source File -# Begin Source File - -SOURCE=..\p_maputl.c -# End Source File -# Begin Source File - -SOURCE=..\p_maputl.h -# End Source File -# Begin Source File - -SOURCE=..\p_mobj.c -# End Source File -# Begin Source File - -SOURCE=..\p_mobj.h -# End Source File -# Begin Source File - -SOURCE=..\p_polyobj.c -# End Source File -# Begin Source File - -SOURCE=..\p_polyobj.h -# End Source File -# Begin Source File - -SOURCE=..\p_pspr.h -# End Source File -# Begin Source File - -SOURCE=..\p_saveg.c -# End Source File -# Begin Source File - -SOURCE=..\p_saveg.h -# End Source File -# Begin Source File - -SOURCE=..\p_setup.c -# End Source File -# Begin Source File - -SOURCE=..\p_setup.h -# End Source File -# Begin Source File - -SOURCE=..\p_sight.c -# End Source File -# Begin Source File - -SOURCE=..\p_spec.c -# End Source File -# Begin Source File - -SOURCE=..\p_spec.h -# End Source File -# Begin Source File - -SOURCE=..\p_telept.c -# End Source File -# Begin Source File - -SOURCE=..\p_tick.c -# End Source File -# Begin Source File - -SOURCE=..\p_tick.h -# End Source File -# Begin Source File - -SOURCE=..\p_user.c -# End Source File -# Begin Source File - -SOURCE=..\tables.c -# End Source File -# Begin Source File - -SOURCE=..\tables.h -# End Source File -# End Group -# Begin Group "R_Rend" - -# PROP Default_Filter "" -# Begin Source File - -SOURCE=..\r_bsp.c -# End Source File -# Begin Source File - -SOURCE=..\r_bsp.h -# End Source File -# Begin Source File - -SOURCE=..\r_data.c -# End Source File -# Begin Source File - -SOURCE=..\r_data.h -# End Source File -# Begin Source File - -SOURCE=..\r_defs.h -# End Source File -# Begin Source File - -SOURCE=..\r_draw.c -# End Source File -# Begin Source File - -SOURCE=..\r_draw.h -# End Source File -# Begin Source File - -SOURCE=..\r_draw8.c -# PROP Exclude_From_Build 1 -# End Source File -# Begin Source File - -SOURCE=..\r_local.h -# End Source File -# Begin Source File - -SOURCE=..\r_main.c -# End Source File -# Begin Source File - -SOURCE=..\r_main.h -# End Source File -# Begin Source File - -SOURCE=..\r_patch.c -# End Source File -# Begin Source File - -SOURCE=..\r_patch.h -# End Source File -# Begin Source File - -SOURCE=..\r_patchrotation.c -# End Source File -# Begin Source File - -SOURCE=..\r_patchrotation.h -# End Source File -# Begin Source File - -SOURCE=..\r_plane.c -# End Source File -# Begin Source File - -SOURCE=..\r_plane.h -# End Source File -# Begin Source File - -SOURCE=..\r_segs.c -# End Source File -# Begin Source File - -SOURCE=..\r_segs.h -# End Source File -# Begin Source File - -SOURCE=..\r_sky.c -# End Source File -# Begin Source File - -SOURCE=..\r_sky.h -# End Source File -# Begin Source File - -SOURCE=..\r_splats.c -# End Source File -# Begin Source File - -SOURCE=..\r_splats.h -# End Source File -# Begin Source File - -SOURCE=..\r_state.h -# End Source File -# Begin Source File - -SOURCE=..\r_things.c -# End Source File -# Begin Source File - -SOURCE=..\r_things.h -# End Source File -# Begin Source File - -SOURCE=..\screen.c -# End Source File -# Begin Source File - -SOURCE=..\screen.h -# End Source File -# Begin Source File - -SOURCE=..\v_video.c -# End Source File -# Begin Source File - -SOURCE=..\v_video.h -# End Source File -# End Group -# Begin Group "S_Sounds" - -# PROP Default_Filter "" -# Begin Source File - -SOURCE=..\s_sound.c -# End Source File -# Begin Source File - -SOURCE=..\s_sound.h -# End Source File -# Begin Source File - -SOURCE=..\sounds.c -# End Source File -# Begin Source File - -SOURCE=..\sounds.h -# End Source File -# End Group -# Begin Group "W_Wad" - -# PROP Default_Filter "" -# Begin Source File - -SOURCE=..\lzf.c -# End Source File -# Begin Source File - -SOURCE=..\lzf.h -# End Source File -# Begin Source File - -SOURCE=..\md5.c -# End Source File -# Begin Source File - -SOURCE=..\md5.h -# End Source File -# Begin Source File - -SOURCE=..\w_wad.c -# End Source File -# Begin Source File - -SOURCE=..\w_wad.h -# End Source File -# End Group -# Begin Group "Docs" - -# PROP Default_Filter "" -# Begin Source File - -SOURCE=..\..\doc\copying -# End Source File -# Begin Source File - -SOURCE=..\..\doc\faq.txt -# End Source File -# Begin Source File - -SOURCE=..\..\readme.txt -# End Source File -# Begin Source File - -SOURCE=..\..\doc\source.txt -# End Source File -# End Group -# Begin Source File - -SOURCE=..\win32\Srb2win.ico -# End Source File -# End Target -# End Project diff --git a/src/sdl/Srb2SDL.dsw b/src/sdl/Srb2SDL.dsw deleted file mode 100644 index 888d2fcf3..000000000 --- a/src/sdl/Srb2SDL.dsw +++ /dev/null @@ -1,62 +0,0 @@ -Microsoft Developer Studio Workspace File, Format Version 6.00 -# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! - -############################################################################### - -Project: "Srb2SDL"=.\Srb2SDL.dsp - Package Owner=<4> - -Package=<5> -{{{ -}}} - -Package=<4> -{{{ - Begin Project Dependency - Project_Dep_Name libpng - End Project Dependency - Begin Project Dependency - Project_Dep_Name zlib - End Project Dependency -}}} - -############################################################################### - -Project: "libpng"="..\..\libs\libpng-src\projects\visualc6\libpng.dsp" - Package Owner=<4> - -Package=<5> -{{{ -}}} - -Package=<4> -{{{ - Begin Project Dependency - Project_Dep_Name zlib - End Project Dependency -}}} - -############################################################################### - -Project: "zlib"=..\..\libs\zlib\projects\visualc6\zlib.dsp - Package Owner=<4> - -Package=<5> -{{{ -}}} - -Package=<4> -{{{ -}}} - -############################################################################### - -Global: - -Package=<5> -{{{ -}}} - -Package=<3> -{{{ -}}} - -############################################################################### - diff --git a/src/sdl/Srb2SDL.ico b/src/sdl/Srb2SDL.ico deleted file mode 100644 index 87bd2766e..000000000 Binary files a/src/sdl/Srb2SDL.ico and /dev/null differ diff --git a/src/sdl/Srb2SDL.props b/src/sdl/Srb2SDL.props deleted file mode 100644 index 8c4799f20..000000000 --- a/src/sdl/Srb2SDL.props +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - HAVE_ZLIB;HAVE_LIBGME;USE_WGL_SWAP;HAVE_SDL;HWRENDER;HAVE_FILTER;HAVE_MIXER;SDLMAIN;%(PreprocessorDefinitions) - - USE_WGL_SWAP;HAVE_SDL;HWRENDER;HAVE_FILTER;HAVE_MIXER;SDLMAIN;%(PreprocessorDefinitions) - - - - diff --git a/src/sdl/i_system.cpp b/src/sdl/i_system.cpp index 00250bf4f..6f7478f81 100644 --- a/src/sdl/i_system.cpp +++ b/src/sdl/i_system.cpp @@ -31,6 +31,10 @@ #include +#if defined (__unix__) || defined(__APPLE__) || defined (UNIXCOMMON) +#include +#endif + #ifdef _WIN32 #define RPC_NO_WINDOWS_H #include @@ -53,10 +57,13 @@ typedef LPVOID (WINAPI *p_MapViewOfFile) (HANDLE, DWORD, DWORD, DWORD, SIZE_T); #include #include #include + #ifdef __GNUC__ #include #endif + #if defined (__unix__) || defined (UNIXCOMMON) +#include #include #endif @@ -79,6 +86,12 @@ typedef LPVOID (WINAPI *p_MapViewOfFile) (HANDLE, DWORD, DWORD, DWORD, SIZE_T); #if defined (__unix__) || defined(__APPLE__) || (defined (UNIXCOMMON) && !defined (__HAIKU__)) #if defined (__linux__) #include +#elif defined(__APPLE__) +#include +#include +#include +#include +#include #else #include #include @@ -168,8 +181,7 @@ const char *wadSearchPaths[] = { /** \brief WAD file to look for */ -#define WADKEYWORD1 "srb2.srb" -#define WADKEYWORD2 "srb2.wad" +#define WADKEYWORD "srb2.srb" /** \brief holds wad path */ static char returnWadPath[256]; @@ -201,10 +213,6 @@ static char returnWadPath[256]; #include "../s_sound.h" -#ifdef MAC_ALERT -#include "macosx/mac_alert.h" -#endif - #include "../d_main.h" #if !defined(NOMUMBLE) && defined(HAVE_MUMBLE) @@ -213,14 +221,12 @@ static char returnWadPath[256]; #include "../byteptr.h" #endif -SDL_bool consolevent = SDL_FALSE; -SDL_bool framebuffer = SDL_FALSE; +boolean consolevent = false; +boolean framebuffer = false; UINT8 keyboard_started = false; #ifdef HAVE_TERMIOS // TERMIOS console code from Quake3: thank you! -SDL_bool stdin_active = SDL_TRUE; - typedef struct { size_t cursor; @@ -282,7 +288,7 @@ static void I_ShutdownConsole(void) if (consolevent) { I_OutputMsg("Shutdown tty console\n"); - consolevent = SDL_FALSE; + consolevent = false; tcsetattr(STDIN_FILENO, TCSADRAIN, &tty_tc); } } @@ -301,15 +307,15 @@ static void I_StartupConsole(void) framebuffer = static_cast( M_CheckParm("-framebuffer")); if (framebuffer) - consolevent = SDL_FALSE; + consolevent = false; if (!consolevent) return; - if (isatty(STDIN_FILENO)!=1) + if (isatty(STDIN_FILENO) != 1) { I_OutputMsg("stdin is not a tty, tty console mode failed\n"); - consolevent = SDL_FALSE; + consolevent = false; return; } @@ -511,7 +517,7 @@ static void I_StartupConsole(void) if (gotConsole) { SetConsoleTitleA("SRB2Kart Console"); - consolevent = SDL_TRUE; + consolevent = true; } //Let get the real console HANDLE, because Mingw's Bash is bad! @@ -544,7 +550,7 @@ static inline void I_StartupConsole(void) framebuffer = M_CheckParm("-framebuffer"); if (framebuffer) - consolevent = SDL_FALSE; + consolevent = false; } static inline void I_ShutdownConsole(void){} #endif @@ -557,12 +563,12 @@ void I_OutputMsg(const char *fmt, ...) { size_t len; char *txt; - va_list argptr; + va_list argptr; if (!fmt) return; - va_start(argptr,fmt); + va_start(argptr, fmt); len = vsnprintf(NULL, 0, fmt, argptr); va_end(argptr); if (len == 0) @@ -573,8 +579,8 @@ void I_OutputMsg(const char *fmt, ...) if (!txt) I_Error("I_OutputMsg: Out of memory!\n"); - va_start(argptr,fmt); - vsprintf(txt, fmt, argptr); + va_start(argptr, fmt); + vsnprintf(txt, len+1, fmt, argptr); va_end(argptr); #ifdef HAVE_TTF @@ -582,7 +588,7 @@ void I_OutputMsg(const char *fmt, ...) DEFAULTFONTBGR, DEFAULTFONTBGG, DEFAULTFONTBGB, DEFAULTFONTBGA, txt); #endif - len = strlen(txt); + len = strnlen(txt, len+1); #ifdef LOGMESSAGES if (logstream) @@ -693,7 +699,7 @@ void I_OutputMsg(const char *fmt, ...) // // I_GetKey // -INT32 I_GetKey (void) +INT32 I_GetKey(void) { // Warning: I_GetKey empties the event queue till next keypress event_t *ev; @@ -728,13 +734,16 @@ static void JoyReset(SDLJoyInfo_t *JoySet) JoySet->dev = NULL; JoySet->oldjoy = -1; +#if (SDL_VERSION_ATLEAST(2,32,4)) JoySet->id = -1; - JoySet->axises = JoySet->buttons = JoySet->hats = JoySet->balls = 0; +#endif + JoySet->hasled = false; + JoySet->hasrumble = false; } /** \brief SDL info about joystick */ -SDLJoyInfo_t JoyInfo[MAXSPLITSCREENPLAYERS]; +SDLJoyInfo_t JoyInfo[MAXSPLITSCREENPLAYERS] = {}; INT32 numcontrollers = 0; // @@ -742,30 +751,26 @@ INT32 numcontrollers = 0; // void I_JoyScale(void) { - Joystick[0].bGamepadStyle = cv_joyscale[0].value==0; - JoyInfo[0].scale = Joystick[0].bGamepadStyle?1:cv_joyscale[0].value; + JoyInfo[0].scale = DigitalGamepadStyle(0) ? 1 : cv_joyscale[0].value; } void I_JoyScale2(void) { - Joystick[1].bGamepadStyle = cv_joyscale[1].value==0; - JoyInfo[1].scale = Joystick[1].bGamepadStyle?1:cv_joyscale[1].value; + JoyInfo[1].scale = DigitalGamepadStyle(1) ? 1 : cv_joyscale[1].value; } void I_JoyScale3(void) { - Joystick[2].bGamepadStyle = cv_joyscale[2].value==0; - JoyInfo[2].scale = Joystick[2].bGamepadStyle?1:cv_joyscale[2].value; + JoyInfo[2].scale = DigitalGamepadStyle(2) ? 1 : cv_joyscale[2].value; } void I_JoyScale4(void) { - Joystick[3].bGamepadStyle = cv_joyscale[3].value==0; - JoyInfo[3].scale = Joystick[3].bGamepadStyle?1:cv_joyscale[3].value; + JoyInfo[3].scale = DigitalGamepadStyle(3) ? 1 : cv_joyscale[3].value; } // Cheat to get the device index for a joystick handle -INT32 I_GetJoystickDeviceIndex(SDL_GameController *dev) +static INT32 I_GetJoystickDeviceIndex(SDL_GameController *dev) { SDL_Joystick *joystick = NULL; @@ -786,7 +791,11 @@ void I_UpdateJoystickDeviceIndex(UINT8 player) /////////////////////////////////////////////// if (JoyInfo[player].dev) { +#if (SDL_VERSION_ATLEAST(2,32,4)) cv_usejoystick[player].value = JoyInfo[player].id + 1; +#else + cv_usejoystick[player].value = I_GetJoystickDeviceIndex(JoyInfo[player].dev) + 1; +#endif } else { @@ -888,13 +897,13 @@ static int joy_open(int playerIndex, int joyIndex) if (SDL_WasInit(SDL_INIT_JOYSTICK) == 0) { - CONS_Printf(M_GetText("Joystick subsystem not started\n")); + CONS_Printf("Joystick subsystem not started\n"); return -1; } if (SDL_WasInit(SDL_INIT_GAMECONTROLLER) == 0) { - CONS_Printf(M_GetText("Game Controller subsystem not started\n")); + CONS_Printf("Game Controller subsystem not started\n"); return -1; } @@ -905,7 +914,7 @@ static int joy_open(int playerIndex, int joyIndex) if (num_joy == 0) { - CONS_Printf("%s", M_GetText("Found no joysticks on this system\n")); + CONS_Printf("%s", "Found no joysticks on this system\n"); return -1; } @@ -928,38 +937,37 @@ static int joy_open(int playerIndex, int joyIndex) return SDL_CONTROLLER_AXIS_MAX; // Else, we're changing devices, so send neutral joy events - CONS_Debug(DBG_GAMELOGIC, "Joystick1 device is changing; resetting events...\n"); + CONS_Debug(DBG_GAMELOGIC, "Joystick %d device is changing; resetting events...\n", playerIndex+1); I_ShutdownJoystick(playerIndex); } JoyInfo[playerIndex].dev = newdev; - JoyInfo[playerIndex].id = I_GetJoystickDeviceIndex(JoyInfo[playerIndex].dev); if (JoyInfo[playerIndex].dev == NULL) { - CONS_Debug(DBG_GAMELOGIC, M_GetText("Joystick1: Couldn't open device - %s\n"), SDL_GetError()); + CONS_Debug(DBG_GAMELOGIC, "Joystick %d: Couldn't open device - %s\n", playerIndex+1, SDL_GetError()); return -1; } - else - { - CONS_Debug(DBG_GAMELOGIC, M_GetText("Joystick1: %s\n"), SDL_GameControllerName(JoyInfo[playerIndex].dev)); - JoyInfo[playerIndex].axises = SDL_CONTROLLER_AXIS_MAX; - if (JoyInfo[playerIndex].axises > JOYAXISSET*2) - JoyInfo[playerIndex].axises = JOYAXISSET*2; + CONS_Debug(DBG_GAMELOGIC, "Joystick %d: %s\n", playerIndex+1, SDL_GameControllerName(JoyInfo[playerIndex].dev)); - JoyInfo[playerIndex].buttons = SDL_CONTROLLER_BUTTON_MAX ; // dpad is 4 buttons - if (JoyInfo[playerIndex].buttons > JOYBUTTONS) - JoyInfo[playerIndex].buttons = JOYBUTTONS; +#if (SDL_VERSION_ATLEAST(2,32,4)) + JoyInfo[playerIndex].id = I_GetJoystickDeviceIndex(JoyInfo[playerIndex].dev); +#endif - JoyInfo[playerIndex].hats = 4; - if (JoyInfo[playerIndex].hats > JOYHATS) - JoyInfo[playerIndex].hats = JOYHATS; +#if (SDL_VERSION_ATLEAST(2,0,14)) + JoyInfo[playerIndex].hasled = SDL_GameControllerHasLED(JoyInfo[playerIndex].dev); +#endif +#if (SDL_VERSION_ATLEAST(2,0,18)) + JoyInfo[playerIndex].hasrumble = SDL_GameControllerHasRumble(JoyInfo[playerIndex].dev); +#endif - JoyInfo[playerIndex].balls = 0; + return SDL_CONTROLLER_AXIS_MAX; +} - return JoyInfo[playerIndex].axises; - } +void I_SetJoystickFocus(void) +{ + SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, cv_gamepadifunfocused.value ? "1" : "0"); } // @@ -976,6 +984,18 @@ void I_InitJoystick(UINT8 index) if (M_CheckParm("-nojoy")) return; + { + char dbpath[1024]; + snprintf(dbpath, sizeof(dbpath), "%s" PATHSEP "gamecontrollerdb.txt", srb2path); + SDL_GameControllerAddMappingsFromFile(dbpath); + } + + { + char dbpath[1024]; + snprintf(dbpath, sizeof(dbpath), "%s" PATHSEP "gamecontrollerdb_user.txt", srb2home); + SDL_GameControllerAddMappingsFromFile(dbpath); + } + if (M_CheckParm("-noxinput")) SDL_SetHintWithPriority("SDL_XINPUT_ENABLED", "0", SDL_HINT_OVERRIDE); @@ -1003,8 +1023,11 @@ void I_InitJoystick(UINT8 index) JoyInfo[index].dev = NULL; JoyInfo[index].oldjoy = -1; +#if (SDL_VERSION_ATLEAST(2,32,4)) JoyInfo[index].id = -1; - JoyInfo[index].axises = JoyInfo[index].buttons = JoyInfo[index].hats = JoyInfo[index].balls = 0; +#endif + JoyInfo[index].hasled = false; + JoyInfo[index].hasrumble = false; if (cv_usejoystick[index].value) newcontroller = SDL_GameControllerOpen(cv_usejoystick[index].value-1); @@ -1018,17 +1041,27 @@ void I_InitJoystick(UINT8 index) break; } +#if (SDL_VERSION_ATLEAST(2,32,4)) JoyInfo[index].id = I_GetJoystickDeviceIndex(JoyInfo[index].dev); +#endif if (newcontroller && i < MAXSPLITSCREENPLAYERS) // don't override an active device { +#if (SDL_VERSION_ATLEAST(2,32,4)) cv_usejoystick[index].value = JoyInfo[index].id + 1; +#else + cv_usejoystick[index].value = I_GetJoystickDeviceIndex(JoyInfo[index].dev) + 1; +#endif } else if (newcontroller && joy_open(index, cv_usejoystick[index].value) != -1) { +#if (SDL_VERSION_ATLEAST(2,32,4)) + JoyInfo[index].oldjoy = JoyInfo[index].id + 1; +#else // SDL's device indexes are unstable, so cv_usejoystick may not match // the actual device index. So let's cheat a bit and find the device's current index. - JoyInfo[index].oldjoy = JoyInfo[index].id + 1; + JoyInfo[index].oldjoy = I_GetJoystickDeviceIndex(JoyInfo[index].dev) + 1; +#endif } else { @@ -1121,14 +1154,33 @@ const char *I_GetJoyName(INT32 joyindex) if (tempname) { - memcpy(joyname, tempname, 255); - joyname[255] = '\0'; + snprintf(joyname, sizeof(joyname), "%s", tempname); } } return joyname; } +boolean I_GamepadHasLED(INT32 playernum) +{ +#if !(SDL_VERSION_ATLEAST(2,0,14)) + (void)playernum; + return false; +#else + return (JoyInfo[playernum].dev != NULL && JoyInfo[playernum].hasled); +#endif +} + +boolean I_GamepadHasRumble(INT32 playernum) +{ +#if !(SDL_VERSION_ATLEAST(2,0,18)) + (void)playernum; + return false; +#else + return (JoyInfo[playernum].dev != NULL && JoyInfo[playernum].hasrumble); +#endif +} + void I_GamepadRumble(INT32 playernum, UINT16 low_strength, UINT16 high_strength, UINT32 duration) { #if !(SDL_VERSION_ATLEAST(2,0,14)) @@ -1144,6 +1196,11 @@ void I_GamepadRumble(INT32 playernum, UINT16 low_strength, UINT16 high_strength, return; } + if (!I_GamepadHasRumble(playernum)) + { + return; + } + SDL_GameControllerRumble(controller, low_strength, high_strength, duration); #endif } @@ -1163,6 +1220,11 @@ void I_SetGamepadIndicatorColor(INT32 playernum, UINT8 red, UINT8 green, UINT8 b return; } + if (!I_GamepadHasLED(playernum)) + { + return; + } + SDL_GameControllerSetLED(controller, red, green, blue); #endif } @@ -1219,7 +1281,7 @@ static void I_SetupMumble(void) int shmfd; char memname[256]; - snprintf(memname, 256, "/MumbleLink.%d", getuid()); + snprintf(memname, sizeof(memname), "/MumbleLink.%d", getuid()); shmfd = shm_open(memname, O_RDWR, S_IRUSR | S_IWUSR); if (shmfd < 0) @@ -1336,19 +1398,31 @@ void I_Sleep(UINT32 ms) void I_SleepDuration(precise_t duration) { -#if defined(__linux__) || defined(__FreeBSD__) || defined(__HAIKU__) +#if defined(__linux__) || defined(__FreeBSD__) || defined(__HAIKU__) || defined(__OpenBSD__) UINT64 precision = I_GetPrecisePrecision(); precise_t dest = I_GetPreciseTime() + duration; +#ifdef __OpenBSD__ + precise_t slack = (precision / 50); // 20 ms slack +#else precise_t slack = (precision / 5000); // 0.2 ms slack +#endif if (duration > slack) { duration -= slack; struct timespec ts = { .tv_sec = static_cast<__time_t>(duration / precision), +#ifdef __BIONIC__ + .tv_nsec = static_cast(duration * 1000000000 / precision % 1000000000), +#else .tv_nsec = static_cast<__syscall_slong_t>(duration * 1000000000 / precision % 1000000000), +#endif }; int status; +#ifdef __OpenBSD__ + do status = nanosleep(&ts, &ts); +#else do status = clock_nanosleep(CLOCK_MONOTONIC, 0, &ts, &ts); +#endif while (status == EINTR); } @@ -1388,7 +1462,7 @@ void I_SleepDuration(precise_t duration) #endif } -static void I_PrintSignal(INT32 signal_num, boolean core_dumped, char *signal_msg); +static void I_PrintSignal(INT32 signal_num, boolean core_dumped, char *signal_msg, char *signal_ttl); #ifdef HAVE_LIBBACKTRACE #include @@ -1484,6 +1558,7 @@ static void bt_error_cb(void *data, const char *msg, int errnum) static void write_backtrace(bt_crash_reason_t reason) { char sig_msg[512]; + char sig_name[128]; const char *filename = va("%s" PATHSEP CRASH_LOGFILE_NAME, srb2home); FILE *out = fopen(filename, "a+"); @@ -1540,8 +1615,8 @@ static void write_backtrace(bt_crash_reason_t reason) switch (reason.type) { case BTCRASH_SIGNAL: - I_PrintSignal(reason.value.signal, false, sig_msg); - fprintf(out, "%s", sig_msg); + I_PrintSignal(reason.value.signal, false, sig_msg, sig_name); + fprintf(out, "%s - %s", sig_name, sig_msg); break; case BTCRASH_ERRORMSG: @@ -1575,70 +1650,160 @@ static void write_backtrace(bt_crash_reason_t reason) static std::thread::id g_main_thread_id; #endif -boolean g_in_exiting_signal_handler = false; +static volatile sig_atomic_t g_in_exiting_signal_handler = false; -static void I_PrintSignal(INT32 signal_num, boolean core_dumped, char *signal_msg) +static void I_PrintSignal(INT32 signal_num, boolean core_dumped, char *signal_msg, char *signal_name) { - const char *sigmsg; + const char *sigmsg, *signame; switch (signal_num) { #ifdef SIGINT case SIGINT: - sigmsg = ("SIGINT - SRB2Kart-Saturn was interrupted prematurely by the user."); + sigmsg = ("SRB2Kart-Saturn was interrupted prematurely by the user."); + signame = "SIGINT"; break; #endif case SIGILL: // illegal instruction - invalid function image - sigmsg = ("SIGILL - SRB2Kart-Saturn has attempted to execute an illegal instruction and needs to close."); + sigmsg = ("SRB2Kart-Saturn has attempted to execute an illegal instruction and needs to close."); + signame = "SIGILL"; break; case SIGFPE: // mathematical exception - sigmsg = ("SIGFPE - SRB2Kart-Saturn has encountered a mathematical exception and needs to close."); + sigmsg = ("SRB2Kart-Saturn has encountered a mathematical exception and needs to close."); + signame = "SIGFPE"; break; case SIGSEGV: // segment violation - sigmsg = ("SIGSEGV - SRB2Kart-Saturn has attempted to access a memory location that it shouldn't and needs to close."); + sigmsg = ("SRB2Kart-Saturn has attempted to access a memory location that it shouldn't and needs to close."); + signame = "SIGSEGV"; break; #ifdef SIGTERM - case SIGTERM: // Software termination signal from kill - sigmsg = ("SIGTERM - SRB2Kart-Saturn was terminated by a kill signal."); + case SIGTERM: // Software termination signal from terminate + sigmsg = ("SRB2Kart-Saturn was terminated by a terminate signal."); + signame = "SIGTERM"; + break; +#endif +#ifdef SIGKILL + case SIGKILL: // Software termination signal from kill + sigmsg = ("SRB2Kart-Saturn was terminated by a kill signal."); + signame = "SIGKILL"; break; #endif #ifdef SIGBREAK case SIGBREAK: // Ctrl-Break sequence sigmsg =("SIGBREAK - SRB2Kart-Saturn was terminated by a Ctrl-Break sequence."); + signame = "SIGBREAK"; break; #endif case SIGABRT: // abnormal termination triggered by abort call - sigmsg = ("SIGABRT - SRB2Kart-Saturn was terminated by an abort signal."); + sigmsg = ("SRB2Kart-Saturn was terminated by an abort signal."); + signame = "SIGABRT"; break; default: - sprintf(signal_msg, "Signal number %d", signal_num); - sigmsg = (core_dumped ? "Unknown signal" : signal_msg); + sigmsg = "SRB2Kart-Saturn was terminated by an unknown signal."; + signame = core_dumped ? "Unknown signal" : va("Signal number %d", signal_num); break; } if (core_dumped) { if (sigmsg) - sprintf(signal_msg, "%s (core dumped)", sigmsg); + { + snprintf(signal_msg, 512, "%s (core dumped)", sigmsg); + } else + { strcat(signal_msg, " (core dumped)"); + } } else { - sprintf(signal_msg, "%s", sigmsg); + snprintf(signal_msg, 512, "%s", sigmsg); } + + snprintf(signal_name, 128, "%s", signame); +} + +int I_OpenURL(const char *url) +{ +#if SDL_VERSION_ATLEAST(2,0,14) + return SDL_OpenURL(va("%s", url)); +#else + return -1; +#endif +} + +static void I_ShowErrorBox(const char *title, const char *msg) +{ + if (M_CheckParm("-dedicated")) + return; + + const char *reportmsg = "\n\n\nTo help us figure out the cause, please report the issue to our github page with " CRASH_LOGFILE_NAME " attached.\n\nSorry for the inconvenience!"; + + const SDL_MessageBoxButtonData buttons[] = { + { SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT, 0, "OK" }, + { 0, 1, "Report Issue" }, + }; + + const SDL_MessageBoxData messageboxdata = { + SDL_MESSAGEBOX_ERROR, /* .flags */ + NULL, /* .window */ + title, /* .title */ + va("%s %s", msg, reportmsg), /* .message */ + SDL_arraysize(buttons), /* .numbuttons */ + buttons, /* .buttons */ + NULL /* .colorScheme */ + }; + + int buttonid; + + SDL_ShowMessageBox(&messageboxdata, &buttonid); + + if (buttonid == 1) + { + int url = I_OpenURL(SATURNISSUEPAGE); + + // SDL_OpenURL unsupported or failed + if (url == -1) + SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Failed to Open Web Page", "Please open the following page in your web browser:\n" SATURNISSUEPAGE, NULL); + } +} + +static void I_ShowSimpleErrorBox(const char *title, char *msg) +{ + if (M_CheckParm("-dedicated")) + return; + + // Implement message box with SDL_ShowSimpleMessageBox, + // which should fail gracefully if it can't put a message box up + // on the target system + SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, title, msg, NULL); + // Note that SDL_ShowSimpleMessageBox does *not* require SDL to be + // initialized at the time, so calling it after SDL_Quit() is + // perfectly okay! In addition, we do this on purpose so the + // fullscreen window is closed before displaying the error message + // in case the fullscreen window blocks it for some absurd reason. } static void I_ReportSignal(int num, int coredumped) { char sigmsg[512]; + char signame[128]; + char sigttl[512] = "Process killed by signal: "; - I_PrintSignal(num, coredumped, sigmsg); + I_PrintSignal(num, coredumped, sigmsg, signame); size_t len = strlen(sigmsg); snprintf(sigmsg + len, sizeof(sigmsg) - len, "\n\nCrash report has been saved into %s", CRASH_LOGFILE_NAME); - I_OutputMsg("\nProcess killed by signal: %s\n\n", sigmsg); - SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Process killed by signal", sigmsg, NULL); + + strcat(sigttl, signame); + I_OutputMsg("\n%s\n\n", sigttl); + //I_ShowSimpleErrorBox(sigttl, sigmsg); + I_ShowErrorBox(sigttl, sigmsg); +} + +boolean I_In_Exiting_Signal_Handler(void) +{ + return g_in_exiting_signal_handler; } #ifndef NEWSIGNALHANDLER @@ -1670,21 +1835,17 @@ FUNCNORETURN static ATTRNORETURN void signal_handler(INT32 num) } #endif -FUNCNORETURN static ATTRNORETURN void quit_handler(int num) -{ -#ifdef HAVE_THREADS - if (g_main_thread_id != std::this_thread::get_id()) - { - // Do not attempt any sort of recovery if this signal triggers off the main thread - signal(num, SIG_DFL); - raise(num); - exit(-2); - } -#endif +static volatile sig_atomic_t interrupted = false; - signal(num, SIG_DFL); //default signal action - raise(num); - I_Quit(); +boolean I_Interrupted(void) +{ + return interrupted; +} + +static void quit_handler(int num) +{ + (void)num; + interrupted = true; } static void I_RegisterSignals(void) @@ -1732,24 +1893,19 @@ static void I_RegisterChildSignals(void) signal(SIGABRT, signal_handler_child); signal(SIGFPE, signal_handler_child); } -#endif -#ifdef NEWSIGNALHANDLER FUNCNORETURN static ATTRNORETURN void newsignalhandler_Warn(const char *pr) { char text[128]; - snprintf(text, sizeof text, + snprintf(text, sizeof(text), "Error while setting up signal reporting: %s: %s", pr, strerror(errno) ); I_OutputMsg("%s\n", text); - - SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, - "Startup error", - text, NULL); + I_ShowSimpleErrorBox("Startup error", text); I_ShutdownConsole(); exit(-1); @@ -1773,18 +1929,29 @@ static void I_Fork(void) I_RegisterChildSignals(); break; default: + // ignore those, those are handled by child process + // otherwise parent might exit before it + // and the below stuff wont run and your terminal will be left in an awkward state +#ifdef SIGINT + signal(SIGINT, SIG_IGN); +#endif +#ifdef SIGBREAK + signal(SIGBREAK, SIG_IGN); +#endif +#ifdef SIGTERM + signal(SIGTERM, SIG_IGN); +#endif +#ifdef LOGMESSAGES if (logstream) fclose(logstream);/* the child has this */ - +#endif c = wait(&status); - #ifdef LOGMESSAGES /* By the way, exit closes files. */ logstream = fopen(logfilename, "at"); #else logstream = 0; #endif - if (c == -1) { kill(child, SIGKILL); @@ -1820,6 +1987,7 @@ INT32 I_StartupSystem(void) SDL_version SDLlinked; SDL_VERSION(&SDLcompiled) SDL_GetVersion(&SDLlinked); + I_StartupConsole(); #ifdef NEWSIGNALHANDLER // This is useful when debugging. It lets GDB attach to @@ -1851,18 +2019,20 @@ INT32 I_StartupSystem(void) return 0; } +boolean is_quitting = false; + // // I_Quit // FUNCNORETURN void ATTRNORETURN I_Quit(void) { - static SDL_bool quiting = SDL_FALSE; - /* prevent recursive I_Quit() */ - if (quiting) goto death; + if (is_quitting) + abort(); + + is_quitting = true; SDL_ShowCursor(SDL_TRUE); - quiting = SDL_FALSE; - I_ShutdownConsole(); + M_SaveConfig(NULL); //save game config, cvars.. D_SaveBan(); // save the ban list G_SaveGameData(false); // Tails 12-08-2002 @@ -1880,16 +2050,17 @@ FUNCNORETURN void ATTRNORETURN I_Quit(void) I_ShutdownInput(); I_ShutdownSystem(); SDL_Quit(); + /* if option -noendtxt is set, don't print the text */ if (!M_CheckParm("-noendtxt") && W_CheckNumForName("ENDOOM") != LUMPERROR) { printf("\r"); ShowEndTxt(); } + if (myargmalloc) free(myargv); // Deallocate allocated memory -death: - W_Shutdown(); + exit(0); } @@ -1908,6 +2079,7 @@ FUNCIERROR void ATTRNORETURN I_Error(const char *error, ...) { va_list argptr; char buffer[8192]; + const char *sigttl = ""; #ifdef HAVE_THREADS if (std::this_thread::get_id() != g_main_thread_id) @@ -1942,16 +2114,12 @@ FUNCIERROR void ATTRNORETURN I_Error(const char *error, ...) if (errorcount > 20) { va_start(argptr, error); - vsnprintf(buffer, 8192, error, argptr); + vsnprintf(buffer, sizeof(buffer), error, argptr); va_end(argptr); - // Implement message box with SDL_ShowSimpleMessageBox, - // which should fail gracefully if it can't put a message box up - // on the target system - SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, - "SRB2Kart " VERSIONSTRING " Recursive Error", - buffer, NULL); - W_Shutdown(); + sigttl = "SRB2Kart " VERSIONSTRING " Recursive Error"; + I_ShowSimpleErrorBox(sigttl, buffer); + exit(-1); // recursive errors detected } } @@ -1960,7 +2128,7 @@ FUNCIERROR void ATTRNORETURN I_Error(const char *error, ...) // Display error message in the console before we start shutting it down va_start(argptr, error); - vsnprintf(buffer, 8192, error, argptr); + vsnprintf(buffer, sizeof(buffer), error, argptr); va_end(argptr); I_OutputMsg("\nI_Error(): %s\n", buffer); @@ -1970,8 +2138,6 @@ FUNCIERROR void ATTRNORETURN I_Error(const char *error, ...) // --- - I_ShutdownConsole(); - M_SaveConfig(NULL); // save game config, cvars.. D_SaveBan(); // save the ban list G_SaveGameData(false); // Tails 12-08-2002 @@ -1989,17 +2155,9 @@ FUNCIERROR void ATTRNORETURN I_Error(const char *error, ...) I_ShutdownSystem(); SDL_Quit(); - // Implement message box with SDL_ShowSimpleMessageBox, - // which should fail gracefully if it can't put a message box up - // on the target system - SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "SRB2Kart " VERSIONSTRING " Error", buffer, NULL); - // Note that SDL_ShowSimpleMessageBox does *not* require SDL to be - // initialized at the time, so calling it after SDL_Quit() is - // perfectly okay! In addition, we do this on purpose so the - // fullscreen window is closed before displaying the error message - // in case the fullscreen window blocks it for some absurd reason. - - W_Shutdown(); + sigttl = "SRB2Kart " VERSIONSTRING " Error"; + //I_ShowSimpleErrorBox(sigttl, buffer); + I_ShowErrorBox(sigttl, buffer); #if defined (PARANOIA) && defined (__CYGWIN__) *(INT32 *)2 = 4; //Alam: Debug! @@ -2113,6 +2271,7 @@ void I_ShutdownSystem(void) for (c = MAX_QUIT_FUNCS-1; c >= 0; c--) if (quit_funcs[c]) (*quit_funcs[c])(); + #ifdef LOGMESSAGES if (logstream) { @@ -2124,7 +2283,6 @@ void I_ShutdownSystem(void) logstream = NULL; } #endif - } void I_GetDiskFreeSpace(INT64 *freespace) @@ -2198,9 +2356,9 @@ char *I_GetUserName(void) } } } - strncpy(username, p, MAXPLAYERNAME); - } + snprintf(username, sizeof(username), "%s", p); + } if (!fastcmp(username, "")) return username; @@ -2223,6 +2381,24 @@ INT32 I_mkdir(const char *dirname, INT32 unixright) #endif } +INT32 I_ChDir(const char *path) +{ +#ifdef _WIN32 + return (SetCurrentDirectoryA(path) ? 0 : -1); +#else + return chdir(path); +#endif +} + +char *I_GetCwd(char *buf, size_t size) +{ +#ifdef _WIN32 + return (GetCurrentDirectoryA((DWORD)size, buf) ? buf : NULL); +#else + return getcwd(buf, size); +#endif +} + char *I_GetEnv(const char *name) { #ifdef NEED_SDL_GETENV @@ -2244,13 +2420,15 @@ INT32 I_PutEnv(char *variable) INT32 I_ClipboardCopy(const char *data, size_t size) { char storage[256]; + if (size > 255) size = 255; - memcpy(storage, data, size); - storage[size] = 0; + + snprintf(storage, sizeof(storage), "%.*s", (int)size, data); if (SDL_SetClipboardText(storage)) return 0; + return -1; } @@ -2263,7 +2441,7 @@ const char *I_ClipboardPaste(void) return NULL; clipboard_contents = SDL_GetClipboardText(); - strlcpy(clipboard_modified, clipboard_contents, 256); + snprintf(clipboard_modified, sizeof(clipboard_modified), "%s", clipboard_contents); SDL_free(clipboard_contents); while (*i) @@ -2279,6 +2457,7 @@ const char *I_ClipboardPaste(void) *i = '?'; // Nonprintable chars become question marks ++i; } + return (const char *)&clipboard_modified; } @@ -2292,34 +2471,34 @@ const char *I_ClipboardPaste(void) */ static boolean isWadPathOk(const char *path) { - char *wad3path = static_cast(malloc(256)); + char wad3path[256]; - if (!wad3path) - return false; - - sprintf(wad3path, pandf, path, WADKEYWORD1); + snprintf(wad3path, sizeof(wad3path), pandf, path, WADKEYWORD); if (FIL_ReadFileOK(wad3path)) { - free(wad3path); return true; } - free(wad3path); return false; } -static void pathonly(char *s) +static void pathonly(char *s, size_t size) { size_t j; - for (j = strlen(s); j != (size_t)-1; j--) + for (j = strnlen(s, size); j != (size_t)-1; j--) + { if ((s[j] == '\\') || (s[j] == ':') || (s[j] == '/')) { - if (s[j] == ':') s[j+1] = 0; - else s[j] = 0; + if (s[j] == ':') + s[j+1] = 0; + else + s[j] = 0; + return; } + } } /** \brief search for srb2.srb in the given path @@ -2332,14 +2511,15 @@ static void pathonly(char *s) */ static const char *searchWad(const char *searchDir) { - static char tempsw[255] = ""; + static char tempsw[256] = ""; filestatus_t fstemp; - strcpy(tempsw, WADKEYWORD1); + snprintf(tempsw, sizeof(tempsw), "%s", WADKEYWORD); fstemp = filesearch(tempsw, searchDir, NULL, true, 20); + if (fstemp == FS_FOUND) { - pathonly(tempsw); + pathonly(tempsw, sizeof(tempsw)); return tempsw; } @@ -2377,7 +2557,7 @@ static const char *locateWad(void) #ifndef NOCWD // examine current dir - strcpy(returnWadPath, "."); + snprintf(returnWadPath, sizeof(returnWadPath), "%s", "."); I_OutputMsg(",%s", returnWadPath); if (isWadPathOk(returnWadPath)) return NULL; @@ -2389,7 +2569,7 @@ static const char *locateWad(void) // examine user jart directory if ((envstr = I_GetEnv("HOME")) != NULL) { - sprintf(returnWadPath, "%s" PATHSEP DEFAULTDIR, envstr); + snprintf(returnWadPath, sizeof(returnWadPath), "%s" PATHSEP DEFAULTDIR, envstr); CHECKWADPATH(returnWadPath); } #endif @@ -2403,7 +2583,7 @@ static const char *locateWad(void) // examine default dirs for (i = 0; wadDefaultPaths[i]; i++) { - strcpy(returnWadPath, wadDefaultPaths[i]); + snprintf(returnWadPath, sizeof(returnWadPath), "%s", wadDefaultPaths[i]); CHECKWADPATH(returnWadPath); } @@ -2418,7 +2598,7 @@ static const char *locateWad(void) return NULL; } -const char *I_LocateWad(void) +extern "C" const char *I_LocateWad(void) { const char *waddir = NULL; @@ -2431,12 +2611,11 @@ const char *I_LocateWad(void) // change to the directory where we found srb2.srb #if defined (_WIN32) waddir = _fullpath(NULL, waddir, MAX_PATH); - SetCurrentDirectoryA(waddir); #else waddir = realpath(waddir, NULL); - if (waddir == NULL || chdir(waddir) == -1) - I_OutputMsg("Couldn't change working directory\n"); #endif + if (waddir == NULL || I_ChDir(waddir) == -1) + I_OutputMsg("Couldn't change working directory\n"); } return waddir; @@ -2496,13 +2675,13 @@ size_t I_GetFreeMem(size_t *total) *total = 32 << 20; return 32 << 20; #elif defined (_WIN32) - MEMORYSTATUS info; + MEMORYSTATUSEX info; - info.dwLength = sizeof (MEMORYSTATUS); - GlobalMemoryStatus( &info ); + info.dwLength = sizeof (MEMORYSTATUSEX); + GlobalMemoryStatusEx( &info ); if (total) - *total = (size_t)info.dwTotalPhys; - return (size_t)info.dwAvailPhys; + *total = (size_t)info.ullTotalPhys; + return (size_t)info.ullAvailPhys; #elif defined (__OS2__) UINT32 pr_arena; @@ -2535,7 +2714,7 @@ size_t I_GetFreeMem(size_t *total) { // Error if (total) - *total = 0L; + *total = 0; return 0; } @@ -2544,12 +2723,12 @@ size_t I_GetFreeMem(size_t *total) { // Error if (total) - *total = 0L; + *total = 0; return 0; } memTag += sizeof (MEMTOTAL); - totalKBytes = (size_t)atoi(memTag); + totalKBytes = strtoul(memTag, NULL, 10); if ((memTag = strstr(buf, MEMAVAILABLE)) == NULL) { @@ -2563,7 +2742,7 @@ size_t I_GetFreeMem(size_t *total) { // Error if (total) - *total = 0L; + *total = 0; return 0; } freeKBytes = MemAvailable; @@ -2571,12 +2750,40 @@ size_t I_GetFreeMem(size_t *total) else { memTag += sizeof (MEMAVAILABLE); - freeKBytes = atoi(memTag); + freeKBytes = strtoul(memTag, NULL, 10); } if (total) *total = totalKBytes << 10; return freeKBytes << 10; +#elif defined(__APPLE__) + /* macOS */ + mach_port_t host = mach_host_self(); + kern_return_t kr; + mach_msg_type_number_t count; + vm_size_t v_page_size; + struct vm_statistics64 vm_stats; + uint64_t total_mem, free_mem; + size_t size; + + size = sizeof(total_mem); + if (sysctlbyname("hw.memsize", &total_mem, &size, NULL, 0) < 0) + total_mem = 0; + + kr = host_page_size(host, &v_page_size); + if (kr != KERN_SUCCESS) + v_page_size = 4096; + + count = HOST_VM_INFO64_COUNT; + kr = host_statistics64(host, HOST_VM_INFO64, (host_info64_t)&vm_stats, &count); + if (kr == KERN_SUCCESS) + free_mem = (uint64_t)(vm_stats.free_count + vm_stats.inactive_count) * v_page_size; + else + free_mem = 0; + + if (total) + *total = (size_t)total_mem; + return (size_t)free_mem; #else // Guess 48 MB. if (total) diff --git a/src/sdl/i_threads.c b/src/sdl/i_threads.c index 078f4e0f4..26d3bbefe 100644 --- a/src/sdl/i_threads.c +++ b/src/sdl/i_threads.c @@ -9,6 +9,8 @@ /// \file i_threads.c /// \brief Multithreading abstraction +#ifdef HAVE_THREADS + #include "../doomdef.h" #include "../i_threads.h" @@ -354,3 +356,5 @@ I_wake_all_cond ( if (SDL_CondBroadcast(cond) == -1) abort(); } + +#endif // HAVE_THREADS diff --git a/src/sdl/i_ttf.c b/src/sdl/i_ttf.c index f2cd497ee..fcba5ec46 100644 --- a/src/sdl/i_ttf.c +++ b/src/sdl/i_ttf.c @@ -183,13 +183,17 @@ void I_TTFDrawText(TTF_Font *font, TextQuality quality, INT32 fgR, INT32 fgG, IN TTFRect.x = TTFRectCheck.x; TTFRect.y = TTFRectCheck.y; } + // Copy the character to the text buffer. - sprintf(textbuffer, "%s%c", textbuffer, c); + snprintf(textbuffer, sizeof(textbuffer), "%s%c", textbuffer, c); + // Hack to allow TTF_SizeText to work properly. - sprintf(linebuffer, "%c", c); + snprintf(linebuffer, sizeof(linebuffer), "%c", c); + // If we have reached the end of the screen, move to the next available line. TTF_SizeText(currentfont, linebuffer, &w, &h); TTFRectCheck.x += w; + if (TTFRectCheck.x >= res.width) { // Render cached text to the SDL surface. @@ -204,8 +208,10 @@ void I_TTFDrawText(TTF_Font *font, TextQuality quality, INT32 fgR, INT32 fgG, IN TTFRect.y = TTFRectCheck.y; } } + // Add 1 to the pointer reference for the character to process. textmsg++; + // Copy contents of the now-old buffer to somewhere else, so it can be referenced in next loop. prevc = c; } diff --git a/src/sdl/i_video.c b/src/sdl/i_video.c index c2d87e3f1..ae9b61446 100644 --- a/src/sdl/i_video.c +++ b/src/sdl/i_video.c @@ -108,7 +108,6 @@ static void KeyboardLayout_OnChange(void) { if (cv_keyboardlayout.value != 2) SDL_StopTextInput(); - HU_Shiftform(); } static CV_PossibleValue_t keyboardlayout_cons_t[] = {{1,"Default US"}, {2, "Native"}, {3, "AZERTY"}, {0, NULL}}; @@ -155,9 +154,12 @@ static SDL_bool usesdl2soft = SDL_FALSE; static SDL_bool borderlesswindow = SDL_FALSE; // SDL2 vars -SDL_Window *window = NULL; -SDL_Renderer *renderer = NULL; +static SDL_Window *window = NULL; +static SDL_Renderer *renderer = NULL; static SDL_Texture *texture = NULL; +#ifdef HWRENDER +static SDL_GLContext sdlglcontext = NULL; +#endif static SDL_bool havefocus = SDL_TRUE; static const char *fallback_resolution_name = "Fallback"; @@ -452,7 +454,7 @@ static INT32 SDLJoyAxis(const Sint16 axis, evtype_t which) return 0; } - if (Joystick[pid].bGamepadStyle) + if (DigitalGamepadStyle(pid)) { // gamepad control type, on or off, live or die if (raxis < -(JOYAXISRANGE/2)) @@ -464,7 +466,7 @@ static INT32 SDLJoyAxis(const Sint16 axis, evtype_t which) } else { - raxis = JoyInfo[pid].scale!=1?((raxis/JoyInfo[pid].scale)*JoyInfo[pid].scale):raxis; + raxis = JoyInfo[pid].scale != 1 ? ((raxis/JoyInfo[pid].scale)*JoyInfo[pid].scale) : raxis; #ifdef SDL_JDEADZONE if (-SDL_JDEADZONE <= raxis && raxis <= SDL_JDEADZONE) @@ -781,7 +783,11 @@ static void Impl_HandleControllerAxisEvent(SDL_ControllerAxisEvent evt) // Determine the Joystick IDs for each current open joystick for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) { +#if (SDL_VERSION_ATLEAST(2,32,4)) if (evt.which == JoyInfo[i].id) +#else + if (evt.which == SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(JoyInfo[i].dev))) +#endif { event.type = ev_joystick + i; break; @@ -841,7 +847,11 @@ static void Impl_HandleControllerHatEvent(SDL_ControllerButtonEvent evt, Uint32 // Determine the Joystick IDs for each current open joystick for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) { +#if (SDL_VERSION_ATLEAST(2,32,4)) if (evt.which == JoyInfo[i].id) +#else + if (evt.which == SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(JoyInfo[i].dev))) +#endif { event.data1 = hat_buttons_base[i]; break; @@ -903,7 +913,11 @@ static void Impl_HandleControllerButtonEvent(SDL_ControllerButtonEvent evt, Uint // Determine the Joystick IDs for each current open joystick for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) { +#if (SDL_VERSION_ATLEAST(2,32,4)) if (evt.which == JoyInfo[i].id) +#else + if (evt.which == SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(JoyInfo[i].dev))) +#endif { event.data1 = buttons_base[i]; break; @@ -1149,8 +1163,8 @@ void I_GetEvent(void) SDL_GetWindowSize(window, &wwidth, &wheight); event.type = ev_mouse; event.data1 = 0; - event.data2 = (INT32)lround(mousemovex * ((float)wwidth / (float)realwidth)); - event.data3 = (INT32)lround(mousemovey * ((float)wheight / (float)realheight)); + event.data2 = (INT32)lroundf(mousemovex * ((float)wwidth / (float)realwidth)); + event.data3 = (INT32)lroundf(mousemovey * ((float)wheight / (float)realheight)); D_PostEvent(&event); } @@ -1426,7 +1440,7 @@ void I_FinishUpdate(void) #ifdef HWRENDER if (rendermode == render_opengl) { - OglSdlFinishUpdate(cv_vidwait.value); + OglSdlFinishUpdate(window); return; } #endif @@ -1524,9 +1538,9 @@ const char *VID_GetModeName(INT32 modeNum) if (modeNum > MAXWINMODES) return NULL; - sprintf(&vidModeName[modeNum][0], "%dx%d", - windowedModes[modeNum][0], - windowedModes[modeNum][1]); + snprintf(&vidModeName[modeNum][0], sizeof(vidModeName[modeNum]), "%dx%d", + windowedModes[modeNum][0], + windowedModes[modeNum][1]); return &vidModeName[modeNum][0]; } @@ -1802,15 +1816,18 @@ void I_StartupGraphics(void) framebuffer = SDL_TRUE; } + // Choose Software renderer if (M_CheckParm("-software")) rendermode = render_soft; #ifdef HWRENDER + // Choose OpenGL renderer else if (M_CheckParm("-opengl")) rendermode = render_opengl; msaa = 0; boolean msaa_set = false; a2c = false; boolean a2c_set = false; + // MSAA antialiasing if (M_CheckParm("-msaa") && M_IsNextParm()) { const char* str = M_GetNextParm(); @@ -1841,6 +1858,9 @@ void I_StartupGraphics(void) { word = strtok(line, " \n"); + if (!word) + continue; + if (rendermode == render_none) { if (fasticmp(word, "software")) @@ -2012,7 +2032,8 @@ void I_ShutdownGraphics(void) SDL_DestroyWindow(window); window = NULL; - SDL_QuitSubSystem(SDL_INIT_VIDEO); + if (SDL_WasInit(SDL_INIT_VIDEO) == SDL_INIT_VIDEO) + SDL_QuitSubSystem(SDL_INIT_VIDEO); framebuffer = SDL_FALSE; } @@ -2028,17 +2049,17 @@ UINT32 I_GetRefreshRate(void) static void Impl_SetVsync(void) { -#if SDL_VERSION_ATLEAST(2,0,18) - if (renderer) - SDL_RenderSetVSync(renderer, cv_vidwait.value); -#endif #ifdef HWRENDER - if (!renderer && rendermode == render_opengl && - sdlglcontext != NULL && SDL_GL_GetCurrentContext() == sdlglcontext) + if (rendermode == render_opengl && + sdlglcontext != NULL && SDL_GL_GetCurrentContext() == sdlglcontext) { SDL_GL_SetSwapInterval(cv_vidwait.value ? 1 : 0); } #endif +#if SDL_VERSION_ATLEAST(2,0,18) + if (renderer) + SDL_RenderSetVSync(renderer, cv_vidwait.value); +#endif } void I_SetBorderlessWindow(void) diff --git a/src/sdl/macosx/Srb2mac.icns b/src/sdl/macosx/Srb2mac.icns index 890c268f7..a2067f54d 100644 Binary files a/src/sdl/macosx/Srb2mac.icns and b/src/sdl/macosx/Srb2mac.icns differ diff --git a/src/sdl/macosx/mac_alert.c b/src/sdl/macosx/mac_alert.c deleted file mode 100644 index 2a139041a..000000000 --- a/src/sdl/macosx/mac_alert.c +++ /dev/null @@ -1,64 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// Copyright (C) 1993-1996 by id Software, Inc. -// Portions Copyright (C) 1998-2000 by DooM Legacy Team. -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -//----------------------------------------------------------------------------- -/// \file -/// \brief Graphical Alerts for MacOSX -/// -/// Shows alerts, since we can't just print these to the screen when -/// launched graphically on a mac. - -#ifdef __APPLE_CC__ - -#include "mac_alert.h" -#include - -#define CFSTRINGIFY(x) CFStringCreateWithCString(NULL, x, kCFStringEncodingASCII) - -int MacShowAlert(const char *title, const char *message, const char *button1, const char *button2, const char *button3) -{ - CFOptionFlags results; - - CFStringRef cf_title = CFSTRINGIFY(title); - CFStringRef cf_message = CFSTRINGIFY(message); - CFStringRef cf_button1 = NULL; - CFStringRef cf_button2 = NULL; - CFStringRef cf_button3 = NULL; - - if (button1 != NULL) - cf_button1 = CFSTRINGIFY(button1); - if (button2 != NULL) - cf_button2 = CFSTRINGIFY(button2); - if (button3 != NULL) - cf_button3 = CFSTRINGIFY(button3); - - CFOptionFlags alert_flags = kCFUserNotificationStopAlertLevel | kCFUserNotificationNoDefaultButtonFlag; - - CFUserNotificationDisplayAlert(0, alert_flags, NULL, NULL, NULL, cf_title, cf_message, - cf_button1, cf_button2, cf_button3, &results); - - if (cf_button1 != NULL) - CFRelease(cf_button1); - if (cf_button2 != NULL) - CFRelease(cf_button2); - if (cf_button3 != NULL) - CFRelease(cf_button3); - CFRelease(cf_message); - CFRelease(cf_title); - - return (int)results; -} - -#endif diff --git a/src/sdl/macosx/mac_alert.h b/src/sdl/macosx/mac_alert.h deleted file mode 100644 index 82a28d120..000000000 --- a/src/sdl/macosx/mac_alert.h +++ /dev/null @@ -1,27 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// Copyright (C) 1993-1996 by id Software, Inc. -// Portions Copyright (C) 1998-2000 by DooM Legacy Team. -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -//----------------------------------------------------------------------------- -/// \file -/// \brief Graphical Alerts for MacOSX -/// -/// Shows alerts, since we can't just print these to the screen when -/// launched graphically on a mac. - -#ifdef __APPLE_CC__ - -extern int MacShowAlert(const char *title, const char *message, const char *button1, const char *button2, const char *button3); - -#endif diff --git a/src/sdl/macosx/mac_resources.h b/src/sdl/macosx/mac_resources.h index 727ac9f6b..d63232dac 100644 --- a/src/sdl/macosx/mac_resources.h +++ b/src/sdl/macosx/mac_resources.h @@ -1,5 +1,11 @@ #ifndef __MAC_RESOURCES_H__ #define __MAC_RESOURCES_H__ +#ifdef __cplusplus +extern "C" { +#endif void OSX_GetResourcesPath(char * buffer); -#endif \ No newline at end of file +#ifdef __cplusplus +} +#endif +#endif diff --git a/src/sdl/mixer_sound.c b/src/sdl/mixer_sound.c index 529b47399..420326043 100644 --- a/src/sdl/mixer_sound.c +++ b/src/sdl/mixer_sound.c @@ -216,8 +216,13 @@ void I_StartupSound(void) SDLmixlinked->major, SDLmixlinked->minor, SDLmixlinked->patch); #ifdef HAVE_OPENMPT - I_OutputMsg("libopenmpt version: %s\n", openmpt_get_string("library_version")); - I_OutputMsg("libopenmpt build date: %s\n", openmpt_get_string("build")); + const char *openmptstr; + openmptstr = openmpt_get_string("library_version"); + I_OutputMsg("libopenmpt version: %s\n", openmptstr); + openmpt_free_string(openmptstr); + openmptstr = openmpt_get_string("build"); + I_OutputMsg("libopenmpt build date: %s\n", openmptstr); + openmpt_free_string(openmptstr); #endif sound_started = true; @@ -237,7 +242,8 @@ void I_ShutdownSound(void) Mix_Quit(); #endif - SDL_QuitSubSystem(SDL_INIT_AUDIO); + if (SDL_WasInit(SDL_INIT_AUDIO) == SDL_INIT_AUDIO) + SDL_QuitSubSystem(SDL_INIT_AUDIO); #ifdef HAVE_LIBGME if (gme) @@ -461,7 +467,7 @@ void *I_GetSfx(sfxinfo_t *sfx) gme_track_info(emu, &info, 0); len = (info->play_length * 441 / 10) << 2; - mem = Z_Malloc(len, PU_SOUND, 0); + mem = Z_Malloc(len, PU_SOUND, NULL); gme_play(emu, len >> 1, mem); gme_free_info(info); @@ -499,7 +505,7 @@ void *I_GetSfx(sfxinfo_t *sfx) gme_track_info(emu, &info, 0); len = (info->play_length * 441 / 10) << 2; - mem = Z_Malloc(len, PU_SOUND, 0); + mem = Z_Malloc(len, PU_SOUND, NULL); gme_play(emu, len >> 1, mem); gme_free_info(info); @@ -862,7 +868,7 @@ boolean I_SetSongSpeed(float speed) { // deprecated in 0.5.0 char modspd[13]; - sprintf(modspd, "%g", speed); + snprintf(modspd, sizeof(modspd), "%g", speed); openmpt_module_ctl_set(openmpt_mhandle, "play.tempo_factor", modspd); } #else @@ -939,7 +945,7 @@ UINT32 I_GetSongLength(void) boolean I_SetSongLoopPoint(UINT32 looppoint) { - if (!music|| !is_looping) + if (!music || !is_looping) return false; const musictype_t mustype = I_SongType(); @@ -952,7 +958,7 @@ boolean I_SetSongLoopPoint(UINT32 looppoint) if (length > 0) looppoint %= length; - loop_point = max((float)(looppoint / 1000.0L), 0); + loop_point = max((float)(looppoint / 1000.0L), 0.0f); return true; } @@ -1107,7 +1113,7 @@ UINT32 I_GetSongPosition(void) void I_UpdateSongLagThreshold(void) { - stutter_threshold = cv_music_resync_powerups_only.value ? 0 : (cv_music_resync_threshold.value/1000.0*(4*44100)); + stutter_threshold = (UINT32)(cv_music_resync_powerups_only.value ? 0 : (cv_music_resync_threshold.value/1000.0*(4*44100))); } /// ------------------------ diff --git a/src/sdl/ogl_sdl.c b/src/sdl/ogl_sdl.c index 319acab4b..f5e7f2aea 100644 --- a/src/sdl/ogl_sdl.c +++ b/src/sdl/ogl_sdl.c @@ -63,25 +63,15 @@ PFNglGetString pglGetString; #endif #ifdef USE_FBO_OGL - -#if defined (__unix__) -static boolean xwaylandcrap = false; -#endif - boolean UseScreenFBO(void) { - return ((supportFBO && cv_glframebuffer.value && downsample) -#if defined (__unix__) - || (supportFBO && xwaylandcrap) -#endif - ); + return (supportFBO && cv_glframebuffer.value && downsample); } #endif /** \brief SDL video display surface */ INT32 oglflags = 0; -SDL_GLContext sdlglcontext = NULL; void *GetGLFunc(const char *proc) { @@ -147,13 +137,13 @@ boolean OglSdlSurface(INT32 w, INT32 h) GL_DBG_Printf("OpenGL %s\n", gl_version); GL_DBG_Printf("GPU: %s\n", gl_renderer); - GL_DBG_Printf("Extensions:"); + GL_DBG_Printf("Extensions: \n"); { // Need to do it with strtok for same reason its done like that in gr_glinfo command char *copy = strdup((const char*)gl_extensions); - char *ext = strtok(copy, " "); + char *ext; if (copy == NULL) { @@ -161,9 +151,11 @@ boolean OglSdlSurface(INT32 w, INT32 h) } else { + ext = strtok(copy, " "); + do { - GL_DBG_Printf(" %s", ext); + GL_DBG_Printf(" - %s\n", ext); } while ((ext = strtok(NULL, " ")) != NULL); free(copy); @@ -201,17 +193,6 @@ boolean OglSdlSurface(INT32 w, INT32 h) supportNPO2tex = true; glanisotropicmode_cons_t[1].value = maximumAnisotropy; - -#if defined (__unix__) -#ifdef USE_FBO_OGL - // TODO: delet this since nvidia fixed their shit on 575 - char videodriver[4] = {'S','D','L',0}; - if (supportFBO && strstr((const char*)gl_renderer, "NVIDIA") - && (*strncpy(videodriver, SDL_GetCurrentVideoDriver(), sizeof(videodriver)-1) != '\0') - && (strncasecmp("x11", videodriver, 4) == 0)) - xwaylandcrap = true; -#endif -#endif } SDL_GL_SetSwapInterval(cv_vidwait.value ? 1 : 0); @@ -241,22 +222,14 @@ boolean OglSdlSurface(INT32 w, INT32 h) \return void */ -void OglSdlFinishUpdate(boolean waitvbl) +void OglSdlFinishUpdate(SDL_Window *window) { - static boolean oldwaitvbl = false; int sdlw, sdlh; #ifdef USE_FBO_OGL const boolean usefbo = UseScreenFBO(); #endif - if (oldwaitvbl != waitvbl) - { - SDL_GL_SetSwapInterval(waitvbl ? 1 : 0); - } - - oldwaitvbl = waitvbl; - SDL_GetWindowSize(window, &sdlw, &sdlh); HWR_MakeScreenFinalTexture(); @@ -267,7 +240,18 @@ void OglSdlFinishUpdate(boolean waitvbl) } #endif - HWR_DrawScreenFinalTexture(sdlw, sdlh, HWR_ShouldUsePaletteRendering()); + if (HWR_ShouldUsePaletteRendering()) + { + // Final postprocess step of palette rendering, after everything else has been drawn. + GL_SetShader(HWR_GetShaderFromTarget(SHADER_PALETTE_POSTPROCESS)); + GL_EnableShader(); + HWR_DrawScreenFinalTexture(sdlw, sdlh); + GL_UnSetShader(); + } + else + { + HWR_DrawScreenFinalTexture(sdlw, sdlh); + } #ifdef USE_FBO_OGL if (usefbo) @@ -288,14 +272,7 @@ void OglSdlFinishUpdate(boolean waitvbl) #else if (!I_CheckNativeRes() || WipeInAction) #endif - HWR_DrawScreenFinalTexture(realwidth, realheight, false); - -#if defined (__unix__) -#ifdef USE_FBO_OGL - if (loaded_config) - xwaylandcrap = false; -#endif -#endif + HWR_DrawScreenFinalTexture(realwidth, realheight); } #endif //HWRENDER diff --git a/src/sdl/ogl_sdl.h b/src/sdl/ogl_sdl.h index 6d614cd22..9bdebc715 100644 --- a/src/sdl/ogl_sdl.h +++ b/src/sdl/ogl_sdl.h @@ -20,11 +20,9 @@ boolean OglSdlSurface(INT32 w, INT32 h); -void OglSdlFinishUpdate(boolean vidwait); +void OglSdlFinishUpdate(SDL_Window *window); boolean VID_LoadOGLAPI(void); -extern SDL_Renderer *renderer; -extern SDL_GLContext sdlglcontext; extern Uint16 realwidth; extern Uint16 realheight; diff --git a/src/sdl/sdlmain.h b/src/sdl/sdlmain.h index c711d68d7..b904eefc6 100644 --- a/src/sdl/sdlmain.h +++ b/src/sdl/sdlmain.h @@ -23,8 +23,7 @@ extern "C" { #endif -extern SDL_bool consolevent; -extern SDL_bool framebuffer; +#include "SDL_version.h" #include "../m_fixed.h" @@ -42,20 +41,26 @@ typedef struct SDLJoyInfo_s { /// Controller handle SDL_GameController *dev; +#if (SDL_VERSION_ATLEAST(2,32,4)) /// Controller index INT32 id; +#endif /// number of old joystick int oldjoy; /// number of axies - int axises; + //int axises; /// scale of axises INT32 scale; /// number of buttons - int buttons; + //int buttons; /// number of hats - int hats; + //int hats; /// number of balls - int balls; + //int balls; + /// + boolean hasled; + /// + boolean hasrumble; } SDLJoyInfo_t; /** \brief SDL info about controller 1 @@ -67,21 +72,6 @@ extern SDLJoyInfo_t JoyInfo[4]; //MAXSPLITSCREENPLAYERS #define SDL_JDEADZONE 153 #undef SDL_JDEADZONE -// So we can call this from i_video event loop -void I_ShutdownJoystick(UINT8 index); - -// Cheat to get the device index for a game controller handle -INT32 I_GetJoystickDeviceIndex(SDL_GameController *dev); - -// Quick thing to make SDL_JOYDEVICEADDED events less of an abomination -void I_UpdateJoystickDeviceIndex(UINT8 player); -void I_UpdateJoystickDeviceIndices(UINT8 excludePlayer); - -void I_GetConsoleEvents(void); - -// Needed for some WIN32 functions -extern SDL_Window *window; - #ifdef __cplusplus } // extern "C" #endif diff --git a/src/sounds.c b/src/sounds.c index dbd5478bd..26d4ead57 100644 --- a/src/sounds.c +++ b/src/sounds.c @@ -28,980 +28,972 @@ sfxinfo_t S_sfx[NUMSFX] = { - /***** Legacy doesn't use the PITCH variable, so now it is used for various flags. See soundflags_t. *****/ - // S_sfx[0] needs to be a dummy for odd reasons. (don't modify this comment) -// name, singularity, priority, pitch, data, length, skinsound, lumpnum - {"none" , false, 0, 0, NULL, 0, -1, LUMPERROR}, + // S_sfx[0] needs to be a dummy for odd reasons. (don't modify this comment) + // name, singularity, priority, pitch, data, length, skinsound, lumpnum + {"none" , false, 0, 0, NULL, 0, -1, LUMPERROR}, - // Skin Sounds - {"altdi1", false, 192, 16, NULL, 0, SKSPLDET1, LUMPERROR}, - {"altdi2", false, 192, 16, NULL, 0, SKSPLDET2, LUMPERROR}, - {"altdi3", false, 192, 16, NULL, 0, SKSPLDET3, LUMPERROR}, - {"altdi4", false, 192, 16, NULL, 0, SKSPLDET4, LUMPERROR}, - {"altow1", false, 192, 16, NULL, 0, SKSPLPAN1, LUMPERROR}, - {"altow2", false, 192, 16, NULL, 0, SKSPLPAN2, LUMPERROR}, - {"altow3", false, 192, 16, NULL, 0, SKSPLPAN3, LUMPERROR}, - {"altow4", false, 192, 16, NULL, 0, SKSPLPAN4, LUMPERROR}, - {"victr1", false, 64, 16, NULL, 0, SKSPLVCT1, LUMPERROR}, - {"victr2", false, 64, 16, NULL, 0, SKSPLVCT2, LUMPERROR}, - {"victr3", false, 64, 16, NULL, 0, SKSPLVCT3, LUMPERROR}, - {"victr4", false, 64, 16, NULL, 0, SKSPLVCT4, LUMPERROR}, - {"gasp" , false, 64, 0, NULL, 0, SKSGASP, LUMPERROR}, - {"jump" , false, 140, 0, NULL, 0, SKSJUMP, LUMPERROR}, - {"pudpud", false, 64, 0, NULL, 0, SKSPUDPUD, LUMPERROR}, - {"putput", false, 64, 0, NULL, 0, SKSPUTPUT, LUMPERROR}, // not as high a priority - {"spin" , false, 100, 0, NULL, 0, SKSSPIN, LUMPERROR}, - {"spndsh", false, 64, 1, NULL, 0, SKSSPNDSH, LUMPERROR}, - {"thok" , false, 96, 0, NULL, 0, SKSTHOK, LUMPERROR}, - {"zoom" , false, 120, 1, NULL, 0, SKSZOOM, LUMPERROR}, - {"skid", false, 64, 32, NULL, 0, SKSSKID, LUMPERROR}, + // Skin Sounds + {"altdi1", false, 192, 16, NULL, 0, SKSPLDET1, LUMPERROR}, + {"altdi2", false, 192, 16, NULL, 0, SKSPLDET2, LUMPERROR}, + {"altdi3", false, 192, 16, NULL, 0, SKSPLDET3, LUMPERROR}, + {"altdi4", false, 192, 16, NULL, 0, SKSPLDET4, LUMPERROR}, + {"altow1", false, 192, 16, NULL, 0, SKSPLPAN1, LUMPERROR}, + {"altow2", false, 192, 16, NULL, 0, SKSPLPAN2, LUMPERROR}, + {"altow3", false, 192, 16, NULL, 0, SKSPLPAN3, LUMPERROR}, + {"altow4", false, 192, 16, NULL, 0, SKSPLPAN4, LUMPERROR}, + {"victr1", false, 64, 16, NULL, 0, SKSPLVCT1, LUMPERROR}, + {"victr2", false, 64, 16, NULL, 0, SKSPLVCT2, LUMPERROR}, + {"victr3", false, 64, 16, NULL, 0, SKSPLVCT3, LUMPERROR}, + {"victr4", false, 64, 16, NULL, 0, SKSPLVCT4, LUMPERROR}, + {"gasp" , false, 64, 0, NULL, 0, SKSGASP, LUMPERROR}, + {"jump" , false, 140, 0, NULL, 0, SKSJUMP, LUMPERROR}, + {"pudpud", false, 64, 0, NULL, 0, SKSPUDPUD, LUMPERROR}, + {"putput", false, 64, 0, NULL, 0, SKSPUTPUT, LUMPERROR}, // not as high a priority + {"spin" , false, 100, 0, NULL, 0, SKSSPIN, LUMPERROR}, + {"spndsh", false, 64, 1, NULL, 0, SKSSPNDSH, LUMPERROR}, + {"thok" , false, 96, 0, NULL, 0, SKSTHOK, LUMPERROR}, + {"zoom" , false, 120, 1, NULL, 0, SKSZOOM, LUMPERROR}, + {"skid", false, 64, 32, NULL, 0, SKSSKID, LUMPERROR}, - // Ambience/background objects/etc - {"ambint", true, 32, 0, NULL, 0, -1, LUMPERROR}, + // Ambience/background objects/etc + {"ambint", true, 32, 0, NULL, 0, -1, LUMPERROR}, - {"alarm", false, 32, 0, NULL, 0, -1, LUMPERROR}, - {"buzz1", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"buzz2", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"buzz3", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"buzz4", false, 8, 0, NULL, 0, -1, LUMPERROR}, - {"crumbl", true, 127, 0, NULL, 0, -1, LUMPERROR}, // Platform Crumble Tails 03-16-2001 - {"fire", false, 8, 32, NULL, 0, -1, LUMPERROR}, - {"grind", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"laser", true, 16, 2, NULL, 0, -1, LUMPERROR}, - {"mswing", false, 16, 0, NULL, 0, -1, LUMPERROR}, - {"pstart", false, 100, 0, NULL, 0, -1, LUMPERROR}, - {"pstop", false, 100, 0, NULL, 0, -1, LUMPERROR}, - {"steam1", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Tails 06-19-2001 - {"steam2", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Tails 06-19-2001 - {"wbreak", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"alarm", false, 32, 0, NULL, 0, -1, LUMPERROR}, + {"buzz1", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"buzz2", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"buzz3", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"buzz4", false, 8, 0, NULL, 0, -1, LUMPERROR}, + {"crumbl", true, 127, 0, NULL, 0, -1, LUMPERROR}, // Platform Crumble Tails 03-16-2001 + {"fire", false, 8, 32, NULL, 0, -1, LUMPERROR}, + {"grind", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"laser", true, 16, 2, NULL, 0, -1, LUMPERROR}, + {"mswing", false, 16, 0, NULL, 0, -1, LUMPERROR}, + {"pstart", false, 100, 0, NULL, 0, -1, LUMPERROR}, + {"pstop", false, 100, 0, NULL, 0, -1, LUMPERROR}, + {"steam1", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Tails 06-19-2001 + {"steam2", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Tails 06-19-2001 + {"wbreak", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"rainin", true, 24, 4, NULL, 0, -1, LUMPERROR}, - {"litng1", false, 16, 2, NULL, 0, -1, LUMPERROR}, - {"litng2", false, 16, 2, NULL, 0, -1, LUMPERROR}, - {"litng3", false, 16, 2, NULL, 0, -1, LUMPERROR}, - {"litng4", false, 16, 2, NULL, 0, -1, LUMPERROR}, - {"athun1", false, 16, 2, NULL, 0, -1, LUMPERROR}, - {"athun2", false, 16, 2, NULL, 0, -1, LUMPERROR}, + {"rainin", true, 24, 4, NULL, 0, -1, LUMPERROR}, + {"litng1", false, 16, 2, NULL, 0, -1, LUMPERROR}, + {"litng2", false, 16, 2, NULL, 0, -1, LUMPERROR}, + {"litng3", false, 16, 2, NULL, 0, -1, LUMPERROR}, + {"litng4", false, 16, 2, NULL, 0, -1, LUMPERROR}, + {"athun1", false, 16, 2, NULL, 0, -1, LUMPERROR}, + {"athun2", false, 16, 2, NULL, 0, -1, LUMPERROR}, - {"amwtr1", false, 12, 0, NULL, 0, -1, LUMPERROR}, - {"amwtr2", false, 12, 0, NULL, 0, -1, LUMPERROR}, - {"amwtr3", false, 12, 0, NULL, 0, -1, LUMPERROR}, - {"amwtr4", false, 12, 0, NULL, 0, -1, LUMPERROR}, - {"amwtr5", false, 12, 0, NULL, 0, -1, LUMPERROR}, - {"amwtr6", false, 12, 0, NULL, 0, -1, LUMPERROR}, - {"amwtr7", false, 12, 0, NULL, 0, -1, LUMPERROR}, - {"amwtr8", false, 12, 0, NULL, 0, -1, LUMPERROR}, - {"bubbl1", false, 11, 0, NULL, 0, -1, LUMPERROR}, - {"bubbl2", false, 11, 0, NULL, 0, -1, LUMPERROR}, - {"bubbl3", false, 11, 0, NULL, 0, -1, LUMPERROR}, - {"bubbl4", false, 11, 0, NULL, 0, -1, LUMPERROR}, - {"bubbl5", false, 11, 0, NULL, 0, -1, LUMPERROR}, - {"floush", false, 16, 0, NULL, 0, -1, LUMPERROR}, - {"splash", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"splish", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Splish Tails 12-08-2000 - {"wdrip1", false, 8, 0, NULL, 0, -1, LUMPERROR}, - {"wdrip2", false, 8 , 0, NULL, 0, -1, LUMPERROR}, - {"wdrip3", false, 8, 0, NULL, 0, -1, LUMPERROR}, - {"wdrip4", false, 8, 0, NULL, 0, -1, LUMPERROR}, - {"wdrip5", false, 8, 0, NULL, 0, -1, LUMPERROR}, - {"wdrip6", false, 8, 0, NULL, 0, -1, LUMPERROR}, - {"wdrip7", false, 8, 0, NULL, 0, -1, LUMPERROR}, - {"wdrip8", false, 8, 0, NULL, 0, -1, LUMPERROR}, - {"wslap", false, 32, 0, NULL, 0, -1, LUMPERROR}, // Water Slap Tails 12-13-2000 + {"amwtr1", false, 12, 0, NULL, 0, -1, LUMPERROR}, + {"amwtr2", false, 12, 0, NULL, 0, -1, LUMPERROR}, + {"amwtr3", false, 12, 0, NULL, 0, -1, LUMPERROR}, + {"amwtr4", false, 12, 0, NULL, 0, -1, LUMPERROR}, + {"amwtr5", false, 12, 0, NULL, 0, -1, LUMPERROR}, + {"amwtr6", false, 12, 0, NULL, 0, -1, LUMPERROR}, + {"amwtr7", false, 12, 0, NULL, 0, -1, LUMPERROR}, + {"amwtr8", false, 12, 0, NULL, 0, -1, LUMPERROR}, + {"bubbl1", false, 11, 0, NULL, 0, -1, LUMPERROR}, + {"bubbl2", false, 11, 0, NULL, 0, -1, LUMPERROR}, + {"bubbl3", false, 11, 0, NULL, 0, -1, LUMPERROR}, + {"bubbl4", false, 11, 0, NULL, 0, -1, LUMPERROR}, + {"bubbl5", false, 11, 0, NULL, 0, -1, LUMPERROR}, + {"floush", false, 16, 0, NULL, 0, -1, LUMPERROR}, + {"splash", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"splish", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Splish Tails 12-08-2000 + {"wdrip1", false, 8, 0, NULL, 0, -1, LUMPERROR}, + {"wdrip2", false, 8 , 0, NULL, 0, -1, LUMPERROR}, + {"wdrip3", false, 8, 0, NULL, 0, -1, LUMPERROR}, + {"wdrip4", false, 8, 0, NULL, 0, -1, LUMPERROR}, + {"wdrip5", false, 8, 0, NULL, 0, -1, LUMPERROR}, + {"wdrip6", false, 8, 0, NULL, 0, -1, LUMPERROR}, + {"wdrip7", false, 8, 0, NULL, 0, -1, LUMPERROR}, + {"wdrip8", false, 8, 0, NULL, 0, -1, LUMPERROR}, + {"wslap", false, 32, 0, NULL, 0, -1, LUMPERROR}, // Water Slap Tails 12-13-2000 - {"doora1", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"doorb1", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"doorc1", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"doorc2", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"doord1", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"doord2", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"eleva1", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"eleva2", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"eleva3", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"elevb1", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"elevb2", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"elevb3", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"doora1", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"doorb1", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"doorc1", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"doorc2", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"doord1", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"doord2", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"eleva1", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"eleva2", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"eleva3", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"elevb1", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"elevb2", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"elevb3", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"ambin2", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"lavbub", false, 64, 8, NULL, 0, -1, LUMPERROR}, - {"rocks1", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"rocks2", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"rocks3", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"rocks4", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"rumbam", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"rumble", false, 64, 24, NULL, 0, -1, LUMPERROR}, + {"ambin2", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"lavbub", false, 64, 8, NULL, 0, -1, LUMPERROR}, + {"rocks1", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"rocks2", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"rocks3", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"rocks4", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"rumbam", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"rumble", false, 64, 24, NULL, 0, -1, LUMPERROR}, - // Game objects, etc - {"appear", false, 127, 0, NULL, 0, -1, LUMPERROR}, - {"bkpoof", false, 70, 8, NULL, 0, -1, LUMPERROR}, - {"bnce1", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Boing! - {"bnce2", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Boing! - {"cannon", false, 64, 8, NULL, 0, -1, LUMPERROR}, - {"cgot" , true, 120, 0, NULL, 0, -1, LUMPERROR}, // Got Emerald! Tails 09-02-2001 - {"cybdth", false, 32, 0, NULL, 0, -1, LUMPERROR}, - {"deton", true, 64, 0, NULL, 0, -1, LUMPERROR}, - {"ding", false, 127, 8, NULL, 0, -1, LUMPERROR}, - {"dmpain", false, 96, 0, NULL, 0, -1, LUMPERROR}, - {"drown", false, 192, 0, NULL, 0, -1, LUMPERROR}, - {"fizzle", false, 127, 8, NULL, 0, -1, LUMPERROR}, - {"gbeep", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Grenade beep - {"ghit" , false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"gloop", false, 60, 0, NULL, 0, -1, LUMPERROR}, - {"gspray", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"gravch", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"itemup", true, 255, 0, NULL, 0, -1, LUMPERROR}, - {"jet", false, 8, 0, NULL, 0, -1, LUMPERROR}, - {"jshard", true, 167, 0, NULL, 0, -1, LUMPERROR}, - {"lose" , false, 127, 0, NULL, 0, -1, LUMPERROR}, - {"lvpass", false, 96, 0, NULL, 0, -1, LUMPERROR}, - {"mindig", false, 8, 64, NULL, 0, -1, LUMPERROR}, - {"mixup", true, 127, 0, NULL, 0, -1, LUMPERROR}, - {"pogo" , false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"pop" , false, 78, 0, NULL, 0, -1, LUMPERROR}, - {"rail1", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"rail2", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"rlaunc", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"shield", false, 60, 0, NULL, 0, -1, LUMPERROR}, - {"shldls", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"spdpad", false, 127, 0, NULL, 0, -1, LUMPERROR}, - {"spkdth", false, 127, 0, NULL, 0, -1, LUMPERROR}, - {"spring", false, 112, 0, NULL, 0, -1, LUMPERROR}, - {"statu1", true, 64, 2, NULL, 0, -1, LUMPERROR}, - {"statu2", true, 64, 2, NULL, 0, -1, LUMPERROR}, - {"strpst", true, 192, 0, NULL, 0, -1, LUMPERROR}, // Starpost Sound Tails 07-04-2002 - {"supert", true, 127, 2, NULL, 0, -1, LUMPERROR}, - {"telept", false, 32, 0, NULL, 0, -1, LUMPERROR}, - {"tink" , false, 60, 0, NULL, 0, -1, LUMPERROR}, - {"token" , true, 224, 0, NULL, 0, -1, LUMPERROR}, // SS token - {"trfire", true, 60, 8, NULL, 0, -1, LUMPERROR}, - {"trpowr", true, 127, 8, NULL, 0, -1, LUMPERROR}, - {"turhit", false, 40, 8, NULL, 0, -1, LUMPERROR}, - {"wdjump", false, 60, 0, NULL, 0, -1, LUMPERROR}, - {"mswarp", false, 60, 16, NULL, 0, -1, LUMPERROR}, - {"mspogo", false, 60, 8, NULL, 0, -1, LUMPERROR}, + // Game objects, etc + {"appear", false, 127, 0, NULL, 0, -1, LUMPERROR}, + {"bkpoof", false, 70, 8, NULL, 0, -1, LUMPERROR}, + {"bnce1", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Boing! + {"bnce2", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Boing! + {"cannon", false, 64, 8, NULL, 0, -1, LUMPERROR}, + {"cgot" , true, 120, 0, NULL, 0, -1, LUMPERROR}, // Got Emerald! Tails 09-02-2001 + {"cybdth", false, 32, 0, NULL, 0, -1, LUMPERROR}, + {"deton", true, 64, 0, NULL, 0, -1, LUMPERROR}, + {"ding", false, 127, 8, NULL, 0, -1, LUMPERROR}, + {"dmpain", false, 96, 0, NULL, 0, -1, LUMPERROR}, + {"drown", false, 192, 0, NULL, 0, -1, LUMPERROR}, + {"fizzle", false, 127, 8, NULL, 0, -1, LUMPERROR}, + {"gbeep", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Grenade beep + {"ghit" , false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"gloop", false, 60, 0, NULL, 0, -1, LUMPERROR}, + {"gspray", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"gravch", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"itemup", true, 255, 0, NULL, 0, -1, LUMPERROR}, + {"jet", false, 8, 0, NULL, 0, -1, LUMPERROR}, + {"jshard", true, 167, 0, NULL, 0, -1, LUMPERROR}, + {"lose" , false, 127, 0, NULL, 0, -1, LUMPERROR}, + {"lvpass", false, 96, 0, NULL, 0, -1, LUMPERROR}, + {"mindig", false, 8, 64, NULL, 0, -1, LUMPERROR}, + {"mixup", true, 127, 0, NULL, 0, -1, LUMPERROR}, + {"pogo" , false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"pop" , false, 78, 0, NULL, 0, -1, LUMPERROR}, + {"rail1", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"rail2", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"rlaunc", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"shield", false, 60, 0, NULL, 0, -1, LUMPERROR}, + {"shldls", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"spdpad", false, 127, 0, NULL, 0, -1, LUMPERROR}, + {"spkdth", false, 127, 0, NULL, 0, -1, LUMPERROR}, + {"spring", false, 112, 0, NULL, 0, -1, LUMPERROR}, + {"statu1", true, 64, 2, NULL, 0, -1, LUMPERROR}, + {"statu2", true, 64, 2, NULL, 0, -1, LUMPERROR}, + {"strpst", true, 192, 0, NULL, 0, -1, LUMPERROR}, // Starpost Sound Tails 07-04-2002 + {"supert", true, 127, 2, NULL, 0, -1, LUMPERROR}, + {"telept", false, 32, 0, NULL, 0, -1, LUMPERROR}, + {"tink" , false, 60, 0, NULL, 0, -1, LUMPERROR}, + {"token" , true, 224, 0, NULL, 0, -1, LUMPERROR}, // SS token + {"trfire", true, 60, 8, NULL, 0, -1, LUMPERROR}, + {"trpowr", true, 127, 8, NULL, 0, -1, LUMPERROR}, + {"turhit", false, 40, 8, NULL, 0, -1, LUMPERROR}, + {"wdjump", false, 60, 0, NULL, 0, -1, LUMPERROR}, + {"mswarp", false, 60, 16, NULL, 0, -1, LUMPERROR}, + {"mspogo", false, 60, 8, NULL, 0, -1, LUMPERROR}, - // Menu, interface - {"chchng", false, 120, 0, NULL, 0, -1, LUMPERROR}, - {"dwnind", false, 212, 0, NULL, 0, -1, LUMPERROR}, - {"emfind", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"flgcap", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"menu1", true, 64, 0, NULL, 0, -1, LUMPERROR}, - {"oneup", true, 192, 0, NULL, 0, -1, LUMPERROR}, - {"ptally", true, 64, 0, NULL, 0, -1, LUMPERROR}, // Point tally is identical to menu for now - {"radio", false, 60, 0, NULL, 0, -1, LUMPERROR}, - {"wepchg", true, 64, 0, NULL, 0, -1, LUMPERROR}, // Weapon switch is identical to menu for now - {"wtrdng", true, 212, 0, NULL, 0, -1, LUMPERROR}, // make sure you can hear the DING DING! Tails 03-08-2000 - {"zelda", false, 120, 0, NULL, 0, -1, LUMPERROR}, + // Menu, interface + {"chchng", false, 120, 0, NULL, 0, -1, LUMPERROR}, + {"dwnind", false, 212, 0, NULL, 0, -1, LUMPERROR}, + {"emfind", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"flgcap", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"menu1", true, 64, 0, NULL, 0, -1, LUMPERROR}, + {"oneup", true, 192, 0, NULL, 0, -1, LUMPERROR}, + {"ptally", true, 64, 0, NULL, 0, -1, LUMPERROR}, // Point tally is identical to menu for now + {"radio", false, 60, 0, NULL, 0, -1, LUMPERROR}, + {"wepchg", true, 64, 0, NULL, 0, -1, LUMPERROR}, // Weapon switch is identical to menu for now + {"wtrdng", true, 212, 0, NULL, 0, -1, LUMPERROR}, // make sure you can hear the DING DING! Tails 03-08-2000 + {"zelda", false, 120, 0, NULL, 0, -1, LUMPERROR}, - // NiGHTS - {"ideya", false, 127, 0, NULL, 0, -1, LUMPERROR}, - {"xideya", false, 127, 0, NULL, 0, -1, LUMPERROR}, // Xmas - {"nbmper", false, 96, 0, NULL, 0, -1, LUMPERROR}, - {"nxbump", false, 96, 0, NULL, 0, -1, LUMPERROR}, // Xmas - {"ncitem", false, 204, 0, NULL, 0, -1, LUMPERROR}, - {"nxitem", false, 204, 0, NULL, 0, -1, LUMPERROR}, // Xmas - {"ngdone", true, 127, 0, NULL, 0, -1, LUMPERROR}, - {"nxdone", true, 127, 0, NULL, 0, -1, LUMPERROR}, // Xmas - {"drill1", false, 48, 0, NULL, 0, -1, LUMPERROR}, - {"drill2", false, 48, 0, NULL, 0, -1, LUMPERROR}, - {"ncspec", false, 204, 0, NULL, 0, -1, LUMPERROR}, // Tails 12-15-2003 - {"nghurt", false, 96, 0, NULL, 0, -1, LUMPERROR}, - {"ngskid", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"hoop1", false, 192, 0, NULL, 0, -1, LUMPERROR}, - {"hoop2", false, 192, 0, NULL, 0, -1, LUMPERROR}, - {"hoop3", false, 192, 0, NULL, 0, -1, LUMPERROR}, - {"hidden", false, 204, 0, NULL, 0, -1, LUMPERROR}, - {"prloop", false, 104, 0, NULL, 0, -1, LUMPERROR}, - {"timeup", true, 256, 0, NULL, 0, -1, LUMPERROR}, + // NiGHTS + {"ideya", false, 127, 0, NULL, 0, -1, LUMPERROR}, + {"xideya", false, 127, 0, NULL, 0, -1, LUMPERROR}, // Xmas + {"nbmper", false, 96, 0, NULL, 0, -1, LUMPERROR}, + {"nxbump", false, 96, 0, NULL, 0, -1, LUMPERROR}, // Xmas + {"ncitem", false, 204, 0, NULL, 0, -1, LUMPERROR}, + {"nxitem", false, 204, 0, NULL, 0, -1, LUMPERROR}, // Xmas + {"ngdone", true, 127, 0, NULL, 0, -1, LUMPERROR}, + {"nxdone", true, 127, 0, NULL, 0, -1, LUMPERROR}, // Xmas + {"drill1", false, 48, 0, NULL, 0, -1, LUMPERROR}, + {"drill2", false, 48, 0, NULL, 0, -1, LUMPERROR}, + {"ncspec", false, 204, 0, NULL, 0, -1, LUMPERROR}, // Tails 12-15-2003 + {"nghurt", false, 96, 0, NULL, 0, -1, LUMPERROR}, + {"ngskid", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"hoop1", false, 192, 0, NULL, 0, -1, LUMPERROR}, + {"hoop2", false, 192, 0, NULL, 0, -1, LUMPERROR}, + {"hoop3", false, 192, 0, NULL, 0, -1, LUMPERROR}, + {"hidden", false, 204, 0, NULL, 0, -1, LUMPERROR}, + {"prloop", false, 104, 0, NULL, 0, -1, LUMPERROR}, + {"timeup", true, 256, 0, NULL, 0, -1, LUMPERROR}, - // Mario - {"koopfr" , true, 127, 8, NULL, 0, -1, LUMPERROR}, - {"mario1", false, 60, 0, NULL, 0, -1, LUMPERROR}, - {"mario2", false, 127, 0, NULL, 0, -1, LUMPERROR}, - {"mario3", false, 60, 0, NULL, 0, -1, LUMPERROR}, - {"mario4", true, 78, 0, NULL, 0, -1, LUMPERROR}, - {"mario5", false, 78, 0, NULL, 0, -1, LUMPERROR}, - {"mario6", false, 60, 0, NULL, 0, -1, LUMPERROR}, - {"mario7", false, 32, 0, NULL, 0, -1, LUMPERROR}, - {"mario8", false, 48, 8, NULL, 0, -1, LUMPERROR}, - {"mario9", true, 120, 0, NULL, 0, -1, LUMPERROR}, - {"marioa", true, 127, 0, NULL, 0, -1, LUMPERROR}, - {"thwomp", true, 127, 8, NULL, 0, -1, LUMPERROR}, + // Mario + {"koopfr" , true, 127, 8, NULL, 0, -1, LUMPERROR}, + {"mario1", false, 60, 0, NULL, 0, -1, LUMPERROR}, + {"mario2", false, 127, 0, NULL, 0, -1, LUMPERROR}, + {"mario3", false, 60, 0, NULL, 0, -1, LUMPERROR}, + {"mario4", true, 78, 0, NULL, 0, -1, LUMPERROR}, + {"mario5", false, 78, 0, NULL, 0, -1, LUMPERROR}, + {"mario6", false, 60, 0, NULL, 0, -1, LUMPERROR}, + {"mario7", false, 32, 0, NULL, 0, -1, LUMPERROR}, + {"mario8", false, 48, 8, NULL, 0, -1, LUMPERROR}, + {"mario9", true, 120, 0, NULL, 0, -1, LUMPERROR}, + {"marioa", true, 127, 0, NULL, 0, -1, LUMPERROR}, + {"thwomp", true, 127, 8, NULL, 0, -1, LUMPERROR}, - // Black Eggman - {"bebomb", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"bechrg", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"becrsh", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"bedeen", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"bedie1", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"bedie2", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"beeyow", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"befall", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"befire", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"beflap", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"begoop", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"begrnd", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"behurt", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"bejet1", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"belnch", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"beoutb", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"beragh", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"beshot", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"bestep", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"bestp2", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"bewar1", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"bewar2", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"bewar3", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"bewar4", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"bexpld", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"bgxpld", false, 64, 64, NULL, 0, -1, LUMPERROR}, + // Black Eggman + {"bebomb", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"bechrg", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"becrsh", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"bedeen", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"bedie1", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"bedie2", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"beeyow", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"befall", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"befire", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"beflap", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"begoop", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"begrnd", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"behurt", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"bejet1", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"belnch", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"beoutb", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"beragh", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"beshot", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"bestep", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"bestp2", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"bewar1", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"bewar2", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"bewar3", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"bewar4", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"bexpld", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"bgxpld", false, 64, 64, NULL, 0, -1, LUMPERROR}, - // Cybrakdemon - {"beelec", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"brakrl", false, 64, 64, NULL, 0, -1, LUMPERROR}, - {"brakrx", false, 64, 64, NULL, 0, -1, LUMPERROR}, + // Cybrakdemon + {"beelec", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"brakrl", false, 64, 64, NULL, 0, -1, LUMPERROR}, + {"brakrx", false, 64, 64, NULL, 0, -1, LUMPERROR}, - // Sonic 1 sounds - {"s1a0", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1a1", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1a2", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Monty Mole attach - {"s1a3", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1a4", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1a5", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1a6", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1a7", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1a8", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1a9", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1aa", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1ab", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Monty Mole twitch - {"s1ac", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Misc. obstacle destroyed - {"s1ad", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1ae", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1af", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1b0", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1b1", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1b2", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1b3", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1b4", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Toggle all items - {"s1b5", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1b6", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1b7", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1b8", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1b9", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1ba", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Toggle item - {"s1bb", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Thwomp drop - {"s1bc", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1bd", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Ballhog bounce - {"s1be", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1bf", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1c0", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1c1", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Monokuma death - {"s1c2", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1c3", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1c4", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1c5", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1c6", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1c7", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1c8", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1c9", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Item hit w/ voices off - {"s1ca", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1cb", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1cc", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1cd", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1ce", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s1cf", false, 64, 0, NULL, 0, -1, LUMPERROR}, + // Sonic 1 sounds + {"s1a0", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1a1", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1a2", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Monty Mole attach + {"s1a3", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1a4", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1a5", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1a6", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1a7", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1a8", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1a9", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1aa", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1ab", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Monty Mole twitch + {"s1ac", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Misc. obstacle destroyed + {"s1ad", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1ae", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1af", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1b0", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1b1", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1b2", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1b3", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1b4", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Toggle all items + {"s1b5", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1b6", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1b7", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1b8", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1b9", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1ba", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Toggle item + {"s1bb", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Thwomp drop + {"s1bc", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1bd", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Ballhog bounce + {"s1be", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1bf", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1c0", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1c1", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Monokuma death + {"s1c2", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1c3", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1c4", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1c5", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1c6", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1c7", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1c8", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1c9", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Item hit w/ voices off + {"s1ca", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1cb", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1cc", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1cd", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1ce", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s1cf", false, 64, 0, NULL, 0, -1, LUMPERROR}, - // Sonic 2 sounds - {"s220", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s221", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Lap sound - {"s222", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s223", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s224", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s225", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s226", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s227", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s228", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s229", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s22a", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s22b", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s22c", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s22d", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s22e", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s22f", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s230", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s231", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s232", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s233", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s234", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s235", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s236", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s237", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s238", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s239", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s23a", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s23b", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s23c", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Drift boost - {"s23d", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s23e", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Title screen opening - {"s23f", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s240", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s241", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s242", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s243", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s244", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s245", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s246", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s247", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s248", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s249", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s24a", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s24b", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s24c", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s24d", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s24e", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s24f", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s250", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s251", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s252", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s253", false, 255, 0, NULL, 0, -1, LUMPERROR}, // 1st place finish - {"s254", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s255", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s256", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s257", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s258", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s259", false, 96, 8, NULL, 0, -1, LUMPERROR}, // Item clashing - {"s25a", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s25b", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s25c", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s25d", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s25e", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s25f", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Perfect start boost - {"s260", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s261", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s262", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s263", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s264", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s265", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s266", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s267", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s268", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s269", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s26a", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s26b", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s26c", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s26d", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Missed checkpoint - {"s26e", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s26f", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s270", false, 64, 0, NULL, 0, -1, LUMPERROR}, + // Sonic 2 sounds + {"s220", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s221", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Lap sound + {"s222", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s223", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s224", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s225", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s226", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s227", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s228", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s229", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s22a", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s22b", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s22c", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s22d", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s22e", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s22f", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s230", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s231", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s232", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s233", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s234", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s235", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s236", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s237", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s238", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s239", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s23a", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s23b", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s23c", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Drift boost + {"s23d", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s23e", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Title screen opening + {"s23f", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s240", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s241", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s242", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s243", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s244", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s245", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s246", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s247", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s248", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s249", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s24a", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s24b", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s24c", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s24d", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s24e", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s24f", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s250", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s251", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s252", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s253", false, 255, 0, NULL, 0, -1, LUMPERROR}, // 1st place finish + {"s254", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s255", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s256", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s257", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s258", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s259", false, 96, 8, NULL, 0, -1, LUMPERROR}, // Item clashing + {"s25a", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s25b", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s25c", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s25d", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s25e", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s25f", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Perfect start boost + {"s260", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s261", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s262", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s263", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s264", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s265", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s266", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s267", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s268", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s269", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s26a", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s26b", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s26c", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s26d", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Missed checkpoint + {"s26e", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s26f", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s270", false, 64, 0, NULL, 0, -1, LUMPERROR}, - // S3&K sounds - {"s3k33", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k34", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k35", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k36", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k37", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k38", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k39", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k3a", false, 96, 0, NULL, 0, -1, LUMPERROR}, // Kart item shield - {"s3k3b", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k3c", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k3d", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k3e", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k3f", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k40", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k41", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k42", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Kart Thunder Shield spawned - {"s3k43", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k44", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k45", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k46", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k47", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Kart AIZ dust - {"s3k48", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k49", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Kart bump sound - {"s3k4a", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k4b", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k4c", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k4d", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k4e", false, 64, 8, NULL, 0, -1, LUMPERROR}, // Kart explosion - {"s3k4f", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k50", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k51", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k52", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k53", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k54", false, 64, 64, NULL, 0, -1, LUMPERROR}, // MetalSonic shot fire - {"s3k55", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k56", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k57", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k58", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k59", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k5a", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k5b", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k5c", false, 96, 0, NULL, 0, -1, LUMPERROR}, // Kart Mine tick - {"s3k5d", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k5e", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k5f", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k60", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k61", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k62", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k63", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k64", false, 64, 2, NULL, 0, -1, LUMPERROR}, - {"s3k65", false, 255, 0, NULL, 0, -1, LUMPERROR}, // Blue Spheres - {"s3k66", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k67", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k68", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Kart final lap - {"s3k69", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k6a", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Kart finish - {"s3k6b", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k6c", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k6d", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k6e", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k6f", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k70", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k71", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k72", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k73", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k74", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k75", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k76", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k77", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k78", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k79", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k7a", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k7b", false, 96, 16, NULL, 0, -1, LUMPERROR}, // Kart successful hit - {"s3k7c", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k7d", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k7e", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k7f", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k80", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k81", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k82", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k83", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Overcharged start boost - {"s3k84", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k85", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k86", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k87", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k88", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k89", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Kart Jawz target - {"s3k8a", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k8b", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k8c", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k8d", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k8e", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k8f", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k90", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k91", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k92", false, 64, 8, NULL, 0, -1, LUMPERROR}, // Kart Hyudoro use - {"s3k93", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k94", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k95", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k96", false, 128, 0, NULL, 0, -1, LUMPERROR}, // Kart Orbinaut - {"s3k97", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k98", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k99", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k9a", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k9b", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k9c", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k9d", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k9e", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3k9f", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3ka0", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3ka1", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3ka2", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Kart drift spark gain - {"s3ka3", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3ka4", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3ka5", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3ka6", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3ka7", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Kart 3,2,1 - {"s3ka8", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3ka9", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kaa", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kab", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kac", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kad", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Kart GO! - {"s3kae", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kaf", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kb0", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kb1", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kb2", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kb3", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kb4", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kb5", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kb6", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kb7", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kb8", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kb9", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kba", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kbb", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kbcs", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kbcl", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kbds", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kbdl", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kbes", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kbel", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kbfs", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kbfl", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kc0s", false, 192, 8, NULL, 0, -1, LUMPERROR}, // Kart Jawz - {"s3kc0l", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kc1s", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kc1l", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kc2s", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kc2l", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kc3s", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kc3l", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kc4s", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kc4l", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kc5s", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kc5l", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kc6s", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kc6l", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kc7s", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kc7l", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kc8s", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kc8l", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kc9s", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kc9l", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kcas", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Kart respawn - {"s3kcal", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kcbs", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kcbl", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kccs", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kccl", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kcds", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kcdl", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kces", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kcel", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kcfs", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kcfl", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kd0s", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kd0l", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kd1s", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kd1l", false, 48, 0, NULL, 0, -1, LUMPERROR}, - {"s3kd2s", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kd2l", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kd3s", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kd3l", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kd4s", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kd4l", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kd5s", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kd5l", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kd6s", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kd6l", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kd7s", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kd7l", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kd8s", false, 64, 64, NULL, 0, -1, LUMPERROR}, // Sharp Spin (maybe use the long/L version?) - {"s3kd8l", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kd9s", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kd9l", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kdas", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kdal", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kdbs", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"s3kdbl", false, 64, 0, NULL, 0, -1, LUMPERROR}, + // S3&K sounds + {"s3k33", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k34", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k35", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k36", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k37", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k38", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k39", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k3a", false, 96, 0, NULL, 0, -1, LUMPERROR}, // Kart item shield + {"s3k3b", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k3c", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k3d", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k3e", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k3f", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k40", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k41", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k42", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Kart Thunder Shield spawned + {"s3k43", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k44", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k45", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k46", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k47", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Kart AIZ dust + {"s3k48", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k49", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Kart bump sound + {"s3k4a", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k4b", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k4c", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k4d", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k4e", false, 64, 8, NULL, 0, -1, LUMPERROR}, // Kart explosion + {"s3k4f", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k50", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k51", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k52", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k53", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k54", false, 64, 64, NULL, 0, -1, LUMPERROR}, // MetalSonic shot fire + {"s3k55", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k56", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k57", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k58", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k59", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k5a", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k5b", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k5c", false, 96, 0, NULL, 0, -1, LUMPERROR}, // Kart Mine tick + {"s3k5d", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k5e", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k5f", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k60", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k61", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k62", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k63", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k64", false, 64, 2, NULL, 0, -1, LUMPERROR}, + {"s3k65", false, 255, 0, NULL, 0, -1, LUMPERROR}, // Blue Spheres + {"s3k66", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k67", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k68", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Kart final lap + {"s3k69", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k6a", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Kart finish + {"s3k6b", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k6c", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k6d", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k6e", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k6f", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k70", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k71", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k72", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k73", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k74", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k75", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k76", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k77", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k78", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k79", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k7a", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k7b", false, 96, 16, NULL, 0, -1, LUMPERROR}, // Kart successful hit + {"s3k7c", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k7d", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k7e", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k7f", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k80", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k81", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k82", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k83", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Overcharged start boost + {"s3k84", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k85", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k86", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k87", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k88", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k89", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Kart Jawz target + {"s3k8a", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k8b", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k8c", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k8d", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k8e", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k8f", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k90", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k91", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k92", false, 64, 8, NULL, 0, -1, LUMPERROR}, // Kart Hyudoro use + {"s3k93", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k94", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k95", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k96", false, 128, 0, NULL, 0, -1, LUMPERROR}, // Kart Orbinaut + {"s3k97", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k98", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k99", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k9a", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k9b", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k9c", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k9d", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k9e", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3k9f", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3ka0", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3ka1", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3ka2", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Kart drift spark gain + {"s3ka3", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3ka4", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3ka5", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3ka6", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3ka7", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Kart 3,2,1 + {"s3ka8", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3ka9", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kaa", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kab", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kac", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kad", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Kart GO! + {"s3kae", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kaf", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kb0", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kb1", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kb2", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kb3", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kb4", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kb5", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kb6", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kb7", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kb8", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kb9", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kba", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kbb", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kbcs", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kbcl", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kbds", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kbdl", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kbes", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kbel", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kbfs", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kbfl", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kc0s", false, 192, 8, NULL, 0, -1, LUMPERROR}, // Kart Jawz + {"s3kc0l", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kc1s", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kc1l", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kc2s", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kc2l", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kc3s", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kc3l", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kc4s", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kc4l", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kc5s", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kc5l", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kc6s", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kc6l", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kc7s", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kc7l", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kc8s", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kc8l", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kc9s", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kc9l", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kcas", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Kart respawn + {"s3kcal", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kcbs", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kcbl", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kccs", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kccl", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kcds", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kcdl", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kces", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kcel", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kcfs", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kcfl", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kd0s", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kd0l", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kd1s", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kd1l", false, 48, 0, NULL, 0, -1, LUMPERROR}, + {"s3kd2s", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kd2l", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kd3s", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kd3l", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kd4s", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kd4l", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kd5s", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kd5l", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kd6s", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kd6l", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kd7s", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kd7l", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kd8s", false, 64, 64, NULL, 0, -1, LUMPERROR}, // Sharp Spin (maybe use the long/L version?) + {"s3kd8l", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kd9s", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kd9l", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kdas", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kdal", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kdbs", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"s3kdbl", false, 64, 0, NULL, 0, -1, LUMPERROR}, - // 3D Blast sounds (the "missing" ones are direct copies of S3K's, no minor differences what-so-ever) - {"3db06", false, 96, 8, NULL, 0, -1, LUMPERROR}, // Bumper stolen - {"3db09", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"3db14", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"3db16", false, 64, 0, NULL, 0, -1, LUMPERROR}, + // 3D Blast sounds (the "missing" ones are direct copies of S3K's, no minor differences what-so-ever) + {"3db06", false, 96, 8, NULL, 0, -1, LUMPERROR}, // Bumper stolen + {"3db09", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"3db14", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"3db16", false, 64, 0, NULL, 0, -1, LUMPERROR}, - // Sonic CD sounds - {"cdfm00", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Undercharged start boost - {"cdfm01", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Sneaker boost - {"cdfm02", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm03", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm04", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm05", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm06", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm07", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm08", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm09", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm10", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm11", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm12", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm13", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm14", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm15", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm16", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm17", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Brake drift ambient - {"cdfm18", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm19", false, 64, 0, NULL, 0, -1, LUMPERROR}, // CD SS1 UFO death - {"cdfm20", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm21", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm22", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm23", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm24", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm25", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm26", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm27", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm28", false, 96, 0, NULL, 0, -1, LUMPERROR}, // Eggman item landing - {"cdfm29", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm30", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm31", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm32", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm33", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm34", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm35", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm36", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm37", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm38", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm39", false, 128, 8, NULL, 0, -1, LUMPERROR}, // Mine deployed - {"cdfm40", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm41", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm42", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm43", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm44", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm45", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm46", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm47", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm48", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm49", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm50", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm51", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm52", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm53", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm54", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm55", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm56", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm57", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm58", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm59", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm60", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm61", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm62", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm63", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm64", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm65", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm66", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm67", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm68", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm69", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm70", false, 96, 0, NULL, 0, -1, LUMPERROR}, // Trail item dragging - {"cdfm71", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm72", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm73", false, 64, 0, NULL, 0, -1, LUMPERROR}, // CD SS1 UFO hit - {"cdfm74", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm75", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm76", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm77", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm78", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdfm79", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdpcm0", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdpcm1", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdpcm2", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdpcm3", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdpcm4", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdpcm5", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdpcm6", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdpcm7", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdpcm8", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"cdpcm9", false, 96, 8, NULL, 0, -1, LUMPERROR}, // No damage taken + // Sonic CD sounds + {"cdfm00", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Undercharged start boost + {"cdfm01", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Sneaker boost + {"cdfm02", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm03", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm04", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm05", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm06", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm07", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm08", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm09", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm10", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm11", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm12", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm13", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm14", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm15", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm16", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm17", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Brake drift ambient + {"cdfm18", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm19", false, 64, 0, NULL, 0, -1, LUMPERROR}, // CD SS1 UFO death + {"cdfm20", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm21", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm22", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm23", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm24", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm25", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm26", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm27", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm28", false, 96, 0, NULL, 0, -1, LUMPERROR}, // Eggman item landing + {"cdfm29", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm30", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm31", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm32", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm33", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm34", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm35", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm36", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm37", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm38", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm39", false, 128, 8, NULL, 0, -1, LUMPERROR}, // Mine deployed + {"cdfm40", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm41", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm42", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm43", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm44", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm45", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm46", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm47", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm48", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm49", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm50", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm51", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm52", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm53", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm54", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm55", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm56", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm57", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm58", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm59", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm60", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm61", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm62", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm63", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm64", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm65", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm66", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm67", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm68", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm69", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm70", false, 96, 0, NULL, 0, -1, LUMPERROR}, // Trail item dragging + {"cdfm71", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm72", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm73", false, 64, 0, NULL, 0, -1, LUMPERROR}, // CD SS1 UFO hit + {"cdfm74", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm75", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm76", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm77", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm78", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdfm79", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdpcm0", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdpcm1", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdpcm2", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdpcm3", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdpcm4", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdpcm5", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdpcm6", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdpcm7", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdpcm8", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"cdpcm9", false, 96, 8, NULL, 0, -1, LUMPERROR}, // No damage taken - // Knuckles Chaotix sound - {"kc2a", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc2b", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc2c", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc2d", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc2e", false, 96, 0, NULL, 0, -1, LUMPERROR}, // Item box gotten - {"kc2f", false, 96, 8, NULL, 0, -1, LUMPERROR}, // Spring pad - {"kc30", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc31", false, 64, 64, NULL, 0, -1, LUMPERROR}, // NO CONTEST explosion - {"kc32", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc33", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc34", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc35", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc36", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc37", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc38", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc39", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Voting roulette - {"kc3a", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc3b", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc3c", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc3d", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc3e", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc3f", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc40", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc41", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc42", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Unlock everything cheat - {"kc43", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc44", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc45", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc46", false, 96, 8, NULL, 0, -1, LUMPERROR}, // Shrink use - {"kc47", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc48", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Vote picked - {"kc49", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc4a", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Voting beep - {"kc4b", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc4c", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc4d", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc4e", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc4f", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc50", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc51", false, 64, 64, NULL, 0, -1, LUMPERROR}, // NO CONTEST debris ambience - {"kc52", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc53", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc54", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc55", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc56", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc57", false, 128, 8, NULL, 0, -1, LUMPERROR}, // SPB locked in - {"kc58", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc59", false, 128, 8, NULL, 0, -1, LUMPERROR}, // Shrink - {"kc5a", false, 128, 8, NULL, 0, -1, LUMPERROR}, // Grow - {"kc5b", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc5c", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc5d", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc5e", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc5f", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc60", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc61", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc62", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc63", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc64", false, 96, 0, NULL, 0, -1, LUMPERROR}, // SPB ambient - {"kc65", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc66", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc67", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc68", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc69", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc6b", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc6c", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc6d", false, 64, 0, NULL, 0, -1, LUMPERROR}, - {"kc6e", false, 64, 0, NULL, 0, -1, LUMPERROR}, + // Knuckles Chaotix sound + {"kc2a", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc2b", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc2c", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc2d", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc2e", false, 96, 0, NULL, 0, -1, LUMPERROR}, // Item box gotten + {"kc2f", false, 96, 8, NULL, 0, -1, LUMPERROR}, // Spring pad + {"kc30", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc31", false, 64, 64, NULL, 0, -1, LUMPERROR}, // NO CONTEST explosion + {"kc32", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc33", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc34", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc35", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc36", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc37", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc38", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc39", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Voting roulette + {"kc3a", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc3b", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc3c", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc3d", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc3e", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc3f", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc40", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc41", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc42", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Unlock everything cheat + {"kc43", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc44", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc45", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc46", false, 96, 8, NULL, 0, -1, LUMPERROR}, // Shrink use + {"kc47", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc48", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Vote picked + {"kc49", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc4a", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Voting beep + {"kc4b", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc4c", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc4d", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc4e", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc4f", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc50", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc51", false, 64, 64, NULL, 0, -1, LUMPERROR}, // NO CONTEST debris ambience + {"kc52", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc53", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc54", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc55", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc56", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc57", false, 128, 8, NULL, 0, -1, LUMPERROR}, // SPB locked in + {"kc58", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc59", false, 128, 8, NULL, 0, -1, LUMPERROR}, // Shrink + {"kc5a", false, 128, 8, NULL, 0, -1, LUMPERROR}, // Grow + {"kc5b", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc5c", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc5d", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc5e", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc5f", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc60", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc61", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc62", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc63", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc64", false, 96, 0, NULL, 0, -1, LUMPERROR}, // SPB ambient + {"kc65", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc66", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc67", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc68", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc69", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc6b", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc6c", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc6d", false, 64, 0, NULL, 0, -1, LUMPERROR}, + {"kc6e", false, 64, 0, NULL, 0, -1, LUMPERROR}, - // SRB2kart - {"slip", false, 96, 0, NULL, 0, -1, LUMPERROR}, // Spinout - {"screec", false, 48, 0, NULL, 0, -1, LUMPERROR}, // Tight turning screech - {"drift", false, 48, 0, NULL, 0, -1, LUMPERROR}, // Drifting ambient - {"ruburn", false, 48, 0, NULL, 0, -1, LUMPERROR}, // Rubber-burn turn ambient - {"ddash", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Respawn Drop Dash - {"tossed", false, 192, 8, NULL, 0, -1, LUMPERROR}, // Item fired - {"itpick", false, 128, 8, NULL, 0, -1, LUMPERROR}, // Pick up HUD drop - {"peel", false, 96, 0, NULL, 0, -1, LUMPERROR}, // Edited S25A for banana landing - {"hogbom", false, 96, 8, NULL, 0, -1, LUMPERROR}, // Ballhog explosions - {"zio3", false, 128, 8, NULL, 0, -1, LUMPERROR}, // Thunder Shield use - {"kpogos", false, 96, 8, NULL, 0, -1, LUMPERROR}, // Pogo Spring use - {"alarmi", false, 255, 8, NULL, 0, -1, LUMPERROR}, // Invincibility alarm - {"alarmg", false, 255, 8, NULL, 0, -1, LUMPERROR}, // Grow alarm - {"kinvnc", false, 255, 8, NULL, 0, -1, LUMPERROR}, // Invincibility music - {"kgrow", false, 255, 8, NULL, 0, -1, LUMPERROR}, // Grow music - {"itrol1", true, 96, 0, NULL, 0, -1, LUMPERROR}, // Roulette spinning - {"itrol2", true, 96, 0, NULL, 0, -1, LUMPERROR}, - {"itrol3", true, 96, 0, NULL, 0, -1, LUMPERROR}, - {"itrol4", true, 96, 0, NULL, 0, -1, LUMPERROR}, - {"itrol5", true, 96, 0, NULL, 0, -1, LUMPERROR}, - {"itrol6", true, 96, 0, NULL, 0, -1, LUMPERROR}, - {"itrol7", true, 96, 0, NULL, 0, -1, LUMPERROR}, - {"itrol8", true, 96, 0, NULL, 0, -1, LUMPERROR}, - {"itrolf", true, 96, 0, NULL, 0, -1, LUMPERROR}, // Roulette end - {"itrolm", true, 96, 0, NULL, 0, -1, LUMPERROR}, // Roulette end (mashed) - {"itrolk", true, 96, 0, NULL, 0, -1, LUMPERROR}, // Roulette end (karma enhanced) - {"itrole", true, 96, 0, NULL, 0, -1, LUMPERROR}, // Roulette end (Eggman) - {"vroom", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Kart Krew opening vroom - {"chaooo", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Chao audience cheer - {"yeeeah", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Voting picks you - {"noooo1", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Voting picks hell (by chance) - {"noooo2", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Voting picks hell (on purpose) - {"ruby1", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Phantom Ruby charge up - {"ruby2", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Phantom Ruby teleport - {"tcart", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Twinkle Cart - {"bfare", false, 128, 0, NULL, 0, -1, LUMPERROR}, // Pleasure Castle fanfare - {"merry", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Pleasure Castle merry-go-round ambient - {"bowlh", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Pleasure Castle pins - {"tppop", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Pleasure Castle bombs - {"hsdoor", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Red Barrage Area door - {"hstrn", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Red Barrage Area train - {"aspkb", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Red Barrage Area spikeballs - {"wind1", false, 64, 8, NULL, 0, -1, LUMPERROR}, // Midnight Channel monsters - {"fire2", false, 64, 8, NULL, 0, -1, LUMPERROR}, - {"chain", false, 255, 8, NULL, 0, -1, LUMPERROR}, // Mementos Reaper - {"mkuma", false, 96, 8, NULL, 0, -1, LUMPERROR}, // Trigger Happy Havoc Monokuma - {"toada", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Arid Sands Toad scream - {"gemhit", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Opulence gem/coin tumbling - {"wrink", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Some sort of ghoulie? - {"bsnipe", false, 96, 8, NULL, 0, -1, LUMPERROR}, // Banana sniping - {"join", true, 96, 8, NULL, 0, -1, LUMPERROR}, // Player joined server - {"leave", true, 96, 8, NULL, 0, -1, LUMPERROR}, // Player left server - {"requst", true, 96, 8, NULL, 0, -1, LUMPERROR}, // Got a Discord join request - {"syfail", true, 96, 8, NULL, 0, -1, LUMPERROR}, // Funny sync failure - {"itfree", false, 64, 0, NULL, 0, -1, LUMPERROR}, // :shitsfree: - {"dbgsal", false, 255, 8, NULL, 0, -1, LUMPERROR}, // Debug notification + // SRB2kart + {"slip", false, 96, 0, NULL, 0, -1, LUMPERROR}, // Spinout + {"screec", false, 48, 0, NULL, 0, -1, LUMPERROR}, // Tight turning screech + {"drift", false, 48, 0, NULL, 0, -1, LUMPERROR}, // Drifting ambient + {"ruburn", false, 48, 0, NULL, 0, -1, LUMPERROR}, // Rubber-burn turn ambient + {"ddash", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Respawn Drop Dash + {"tossed", false, 192, 8, NULL, 0, -1, LUMPERROR}, // Item fired + {"itpick", false, 128, 8, NULL, 0, -1, LUMPERROR}, // Pick up HUD drop + {"peel", false, 96, 0, NULL, 0, -1, LUMPERROR}, // Edited S25A for banana landing + {"hogbom", false, 96, 8, NULL, 0, -1, LUMPERROR}, // Ballhog explosions + {"zio3", false, 128, 8, NULL, 0, -1, LUMPERROR}, // Thunder Shield use + {"kpogos", false, 96, 8, NULL, 0, -1, LUMPERROR}, // Pogo Spring use + {"alarmi", false, 255, 8, NULL, 0, -1, LUMPERROR}, // Invincibility alarm + {"alarmg", false, 255, 8, NULL, 0, -1, LUMPERROR}, // Grow alarm + {"kinvnc", false, 255, 8, NULL, 0, -1, LUMPERROR}, // Invincibility music + {"kgrow", false, 255, 8, NULL, 0, -1, LUMPERROR}, // Grow music + {"itrol1", true, 96, 0, NULL, 0, -1, LUMPERROR}, // Roulette spinning + {"itrol2", true, 96, 0, NULL, 0, -1, LUMPERROR}, + {"itrol3", true, 96, 0, NULL, 0, -1, LUMPERROR}, + {"itrol4", true, 96, 0, NULL, 0, -1, LUMPERROR}, + {"itrol5", true, 96, 0, NULL, 0, -1, LUMPERROR}, + {"itrol6", true, 96, 0, NULL, 0, -1, LUMPERROR}, + {"itrol7", true, 96, 0, NULL, 0, -1, LUMPERROR}, + {"itrol8", true, 96, 0, NULL, 0, -1, LUMPERROR}, + {"itrolf", true, 96, 0, NULL, 0, -1, LUMPERROR}, // Roulette end + {"itrolm", true, 96, 0, NULL, 0, -1, LUMPERROR}, // Roulette end (mashed) + {"itrolk", true, 96, 0, NULL, 0, -1, LUMPERROR}, // Roulette end (karma enhanced) + {"itrole", true, 96, 0, NULL, 0, -1, LUMPERROR}, // Roulette end (Eggman) + {"vroom", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Kart Krew opening vroom + {"chaooo", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Chao audience cheer + {"yeeeah", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Voting picks you + {"noooo1", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Voting picks hell (by chance) + {"noooo2", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Voting picks hell (on purpose) + {"ruby1", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Phantom Ruby charge up + {"ruby2", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Phantom Ruby teleport + {"tcart", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Twinkle Cart + {"bfare", false, 128, 0, NULL, 0, -1, LUMPERROR}, // Pleasure Castle fanfare + {"merry", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Pleasure Castle merry-go-round ambient + {"bowlh", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Pleasure Castle pins + {"tppop", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Pleasure Castle bombs + {"hsdoor", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Red Barrage Area door + {"hstrn", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Red Barrage Area train + {"aspkb", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Red Barrage Area spikeballs + {"wind1", false, 64, 8, NULL, 0, -1, LUMPERROR}, // Midnight Channel monsters + {"fire2", false, 64, 8, NULL, 0, -1, LUMPERROR}, + {"chain", false, 255, 8, NULL, 0, -1, LUMPERROR}, // Mementos Reaper + {"mkuma", false, 96, 8, NULL, 0, -1, LUMPERROR}, // Trigger Happy Havoc Monokuma + {"toada", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Arid Sands Toad scream + {"gemhit", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Opulence gem/coin tumbling + {"wrink", false, 64, 0, NULL, 0, -1, LUMPERROR}, // Some sort of ghoulie? + {"bsnipe", false, 96, 8, NULL, 0, -1, LUMPERROR}, // Banana sniping + {"join", true, 96, 8, NULL, 0, -1, LUMPERROR}, // Player joined server + {"leave", true, 96, 8, NULL, 0, -1, LUMPERROR}, // Player left server + {"requst", true, 96, 8, NULL, 0, -1, LUMPERROR}, // Got a Discord join request + {"syfail", true, 96, 8, NULL, 0, -1, LUMPERROR}, // Funny sync failure + {"itfree", false, 64, 0, NULL, 0, -1, LUMPERROR}, // :shitsfree: + {"dbgsal", false, 255, 8, NULL, 0, -1, LUMPERROR}, // Debug notification - // SRB2Kart - Engine sounds - // Engine class A - {"krta00", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krta01", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krta02", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krta03", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krta04", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krta05", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krta06", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krta07", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krta08", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krta09", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krta10", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krta11", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krta12", false, 48, 65, NULL, 0, -1, LUMPERROR}, - // Engine class B - {"krtb00", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtb01", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtb02", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtb03", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtb04", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtb05", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtb06", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtb07", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtb08", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtb09", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtb10", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtb11", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtb12", false, 48, 65, NULL, 0, -1, LUMPERROR}, - // Engine class C - {"krtc00", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtc01", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtc02", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtc03", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtc04", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtc05", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtc06", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtc07", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtc08", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtc09", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtc10", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtc11", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtc12", false, 48, 65, NULL, 0, -1, LUMPERROR}, - // Engine class D - {"krtd00", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtd01", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtd02", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtd03", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtd04", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtd05", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtd06", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtd07", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtd08", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtd09", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtd10", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtd11", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtd12", false, 48, 65, NULL, 0, -1, LUMPERROR}, - // Engine class E - {"krte00", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krte01", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krte02", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krte03", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krte04", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krte05", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krte06", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krte07", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krte08", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krte09", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krte10", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krte11", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krte12", false, 48, 65, NULL, 0, -1, LUMPERROR}, - // Engine class F - {"krtf00", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtf01", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtf02", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtf03", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtf04", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtf05", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtf06", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtf07", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtf08", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtf09", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtf10", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtf11", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtf12", false, 48, 65, NULL, 0, -1, LUMPERROR}, - // Engine class G - {"krtg00", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtg01", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtg02", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtg03", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtg04", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtg05", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtg06", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtg07", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtg08", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtg09", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtg10", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtg11", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krtg12", false, 48, 65, NULL, 0, -1, LUMPERROR}, - // Engine class H - {"krth00", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krth01", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krth02", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krth03", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krth04", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krth05", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krth06", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krth07", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krth08", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krth09", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krth10", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krth11", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krth12", false, 48, 65, NULL, 0, -1, LUMPERROR}, - // Engine class I - {"krti00", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krti01", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krti02", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krti03", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krti04", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krti05", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krti06", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krti07", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krti08", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krti09", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krti10", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krti11", false, 48, 65, NULL, 0, -1, LUMPERROR}, - {"krti12", false, 48, 65, NULL, 0, -1, LUMPERROR}, + // SRB2Kart - Engine sounds + // Engine class A + {"krta00", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krta01", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krta02", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krta03", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krta04", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krta05", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krta06", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krta07", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krta08", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krta09", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krta10", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krta11", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krta12", false, 48, 65, NULL, 0, -1, LUMPERROR}, + // Engine class B + {"krtb00", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtb01", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtb02", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtb03", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtb04", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtb05", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtb06", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtb07", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtb08", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtb09", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtb10", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtb11", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtb12", false, 48, 65, NULL, 0, -1, LUMPERROR}, + // Engine class C + {"krtc00", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtc01", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtc02", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtc03", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtc04", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtc05", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtc06", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtc07", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtc08", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtc09", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtc10", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtc11", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtc12", false, 48, 65, NULL, 0, -1, LUMPERROR}, + // Engine class D + {"krtd00", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtd01", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtd02", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtd03", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtd04", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtd05", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtd06", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtd07", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtd08", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtd09", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtd10", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtd11", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtd12", false, 48, 65, NULL, 0, -1, LUMPERROR}, + // Engine class E + {"krte00", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krte01", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krte02", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krte03", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krte04", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krte05", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krte06", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krte07", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krte08", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krte09", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krte10", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krte11", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krte12", false, 48, 65, NULL, 0, -1, LUMPERROR}, + // Engine class F + {"krtf00", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtf01", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtf02", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtf03", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtf04", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtf05", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtf06", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtf07", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtf08", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtf09", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtf10", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtf11", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtf12", false, 48, 65, NULL, 0, -1, LUMPERROR}, + // Engine class G + {"krtg00", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtg01", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtg02", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtg03", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtg04", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtg05", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtg06", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtg07", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtg08", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtg09", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtg10", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtg11", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krtg12", false, 48, 65, NULL, 0, -1, LUMPERROR}, + // Engine class H + {"krth00", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krth01", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krth02", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krth03", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krth04", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krth05", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krth06", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krth07", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krth08", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krth09", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krth10", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krth11", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krth12", false, 48, 65, NULL, 0, -1, LUMPERROR}, + // Engine class I + {"krti00", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krti01", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krti02", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krti03", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krti04", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krti05", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krti06", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krti07", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krti08", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krti09", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krti10", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krti11", false, 48, 65, NULL, 0, -1, LUMPERROR}, + {"krti12", false, 48, 65, NULL, 0, -1, LUMPERROR}, - // SRB2kart - Skin sounds - {"kwin", false, 64, 96, NULL, 0, SKSKWIN, LUMPERROR}, - {"klose", false, 64, 96, NULL, 0, SKSKLOSE, LUMPERROR}, - {"khurt1", false, 64, 96, NULL, 0, SKSKPAN1, LUMPERROR}, - {"khurt2", false, 64, 96, NULL, 0, SKSKPAN2, LUMPERROR}, - {"kattk1", false, 64, 96, NULL, 0, SKSKATK1, LUMPERROR}, - {"kattk2", false, 64, 96, NULL, 0, SKSKATK2, LUMPERROR}, - {"kbost1", false, 64, 96, NULL, 0, SKSKBST1, LUMPERROR}, - {"kbost2", false, 64, 96, NULL, 0, SKSKBST2, LUMPERROR}, - {"kslow", false, 64, 32, NULL, 0, SKSKSLOW, LUMPERROR}, - {"khitem", false, 128, 32, NULL, 0, SKSKHITM, LUMPERROR}, - {"kgloat", false, 64, 48, NULL, 0, SKSKPOWR, LUMPERROR}, + // SRB2kart - Skin sounds + {"kwin", false, 64, 96, NULL, 0, SKSKWIN, LUMPERROR}, + {"klose", false, 64, 96, NULL, 0, SKSKLOSE, LUMPERROR}, + {"khurt1", false, 64, 96, NULL, 0, SKSKPAN1, LUMPERROR}, + {"khurt2", false, 64, 96, NULL, 0, SKSKPAN2, LUMPERROR}, + {"kattk1", false, 64, 96, NULL, 0, SKSKATK1, LUMPERROR}, + {"kattk2", false, 64, 96, NULL, 0, SKSKATK2, LUMPERROR}, + {"kbost1", false, 64, 96, NULL, 0, SKSKBST1, LUMPERROR}, + {"kbost2", false, 64, 96, NULL, 0, SKSKBST2, LUMPERROR}, + {"kslow", false, 64, 32, NULL, 0, SKSKSLOW, LUMPERROR}, + {"khitem", false, 128, 32, NULL, 0, SKSKHITM, LUMPERROR}, + {"kgloat", false, 64, 48, NULL, 0, SKSKPOWR, LUMPERROR}, - // skin sounds free slots to add sounds at run time (Boris HACK!!!) - // initialized to NULL + // skin sounds free slots to add sounds at run time (Boris HACK!!!) + // initialized to NULL }; -char freeslotnames[sfx_freeslot0 + NUMSFXFREESLOTS + NUMSKINSFXSLOTS][7] = {}; +static char freeslotnames[sfx_freeslot0 + NUMSFXFREESLOTS + NUMSKINSFXSLOTS][MAXSOUNDNAME] = {}; // Prepare free sfx slots to add sfx at run time -void S_InitRuntimeSounds (void) +void S_InitRuntimeSounds(void) { sfxenum_t i; INT32 value; - char soundname[10]; for (i = sfx_freeslot0; i <= sfx_lastskinsoundslot; i++) { value = (i+1) - sfx_freeslot0; - if (value < 10) - sprintf(soundname, "fre00%d", value); - else if (value < 100) - sprintf(soundname, "fre0%d", value); - else if (value < 1000) - sprintf(soundname, "fre%d", value); - else - sprintf(soundname, "fr%d", value); + // can happen if skinlimit is too high, then this would truncate + I_Assert(value <= 0xffff); - strcpy(freeslotnames[value-1], soundname); + snprintf(freeslotnames[value-1], MAXSOUNDNAME, "fr%04x", value); S_sfx[i].name = freeslotnames[value-1]; S_sfx[i].singularity = false; S_sfx[i].priority = 0; S_sfx[i].pitch = 0; S_sfx[i].data = NULL; - S_sfx[i].length = 0; + S_sfx[i].length = 0; S_sfx[i].skinsound = -1; S_sfx[i].lumpnum = LUMPERROR; } @@ -1018,18 +1010,19 @@ sfxenum_t S_AddSoundFx(const char *name, boolean singular, INT32 flags, boolean else slot = sfx_freeslot0; - const int precache = S_CacheSound(); + const int precache = S_CacheSound(); for (i = slot; i < NUMSFX; i++) { if (!S_sfx[i].priority) { - strncpy(freeslotnames[i-sfx_freeslot0], name, 6); + snprintf(freeslotnames[i - sfx_freeslot0], MAXSOUNDNAME, "%s", name); + S_sfx[i].singularity = singular; S_sfx[i].priority = 60; S_sfx[i].pitch = flags; S_sfx[i].lumpnum = LUMPERROR; - S_sfx[i].length = 0; + S_sfx[i].length = 0; S_sfx[i].skinsound = -1; if (precache == SOUNDCACHE_PRECACHE) @@ -1040,6 +1033,7 @@ sfxenum_t S_AddSoundFx(const char *name, boolean singular, INT32 flags, boolean return i; } } + I_Error("Out of Sound Freeslots while allocating \"%s\"\nLoad less addons to fix this.", name); return 0; } diff --git a/src/sounds.h b/src/sounds.h index ea530da05..a8522f1c6 100644 --- a/src/sounds.h +++ b/src/sounds.h @@ -59,6 +59,8 @@ typedef enum #define NUMSFXFREESLOTS 1600 // Matches SOC Editor. #define NUMSKINSFXSLOTS (MAXSKINS*NUMSKINSOUNDS) +#define MAXSOUNDNAME 7 + // // SoundFX struct. // diff --git a/src/st_stuff.c b/src/st_stuff.c index 99188e919..bc7f9e3e3 100644 --- a/src/st_stuff.c +++ b/src/st_stuff.c @@ -14,6 +14,7 @@ /// Does palette indicators as well (red pain/berserk, bright pickup) #include "doomdef.h" +#include "d_main.h" #include "g_game.h" #include "g_input.h" #include "k_director.h" @@ -52,8 +53,6 @@ #include "r_fps.h" -UINT16 objectsdrawn = 0; - // dumb fade thing for director toggle tic_t directortoggletimer = 0; @@ -174,7 +173,8 @@ INT32 st_palette = 0; void ST_ResetPaletteStuff(void) { st_palette = 0; - V_SetPalette(0); + if (loaded_config) + V_SetPalette(0); } static void ST_doPaletteStuff(void) @@ -182,12 +182,12 @@ static void ST_doPaletteStuff(void) INT32 palette = 0; #ifdef HWRENDER - if (rendermode == render_opengl && !HWR_PalRenderFlashpal()) + if (rendermode == render_opengl && !HWR_ShouldUsePaletteRendering()) return; #endif if (stplyr && stplyr->flashcount) - palette = CLAMP(stplyr->flashpal, 0, 13); + palette = min(stplyr->flashpal, 13); if (palette != st_palette) { @@ -591,7 +591,7 @@ static void ST_overlayDrawer(void) char name[MAXPLAYERNAME+12]; INT32 y = (stplyrnum == 0) ? 4 : BASEVIDHEIGHT/2-12; - sprintf(name, "VIEWPOINT: %s", player_names[stplyr-players]); + snprintf(name, sizeof(name), "VIEWPOINT: %s", player_names[stplyr-players]); V_DrawRightAlignedThinString(BASEVIDWIDTH-40, y, V_HUDTRANSHALF|V_ALLOWLOWERCASE|K_calcSplitFlags(V_SNAPTOTOP|V_SNAPTOBOTTOM|V_SNAPTORIGHT), name); } else if (splitscreen) @@ -720,7 +720,7 @@ void ST_DrawDemoTitleEntry(void) static void ST_MayonakaStatic(void) { INT32 flag; - if (cv_lessflicker.value) + if (cv_lessflicker.value || cv_reducevfx.value) flag = V_70TRANS; else flag = (leveltime%2) ? V_90TRANS : V_70TRANS; diff --git a/src/st_stuff.h b/src/st_stuff.h index 8e7f8fa41..24202646a 100644 --- a/src/st_stuff.h +++ b/src/st_stuff.h @@ -134,8 +134,6 @@ typedef enum extern hudinfo_t hudinfo[NUMHUDITEMS]; -extern UINT16 objectsdrawn; - // variable to stop mayonaka static from flickering extern consvar_t cv_lessflicker; extern consvar_t cv_stagetitle; diff --git a/src/strcasestr.c b/src/strcasestr.c index d24a36e54..84bc0671e 100644 --- a/src/strcasestr.c +++ b/src/strcasestr.c @@ -23,20 +23,26 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -static inline int -trycmp (char **pp, char *cp, - const char *q, size_t qn) +#ifndef _GNU_SOURCE + +#include +#include +#include + +static inline int trycmp(char **pp, char *cp, const char *q, size_t qn) { char *p; p = (*pp); + if (strncasecmp(p, q, qn) == 0) return 0; + (*pp) = strchr(&p[1], (*cp)); + return 1; } -static inline void -swapp (char ***ppap, char ***ppbp, char **cpap, char **cpbp) +static inline void swapp(char ***ppap, char ***ppbp, char **cpap, char **cpbp) { char **pp; char *p; @@ -50,8 +56,7 @@ swapp (char ***ppap, char ***ppbp, char **cpap, char **cpbp) *cpbp = p; } -char * -nongnu_strcasestr (const char *s, const char *q) +char *nongnu_strcasestr(const char *s, const char *q) { size_t qn; @@ -73,8 +78,8 @@ nongnu_strcasestr (const char *s, const char *q) up = strchr(s, uc); lp = strchr(s, lc); - if (!( (intptr_t)up|(intptr_t)lp )) - return 0; + if (up == NULL && lp == NULL) + return NULL; if (!lp || ( up && up < lp )) { @@ -100,12 +105,14 @@ nongnu_strcasestr (const char *s, const char *q) if (trycmp(ppa, cpa, q, qn) == 0) return (*ppa); - if (!( (intptr_t)up|(intptr_t)lp )) + if (up == NULL && lp == NULL) break; if (!(*ppa) || ( (*ppb) && (*ppb) < (*ppa) )) swapp(&ppa, &ppb, &cpa, &cpb); } - return 0; + return NULL; } + +#endif diff --git a/src/v_paldeltas.h b/src/v_paldeltas.h new file mode 100644 index 000000000..30fc86dfc --- /dev/null +++ b/src/v_paldeltas.h @@ -0,0 +1,525 @@ +#ifndef H_PALDELTA +#define H_PALDELTA + +// those are the differences in palette indices between the main srb2 playpal and its white and nuke subpalettes +// this is probably not the best way of doing any of this, but it works lol + +static const INT16 pPaletteDeltaFlash[256][3] = { + { 6, 6, 6}, + { 12, 12, 12}, + { 18, 18, 18}, + { 24, 24, 24}, + { 30, 30, 30}, + { 36, 36, 36}, + { 42, 42, 42}, + { 48, 48, 48}, + { 54, 54, 54}, + { 60, 60, 60}, + { 66, 66, 66}, + { 72, 72, 72}, + { 78, 78, 78}, + { 84, 84, 84}, + { 90, 90, 90}, + { 95, 95, 95}, + { 101, 101, 101}, + { 107, 107, 107}, + { 113, 113, 113}, + { 119, 119, 119}, + { 125, 125, 125}, + { 131, 131, 131}, + { 137, 137, 137}, + { 143, 143, 143}, + { 149, 149, 149}, + { 155, 155, 155}, + { 161, 161, 161}, + { 167, 167, 167}, + { 173, 173, 173}, + { 179, 179, 179}, + { 185, 185, 185}, + { 191, 191, 191}, + { 48, 66, 84}, + { 54, 71, 89}, + { 60, 77, 95}, + { 66, 83, 100}, + { 72, 88, 105}, + { 79, 94, 111}, + { 85, 99, 117}, + { 91, 105, 123}, + { 96, 111, 129}, + { 102, 117, 135}, + { 108, 123, 141}, + { 114, 128, 146}, + { 120, 134, 152}, + { 127, 140, 158}, + { 133, 145, 163}, + { 140, 152, 170}, + { 48, 98, 134}, + { 57, 104, 137}, + { 63, 107, 140}, + { 69, 110, 143}, + { 75, 116, 146}, + { 84, 119, 149}, + { 90, 125, 152}, + { 95, 128, 155}, + { 101, 131, 158}, + { 110, 137, 161}, + { 119, 140, 164}, + { 128, 143, 167}, + { 134, 149, 170}, + { 143, 155, 173}, + { 152, 158, 176}, + { 158, 164, 179}, + { 0, 15, 24}, + { 0, 21, 33}, + { 0, 27, 42}, + { 0, 33, 51}, + { 0, 36, 57}, + { 0, 42, 66}, + { 0, 48, 75}, + { 0, 51, 81}, + { 0, 57, 93}, + { 6, 63, 98}, + { 12, 69, 104}, + { 18, 75, 110}, + { 24, 81, 116}, + { 30, 87, 122}, + { 36, 93, 128}, + { 39, 95, 131}, + { 0, 12, 26}, + { 0, 26, 52}, + { 0, 39, 78}, + { 0, 52, 102}, + { 0, 65, 127}, + { 0, 78, 150}, + { 0, 91, 172}, + { 0, 102, 191}, + { 9, 108, 191}, + { 19, 114, 191}, + { 29, 120, 191}, + { 39, 127, 191}, + { 48, 133, 191}, + { 58, 139, 191}, + { 68, 145, 191}, + { 78, 150, 191}, + { 0, 0, 12}, + { 0, 0, 36}, + { 0, 0, 60}, + { 0, 0, 84}, + { 0, 0, 107}, + { 0, 0, 131}, + { 0, 0, 155}, + { 0, 0, 179}, + { 0, 0, 191}, + { 36, 36, 191}, + { 60, 60, 191}, + { 84, 84, 191}, + { 107, 107, 191}, + { 131, 131, 191}, + { 155, 155, 191}, + { 179, 179, 191}, + { 0, 0, 104}, + { 15, 27, 125}, + { 30, 51, 140}, + { 45, 75, 155}, + { 60, 98, 167}, + { 75, 122, 176}, + { 90, 140, 185}, + { 104, 158, 191}, + { 0, 0, 0}, + { 0, 24, 24}, + { 0, 48, 48}, + { 0, 72, 72}, + { 0, 95, 95}, + { 0, 119, 119}, + { 0, 143, 143}, + { 0, 167, 167}, + { 0, 191, 191}, + { 12, 191, 191}, + { 24, 191, 191}, + { 36, 191, 191}, + { 48, 191, 191}, + { 60, 191, 191}, + { 72, 191, 191}, + { 84, 191, 191}, + { 95, 191, 191}, + { 107, 191, 191}, + { 119, 191, 191}, + { 131, 191, 191}, + { 143, 191, 191}, + { 155, 191, 191}, + { 167, 191, 191}, + { 179, 191, 191}, + { 0, 54, 54}, + { 9, 69, 69}, + { 18, 84, 84}, + { 27, 98, 98}, + { 39, 110, 110}, + { 48, 122, 122}, + { 57, 131, 131}, + { 66, 143, 143}, + { 85, 156, 191}, + { 91, 161, 191}, + { 96, 166, 191}, + { 102, 172, 191}, + { 108, 177, 191}, + { 114, 182, 191}, + { 120, 187, 191}, + { 127, 191, 191}, + { 101, 0, 131}, + { 106, 11, 134}, + { 111, 23, 138}, + { 117, 35, 142}, + { 123, 47, 145}, + { 129, 59, 149}, + { 134, 71, 153}, + { 140, 83, 157}, + { 145, 95, 160}, + { 151, 106, 164}, + { 157, 118, 168}, + { 162, 130, 172}, + { 168, 142, 175}, + { 173, 154, 179}, + { 179, 166, 183}, + { 185, 179, 187}, + { 24, 0, 65}, + { 42, 20, 80}, + { 61, 41, 95}, + { 79, 61, 110}, + { 97, 82, 124}, + { 115, 101, 139}, + { 135, 123, 154}, + { 153, 143, 169}, + { 191, 0, 191}, + { 191, 24, 191}, + { 191, 48, 191}, + { 191, 72, 191}, + { 191, 95, 191}, + { 191, 119, 191}, + { 191, 143, 191}, + { 191, 167, 191}, + { 0, 107, 0}, + { 0, 191, 0}, + { 24, 191, 24}, + { 48, 191, 48}, + { 72, 191, 72}, + { 95, 191, 95}, + { 119, 191, 119}, + { 143, 191, 143}, + { 16, 16, 9}, + { 44, 44, 22}, + { 73, 73, 36}, + { 101, 101, 51}, + { 127, 127, 66}, + { 142, 142, 93}, + { 156, 156, 121}, + { 170, 170, 151}, + { 31, 10, 0}, + { 48, 15, 0}, + { 64, 21, 0}, + { 79, 25, 0}, + { 95, 30, 0}, + { 111, 36, 0}, + { 127, 41, 0}, + { 143, 48, 0}, + { 149, 73, 24}, + { 155, 84, 48}, + { 161, 101, 72}, + { 167, 119, 95}, + { 191, 48, 48}, + { 191, 95, 95}, + { 191, 119, 119}, + { 191, 143, 143}, + { 18, 18, 0}, + { 42, 42, 0}, + { 61, 61, 0}, + { 86, 86, 0}, + { 104, 104, 0}, + { 129, 129, 0}, + { 154, 154, 0}, + { 172, 172, 0}, + { 191, 191, 0}, + { 191, 191, 18}, + { 191, 191, 36}, + { 191, 191, 55}, + { 191, 191, 74}, + { 191, 191, 92}, + { 191, 191, 110}, + { 191, 191, 129}, + { 191, 191, 131}, + { 191, 191, 143}, + { 191, 191, 149}, + { 191, 191, 161}, + { 191, 191, 167}, + { 191, 191, 179}, + { 191, 191, 185}, + { 191, 0, 0}, + { 36, 95, 36}, + { 54, 107, 54}, + { 72, 119, 72}, + { 90, 131, 90}, + { 107, 143, 107}, + { 125, 155, 125}, + { 143, 167, 143}, + { 161, 179, 161} +}; + +static const INT16 pPaletteDeltaNuke[256][3] = { + { 6,-133,-133}, + { 12,-125,-125}, + { 18,-117,-117}, + { 24,-109,-109}, + { 30,-101,-101}, + { 36, -93, -93}, + { 42, -85, -85}, + { 48, -77, -77}, + { 54, -69, -69}, + { 60, -61, -61}, + { 66, -53, -53}, + { 72, -45, -45}, + { 78, -37, -37}, + { 84, -29, -29}, + { 90, -21, -21}, + { 95, -14, -14}, + { 101, -6, -6}, + { 107, 2, 2}, + { 113, 10, 10}, + { 119, 18, 18}, + { 125, 26, 26}, + { 131, 34, 34}, + { 137, 42, 42}, + { 143, 50, 50}, + { 149, 58, 58}, + { 155, 66, 66}, + { 161, 74, 74}, + { 167, 82, 82}, + { 173, 90, 90}, + { 179, 98, 98}, + { 185, 106, 106}, + { 191, 113, 113}, + { 48, -53, -29}, + { 54, -46, -22}, + { 60, -38, -14}, + { 66, -30, -7}, + { 72, -23, 0}, + { 79, -15, 8}, + { 85, -8, 16}, + { 91, -1, 23}, + { 96, 7, 31}, + { 102, 15, 39}, + { 108, 23, 47}, + { 114, 30, 54}, + { 120, 38, 62}, + { 127, 46, 70}, + { 133, 53, 77}, + { 140, 62, 86}, + { 48, -10, 38}, + { 57, -2, 42}, + { 63, 2, 46}, + { 69, 6, 50}, + { 75, 14, 54}, + { 84, 18, 58}, + { 90, 26, 62}, + { 95, 30, 66}, + { 101, 34, 70}, + { 110, 42, 74}, + { 119, 46, 78}, + { 128, 50, 82}, + { 134, 58, 86}, + { 143, 66, 90}, + { 152, 70, 94}, + { 158, 78, 98}, + { 0,-121,-109}, + { 0,-113, -97}, + { 0,-105, -85}, + { 0, -97, -73}, + { 0, -93, -65}, + { 0, -85, -53}, + { 0, -77, -41}, + { 0, -73, -33}, + { 0, -65, -17}, + { 6, -57, -10}, + { 12, -49, -2}, + { 18, -41, 6}, + { 24, -33, 14}, + { 30, -25, 22}, + { 36, -17, 30}, + { 39, -14, 34}, + { 0,-124,-106}, + { 0,-106, -71}, + { 0, -89, -37}, + { 0, -71, -4}, + { 0, -54, 28}, + { 0, -37, 59}, + { 0, -20, 88}, + { 0, -4, 113}, + { 9, 4, 113}, + { 19, 12, 113}, + { 29, 20, 113}, + { 39, 28, 113}, + { 48, 36, 113}, + { 58, 44, 113}, + { 68, 52, 113}, + { 78, 59, 113}, + { 0,-141,-125}, + { 0,-141, -93}, + { 0,-141, -61}, + { 0,-141, -29}, + { 0,-141, 2}, + { 0,-141, 34}, + { 0,-141, 66}, + { 0,-141, 98}, + { 0,-141, 113}, + { 36, -93, 113}, + { 60, -61, 113}, + { 84, -29, 113}, + { 107, 2, 113}, + { 131, 34, 113}, + { 155, 66, 113}, + { 179, 98, 113}, + { 0,-141, -2}, + { 15,-105, 26}, + { 30, -73, 46}, + { 45, -41, 66}, + { 60, -10, 82}, + { 75, 22, 94}, + { 90, 46, 106}, + { 104, 70, 113}, + { 0,-141,-141}, + { 0,-109,-109}, + { 0, -77, -77}, + { 0, -45, -45}, + { 0, -14, -14}, + { 0, 18, 18}, + { 0, 50, 50}, + { 0, 82, 82}, + { 0, 113, 113}, + { 12, 113, 113}, + { 24, 113, 113}, + { 36, 113, 113}, + { 48, 113, 113}, + { 60, 113, 113}, + { 72, 113, 113}, + { 84, 113, 113}, + { 95, 113, 113}, + { 107, 113, 113}, + { 119, 113, 113}, + { 131, 113, 113}, + { 143, 113, 113}, + { 155, 113, 113}, + { 167, 113, 113}, + { 179, 113, 113}, + { 0, -69, -69}, + { 9, -49, -49}, + { 18, -29, -29}, + { 27, -10, -10}, + { 39, 6, 6}, + { 48, 22, 22}, + { 57, 34, 34}, + { 66, 50, 50}, + { 85, 67, 113}, + { 91, 74, 113}, + { 96, 81, 113}, + { 102, 88, 113}, + { 108, 95, 113}, + { 114, 102, 113}, + { 120, 108, 113}, + { 127, 113, 113}, + { 101,-141, 34}, + { 106,-126, 38}, + { 111,-110, 43}, + { 117, -94, 48}, + { 123, -78, 53}, + { 129, -62, 58}, + { 134, -46, 63}, + { 140, -30, 68}, + { 145, -14, 73}, + { 151, 1, 78}, + { 157, 17, 83}, + { 162, 33, 88}, + { 168, 49, 93}, + { 173, 65, 98}, + { 179, 81, 103}, + { 185, 98, 109}, + { 24,-141, -54}, + { 42,-114, -34}, + { 61, -86, -14}, + { 79, -59, 6}, + { 97, -32, 25}, + { 115, -6, 45}, + { 135, 23, 65}, + { 153, 50, 84}, + { 191,-141, 113}, + { 191,-109, 113}, + { 191, -77, 113}, + { 191, -45, 113}, + { 191, -14, 113}, + { 191, 18, 113}, + { 191, 50, 113}, + { 191, 82, 113}, + { 0, 2,-141}, + { 0, 113,-141}, + { 24, 113,-109}, + { 48, 113, -77}, + { 72, 113, -45}, + { 95, 113, -14}, + { 119, 113, 18}, + { 143, 113, 50}, + { 16,-119,-129}, + { 44, -82,-111}, + { 73, -43, -92}, + { 101, -6, -73}, + { 127, 29, -53}, + { 142, 48, -17}, + { 156, 67, 21}, + { 170, 86, 61}, + { 31,-127,-141}, + { 48,-121,-141}, + { 64,-113,-141}, + { 79,-107,-141}, + { 95,-100,-141}, + { 111, -93,-141}, + { 127, -86,-141}, + { 143, -77,-141}, + { 149, -43,-109}, + { 155, -29, -77}, + { 161, -6, -45}, + { 167, 18, -14}, + { 191, -77, -77}, + { 191, -14, -14}, + { 191, 18, 18}, + { 191, 50, 50}, + { 18,-117,-141}, + { 42, -84,-141}, + { 61, -59,-141}, + { 86, -26,-141}, + { 104, -2,-141}, + { 129, 31,-141}, + { 154, 64,-141}, + { 172, 89,-141}, + { 191, 113,-141}, + { 191, 113,-117}, + { 191, 113, -92}, + { 191, 113, -67}, + { 191, 113, -42}, + { 191, 113, -18}, + { 191, 113, 6}, + { 191, 113, 31}, + { 191, 113, 34}, + { 191, 113, 50}, + { 191, 113, 58}, + { 191, 113, 74}, + { 191, 113, 82}, + { 191, 113, 98}, + { 191, 113, 106}, + { 191,-141,-141}, + { 36, -14, -93}, + { 54, 2, -69}, + { 72, 18, -45}, + { 90, 34, -21}, + { 107, 50, 2}, + { 125, 66, 26}, + { 143, 82, 50}, + { 161, 98, 74} +}; + +#endif diff --git a/src/v_video.c b/src/v_video.c index 213db7bfc..5c98d8e52 100644 --- a/src/v_video.c +++ b/src/v_video.c @@ -15,6 +15,7 @@ #include "doomdef.h" #include "d_main.h" +#include "g_game.h" #include "r_local.h" #include "p_local.h" #include "v_video.h" @@ -90,6 +91,7 @@ consvar_t cv_menucaps = {"menucaps", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NUL // local copy of the palette for V_GetColor() RGBA_t *pLocalPalette = NULL; RGBA_t *pGammaCorrectedPalette = NULL; +static RGBA_t *pFallbackFlashPal = NULL; static size_t currentPaletteSize; @@ -408,6 +410,61 @@ UINT32 V_GammaCorrect(UINT32 input, double power) return result.rgba; } +#include "v_paldeltas.h" +// remaps a palette with given "deltas" +// this is used with premade deltas between the srb2 palette and its both flashpals +// so we may approximate generate our own, should the current palette miss them +static void ApplyPaletteDelta(const RGBA_t *pal_in, RGBA_t *pal_out, const INT16 pal_delta[][3]) +{ + size_t i; + + for (i = 0; i < 256; i++) + { + INT16 r = (INT16)pal_in[i].s.red + pal_delta[i][0]; + INT16 g = (INT16)pal_in[i].s.green + pal_delta[i][1]; + INT16 b = (INT16)pal_in[i].s.blue + pal_delta[i][2]; + pal_out[i].s.red = (UINT8)CLAMP(r, 0, 255); + pal_out[i].s.green = (UINT8)CLAMP(g, 0, 255); + pal_out[i].s.blue = (UINT8)CLAMP(b, 0, 255); + pal_out[i].s.alpha = 0xFF; // pal_in[i].s.alpha + } +} + +static void GenerateFlashPalettes(void) +{ + size_t i; + static const size_t palsize = (2*256); // two flashpals + RGBA_t *pFlashPalGammaCorrectedPalette = NULL; + + // generate flashpalettes if the current palette does not provide any subpalettes + if (currentPaletteSize >= (14 * (256 * 3))) // 14 palettes are in playpal + { + return; + } + + CONS_Debug(DBG_RENDER, "Current palette does not provide enough subpalettes for flashpalettes to work!\nCreating fallback palettes...\n"); + + pFallbackFlashPal = Z_Malloc(sizeof(*pFallbackFlashPal)*palsize, PU_STATIC, NULL); + pFlashPalGammaCorrectedPalette = Z_Malloc(sizeof (*pFlashPalGammaCorrectedPalette)*palsize, PU_STATIC, NULL); + + // apply our deltas to the palettes to get the white and red "flashes" + ApplyPaletteDelta(pLocalPalette, pFallbackFlashPal, pPaletteDeltaFlash); + ApplyPaletteDelta(pLocalPalette, pFallbackFlashPal+256, pPaletteDeltaNuke); + + // apply colour and gamma correction if needed + if (Cubeapply) + { + for (i = 0; i < palsize; i++) + { + pFlashPalGammaCorrectedPalette[i].rgba = V_GammaDecode(pFallbackFlashPal[i].rgba); + V_CubeApply(&pFlashPalGammaCorrectedPalette[i]); + pFallbackFlashPal[i].rgba = V_GammaEncode(pFlashPalGammaCorrectedPalette[i].rgba); + } + } + + Z_Free(pFlashPalGammaCorrectedPalette); +} + // keep a copy of the palette so that we can get the RGB value for a color index at any time. static void LoadPalette(const char *lumpname) { @@ -427,6 +484,8 @@ static void LoadPalette(const char *lumpname) Z_Free(pLocalPalette); Z_Free(pGammaCorrectedPalette); + Z_Free(pFallbackFlashPal); + pFallbackFlashPal = NULL; pLocalPalette = Z_Malloc(sizeof (*pLocalPalette)*palsize, PU_STATIC, NULL); pGammaCorrectedPalette = Z_Malloc(sizeof (*pGammaCorrectedPalette)*palsize, PU_STATIC, NULL); @@ -446,12 +505,19 @@ static void LoadPalette(const char *lumpname) pLocalPalette[i].s.alpha = 0xFF; pGammaCorrectedPalette[i].rgba = V_GammaDecode(pLocalPalette[i].rgba); + } - if (!Cubeapply) - continue; + GenerateFlashPalettes(); - V_CubeApply(&pGammaCorrectedPalette[i]); - pLocalPalette[i].rgba = V_GammaEncode(pGammaCorrectedPalette[i].rgba); + // gotta apply any colour and gamma adjustments afterwards + // so we dont double apply it to the generated flashpals + if (Cubeapply) + { + for (i = 0; i < palsize; i++) + { + V_CubeApply(&pGammaCorrectedPalette[i]); + pLocalPalette[i].rgba = V_GammaEncode(pGammaCorrectedPalette[i].rgba); + } } } @@ -464,7 +530,7 @@ void V_CubeApply(RGBA_t *input) if (!Cubeapply) return; - linear = ((*input).s.red/255.0); + linear = ((*input).s.red/255.0f); #define dolerp(e1, e2) ((1 - linear)*e1 + linear*e2) for (q = 0; q < 3; q++) { @@ -474,21 +540,21 @@ void V_CubeApply(RGBA_t *input) working[3][q] = dolerp(Cubepal[0][1][1][q], Cubepal[1][1][1][q]); } - linear = ((*input).s.green/255.0); + linear = ((*input).s.green/255.0f); for (q = 0; q < 3; q++) { working[0][q] = dolerp(working[0][q], working[1][q]); working[1][q] = dolerp(working[2][q], working[3][q]); } - linear = ((*input).s.blue/255.0); + linear = ((*input).s.blue/255.0f); for (q = 0; q < 3; q++) { working[0][q] = 255*dolerp(working[0][q], working[1][q]); if (working[0][q] > 255.0f) working[0][q] = 255.0f; else if (working[0][q] < 0.0f) - working[0][q] = 0.0; + working[0][q] = 0.0f; } #undef dolerp @@ -515,13 +581,19 @@ const char *GetPalette(void) if (user && user[0]) { - if (W_CheckNumForName(user) == LUMPERROR) + const lumpnum_t palnum = W_CheckNumForName(user); + + if (palnum == LUMPERROR) { CONS_Alert(CONS_WARNING, "cv_palette %s lump does not exist\n", user); } + else if (W_LumpLength(palnum) % (256 * 3) != 0) // not divisable by 768, so most def not a valid palette, idk if theres a better way to check this + { + CONS_Alert(CONS_WARNING, "cv_palette %s is not a valid palette lump\n", user); + } else { - return cv_palette.string; + return user; } } @@ -542,35 +614,60 @@ void V_ReloadPalette(void) // -------------+ void V_SetPalette(INT32 palettenum) { + RGBA_t *pal = NULL; + if (!pLocalPalette) V_ReloadPalette(); -#ifdef HWRENDER - if (rendermode == render_soft || - (rendermode == render_opengl && HWR_ShouldUsePaletteRendering())) // opengl without paletterendering hates subpalettes -#endif + if (palettenum == 0) { - if (palettenum == 0) +#ifdef HWRENDER + if (rendermode == render_soft || + (rendermode == render_opengl && HWR_ShouldUsePaletteRendering())) // opengl without paletterendering hates subpalettes +#endif { palettenum = cv_palettenum.value; - - if (palettenum * 256U > currentPaletteSize - 256) - { - CONS_Alert(CONS_WARNING, "cv_palettenum %d out of range\n", palettenum); - palettenum = 0; - } } } + // in many cases custom palettes do not provide the needed subpalettes for flashpals to work + // before this would mean the renderer gets passed random data out of allocated memory bounds + // which was not very cool :chonkbuncle: + // gladly 2.1 only actually has 2 different subpalettes + // one for "white flash" and one red/pinkish one for nuke + // since we checked the palette earlier we should have generated those ourselves + if (((size_t)palettenum >= currentPaletteSize / (256 * 3))) + { + CONS_Debug(DBG_RENDER, "palettenum %d out of range\n", palettenum); + + // if for some reason we did not generate flashpals + // just fall back to the main palette i guess? + if (pFallbackFlashPal != NULL) + { + if (palettenum == PAL_NUKE) + pal = &pFallbackFlashPal[256]; + else + pal = pFallbackFlashPal; + } + else + { + pal = pLocalPalette; + } + } + else + { + pal = &pLocalPalette[palettenum*256]; + } + #ifdef HWRENDER if (rendermode == render_opengl) - HWR_SetPalette(&pLocalPalette[palettenum*256]); + HWR_SetPalette(pal); #if defined (__unix__) || defined (UNIXCOMMON) || defined (HAVE_SDL) else #endif #endif if (rendermode != render_none) - I_SetPalette(&pLocalPalette[palettenum*256]); + I_SetPalette(pal); } void V_SetPaletteLump(const char *pal) @@ -586,6 +683,7 @@ static void CV_palette_OnChange(void) { if (!loaded_config) return; + // reload palette // recalculate Color Cube V_ReloadPalette(); @@ -1473,8 +1571,8 @@ void V_DrawFillConsoleMap(INT32 x, INT32 y, INT32 w, INT32 h, INT32 c) { // mpc 12-04-2018 const UINT8 *fadetable = ((UINT8 *)transtables + ((alphalevel-1)<y) ? y : x - w = clip(w,vid.width); - h = clip(h,vid.height); + w = clip(w, vid.width); + h = clip(h, vid.height); #undef clip for (v = 0; v < h; v++, dest += vid.width) { @@ -1741,6 +1839,7 @@ void V_DrawHorizontallyScaledFullScreenPatch(patch_t *patch) void V_DrawVhsEffect(boolean rewind) { fixed_t uby, dby; + // upbary is the bar going from top to bottom for some reason static fixed_t upbary = 100*FRACUNIT, downbary = 150*FRACUNIT; UINT8 barsize, updistort, downdistort; @@ -1755,20 +1854,27 @@ void V_DrawVhsEffect(boolean rewind) #endif SINT8 offs; - barsize = vid.dup << 5; - updistort = vid.dup << (rewind ? 5 : 3); + if (cv_reducevfx.value) + return; + + barsize = vid.udup << 5; + updistort = vid.udup << (rewind ? 5 : 3); downdistort = updistort >> 1; if (rewind) V_DrawVhsEffect(false); // experimentation - upbary -= renderdeltatics * (vid.dup * (rewind ? 3 : 1.8f)); - downbary += renderdeltatics * (vid.dup * (rewind ? 2 : 1)); + upbary -= renderdeltatics * (fixed_t)(vid.udup * (rewind ? 3 : 1.8f)); + downbary += renderdeltatics * (vid.udup * (rewind ? 2 : 1)); if (upbary < -barsize*FRACUNIT) upbary = vid.height << FRACBITS; + if (upbary > vid.height << FRACBITS) + upbary = -barsize*FRACUNIT; if (downbary > vid.height << FRACBITS) downbary = -barsize*FRACUNIT; + if (downbary < -barsize*FRACUNIT) + downbary = vid.height << FRACBITS; uby = upbary >> FRACBITS; dby = downbary >> FRACBITS; @@ -2105,6 +2211,7 @@ void V_DrawString(INT32 x, INT32 y, INT32 option, const char *string) { if (!*ch) break; + if (*ch & 0x80) //color parsing -x 2.16.09 { // manually set flags override color codes @@ -2115,6 +2222,7 @@ void V_DrawString(INT32 x, INT32 y, INT32 option, const char *string) } continue; } + if (*ch == '\n') { cx = x; @@ -2149,6 +2257,7 @@ void V_DrawString(INT32 x, INT32 y, INT32 option, const char *string) if (cx > scrwidth) break; + if (cx+left + w < 0) //left boundary check { cx += w; @@ -2206,6 +2315,7 @@ void V_DrawKartString(INT32 x, INT32 y, INT32 option, const char *string) { if (!*ch) break; + if (*ch & 0x80) //color parsing -x 2.16.09 { // manually set flags override color codes @@ -2216,6 +2326,7 @@ void V_DrawKartString(INT32 x, INT32 y, INT32 option, const char *string) } continue; } + if (*ch == '\n') { cx = x; @@ -2250,6 +2361,7 @@ void V_DrawKartString(INT32 x, INT32 y, INT32 option, const char *string) if (cx > scrwidth) break; + if (cx+left + w < 0) //left boundary check { cx += w; @@ -2324,6 +2436,7 @@ void V_DrawSmallString(INT32 x, INT32 y, INT32 option, const char *string) { if (!*ch) break; + if (*ch & 0x80) //color parsing -x 2.16.09 { // manually set flags override color codes @@ -2334,6 +2447,7 @@ void V_DrawSmallString(INT32 x, INT32 y, INT32 option, const char *string) } continue; } + if (*ch == '\n') { cx = x; @@ -2442,6 +2556,7 @@ void V_DrawThinString(INT32 x, INT32 y, INT32 option, const char *string) { if (!*ch) break; + if (*ch & 0x80) //color parsing -x 2.16.09 { // manually set flags override color codes @@ -2452,6 +2567,7 @@ void V_DrawThinString(INT32 x, INT32 y, INT32 option, const char *string) } continue; } + if (*ch == '\n') { cx = x; @@ -2610,6 +2726,7 @@ void V_DrawSmallStringAtFixed(fixed_t x, fixed_t y, INT32 option, const char *st INT32 charflags = 0; const UINT8 *colormap = NULL; INT32 spacewidth = 2, charwidth = 0; + INT32 lowercase = (option & V_ALLOWLOWERCASE); option &= ~V_FLIP; // which is also shared with V_ALLOWLOWERCASE... @@ -2630,6 +2747,7 @@ void V_DrawSmallStringAtFixed(fixed_t x, fixed_t y, INT32 option, const char *st scrwidth *= vid.dup; charflags = (option & V_CHARCOLORMASK); + colormap = V_GetStringColormap(charflags); switch (option & V_SPACINGMASK) { @@ -2654,7 +2772,11 @@ void V_DrawSmallStringAtFixed(fixed_t x, fixed_t y, INT32 option, const char *st { // manually set flags override color codes if (!(option & V_CHARCOLORMASK)) + { charflags = ((*ch & 0x7f) << V_CHARCOLORSHIFT) & V_CHARCOLORMASK; + colormap = V_GetStringColormap(charflags); + } + continue; } @@ -2698,7 +2820,6 @@ void V_DrawSmallStringAtFixed(fixed_t x, fixed_t y, INT32 option, const char *st continue; } - colormap = V_GetStringColormap(charflags); V_DrawFixedPatch(cx + (center<= CRED_FONTSIZE) @@ -3070,7 +3200,9 @@ INT32 V_LevelNameWidth(const char *string) INT32 c, w = 0; size_t i; - for (i = 0; i < strlen(string); i++) + const size_t strlength = strlen(string); + + for (i = 0; i < strlength; i++) { c = toupper(string[i]) - LT_FONTSTART; if (c < 0 || c >= LT_FONTSIZE || !lt_font[c]) @@ -3089,7 +3221,9 @@ INT32 V_LevelNameHeight(const char *string) INT32 c, w = 0; size_t i; - for (i = 0; i < strlen(string); i++) + const size_t strlength = strlen(string); + + for (i = 0; i < strlength; i++) { c = toupper(string[i]) - LT_FONTSTART; if (c < 0 || c >= LT_FONTSIZE || !lt_font[c]) @@ -3131,7 +3265,7 @@ INT32 V_SubStringWidth(const char *string, INT32 length, INT32 option) break; } - for (i = 0; string[i] && i < length; i++) + for (i = 0; i < length && string[i]; i++) { c = string[i]; if ((UINT8)c >= 0x80 && (UINT8)c <= 0x8F) //color parsing! -Inuyasha 2.16.09 @@ -3176,7 +3310,7 @@ INT32 V_SmallSubStringWidth(const char *string, INT32 length, INT32 option) break; } - for (i = 0; string[i] && i < length; i++) + for (i = 0; i < length && string[i]; i++) { c = string[i]; if ((UINT8)c >= 0x80 && (UINT8)c <= 0x8F) //color parsing! -Inuyasha 2.16.09 @@ -3225,7 +3359,7 @@ INT32 V_ThinSubStringWidth(const char *string, INT32 length, INT32 option) break; } - for (i = 0; string[i] && i < length; i++) + for (i = 0; i < length && string[i]; i++) { c = string[i]; if ((UINT8)c >= 0x80 && (UINT8)c <= 0x8F) //color parsing! -Inuyasha 2.16.09 @@ -3294,167 +3428,6 @@ INT32 V_SubStringLengthToFit(const char *string, INT32 width, INT32 option) return max(i-1, 0); } -char V_GetSkincolorChar(INT32 color) -{ - char cstart = 0x80; - - switch (color) - { - case SKINCOLOR_WHITE: - case SKINCOLOR_SILVER: - case SKINCOLOR_SLATE: - cstart = 0x80; // White - break; - - case SKINCOLOR_GREY: - case SKINCOLOR_NICKEL: - case SKINCOLOR_BLACK: - case SKINCOLOR_SKUNK: - case SKINCOLOR_JET: - cstart = 0x86; // V_GRAYMAP - break; - - case SKINCOLOR_SEPIA: - case SKINCOLOR_BEIGE: - case SKINCOLOR_WALNUT: - case SKINCOLOR_BROWN: - case SKINCOLOR_LEATHER: - case SKINCOLOR_RUST: - case SKINCOLOR_WRISTWATCH: - cstart = 0x8e; // V_BROWNMAP - break; - - case SKINCOLOR_FAIRY: - case SKINCOLOR_SALMON: - case SKINCOLOR_PINK: - case SKINCOLOR_ROSE: - case SKINCOLOR_BRICK: - case SKINCOLOR_LEMONADE: - case SKINCOLOR_BUBBLEGUM: - case SKINCOLOR_LILAC: - cstart = 0x8d; // V_PINKMAP - break; - - case SKINCOLOR_CINNAMON: - case SKINCOLOR_RUBY: - case SKINCOLOR_RASPBERRY: - case SKINCOLOR_CHERRY: - case SKINCOLOR_RED: - case SKINCOLOR_CRIMSON: - case SKINCOLOR_MAROON: - case SKINCOLOR_FLAME: - case SKINCOLOR_SCARLET: - case SKINCOLOR_KETCHUP: - cstart = 0x85; // V_REDMAP - break; - - case SKINCOLOR_DAWN: - case SKINCOLOR_SUNSET: - case SKINCOLOR_CREAMSICLE: - case SKINCOLOR_ORANGE: - case SKINCOLOR_PUMPKIN: - case SKINCOLOR_ROSEWOOD: - case SKINCOLOR_BURGUNDY: - case SKINCOLOR_TANGERINE: - cstart = 0x87; // V_ORANGEMAP - break; - - case SKINCOLOR_PEACH: - case SKINCOLOR_CARAMEL: - case SKINCOLOR_CREAM: - cstart = 0x8f; // V_PEACHMAP - break; - - case SKINCOLOR_GOLD: - case SKINCOLOR_ROYAL: - case SKINCOLOR_BRONZE: - case SKINCOLOR_COPPER: - case SKINCOLOR_THUNDER: - cstart = 0x8a; // V_GOLDMAP - break; - - case SKINCOLOR_POPCORN: - case SKINCOLOR_QUARRY: - case SKINCOLOR_YELLOW: - case SKINCOLOR_MUSTARD: - case SKINCOLOR_CROCODILE: - case SKINCOLOR_OLIVE: - cstart = 0x82; // V_YELLOWMAP - break; - - case SKINCOLOR_ARTICHOKE: - case SKINCOLOR_VOMIT: - case SKINCOLOR_GARDEN: - case SKINCOLOR_TEA: - case SKINCOLOR_PISTACHIO: - cstart = 0x8b; // V_TEAMAP - break; - - case SKINCOLOR_LIME: - case SKINCOLOR_HANDHELD: - case SKINCOLOR_MOSS: - case SKINCOLOR_CAMOUFLAGE: - case SKINCOLOR_ROBOHOOD: - case SKINCOLOR_MINT: - case SKINCOLOR_GREEN: - case SKINCOLOR_PINETREE: - case SKINCOLOR_EMERALD: - case SKINCOLOR_SWAMP: - case SKINCOLOR_DREAM: - case SKINCOLOR_PLAGUE: - case SKINCOLOR_ALGAE: - cstart = 0x83; // V_GREENMAP - break; - - case SKINCOLOR_CARIBBEAN: - case SKINCOLOR_AZURE: - case SKINCOLOR_AQUA: - case SKINCOLOR_TEAL: - case SKINCOLOR_CYAN: - case SKINCOLOR_JAWZ: - case SKINCOLOR_CERULEAN: - case SKINCOLOR_NAVY: - case SKINCOLOR_SAPPHIRE: - cstart = 0x88; // V_SKYMAP - break; - - case SKINCOLOR_PIGEON: - case SKINCOLOR_PLATINUM: - case SKINCOLOR_STEEL: - cstart = 0x8c; // V_STEELMAP - break; - - case SKINCOLOR_PERIWINKLE: - case SKINCOLOR_BLUE: - case SKINCOLOR_BLUEBERRY: - case SKINCOLOR_NOVA: - cstart = 0x84; // V_BLUEMAP - break; - - case SKINCOLOR_ULTRAVIOLET: - case SKINCOLOR_PURPLE: - case SKINCOLOR_FUCHSIA: - cstart = 0x81; // V_PURPLEMAP - break; - - case SKINCOLOR_PASTEL: - case SKINCOLOR_MOONSLAM: - case SKINCOLOR_DUSK: - case SKINCOLOR_TOXIC: - case SKINCOLOR_MAUVE: - case SKINCOLOR_LAVENDER: - case SKINCOLOR_BYZANTIUM: - case SKINCOLOR_POMEGRANATE: - cstart = 0x89; // V_LAVENDERMAP - break; - - default: - break; - } - - return cstart; -} - INT32 V_SkinColorToHighlightcolor(skincolors_t color) { switch (color) @@ -3633,127 +3606,128 @@ void V_DoPostProcessor(INT32 view, INT32 param) UINT8 *tmpscr = vid.screens[4]; UINT8 *srcscr = vid.screens[0]; - if (thiscam->postimg & POSTIMG_WATER) + if (!cv_reducevfx.value) { - INT32 y; - // Set disStart to a range from 0 to FINEANGLE, incrementing by 128 per tic - angle_t disStart = (((leveltime-1)*128) + (R_GetTimeFrac(RTF_LEVEL) / (FRACUNIT/128))) & FINEMASK; - INT32 newpix; - INT32 sine; - //UINT8 *transme = transtables + ((tr_trans50-1)<postimg & POSTIMG_WATER) { - sine = (FINESINE(disStart)*5)>>FRACBITS; - newpix = abs(sine); + INT32 y; + // Set disStart to a range from 0 to FINEANGLE, incrementing by 128 per tic + angle_t disStart = (((leveltime-1)*128) + (R_GetTimeFrac(RTF_LEVEL) / (FRACUNIT/128))) & FINEMASK; + INT32 newpix; + INT32 sine; + //UINT8 *transme = transtables + ((tr_trans50-1)<>FRACBITS; + newpix = abs(sine); - // Cleanup edge - while (newpix) + if (sine < 0) { - tmpscr[(y*vid.width)+xoffset+newpix] = srcscr[(y*vid.width)+xoffset]; - newpix--; - } - } - else - { - memcpy(&tmpscr[(y*vid.width)+xoffset+0], &srcscr[(y*vid.width)+xoffset+sine], viewwidth-newpix); + memcpy(&tmpscr[(y*vid.width)+xoffset+newpix], &srcscr[(y*vid.width)+xoffset], viewwidth-newpix); - // Cleanup edge - while (newpix) - { - tmpscr[(y*vid.width)+xoffset+viewwidth-newpix] = srcscr[(y*vid.width)+xoffset+(viewwidth-1)]; - newpix--; + // Cleanup edge + while (newpix) + { + tmpscr[(y*vid.width)+xoffset+newpix] = srcscr[(y*vid.width)+xoffset]; + newpix--; + } } + else + { + memcpy(&tmpscr[(y*vid.width)+xoffset+0], &srcscr[(y*vid.width)+xoffset+sine], viewwidth-newpix); + + // Cleanup edge + while (newpix) + { + tmpscr[(y*vid.width)+xoffset+viewwidth-newpix] = srcscr[(y*vid.width)+xoffset+(viewwidth-1)]; + newpix--; + } + } + + /* + Unoptimized version + for (x = 0; x < vid.width; x++) + { + newpix = (x + sine); + + if (newpix < 0) + newpix = 0; + else if (newpix >= vid.width) + newpix = vid.width-1; + + tmpscr[y*vid.width + x] = srcscr[y*vid.width+newpix]; // *(transme + (srcscr[y*vid.width+x]<<8) + srcscr[y*vid.width+newpix]); + }*/ + + disStart += 22;//the offset into the displacement map, increment each game loop + disStart &= FINEMASK; //clip it to FINEMASK } - /* - Unoptimized version - for (x = 0; x < vid.width; x++) - { - newpix = (x + sine); - - if (newpix < 0) - newpix = 0; - else if (newpix >= vid.width) - newpix = vid.width-1; - - tmpscr[y*vid.width + x] = srcscr[y*vid.width+newpix]; // *(transme + (srcscr[y*vid.width+x]<<8) + srcscr[y*vid.width+newpix]); - }*/ - - disStart += 22;//the offset into the displacement map, increment each game loop - disStart &= FINEMASK; //clip it to FINEMASK + UINT8 *tmp = tmpscr; + tmpscr = srcscr; + srcscr = tmp; } - - UINT8 *tmp = tmpscr; - tmpscr = srcscr; - srcscr = tmp; - } - else if (thiscam->postimg & POSTIMG_HEAT) // Heat wave - { - INT32 y; - - // Make sure table is built - if (heatshifter == NULL || lastheight != viewheight) + else if (thiscam->postimg & POSTIMG_HEAT) // Heat wave { - if (heatshifter) + INT32 y; + + // Make sure table is built + if (heatshifter == NULL || lastheight != viewheight) + { Z_Free(heatshifter); + heatshifter = Z_Calloc(viewheight * sizeof(boolean), PU_STATIC, NULL); - heatshifter = Z_Calloc(viewheight * sizeof(boolean), PU_STATIC, NULL); + for (y = 0; y < viewheight; y++) + { + if (M_RandomChance(FRACUNIT/8)) // 12.5% + heatshifter[y] = true; + } - for (y = 0; y < viewheight; y++) - { - if (M_RandomChance(FRACUNIT/8)) // 12.5% - heatshifter[y] = true; + heatindex[0] = heatindex[1] = heatindex[2] = heatindex[3] = 0; + lastheight = viewheight; } - heatindex[0] = heatindex[1] = heatindex[2] = heatindex[3] = 0; - lastheight = viewheight; - } - - for (y = yoffset; y < yoffset+viewheight; y++) - { - if (heatshifter[heatindex[view]++]) + for (y = yoffset; y < yoffset+viewheight; y++) { - // Shift this row of pixels to the right by 2 - tmpscr[(y*vid.width)+xoffset] = srcscr[(y*vid.width)+xoffset]; - memcpy(&tmpscr[(y*vid.width)+xoffset], &srcscr[(y*vid.width)+xoffset+vid.dup], viewwidth-vid.dup); + if (heatshifter[heatindex[view]++]) + { + // Shift this row of pixels to the right by 2 + tmpscr[(y*vid.width)+xoffset] = srcscr[(y*vid.width)+xoffset]; + memcpy(&tmpscr[(y*vid.width)+xoffset], &srcscr[(y*vid.width)+xoffset+vid.dup], viewwidth-vid.dup); + } + else + memcpy(&tmpscr[(y*vid.width)+xoffset], &srcscr[(y*vid.width)+xoffset], viewwidth); + + heatindex[view] %= viewheight; } - else - memcpy(&tmpscr[(y*vid.width)+xoffset], &srcscr[(y*vid.width)+xoffset], viewwidth); - heatindex[view] %= viewheight; + if (renderisnewtic) // This isn't interpolated... but how do you interpolate a one-pixel shift? + { + heatindex[view]++; + heatindex[view] %= vid.height; + } + + UINT8 *tmp = tmpscr; + tmpscr = srcscr; + srcscr = tmp; } - if (renderisnewtic) // This isn't interpolated... but how do you interpolate a one-pixel shift? - { - heatindex[view]++; - heatindex[view] %= vid.height; - } - - UINT8 *tmp = tmpscr; - tmpscr = srcscr; - srcscr = tmp; - } - #ifdef MOTIONBLUR - if (thiscam->postimg & POSTIMG_MOTION) // Motion Blur! - { - INT32 x, y; - - // TODO: Add a postimg_param so that we can pick the translucency level... - UINT8 *transme = transtables + ((param-1)<postimg & POSTIMG_MOTION) // Motion Blur! { - for (x = xoffset; x < xoffset+viewwidth; x++) - tmpscr[y*vid.width + x] = colormaps[*(transme + (srcscr [(y*vid.width)+x ] <<8) + (tmpscr[(y*vid.width)+x]))]; + INT32 x, y; + + // TODO: Add a postimg_param so that we can pick the translucency level... + UINT8 *transme = transtables + ((param-1)<postimg & POSTIMG_FLIP) && !(thiscam->postimg & POSTIMG_MIRROR)) // Flip the screen upside-down { @@ -3808,7 +3782,7 @@ void InitColorLUT(colorlookup_t *lut, RGBA_t *palette, boolean makecolors) lut->init = true; memcpy(lut->palette, palette, palsize); - for (i = 0; i < 0xFFFF; i++) + for (i = 0; i < 0x10000; i++) lut->table[i] = 0xFFFF; if (makecolors) @@ -3821,7 +3795,9 @@ void InitColorLUT(colorlookup_t *lut, RGBA_t *palette, boolean makecolors) { for (b = 0; b < 0xFF; b++) { - lut->table[i] = GetColorLUT(lut, r, g, b); + i = CLUTINDEX(r, g, b); + if (lut->table[i] == 0xFFFF) + lut->table[i] = NearestPaletteColor(r, g, b, palette); } } } @@ -3899,15 +3875,17 @@ void V_Recalc(void) // Set dup based on width or height, whichever is less if (((vid.width*FRACUNIT) / BASEVIDWIDTH) < ((vid.height*FRACUNIT) / BASEVIDHEIGHT)) { - vid.dup = vid.width / BASEVIDWIDTH; + vid.dup = max(vid.width / BASEVIDWIDTH, 1); vid.fdup = (vid.width*FRACUNIT) / BASEVIDWIDTH; } else { - vid.dup = vid.height / BASEVIDHEIGHT; + vid.dup = max(vid.height / BASEVIDHEIGHT, 1); vid.fdup = (vid.height*FRACUNIT) / BASEVIDHEIGHT; } + vid.udup = vid.dup; + if (loaded_config // this could use a better name, since it is more and indicator that early startup is done and its safe to do sketchy shit now :chaosleep: && (vid.width > 720) && (vid.height > 1280)) // ehhhh well this thing has so many issues, so ill lock it to higher resolutions instead { diff --git a/src/v_video.h b/src/v_video.h index 7eea1468c..108a16a9d 100644 --- a/src/v_video.h +++ b/src/v_video.h @@ -252,6 +252,7 @@ void V_DrawStringAtFixed(fixed_t x, fixed_t y, INT32 option, const char *string) void V_DrawSmallStringAtFixed(fixed_t x, fixed_t y, INT32 option, const char *string); void V_DrawCenteredSmallStringAtFixed(fixed_t x, fixed_t y, INT32 option, const char *string); +void V_DrawRightAlignedSmallStringAtFixed(fixed_t x, fixed_t y, INT32 option, const char *string); void V_DrawThinStringAtFixed(fixed_t x, fixed_t y, INT32 option, const char *string); @@ -287,8 +288,6 @@ INT32 V_ThinSubStringWidth(const char *string, INT32 length, INT32 option); // Find maximum length for substring taken from current string to fit into given width INT32 V_SubStringLengthToFit(const char *string, INT32 width, INT32 option); -char V_GetSkincolorChar(INT32 color); - INT32 V_SkinColorToHighlightcolor(skincolors_t color); // this is pretty dumb, but has to be done like this, otherwise the fps counter just disappears sometimes for no reason lol diff --git a/src/verstable.h b/src/verstable.h new file mode 100644 index 000000000..d7165e4e9 --- /dev/null +++ b/src/verstable.h @@ -0,0 +1,2126 @@ +/*------------------------------------------------- VERSTABLE v2.2.1 --------------------------------------------------- + +Verstable is a C99-compatible, open-addressing hash table using quadratic probing and the following additions: + +* All keys that hash (i.e. "belong") to the same bucket (their "home bucket") are linked together by an 11-bit integer + specifying the quadratic displacement, relative to that bucket, of the next key in the chain. + +* If a chain of keys exists for a given bucket, then it always begins at that bucket. To maintain this policy, a 1-bit + flag is used to mark whether the key occupying a bucket belongs there. When inserting a new key, if the bucket it + belongs to is occupied by a key that does not belong there, then the occupying key is evicted and the new key takes + the bucket. + +* A 4-bit fragment of each key's hash code is also stored. + +* The aforementioned metadata associated with each bucket (the 4-bit hash fragment, the 1-bit flag, and the 11-bit link + to the next key in the chain) are stored together in a uint16_t array rather than in the bucket alongside the key and + (optionally) the value. + +One way to conceptualize this scheme is as a chained hash table in which overflowing keys are stored not in separate +memory allocations but in otherwise unused buckets. In this regard, it shares similarities with Malte Skarupke's Bytell +hash table (https://www.youtube.com/watch?v=M2fKMP47slQ) and traditional "coalesced hashing". + +Advantages of this scheme include: + +* Fast lookups impervious to load factor: If the table contains any key belonging to the lookup key's home bucket, then + that bucket contains the first in a traversable chain of all keys belonging to it. Hence, only the home bucket and + other buckets containing keys belonging to it are ever probed. Moreover, the stored hash fragments allow skipping most + non-matching keys in the chain without accessing the actual buckets array or calling the (potentially expensive) key + comparison function. + +* Fast insertions: Insertions are faster than they are in other schemes that move keys around (e.g. Robin Hood) because + they only move, at most, one existing key. + +* Fast, tombstone-free deletions: Deletions, which usually require tombstones in quadratic-probing hash tables, are + tombstone-free and only move, at most, one existing key. + +* Fast iteration: The separate metadata array allows keys in sparsely populated tables to be found without incurring the + frequent cache misses that would result from traversing the buckets array. + +Usage example: + + +---------------------------------------------------------+----------------------------------------------------------+ + | Using the generic macro API (C11 and later): | Using the prefixed functions API (C99 and later): | + +---------------------------------------------------------+----------------------------------------------------------+ + | #include | #include | + | | | + | // Instantiating a set template. | // Instantiating a set template. | + | #define NAME int_set | #define NAME int_set | + | #define KEY_TY int | #define KEY_TY int | + | #include "verstable.h" | #define HASH_FN vt_hash_integer | + | | #define CMPR_FN vt_cmpr_integer | + | // Instantiating a map template. | #include "verstable.h" | + | #define NAME int_int_map | | + | #define KEY_TY int | // Instantiating a map template. | + | #define VAL_TY int | #define NAME int_int_map | + | #include "verstable.h" | #define KEY_TY int | + | | #define VAL_TY int | + | int main( void ) | #define HASH_FN vt_hash_integer | + | { | #define CMPR_FN vt_cmpr_integer | + | // Set. | #include "verstable.h" | + | | | + | int_set our_set; | int main( void ) | + | vt_init( &our_set ); | { | + | | // Set. | + | // Inserting keys. | | + | for( int i = 0; i < 10; ++i ) | int_set our_set; | + | { | int_set_init( &our_set ); | + | int_set_itr itr = vt_insert( &our_set, i ); | | + | if( vt_is_end( itr ) ) | // Inserting keys. | + | { | for( int i = 0; i < 10; ++i ) | + | // Out of memory, so abort. | { | + | vt_cleanup( &our_set ); | int_set_itr itr = | + | return 1; | int_set_insert( &our_set, i ); | + | } | if( int_set_is_end( itr ) ) | + | } | { | + | | // Out of memory, so abort. | + | // Erasing keys. | int_set_cleanup( &our_set ); | + | for( int i = 0; i < 10; i += 3 ) | return 1; | + | vt_erase( &our_set, i ); | } | + | | } | + | // Retrieving keys. | | + | for( int i = 0; i < 10; ++i ) | // Erasing keys. | + | { | for( int i = 0; i < 10; i += 3 ) | + | int_set_itr itr = vt_get( &our_set, i ); | int_set_erase( &our_set, i ); | + | if( !vt_is_end( itr ) ) | | + | printf( "%d ", itr.data->key ); | // Retrieving keys. | + | } | for( int i = 0; i < 10; ++i ) | + | // Printed: 1 2 4 5 7 8 | { | + | | int_set_itr itr = int_set_get( &our_set, i ); | + | // Iteration. | if( !int_set_is_end( itr ) ) | + | for( | printf( "%d ", itr.data->key ); | + | int_set_itr itr = vt_first( &our_set ); | } | + | !vt_is_end( itr ); | // Printed: 1 2 4 5 7 8 | + | itr = vt_next( itr ) | | + | ) | // Iteration. | + | printf( "%d ", itr.data->key ); | for( | + | // Printed: 2 4 7 1 5 8 | int_set_itr itr = | + | | int_set_first( &our_set ); | + | vt_cleanup( &our_set ); | !int_set_is_end( itr ); | + | | itr = int_set_next( itr ) | + | // Map. | ) | + | | printf( "%d ", itr.data->key ); | + | int_int_map our_map; | // Printed: 2 4 7 1 5 8 | + | vt_init( &our_map ); | | + | | int_set_cleanup( &our_set ); | + | // Inserting keys and values. | | + | for( int i = 0; i < 10; ++i ) | // Map. | + | { | | + | int_int_map_itr itr = | int_int_map our_map; | + | vt_insert( &our_map, i, i + 1 ); | int_int_map_init( &our_map ); | + | if( vt_is_end( itr ) ) | | + | { | // Inserting keys and values. | + | // Out of memory, so abort. | for( int i = 0; i < 10; ++i ) | + | vt_cleanup( &our_map ); | { | + | return 1; | int_int_map_itr itr = | + | } | int_int_map_insert( &our_map, i, i + 1 ); | + | } | if( int_int_map_is_end( itr ) ) | + | | { | + | // Erasing keys and values. | // Out of memory, so abort. | + | for( int i = 0; i < 10; i += 3 ) | int_int_map_cleanup( &our_map ); | + | vt_erase( &our_map, i ); | return 1; | + | | } | + | // Retrieving keys and values. | } | + | for( int i = 0; i < 10; ++i ) | | + | { | // Erasing keys and values. | + | int_int_map_itr itr = vt_get( &our_map, i ); | for( int i = 0; i < 10; i += 3 ) | + | if( !vt_is_end( itr ) ) | int_int_map_erase( &our_map, i ); | + | printf( | | + | "%d:%d ", | // Retrieving keys and values. | + | itr.data->key, | for( int i = 0; i < 10; ++i ) | + | itr.data->val | { | + | ); | int_int_map_itr itr = | + | } | int_int_map_get( &our_map, i ); | + | // Printed: 1:2 2:3 4:5 5:6 7:8 8:9 | if( !int_int_map_is_end( itr ) ) | + | | printf( | + | // Iteration. | "%d:%d ", | + | for( | itr.data->key, | + | int_int_map_itr itr = vt_first( &our_map ); | itr.data->val | + | !vt_is_end( itr ); | ); | + | itr = vt_next( itr ) | } | + | ) | // Printed: 1:2 2:3 4:5 5:6 7:8 8:9 | + | printf( | | + | "%d:%d ", | // Iteration. | + | itr.data->key, | for( | + | itr.data->val | int_int_map_itr itr = | + | ); | int_int_map_first( &our_map ); | + | // Printed: 2:3 4:5 7:8 1:2 5:6 8:9 | !int_int_map_is_end( itr ); | + | | itr = int_int_map_next( itr ) | + | vt_cleanup( &our_map ); | ) | + | } | printf( | + | | "%d:%d ", | + | | itr.data->key, | + | | itr.data->val | + | | ); | + | | // Printed: 2:3 4:5 7:8 1:2 5:6 8:9 | + | | | + | | int_int_map_cleanup( &our_map ); | + | | } | + | | | + +---------------------------------------------------------+----------------------------------------------------------+ + +API: + + Instantiating a hash table template: + + Create a new hash table type in the following manner: + + #define NAME + #define KEY_TY + #include "verstable.h" + + The NAME macro specifies the name of hash table type that the library will declare, the prefix for the functions + associated with it, and the prefix for the associated iterator type. + + The KEY_TY macro specifies the key type. + + In C99, it is also always necessary to define HASH_FN and CMPR_FN (see below) before including the header. + + The following macros may also be defined before including the header: + + #define KEY_GET_CONST + + Forces the key getter to take a const pointer even if the input key is not marked const + + #define VAL_TY + + The type of the value associated with each key. + If this macro is defined, the hash table acts as a map associating keys with values. + Otherwise, it acts as a set containing only keys. + + #define HASH_FN + + The name of the existing function used to hash each key. + The function should have the signature uint64_t ( KEY_TY key ) and return a 64-bit hash code. + For best performance, the hash function should provide a high level of entropy across all bits. + There are two default hash functions: vt_hash_integer for all integer types up to 64 bits in size, and + vt_hash_string for NULL-terminated strings (i.e. char *). + When KEY_TY is one of such types and the compiler is in C11 mode or later, HASH_FN may be left undefined, in + which case the appropriate default function is inferred from KEY_TY. + Otherwise, HASH_FN must be defined. + + #define CMPR_FN + + The name of the existing function used to compare two keys. + The function should have the signature bool ( KEY_TY key_1, KEY_TY key_2 ) and return true if the two keys are + equal. + There are two default comparison functions: vt_cmpr_integer for all integer types up to 64 bits in size, and + vt_cmpr_string for NULL-terminated strings (i.e. char *). + As with the default hash functions, in C11 or later the appropriate default comparison function is inferred if + KEY_TY is one of such types and CMPR_FN is left undefined. + Otherwise, CMPR_FN must be defined. + + #define MAX_LOAD + + The floating-point load factor at which the hash table automatically doubles the size of its internal buckets + array. + The default is 0.9, i.e. 90%. + + #define KEY_DTOR_FN + + The name of the existing destructor function, with the signature void ( KEY_TY key ), called on a key when it is + erased from the table or replaced by a newly inserted key. + The API functions that may call the key destructor are NAME_insert, NAME_erase, NAME_erase_itr, NAME_clear, + and NAME_cleanup. + + #define VAL_DTOR_FN + + The name of the existing destructor function, with the signature void ( VAL_TY val ), called on a value when it + is erased from the table or replaced by a newly inserted value. + The API functions that may call the value destructor are NAME_insert, NAME_erase, NAME_erase_itr, NAME_clear, + and NAME_cleanup. + + #define CTX_TY + + The type of the hash table type's ctx (context) member. + This member only exists if CTX_TY was defined. + It is intended to be used in conjunction with MALLOC_FN and FREE_FN (see below). + + #define MALLOC_FN + + The name of the existing function used to allocate memory. + If CTX_TY was defined, the signature should be void *( size_t size, CTX_TY *ctx ), where size is the number of + bytes to allocate and ctx points to the table's ctx member. + Otherwise, the signature should be void *( size_t size ). + The default wraps stdlib.h's malloc. + + #define FREE_FN + + The name of the existing function used to free memory. + If CTX_TY was defined, the signature should be void ( void *ptr, size_t size, CTX_TY *ctx ), where ptr points to + the memory to free, size is the number of bytes that were allocated, and ctx points to the table's ctx member. + Otherwise, the signature should be void ( void *ptr, size_t size ). + The default wraps stdlib.h's free. + + #define HEADER_MODE + #define IMPLEMENTATION_MODE + + By default, all hash table functions are defined as static inline functions, the intent being that a given hash + table template should be instantiated once per translation unit; for best performance, this is the recommended + way to use the library. + However, it is also possible to separate the struct definitions and function declarations from the function + definitions such that one implementation can be shared across all translation units (as in a traditional header + and source file pair). + In that case, instantiate a template wherever it is needed by defining HEADER_MODE, along with only NAME, + KEY_TY, and (optionally) VAL_TY, CTX_TY, and header guards, and including the library, e.g.: + + #ifndef INT_INT_MAP_H + #define INT_INT_MAP_H + #define NAME int_int_map + #define KEY_TY int + #define VAL_TY int + #define HEADER_MODE + #include "verstable.h" + #endif + + In one source file, define IMPLEMENTATION_MODE, along with NAME, KEY_TY, and any of the aforementioned optional + macros, and include the library, e.g.: + + #define NAME int_int_map + #define KEY_TY int + #define VAL_TY int + #define HASH_FN vt_hash_integer // C99. + #define CMPR_FN vt_cmpr_integer // C99. + #define MAX_LOAD 0.8 + #define IMPLEMENTATION_MODE + #include "verstable.h" + + Including the library automatically undefines all the aforementioned macros after they have been used to instantiate + the template. + + Functions: + + The functions associated with a hash table type are all prefixed with the name the user supplied via the NAME macro. + In C11 and later, the generic "vt_"-prefixed macros may be used to automatically select the correct version of the + specified function based on the arguments. + + void NAME_init( NAME *table ) + void NAME_init( NAME *table, CTX_TY ctx ) + // C11 generic macro: vt_init. + + Initializes the table for use. + If CTX_TY was defined, ctx sets the table's ctx member. + + bool NAME_init_clone( NAME *table, NAME *source ) + bool NAME_init_clone( NAME *table, NAME *source, CTX_TY ctx ) + // C11 generic macro: vt_init_clone. + + Initializes the table as a shallow copy of the specified source table. + If CTX_TY was defined, ctx sets the table's ctx member. + Returns false in the case of memory allocation failure. + + size_t NAME_size( NAME *table ) // C11 generic macro: vt_size. + + Returns the number of keys currently in the table. + + size_t NAME_bucket_count( NAME *table ) // C11 generic macro: vt_bucket_count. + + Returns the table's current bucket count. + + NAME_itr NAME_insert( NAME *table, KEY_TY key ) + NAME_itr NAME_insert( NAME *table, KEY_TY key, VAL_TY val ) + // C11 generic macro: vt_insert. + + Inserts the specified key (and value, if VAL_TY was defined) into the hash table. + If the same key already exists, then the new key (and value) replaces the existing key (and value). + Returns an iterator to the new key, or an end iterator in the case of memory allocation failure. + + NAME_itr NAME_get_or_insert( NAME *table, KEY_TY key ) + NAME_itr NAME_get_or_insert( NAME *table, KEY_TY key, VAL_TY val ) + // C11 generic macro: vt_get_or_insert. + + Inserts the specified key (and value, if VAL_TY was defined) if it does not already exist in the table. + Returns an iterator to the new key if it was inserted, or an iterator to the existing key, or an end iterator if + the key did not exist but the new key could not be inserted because of memory allocation failure. + Determine whether the key was inserted by comparing the table's size before and after the call. + + NAME_itr NAME_get( NAME *table, KEY_TY key ) // C11 generic macro: vt_get. + + Returns a iterator to the specified key, or an end iterator if no such key exists. + + bool NAME_erase( NAME *table, KEY_TY key ) // C11 generic macro: vt_erase. + + Erases the specified key (and associated value, if VAL_TY was defined), if it exists. + Returns true if a key was erased. + + NAME_itr NAME_erase_itr( NAME *table, NAME_itr itr ) // C11 generic macro: vt_erase_itr. + + Erases the key (and associated value, if VAL_TY was defined) pointed to by the specified iterator. + Returns an iterator to the next key in the table, or an end iterator if the erased key was the last one. + + bool NAME_reserve( NAME *table, size_t size ) // C11 generic macro: vt_reserve. + + Ensures that the bucket count is large enough to support the specified key count (i.e. size) without rehashing. + Returns false if unsuccessful due to memory allocation failure. + + bool NAME_shrink( NAME *table ) // C11 generic macro: vt_shrink. + + Shrinks the bucket count to best accommodate the current size. + Returns false if unsuccessful due to memory allocation failure. + + NAME_itr NAME_first( NAME *table ) // C11 generic macro: vt_first. + + Returns an iterator to the first key in the table, or an end iterator if the table is empty. + + bool NAME_is_end( NAME_itr itr ) // C11 generic macro: vt_is_end. + + Returns true if the iterator is an end iterator. + + NAME_itr NAME_next( NAME_itr itr ) // C11 generic macro: vt_next. + + Returns an iterator to the key after the one pointed to by the specified iterator, or an end iterator if the + specified iterator points to the last key in the table. + + void NAME_clear( NAME *table ) // C11 generic macro: vt_clear. + + Erases all keys (and values, if VAL_TY was defined) in the table. + + void NAME_cleanup( NAME *table ) // C11 generic macro: vt_cleanup. + + Erases all keys (and values, if VAL_TY was defined) in the table, frees all memory associated with it, and + initializes it for reuse. + + Iterators: + + Access the key (and value, if VAL_TY was defined) that an iterator points to using the NAME_itr struct's data + member: + + itr.data->key + itr.data->val + + Functions that may insert new keys (NAME_insert and NAME_get_or_insert), erase keys (NAME_erase and NAME_erase_itr), + or reallocate the internal bucket array (NAME_reserve and NAME_shrink) invalidate all existing iterators. + To delete keys during iteration and resume iterating, use the return value of NAME_erase_itr. + +SRB2Kart - Saturn: + added KEY_GET_CONST to force the getters to take a const pointer even if the type of key to be inserted is not const + +Version history: + + 06/05/2025 2.2.1: Fixed incorrect signature of NAME_is_end in documentation. + 18/04/2025 2.2.0: Added const qualifier to the table parameter of NAME_size, NAME_bucket_count, NAME_get, and + NAME_first and to the source parameter of NAME_init_clone. + Added default support for const char * strings. + Added support for -Wextra. + Replaced FNV-1a with Wyhash as the default string hash function. + 18/06/2024 2.1.1: Fixed a bug affecting iteration on big-endian platforms under MSVC. + 27/05/2024 2.1.0: Replaced the Murmur3 mixer with the fast-hash mixer as the default integer hash function. + Fixed a bug that could theoretically cause a crash on rehash (triggerable in testing using + NAME_shrink with a maximum load factor significantly higher than 1.0). + 06/02/2024 2.0.0: Improved custom allocator support by introducing the CTX_TY option and allowing user-supplied free + functions to receive the allocation size. + Improved documentation. + Introduced various optimizations, including storing the buckets-array size mask instead of the + bucket count, eliminating empty-table checks, combining the buckets memory and metadata memory into + one allocation, and adding branch prediction macros. + Fixed a bug that caused a key to be used after destruction during erasure. + 12/12/2023 1.0.0: Initial release. + +License (MIT): + + Copyright (c) 2023-2025 Jackson L. Allan + + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + documentation files (the "Software"), to deal in the Software without restriction, including without limitation the + rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the + Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +*/ + +/*--------------------------------------------------------------------------------------------------------------------*/ +/* Common header section */ +/*--------------------------------------------------------------------------------------------------------------------*/ + +#ifdef __GNUC__ + #if (__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1) // >= GCC 3.1 + #define FORCE_INLINE __attribute__((always_inline)) + #else + #define FORCE_INLINE + #endif +#else + #define FORCE_INLINE +#endif + +#ifndef VERSTABLE_H +#define VERSTABLE_H + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Waggregate-return" + +#include +#include +#include +#include +#include +#include + +#include "fastcmp.h" + +// Two-way concatenation macro. +#define VT_CAT_( a, b ) a##b +#define VT_CAT( a, b ) VT_CAT_( a, b ) + +// Branch optimization macros. +#ifdef __GNUC__ +#define VT_LIKELY( expression ) __builtin_expect( (bool)( expression ), true ) +#define VT_UNLIKELY( expression ) __builtin_expect( (bool)( expression ), false ) +#else +#define VT_LIKELY( expression ) ( expression ) +#define VT_UNLIKELY( expression ) ( expression ) +#endif + +// Masks for manipulating and extracting data from a bucket's uint16_t metadatum. +#define VT_EMPTY 0x0000 +#define VT_HASH_FRAG_MASK 0xF000 // 0b1111000000000000. +#define VT_IN_HOME_BUCKET_MASK 0x0800 // 0b0000100000000000. +#define VT_DISPLACEMENT_MASK 0x07FF // 0b0000011111111111, also denotes the displacement limit. Set to VT_LOAD to 1.0 + // to test proper handling of encroachment on the displacement limit during + // inserts. + +// Extracts a hash fragment from a uint64_t hash code. +// We take the highest four bits so that keys that map (via modulo) to the same bucket have distinct hash fragments. +static inline FORCE_INLINE uint16_t vt_hashfrag( uint64_t hash ) +{ + return ( hash >> 48 ) & VT_HASH_FRAG_MASK; +} + +// Standard quadratic probing formula that guarantees that all buckets are visited when the bucket count is a power of +// two (at least in theory, because the displacement limit could terminate the search early when the bucket count is +// high). +static inline FORCE_INLINE size_t vt_quadratic( uint16_t displacement ) +{ + return ( (size_t)displacement * displacement + displacement ) / 2; +} + +#define VT_MIN_NONZERO_BUCKET_COUNT 8 // Must be a power of two. + +// Function to find the left-most non-zero uint16_t in a uint64_t. +// This function is used when we scan four buckets at a time while iterating and relies on compiler intrinsics wherever +// possible. + +#if defined( __GNUC__ ) && ULLONG_MAX == 0xFFFFFFFFFFFFFFFF + +static inline FORCE_INLINE int vt_first_nonzero_uint16( uint64_t val ) +{ + const uint16_t endian_checker = 0x0001; + if( *(const char *)&endian_checker ) // Little-endian (the compiler will optimize away the check at -O1 and above). + return __builtin_ctzll( val ) / 16; + + return __builtin_clzll( val ) / 16; +} + +#elif defined( _MSC_VER ) && ( defined( _M_X64 ) || defined( _M_ARM64 ) ) + +#include +#pragma intrinsic(_BitScanForward64) +#pragma intrinsic(_BitScanReverse64) + +static inline FORCE_INLINE int vt_first_nonzero_uint16( uint64_t val ) +{ + unsigned long result; + + const uint16_t endian_checker = 0x0001; + if( *(const char *)&endian_checker ) + _BitScanForward64( &result, val ); + else + { + _BitScanReverse64( &result, val ); + result = 63 - result; + } + + return result / 16; +} + +#else + +static inline FORCE_INLINE int vt_first_nonzero_uint16( uint64_t val ) +{ + int result = 0; + + uint32_t half; + memcpy( &half, &val, sizeof( uint32_t ) ); + if( !half ) + result += 2; + + uint16_t quarter; + memcpy( &quarter, (char *)&val + result * sizeof( uint16_t ), sizeof( uint16_t ) ); + if( !quarter ) + result += 1; + + return result; +} + +#endif + +// When the bucket count is zero, setting the metadata pointer to point to a VT_EMPTY placeholder, rather than NULL, +// allows us to avoid checking for a zero bucket count during insertion and lookup. +static const uint16_t vt_empty_placeholder_metadatum = VT_EMPTY; + +// Default hash and comparison functions. + +// Fast-hash, as described by https://jonkagstrom.com/bit-mixer-construction and +// https://code.google.com/archive/p/fast-hash. +// In testing, this hash function provided slightly better performance than the Murmur3 mixer. +static inline FORCE_INLINE uint64_t vt_hash_integer( uint64_t key ) +{ + key ^= key >> 23; + key *= 0x2127599bf4325c37ull; + key ^= key >> 47; + return key; +} + +// For hashing strings, we use the public-domain Wyhash +// (https://github.com/wangyi-fudan/wyhash) with the following modifications: +// * We use a fixed seed and secret (the defaults suggested in the Wyhash repository). +// * We do not handle endianness, so the result will differ depending on the platform. +// * We omit the code optimized for 32-bit platforms. + +static inline FORCE_INLINE void vt_wymum( uint64_t *a, uint64_t *b ) +{ +#if defined( __SIZEOF_INT128__ ) + __uint128_t r = *a; + r *= *b; + *a = (uint64_t)r; + *b = (uint64_t)( r >> 64 ); +#elif defined( _MSC_VER ) && defined( _M_X64 ) + *a = _umul128( *a, *b, b ); +#else + uint64_t ha = *a >> 32; + uint64_t hb = *b >> 32; + uint64_t la = (uint32_t)*a; + uint64_t lb = (uint32_t)*b; + uint64_t rh = ha * hb; + uint64_t rm0 = ha * lb; + uint64_t rm1 = hb * la; + uint64_t rl = la * lb; + uint64_t t = rl + ( rm0 << 32 ); + uint64_t c = t < rl; + uint64_t lo = t + ( rm1 << 32 ); + c += lo < t; + uint64_t hi = rh + ( rm0 >> 32 ) + ( rm1 >> 32 ) + c; + *a = lo; + *b = hi; +#endif +} + +static inline FORCE_INLINE uint64_t vt_wymix( uint64_t a, uint64_t b ) +{ + vt_wymum( &a, &b ); + return a ^ b; +} + +static inline FORCE_INLINE uint64_t vt_wyr8( const unsigned char *p ) +{ + uint64_t v; + memcpy( &v, p, 8 ); + return v; +} + +static inline FORCE_INLINE uint64_t vt_wyr4( const unsigned char *p ) +{ + uint32_t v; + memcpy( &v, p, 4 ); + return v; +} + +static inline FORCE_INLINE uint64_t vt_wyr3( const unsigned char *p, size_t k ) +{ + return ( ( (uint64_t)p[ 0 ] ) << 16 ) | ( ( (uint64_t)p[ k >> 1 ] ) << 8 ) | p[ k - 1 ]; +} + +static inline FORCE_INLINE size_t vt_wyhash( const void *key, size_t len ) +{ + const unsigned char *p = (const unsigned char *)key; + uint64_t seed = 0xca813bf4c7abf0a9ull; + uint64_t a; + uint64_t b; + if( VT_LIKELY( len <= 16 ) ) + { + if( VT_LIKELY( len >= 4 ) ) + { + a = ( vt_wyr4( p ) << 32 ) | vt_wyr4( p + ( ( len >> 3 ) << 2 ) ); + b = ( vt_wyr4( p + len - 4 ) << 32 ) | vt_wyr4( p + len - 4 - ( ( len >> 3 ) << 2 ) ); + } + else if( VT_LIKELY( len > 0 ) ) + { + a = vt_wyr3( p, len ); + b = 0; + } + else + { + a = 0; + b = 0; + } + } + else + { + size_t i = len; + if( VT_UNLIKELY( i >= 48 ) ) + { + uint64_t see1 = seed; + uint64_t see2 = seed; + do{ + seed = vt_wymix( vt_wyr8( p ) ^ 0x8bb84b93962eacc9ull, vt_wyr8( p + 8 ) ^ seed ); + see1 = vt_wymix( vt_wyr8( p + 16 ) ^ 0x4b33a62ed433d4a3ull, vt_wyr8( p + 24 ) ^ see1 ); + see2 = vt_wymix( vt_wyr8( p + 32 ) ^ 0x4d5a2da51de1aa47ull, vt_wyr8( p + 40 ) ^ see2 ); + p += 48; + i -= 48; + } + while( VT_LIKELY( i >= 48 ) ); + seed ^= see1 ^ see2; + } + + while( VT_UNLIKELY( i > 16 ) ) + { + seed = vt_wymix( vt_wyr8( p ) ^ 0x8bb84b93962eacc9ull, vt_wyr8( p + 8 ) ^ seed ); + i -= 16; + p += 16; + } + + a = vt_wyr8( p + i - 16 ); + b = vt_wyr8( p + i - 8 ); + } + + a ^= 0x8bb84b93962eacc9ull; + b ^= seed; + vt_wymum( &a, &b ); + return (size_t)vt_wymix( a ^ 0x2d358dccaa6c78a5ull ^ len, b ^ 0x8bb84b93962eacc9ull ); +} + +static inline FORCE_INLINE uint64_t vt_hash_string( const char *key ) +{ + return vt_wyhash( key, strlen( key ) ); +} + +static inline FORCE_INLINE bool vt_cmpr_integer( uint64_t key_1, uint64_t key_2 ) +{ + return key_1 == key_2; +} + +static inline FORCE_INLINE bool vt_cmpr_string( const char *key_1, const char *key_2 ) +{ + return fastcmp( key_1, key_2 ); +} + +static inline FORCE_INLINE bool vt_cmpr_casestring( const char *key_1, const char *key_2 ) +{ + return fasticmp( key_1, key_2 ); +} + +// Default allocation and free functions. + +static inline FORCE_INLINE void *vt_malloc( size_t size ) +{ + return malloc( size ); +} + +static inline FORCE_INLINE void vt_free( void *ptr, size_t size ) +{ + (void)size; + free( ptr ); +} + +static inline FORCE_INLINE void *vt_malloc_with_ctx( size_t size, void *ctx ) +{ + (void)ctx; + return malloc( size ); +} + +static inline FORCE_INLINE void vt_free_with_ctx( void *ptr, size_t size, void *ctx ) +{ + (void)size; + (void)ctx; + free( ptr ); +} + +// The rest of the common header section pertains to the C11 generic macro API. +// This interface is based on the extendible-_Generic mechanism documented in detail at +// https://github.com/JacksonAllan/CC/blob/main/articles/Better_C_Generics_Part_1_The_Extendible_Generic.md. +// In summary, instantiating a template also defines wrappers for the template's types and functions with names in the +// pattern of vt_table_NNNN and vt_init_NNNN, where NNNN is an automatically generated integer unique to the template +// instance in the current translation unit. +// These wrappers plug into _Generic-based API macros, which use preprocessor magic to automatically generate _Generic +// slots for every existing template instance. +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined( VT_NO_C11_GENERIC_API ) + +// Octal counter that supports up to 511 hash table templates. +#define VT_TEMPLATE_COUNT_D1 0 // Digit 1, i.e. least significant digit. +#define VT_TEMPLATE_COUNT_D2 0 +#define VT_TEMPLATE_COUNT_D3 0 + +// Four-way concatenation macro. +#define VT_CAT_4_( a, b, c, d ) a##b##c##d +#define VT_CAT_4( a, b, c, d ) VT_CAT_4_( a, b, c, d ) + +// Provides the current value of the counter as a three-digit octal number preceded by 0. +#define VT_TEMPLATE_COUNT VT_CAT_4( 0, VT_TEMPLATE_COUNT_D3, VT_TEMPLATE_COUNT_D2, VT_TEMPLATE_COUNT_D1 ) + +// _Generic-slot generation macros. + +#define VT_GENERIC_SLOT( ty, fn, n ) , VT_CAT( ty, n ): VT_CAT( fn, n ) +#define VT_R1_0( ty, fn, d3, d2 ) +#define VT_R1_1( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 0 ) ) +#define VT_R1_2( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 1 ) ) VT_R1_1( ty, fn, d3, d2 ) +#define VT_R1_3( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 2 ) ) VT_R1_2( ty, fn, d3, d2 ) +#define VT_R1_4( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 3 ) ) VT_R1_3( ty, fn, d3, d2 ) +#define VT_R1_5( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 4 ) ) VT_R1_4( ty, fn, d3, d2 ) +#define VT_R1_6( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 5 ) ) VT_R1_5( ty, fn, d3, d2 ) +#define VT_R1_7( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 6 ) ) VT_R1_6( ty, fn, d3, d2 ) +#define VT_R1_8( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 7 ) ) VT_R1_7( ty, fn, d3, d2 ) +#define VT_R2_0( ty, fn, d3 ) +#define VT_R2_1( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 0 ) +#define VT_R2_2( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 1 ) VT_R2_1( ty, fn, d3 ) +#define VT_R2_3( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 2 ) VT_R2_2( ty, fn, d3 ) +#define VT_R2_4( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 3 ) VT_R2_3( ty, fn, d3 ) +#define VT_R2_5( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 4 ) VT_R2_4( ty, fn, d3 ) +#define VT_R2_6( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 5 ) VT_R2_5( ty, fn, d3 ) +#define VT_R2_7( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 6 ) VT_R2_6( ty, fn, d3 ) +#define VT_R2_8( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 7 ) VT_R2_7( ty, fn, d3 ) +#define VT_R3_0( ty, fn ) +#define VT_R3_1( ty, fn ) VT_R2_8( ty, fn, 0 ) +#define VT_R3_2( ty, fn ) VT_R2_8( ty, fn, 1 ) VT_R3_1( ty, fn ) +#define VT_R3_3( ty, fn ) VT_R2_8( ty, fn, 2 ) VT_R3_2( ty, fn ) +#define VT_R3_4( ty, fn ) VT_R2_8( ty, fn, 3 ) VT_R3_3( ty, fn ) +#define VT_R3_5( ty, fn ) VT_R2_8( ty, fn, 4 ) VT_R3_4( ty, fn ) +#define VT_R3_6( ty, fn ) VT_R2_8( ty, fn, 5 ) VT_R3_5( ty, fn ) +#define VT_R3_7( ty, fn ) VT_R2_8( ty, fn, 6 ) VT_R3_6( ty, fn ) + +#define VT_GENERIC_SLOTS( ty, fn ) \ +VT_CAT( VT_R1_, VT_TEMPLATE_COUNT_D1 )( ty, fn, VT_TEMPLATE_COUNT_D3, VT_TEMPLATE_COUNT_D2 ) \ +VT_CAT( VT_R2_, VT_TEMPLATE_COUNT_D2 )( ty, fn, VT_TEMPLATE_COUNT_D3 ) \ +VT_CAT( VT_R3_, VT_TEMPLATE_COUNT_D3 )( ty, fn ) \ + +// Actual generic API macros. + +// vt_init must be handled as a special case because it could take one or two arguments, depending on whether CTX_TY +// was defined. +#define VT_ARG_3( _1, _2, _3, ... ) _3 +#define vt_init( ... ) VT_ARG_3( __VA_ARGS__, vt_init_with_ctx, vt_init_without_ctx, )( __VA_ARGS__ ) +#define vt_init_without_ctx( table ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_init_ ) )( table ) +#define vt_init_with_ctx( table, ... ) _Generic( *( table ) \ + VT_GENERIC_SLOTS( vt_table_, vt_init_ ) \ +)( table, __VA_ARGS__ ) \ + +#define vt_init_clone( table, ... ) _Generic( *( table ) \ + VT_GENERIC_SLOTS( vt_table_, vt_init_clone_ ) \ +)( table, __VA_ARGS__ ) \ + +#define vt_size( table )_Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_size_ ) )( table ) + +#define vt_bucket_count( table ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_bucket_count_ ) )( table ) + +#define vt_is_end( itr ) _Generic( itr VT_GENERIC_SLOTS( vt_table_itr_, vt_is_end_ ) )( itr ) + +#define vt_insert( table, ... ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_insert_ ) )( table, __VA_ARGS__ ) + +#define vt_get_or_insert( table, ... ) _Generic( *( table ) \ + VT_GENERIC_SLOTS( vt_table_, vt_get_or_insert_ ) \ +)( table, __VA_ARGS__ ) \ + +#define vt_get( table, ... ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_get_ ) )( table, __VA_ARGS__ ) + +#define vt_erase( table, ... ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_erase_ ) )( table, __VA_ARGS__ ) + +#define vt_next( itr ) _Generic( itr VT_GENERIC_SLOTS( vt_table_itr_, vt_next_ ) )( itr ) + +#define vt_erase_itr( table, ... ) _Generic( *( table ) \ + VT_GENERIC_SLOTS( vt_table_, vt_erase_itr_ ) \ +)( table, __VA_ARGS__ ) \ + +#define vt_reserve( table, ... ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_reserve_ ) )( table, __VA_ARGS__ ) + +#define vt_shrink( table ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_shrink_ ) )( table ) + +#define vt_first( table ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_first_ ) )( table ) + +#define vt_clear( table ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_clear_ ) )( table ) + +#define vt_cleanup( table ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_cleanup_ ) )( table ) + +#endif + +#endif + +/*--------------------------------------------------------------------------------------------------------------------*/ +/* Prefixed structs */ +/*--------------------------------------------------------------------------------------------------------------------*/ + +#ifndef IMPLEMENTATION_MODE + +typedef struct +{ + KEY_TY key; + #ifdef VAL_TY + VAL_TY val; + #endif +} VT_CAT( NAME, _bucket ); + +typedef struct +{ + VT_CAT( NAME, _bucket ) *data; + uint16_t *metadatum; + uint16_t *metadata_end; // Iterators carry an internal end pointer so that NAME_is_end does not need the table to be + // passed in as an argument. + // This also allows for the zero-bucket-count check to occur once in NAME_first, rather than + // repeatedly in NAME_is_end. + size_t home_bucket; // SIZE_MAX if home bucket is unknown. +} VT_CAT( NAME, _itr ); + +typedef struct +{ + size_t key_count; + size_t buckets_mask; // Rather than storing the bucket count directly, we store the bit mask used to reduce a hash + // code or displacement-derived bucket index to the buckets array, i.e. the bucket count minus + // one. + // Consequently, a zero bucket count (i.e. when .metadata points to the placeholder) constitutes + // a special case, represented by all bits unset (i.e. zero). + VT_CAT( NAME, _bucket ) *buckets; + uint16_t *metadata; // As described above, each metadatum consists of a 4-bit hash-code fragment (X), a 1-bit flag + // indicating whether the key in this bucket begins a chain associated with the bucket (Y), and + // an 11-bit value indicating the quadratic displacement of the next key in the chain (Z): + // XXXXYZZZZZZZZZZZ. + #ifdef CTX_TY + CTX_TY ctx; + #endif +} NAME; + +#endif + +/*--------------------------------------------------------------------------------------------------------------------*/ +/* Function prototypes */ +/*--------------------------------------------------------------------------------------------------------------------*/ + +#if defined( HEADER_MODE ) || defined( IMPLEMENTATION_MODE ) +#define VT_API_FN_QUALIFIERS +#else +#define VT_API_FN_QUALIFIERS static inline FORCE_INLINE +#endif + +#ifndef IMPLEMENTATION_MODE + +VT_API_FN_QUALIFIERS void VT_CAT( NAME, _init )( + NAME * + #ifdef CTX_TY + , CTX_TY + #endif +); + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _init_clone )( + NAME *, + const NAME * + #ifdef CTX_TY + , CTX_TY + #endif +); + +VT_API_FN_QUALIFIERS size_t VT_CAT( NAME, _size )( const NAME * ); + +VT_API_FN_QUALIFIERS size_t VT_CAT( NAME, _bucket_count )( const NAME * ); + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _is_end )( VT_CAT( NAME, _itr ) ); + +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _insert )( + NAME *, + KEY_TY + #ifdef VAL_TY + , VAL_TY + #endif +); + +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _get_or_insert )( + NAME *, + KEY_TY + #ifdef VAL_TY + , VAL_TY + #endif +); + +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _get )( + const NAME *table, +#ifdef KEY_GET_CONST + const KEY_TY key +#else + KEY_TY key +#endif +); + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _erase )( NAME *, KEY_TY ); + +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _next )( VT_CAT( NAME, _itr ) ); + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _reserve )( NAME *, size_t ); + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _shrink )( NAME * ); + +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _first )( const NAME * ); + +VT_API_FN_QUALIFIERS void VT_CAT( NAME, _clear )( NAME * ); + +VT_API_FN_QUALIFIERS void VT_CAT( NAME, _cleanup )( NAME * ); + +// Not an API function, but must be prototyped anyway because it is called by the inline NAME_erase_itr below. +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _erase_itr_raw ) ( NAME *, VT_CAT( NAME, _itr ) ); + +// Erases the key pointed to by itr and returns an iterator to the next key in the table. +// This function must be inlined to ensure that the compiler optimizes away the NAME_fast_forward call if the returned +// iterator is discarded. +#ifdef __GNUC__ +static inline FORCE_INLINE +#elif defined( _MSC_VER ) +static __forceinline +#else +static inline +#endif +VT_CAT( NAME, _itr ) VT_CAT( NAME, _erase_itr )( NAME *table, VT_CAT( NAME, _itr ) itr ) +{ + if( VT_CAT( NAME, _erase_itr_raw )( table, itr ) ) + return VT_CAT( NAME, _next )( itr ); + + return itr; +} + +#endif + +/*--------------------------------------------------------------------------------------------------------------------*/ +/* Function implementations */ +/*--------------------------------------------------------------------------------------------------------------------*/ + +#ifndef HEADER_MODE + +// Default settings. + +#ifndef MAX_LOAD +#define MAX_LOAD 0.9 +#endif + +#ifndef MALLOC_FN +#ifdef CTX_TY +#define MALLOC_FN vt_malloc_with_ctx +#else +#define MALLOC_FN vt_malloc +#endif +#endif + +#ifndef FREE_FN +#ifdef CTX_TY +#define FREE_FN vt_free_with_ctx +#else +#define FREE_FN vt_free +#endif +#endif + +#ifndef HASH_FN +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L +#ifdef _MSC_VER // In MSVC, the compound literal in the _Generic triggers a warning about unused local variables at /W4. +#define HASH_FN \ +_Pragma( "warning( push )" ) \ +_Pragma( "warning( disable: 4189 )" ) \ +_Generic( ( KEY_TY ){ 0 }, char *: vt_hash_string, const char*: vt_hash_string, default: vt_hash_integer ) \ +_Pragma( "warning( pop )" ) +#else +#define HASH_FN _Generic( ( KEY_TY ){ 0 }, \ + char *: vt_hash_string, \ + const char*: vt_hash_string, \ + default: vt_hash_integer \ +) +#endif +#else +#error Hash function inference is only available in C11 and later. In C99, you need to define HASH_FN manually to \ +vt_hash_integer, vt_hash_string, or your own custom function with the signature uint64_t ( KEY_TY ). +#endif +#endif + +#ifndef CMPR_FN +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L +#ifdef _MSC_VER +#define CMPR_FN \ +_Pragma( "warning( push )" ) \ +_Pragma( "warning( disable: 4189 )" ) \ +_Generic( ( KEY_TY ){ 0 }, char *: vt_cmpr_string, const char*: vt_cmpr_string, default: vt_cmpr_integer ) \ +_Pragma( "warning( pop )" ) +#else +#define CMPR_FN _Generic( ( KEY_TY ){ 0 }, \ + char *: vt_cmpr_string, \ + const char*: vt_cmpr_string, \ + default: vt_cmpr_integer \ +) +#endif +#else +#error Comparison function inference is only available in C11 and later. In C99, you need to define CMPR_FN manually \ +to vt_cmpr_integer, vt_cmpr_string, or your own custom function with the signature bool ( KEY_TY, KEY_TY ). +#endif +#endif + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-qual" + +VT_API_FN_QUALIFIERS void VT_CAT( NAME, _init )( + NAME *table + #ifdef CTX_TY + , CTX_TY ctx + #endif +) +{ + table->key_count = 0; + table->buckets_mask = 0x0000000000000000ull; + table->buckets = NULL; + table->metadata = (uint16_t *)&vt_empty_placeholder_metadatum; + #ifdef CTX_TY + table->ctx = ctx; + #endif +} + +#pragma GCC diagnostic pop + +// For efficiency, especially in the case of a small table, the buckets array and metadata share the same dynamic memory +// allocation: +// +-----------------------------+-----+----------------+--------+ +// | Buckets | Pad | Metadata | Excess | +// +-----------------------------+-----+----------------+--------+ +// Any allocated metadata array requires four excess elements to ensure that iteration functions, which read four +// metadata at a time, never read beyond the end of it. +// This function returns the offset of the beginning of the metadata, i.e. the size of the buckets array plus the +// (usually zero) padding. +// It assumes that the bucket count is not zero. +static inline FORCE_INLINE size_t VT_CAT( NAME, _metadata_offset )( NAME *table ) +{ + // Use sizeof, rather than alignof, for C99 compatibility. + return ( ( ( table->buckets_mask + 1 ) * sizeof( VT_CAT( NAME, _bucket ) ) + sizeof( uint16_t ) - 1 ) / + sizeof( uint16_t ) ) * sizeof( uint16_t ); +} + +// Returns the total allocation size, including the buckets array, padding, metadata, and excess metadata. +// As above, this function assumes that the bucket count is not zero. +static inline FORCE_INLINE size_t VT_CAT( NAME, _total_alloc_size )( NAME *table ) +{ + return VT_CAT( NAME, _metadata_offset )( table ) + ( table->buckets_mask + 1 + 4 ) * sizeof( uint16_t ); +} + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-qual" + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _init_clone )( + NAME *table, + const NAME *source + #ifdef CTX_TY + , CTX_TY ctx + #endif +) +{ + table->key_count = source->key_count; + table->buckets_mask = source->buckets_mask; + #ifdef CTX_TY + table->ctx = ctx; + #endif + + if( !source->buckets_mask ) + { + table->metadata = (uint16_t *)&vt_empty_placeholder_metadatum; + table->buckets = NULL; + return true; + } + + void *allocation = MALLOC_FN( + VT_CAT( NAME, _total_alloc_size )( table ) + #ifdef CTX_TY + , &table->ctx + #endif + ); + + if( VT_UNLIKELY( !allocation ) ) + return false; + + table->buckets = (VT_CAT( NAME, _bucket ) *)allocation; + table->metadata = (uint16_t *)( (unsigned char *)allocation + VT_CAT( NAME, _metadata_offset )( table ) ); + memcpy( allocation, source->buckets, VT_CAT( NAME, _total_alloc_size )( table ) ); + + return true; +} + +#pragma GCC diagnostic pop + +VT_API_FN_QUALIFIERS size_t VT_CAT( NAME, _size )( const NAME *table ) +{ + return table->key_count; +} + +VT_API_FN_QUALIFIERS size_t VT_CAT( NAME, _bucket_count )( const NAME *table ) +{ + // If the bucket count is zero, buckets_mask will be zero, not the bucket count minus one. + // We account for this special case by adding (bool)buckets_mask rather than one. + return table->buckets_mask + (bool)table->buckets_mask; +} + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _is_end )( VT_CAT( NAME, _itr ) itr ) +{ + return itr.metadatum == itr.metadata_end; +} + +// Finds the earliest empty bucket in which a key belonging to home_bucket can be placed, assuming that home_bucket +// is already occupied. +// The reason to begin the search at home_bucket, rather than the end of the existing chain, is that keys deleted from +// other chains might have freed up buckets that could fall in this chain before the final key. +// Returns true if an empty bucket within the range of the displacement limit was found, in which case the final two +// pointer arguments contain the index of the empty bucket and its quadratic displacement from home_bucket. +static inline FORCE_INLINE bool VT_CAT( NAME, _find_first_empty )( + NAME *table, + size_t home_bucket, + size_t *empty, + uint16_t *displacement +) +{ + *displacement = 1; + size_t linear_dispacement = 1; + + while( true ) + { + *empty = ( home_bucket + linear_dispacement ) & table->buckets_mask; + if( table->metadata[ *empty ] == VT_EMPTY ) + return true; + + if( VT_UNLIKELY( ++*displacement == VT_DISPLACEMENT_MASK ) ) + return false; + + linear_dispacement += *displacement; + } +} + +// Finds the key in the chain beginning in home_bucket after which to link a new key with displacement_to_empty +// quadratic displacement and returns the index of the bucket containing that key. +// Although the new key could simply be linked to the end of the chain, keeping the chain ordered by displacement +// theoretically improves cache locality during lookups. +static inline FORCE_INLINE size_t VT_CAT( NAME, _find_insert_location_in_chain )( + NAME *table, + size_t home_bucket, + uint16_t displacement_to_empty +) +{ + size_t candidate = home_bucket; + while( true ) + { + uint16_t displacement = table->metadata[ candidate ] & VT_DISPLACEMENT_MASK; + + if( displacement > displacement_to_empty ) + return candidate; + + candidate = ( home_bucket + vt_quadratic( displacement ) ) & table->buckets_mask; + } +} + +// Frees up a bucket occupied by a key not belonging there so that a new key belonging there can be placed there as the +// beginning of a new chain. +// This requires: +// * Finding the previous key in the chain to which the occupying key belongs by rehashing it and then traversing the +// chain. +// * Disconnecting the key from the chain. +// * Finding the appropriate empty bucket to which to move the key. +// * Moving the key (and value) data to the empty bucket. +// * Re-linking the key to the chain. +// Returns true if the eviction succeeded, or false if no empty bucket to which to evict the occupying key could be +// found within the displacement limit. +static inline FORCE_INLINE bool VT_CAT( NAME, _evict )( NAME *table, size_t bucket ) +{ + // Find the previous key in chain. + size_t home_bucket = HASH_FN( table->buckets[ bucket ].key ) & table->buckets_mask; + size_t prev = home_bucket; + while( true ) + { + size_t next = ( home_bucket + vt_quadratic( table->metadata[ prev ] & VT_DISPLACEMENT_MASK ) ) & + table->buckets_mask; + + if( next == bucket ) + break; + + prev = next; + } + + // Disconnect the key from chain. + table->metadata[ prev ] = ( table->metadata[ prev ] & ~VT_DISPLACEMENT_MASK ) | ( table->metadata[ bucket ] & + VT_DISPLACEMENT_MASK ); + + // Find the empty bucket to which to move the key. + size_t empty; + uint16_t displacement; + if( VT_UNLIKELY( !VT_CAT( NAME, _find_first_empty )( table, home_bucket, &empty, &displacement ) ) ) + return false; + + // Find the key in the chain after which to link the moved key. + prev = VT_CAT( NAME, _find_insert_location_in_chain )( table, home_bucket, displacement ); + + // Move the key (and value) data. + table->buckets[ empty ] = table->buckets[ bucket ]; + + // Re-link the key to the chain from its new bucket. + table->metadata[ empty ] = ( table->metadata[ bucket ] & VT_HASH_FRAG_MASK ) | ( table->metadata[ prev ] & + VT_DISPLACEMENT_MASK ); + table->metadata[ prev ] = ( table->metadata[ prev ] & ~VT_DISPLACEMENT_MASK ) | displacement; + + return true; +} + +// Returns an end iterator, i.e. any iterator for which .metadatum == .metadata_end. +// This function just cleans up the library code in functions that return an end iterator as a failure indicator. +static inline FORCE_INLINE VT_CAT( NAME, _itr ) VT_CAT( NAME, _end_itr )( void ) +{ + VT_CAT( NAME, _itr ) itr = { NULL, NULL, NULL, 0 }; + return itr; +} + +// Inserts a key, optionally replacing the existing key if it already exists. +// There are two main cases that must be handled: +// * If the key's home bucket is empty or occupied by a key that does not belong there, then the key is inserted there, +// evicting the occupying key if there is one. +// * Otherwise, the chain of keys beginning at the home bucket is (if unique is false) traversed in search of a matching +// key. +// If none is found, then the new key is inserted at the earliest available bucket, per quadratic probing from the +// home bucket, and then linked to the chain in a manner that maintains its quadratic order. +// The unique argument tells the function whether to skip searching for the key before inserting it (on rehashing, this +// step is unnecessary). +// The replace argument tells the function whether to replace an existing key. +// If replace is true, the function returns an iterator to the inserted key, or an end iterator if the key was not +// inserted because of the maximum load factor or displacement limit constraints. +// If replace is false, then the return value is as described above, except that if the key already exists, the function +// returns an iterator to the existing key. +static inline FORCE_INLINE VT_CAT( NAME, _itr ) VT_CAT( NAME, _insert_raw )( + NAME *table, + KEY_TY key, + #ifdef VAL_TY + VAL_TY *val, + #endif + bool unique, + bool replace +) +{ + uint64_t hash = HASH_FN( key ); + uint16_t hashfrag = vt_hashfrag( hash ); + size_t home_bucket = hash & table->buckets_mask; + + // Case 1: The home bucket is empty or contains a key that doesn't belong there. + // This case also implicitly handles the case of a zero bucket count, since home_bucket will be zero and metadata[ 0 ] + // will be the empty placeholder. + // In that scenario, the zero buckets_mask triggers the below load-factor check. + if( !( table->metadata[ home_bucket ] & VT_IN_HOME_BUCKET_MASK ) ) + { + if( + // Load-factor check. + VT_UNLIKELY( table->key_count + 1 > VT_CAT( NAME, _bucket_count )( table ) * MAX_LOAD ) || + // Vacate the home bucket if it contains a key. + ( table->metadata[ home_bucket ] != VT_EMPTY && VT_UNLIKELY( !VT_CAT( NAME, _evict )( table, home_bucket ) ) ) + ) + return VT_CAT( NAME, _end_itr )(); + + table->buckets[ home_bucket ].key = key; + #ifdef VAL_TY + table->buckets[ home_bucket ].val = *val; + #endif + table->metadata[ home_bucket ] = hashfrag | VT_IN_HOME_BUCKET_MASK | VT_DISPLACEMENT_MASK; + + ++table->key_count; + + VT_CAT( NAME, _itr ) itr = { + table->buckets + home_bucket, + table->metadata + home_bucket, + table->metadata + table->buckets_mask + 1, // Iteration stopper (i.e. the first of the four excess metadata). + home_bucket + }; + return itr; + } + + // Case 2: The home bucket contains the beginning of a chain. + + // Optionally, check the existing chain. + if( !unique ) + { + size_t bucket = home_bucket; + while( true ) + { + if( + ( table->metadata[ bucket ] & VT_HASH_FRAG_MASK ) == hashfrag && + VT_LIKELY( CMPR_FN( table->buckets[ bucket ].key, key ) ) + ) + { + if( replace ) + { + #ifdef KEY_DTOR_FN + KEY_DTOR_FN( table->buckets[ bucket ].key ); + #endif + table->buckets[ bucket ].key = key; + + #ifdef VAL_TY + #ifdef VAL_DTOR_FN + VAL_DTOR_FN( table->buckets[ bucket ].val ); + #endif + table->buckets[ bucket ].val = *val; + #endif + } + + VT_CAT( NAME, _itr ) itr = { + table->buckets + bucket, + table->metadata + bucket, + table->metadata + table->buckets_mask + 1, + home_bucket + }; + return itr; + } + + uint16_t displacement = table->metadata[ bucket ] & VT_DISPLACEMENT_MASK; + if( displacement == VT_DISPLACEMENT_MASK ) + break; + + bucket = ( home_bucket + vt_quadratic( displacement ) ) & table->buckets_mask; + } + } + + size_t empty; + uint16_t displacement; + if( + VT_UNLIKELY( + // Load-factor check. + table->key_count + 1 > VT_CAT( NAME, _bucket_count )( table ) * MAX_LOAD || + // Find the earliest empty bucket, per quadratic probing. + !VT_CAT( NAME, _find_first_empty )( table, home_bucket, &empty, &displacement ) + ) + ) + return VT_CAT( NAME, _end_itr )(); + + // Insert the new key (and value) in the empty bucket and link it to the chain. + + size_t prev = VT_CAT( NAME, _find_insert_location_in_chain )( table, home_bucket, displacement ); + + table->buckets[ empty ].key = key; + #ifdef VAL_TY + table->buckets[ empty ].val = *val; + #endif + table->metadata[ empty ] = hashfrag | ( table->metadata[ prev ] & VT_DISPLACEMENT_MASK ); + table->metadata[ prev ] = ( table->metadata[ prev ] & ~VT_DISPLACEMENT_MASK ) | displacement; + + ++table->key_count; + + VT_CAT( NAME, _itr ) itr = { + table->buckets + empty, + table->metadata + empty, + table->metadata + table->buckets_mask + 1, + home_bucket + }; + return itr; +} + +// Resizes the bucket array. +// This function assumes that bucket_count is a power of two and large enough to accommodate all keys without violating +// the maximum load factor. +// Returns false in the case of allocation failure. +// As this function is called very rarely in _insert and _get_or_insert, ideally it should not be inlined into those +// functions. +// In testing, the no-inline approach showed a performance benefit when inserting existing keys (i.e. replacing). +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wattributes" // Silence warning about combining noinline with static inline FORCE_INLINE. +__attribute__((noinline)) static inline +#elif defined( _MSC_VER ) +__declspec(noinline) static inline +#else +static inline +#endif +bool VT_CAT( NAME, _rehash )( NAME *table, size_t bucket_count ) +{ + // The attempt to resize the bucket array and rehash the keys must occur inside a loop that incrementally doubles the + // target bucket count because a failure could theoretically occur at any load factor due to the displacement limit. + while( true ) + { + NAME new_table = { + 0, + bucket_count - 1, + NULL, + NULL + #ifdef CTX_TY + , table->ctx + #endif + }; + + void *allocation = MALLOC_FN( + VT_CAT( NAME, _total_alloc_size )( &new_table ) + #ifdef CTX_TY + , &new_table.ctx + #endif + ); + + if( VT_UNLIKELY( !allocation ) ) + return false; + + new_table.buckets = (VT_CAT( NAME, _bucket ) *)allocation; + new_table.metadata = (uint16_t *)( (unsigned char *)allocation + VT_CAT( NAME, _metadata_offset )( &new_table ) ); + + memset( new_table.metadata, 0x00, ( bucket_count + 4 ) * sizeof( uint16_t ) ); + + // Iteration stopper at the end of the actual metadata array (i.e. the first of the four excess metadata). + new_table.metadata[ bucket_count ] = 0x01; + + for( size_t bucket = 0; bucket < VT_CAT( NAME, _bucket_count )( table ); ++bucket ) + if( table->metadata[ bucket ] != VT_EMPTY ) + { + VT_CAT( NAME, _itr ) itr = VT_CAT( NAME, _insert_raw )( + &new_table, + table->buckets[ bucket ].key, + #ifdef VAL_TY + &table->buckets[ bucket ].val, + #endif + true, + false + ); + + if( VT_UNLIKELY( VT_CAT( NAME, _is_end )( itr ) ) ) + break; + } + + // If a key could not be reinserted due to the displacement limit, double the bucket count and retry. + if( VT_UNLIKELY( new_table.key_count < table->key_count ) ) + { + FREE_FN( + new_table.buckets, + VT_CAT( NAME, _total_alloc_size )( &new_table ) + #ifdef CTX_TY + , &new_table.ctx + #endif + ); + + bucket_count *= 2; + continue; + } + + if( table->buckets_mask ) + FREE_FN( + table->buckets, + VT_CAT( NAME, _total_alloc_size )( table ) + #ifdef CTX_TY + , &table->ctx + #endif + ); + + *table = new_table; + return true; + } +} +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif + +// Inserts a key, replacing the existing key if it already exists. +// This function wraps insert_raw in a loop that handles growing and rehashing the table if a new key cannot be inserted +// because of the maximum load factor or displacement limit constraints. +// Returns an iterator to the inserted key, or an end iterator in the case of allocation failure. +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _insert )( + NAME *table, + KEY_TY key + #ifdef VAL_TY + , VAL_TY val + #endif +) +{ + while( true ) + { + VT_CAT( NAME, _itr ) itr = VT_CAT( NAME, _insert_raw )( + table, + key, + #ifdef VAL_TY + &val, + #endif + false, + true + ); + + if( + // Lookup succeeded, in which case itr points to the found key. + VT_LIKELY( !VT_CAT( NAME, _is_end )( itr ) ) || + // Lookup failed and rehash also fails, in which case itr is an end iterator. + VT_UNLIKELY( + !VT_CAT( NAME, _rehash )( + table, table->buckets_mask ? VT_CAT( NAME, _bucket_count )( table ) * 2 : VT_MIN_NONZERO_BUCKET_COUNT + ) + ) + ) + return itr; + } +} + +// Same as NAME_insert, except that if the key already exists, no insertion occurs and the function returns an iterator +// to the existing key. +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _get_or_insert )( + NAME *table, + KEY_TY key + #ifdef VAL_TY + , VAL_TY val + #endif +) +{ + while( true ) + { + VT_CAT( NAME, _itr ) itr = VT_CAT( NAME, _insert_raw )( + table, + key, + #ifdef VAL_TY + &val, + #endif + false, + false + ); + + if( + // Lookup succeeded, in which case itr points to the found key. + VT_LIKELY( !VT_CAT( NAME, _is_end )( itr ) ) || + // Lookup failed and rehash also fails, in which case itr is an end iterator. + VT_UNLIKELY( + !VT_CAT( NAME, _rehash )( + table, table->buckets_mask ? VT_CAT( NAME, _bucket_count )( table ) * 2 : VT_MIN_NONZERO_BUCKET_COUNT + ) + ) + ) + return itr; + } +} + +// Returns an iterator pointing to the specified key, or an end iterator if the key does not exist. +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _get )( const NAME *table, +#ifdef KEY_GET_CONST + const KEY_TY key +#else + KEY_TY key +#endif + ) +{ + uint64_t hash = HASH_FN( key ); + size_t home_bucket = hash & table->buckets_mask; + + // If the home bucket is empty or contains a key that does not belong there, then our key does not exist. + // This check also implicitly handles the case of a zero bucket count, since home_bucket will be zero and + // metadata[ 0 ] will be the empty placeholder. + if( !( table->metadata[ home_bucket ] & VT_IN_HOME_BUCKET_MASK ) ) + return VT_CAT( NAME, _end_itr )(); + + // Traverse the chain of keys belonging to the home bucket. + uint16_t hashfrag = vt_hashfrag( hash ); + size_t bucket = home_bucket; + while( true ) + { + if( + ( table->metadata[ bucket ] & VT_HASH_FRAG_MASK ) == hashfrag && + VT_LIKELY( CMPR_FN( table->buckets[ bucket ].key, key ) ) + ) + { + VT_CAT( NAME, _itr ) itr = { + table->buckets + bucket, + table->metadata + bucket, + table->metadata + table->buckets_mask + 1, + home_bucket + }; + return itr; + } + + uint16_t displacement = table->metadata[ bucket ] & VT_DISPLACEMENT_MASK; + if( displacement == VT_DISPLACEMENT_MASK ) + return VT_CAT( NAME, _end_itr )(); + + bucket = ( home_bucket + vt_quadratic( displacement ) ) & table->buckets_mask; + } +} + +// Erases the key pointed to by the specified iterator. +// The erasure always occurs at the end of the chain to which the key belongs. +// If the key to be erased is not the last in the chain, it is swapped with the last so that erasure occurs at the end. +// This helps keep a chain's keys close to their home bucket for the sake of cache locality. +// Returns true if, in the case of iteration from first to end, NAME_next should now be called on the iterator to find +// the next key. +// This return value is necessary because at the iterator location, the erasure could result in an empty bucket, a +// bucket containing a moved key already visited during the iteration, or a bucket containing a moved key not yet +// visited. +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _erase_itr_raw )( NAME *table, VT_CAT( NAME, _itr ) itr ) +{ + --table->key_count; + size_t itr_bucket = itr.metadatum - table->metadata; + + // For now, we only call the value's destructor because the key may need to be hashed below to determine the home + // bucket. + #ifdef VAL_DTOR_FN + VAL_DTOR_FN( table->buckets[ itr_bucket ].val ); + #endif + + // Case 1: The key is the only one in its chain, so just remove it. + if( + table->metadata[ itr_bucket ] & VT_IN_HOME_BUCKET_MASK && + ( table->metadata[ itr_bucket ] & VT_DISPLACEMENT_MASK ) == VT_DISPLACEMENT_MASK + ) + { + #ifdef KEY_DTOR_FN + KEY_DTOR_FN( table->buckets[ itr_bucket ].key ); + #endif + table->metadata[ itr_bucket ] = VT_EMPTY; + return true; + } + + // Case 2 and 3 require that we know the key's home bucket, which the iterator may not have recorded. + if( itr.home_bucket == SIZE_MAX ) + { + if( table->metadata[ itr_bucket ] & VT_IN_HOME_BUCKET_MASK ) + itr.home_bucket = itr_bucket; + else + itr.home_bucket = HASH_FN( table->buckets[ itr_bucket ].key ) & table->buckets_mask; + } + + // The key can now be safely destructed for cases 2 and 3. + #ifdef KEY_DTOR_FN + KEY_DTOR_FN( table->buckets[ itr_bucket ].key ); + #endif + + // Case 2: The key is the last in a multi-key chain. + // Traverse the chain from the beginning and find the penultimate key. + // Then disconnect the key and erase. + if( ( table->metadata[ itr_bucket ] & VT_DISPLACEMENT_MASK ) == VT_DISPLACEMENT_MASK ) + { + size_t bucket = itr.home_bucket; + while( true ) + { + uint16_t displacement = table->metadata[ bucket ] & VT_DISPLACEMENT_MASK; + size_t next = ( itr.home_bucket + vt_quadratic( displacement ) ) & table->buckets_mask; + if( next == itr_bucket ) + { + table->metadata[ bucket ] |= VT_DISPLACEMENT_MASK; + table->metadata[ itr_bucket ] = VT_EMPTY; + return true; + } + + bucket = next; + } + } + + // Case 3: The chain has multiple keys, and the key is not the last one. + // Traverse the chain from the key to be erased and find the last and penultimate keys. + // Disconnect the last key from the chain, and swap it with the key to erase. + size_t bucket = itr_bucket; + while( true ) + { + size_t prev = bucket; + bucket = ( itr.home_bucket + vt_quadratic( table->metadata[ bucket ] & VT_DISPLACEMENT_MASK ) ) & + table->buckets_mask; + + if( ( table->metadata[ bucket ] & VT_DISPLACEMENT_MASK ) == VT_DISPLACEMENT_MASK ) + { + table->buckets[ itr_bucket ] = table->buckets[ bucket ]; + + table->metadata[ itr_bucket ] = ( table->metadata[ itr_bucket ] & ~VT_HASH_FRAG_MASK ) | ( + table->metadata[ bucket ] & VT_HASH_FRAG_MASK ); + + table->metadata[ prev ] |= VT_DISPLACEMENT_MASK; + table->metadata[ bucket ] = VT_EMPTY; + + // Whether the iterator should be advanced depends on whether the key moved to the iterator bucket came from + // before or after that bucket. + // In the former case, the iteration would already have hit the moved key, so the iterator should still be + // advanced. + if( bucket > itr_bucket ) + return false; + + return true; + } + } +} + +// Erases the specified key, if it exists. +// Returns true if a key was erased. +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _erase )( NAME *table, KEY_TY key ) +{ + VT_CAT( NAME, _itr ) itr = VT_CAT( NAME, _get)( table, key ); + if( VT_CAT( NAME, _is_end )( itr ) ) + return false; + + VT_CAT( NAME, _erase_itr_raw )( table, itr ); + return true; +} + +// Finds the first occupied bucket at or after the bucket pointed to by itr. +// This function scans four buckets at a time, ideally using intrinsics. +static inline FORCE_INLINE void VT_CAT( NAME, _fast_forward )( VT_CAT( NAME, _itr ) *itr ) +{ + while( true ) + { + uint64_t metadata; + memcpy( &metadata, itr->metadatum, sizeof( uint64_t ) ); + if( metadata ) + { + int offset = vt_first_nonzero_uint16( metadata ); + itr->data += offset; + itr->metadatum += offset; + itr->home_bucket = SIZE_MAX; + return; + } + + itr->data += 4; + itr->metadatum += 4; + } +} + +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _next )( VT_CAT( NAME, _itr ) itr ) +{ + ++itr.data; + ++itr.metadatum; + VT_CAT( NAME, _fast_forward )( &itr ); + return itr; +} + +// Returns the minimum bucket count required to accommodate a certain number of keys, which is governed by the maximum +// load factor. +static inline FORCE_INLINE size_t VT_CAT( NAME, _min_bucket_count_for_size )( size_t size ) +{ + if( size == 0 ) + return 0; + + // Round up to a power of two. + size_t bucket_count = VT_MIN_NONZERO_BUCKET_COUNT; + while( size > bucket_count * MAX_LOAD ) + bucket_count *= 2; + + return bucket_count; +} + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _reserve )( NAME *table, size_t size ) +{ + size_t bucket_count = VT_CAT( NAME, _min_bucket_count_for_size )( size ); + + if( bucket_count <= VT_CAT( NAME, _bucket_count )( table ) ) + return true; + + return VT_CAT( NAME, _rehash )( table, bucket_count ); +} + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-qual" + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _shrink )( NAME *table ) +{ + size_t bucket_count = VT_CAT( NAME, _min_bucket_count_for_size )( table->key_count ); + + if( bucket_count == VT_CAT( NAME, _bucket_count )( table ) ) // Shrink unnecessary. + return true; + + if( bucket_count == 0 ) + { + FREE_FN( + table->buckets, + VT_CAT( NAME, _total_alloc_size )( table ) + #ifdef CTX_TY + , &table->ctx + #endif + ); + + table->buckets_mask = 0x0000000000000000ull; + table->metadata = (uint16_t *)&vt_empty_placeholder_metadatum; + return true; + } + + return VT_CAT( NAME, _rehash )( table, bucket_count ); +} + +#pragma GCC diagnostic pop + +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _first )( const NAME *table ) +{ + if( !table->key_count ) + return VT_CAT( NAME, _end_itr )(); + + VT_CAT( NAME, _itr ) itr = { table->buckets, table->metadata, table->metadata + table->buckets_mask + 1, SIZE_MAX }; + VT_CAT( NAME, _fast_forward )( &itr ); + return itr; +} + +VT_API_FN_QUALIFIERS void VT_CAT( NAME, _clear )( NAME *table ) +{ + if( !table->key_count ) + return; + + for( size_t i = 0; i < VT_CAT( NAME, _bucket_count )( table ); ++i ) + { + if( table->metadata[ i ] != VT_EMPTY ) + { + #ifdef KEY_DTOR_FN + KEY_DTOR_FN( table->buckets[ i ].key ); + #endif + #ifdef VAL_DTOR_FN + VAL_DTOR_FN( table->buckets[ i ].val ); + #endif + } + + table->metadata[ i ] = VT_EMPTY; + } + + table->key_count = 0; +} + +VT_API_FN_QUALIFIERS void VT_CAT( NAME, _cleanup )( NAME *table ) +{ + if( !table->buckets_mask ) + return; + + #if defined( KEY_DTOR_FN ) || defined( VAL_DTOR_FN ) + VT_CAT( NAME, _clear )( table ); + #endif + + FREE_FN( + table->buckets, + VT_CAT( NAME, _total_alloc_size )( table ) + #ifdef CTX_TY + , &table->ctx + #endif + ); + + VT_CAT( NAME, _init )( + table + #ifdef CTX_TY + , table->ctx + #endif + ); +} + +#endif + +/*--------------------------------------------------------------------------------------------------------------------*/ +/* Wrapper types and functions for the C11 generic API */ +/*--------------------------------------------------------------------------------------------------------------------*/ + +#if defined(__STDC_VERSION__) && \ + __STDC_VERSION__ >= 201112L && \ + !defined( IMPLEMENTATION_MODE ) && \ + !defined( VT_NO_C11_GENERIC_API ) \ + +typedef NAME VT_CAT( vt_table_, VT_TEMPLATE_COUNT ); +typedef VT_CAT( NAME, _itr ) VT_CAT( vt_table_itr_, VT_TEMPLATE_COUNT ); + +static inline FORCE_INLINE void VT_CAT( vt_init_, VT_TEMPLATE_COUNT )( + NAME *table + #ifdef CTX_TY + , CTX_TY ctx + #endif +) +{ + VT_CAT( NAME, _init )( + table + #ifdef CTX_TY + , ctx + #endif + ); +} + +static inline FORCE_INLINE bool VT_CAT( vt_init_clone_, VT_TEMPLATE_COUNT )( + NAME *table, + const NAME* source + #ifdef CTX_TY + , CTX_TY ctx + #endif +) +{ + return VT_CAT( NAME, _init_clone )( + table, + source + #ifdef CTX_TY + , ctx + #endif + ); +} + +static inline FORCE_INLINE size_t VT_CAT( vt_size_, VT_TEMPLATE_COUNT )( const NAME *table ) +{ + return VT_CAT( NAME, _size )( table ); +} + +static inline FORCE_INLINE size_t VT_CAT( vt_bucket_count_, VT_TEMPLATE_COUNT )( const NAME *table ) +{ + return VT_CAT( NAME, _bucket_count )( table ); +} + +static inline FORCE_INLINE bool VT_CAT( vt_is_end_, VT_TEMPLATE_COUNT )( VT_CAT( NAME, _itr ) itr ) +{ + return VT_CAT( NAME, _is_end )( itr ); +} + +static inline FORCE_INLINE VT_CAT( NAME, _itr ) VT_CAT( vt_insert_, VT_TEMPLATE_COUNT )( + NAME *table, + KEY_TY key + #ifdef VAL_TY + , VAL_TY val + #endif +) +{ + return VT_CAT( NAME, _insert )( + table, + key + #ifdef VAL_TY + , val + #endif + ); +} + +static inline FORCE_INLINE VT_CAT( NAME, _itr ) VT_CAT( vt_get_or_insert_, VT_TEMPLATE_COUNT )( + NAME *table, + KEY_TY key + #ifdef VAL_TY + , VAL_TY val + #endif +) +{ + return VT_CAT( NAME, _get_or_insert )( + table, + key + #ifdef VAL_TY + , val + #endif + ); +} + +static inline FORCE_INLINE VT_CAT( NAME, _itr ) VT_CAT( vt_get_, VT_TEMPLATE_COUNT )( const NAME *table, KEY_TY key ) +{ + return VT_CAT( NAME, _get )( table, key ); +} + +static inline FORCE_INLINE bool VT_CAT( vt_erase_, VT_TEMPLATE_COUNT )( NAME *table, KEY_TY key ) +{ + return VT_CAT( NAME, _erase )( table, key ); +} + +static inline FORCE_INLINE VT_CAT( NAME, _itr ) VT_CAT( vt_next_, VT_TEMPLATE_COUNT )( VT_CAT( NAME, _itr ) itr ) +{ + return VT_CAT( NAME, _next )( itr ); +} + +static inline FORCE_INLINE VT_CAT( NAME, _itr ) VT_CAT( vt_erase_itr_, VT_TEMPLATE_COUNT )( NAME *table, VT_CAT( NAME, _itr ) itr ) +{ + return VT_CAT( NAME, _erase_itr )( table, itr ); +} + +static inline FORCE_INLINE bool VT_CAT( vt_reserve_, VT_TEMPLATE_COUNT )( NAME *table, size_t bucket_count ) +{ + return VT_CAT( NAME, _reserve )( table, bucket_count ); +} + +static inline FORCE_INLINE bool VT_CAT( vt_shrink_, VT_TEMPLATE_COUNT )( NAME *table ) +{ + return VT_CAT( NAME, _shrink )( table ); +} + +static inline FORCE_INLINE VT_CAT( NAME, _itr ) VT_CAT( vt_first_, VT_TEMPLATE_COUNT )( const NAME *table ) +{ + return VT_CAT( NAME, _first )( table ); +} + +static inline FORCE_INLINE void VT_CAT( vt_clear_, VT_TEMPLATE_COUNT )( NAME *table ) +{ + VT_CAT( NAME, _clear )( table ); +} + +static inline FORCE_INLINE void VT_CAT( vt_cleanup_, VT_TEMPLATE_COUNT )( NAME *table ) +{ + VT_CAT( NAME, _cleanup )( table ); +} + +// Increment the template counter. +#if VT_TEMPLATE_COUNT_D1 == 0 +#undef VT_TEMPLATE_COUNT_D1 +#define VT_TEMPLATE_COUNT_D1 1 +#elif VT_TEMPLATE_COUNT_D1 == 1 +#undef VT_TEMPLATE_COUNT_D1 +#define VT_TEMPLATE_COUNT_D1 2 +#elif VT_TEMPLATE_COUNT_D1 == 2 +#undef VT_TEMPLATE_COUNT_D1 +#define VT_TEMPLATE_COUNT_D1 3 +#elif VT_TEMPLATE_COUNT_D1 == 3 +#undef VT_TEMPLATE_COUNT_D1 +#define VT_TEMPLATE_COUNT_D1 4 +#elif VT_TEMPLATE_COUNT_D1 == 4 +#undef VT_TEMPLATE_COUNT_D1 +#define VT_TEMPLATE_COUNT_D1 5 +#elif VT_TEMPLATE_COUNT_D1 == 5 +#undef VT_TEMPLATE_COUNT_D1 +#define VT_TEMPLATE_COUNT_D1 6 +#elif VT_TEMPLATE_COUNT_D1 == 6 +#undef VT_TEMPLATE_COUNT_D1 +#define VT_TEMPLATE_COUNT_D1 7 +#elif VT_TEMPLATE_COUNT_D1 == 7 +#undef VT_TEMPLATE_COUNT_D1 +#define VT_TEMPLATE_COUNT_D1 0 +#if VT_TEMPLATE_COUNT_D2 == 0 +#undef VT_TEMPLATE_COUNT_D2 +#define VT_TEMPLATE_COUNT_D2 1 +#elif VT_TEMPLATE_COUNT_D2 == 1 +#undef VT_TEMPLATE_COUNT_D2 +#define VT_TEMPLATE_COUNT_D2 2 +#elif VT_TEMPLATE_COUNT_D2 == 2 +#undef VT_TEMPLATE_COUNT_D2 +#define VT_TEMPLATE_COUNT_D2 3 +#elif VT_TEMPLATE_COUNT_D2 == 3 +#undef VT_TEMPLATE_COUNT_D2 +#define VT_TEMPLATE_COUNT_D2 4 +#elif VT_TEMPLATE_COUNT_D2 == 4 +#undef VT_TEMPLATE_COUNT_D2 +#define VT_TEMPLATE_COUNT_D2 5 +#elif VT_TEMPLATE_COUNT_D2 == 5 +#undef VT_TEMPLATE_COUNT_D2 +#define VT_TEMPLATE_COUNT_D2 6 +#elif VT_TEMPLATE_COUNT_D2 == 6 +#undef VT_TEMPLATE_COUNT_D2 +#define VT_TEMPLATE_COUNT_D2 7 +#elif VT_TEMPLATE_COUNT_D2 == 7 +#undef VT_TEMPLATE_COUNT_D2 +#define VT_TEMPLATE_COUNT_D2 0 +#if VT_TEMPLATE_COUNT_D3 == 0 +#undef VT_TEMPLATE_COUNT_D3 +#define VT_TEMPLATE_COUNT_D3 1 +#elif VT_TEMPLATE_COUNT_D3 == 1 +#undef VT_TEMPLATE_COUNT_D3 +#define VT_TEMPLATE_COUNT_D3 2 +#elif VT_TEMPLATE_COUNT_D3 == 2 +#undef VT_TEMPLATE_COUNT_D3 +#define VT_TEMPLATE_COUNT_D3 3 +#elif VT_TEMPLATE_COUNT_D3 == 3 +#undef VT_TEMPLATE_COUNT_D3 +#define VT_TEMPLATE_COUNT_D3 4 +#elif VT_TEMPLATE_COUNT_D3 == 4 +#undef VT_TEMPLATE_COUNT_D3 +#define VT_TEMPLATE_COUNT_D3 5 +#elif VT_TEMPLATE_COUNT_D3 == 5 +#undef VT_TEMPLATE_COUNT_D3 +#define VT_TEMPLATE_COUNT_D3 6 +#elif VT_TEMPLATE_COUNT_D3 == 6 +#undef VT_TEMPLATE_COUNT_D3 +#define VT_TEMPLATE_COUNT_D3 7 +#elif VT_TEMPLATE_COUNT_D3 == 7 +#error Sorry, the number of template instances is limited to 511. Define VT_NO_C11_GENERIC_API globally and use the \ +C99 prefixed function API to circumvent this restriction. +#endif +#endif +#endif + +#pragma GCC diagnostic pop + +#endif + +#undef NAME +#undef KEY_TY +#undef KEY_GET_CONST +#undef VAL_TY +#undef HASH_FN +#undef CMPR_FN +#undef MAX_LOAD +#undef KEY_DTOR_FN +#undef VAL_DTOR_FN +#undef CTX_TY +#undef MALLOC_FN +#undef FREE_FN +#undef HEADER_MODE +#undef IMPLEMENTATION_MODE +#undef VT_API_FN_QUALIFIERS + +#undef FORCE_INLINE diff --git a/src/w_wad.c b/src/w_wad.c index 640ee0367..5d0771dc3 100644 --- a/src/w_wad.c +++ b/src/w_wad.c @@ -87,18 +87,32 @@ typedef struct } lumpchecklist_t; // Must be a power of two -#define LUMPNUMCACHESIZE 64 +#define LUMPNUMCACHESIZE 2048 // should be reasonable ig #define LUMPNUMCACHENAME 32 -typedef struct lumpnum_cache_s -{ - char lumpname[LUMPNUMCACHENAME]; - lumpnum_t lumpnum; - UINT32 hash; -} lumpnum_cache_t; +#define NAME lumpnum_map +#define KEY_TY char * +#define KEY_GET_CONST +#define VAL_TY lumpnum_t +#define HASH_FN vt_hash_string +#define CMPR_FN vt_cmpr_string +#define KEY_DTOR_FN free +#include "verstable.h" -static lumpnum_cache_t lumpnumcache[LUMPNUMCACHESIZE]; -static UINT16 lumpnumcacheindex = 0; +#define NAME folder_map +#define KEY_TY char * +#define KEY_GET_CONST +#define VAL_TY UINT16 +#define HASH_FN vt_hash_string +#define CMPR_FN vt_cmpr_string +#define KEY_DTOR_FN free +#include "verstable.h" + +static lumpnum_map lumpnumcache; + +typedef struct FolderCache { + folder_map map; +} FolderCache; static const char pat_central[] = {0x50, 0x4b, 0x01, 0x02, 0x00}; static const char pat_end[] = {0x50, 0x4b, 0x05, 0x06, 0x00}; @@ -109,34 +123,50 @@ static const char pat_end[] = {0x50, 0x4b, 0x05, 0x06, 0x00}; UINT16 numwadfiles = 0; // number of active wadfiles wadfile_t *wadfiles[MAX_WADFILES] = {}; // 0 to numwadfiles-1 are valid +// use strnlen as some lump names may not be null terminated +#define CHECKMAPMARKER(name) (memcmp(name, "MAP", 3) == 0 && strnlen(name, 8) == 5) + // W_Shutdown // Closes all of the WAD files before quitting // If not done on a Mac then open wad files // can prevent removable media they are on from // being ejected -void W_Shutdown(void) +DESTRUCTOR static void W_Shutdown(void) { + lumpnum_map_cleanup(&lumpnumcache); + while (numwadfiles--) { wadfile_t *wad = wadfiles[numwadfiles]; if (wad->handle) fclose(wad->handle); + Z_Free(wad->filename); + while (wad->numlumps--) { - Z_Free(wad->lumpinfo[wad->numlumps].longname); + //Z_Free(wad->lumpinfo[wad->numlumps].longname); Z_Free(wad->lumpinfo[wad->numlumps].fullname); } - M_AATreeFree(wad->startfolders); - M_AATreeFree(wad->endfolders); + folder_map_cleanup(&wad->startfolders->map); + free(wad->startfolders); + folder_map_cleanup(&wad->endfolders->map); + free(wad->endfolders); Z_Free(wad->lumpinfo); Z_Free(wad); } } +// the lumpnum cache needs to be initialized before use +CONSTRUCTOR static void W_Startup(void) +{ + lumpnum_map_init(&lumpnumcache); + lumpnum_map_reserve(&lumpnumcache, LUMPNUMCACHESIZE); +} + //=========================================================================== // LUMP BASED ROUTINES //=========================================================================== @@ -257,13 +287,12 @@ static inline void W_LoadDehackedLumpsPK3(UINT16 wadnum) lumpinfo_t *lump_p = &wadfiles[wadnum]->lumpinfo[posStart]; size_t length = len + 1 + strlen(lump_p->fullname); // length of file name, '|', and lump name - char *name = malloc(length + 1); + char *name = (char *)(malloc(length + 1)); if (!name) I_Error("W_LoadDehackedLumpsPK3: Out of memory!\n"); - sprintf(name, "%s|%s", wadfiles[wadnum]->filename, lump_p->fullname); - name[length] = '\0'; + snprintf(name, length + 1, "%s|%s", wadfiles[wadnum]->filename, lump_p->fullname); CONS_Printf("Loading SOC from %s\n", name); DEH_LoadDehackedLumpPwad(wadnum, posStart); free(name); @@ -293,13 +322,12 @@ static inline void W_LoadDehackedLumps(UINT16 wadnum) if (memcmp(lump_p->name, "SOC_", 4) == 0) // Check for generic SOC lump { // shameless copy+paste of code from LUA_LoadLump size_t length = len + 1 + strlen(lump_p->fullname); // length of file name, '|', and lump name - char *name = malloc(length + 1); + char *name = (char *)(malloc(length + 1)); if (!name) I_Error("W_LoadDehackedLumps: Out of memory!\n"); - sprintf(name, "%s|%s", wadfiles[wadnum]->filename, lump_p->fullname); - name[length] = '\0'; + snprintf(name, length + 1, "%s|%s", wadfiles[wadnum]->filename, lump_p->fullname); CONS_Printf(M_GetText("Loading SOC from %s\n"), name); DEH_LoadDehackedLumpPwad(wadnum, lump); @@ -337,9 +365,9 @@ static inline INT32 W_MakeFileMD5(const char *filename, void *resblock) if ((fhandle = fopen(filename, "rb")) != NULL) { - tic_t t = I_GetTime(); + precise_t t = I_GetPreciseTime(); - CONS_Debug(DBG_SETUP, "Making MD5 for %s\n",filename); + CONS_Debug(DBG_SETUP, "Making MD5 for %s\n", filename); if (md5_stream(fhandle, resblock) == 1) { @@ -348,7 +376,7 @@ static inline INT32 W_MakeFileMD5(const char *filename, void *resblock) } CONS_Debug(DBG_SETUP, "MD5 calc for %s took %f seconds\n", - filename, (float)(I_GetTime() - t)/NEWTICRATE); + filename, (float)(I_GetPreciseTime() - t)/I_GetPrecisePrecision()); fclose(fhandle); return 0; @@ -358,12 +386,12 @@ static inline INT32 W_MakeFileMD5(const char *filename, void *resblock) } // Invalidates the cache of lump numbers. Call this whenever a wad is added. -static void W_InvalidateLumpnumCache(void) +FUNCINLINE static ATTRINLINE void W_InvalidateLumpnumCache(void) { - memset(lumpnumcache, 0, sizeof(lumpnumcache)); + lumpnum_map_clear(&lumpnumcache); } -UINT32 W_HashLumpName(const char *name) +FUNCINLINE static ATTRINLINE UINT32 W_HashLumpName(const char *name) { return FNV1a_HashLowercaseString(name); } @@ -389,28 +417,28 @@ static restype_t ResourceFileDetect(const char* filename) */ static lumpinfo_t* ResGetLumpsStandalone(FILE* handle, UINT16* numlumps, const char* lumpname) { - lumpinfo_t* lumpinfo = Z_Calloc(sizeof (*lumpinfo), PU_STATIC, NULL); + lumpinfo_t* lumpinfo = (lumpinfo_t *)(Z_Calloc(sizeof (*lumpinfo), PU_STATIC, NULL)); lumpinfo->position = 0; fseek(handle, 0, SEEK_END); - lumpinfo->size = ftell(handle); + lumpinfo->size = (size_t)(ftell(handle)); fseek(handle, 0, SEEK_SET); strlcpy(lumpinfo->name, lumpname, sizeof(lumpinfo->name)); lumpinfo->namelength = strlen(lumpinfo->name); lumpinfo->hash.name = W_HashLumpName(lumpname); // Allocate the lump's long name. - lumpinfo->longname = Z_Malloc((lumpinfo->namelength + 1) * sizeof(char), PU_STATIC, NULL); + /*lumpinfo->longname = (char *)(Z_Malloc((lumpinfo->namelength + 1) * sizeof(char), PU_STATIC, NULL)); strcpy(lumpinfo->longname, lumpname); lumpinfo->longname[lumpinfo->namelength] = '\0'; lumpinfo->longnamelength = lumpinfo->namelength; - lumpinfo->hash.longname = lumpinfo->hash.name; + lumpinfo->hash.longname = lumpinfo->hash.name;*/ // Allocate the lump's full name. - lumpinfo->fullname = Z_Malloc((lumpinfo->namelength + 1) * sizeof(char), PU_STATIC, NULL); + lumpinfo->fullname = (char *)(Z_Malloc((lumpinfo->namelength + 1) * sizeof(char), PU_STATIC, NULL)); strcpy(lumpinfo->fullname, lumpname); lumpinfo->fullname[lumpinfo->namelength] = '\0'; lumpinfo->fullnamelength = lumpinfo->namelength; - lumpinfo->hash.fullname = lumpinfo->hash.name; + //lumpinfo->hash.fullname = lumpinfo->hash.name; *numlumps = 1; return lumpinfo; @@ -453,8 +481,8 @@ static lumpinfo_t* ResGetLumpsWad(FILE* handle, UINT16* nlmp, const char* filena header.infotableofs = LONG(header.infotableofs); // read wad file directory - i = header.numlumps * sizeof (*fileinfo); - fileinfov = fileinfo = malloc(i); + i = header.numlumps * sizeof(*fileinfo); + fileinfov = fileinfo = (filelump_t *)(malloc(i)); if (fseek(handle, header.infotableofs, SEEK_SET) == -1 || fread(fileinfo, 1, i, handle) < i) @@ -466,7 +494,7 @@ static lumpinfo_t* ResGetLumpsWad(FILE* handle, UINT16* nlmp, const char* filena numlumps = header.numlumps; // fill in lumpinfo for this wad - lump_p = lumpinfo = Z_Malloc(numlumps * sizeof (*lumpinfo), PU_STATIC, NULL); + lump_p = lumpinfo = (lumpinfo_t *)(Z_Malloc(numlumps * sizeof (*lumpinfo), PU_STATIC, NULL)); for (i = 0; i < numlumps; i++, lump_p++, fileinfo++) { @@ -510,18 +538,18 @@ static lumpinfo_t* ResGetLumpsWad(FILE* handle, UINT16* nlmp, const char* filena lump_p->hash.name = W_HashLumpName(lump_p->name); // Allocate the lump's long name. - lump_p->longname = Z_Malloc(9 * sizeof(char), PU_STATIC, NULL); + /*lump_p->longname = (char *)(Z_Malloc(9 * sizeof(char), PU_STATIC, NULL)); strncpy(lump_p->longname, fileinfo->name, 8); lump_p->longname[8] = '\0'; lump_p->longnamelength = lump_p->namelength; - lump_p->hash.longname = lump_p->hash.name; + lump_p->hash.longname = lump_p->hash.name;*/ // Allocate the lump's full name. - lump_p->fullname = Z_Malloc(9 * sizeof(char), PU_STATIC, NULL); + lump_p->fullname = (char *)(Z_Malloc(9 * sizeof(char), PU_STATIC, NULL)); strncpy(lump_p->fullname, fileinfo->name, 8); lump_p->fullname[8] = '\0'; lump_p->fullnamelength = lump_p->namelength; - lump_p->hash.fullname = lump_p->hash.name; + //lump_p->hash.fullname = lump_p->hash.name; } *nlmp = numlumps; @@ -538,24 +566,24 @@ static boolean ResFindSignature(FILE* handle, const char endPat[], UINT32 startp int c; fseek(handle, 0, SEEK_END); - size_t len = ftell(handle); + size_t len = (size_t)(ftell(handle)); fseek(handle, startpos, SEEK_SET); - size_t remaining = len - startpos; - size_t chunkpos = startpos; + size_t remaining = (size_t)(len - startpos); + size_t chunkpos = (size_t)(startpos); s = endPat; //128k buffers size_t buffer_size = min(128 * 1024 * sizeof(char), remaining); - CLEANUP(pfree) char* buffer = (char*)(malloc(buffer_size)); + CLEANUP(pfree) char* buffer = (char *)(malloc(buffer_size)); size_t bytes_read = 0; while ((bytes_read = fread(buffer, 1, buffer_size, handle)) > 0) { for (size_t i = 0; i < bytes_read; i++) { - c = (int)buffer[i]; + c = (int)(buffer[i]); if (*s != c && s > endPat) // No match? s = endPat; // We "reset" the counter by sending the s pointer back to the start of the array. @@ -567,7 +595,7 @@ static boolean ResFindSignature(FILE* handle, const char endPat[], UINT32 startp if (*s == 0x00) // The array pointer has reached the key char which marks the end. It means we have matched the signature. { //the original function would leave the FILE* seeked to the end of the match - size_t foundpos = chunkpos + i + 1; + size_t foundpos = (size_t)(chunkpos + i + 1); fseek(handle, foundpos, SEEK_SET); return true; } @@ -644,7 +672,7 @@ static lumpinfo_t* ResGetLumpsZip(FILE* handle, UINT16* nlmp) // Contains entry number (number of lumps), and central directory start offset. fseek(handle, 0, SEEK_END); - const long startpos = (ftell(handle) - (22 + 65536)); + const long startpos = ftell(handle) - (22 + 65536); if (!ResFindSignature(handle, pat_end, max(0l, startpos))) { CONS_Alert(CONS_ERROR, "Missing central directory\n"); @@ -660,11 +688,11 @@ static lumpinfo_t* ResGetLumpsZip(FILE* handle, UINT16* nlmp) numlumps = SHORT(zend.entries); - lump_p = lumpinfo = Z_Malloc(numlumps * sizeof (*lumpinfo), PU_STATIC, NULL); + lump_p = lumpinfo = (lumpinfo_t *)(Z_Malloc(numlumps * sizeof (*lumpinfo), PU_STATIC, NULL)); fseek(handle, LONG(zend.cdiroffset), SEEK_SET); - CLEANUP(Z_Pfree) char *cdir = Z_Malloc(LONG(zend.cdirsize), PU_STATIC, &cdir); + CLEANUP(Z_Pfree) char *cdir = (char *)(Z_Malloc(LONG(zend.cdirsize), PU_STATIC, &cdir)); if (fread(cdir, 1, LONG(zend.cdirsize), handle) < (UINT32)(LONG(zend.cdirsize))) { @@ -677,7 +705,7 @@ static lumpinfo_t* ResGetLumpsZip(FILE* handle, UINT16* nlmp) for (i = 0; i < numlumps; i++, lump_p++) { - zentry_t *zentry = (zentry_t*)(cdir + offset); + zentry_t *zentry = (zentry_t *)(cdir + offset); char* fullname; char* trimname; char* dotpos; @@ -693,16 +721,17 @@ static lumpinfo_t* ResGetLumpsZip(FILE* handle, UINT16* nlmp) lump_p->disksize = LONG(zentry->compsize); lump_p->size = LONG(zentry->size); - fullname = (char*)(malloc(SHORT(zentry->namelen) + 1)); - strlcpy(fullname, (char*)(zentry + 1), SHORT(zentry->namelen) + 1); + fullname = (char *)(malloc(SHORT(zentry->namelen) + 1)); + strncpy(fullname, (char *)(zentry + 1), SHORT(zentry->namelen)); + fullname[zentry->namelen] = 0; // Strip away file address and extension for the 8char name. - if ((trimname = strrchr(fullname, '/')) != 0) + if ((trimname = strrchr(fullname, '/')) != NULL) trimname++; else trimname = fullname; // Care taken for root files. - if ((dotpos = strrchr(trimname, '.')) == 0) + if ((dotpos = strrchr(trimname, '.')) == NULL) dotpos = fullname + strlen(fullname); // Watch for files without extension. memset(lump_p->name, '\0', 9); // Making sure they're initialized to 0. Is it necessary? @@ -710,15 +739,15 @@ static lumpinfo_t* ResGetLumpsZip(FILE* handle, UINT16* nlmp) lump_p->namelength = strlen(lump_p->name); lump_p->hash.name = W_HashLumpName(lump_p->name); - lump_p->longname = Z_Calloc(dotpos - trimname + 1, PU_STATIC, NULL); + /*lump_p->longname = (char *)(Z_Calloc(dotpos - trimname + 1, PU_STATIC, NULL)); strlcpy(lump_p->longname, trimname, dotpos - trimname + 1); lump_p->longnamelength = strlen(lump_p->longname); - lump_p->hash.longname = W_HashLumpName(lump_p->longname); + lump_p->hash.longname = W_HashLumpName(lump_p->longname);*/ - lump_p->fullname = (char*)(Z_Calloc(SHORT(zentry->namelen) + 1, PU_STATIC, NULL)); + lump_p->fullname = (char *)(Z_Calloc(SHORT(zentry->namelen) + 1, PU_STATIC, NULL)); strncpy(lump_p->fullname, fullname, SHORT(zentry->namelen)); lump_p->fullnamelength = zentry->namelen; - lump_p->hash.fullname = W_HashLumpName(lump_p->fullname); + //lump_p->hash.fullname = W_HashLumpName(lump_p->fullname); switch(SHORT(zentry->compression)) { @@ -893,17 +922,19 @@ UINT16 W_InitFile(const char *filename, boolean local, boolean startup) // // link wad file to search files // - wadfile = Z_Calloc(sizeof (*wadfile), PU_STATIC, NULL); + wadfile = (wadfile_t *)(Z_Calloc(sizeof (*wadfile), PU_STATIC, NULL)); wadfile->filename = Z_StrDup(filename); wadfile->handle = handle; - wadfile->numlumps = (UINT16)numlumps; + wadfile->numlumps = (UINT16)(numlumps); wadfile->lumpinfo = lumpinfo; wadfile->important = important; fseek(handle, 0, SEEK_END); - wadfile->filesize = (unsigned)ftell(handle); + wadfile->filesize = (unsigned)(ftell(handle)); wadfile->type = type; - wadfile->startfolders = M_AATreeAlloc(AATREE_STRING); - wadfile->endfolders = M_AATreeAlloc(AATREE_STRING); + wadfile->startfolders = (FolderCache *)malloc(sizeof(FolderCache)); + folder_map_init(&wadfile->startfolders->map); + wadfile->endfolders = (FolderCache *)malloc(sizeof(FolderCache)); + folder_map_init(&wadfile->endfolders->map); // already generated, just copy it over memcpy(&wadfile->md5sum, &md5sum, 16); @@ -928,7 +959,7 @@ UINT16 W_InitFile(const char *filename, boolean local, boolean startup) #ifdef HWRENDER // Read shaders from file if (rendermode == render_opengl && (vid.glstate == VID_GL_LIBRARY_LOADED)) - HWR_LoadCustomShadersFromFile(numwadfiles - 1, (type == RET_PK3)); + HWR_LoadCustomShadersFromFile(numwadfiles - 1, (boolean)(type == RET_PK3)); #endif // TODO: HACK ALERT - Load Lua & SOC stuff right here. I feel like this should be out of this place, but... Let's stick with this for now. @@ -1028,7 +1059,7 @@ INT32 W_AddAutoloadedLocalFiles(char **filenames) /** Make sure a lump number is valid. * Compiles away to nothing if PARANOIA is not defined. */ -static boolean TestValidLump(UINT16 wad, UINT16 lump) +static inline boolean TestValidLump(UINT16 wad, UINT16 lump) { I_Assert(wad < MAX_WADFILES); if (!wadfiles[wad]) // make sure the wad file exists @@ -1051,7 +1082,7 @@ const char *W_CheckNameForNumPwad(UINT16 wad, UINT16 lump) const char *W_CheckNameForNum(lumpnum_t lumpnum) { - return W_CheckNameForNumPwad(WADFILENUM(lumpnum),LUMPNUM(lumpnum)); + return W_CheckNameForNumPwad(WADFILENUM(lumpnum), LUMPNUM(lumpnum)); } // @@ -1105,7 +1136,7 @@ UINT16 W_CheckNumForNamePwad(const char *name, UINT16 wad, UINT16 startlump) // Should be the only version, but that's not possible until we fix // all the instances of non null-terminated strings in the codebase... // -UINT16 W_CheckNumForLongNamePwad(const char *name, UINT16 wad, UINT16 startlump) +/*UINT16 W_CheckNumForLongNamePwad(const char *name, UINT16 wad, UINT16 startlump) { UINT16 i; UINT32 hash; @@ -1137,43 +1168,46 @@ UINT16 W_CheckNumForLongNamePwad(const char *name, UINT16 wad, UINT16 startlump) // not found. return INT16_MAX; -} +}*/ UINT16 W_CheckNumForMarkerStartPwad(const char *name, UINT16 wad, UINT16 startlump) { UINT16 marker; + marker = W_CheckNumForNamePwad(name, wad, startlump); if (marker != INT16_MAX) marker++; // Do not count the first marker + return marker; } // Look for the first lump from a folder. UINT16 W_CheckNumForFolderStartPK3(const char *name, UINT16 wad, UINT16 startlump) { - size_t name_length; - INT32 i; + UINT16 i; + size_t namelen; lumpinfo_t *lump_p = wadfiles[wad]->lumpinfo + startlump; - name_length = strlen(name); - void *val = M_AATreeGetString(wadfiles[wad]->startfolders, name); - if (val != NULL) - return (uintptr_t)val; + folder_map_itr it = folder_map_get(&wadfiles[wad]->startfolders->map, name); + if (!folder_map_is_end(it)) + return it.data->val; + + namelen = strlen(name); for (i = startlump; i < wadfiles[wad]->numlumps; i++, lump_p++) { - if (strnicmp(name, lump_p->fullname, name_length) == 0) + if (strnicmp(name, lump_p->fullname, namelen) == 0) { /* SLADE is special and puts a single directory entry. Skip that. */ - if (strlen(lump_p->fullname) == name_length) + if (lump_p->fullnamelength == namelen) i++; - M_AATreeSetString(wadfiles[wad]->startfolders, name, (void *)(uintptr_t)i); + folder_map_insert(&wadfiles[wad]->startfolders->map, strdup(name), i); return i; } } - M_AATreeSetString(wadfiles[wad]->startfolders, name, (void *)INT16_MAX); + folder_map_insert(&wadfiles[wad]->startfolders->map, strdup(name), INT16_MAX); return INT16_MAX; } @@ -1182,21 +1216,23 @@ UINT16 W_CheckNumForFolderStartPK3(const char *name, UINT16 wad, UINT16 startlum // Returns the position of the lumpinfo entry. UINT16 W_CheckNumForFolderEndPK3(const char *name, UINT16 wad, UINT16 startlump) { - INT32 i; + UINT16 i; + size_t namelen; lumpinfo_t *lump_p = wadfiles[wad]->lumpinfo + startlump; - size_t name_length = strlen(name); - void *val = M_AATreeGetString(wadfiles[wad]->endfolders, name); - if (val != NULL) - return (uintptr_t)val; + folder_map_itr it = folder_map_get(&wadfiles[wad]->endfolders->map, name); + if (!folder_map_is_end(it)) + return it.data->val; + + namelen = strlen(name); for (i = startlump; i < wadfiles[wad]->numlumps; i++, lump_p++) { - if (strnicmp(name, lump_p->fullname, name_length)) + if (strnicmp(name, lump_p->fullname, namelen)) break; } - M_AATreeSetString(wadfiles[wad]->endfolders, name, (void *)(uintptr_t)i); + folder_map_insert(&wadfiles[wad]->endfolders->map, strdup(name), i); return i; } @@ -1204,13 +1240,15 @@ UINT16 W_CheckNumForFolderEndPK3(const char *name, UINT16 wad, UINT16 startlump) // Returns lump position in PK3's lumpinfo, or INT16_MAX if not found. UINT16 W_CheckNumForFullNamePK3(const char *name, UINT16 wad, UINT16 startlump) { - INT32 i; + UINT16 i; + size_t namelen; lumpinfo_t *lump_p = wadfiles[wad]->lumpinfo + startlump; - size_t name_length = strlen(name); + + namelen = strlen(name); for (i = startlump; i < wadfiles[wad]->numlumps; i++, lump_p++) { - if (!strnicmp(name, lump_p->fullname, name_length)) + if (!strnicmp(name, lump_p->fullname, namelen)) { return i; } @@ -1220,61 +1258,19 @@ UINT16 W_CheckNumForFullNamePK3(const char *name, UINT16 wad, UINT16 startlump) return INT16_MAX; } -static lumpnum_t CheckLumpInCache(const char *name, boolean longname) +FUNCINLINE static ATTRINLINE lumpnum_t CheckLumpInCache(const char *name) { - if (longname) - { - UINT32 hash = quickncasehash(name, 32); - - // Loop backwards so that we check most recent entries first - for (INT32 i = lumpnumcacheindex + LUMPNUMCACHESIZE; i > lumpnumcacheindex; i--) - { - if (lumpnumcache[i & (LUMPNUMCACHESIZE - 1)].hash == hash - && fasticmp(lumpnumcache[i & (LUMPNUMCACHESIZE - 1)].lumpname, name)) - { - lumpnumcacheindex = i & (LUMPNUMCACHESIZE - 1); - return lumpnumcache[lumpnumcacheindex].lumpnum; - } - } - } - else - { - UINT32 hash = quickncasehash(name, 8); - - // Loop backwards so that we check most recent entries first - for (INT32 i = lumpnumcacheindex + LUMPNUMCACHESIZE; i > lumpnumcacheindex; i--) - { - if (lumpnumcache[i & (LUMPNUMCACHESIZE - 1)].hash == hash - && lumpnumcache[i & (LUMPNUMCACHESIZE - 1)].lumpname[8] == '\0' - && strnicmp(lumpnumcache[i & (LUMPNUMCACHESIZE - 1)].lumpname, name, 8) == 0) - { - lumpnumcacheindex = i & (LUMPNUMCACHESIZE - 1); - return lumpnumcache[lumpnumcacheindex].lumpnum; - } - } - } + lumpnum_map_itr it = lumpnum_map_get(&lumpnumcache, name); + if (!lumpnum_map_is_end(it)) + return it.data->val; return LUMPERROR; } -static void AddLumpToCache(lumpnum_t lumpnum, const char *name, boolean longname) +FUNCINLINE static ATTRINLINE void AddLumpToCache(lumpnum_t lumpnum, const char *name) { - if (longname && strlen(name) >= LUMPNUMCACHENAME) - return; - - lumpnumcacheindex = (lumpnumcacheindex + 1) & (LUMPNUMCACHESIZE - 1); - memset(lumpnumcache[lumpnumcacheindex].lumpname, '\0', LUMPNUMCACHENAME); - if (longname) - { - strlcpy(lumpnumcache[lumpnumcacheindex].lumpname, name, LUMPNUMCACHENAME); - lumpnumcache[lumpnumcacheindex].hash = quickncasehash(name, LUMPNUMCACHENAME); - } - else - { - strncpy(lumpnumcache[lumpnumcacheindex].lumpname, name, 8); - lumpnumcache[lumpnumcacheindex].hash = quickncasehash(name, 8); - } - lumpnumcache[lumpnumcacheindex].lumpnum = lumpnum; + I_Assert(strnlen(name, 9) <= 8); // we dont have longnames, so assume this is a non terminated string + lumpnum_map_insert(&lumpnumcache, strdup(name), lumpnum); } // @@ -1290,14 +1286,14 @@ lumpnum_t W_CheckNumForName(const char *name) return LUMPERROR; // Check the lumpnumcache first. - lumpnum_t cachenum = CheckLumpInCache(name, false); + lumpnum_t cachenum = CheckLumpInCache(name); if (cachenum != LUMPERROR) return cachenum; // scan wad files backwards so patch lump files take precedence for (i = numwadfiles - 1; i >= 0; i--) { - check = W_CheckNumForNamePwad(name, (UINT16)i, 0); + check = W_CheckNumForNamePwad(name, (UINT16)(i), 0); if (check != INT16_MAX) break; //found it @@ -1311,7 +1307,7 @@ lumpnum_t W_CheckNumForName(const char *name) { // Update the cache. lumpnum_t lumpnum = (i << 16) | check; - AddLumpToCache(lumpnum, name, false); + AddLumpToCache(lumpnum, name); return lumpnum; } @@ -1323,7 +1319,7 @@ lumpnum_t W_CheckNumForName(const char *name) // Should be the only version, but that's not possible until we fix // all the instances of non null-terminated strings in the codebase... // -lumpnum_t W_CheckNumForLongName(const char *name) +/*lumpnum_t W_CheckNumForLongName(const char *name) { INT32 i; lumpnum_t check = INT16_MAX; @@ -1332,14 +1328,14 @@ lumpnum_t W_CheckNumForLongName(const char *name) return LUMPERROR; // Check the lumpnumcache first. - lumpnum_t cachenum = CheckLumpInCache(name, true); + lumpnum_t cachenum = CheckLumpInCache(name); if (cachenum != LUMPERROR) return cachenum; // scan wad files backwards so patch lump files take precedence for (i = numwadfiles - 1; i >= 0; i--) { - check = W_CheckNumForLongNamePwad(name, (UINT16)i, 0); + check = W_CheckNumForLongNamePwad(name, (UINT16)(i), 0); if (check != INT16_MAX) break; //found it @@ -1353,11 +1349,11 @@ lumpnum_t W_CheckNumForLongName(const char *name) { // Update the cache. lumpnum_t lumpnum = (i << 16) | check; - AddLumpToCache(lumpnum, name, true); + AddLumpToCache(lumpnum, name); return lumpnum; } -} +}*/ // // W_GetNumForName @@ -1382,7 +1378,7 @@ lumpnum_t W_GetNumForName(const char *name) // Should be the only version, but that's not possible until we fix // all the instances of non null-terminated strings in the codebase... // -lumpnum_t W_GetNumForLongName(const char *name) +/*lumpnum_t W_GetNumForLongName(const char *name) { lumpnum_t i; @@ -1392,7 +1388,7 @@ lumpnum_t W_GetNumForLongName(const char *name) I_Error("W_GetNumForLongName: %s not found!\n", name); return i; -} +}*/ // // W_CheckNumForNameInBlock @@ -1409,32 +1405,49 @@ lumpnum_t W_CheckNumForNameInBlock(const char *name, const char *blockstart, con { if (wadfiles[i]->type == RET_WAD) { - bsid = W_CheckNumForNamePwad(blockstart, (UINT16)i, 0); + bsid = W_CheckNumForNamePwad(blockstart, (UINT16)(i), 0); if (bsid == INT16_MAX) continue; // Start block doesn't exist? - beid = W_CheckNumForNamePwad(blockend, (UINT16)i, 0); + beid = W_CheckNumForNamePwad(blockend, (UINT16)(i), 0); if (beid == INT16_MAX) continue; // End block doesn't exist? - check = W_CheckNumForNamePwad(name, (UINT16)i, bsid); + check = W_CheckNumForNamePwad(name, (UINT16)(i), bsid); if (check < beid) - return (i<<16)+check; // found it, in our constraints + return (i << 16)+check; // found it, in our constraints } } + return LUMPERROR; } // Used by Lua. Case sensitive lump checking, quickly... UINT8 W_LumpExists(const char *name) { - INT32 i,j; + INT32 i, j; + UINT32 hash; + size_t namelen; + + // Check the lumpnumcache first. + lumpnum_t cachenum = CheckLumpInCache(name); + if (cachenum != LUMPERROR) + return true; + + namelen = strlen(name); + hash = W_HashLumpName(name); + for (i = numwadfiles - 1; i >= 0; i--) { lumpinfo_t *lump_p = wadfiles[i]->lumpinfo; for (j = 0; j < wadfiles[i]->numlumps; ++j, ++lump_p) - if (fastcmp(lump_p->name, name)) + { + if (lump_p->namelength == namelen + && lump_p->hash.name == hash + && fastcmp(lump_p->name, name)) return true; + } } + return false; } @@ -1594,13 +1607,13 @@ size_t W_ReadLumpHeaderPwad(UINT16 wad, UINT16 lump, void *dest, size_t size, si fseek(handle, (long)(l->position + offset), SEEK_SET); // But let's not copy it yet. We support different compression formats on lumps, so we need to take that into account. - switch(wadfiles[wad]->lumpinfo[lump].compression) + switch (wadfiles[wad]->lumpinfo[lump].compression) { case CM_NOCOMPRESSION: // If it's uncompressed, we directly write the data into our destination, and return the bytes read. #ifdef NO_PNG_LUMPS { size_t bytesread = fread(dest, 1, size, handle); - ErrorIfPNG((UINT8 *)dest, bytesread, wadfiles[wad]->filename, l->fullname); + ErrorIfPNG((UINT8 *)(dest), bytesread, wadfiles[wad]->filename, l->fullname); return bytesread; } #else @@ -1613,8 +1626,8 @@ size_t W_ReadLumpHeaderPwad(UINT16 wad, UINT16 lump, void *dest, size_t size, si char *decData; // Lump's decompressed real data. size_t retval; // Helper var, lzf_decompress returns 0 when an error occurs. - rawData = Z_Malloc(l->disksize, PU_STATIC, NULL); - decData = Z_Malloc(l->size, PU_STATIC, NULL); + rawData = (char *)(Z_Malloc(l->disksize, PU_STATIC, NULL)); + decData = (char *)(Z_Malloc(l->size, PU_STATIC, NULL)); if (fread(rawData, 1, l->disksize, handle) < l->disksize) I_Error("wad %d, lump %d: cannot read compressed data", wad, lump); @@ -1641,7 +1654,7 @@ size_t W_ReadLumpHeaderPwad(UINT16 wad, UINT16 lump, void *dest, size_t size, si Z_Free(rawData); Z_Free(decData); #ifdef NO_PNG_LUMPS - ErrorIfPNG((UINT8 *)dest, size, wadfiles[wad]->filename, l->fullname); + ErrorIfPNG((UINT8 *)(dest), size, wadfiles[wad]->filename, l->fullname); #endif return size; #else @@ -1661,15 +1674,15 @@ size_t W_ReadLumpHeaderPwad(UINT16 wad, UINT16 lump, void *dest, size_t size, si unsigned long rawSize = l->disksize; unsigned long decSize = size; - rawData = Z_Malloc(rawSize, PU_STATIC, NULL); - decData = dest; + rawData = (UINT8 *)(Z_Malloc(rawSize, PU_STATIC, NULL)); + decData = (UINT8 *)(dest); if (fread(rawData, 1, rawSize, handle) < rawSize) I_Error("wad %d, lump %d: cannot read compressed data", wad, lump); - strm.zalloc = Z_NULL; - strm.zfree = Z_NULL; - strm.opaque = Z_NULL; + strm.zalloc = NULL; + strm.zfree = NULL; + strm.opaque = NULL; strm.total_in = strm.avail_in = rawSize; strm.total_out = strm.avail_out = decSize; @@ -1698,7 +1711,7 @@ size_t W_ReadLumpHeaderPwad(UINT16 wad, UINT16 lump, void *dest, size_t size, si Z_Free(rawData); #ifdef NO_PNG_LUMPS - ErrorIfPNG((UINT8 *)dest, size, wadfiles[wad]->filename, l->fullname); + ErrorIfPNG((UINT8 *)(dest), size, wadfiles[wad]->filename, l->fullname); #endif return size; } @@ -1886,7 +1899,7 @@ void *W_CacheSoftwarePatchNumPwad(UINT16 wad, UINT16 lump, INT32 tag) W_ReadLumpHeaderPwad(wad, lump, lumpdata, 0, 0); dest = Z_Calloc(sizeof(patch_t), tag, &lumpcache[lump]); - Patch_Create((softwarepatch_t*)lumpdata, len, dest); + Patch_Create((softwarepatch_t *)(lumpdata), len, dest); Z_Free(lumpdata); } @@ -1908,7 +1921,7 @@ void *W_CachePatchNumPwad(UINT16 wad, UINT16 lump, INT32 tag) if (!TestValidLump(wad, lump)) return NULL; - patch = (patch_t *)W_CacheSoftwarePatchNumPwad(wad, lump, tag); + patch = (patch_t *)(W_CacheSoftwarePatchNumPwad(wad, lump, tag)); if (patch == NULL) return NULL; @@ -1919,7 +1932,7 @@ void *W_CachePatchNumPwad(UINT16 wad, UINT16 lump, INT32 tag) Patch_CreateGL(patch); #endif - return (void *)patch; + return (void*)(patch); } void *W_CachePatchNum(lumpnum_t lumpnum, INT32 tag) @@ -1937,17 +1950,20 @@ void *W_GetCachedPatchNumPwad(UINT16 wad, UINT16 lump) #ifdef ROTSPRITE // Caches a rotsprite for patch rotation. -void *W_GetCachedRotPatchPwad(UINT16 wadnum, UINT16 lumpnum) +void *W_GetCachedRotPatchPwad(UINT16 wad, UINT16 lump) { - lumpcache_t *rotcache = wadfiles[wadnum]->rotcache; + if (!TestValidLump(wad, lump)) + return NULL; - if (!rotcache[lumpnum]) + lumpcache_t *rotcache = wadfiles[wad]->rotcache; + + if (!rotcache[lump]) { rotsprite_t *rspr = RotatedPatch_Create(ROTANGLES); - Z_SetUser(rspr, (void **)(&rotcache[lumpnum])); + Z_SetUser(rspr, (void**)(&rotcache[lump])); } - return (void *)(rotcache[lumpnum]); + return (void*)(rotcache[lump]); } #endif // ROTSPRITE @@ -1960,7 +1976,7 @@ void W_UnlockCachedPatch(void *patch) // have different lifetimes from software's. #ifdef HWRENDER if (rendermode == render_opengl) - HWR_UnlockCachedPatch((GLPatch_t *)((patch_t *)patch)->hardware); + HWR_UnlockCachedPatch((GLPatch_t *)(((patch_t *)(patch))->hardware)); else #endif Z_ChangeTag(patch, PU_PATCH); @@ -1995,13 +2011,18 @@ void *W_CachePatchNameRotated(const char *name, INT32 rotationangle, INT32 tag) if (rotationangle < 1 || rotationangle >= ROTANGLES) return W_CachePatchNum(num, tag); - rspr = (rotsprite_t *)W_GetCachedRotPatchPwad(WADFILENUM(num),LUMPNUM(num)); + rspr = (rotsprite_t *)(W_GetCachedRotPatchPwad(WADFILENUM(num), LUMPNUM(num))); + + if (rspr == NULL) + return W_CachePatchNum(W_GetNumForName("MISSING"), tag); if (rspr->patches[idx] == NULL) { INT32 xpivot = 0, ypivot = 0; - ptr = (patch_t *)W_CachePatchNum(num, PU_PATCH); + ptr = (patch_t *)(W_CachePatchNum(num, PU_PATCH)); + if (ptr == NULL) + return W_CachePatchNum(W_GetNumForName("MISSING"), tag); // >y pivot centered // >x pivot not centered @@ -2192,7 +2213,7 @@ static int W_VerifyPK3(FILE *fp, lumpchecklist_t *checklist, boolean status) fseek(fp, 0, SEEK_END); file_size = ftell(fp); - const long startpos = (file_size - (22 + 65536)); + const long startpos = file_size - (22 + 65536); if (!ResFindSignature(fp, pat_end, max(0l, startpos))) return true; @@ -2206,7 +2227,7 @@ static int W_VerifyPK3(FILE *fp, lumpchecklist_t *checklist, boolean status) fseek(fp, LONG(zend.cdiroffset), SEEK_SET); - CLEANUP(pfree) char *cdir = (char*)(malloc(LONG(zend.cdirsize))); + CLEANUP(pfree) char *cdir = (char *)(malloc(LONG(zend.cdirsize))); if (fread(cdir, 1, LONG(zend.cdirsize), fp) < (UINT32)(LONG(zend.cdirsize))) { @@ -2217,7 +2238,7 @@ static int W_VerifyPK3(FILE *fp, lumpchecklist_t *checklist, boolean status) for (i = 0; i < numlumps; i++) { - zentry_t *zentry = (zentry_t*)(cdir + offset); + zentry_t *zentry = (zentry_t *)(cdir + offset); char* fullname; char* trimname; char* dotpos; @@ -2229,18 +2250,19 @@ static int W_VerifyPK3(FILE *fp, lumpchecklist_t *checklist, boolean status) if (verified == true) { - fullname = (char*)(malloc(SHORT(zentry->namelen) + 1)); - strlcpy(fullname, (char*)(zentry + 1), SHORT(zentry->namelen) + 1); + fullname = (char *)(malloc(SHORT(zentry->namelen) + 1)); + strncpy(fullname, (char *)(zentry + 1), SHORT(zentry->namelen)); + fullname[zentry->namelen] = 0; // Strip away file address and extension for the 8char name. - if ((trimname = strrchr(fullname, '/')) != 0) + if ((trimname = strrchr(fullname, '/')) != NULL) trimname++; else trimname = fullname; // Care taken for root files. if (*trimname) // Ignore directories, well kinda { - if ((dotpos = strrchr(trimname, '.')) == 0) + if ((dotpos = strrchr(trimname, '.')) == NULL) dotpos = fullname + strlen(fullname); // Watch for files without extension. memset(lumpname, '\0', 9); // Making sure they're initialized to 0. Is it necessary? @@ -2371,7 +2393,7 @@ static int W_NameStartsWith(const char *name, lumpchecklist_t *checklist) } // Checks if file contains at least one lump which name starts with one of strings in checklist -static int W_CheckWADContains(FILE *fp, lumpchecklist_t *checklist) +static int W_CheckWADContainsEx(FILE *fp, lumpchecklist_t *checklist, boolean checkmap) { size_t i, j; // if we're here it's a WAD file @@ -2412,13 +2434,29 @@ static int W_CheckWADContains(FILE *fp, lumpchecklist_t *checklist) if (!strncmp(lumpinfo.name, sprnames[j], 4)) // Sprites continue; - if (W_NameStartsWith(lumpinfo.name, checklist)) + if (checkmap) + { + if (CHECKMAPMARKER(lumpinfo.name)) + return true; + } + else if (W_NameStartsWith(lumpinfo.name, checklist)) return true; } + return false; } -static int W_CheckPK3Contains(FILE *fp, lumpchecklist_t *checklist) +static int W_CheckWADContains(FILE *fp, lumpchecklist_t *checklist) +{ + return W_CheckWADContainsEx(fp, checklist, false); +} + +static int W_CheckWADContainsMap(FILE *fp) +{ + return W_CheckWADContainsEx(fp, NULL, true); +} + +static int W_CheckPK3ContainsEx(FILE *fp, lumpchecklist_t *checklist, boolean checkmap) { zend_t zend; zlentry_t zlentry; @@ -2439,7 +2477,7 @@ static int W_CheckPK3Contains(FILE *fp, lumpchecklist_t *checklist) fseek(fp, 0, SEEK_END); file_size = ftell(fp); - const long startpos = (file_size - (22 + 65536)); + const long startpos = file_size - (22 + 65536); if (!ResFindSignature(fp, pat_end, max(0l, startpos))) return true; @@ -2453,7 +2491,7 @@ static int W_CheckPK3Contains(FILE *fp, lumpchecklist_t *checklist) fseek(fp, LONG(zend.cdiroffset), SEEK_SET); - CLEANUP(pfree) char *cdir = (char*)(malloc(LONG(zend.cdirsize))); + CLEANUP(pfree) char *cdir = (char *)(malloc(LONG(zend.cdirsize))); if (fread(cdir, 1, LONG(zend.cdirsize), fp) < (UINT32)(LONG(zend.cdirsize))) { @@ -2464,7 +2502,7 @@ static int W_CheckPK3Contains(FILE *fp, lumpchecklist_t *checklist) for (i = 0; i < numlumps; i++) { - zentry_t *zentry = (zentry_t*)(cdir + offset); + zentry_t *zentry = (zentry_t *)(cdir + offset); CLEANUP(pfree) char* fullname = NULL; char* trimname; char* dotpos; @@ -2474,30 +2512,41 @@ static int W_CheckPK3Contains(FILE *fp, lumpchecklist_t *checklist) return false; } - fullname = (char*)(malloc(SHORT(zentry->namelen) + 1)); - strlcpy(fullname, (char*)(zentry + 1), SHORT(zentry->namelen) + 1); + fullname = (char *)(malloc(SHORT(zentry->namelen) + 1)); + strncpy(fullname, (char *)(zentry + 1), SHORT(zentry->namelen)); + fullname[zentry->namelen] = 0; // Strip away file address and extension for the 8char name. - if ((trimname = strrchr(fullname, '/')) != 0) + if ((trimname = strrchr(fullname, '/')) != NULL) trimname++; else trimname = fullname; // Care taken for root files. if (*trimname) // Ignore directories, well kinda { - if ((dotpos = strrchr(trimname, '.')) == 0) + if ((dotpos = strrchr(trimname, '.')) == NULL) dotpos = fullname + strlen(fullname); // Watch for files without extension. memset(lumpname, '\0', 9); // Making sure they're initialized to 0. Is it necessary? strncpy(lumpname, trimname, min(8, dotpos - trimname)); - if (W_NameStartsWith(lumpname, checklist)) + if (checkmap) + { + if (CHECKMAPMARKER(lumpname)) + return true; + } + else if (W_NameStartsWith(lumpname, checklist)) { return true; } } - if (W_NameStartsWith(fullname, checklist)) + if (checkmap) + { + if (CHECKMAPMARKER(fullname)) + return true; + } + else if (W_NameStartsWith(fullname, checklist)) { return true; } @@ -2539,12 +2588,24 @@ static int W_CheckPK3Contains(FILE *fp, lumpchecklist_t *checklist) } } -static int W_CheckFileContains(const char *filename, lumpchecklist_t *checklist) +static int W_CheckPK3Contains(FILE *fp, lumpchecklist_t *checklist) +{ + return W_CheckPK3ContainsEx(fp, checklist, false); +} + +static int W_CheckPK3ContainsMap(FILE *fp) +{ + return W_CheckPK3ContainsEx(fp, NULL, true); +} + +static int W_CheckFileContainsEx(const char *filename, lumpchecklist_t *checklist, boolean checkmap) { FILE *handle; int contains = false; - if (!checklist) + // if we just check for maps this will be NULL + // hacky but i dont care + if (!checklist && !checkmap) I_Error("No checklist for %s\n", filename); // open wad file @@ -2555,17 +2616,43 @@ static int W_CheckFileContains(const char *filename, lumpchecklist_t *checklist) if (type == RET_PK3) { - contains = W_CheckPK3Contains(handle, checklist); + if (checkmap) + contains = W_CheckPK3ContainsMap(handle); + else + contains = W_CheckPK3Contains(handle, checklist); } else if (type == RET_WAD) { - contains = W_CheckWADContains(handle, checklist); + if (checkmap) + contains = W_CheckWADContainsMap(handle); + else + contains = W_CheckWADContains(handle, checklist); } fclose(handle); return contains; } +static int W_CheckFileContains(const char *filename, lumpchecklist_t *checklist) +{ + return W_CheckFileContainsEx(filename, checklist, false); +} + +static int W_CheckFileContainsMap(const char *filename) +{ + return W_CheckFileContainsEx(filename, NULL, true); +} + +// kinda stupid but we cant just check for any lump containing "MAP" +// we have to explicitly check if its MAP and 5 characters long +// the more correct way would be checking inside wad files nested within pk3´s +// and check the presence of actual map data like SSECTORS or something +// but man i cannot be assed to rework shit for that +int W_CheckAutoLoadContainsMap(const char *filename) +{ + return W_CheckFileContainsMap(filename); +} + int W_CheckPostLoadList(const char *filename) { static lumpchecklist_t postloadlist[] = @@ -2578,7 +2665,6 @@ int W_CheckPostLoadList(const char *filename) {"SOC_", 4}, {"MAINCFG", 7}, {"OBJCTCFG", 8}, - {"MAP", 3}, {NULL, 0}, }; @@ -2611,11 +2697,14 @@ virtres_t* vres_GetMap(lumpnum_t lumpnum) size_t *vsizecache; // Remember that we're assuming that the WAD will have a specific set of lumps in a specific order. - UINT8 *wadData = (UINT8*)(W_CacheLumpNum(lumpnum, PU_LEVEL)); - filelump_t *fileinfo = (filelump_t *)(wadData + LONG(((wadinfo_t *)wadData)->infotableofs)); + UINT8 *wadData = (UINT8 *)(W_CacheLumpNum(lumpnum, PU_LEVEL)); + if (wadData == NULL) + I_Error("vres_GetMap: Invalid WadData!\n"); - i = LONG(((wadinfo_t *)wadData)->numlumps); - vsizecache = (size_t*)(Z_Malloc(sizeof(size_t)*i, PU_LEVEL, NULL)); + filelump_t *fileinfo = (filelump_t *)(wadData + LONG(((wadinfo_t *)(wadData))->infotableofs)); + + i = LONG(((wadinfo_t *)(wadData))->numlumps); + vsizecache = (size_t *)(Z_Malloc(sizeof(size_t)*i, PU_LEVEL, NULL)); for (realentry = 0; realentry < i; realentry++) { @@ -2627,18 +2716,22 @@ virtres_t* vres_GetMap(lumpnum_t lumpnum) numlumps++; } - vlumps = (virtlump_t*)(Z_Malloc(sizeof(virtlump_t)*numlumps, PU_LEVEL, NULL)); + vlumps = (virtlump_t *)(Z_Malloc(sizeof(virtlump_t)*numlumps, PU_LEVEL, NULL)); + if (vlumps == NULL) + I_Error("vres_GetMap: Out of memory!\n"); // Build the lumps, skipping over empty entries. for (i = 0, realentry = 0; i < numlumps; realentry++) { if (vsizecache[realentry] == 0) continue; + vlumps[i].size = vsizecache[realentry]; const char *name = (fileinfo + realentry)->name; + I_Assert(name != NULL); - if (strlen(name) == 5 && memcmp(name, "MAP", 3) == 0) + if (!name || CHECKMAPMARKER(name)) { numlumps--; // We skip map marker, so 1 of entries becomes empty continue; // This will skip i++ so we will write to same entry @@ -2647,9 +2740,7 @@ virtres_t* vres_GetMap(lumpnum_t lumpnum) // Play it safe with the name in this case. memcpy(vlumps[i].name, name, 8); vlumps[i].name[8] = '\0'; - vlumps[i].data = (UINT8*)( - Z_Malloc(vlumps[i].size, PU_LEVEL, NULL) // This is memory inefficient, sorry about that. - ); + vlumps[i].data = (UINT8 *)(Z_Malloc(vlumps[i].size, PU_LEVEL, NULL)); // This is memory inefficient, sorry about that. memcpy(vlumps[i].data, wadData + LONG((fileinfo + realentry)->filepos), vlumps[i].size); i++; } @@ -2659,24 +2750,37 @@ virtres_t* vres_GetMap(lumpnum_t lumpnum) } else { - // Count number of lumps until the end of resource OR up until next "MAPXX" lump. + // Count number of lumps until the end of resource OR up until next 0-length lump OR up until next "MAPXX" lump. lumpnum_t lumppos = lumpnum + 1; for (i = LUMPNUM(lumppos); i < wadfiles[WADFILENUM(lumpnum)]->numlumps; i++, lumppos++, numlumps++) { - if (memcmp(W_CheckNameForNum(lumppos), "MAP", 3) == 0 || W_LumpLength(lumppos) == 0) + if (W_LumpLength(lumppos) == 0) + { + break; + } + + const char *name = W_CheckNameForNum(lumppos); + I_Assert(name != NULL); + + // if no name then theres no lump + if (!name || CHECKMAPMARKER(name)) { break; } } numlumps++; - vlumps = (virtlump_t*)(Z_Malloc(sizeof(virtlump_t)*numlumps, PU_LEVEL, NULL)); + vlumps = (virtlump_t *)(Z_Malloc(sizeof(virtlump_t)*numlumps, PU_LEVEL, NULL)); + if (vlumps == NULL) + I_Error("vres_GetMap: Out of memory!\n"); + for (i = 0; i < numlumps; i++, lumpnum++) { // Check if it is map marker. It is not always first lump sadly, so we need to expect it anywhere const char *name = W_CheckNameForNum(lumpnum); + I_Assert(name != NULL); - if (strlen(name) == 5 && memcmp(name, "MAP", 3) == 0) + if (!name || CHECKMAPMARKER(name)) { --i; // Decrement so on next iteration we write on same i, so we don't leave corrupted vlumps entry numlumps--; // Just so we don't try to access the leftover vlumps entry @@ -2686,11 +2790,11 @@ virtres_t* vres_GetMap(lumpnum_t lumpnum) vlumps[i].size = W_LumpLength(lumpnum); memcpy(vlumps[i].name, name, 8); vlumps[i].name[8] = '\0'; - vlumps[i].data = (UINT8*)(W_CacheLumpNum(lumpnum, PU_LEVEL)); + vlumps[i].data = (UINT8 *)(W_CacheLumpNum(lumpnum, PU_LEVEL)); } } - vres = (virtres_t*)(Z_Malloc(sizeof(virtres_t), PU_LEVEL, NULL)); + vres = (virtres_t *)(Z_Malloc(sizeof(virtres_t), PU_LEVEL, NULL)); vres->vlumps = vlumps; vres->numlumps = numlumps; @@ -2711,10 +2815,7 @@ void vres_Free(virtres_t* vres) while (vres->numlumps--) { - if (vres->vlumps[vres->numlumps].data) - { - Z_Free(vres->vlumps[vres->numlumps].data); - } + Z_Free(vres->vlumps[vres->numlumps].data); } Z_Free(vres->vlumps); diff --git a/src/w_wad.h b/src/w_wad.h index 6240c31f3..a17023821 100644 --- a/src/w_wad.h +++ b/src/w_wad.h @@ -68,11 +68,11 @@ typedef struct unsigned long position; // filelump_t filepos unsigned long disksize; // filelump_t size char name[9]; // filelump_t name[] e.g. "LongEntr" - char *longname; // e.g. "LongEntryName" + //char *longname; // e.g. "LongEntryName" char *fullname; // e.g. "Folder/Subfolder/LongEntryName.extension" size_t namelength; // length of name - size_t longnamelength; // length of longname + //size_t longnamelength; // length of longname size_t fullnamelength; // length of fullname size_t size; // real (uncompressed) size @@ -80,8 +80,8 @@ typedef struct struct { UINT32 name; // hash of name - UINT32 longname; // hash of longname - UINT32 fullname; // hash of fullname + //UINT32 longname; // hash of longname + //UINT32 fullname; // hash of fullname } hash; } lumpinfo_t; @@ -126,7 +126,6 @@ typedef enum restype RET_UNKNOWN, } restype_t; - typedef struct wadfile_s { char *filename; @@ -137,8 +136,8 @@ typedef struct wadfile_s #ifdef ROTSPRITE lumpcache_t *rotcache; // Cache rotsprites for rotating patches. #endif - aatree_t *startfolders; - aatree_t *endfolders; + struct FolderCache *startfolders; + struct FolderCache *endfolders; UINT16 numlumps; // this wad's number of resources FILE *handle; UINT32 filesize; // for network @@ -155,8 +154,6 @@ extern wadfile_t *wadfiles[MAX_WADFILES]; // ========================================================================= -void W_Shutdown(void); - // Opens a WAD file. Returns the FILE * handle for the file, or NULL if not found or could not be opened FILE *W_OpenWadFile(const char **filename, boolean useerrors); // Load and add a wadfile to the active wad files, returns numbers of lumps, INT16_MAX on error @@ -174,13 +171,11 @@ INT32 W_AddAutoloadedLocalFiles(char **filenames); #define W_FileHasFolders(wadfile) ((wadfile)->type == RET_PK3) -UINT32 W_HashLumpName(const char *name); - const char *W_CheckNameForNumPwad(UINT16 wad, UINT16 lump); const char *W_CheckNameForNum(lumpnum_t lumpnum); UINT16 W_CheckNumForNamePwad(const char *name, UINT16 wad, UINT16 startlump); // checks only in one pwad -UINT16 W_CheckNumForLongNamePwad(const char *name, UINT16 wad, UINT16 startlump); +//UINT16 W_CheckNumForLongNamePwad(const char *name, UINT16 wad, UINT16 startlump); /* Find the first lump after F_START for instance. */ UINT16 W_CheckNumForMarkerStartPwad(const char *name, UINT16 wad, UINT16 startlump); @@ -190,9 +185,9 @@ UINT16 W_CheckNumForFolderStartPK3(const char *name, UINT16 wad, UINT16 startlum UINT16 W_CheckNumForFolderEndPK3(const char *name, UINT16 wad, UINT16 startlump); lumpnum_t W_CheckNumForName(const char *name); -lumpnum_t W_CheckNumForLongName(const char *name); +//lumpnum_t W_CheckNumForLongName(const char *name); lumpnum_t W_GetNumForName(const char *name); // like W_CheckNumForName but I_Error on LUMPERROR -lumpnum_t W_GetNumForLongName(const char *name); +//lumpnum_t W_GetNumForLongName(const char *name); lumpnum_t W_CheckNumForNameInBlock(const char *name, const char *blockstart, const char *blockend); UINT8 W_LumpExists(const char *name); // Lua uses this. UINT8 W_CheckMultipleLumps(const char* lump, ...); // variadic version of above lmao @@ -233,7 +228,7 @@ void *W_CacheSoftwarePatchNumPwad(UINT16 wad, UINT16 lump, INT32 tag); void *W_CacheSoftwarePatchNum(lumpnum_t lumpnum, INT32 tag); #ifdef ROTSPRITE -void *W_GetCachedRotPatchPwad(UINT16 wadnum, UINT16 lumpnum); // Get patch-based rotsprites from the cache. +void *W_GetCachedRotPatchPwad(UINT16 wad, UINT16 lump); // Get patch-based rotsprites from the cache. void *W_CachePatchNameRotated(const char *name, INT32 rotationangle, INT32 tag); #endif @@ -243,6 +238,7 @@ void W_VerifyFileMD5(UINT16 wadfilenum, const char *matchmd5); int W_VerifyNMUSlumps(const char *filename, FILE *handle, boolean exit_on_error); +int W_CheckAutoLoadContainsMap(const char *filename); int W_CheckPostLoadList(const char *filename); #ifdef __cplusplus diff --git a/src/win32/win_dbg.c b/src/win32/win_dbg.c index a5d1adc3f..067936be9 100644 --- a/src/win32/win_dbg.c +++ b/src/win32/win_dbg.c @@ -118,7 +118,7 @@ static VOID FPrintf(HANDLE fileHandle, LPCSTR lpFmt, ...) DWORD bytesWritten; va_start(arglist, lpFmt); - vsnprintf(str, 1999, lpFmt, arglist); + vsnprintf(str, sizeof(str), lpFmt, arglist); va_end(arglist); WriteFile(fileHandle, str, (DWORD)strlen(str), &bytesWritten, NULL); @@ -187,13 +187,13 @@ static VOID ShowModuleInfo(HANDLE LogFile, HMODULE ModuleHandle) // Open the code module file so that we can get its file date // and size. ModuleFile = CreateFileA(ModName, GENERIC_READ, - FILE_SHARE_READ, 0, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, 0); + FILE_SHARE_READ, NULL, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, NULL); if (ModuleFile != INVALID_HANDLE_VALUE) { FILETIME LastWriteTime; - FileSize = GetFileSize(ModuleFile, 0); - if (GetFileTime(ModuleFile, 0, 0, &LastWriteTime)) + FileSize = GetFileSize(ModuleFile, NULL); + if (GetFileTime(ModuleFile, NULL, NULL, &LastWriteTime)) { wsprintfA(TimeBuffer, " - file date is "); PrintTime(TimeBuffer + strlen(TimeBuffer), LastWriteTime); @@ -227,7 +227,7 @@ static VOID RecordModuleList(HANDLE LogFile) size_t PageSize; size_t NumPages; size_t pageNum = 0; - LPVOID LastAllocationBase = 0; + LPVOID LastAllocationBase = NULL; FPrintf(LogFile, "\r\n" "\tModule list: names, addresses, sizes, time stamps " @@ -385,7 +385,7 @@ LONG WINAPI RecordExceptionInfo(PEXCEPTION_POINTERS data/*, LPCSTR Message, LPST } // Append to the error log. - SetFilePointer(fileHandle, 0, 0, FILE_END); + SetFilePointer(fileHandle, 0, NULL, FILE_END); // Print out some blank lines to separate this error log from any previous ones. FPrintf(fileHandle, "Email Sonic Team Junior so we can fix the bugs\r\n"); // Tails diff --git a/src/y_inter.c b/src/y_inter.c index d35fa7825..9c5fc9c0f 100644 --- a/src/y_inter.c +++ b/src/y_inter.c @@ -51,13 +51,6 @@ #include "hardware/hw_main.h" #endif -typedef struct -{ - char patch[9]; - INT32 points; - UINT8 display; -} y_bonus_t; - static y_data_t data; // graphics @@ -104,7 +97,7 @@ typedef struct } y_voteclient; // votescreen stuff -votescreen_t VoteScreen = {0}; +votescreen_t VoteScreen = {}; static y_votelvlinfo levelinfo[5]; static y_voteclient voteclient; @@ -160,7 +153,7 @@ static void Y_CalculateMatchData(UINT8 rankingsmode, void (*comparison)(INT32)) ; else if ((data.rankingsmode = (boolean)rankingsmode)) { - sprintf(data.levelstring, "* Total Rankings *"); + snprintf(data.levelstring, sizeof(data.levelstring), "* Total Rankings *"); data.encore = false; } else @@ -169,32 +162,41 @@ static void Y_CalculateMatchData(UINT8 rankingsmode, void (*comparison)(INT32)) if (mapheaderinfo[prevmap]->levelflags & LF_NOZONE) { if (mapheaderinfo[prevmap]->actnum[0]) + { snprintf(data.levelstring, - sizeof data.levelstring, + sizeof(data.levelstring), "* %s %s *", mapheaderinfo[prevmap]->lvlttl, mapheaderinfo[prevmap]->actnum); + } else + { snprintf(data.levelstring, - sizeof data.levelstring, + sizeof(data.levelstring), "* %s *", mapheaderinfo[prevmap]->lvlttl); + } } else { const char *zonttl = (mapheaderinfo[prevmap]->zonttl[0] ? mapheaderinfo[prevmap]->zonttl : "Zone"); + if (mapheaderinfo[prevmap]->actnum[0]) + { snprintf(data.levelstring, - sizeof data.levelstring, + sizeof(data.levelstring), "* %s %s %s *", mapheaderinfo[prevmap]->lvlttl, zonttl, mapheaderinfo[prevmap]->actnum); + } else + { snprintf(data.levelstring, - sizeof data.levelstring, + sizeof(data.levelstring), "* %s %s *", mapheaderinfo[prevmap]->lvlttl, zonttl); + } } - data.levelstring[sizeof data.levelstring - 1] = '\0'; + data.levelstring[sizeof(data.levelstring) - 1] = '\0'; data.encore = encoremode; @@ -272,13 +274,13 @@ static void Y_CalculateMatchData(UINT8 rankingsmode, void (*comparison)(INT32)) // static void Y_PlayerStandingsDrawer(y_data_t *standings, INT32 x, INT32 hilicol) { + INT32 i; + if (standings->numplayers == 0) { return; } - INT32 i; - #define NUMFORNEWCOLUMN 8 INT32 y = 41, gutter = ((standings->numplayers > NUMFORNEWCOLUMN) ? 0 : (BASEVIDWIDTH/2)); INT32 dupadjust = cv_betainterscreen.value ? 314 : vid.scaledwidth, duptweak = cv_betainterscreen.value ? -3 : (dupadjust - BASEVIDWIDTH)/2; @@ -319,6 +321,12 @@ static void Y_PlayerStandingsDrawer(y_data_t *standings, INT32 x, INT32 hilicol) const UINT8 pnum = standings->num[i]; player_t *player = &players[pnum]; +#if MAXPLAYERS > 16 + // 32 Player TODO: port over and cleanup standings drawer from sat-32p/blankart + if (i > 16) + break; +#endif + if (pnum == MAXPLAYERS) ; else if (!playeringame[pnum] || player->spectator) @@ -337,7 +345,7 @@ static void Y_PlayerStandingsDrawer(y_data_t *standings, INT32 x, INT32 hilicol) V_DrawCenteredString(x+6, y, 0, va("%d", standings->pos[i])); // localskins are amazing - if (standings->color[i] != SKINCOLOR_NONE) + if (*standings->color[i] != SKINCOLOR_NONE) { UINT8 *colormap = R_GetTranslationColormap(*standings->character[i], *standings->color[i], GTC_CACHE); INT32 skinnum = (player->localskin ? (player->localskin - 1) : *standings->character[i]); @@ -367,9 +375,9 @@ static void Y_PlayerStandingsDrawer(y_data_t *standings, INT32 x, INT32 hilicol) if (standings->increase[pnum] != UINT8_MAX) { if (standings->increase[pnum] > 9) - snprintf(strtime, sizeof strtime, "(+%02d)", standings->increase[pnum]); + snprintf(strtime, sizeof(strtime), "(+%02d)", standings->increase[pnum]); else - snprintf(strtime, sizeof strtime, "(+ %d)", standings->increase[pnum]); + snprintf(strtime, sizeof(strtime), "(+ %d)", standings->increase[pnum]); if (standings->numplayers > NUMFORNEWCOLUMN) V_DrawRightAlignedThinString(x+135+gutter, y-1, V_6WIDTHSPACE, strtime); @@ -377,7 +385,7 @@ static void Y_PlayerStandingsDrawer(y_data_t *standings, INT32 x, INT32 hilicol) V_DrawRightAlignedString(x+120+gutter, y, 0, strtime); } - snprintf(strtime, sizeof strtime, "%d", standings->val[i]); + snprintf(strtime, sizeof(strtime), "%d", standings->val[i]); if (standings->numplayers > NUMFORNEWCOLUMN) V_DrawRightAlignedThinString(x+152+gutter, y-1, V_6WIDTHSPACE, strtime); @@ -392,9 +400,9 @@ static void Y_PlayerStandingsDrawer(y_data_t *standings, INT32 x, INT32 hilicol) { if (intertype == int_race) { - snprintf(strtime, sizeof strtime, "%i'%02i\"%02i", G_TicsToMinutes(standings->val[i], true), + snprintf(strtime, sizeof(strtime), "%i'%02i\"%02i", G_TicsToMinutes(standings->val[i], true), G_TicsToSeconds(standings->val[i]), G_TicsToCentiseconds(standings->val[i])); - strtime[sizeof strtime - 1] = '\0'; + strtime[sizeof(strtime) - 1] = '\0'; if (standings->numplayers > NUMFORNEWCOLUMN) V_DrawRightAlignedThinString(x+152+gutter, y-1, V_6WIDTHSPACE, strtime); @@ -440,6 +448,7 @@ void Y_IntermissionDrawer(void) return; if (cv_betainterscreen.value == 1 + || !intermissionbginit #ifdef HWRENDER || (rendermode == render_opengl && cv_glscreentextures.value != 2) // use the neato kart bg for intermission on disabled screen textures #endif @@ -592,7 +601,7 @@ void Y_Ticker(void) if (data.rankingsmode && intertic > sorttic+16+(2*TICRATE)) { - INT32 q=0,r=0; + INT32 q = 0, r = 0; boolean kaching = true; for (q = 0; q < data.numplayers; q++) @@ -658,15 +667,16 @@ static void Y_UpdateRecordReplays(void) if ((gpath = malloc(glen)) == NULL) I_Error("Out of memory for replay filepath\n"); - sprintf(gpath,"%s"PATHSEP"replay"PATHSEP"%s"PATHSEP"%s", srb2home, timeattackfolder, G_BuildMapName(gamemap)); - snprintf(lastdemo, 255, "%s-%s-last.lmp", gpath, cv_chooseskin.string); + snprintf(gpath, glen, "%s"PATHSEP"replay"PATHSEP"%s"PATHSEP"%s", srb2home, timeattackfolder, G_BuildMapName(gamemap)); + + snprintf(lastdemo, sizeof(lastdemo)-1, "%s-%s-last.lmp", gpath, cv_chooseskin.string); if (FIL_FileExists(lastdemo)) { UINT8 *buf; size_t len = FIL_ReadFile(lastdemo, &buf); - snprintf(bestdemo, 255, "%s-%s-time-best.lmp", gpath, cv_chooseskin.string); + snprintf(bestdemo, sizeof(bestdemo)-1, "%s-%s-time-best.lmp", gpath, cv_chooseskin.string); if (!FIL_FileExists(bestdemo) || G_CmpDemoTime(bestdemo, lastdemo) & 1) { // Better time, save this demo. if (FIL_FileExists(bestdemo)) @@ -675,7 +685,7 @@ static void Y_UpdateRecordReplays(void) CONS_Printf("\x83%s\x80 %s '%s'\n", M_GetText("NEW RECORD TIME!"), M_GetText("Saved replay as"), bestdemo); } - snprintf(bestdemo, 255, "%s-%s-lap-best.lmp", gpath, cv_chooseskin.string); + snprintf(bestdemo, sizeof(bestdemo)-1, "%s-%s-lap-best.lmp", gpath, cv_chooseskin.string); if (!FIL_FileExists(bestdemo) || G_CmpDemoTime(bestdemo, lastdemo) & (1<<1)) { // Better lap time, save this demo. if (FIL_FileExists(bestdemo)) @@ -801,6 +811,7 @@ void Y_EndIntermission(void) endtic = -1; sorttic = -1; intertype = int_none; + intermissionbginit = false; // not sure if this is the right place to reset, but i guess it works for now.... } // @@ -1093,7 +1104,7 @@ void Y_VoteDrawer(void) V_DrawSmallScaledPatch(BASEVIDWIDTH-100, y, V_SNAPTORIGHT, pic); else { - V_DrawFixedPatch((BASEVIDWIDTH-20)<actnum[0]) snprintf(levelinfo[i].str, - sizeof levelinfo[i].str, + sizeof(levelinfo[i].str), "%s %s", mapheaderinfo[votelevels[i][0]]->lvlttl, mapheaderinfo[votelevels[i][0]]->actnum); else snprintf(levelinfo[i].str, - sizeof levelinfo[i].str, + sizeof(levelinfo[i].str), "%s", mapheaderinfo[votelevels[i][0]]->lvlttl); } @@ -1517,12 +1528,12 @@ void Y_StartVote(void) { if (mapheaderinfo[votelevels[i][0]]->actnum[0]) snprintf(levelinfo[i].str, - sizeof levelinfo[i].str, + sizeof(levelinfo[i].str), "%s %s %s", mapheaderinfo[votelevels[i][0]]->lvlttl, mapheaderinfo[votelevels[i][0]]->zonttl, mapheaderinfo[votelevels[i][0]]->actnum); else snprintf(levelinfo[i].str, - sizeof levelinfo[i].str, + sizeof(levelinfo[i].str), "%s %s", mapheaderinfo[votelevels[i][0]]->lvlttl, mapheaderinfo[votelevels[i][0]]->zonttl); } @@ -1609,9 +1620,6 @@ void Y_SetupVoteFinish(SINT8 pick, SINT8 level) if (votes[i] == -1 || endtype > 1) // Don't need to go on continue; - if (endtype == 2) - continue; - if (votecompare == -1) { votecompare = votes[i]; diff --git a/src/z_zone.cpp b/src/z_zone.cpp index 549696bd7..3a78c7079 100644 --- a/src/z_zone.cpp +++ b/src/z_zone.cpp @@ -44,7 +44,6 @@ #ifdef HAVE_VALGRIND #include "valgrind.h" static boolean Z_calloc = false; -#include "memcheck.h" #endif #define ZONEID 0xa441d13d @@ -114,6 +113,7 @@ void Z_Init(void) head.next = head.prev = &head; memfree = I_GetFreeMem(&total)>>20; + CONS_Printf("System memory: %sMB - Free: %sMB\n", sizeu1(total>>20), sizeu2(memfree)); // Note: This allocates memory. Watch out. @@ -179,7 +179,7 @@ void Z_Free(void *ptr) if (block->user != NULL) *block->user = NULL; -#ifdef VALGRIND_DESTROY_MEMPOOL +#ifdef HAVE_VALGRIND VALGRIND_DESTROY_MEMPOOL(block); #endif block->prev->next = block->next; @@ -245,10 +245,6 @@ void *Z_Malloc(size_t size, INT32 tag, void *user) ptr = MEMORY(block); I_Assert((intptr_t)ptr % alignof (max_align_t) == 0); -#ifdef HAVE_VALGRIND - Z_calloc = false; -#endif - block->next = head.next; block->prev = &head; head.next = block; @@ -262,8 +258,9 @@ void *Z_Malloc(size_t size, INT32 tag, void *user) #endif block->size = size; -#ifdef VALGRIND_CREATE_MEMPOOL +#ifdef HAVE_VALGRIND VALGRIND_CREATE_MEMPOOL(block, size, Z_calloc); + Z_calloc = false; #endif #ifdef PARANOIA @@ -300,7 +297,8 @@ void *Z_Calloc2(size_t size, INT32 tag, void *user, const char *file, INT32 line void *Z_Calloc(size_t size, INT32 tag, void *user) #endif { -#ifdef VALGRIND_MEMPOOL_ALLOC + +#ifdef HAVE_VALGRIND Z_calloc = true; #endif #ifdef ZDEBUG @@ -512,6 +510,16 @@ void Z_CheckHeap(INT32 tag) (void)tag; #endif +#ifdef ZDEBUG +#define HeapError(msg) \ + I_Error("Z_CheckHeap : %s:%d, block %u (owned by %s:%d) %s", \ + file, line, blocknumon, block->ownerfile, block->ownerline, msg) +#else +#define HeapError(msg) \ + I_Error("Z_CheckHeap : block %u (owned by %s:%d) %s", \ + blocknumon, block->ownerfile, block->ownerline, msg) +#endif + for (block = head.next; block != &head; block = block->next) { blocknumon++; @@ -520,100 +528,30 @@ void Z_CheckHeap(INT32 tag) CONS_Debug(DBG_MEMORY, "block %u owned by %s:%d\n", blocknumon, block->ownerfile, block->ownerline); #endif -#ifdef VALGRIND_MEMPOOL_EXISTS - if (!VALGRIND_MEMPOOL_EXISTS(block)) +#ifdef HAVE_VALGRIND + if (RUNNING_ON_VALGRIND && !VALGRIND_MEMPOOL_EXISTS(block)) { - I_Error("Z_CheckHeap %d: block %u" -#ifdef ZDEBUG - " (owned by %s:%d)" -#endif - " should not exist", i, blocknumon -#ifdef ZDEBUG - , block->ownerfile, block->ownerline -#endif - ); + HeapError(" should not exist"); } #endif if (block->user != NULL && *(block->user) != given) { - I_Error("Z_CheckHeap :" -#ifdef ZDEBUG - " %s %d" -#endif - " block %u" -#ifdef ZDEBUG - " (owned by %s:%d)" -#endif - " doesn't have a proper user" -#ifdef ZDEBUG - , file, line -#endif - , blocknumon -#ifdef ZDEBUG - , block->ownerfile, block->ownerline -#endif - ); + HeapError(" doesn't have a proper user"); } + if (block->next->prev != block) { - I_Error("Z_CheckHeap :" -#ifdef ZDEBUG - " %s %d" -#endif - " block %u" -#ifdef ZDEBUG - " (owned by %s:%d)" -#endif - " lacks proper backlink" -#ifdef ZDEBUG - , file, line -#endif - , blocknumon -#ifdef ZDEBUG - , block->ownerfile, block->ownerline -#endif - ); + HeapError(" lacks proper backlink"); } + if (block->prev->next != block) { - I_Error("Z_CheckHeap :" -#ifdef ZDEBUG - " %s %d" -#endif - " block %u" -#ifdef ZDEBUG - " (owned by %s:%d)" -#endif - " lacks proper forward link" -#ifdef ZDEBUG - , file, line -#endif - , blocknumon -#ifdef ZDEBUG - , block->ownerfile, block->ownerline -#endif - ); + HeapError(" lacks proper forward link"); } #ifdef PARANOIA if (block->id != ZONEID) { - I_Error("Z_CheckHeap :" -#ifdef ZDEBUG - " %s %d" -#endif - " block %u" -#ifdef ZDEBUG - " (owned by %s:%d)" -#endif - " have the wrong ID" -#ifdef ZDEBUG - , file, line -#endif - , blocknumon -#ifdef ZDEBUG - , block->ownerfile, block->ownerline -#endif - ); + HeapError(" has the wrong ID"); } #endif } @@ -651,9 +589,6 @@ void Z_ChangeTag(void *ptr, INT32 tag) I_Error("Internal memory management error: " "tried to make block purgable but it has no owner"); - // No, please, don't make my PU_STATIC patch NULL! It supposed to be always valid! - if (block->tag < 10) return; - block->tag = tag; } @@ -740,6 +675,7 @@ static void Command_Memfree_f(void) CONS_Printf(M_GetText("HUD graphics : %7s KB\n"), sizeu1(Z_TagUsage(PU_HUDGFX)>>10)); CONS_Printf(M_GetText("Locked cache : %7s KB\n"), sizeu1(Z_TagUsage(PU_CACHE)>>10)); CONS_Printf(M_GetText("Level : %7s KB\n"), sizeu1(Z_TagUsage(PU_LEVEL)>>10)); + CONS_Printf(M_GetText("Level (pooled) : %7s KB\n"), sizeu1(Z_LevelPoolUsage()>>10)); CONS_Printf(M_GetText("Special thinker : %7s KB\n"), sizeu1(Z_TagUsage(PU_LEVSPEC)>>10)); CONS_Printf(M_GetText("All purgable : %7s KB\n"), sizeu1(Z_TagsUsage(PU_PURGELEVEL, INT32_MAX)>>10)); @@ -799,6 +735,14 @@ char *Z_StrDup(const char *s) return strcpy((char*)ZZ_Alloc(strlen(s) + 1), s); } +size_t Z_LevelPoolUsage(void) +{ + return g_level_large_pool.allocated_bytes() + + g_level_med_pool.allocated_bytes() + + g_level_small_pool.allocated_bytes() + + g_level_tiny_pool.allocated_bytes(); +} + void* Z_LevelPoolMalloc(size_t size) { void* p = nullptr; diff --git a/src/z_zone.h b/src/z_zone.h index 90a55b465..847e47291 100644 --- a/src/z_zone.h +++ b/src/z_zone.h @@ -91,7 +91,7 @@ void Z_Init(void); // Z_Free and alloc with alignment #ifdef ZDEBUG -#define Z_Free(p) Z_Free2(p, __FILE__, __LINE__) +#define Z_Free(p) Z_Free2(p, __FILE__, __LINE__) #define Z_Malloc(s,t,u) Z_Malloc2(s, t, u, __FILE__, __LINE__) #define Z_Calloc(s,t,u) Z_Calloc2(s, t, u, __FILE__, __LINE__) #define Z_Realloc(p,s,t,u) Z_Realloc2(p,s, t, u, __FILE__, __LINE__) @@ -167,6 +167,7 @@ char *Z_StrDup(const char *in); // // Specialty allocation functions // +size_t Z_LevelPoolUsage(void); void *Z_LevelPoolMalloc(size_t size); void *Z_LevelPoolCalloc(size_t size); void Z_LevelPoolFree(void *p, size_t size);