diff --git a/.github/workflows/static_analysis.yml b/.github/workflows/static_analysis.yml index a7262484..993754d3 100644 --- a/.github/workflows/static_analysis.yml +++ b/.github/workflows/static_analysis.yml @@ -26,4 +26,4 @@ jobs: use_cmake: false # (Optional) cppcheck args - cppcheck_args: -i$GITHUB_WORKSPACE/components/gbc/gnuboy -i$GITHUB_WORKSPACE/components/nes/nofrendo -i$GITHUB_WORKSPACE/components/msx/fmsx -i$GITHUB_WORKSPACE/components/doom/prboom -i$GITHUB_WORKSPACE/components/sms/smsplus -i$GITHUB_WORKSPACE/components/genesis/gwenesis -i$GITHUB_WORKSPACE/components/darkforces/tfe -i$GITHUB_WORKSPACE/components/gui/generated -i$GITHUB_WORKSPACE/components/menu/generated -i$GITHUB_WORKSPACE/components/jpegdec -i$GITHUB_WORKSPACE/components/pico8/femto8 --check-level=exhaustive --force --enable=all --inline-suppr --inconclusive --platform=mips32 --std=c++17 --suppressions-list=$GITHUB_WORKSPACE/suppressions.txt + cppcheck_args: -i$GITHUB_WORKSPACE/components/gbc/gnuboy -i$GITHUB_WORKSPACE/components/nes/nofrendo -i$GITHUB_WORKSPACE/components/msx/fmsx -i$GITHUB_WORKSPACE/components/doom/prboom -i$GITHUB_WORKSPACE/components/sms/smsplus -i$GITHUB_WORKSPACE/components/genesis/gwenesis -i$GITHUB_WORKSPACE/components/darkforces/TheForceEngine -i$GITHUB_WORKSPACE/components/gui/generated -i$GITHUB_WORKSPACE/components/menu/generated -i$GITHUB_WORKSPACE/components/jpegdec -i$GITHUB_WORKSPACE/components/pico8/femto8 --check-level=exhaustive --force --enable=all --inline-suppr --inconclusive --platform=mips32 --std=c++17 --suppressions-list=$GITHUB_WORKSPACE/suppressions.txt diff --git a/.gitmodules b/.gitmodules index 4c102a35..a317acaa 100644 --- a/.gitmodules +++ b/.gitmodules @@ -9,3 +9,27 @@ path = components/pico8/femto8 url = https://github.com/esp-cpp/femto8.git branch = esp32 +[submodule "components/nes/nofrendo"] + path = components/nes/nofrendo + url = https://github.com/esp-cpp/nofrendo.git + branch = main +[submodule "components/gbc/gnuboy"] + path = components/gbc/gnuboy + url = https://github.com/esp-cpp/gnuboy.git + branch = main +[submodule "components/msx/fmsx"] + path = components/msx/fmsx + url = https://github.com/esp-cpp/fmsx.git + branch = main +[submodule "components/sms/smsplus"] + path = components/sms/smsplus + url = https://github.com/esp-cpp/smsplus.git + branch = main +[submodule "components/doom/prboom"] + path = components/doom/prboom + url = https://github.com/esp-cpp/prboom.git + branch = main +[submodule "components/darkforces/TheForceEngine"] + path = components/darkforces/TheForceEngine + url = https://github.com/esp-cpp/TheForceEngine.git + branch = main diff --git a/README.md b/README.md index f36a088e..e945cca4 100644 --- a/README.md +++ b/README.md @@ -95,6 +95,15 @@ that removes the frame-rate cap for maximum speed. | Dark Forces | [The Force Engine](https://theforceengine.github.io/) (via [BSzili's Amiga port](https://github.com/BSzili/TheForceEngine/tree/amiga)) | — | Software renderer, iMuse sound effects and OPL3 music; see [Dark Forces setup](#dark-forces-setup) | | PICO-8 | [femto8](https://github.com/benbaker76/femto8) | — | `.p8` and `.p8.png` carts; D-Pad, A/Y = O, B/X = X, START = PICO-8 pause menu; save states; cartdata saves to `pico8/cdata/`; see [PICO-8 setup](#pico-8-setup) | +Every core is a submodule ([esp-cpp/nofrendo](https://github.com/esp-cpp/nofrendo), +[gnuboy](https://github.com/esp-cpp/gnuboy), [smsplus](https://github.com/esp-cpp/smsplus), +[gwenesis](https://github.com/esp-cpp/gwenesis), [fmsx](https://github.com/esp-cpp/fmsx), +[prboom](https://github.com/esp-cpp/prboom), [TheForceEngine](https://github.com/esp-cpp/TheForceEngine), +[femto8](https://github.com/esp-cpp/femto8)): the core plus its `port/` glue to +`BoxEmu`, shared with [tab5-emu](https://github.com/esp-cpp/tab5-emu). Each +`components//CMakeLists.txt` here is the board's wrapper for it +(requirements, compile flags, linker fragment). + > 🧬 **Full-speed Genesis on the S3.** The Genesis core ships with a custom > **dual-core** modification of gwenesis that spreads the workload across both of > the ESP32-S3's CPU cores: **core 0** runs the 68000 CPU and VDP (video), while diff --git a/components/darkforces/CMakeLists.txt b/components/darkforces/CMakeLists.txt index 457171e5..c019ee89 100644 --- a/components/darkforces/CMakeLists.txt +++ b/components/darkforces/CMakeLists.txt @@ -1,42 +1,44 @@ # Dark Forces for esp-box-emu, built on The Force Engine (TFE). # -# tfe/ contains a vendored subset of BSzili's Amiga branch of TFE (based on -# TFE v1.09.410) with the __AMIGA__ platform guards renamed to TFE_ESPBOX. -# src/platform/ provides the ESP32 implementations of the platform interfaces -# (system timers, render backend, audio, threads, memory regions, stubs). +# From the esp-cpp/TheForceEngine submodule: TheForceEngine/tfe is a subset of +# BSzili's Amiga branch of TFE (based on TFE v1.09.410) with the __AMIGA__ +# platform guards renamed to TFE_ESPBOX (see TheForceEngine/VENDOR.md); +# TheForceEngine/port/platform provides the ESP32 implementations of the +# platform interfaces (system timers, render backend, audio, threads, memory +# regions, stubs). set(TFE_SRC_DIRS - "tfe/TFE_System" - "tfe/TFE_Memory" - "tfe/TFE_FileSystem" - "tfe/TFE_Archive" - "tfe/TFE_Asset" - "tfe/TFE_Audio" - "tfe/TFE_Audio/MidiSynth" - "tfe/TFE_Input" - "tfe/TFE_Settings" - "tfe/TFE_Game" - "tfe/TFE_Outlaws" - "tfe/TFE_Jedi/Collision" - "tfe/TFE_Jedi/IMuse" - "tfe/TFE_Jedi/InfSystem" - "tfe/TFE_Jedi/Level" - "tfe/TFE_Jedi/Math" - "tfe/TFE_Jedi/Memory" - "tfe/TFE_Jedi/Serialization" - "tfe/TFE_Jedi/Task" - "tfe/TFE_Jedi/Renderer" - "tfe/TFE_Jedi/Renderer/RClassic_Fixed" - "tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed" - "tfe/TFE_DarkForces" - "tfe/TFE_DarkForces/Actor" - "tfe/TFE_DarkForces/GameUI" - "tfe/TFE_DarkForces/Landru" + "TheForceEngine/tfe/TFE_System" + "TheForceEngine/tfe/TFE_Memory" + "TheForceEngine/tfe/TFE_FileSystem" + "TheForceEngine/tfe/TFE_Archive" + "TheForceEngine/tfe/TFE_Asset" + "TheForceEngine/tfe/TFE_Audio" + "TheForceEngine/tfe/TFE_Audio/MidiSynth" + "TheForceEngine/tfe/TFE_Input" + "TheForceEngine/tfe/TFE_Settings" + "TheForceEngine/tfe/TFE_Game" + "TheForceEngine/tfe/TFE_Outlaws" + "TheForceEngine/tfe/TFE_Jedi/Collision" + "TheForceEngine/tfe/TFE_Jedi/IMuse" + "TheForceEngine/tfe/TFE_Jedi/InfSystem" + "TheForceEngine/tfe/TFE_Jedi/Level" + "TheForceEngine/tfe/TFE_Jedi/Math" + "TheForceEngine/tfe/TFE_Jedi/Memory" + "TheForceEngine/tfe/TFE_Jedi/Serialization" + "TheForceEngine/tfe/TFE_Jedi/Task" + "TheForceEngine/tfe/TFE_Jedi/Renderer" + "TheForceEngine/tfe/TFE_Jedi/Renderer/RClassic_Fixed" + "TheForceEngine/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed" + "TheForceEngine/tfe/TFE_DarkForces" + "TheForceEngine/tfe/TFE_DarkForces/Actor" + "TheForceEngine/tfe/TFE_DarkForces/GameUI" + "TheForceEngine/tfe/TFE_DarkForces/Landru" ) idf_component_register( - INCLUDE_DIRS "include" - SRC_DIRS "src" "src/platform" ${TFE_SRC_DIRS} - PRIV_INCLUDE_DIRS "tfe" "src/platform" + INCLUDE_DIRS "TheForceEngine/port/include" + SRC_DIRS "TheForceEngine/port" "TheForceEngine/port/platform" ${TFE_SRC_DIRS} + PRIV_INCLUDE_DIRS "TheForceEngine/tfe" "TheForceEngine/port/platform" REQUIRES box-emu statistics pool_allocator esp_timer pthread heap esp_system LDFRAGMENTS "linker.lf" ) @@ -82,20 +84,20 @@ target_compile_options(${COMPONENT_LIB} PRIVATE # The renderer and the OPL3 synthesizer are the hot paths: optimize those for speed. file(GLOB_RECURSE DF_HOT_SOURCES - "${CMAKE_CURRENT_SOURCE_DIR}/tfe/TFE_Jedi/Renderer/*.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/tfe/TFE_Jedi/Math/*.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/tfe/TFE_Audio/MidiSynth/*.c" - "${CMAKE_CURRENT_SOURCE_DIR}/tfe/TFE_Audio/MidiSynth/*.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/tfe/TFE_Jedi/IMuse/imDigitalSound.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/TheForceEngine/tfe/TFE_Jedi/Renderer/*.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/TheForceEngine/tfe/TFE_Jedi/Math/*.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/TheForceEngine/tfe/TFE_Audio/MidiSynth/*.c" + "${CMAKE_CURRENT_SOURCE_DIR}/TheForceEngine/tfe/TFE_Audio/MidiSynth/*.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/TheForceEngine/tfe/TFE_Jedi/IMuse/imDigitalSound.cpp" ) set_source_files_properties(${DF_HOT_SOURCES} PROPERTIES COMPILE_OPTIONS "-O2") # Everything Dark Forces allocates lives in BoxEmu's 4MB ROM block while it runs -# (src/platform/esp_alloc.cpp): rename the allocation functions referenced by +# (TheForceEngine/port/platform/esp_alloc.cpp): rename the allocation functions referenced by # this library to the df_* replacements, and route free()/realloc() of block # pointers made anywhere in the firmware back to the block. add_custom_command(TARGET ${COMPONENT_LIB} POST_BUILD - COMMAND ${CMAKE_OBJCOPY} --redefine-syms=${CMAKE_CURRENT_SOURCE_DIR}/alloc_redirect.syms $ + COMMAND ${CMAKE_OBJCOPY} --redefine-syms=${CMAKE_CURRENT_SOURCE_DIR}/TheForceEngine/port/alloc_redirect.syms $ COMMENT "Redirecting Dark Forces allocations to the ROM block" VERBATIM) target_link_libraries(${COMPONENT_LIB} INTERFACE "-Wl,--wrap=free" "-Wl,--wrap=realloc") diff --git a/components/darkforces/TheForceEngine b/components/darkforces/TheForceEngine new file mode 160000 index 00000000..12d2a3b3 --- /dev/null +++ b/components/darkforces/TheForceEngine @@ -0,0 +1 @@ +Subproject commit 12d2a3b308995348f86f35946fa0786ed9931129 diff --git a/components/darkforces/VENDOR.md b/components/darkforces/VENDOR.md deleted file mode 100644 index 60ff55a4..00000000 --- a/components/darkforces/VENDOR.md +++ /dev/null @@ -1,61 +0,0 @@ -# Vendored sources - -`tfe/` is a subset of **The Force Engine** (TFE), taken from BSzili's Amiga port -branch, which had already stripped the desktop-only subsystems (OpenGL, SDL, -ImGui front end, editor, mods) and added low-spec code paths. - -- Upstream: https://github.com/luciusDXL/TheForceEngine (GPL-2.0) -- Branch used: https://github.com/BSzili/TheForceEngine/tree/amiga -- Commit: `d116b7a9efc29e8c9223db19d5e5ad743c8f8372` (based on TFE v1.09.410) - -The file list mirrors `Makefile.amiga` from that branch (minus the Amiga -platform files under `amiga/`). Changes made for the ESP32 port: - -- `__AMIGA__` platform guards were renamed to `TFE_ESPBOX` (defined by the - component's CMakeLists). -- `TFE_System/system.cpp` and `TFE_System/log.cpp` were rewritten for - `esp_timer` / serial logging. -- `TFE_Jedi/Renderer/virtualFramebuffer.cpp`: the 320x200 8-bit framebuffer is - supplied by the platform (`vfb_setPlatformBuffer()`). -- `TFE_Audio/*`: MIDI devices render 16-bit integer samples (`MidiSample`), - `midiPlayer.cpp` sleeps between iMuse updates, and the AHI left/right channel - swap in `imDigitalSound.cpp` was removed. -- `TFE_Jedi/Task/task.cpp`: smaller task context stacks (8KB x 16 per chunk). -- `TFE_FileSystem/fileutil-posix.cpp`: no cwd / executable directory. -- `TFE_Game/saveSystem.h`: save thumbnails disabled (4x4). -- `TFE_DarkForces/darkForcesMain.cpp`: state reset restored in `exitGame()`. -- Loaders (`level.cpp`, `rtexture.cpp`, `infSystem.cpp`, `spriteAsset_Jedi.cpp`, - `modelAsset_jedi.cpp`, `vueAsset.cpp`): `espbox_free_*_scratch()` hooks release - the static read buffers at shutdown. -- `TFE_Asset/modelAsset_jedi.cpp`: no GPU drawId free after the level region is cleared. -- `TFE_Game/saveSystem.cpp`: absolute save paths; buffers nulled on shutdown. -- `TFE_Jedi/Renderer/RClassic_Fixed/rclassicFixedSharedState.*`: the state is a - platform allocated pointer instead of a 320KB static. -- Large statics (stream/parser/settings/save buffers, OPL3 chip, MIDI buffers, - palettes, ...) are pointers allocated from BoxEmu's 4MB ROM block through - per-file `espbox_shared_*()` hooks (`TFE_System/espboxShared.h`). -- Shutdown-only `espbox_release_*_caches()` hooks (settings, paths, MIDI player, - renderer, 3D object, texture, sprite and model caches) release static STL - container storage so nothing is left in the ROM block between sessions. -- `TFE_DarkForces/sound.cpp`: level sounds are registered at startup but read - from the card the first time they play (`vocFileExists()` in `lsound.cpp`). -- `TFE_DarkForces/GameUI/escapeMenu.cpp`: the escape / confirmation menu frames - are loaded when the menu opens and freed when it closes. -- `TFE_Archive/gobArchive.cpp`: directory reads are validated. -- `TFE_Audio/MidiSynth/opl3.c`: lookup tables placed in internal RAM (`DRAM_ATTR`). -- `TFE_System/parser.cpp`: `initFromFile()` parses through a 64KB sliding window - of an open file (`FileStream::reselect()` makes the stream's archive entry - current again before each refill); the level, objects, goals and INF loaders - use it instead of reading the whole file into memory. -- `TFE_DarkForces/Landru/cutscene_player.cpp`: a scene's sounds are released - when it ends (not only when skipped); `cutscenePlayer_abort()` stops a running - sequence when a game is loaded. -- `TFE_DarkForces/GameUI/escapeMenu.cpp`: the confirmation frames load on demand - and all frames are released whenever the menu closes. - -All allocations made by this library go to the 4MB ROM block while the game -runs: see `../src/platform/esp_alloc.cpp` and `../alloc_redirect.syms`. - -`SDL_endian.h` is the Amiga branch's little-endian shim for `TFE_System/endian.h`. - -The ESP32 platform implementations live in `../src/platform/`. diff --git a/components/darkforces/alloc_redirect.syms b/components/darkforces/alloc_redirect.syms deleted file mode 100644 index ded11605..00000000 --- a/components/darkforces/alloc_redirect.syms +++ /dev/null @@ -1,13 +0,0 @@ -malloc df_malloc -calloc df_calloc -realloc df_realloc -free df_free -strdup df_strdup -_Znwj df_new -_Znaj df_new_array -_ZnwjRKSt9nothrow_t df_new_nothrow -_ZnajRKSt9nothrow_t df_new_array_nothrow -_ZdlPv df_delete -_ZdaPv df_delete_array -_ZdlPvj df_delete_sized -_ZdaPvj df_delete_array_sized diff --git a/components/darkforces/include/darkforces.hpp b/components/darkforces/include/darkforces.hpp deleted file mode 100644 index d362ace8..00000000 --- a/components/darkforces/include/darkforces.hpp +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -/// Start Dark Forces. \p gob_filename is the full path to DARK.GOB; the game -/// data (DARK.GOB, SOUNDS.GOB, SPRITES.GOB, TEXTURES.GOB and the LFD/ folder) -/// must live in the same directory, which is also used for settings and saves. -void init_darkforces(const std::string& gob_filename, uint8_t *romdata, size_t rom_data_size); -void reset_darkforces(); -void run_darkforces_rom(); -void deinit_darkforces(); -/// True once the player has quit the game from its own menu. -bool darkforces_quit_requested(); -void pause_darkforces_tasks(); -void resume_darkforces_tasks(); -void load_darkforces(std::string_view save_path, int save_slot); -void save_darkforces(std::string_view save_path, int save_slot); -std::span get_darkforces_video_buffer(); diff --git a/components/darkforces/src/darkforces.cpp b/components/darkforces/src/darkforces.cpp deleted file mode 100644 index 5be0ee59..00000000 --- a/components/darkforces/src/darkforces.cpp +++ /dev/null @@ -1,878 +0,0 @@ -// Dark Forces (The Force Engine) glue for esp-box-emu. -// -// This mirrors what TheForceEngine/main.cpp (and the Amiga port's main) do: -// set up paths/settings/system/render/audio, create the game, and then run one -// iteration of the engine loop per call to run_darkforces_rom(). -#include "darkforces.hpp" - -#include "box-emu.hpp" -#include "statistics.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "pool_allocator.h" -#include "platform/esp_platform.h" -#include -#include - -#include -#include -#include -#include -#if CONFIG_HEAP_TRACING_STANDALONE -#include -#endif -#include -#if CONFIG_ESP_TASK_WDT_EN -#include -#endif -#include -#include - -#include -#include -#include - -using namespace TFE_Input; - -namespace TFE_RenderBackend -{ - const uint16_t* getDisplayPalette(); -} -bool darkforces_init_shared_memory(); -void espbox_release_settings_caches(); -void espbox_release_model_caches(); -void espbox_release_sprite_caches(); -void espbox_release_midiPlayer_caches(); -void espbox_release_renderer_caches(); -void espbox_release_robj3d_caches(); -void espbox_release_robj3dCulling_caches(); -void espbox_release_rtexture_caches(); -void espbox_release_paths_caches(); -void darkforces_free_shared_memory(); -namespace TFE_FrontEndUI -{ - bool exitToMenuRequested(); -} -namespace TFE_DarkForces -{ - extern JBool s_palModified; -} -// Scratch buffer release hooks added to the vendored loaders (see VENDOR.md). -void espbox_free_rtexture_scratch(); -void espbox_free_sprite_scratch(); -void espbox_free_level_scratch(); -void espbox_free_vue_scratch(); -void espbox_free_inf_scratch(); -void espbox_free_model_scratch(); - -namespace -{ - constexpr int DF_WIDTH = 320; - constexpr int DF_HEIGHT = 200; - - std::string s_gobPath; - std::string s_gameDir; // directory containing the GOB files, with trailing slash. - IGame* s_curGame = nullptr; - bool s_initialized = false; - TFE_Jedi::RClassicFixedState* s_rcfStateMem = nullptr; // in the 4MB block - bool s_quit = false; - bool s_paused = false; - uint8_t* s_frameBuffer = nullptr; // 8-bit 320x200 render target (BoxEmu frame buffer 0). - const char* s_argv[2] = { "darkforces", nullptr }; - - // Virtual mouse used to drive the (mouse based) menus with the d-pad. - struct VirtualMouse - { - float x = DF_WIDTH / 2; - float y = DF_HEIGHT / 2; - float speed = 0.0f; - }; - VirtualMouse s_mouse; - - // Controller bindings for the box gamepad. Unmodified buttons map to - // controller buttons; SELECT acts as a modifier that re-routes buttons to - // alternate controller buttons / keyboard keys (see updateInput()). - InputBinding s_boxControllerBinds[] = - { - { IADF_FORWARD, ITYPE_CONTROLLER, CONTROLLER_BUTTON_DPAD_UP }, - { IADF_BACKWARD, ITYPE_CONTROLLER, CONTROLLER_BUTTON_DPAD_DOWN }, - { IADF_TURN_LT, ITYPE_CONTROLLER, CONTROLLER_BUTTON_DPAD_LEFT }, - { IADF_TURN_RT, ITYPE_CONTROLLER, CONTROLLER_BUTTON_DPAD_RIGHT }, - { IADF_PRIMARY_FIRE, ITYPE_CONTROLLER, CONTROLLER_BUTTON_A }, - { IADF_JUMP, ITYPE_CONTROLLER, CONTROLLER_BUTTON_B }, - { IADF_USE, ITYPE_CONTROLLER, CONTROLLER_BUTTON_X }, - { IADF_CYCLEWPN_NEXT, ITYPE_CONTROLLER, CONTROLLER_BUTTON_Y }, - { IADF_MENU_TOGGLE, ITYPE_CONTROLLER, CONTROLLER_BUTTON_START }, - // SELECT + d-pad left/right - { IADF_STRAFE_LT, ITYPE_CONTROLLER, CONTROLLER_BUTTON_LEFTSHOULDER }, - { IADF_STRAFE_RT, ITYPE_CONTROLLER, CONTROLLER_BUTTON_RIGHTSHOULDER }, - // SELECT + down (hold) - { IADF_CROUCH, ITYPE_CONTROLLER, CONTROLLER_BUTTON_LEFTSTICK }, - // SELECT + A - { IADF_SECONDARY_FIRE, ITYPE_CONTROLLER, CONTROLLER_BUTTON_RIGHTSTICK }, - // SELECT + Y - { IADF_CYCLEWPN_PREV, ITYPE_CONTROLLER, CONTROLLER_BUTTON_GUIDE }, - }; - - struct ButtonMap - { - GamepadState::Button pad; - Button ctrl; // controller button when SELECT is not held. - Button altCtrl; // controller button when SELECT is held (CONTROLLER_BUTTON_UNKNOWN = use altKey) - KeyboardCode altKey;// keyboard key when SELECT is held. - }; - // In-game mapping. - const ButtonMap s_gameMap[] = - { - { GamepadState::Button::UP, CONTROLLER_BUTTON_DPAD_UP, CONTROLLER_BUTTON_UNKNOWN, KEY_TAB }, // automap - { GamepadState::Button::DOWN, CONTROLLER_BUTTON_DPAD_DOWN, CONTROLLER_BUTTON_LEFTSTICK, KEY_UNKNOWN }, // crouch - { GamepadState::Button::LEFT, CONTROLLER_BUTTON_DPAD_LEFT, CONTROLLER_BUTTON_LEFTSHOULDER, KEY_UNKNOWN }, // strafe left - { GamepadState::Button::RIGHT, CONTROLLER_BUTTON_DPAD_RIGHT, CONTROLLER_BUTTON_RIGHTSHOULDER, KEY_UNKNOWN }, // strafe right - { GamepadState::Button::A, CONTROLLER_BUTTON_A, CONTROLLER_BUTTON_RIGHTSTICK, KEY_UNKNOWN }, // secondary fire - { GamepadState::Button::B, CONTROLLER_BUTTON_B, CONTROLLER_BUTTON_UNKNOWN, KEY_F5 }, // headlamp - { GamepadState::Button::X, CONTROLLER_BUTTON_X, CONTROLLER_BUTTON_UNKNOWN, KEY_F4 }, // gas mask - { GamepadState::Button::Y, CONTROLLER_BUTTON_Y, CONTROLLER_BUTTON_GUIDE, KEY_UNKNOWN }, // previous weapon - { GamepadState::Button::START, CONTROLLER_BUTTON_START, CONTROLLER_BUTTON_UNKNOWN, KEY_F2 }, // night vision - }; - // Menu / cutscene mapping (keyboard keys only; the d-pad drives the virtual mouse). - struct MenuKeyMap - { - GamepadState::Button pad; - KeyboardCode key; - MouseButton mouse; - }; - const MenuKeyMap s_menuMap[] = - { - { GamepadState::Button::A, KEY_UNKNOWN, MBUTTON_LEFT }, - { GamepadState::Button::START, KEY_RETURN, MBUTTON_COUNT }, - { GamepadState::Button::B, KEY_ESCAPE, MBUTTON_COUNT }, - { GamepadState::Button::Y, KEY_SPACE, MBUTTON_COUNT }, - { GamepadState::Button::X, KEY_N, MBUTTON_COUNT }, - }; - - // Everything that is currently reported as "down" to the engine, so it can - // be released cleanly when the mapping changes (menu <-> game, modifier). - bool s_ctrlDown[CONTROLLER_BUTTON_COUNT] = {}; - bool s_keyDown[KEY_COUNT] = {}; - bool s_mouseDown[MBUTTON_COUNT] = {}; - bool s_wasMenuMode = true; - - // Gamepad text entry for the agent name box (SELECT held in a menu): - // SELECT+Right add a new letter (starts at 'A') - // SELECT+Up/Dn change the last letter - // SELECT+Left backspace - // The engine's edit box applies buffered text before buffered keys within a - // frame, so "replace the last letter" is queued as two frames: backspace, then - // the new letter. - const char c_textChars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 "; - constexpr int TEXT_QUEUE_LEN = 8; - char s_textQueue[TEXT_QUEUE_LEN]; // 0 = nothing, '\b' = backspace, else the character to type. - int s_textQueueHead = 0, s_textQueueCount = 0; - int s_lastTextChar = -1; // index into c_textChars of the last letter we typed, -1 = unknown. - uint16_t s_prevPadButtons = 0; - - void queueText(char c) - { - if (s_textQueueCount >= TEXT_QUEUE_LEN) { return; } - s_textQueue[(s_textQueueHead + s_textQueueCount) % TEXT_QUEUE_LEN] = c; - s_textQueueCount++; - } - - void flushTextQueue() - { - if (s_textQueueCount == 0) { return; } - const char c = s_textQueue[s_textQueueHead]; - s_textQueueHead = (s_textQueueHead + 1) % TEXT_QUEUE_LEN; - s_textQueueCount--; - if (c == '\b') - { - TFE_Input::setBufferedKey(KEY_BACKSPACE); - } - else - { - char text[2] = { c, 0 }; - TFE_Input::setBufferedInput(text); - } - } - - void updateTextEntry(const GamepadState& state) - { - const uint16_t pressed = state.buttons & ~s_prevPadButtons; - const int numChars = int(sizeof(c_textChars) - 1); - if (pressed & (1 << int(GamepadState::Button::RIGHT))) - { - s_lastTextChar = 0; - queueText(c_textChars[0]); - } - else if (pressed & (1 << int(GamepadState::Button::LEFT))) - { - queueText('\b'); - s_lastTextChar = -1; - } - else if ((pressed & (1 << int(GamepadState::Button::UP))) || (pressed & (1 << int(GamepadState::Button::DOWN)))) - { - const int dir = (pressed & (1 << int(GamepadState::Button::UP))) ? 1 : -1; - if (s_lastTextChar < 0) - { - // Nothing known at the end of the field: start a new letter. - s_lastTextChar = 0; - queueText(c_textChars[0]); - } - else - { - s_lastTextChar = (s_lastTextChar + dir + numChars) % numChars; - queueText('\b'); - queueText(c_textChars[s_lastTextChar]); - } - } - } - - void setCtrl(Button b, bool down) - { - if (b >= CONTROLLER_BUTTON_COUNT) { return; } - if (down && !s_ctrlDown[b]) { TFE_Input::setButtonDown(b); } - else if (!down && s_ctrlDown[b]) { TFE_Input::setButtonUp(b); } - s_ctrlDown[b] = down; - } - - void setKey(KeyboardCode k, bool down) - { - if (k == KEY_UNKNOWN || k >= KEY_COUNT) { return; } - if (down && !s_keyDown[k]) - { - TFE_Input::setKeyDown(k); - TFE_Input::setBufferedKey(k); - } - else if (!down && s_keyDown[k]) { TFE_Input::setKeyUp(k); } - s_keyDown[k] = down; - } - - void setMouse(MouseButton m, bool down) - { - if (m >= MBUTTON_COUNT) { return; } - if (down && !s_mouseDown[m]) { TFE_Input::setMouseButtonDown(m); } - else if (!down && s_mouseDown[m]) { TFE_Input::setMouseButtonUp(m); } - s_mouseDown[m] = down; - } - - void releaseAll() - { - for (int i = 0; i < CONTROLLER_BUTTON_COUNT; i++) { setCtrl(Button(i), false); } - for (int i = 0; i < KEY_COUNT; i++) { if (s_keyDown[i]) { setKey(KeyboardCode(i), false); } } - for (int i = 0; i < MBUTTON_COUNT; i++) { setMouse(MouseButton(i), false); } - } - - void updateInput(bool menuMode) - { - static auto& box = BoxEmu::get(); - const GamepadState state = box.gamepad_state(); - - if (menuMode != s_wasMenuMode) - { - releaseAll(); - s_wasMenuMode = menuMode; - } - - if (menuMode) - { - flushTextQueue(); - if (state.select) - { - // Text entry mode: release the regular menu bindings and drive the edit box. - for (const auto& m : s_menuMap) - { - if (m.key != KEY_UNKNOWN) { setKey(m.key, false); } - if (m.mouse != MBUTTON_COUNT) { setMouse(m.mouse, false); } - } - updateTextEntry(state); - s_prevPadButtons = state.buttons; - TFE_Input::setRelativeMousePos(0, 0); - return; - } - s_prevPadButtons = state.buttons; - s_lastTextChar = -1; - - // Virtual mouse: d-pad moves the cursor with a little acceleration. - const bool moving = state.up || state.down || state.left || state.right; - if (moving) - { - s_mouse.speed = std::min(s_mouse.speed + 0.25f, 4.0f); - } - else - { - s_mouse.speed = 1.0f; - } - if (state.left) { s_mouse.x -= s_mouse.speed; } - if (state.right) { s_mouse.x += s_mouse.speed; } - if (state.up) { s_mouse.y -= s_mouse.speed; } - if (state.down) { s_mouse.y += s_mouse.speed; } - s_mouse.x = std::clamp(s_mouse.x, 0.0f, float(DF_WIDTH - 1)); - s_mouse.y = std::clamp(s_mouse.y, 0.0f, float(DF_HEIGHT - 1)); - TFE_Input::setMousePos(int(s_mouse.x), int(s_mouse.y)); - TFE_Input::setRelativeMousePos(0, 0); - - for (const auto& m : s_menuMap) - { - const bool down = state.is_pressed(m.pad); - if (m.key != KEY_UNKNOWN) { setKey(m.key, down); } - if (m.mouse != MBUTTON_COUNT) { setMouse(m.mouse, down); } - } - } - else - { - TFE_Input::setRelativeMousePos(0, 0); - const bool modifier = state.select; - for (const auto& m : s_gameMap) - { - const bool down = state.is_pressed(m.pad); - const bool altDown = down && modifier; - const bool mainDown = down && !modifier; - setCtrl(m.ctrl, mainDown); - if (m.altCtrl != CONTROLLER_BUTTON_UNKNOWN) { setCtrl(m.altCtrl, altDown); } - if (m.altKey != KEY_UNKNOWN) { setKey(m.altKey, altDown); } - } - } - } - - // Hang detector: an esp_timer that fires if the game loop (or init) has not - // made progress for a while and dumps the task list so we can see who is stuck. - volatile int64_t s_lastProgressUs = 0; - const char* volatile s_progressStage = "idle"; - volatile bool s_hangDetectorEnabled = false; - esp_timer_handle_t s_hangTimer = nullptr; - - void progress(const char* stage) - { - s_progressStage = stage; - s_lastProgressUs = esp_timer_get_time(); - } - - // Runs in the esp_timer task: keep the stack use minimal (no fmt). - void hangCheck(void*) - { - if (!s_hangDetectorEnabled || !s_lastProgressUs) { return; } - const int64_t idle = esp_timer_get_time() - s_lastProgressUs; - if (idle < 15000000) { return; } // level loads on the 8MB box take ~8s - // esp_rom_printf bypasses the stdio locks, so this works even if a task is stuck inside printf. - esp_rom_printf("[DarkForces] *** no progress for %d ms, last stage '%s' ***\n", (int)(idle / 1000), (const char*)s_progressStage); -#if (configUSE_TRACE_FACILITY == 1) && (configUSE_STATS_FORMATTING_FUNCTIONS == 1) - // Allocated on demand; this only runs when the game is already stuck. - static char* taskList = (char*)heap_caps_malloc(2048, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); - if (!taskList) { return; } - vTaskList(taskList); - esp_rom_printf("Name State Prio Stack Num Core\n"); - // print line by line (esp_rom_printf has a limited output length) - char* line = taskList; - while (*line) - { - char* end = strchr(line, '\n'); - if (end) { *end = 0; } - esp_rom_printf("%s\n", line); - if (!end) { break; } - line = end + 1; - } -#endif - // Where every task is stuck (the game task in particular). Only run once: it - // suspends the scheduler and the other core while it walks the stacks. - static bool s_backtracesPrinted = false; - if (!s_backtracesPrinted) - { - s_backtracesPrinted = true; - esp_backtrace_print_all_tasks(16); - } - s_lastProgressUs = esp_timer_get_time(); // report again in 8s if still stuck. - } - - void startHangDetector() - { - if (!s_hangTimer) - { - esp_timer_create_args_t args = {}; - args.callback = hangCheck; - args.name = "df_hang"; - esp_timer_create(&args, &s_hangTimer); - esp_timer_start_periodic(s_hangTimer, 2000000); - } - progress("start"); - s_hangDetectorEnabled = true; - } - - void stopHangDetector() - { - if (s_hangTimer) - { - esp_timer_stop(s_hangTimer); - esp_timer_delete(s_hangTimer); - s_hangTimer = nullptr; - } - s_lastProgressUs = 0; - s_hangDetectorEnabled = false; - } - - void logMemory(const char* when) - { - fmt::print("[DarkForces] {}: free internal {} B (largest {} B), free PSRAM {} B (largest {} B)\n", when, - heap_caps_get_free_size(MALLOC_CAP_INTERNAL), heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL), - heap_caps_get_free_size(MALLOC_CAP_SPIRAM), heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM)); - } - -} - -void init_darkforces(const std::string& gob_filename, uint8_t *romdata, size_t rom_data_size) -{ - TFE_Memory::DfAllocScope allocScope; - s_gobPath = gob_filename; - s_quit = false; - s_paused = false; - s_wasMenuMode = true; - memset(s_ctrlDown, 0, sizeof(s_ctrlDown)); - memset(s_keyDown, 0, sizeof(s_keyDown)); - memset(s_mouseDown, 0, sizeof(s_mouseDown)); - - // The game directory is the directory containing DARK.GOB. - size_t slash = s_gobPath.find_last_of('/'); - s_gameDir = (slash == std::string::npos) ? std::string("/sdcard/") : s_gobPath.substr(0, slash + 1); - fmt::print("[DarkForces] game directory: {}\n", s_gameDir); - logMemory("before init"); - // (CONFIG_HEAP_TRACING_STANDALONE: app_main traces each cart's lifetime and lists what it leaves) - startHangDetector(); -#if CONFIG_ESP_TASK_WDT_EN - esp_task_wdt_add(NULL); -#endif - - auto& box = BoxEmu::get(); - // Dark Forces reads its data from the SD card, so the 4MB ROM block is free: - // everything the engine allocates from here on lives in it (see esp_alloc.cpp). - static constexpr size_t ROM_POOL_SIZE = 4 * 1024 * 1024; - const bool poolOk = TFE_Memory::poolBegin(box.romdata(), ROM_POOL_SIZE); - // The engine's large static buffers. - const bool sharedOk = poolOk && darkforces_init_shared_memory(); - // The classic renderer's shared state is large (~320KB); keep it out of static RAM. - s_rcfStateMem = poolOk ? (TFE_Jedi::RClassicFixedState*)TFE_Memory::lockedPoolAlloc(sizeof(TFE_Jedi::RClassicFixedState)) : nullptr; - TFE_Jedi::RClassicFixedState* rcfState = s_rcfStateMem; - if (!sharedOk || !rcfState) - { - // Not enough memory to run: undo the setup and go straight back to the emulator menu. - fmt::print("[DarkForces] ERROR: out of memory, cannot start Dark Forces\n"); - logMemory("init failed"); - stopHangDetector(); -#if CONFIG_ESP_TASK_WDT_EN - esp_task_wdt_delete(NULL); -#endif - darkforces_free_shared_memory(); - TFE_Memory::lockedPoolFree(s_rcfStateMem); - s_rcfStateMem = nullptr; - TFE_Memory::poolEnd(); - s_quit = true; - return; - } - memset(rcfState, 0, sizeof(TFE_Jedi::RClassicFixedState)); - TFE_Jedi::rcf_setStatePtr(rcfState); - - s_frameBuffer = box.frame_buffer0(); - memset(s_frameBuffer, 0, DF_WIDTH * DF_HEIGHT); - box.native_size(DF_WIDTH, DF_HEIGHT); - - // Paths: everything (game data, settings, saves) lives in the game directory. - TFE_Paths::setPath(PATH_PROGRAM, s_gameDir.c_str()); - TFE_Paths::setPath(PATH_PROGRAM_DATA, s_gameDir.c_str()); - TFE_Paths::setPath(PATH_USER_DOCUMENTS, s_gameDir.c_str()); - TFE_Paths::setPath(PATH_SOURCE_DATA, s_gameDir.c_str()); - TFE_System::logOpen("the_force_engine_log.txt"); - progress("settings"); - - bool firstRun = false; - if (!TFE_Settings::init(firstRun)) - { - TFE_System::logWrite(LOG_ERROR, "Main", "Cannot load settings."); - } - // Force the settings that make sense on this hardware. - TFE_Settings_Graphics* graphics = TFE_Settings::getGraphicsSettings(); - graphics->gameResolution.x = DF_WIDTH; - graphics->gameResolution.z = DF_HEIGHT; - graphics->widescreen = false; - graphics->rendererIndex = 0; - graphics->asyncFramebuffer = false; - graphics->gpuColorConvert = false; - graphics->colorCorrection = false; - graphics->extendAjoinLimits = false; - graphics->reticleEnable = false; - graphics->vsync = false; - TFE_Settings_Sound* sound = TFE_Settings::getSoundSettings(); - sound->midiType = MIDI_TYPE_OPL3; - sound->midiOutput = 0; - sound->audioDevice = -1; - sound->use16Channels = false; - TFE_Settings_Game* game = TFE_Settings::getGameSettings(); - game->df_autorun = true; // no run button on the pad. - game->df_enableAutoaim = true; - game->df_smoothVUEs = false; - TFE_Settings::getSystemSettings()->gameQuitExitsToMenu = true; - // Make sure the game source path points at our directory. - const TFE_Game* gameInfo = TFE_Settings::getGame(); - TFE_GameHeader* gameHeader = TFE_Settings::getGameHeader(gameInfo->game); - strcpy(gameHeader->sourcePath, s_gameDir.c_str()); - TFE_Paths::setPath(PATH_SOURCE_DATA, gameHeader->sourcePath); - - progress("system"); - TFE_System::init(0.0f, false, "esp-box-emu"); - - WindowState windowState; - memset(&windowState, 0, sizeof(windowState)); - windowState.width = DF_WIDTH; - windowState.height = DF_HEIGHT; - windowState.baseWindowWidth = DF_WIDTH; - windowState.baseWindowHeight = DF_HEIGHT; - windowState.monitorWidth = DF_WIDTH; - windowState.monitorHeight = DF_HEIGHT; - strcpy(windowState.name, "The Force Engine"); - TFE_RenderBackend::init(windowState); - TFE_Jedi::vfb_resetState(); - TFE_Jedi::vfb_setPlatformBuffer(s_frameBuffer); - - TFE_FrontEndUI::initConsole(); - progress("midi"); - TFE_MidiPlayer::init(sound->midiOutput, (MidiDeviceType)sound->midiType); - progress("audio"); - TFE_Audio::init(false, sound->audioDevice); - TFE_FrontEndUI::init(); - progress("game_init"); - game_init(); - - // Input: default keyboard binds (used for the SELECT combos) plus our controller binds. - inputMapping_resetToDefaults(); - for (size_t i = 0; i < sizeof(s_boxControllerBinds) / sizeof(s_boxControllerBinds[0]); i++) - { - inputMapping_addBinding(&s_boxControllerBinds[i]); - } - InputConfig* inputConfig = inputMapping_get(); - inputConfig->controllerFlags |= CFLAG_ENABLE; - inputConfig->mouseMode = MMODE_NONE; - - TFE_SaveSystem::init(); - - progress("runGame"); - s_curGame = createGame(Game_Dark_Forces); - TFE_SaveSystem::setCurrentGame(s_curGame); - if (!s_curGame) - { - TFE_System::logWrite(LOG_ERROR, "Main", "Cannot create game."); - s_quit = true; - } - else if (!s_curGame->runGame(1, s_argv, nullptr)) - { - TFE_System::logWrite(LOG_ERROR, "Main", "Cannot run game (is the game data in %s?).", s_gameDir.c_str()); - freeGame(s_curGame); - s_curGame = nullptr; - s_quit = true; - } - - s_initialized = true; - logMemory("after init"); - reset_frame_time(); -} - -void reset_darkforces() -{ - TFE_Memory::DfAllocScope allocScope; - deinit_darkforces(); - init_darkforces(s_gobPath, nullptr, 0); -} - -void run_darkforces_rom() -{ - TFE_Memory::DfAllocScope allocScope; - if (!s_initialized || !s_curGame || s_quit) - { - std::this_thread::sleep_for(std::chrono::milliseconds(10)); - return; - } - auto start = esp_timer_get_time(); - progress("frame"); -#if CONFIG_ESP_TASK_WDT_EN - esp_task_wdt_reset(); -#endif - - // Menus, cutscenes and the briefing are mouse driven; in-mission we use the pad directly. - const bool inMission = s_curGame->canSave(); - const bool menuMode = !inMission || s_curGame->isPaused(); - TFE_Input::enableRelativeMode(!menuMode); - updateInput(menuMode); - inputMapping_updateInput(); - - // Load requests (from the cart's load slot menu). - const char* loadRequest = TFE_SaveSystem::loadRequestFilename(); - if (loadRequest) - { - progress("load"); - fmt::print("[DarkForces] loading '{}'\n", loadRequest); - TFE_Jedi::ImStopAllSounds(); - if (!TFE_SaveSystem::loadGame(loadRequest)) - { - TFE_System::logWrite(LOG_ERROR, "Main", "Cannot load '%s'.", loadRequest); - } - // Leaving the previous level blanked the palette, and the save restores the - // "palette modified" flag as it was at save time; force it to be re-applied. - TFE_DarkForces::s_palModified = JTRUE; - releaseAll(); - } - - TFE_System::update(); - if (TFE_System::systemUiRequestPosted()) - { - TFE_FrontEndUI::enableConfigMenu(); - } - - TFE_SaveSystem::update(); - progress("loopGame"); - s_curGame->loopGame(); - progress("task_run"); - const bool endInputFrame = TFE_Jedi::task_run() != 0; - progress("swap"); - - // Push the frame to the display. - TFE_RenderBackend::swap(true); - - if (endInputFrame) - { - TFE_Input::endFrame(); - inputMapping_endFrame(); - } - - if (TFE_System::quitMessagePosted()) - { - s_quit = true; - } - - const int64_t frameTime = esp_timer_get_time() - start; - update_frame_time(frameTime); - { - static int64_t accum = 0, maxFrame = 0, lastReport = 0; - static int frames = 0; - accum += frameTime; frames++; - if (frameTime > maxFrame) { maxFrame = frameTime; } - if (esp_timer_get_time() - lastReport > 5000000) - { - if (lastReport) - { - size_t poolB = 0, heapB = 0, gameB = 0, levelB = 0; - TFE_Memory::getRegionStats(&poolB, &heapB, &gameB, &levelB); - size_t blockUsed = 0, blockPeak = 0, blockOverflow = 0; - TFE_Memory::getPoolStats(&blockUsed, &blockPeak, &blockOverflow); - fmt::print("[DarkForces] {:.1f} fps (avg {:.1f} ms, max {:.1f} ms), free internal {} B, PSRAM {} B | 4MB block used {} KB peak {} KB overflow {} KB | regions game {} KB level {} KB\n", - frames * 1000000.0 / double(esp_timer_get_time() - lastReport), accum / 1000.0 / frames, maxFrame / 1000.0, - heap_caps_get_free_size(MALLOC_CAP_INTERNAL), heap_caps_get_free_size(MALLOC_CAP_SPIRAM), - blockUsed / 1024, blockPeak / 1024, blockOverflow / 1024, gameB / 1024, levelB / 1024); - } - lastReport = esp_timer_get_time(); accum = 0; frames = 0; maxFrame = 0; - } - } - // Cap the frame rate (the LCD tops out around 50 fps anyway) and always block - // for at least one tick so that lower priority tasks (touch/gamepad polling, - // LVGL, the emulator menu) get CPU time; game logic runs on real time ticks, - // so this does not change the game speed. - { - using namespace std::chrono; - static constexpr auto framePeriod = microseconds(20000); - static auto nextFrame = steady_clock::now(); - auto now = steady_clock::now(); - if (nextFrame < now - 2 * framePeriod) { nextFrame = now; } - nextFrame += framePeriod; - if (nextFrame > now + milliseconds(1)) - { - std::this_thread::sleep_until(nextFrame); - } - else - { - vTaskDelay(1); - } - } -} - -bool darkforces_quit_requested() -{ - return s_quit; -} - -void pause_darkforces_tasks() -{ - TFE_Memory::DfAllocScope allocScope; - if (!s_initialized || s_paused) { return; } - s_paused = true; - s_hangDetectorEnabled = false; -#if CONFIG_HEAP_TRACING_STANDALONE - { - size_t poolB = 0, heapB = 0, gameB = 0, levelB = 0; - TFE_Memory::getRegionStats(&poolB, &heapB, &gameB, &levelB); - fmt::print("[DarkForces] ---- live heap allocations at pause (regions game {} KB level {} KB, pool {} KB, heap {} KB) ----\n", gameB / 1024, levelB / 1024, poolB / 1024, heapB / 1024); - TFE_Memory::printRegionCallers(); - // Throttled dump: heap_trace_dump() holds the heap lock for the whole print and trips the interrupt watchdog. - const size_t count = heap_trace_get_count(); - for (size_t i = 0; i < count; i++) - { - heap_trace_record_t rec; - if (heap_trace_get(i, &rec) != ESP_OK) { continue; } - printf(" %u bytes (@ %p) caller", (unsigned)rec.size, rec.address); - for (int d = 0; d < CONFIG_HEAP_TRACING_STACK_DEPTH; d++) { printf("%s0x%08x", d ? ":" : " ", (unsigned)(uintptr_t)rec.alloced_by[d]); } - printf("\n"); - if ((i % 32) == 31) { vTaskDelay(1); } - } - fmt::print("[DarkForces] ---- end live heap allocations ({} records) ----\n", count); - } -#endif -#if CONFIG_ESP_TASK_WDT_EN - esp_task_wdt_delete(NULL); -#endif - TFE_MidiPlayer::pause(); - TFE_Audio::pause(); - if (s_curGame && s_curGame->canSave()) - { - s_curGame->pauseGame(true); - } -} - -void resume_darkforces_tasks() -{ - TFE_Memory::DfAllocScope allocScope; - if (!s_initialized || !s_paused) { return; } - s_paused = false; - progress("resume"); - s_hangDetectorEnabled = true; -#if CONFIG_ESP_TASK_WDT_EN - esp_task_wdt_add(NULL); -#endif - if (s_curGame && s_curGame->canSave()) - { - s_curGame->pauseGame(false); - } - TFE_MidiPlayer::resume(); - TFE_Audio::resume(); - // The emulator menu overwrote the frame buffer and the display palette; force a redraw. - BoxEmu::get().palette(TFE_RenderBackend::getDisplayPalette(), 256); - releaseAll(); -} - -// Saves use the emulator's slot files (an absolute path from the cart); the -// save system accepts absolute paths on this platform. -void load_darkforces(std::string_view save_path, int save_slot) -{ - TFE_Memory::DfAllocScope allocScope; - if (!s_initialized || !s_curGame || save_slot < 0 || save_path.empty()) { return; } - // The load is processed on the next run_darkforces_rom() call (after the emulator menu closes). - std::string path(save_path); - TFE_SaveSystem::postLoadRequest(path.c_str()); -} - -void save_darkforces(std::string_view save_path, int save_slot) -{ - TFE_Memory::DfAllocScope allocScope; - if (!s_initialized || !s_curGame || save_slot < 0 || save_path.empty()) { return; } - if (!s_curGame->canSave()) - { - fmt::print("[DarkForces] cannot save outside of a mission\n"); - return; - } - // Save right away (while the emulator menu is open) so the slot shows up as - // used immediately. The game is paused by the menu; unpause around the save - // so the paused flag isn't captured in the save file. - std::string path(save_path); - auto description = fmt::format("Box Slot {}", save_slot); - const bool wasPaused = s_paused; - if (wasPaused) { s_curGame->pauseGame(false); } - progress("save"); - const bool ok = TFE_SaveSystem::saveGame(path.c_str(), description.c_str()); - if (wasPaused) { s_curGame->pauseGame(true); } - fmt::print("[DarkForces] save '{}' {}\n", path, ok ? "ok" : "FAILED"); -} - -std::span get_darkforces_video_buffer() -{ - // Convert the 8-bit frame to RGB565 (for screenshots) into frame buffer 1. - uint8_t* dst = BoxEmu::get().frame_buffer1(); - const size_t num_pixels = DF_WIDTH * DF_HEIGHT; - std::span frame(dst, num_pixels * sizeof(uint16_t)); - const uint16_t* palette = TFE_RenderBackend::getDisplayPalette(); - const uint8_t* src = s_frameBuffer; - if (palette && src) - { - for (size_t i = 0; i < num_pixels; i++) - { - uint16_t color = palette[src[i]]; - dst[i * 2] = color & 0xFF; - dst[i * 2 + 1] = (color >> 8) & 0xFF; - } - } - return frame; -} - -void deinit_darkforces() -{ - TFE_Memory::DfAllocScope allocScope; - if (!s_initialized) { return; } - s_initialized = false; - stopHangDetector(); -#if CONFIG_ESP_TASK_WDT_EN - esp_task_wdt_delete(NULL); -#endif - - releaseAll(); - if (s_curGame) - { - freeGame(s_curGame); - s_curGame = nullptr; - } - game_destroy(); - inputMapping_shutdown(); - // Close and delete the cached GOB/LFD archives (each open file also holds a - // 16KB stdio buffer) and drop the loaders' scratch buffers. - Archive::freeAllArchives(); - espbox_free_rtexture_scratch(); - espbox_free_sprite_scratch(); - espbox_free_level_scratch(); - espbox_free_vue_scratch(); - espbox_free_inf_scratch(); - espbox_free_model_scratch(); - - TFE_FrontEndUI::shutdown(); - TFE_Audio::shutdown(); - TFE_MidiPlayer::destroy(); - TFE_Settings::shutdown(); - TFE_RenderBackend::destroy(); - TFE_SaveSystem::destroy(); - TFE_Jedi::vfb_resetState(); - TFE_System::logClose(); - - BoxEmu::get().audio_sample_rate(48000); - // Release cached container storage so nothing is left in the 4MB block. - espbox_release_settings_caches(); - espbox_release_model_caches(); - espbox_release_sprite_caches(); - espbox_release_midiPlayer_caches(); - espbox_release_renderer_caches(); - espbox_release_robj3d_caches(); - espbox_release_robj3dCulling_caches(); - espbox_release_rtexture_caches(); - espbox_release_paths_caches(); - TFE_Jedi::rcf_setStatePtr(nullptr); - TFE_Memory::lockedPoolFree(s_rcfStateMem); - s_rcfStateMem = nullptr; - darkforces_free_shared_memory(); - TFE_Memory::poolEnd(); - logMemory("after deinit"); -} diff --git a/components/darkforces/src/darkforces_shared_memory.cpp b/components/darkforces/src/darkforces_shared_memory.cpp deleted file mode 100644 index 0430e6a6..00000000 --- a/components/darkforces/src/darkforces_shared_memory.cpp +++ /dev/null @@ -1,67 +0,0 @@ -// Engine buffers for the Dark Forces port. -// -// The largest statics of The Force Engine (and of the ESP32 platform layer) are -// pointers into BoxEmu's 4MB ROM block rather than fixed arrays, so they only -// take up RAM while Dark Forces is running. Each owning file provides an -// espbox_shared_*(bool alloc) hook; see tfe/TFE_System/espboxShared.h. -#include "esp_platform.h" - -#include - -void espbox_shared_streams(bool alloc); -void espbox_shared_parser(bool alloc); -void espbox_shared_fm4(bool alloc); -void espbox_shared_midiPlayer(bool alloc); -void espbox_shared_lmusic(bool alloc); -void espbox_shared_weapon(bool alloc); -void espbox_shared_vfb(bool alloc); -void espbox_shared_settings(bool alloc); -void espbox_shared_saveSystem(bool alloc); -void espbox_shared_rwallFixed(bool alloc); -void espbox_shared_mission(bool alloc); -void espbox_shared_escapeMenu(bool alloc); -void espbox_shared_audio(bool alloc); -void espbox_shared_render(bool alloc); -void espbox_shared_regionStats(bool alloc); - -static void (*const s_hooks[])(bool) = -{ - espbox_shared_streams, - espbox_shared_parser, - espbox_shared_fm4, - espbox_shared_midiPlayer, - espbox_shared_lmusic, - espbox_shared_weapon, - espbox_shared_vfb, - espbox_shared_settings, - espbox_shared_saveSystem, - espbox_shared_rwallFixed, - espbox_shared_mission, - espbox_shared_escapeMenu, - espbox_shared_audio, - espbox_shared_render, - espbox_shared_regionStats, -}; - -bool g_espboxSharedAllocFailed = false; - -bool darkforces_init_shared_memory() -{ - g_espboxSharedAllocFailed = false; - size_t before = 0, after = 0, peak = 0, overflow = 0; - TFE_Memory::getPoolStats(&before, &peak, &overflow); - for (auto hook : s_hooks) { hook(true); } - TFE_Memory::getPoolStats(&after, &peak, &overflow); - printf("[DarkForces] engine buffers: %u bytes\n", (unsigned)(after - before)); - if (g_espboxSharedAllocFailed) - { - printf("[DarkForces] ERROR: not enough room in the 4MB ROM block for the engine buffers\n"); - return false; - } - return true; -} - -void darkforces_free_shared_memory() -{ - for (auto hook : s_hooks) { hook(false); } -} diff --git a/components/darkforces/src/platform/esp_alloc.cpp b/components/darkforces/src/platform/esp_alloc.cpp deleted file mode 100644 index ec58fae9..00000000 --- a/components/darkforces/src/platform/esp_alloc.cpp +++ /dev/null @@ -1,451 +0,0 @@ -// Dark Forces memory: everything the engine allocates lives in BoxEmu's 4MB ROM block. -// -// Dark Forces loads its data from the SD card, so the ROM block that the other -// cores use for ROM images is free while it runs. The block is managed by the -// pool allocator and holds: -// - the engine's memory regions (esp_memory.cpp), -// - its large static buffers (see TFE_System/espboxShared.h), -// - and every malloc/calloc/realloc/strdup/new made by Dark Forces code: after -// libdarkforces.a is built, those symbols are renamed to the df_* functions -// below (see CMakeLists.txt and alloc_redirect.syms). -// -// Rules that keep this safe: -// - The block is only used while a DfAllocScope is active on the calling task -// (the game entry points in darkforces.cpp and the engine's own threads). -// Template code shared with other components can end up calling df_*, and -// those calls must not put memory into the block. -// - free() and realloc() are wrapped for the whole firmware (--wrap), so a -// block pointer is handled here no matter which code releases it. -// - Each df_* allocation carries a header with a per-session magic value; -// frees of stale pointers (from an earlier session, after the block was -// handed back to the other cores) are ignored. -// - Nothing may outlive a session in the block. darkforces_pool_end() lists -// any allocation that is still live so it can be released at shutdown. -#include "esp_platform.h" -#include "pool_allocator.h" - -#include -#include -#include - -#include -#include -#include -#include - -extern "C" void __real_free(void* ptr); -extern "C" void* __real_realloc(void* ptr, size_t size); - -namespace -{ - struct AllocHeader - { - uint32_t magic; - uint32_t size; // requested size - uint32_t caller; // return address of the allocating call - uint32_t offset; // distance from the pool block to the user pointer - }; - constexpr uint32_t HEADER_MAGIC = 0xDFA11C00; - - SemaphoreHandle_t s_lock = nullptr; - uint8_t* s_base = nullptr; // the block stays known after the session ends (stale frees) - size_t s_size = 0; - bool s_active = false; - uint32_t s_generation = 0; - - size_t s_used = 0; // bytes allocated in the block - size_t s_peak = 0; - size_t s_overflowCount = 0; // allocations that did not fit and went to the PSRAM heap - size_t s_overflowBytes = 0; - size_t s_staleFrees = 0; - - thread_local int t_scope = 0; - - inline uint32_t sessionMagic() { return HEADER_MAGIC ^ s_generation; } - - // The block start itself is excluded: no allocation starts there, and BoxEmu frees - // the whole block with free(romdata). - inline bool inBlock(const void* ptr) - { - return s_base && (const uint8_t*)ptr > s_base && (const uint8_t*)ptr < s_base + s_size; - } - - void* poolAllocLocked(size_t size) - { - if (!s_active) { return nullptr; } - void* mem = pool_alloc(size); - if (mem) - { - s_used += pool_block_size(mem); - if (s_used > s_peak) { s_peak = s_used; } - } - return mem; - } - - void poolFreeLocked(void* mem) - { - s_used -= pool_block_size(mem); - pool_free(mem); - } - - void noteOverflow(size_t size) - { - if (!s_overflowCount) - { - printf("[DarkForces] WARNING: the 4MB ROM block is full (%u KB used); allocating %u B from the PSRAM heap\n", - (unsigned)(s_used / 1024), (unsigned)size); - } - s_overflowCount++; - s_overflowBytes += size; - } - - // Returns the header of a live allocation from this session, or null. - AllocHeader* liveHeader(void* ptr) - { - if (!s_active) { return nullptr; } - AllocHeader* header = ((AllocHeader*)ptr) - 1; - if (reinterpret_cast(header) < s_base || header->magic != sessionMagic()) { return nullptr; } - return header; - } - - void* dfAlloc(size_t size, uintptr_t caller) - { - if (t_scope > 0 && s_active) - { - TFE_Memory::PoolLock lock; - // Keep malloc's 8 byte alignment in front of the header. - const size_t total = size + sizeof(AllocHeader) + 8; - const void* mem = poolAllocLocked(total); - if (mem) - { - uintptr_t user = ((uintptr_t)mem + sizeof(AllocHeader) + 7) & ~(uintptr_t)7; - AllocHeader* header = ((AllocHeader*)user) - 1; - header->magic = sessionMagic(); - header->size = (uint32_t)size; - header->caller = (uint32_t)caller; - header->offset = (uint32_t)(user - (uintptr_t)mem); - return (void*)user; - } - noteOverflow(size); - } - return heap_caps_malloc(size ? size : 1, MALLOC_CAP_DEFAULT); - } - - void dfFree(void* ptr) - { - if (!ptr) { return; } - if (!inBlock(ptr)) - { - __real_free(ptr); - return; - } - TFE_Memory::PoolLock lock; - AllocHeader* header = liveHeader(ptr); - if (!header) - { - s_staleFrees++; - return; - } - header->magic = 0; - poolFreeLocked((uint8_t*)ptr - header->offset); - } - - void* dfRealloc(void* ptr, size_t size, uintptr_t caller) - { - if (!ptr) { return dfAlloc(size, caller); } - if (size == 0) - { - dfFree(ptr); - return nullptr; - } - if (!inBlock(ptr)) { return __real_realloc(ptr, size); } - - size_t oldSize = 0; - { - TFE_Memory::PoolLock lock; - const AllocHeader* header = liveHeader(ptr); - if (!header) - { - printf("[DarkForces] ERROR: realloc of a stale block pointer %p\n", ptr); - s_staleFrees++; - return dfAlloc(size, caller); - } - oldSize = header->size; - } - if (size <= oldSize) { return ptr; } - void* mem = dfAlloc(size, caller); - if (!mem) { return nullptr; } - memcpy(mem, ptr, oldSize); - dfFree(ptr); - return mem; - } - - struct CensusState - { - size_t liveCount; - size_t liveBytes; - size_t rawCount; - size_t rawBytes; - size_t printed; - }; - - // censusVisit matches the pool walker's callback signature; mem can't take const. - // cppcheck-suppress constParameterCallback - void censusVisit(void* mem, size_t size, int used, void* user) - { - if (!used) { return; } - CensusState* state = (CensusState*)user; - uintptr_t userPtr = ((uintptr_t)mem + sizeof(AllocHeader) + 7) & ~(uintptr_t)7; - const AllocHeader* header = ((AllocHeader*)userPtr) - 1; - if (size >= sizeof(AllocHeader) + 8 && header->magic == sessionMagic()) - { - state->liveCount++; - state->liveBytes += header->size; - if (state->printed++ < 32) - { - printf("[DarkForces] still allocated: %u B from 0x%08x\n", (unsigned)header->size, (unsigned)header->caller); - } - } - else - { - state->rawCount++; - state->rawBytes += size; - if (state->printed++ < 32) - { - // Region allocations start with a MemoryBlock header (see esp_memory.cpp): - // prev, next, size, caller, owner. - const uint32_t* words = (const uint32_t*)mem; - const bool regionBlock = size >= 20 && words[2] + 20 <= size && words[2] + 20 + 16 > size && - words[3] >= 0x42000000 && words[3] < 0x44000000; - if (regionBlock) - { - printf("[DarkForces] still allocated: region block of %u B from 0x%08x\n", (unsigned)words[2], (unsigned)words[3]); - } - else if (size >= 16) - { - printf("[DarkForces] still allocated: raw block of %u B at %p (%08x %08x %08x %08x)\n", (unsigned)size, mem, - (unsigned)words[0], (unsigned)words[1], (unsigned)words[2], (unsigned)words[3]); - } - else - { - printf("[DarkForces] still allocated: raw block of %u B at %p\n", (unsigned)size, mem); - } - } - } - } -} - -namespace TFE_Memory -{ - PoolLock::PoolLock() - { - if (!s_lock) { s_lock = xSemaphoreCreateRecursiveMutex(); } - xSemaphoreTakeRecursive(s_lock, portMAX_DELAY); - } - - PoolLock::~PoolLock() - { - xSemaphoreGiveRecursive(s_lock); - } - - DfAllocScope::DfAllocScope() { t_scope++; } - DfAllocScope::~DfAllocScope() { t_scope--; } - - DfHeapScope::DfHeapScope() : m_saved(t_scope) { t_scope = 0; } - DfHeapScope::~DfHeapScope() { t_scope = m_saved; } - - void* lockedPoolAlloc(size_t size) - { - PoolLock lock; - return poolAllocLocked(size); - } - - void lockedPoolFree(void* ptr) - { - PoolLock lock; - if (s_active && ptr && pool_contains(ptr)) { poolFreeLocked(ptr); } - } - - void noteRegionOverflow(size_t size) - { - PoolLock lock; - noteOverflow(size); - } - - bool poolBegin(uint8_t* base, size_t size) - { - PoolLock lock; - if (!base || size < 1024) { return false; } - pool_create(base, size); - printf("[DarkForces] 4MB block: %p - %p\n", (void*)base, (void*)(base + size)); - s_base = base; - s_size = size; - s_active = true; - s_generation++; - s_used = 0; - s_peak = 0; - s_overflowCount = 0; - s_overflowBytes = 0; - s_staleFrees = 0; - return true; - } - - void poolEnd() - { - PoolLock lock; - if (!s_active) { return; } - CensusState state = {}; - pool_walk(censusVisit, &state); - printf("[DarkForces] 4MB block at exit: peak %u KB, %u allocations (%u KB) and %u raw blocks (%u KB) still live, %u overflow allocations (%u KB), %u stale frees\n", - (unsigned)(s_peak / 1024), (unsigned)state.liveCount, (unsigned)(state.liveBytes / 1024), - (unsigned)state.rawCount, (unsigned)(state.rawBytes / 1024), - (unsigned)s_overflowCount, (unsigned)(s_overflowBytes / 1024), (unsigned)s_staleFrees); - s_active = false; - pool_destroy(); - } - - namespace - { - struct PoolSummary { size_t used, usedBlocks, free, freeBlocks, largestFree; }; - void poolSummaryVisit(void*, size_t size, int used, void* user) - { - PoolSummary* s = (PoolSummary*)user; - if (used) { s->used += size; s->usedBlocks++; } - else { s->free += size; s->freeBlocks++; if (size > s->largestFree) { s->largestFree = size; } } - } - } - - void printPoolSummary() - { - PoolLock lock; - if (!s_active) { return; } - PoolSummary s = {}; - pool_walk(poolSummaryVisit, &s); - printf("[DarkForces] 4MB block: %u KB used in %u blocks, %u KB free in %u blocks (largest %u KB); PSRAM heap free %u KB (largest %u KB)\n", - (unsigned)(s.used / 1024), (unsigned)s.usedBlocks, (unsigned)(s.free / 1024), (unsigned)s.freeBlocks, (unsigned)(s.largestFree / 1024), - (unsigned)(heap_caps_get_free_size(MALLOC_CAP_SPIRAM) / 1024), (unsigned)(heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM) / 1024)); - } - - void getPoolStats(size_t* used, size_t* peak, size_t* overflowBytes) - { - PoolLock lock; - *used = s_used; - *peak = s_peak; - *overflowBytes = s_overflowBytes; - } -} - -// Engine buffers (espboxShared.h): zeroed, block only. -extern "C" void* espbox_pool_calloc(size_t size) -{ - void* mem = TFE_Memory::lockedPoolAlloc(size); - if (mem) { memset(mem, 0, size); } - return mem; -} - -extern "C" void espbox_pool_free(void* ptr) -{ - TFE_Memory::lockedPoolFree(ptr); -} - -// Replacements for the allocation functions referenced by libdarkforces.a. -extern "C" -{ - __attribute__((noinline)) void* df_malloc(size_t size) - { - return dfAlloc(size, (uintptr_t)__builtin_return_address(0)); - } - - __attribute__((noinline)) void* df_calloc(size_t count, size_t size) - { - if (size && count > SIZE_MAX / size) { return nullptr; } - void* mem = dfAlloc(count * size, (uintptr_t)__builtin_return_address(0)); - if (mem) { memset(mem, 0, count * size); } - return mem; - } - - __attribute__((noinline)) void* df_realloc(void* ptr, size_t size) - { - return dfRealloc(ptr, size, (uintptr_t)__builtin_return_address(0)); - } - - void df_free(void* ptr) - { - dfFree(ptr); - } - - __attribute__((noinline)) char* df_strdup(const char* str) - { - const size_t size = strlen(str) + 1; - char* mem = (char*)dfAlloc(size, (uintptr_t)__builtin_return_address(0)); - if (mem) { memcpy(mem, str, size); } - return mem; - } - - // operator new / new[] (exceptions are disabled: abort like the default operator new). - __attribute__((noinline)) void* df_new(size_t size) - { - void* mem = dfAlloc(size, (uintptr_t)__builtin_return_address(0)); - if (!mem) - { - printf("[DarkForces] out of memory in operator new (%u B)\n", (unsigned)size); - abort(); - } - return mem; - } - - __attribute__((noinline)) void* df_new_nothrow(size_t size, void* /*nothrow*/) - { - return dfAlloc(size, (uintptr_t)__builtin_return_address(0)); - } - - void df_delete(void* ptr) - { - dfFree(ptr); - } - - void df_delete_sized(void* ptr, size_t /*size*/) - { - dfFree(ptr); - } - - // Array forms (objcopy needs a distinct target symbol for each renamed symbol). - __attribute__((noinline)) void* df_new_array(size_t size) - { - void* mem = dfAlloc(size, (uintptr_t)__builtin_return_address(0)); - if (!mem) - { - printf("[DarkForces] out of memory in operator new[] (%u B)\n", (unsigned)size); - abort(); - } - return mem; - } - - __attribute__((noinline)) void* df_new_array_nothrow(size_t size, void* /*nothrow*/) - { - return dfAlloc(size, (uintptr_t)__builtin_return_address(0)); - } - - void df_delete_array(void* ptr) - { - dfFree(ptr); - } - - void df_delete_array_sized(void* ptr, size_t /*size*/) - { - dfFree(ptr); - } - - // Firmware-wide wrappers (-Wl,--wrap=free,--wrap=realloc): route block pointers here. - void __wrap_free(void* ptr) - { - if (inBlock(ptr)) { dfFree(ptr); } - else { __real_free(ptr); } - } - - void* __wrap_realloc(void* ptr, size_t size) - { - if (inBlock(ptr)) { return dfRealloc(ptr, size, (uintptr_t)__builtin_return_address(0)); } - return __real_realloc(ptr, size); - } -} diff --git a/components/darkforces/src/platform/esp_audio.cpp b/components/darkforces/src/platform/esp_audio.cpp deleted file mode 100644 index fe97e588..00000000 --- a/components/darkforces/src/platform/esp_audio.cpp +++ /dev/null @@ -1,298 +0,0 @@ -// ESP32 (esp-box-emu) audio system for The Force Engine. -// -// Dark Forces mixes all of its sound effects through the iMuse digital sound -// system, which registers itself with setAudioThreadCallback() and fills 8-bit -// stereo frames at 11025 Hz (the same code path the Amiga port uses). Music is -// rendered by the OPL3 MIDI synthesizer through TFE_MidiPlayer::synthesizeMidi(). -// -// A dedicated FreeRTOS task (core 1) mixes the two into 16-bit stereo chunks and -// pushes them to the BoxEmu I2S output at a fixed cadence. -#include -#include -#include -#include -#include // IM_AUDIO_OVERSAMPLE - -#include "box-emu.hpp" -#include "task.hpp" -#include -#include "esp_platform.h" - -#include -#include -#include -#include - -#include -#include -#include -#include - -static_assert(IM_AUDIO_OVERSAMPLE == 0, "The ESP32 audio path expects the non-oversampled 8-bit iMuse output."); - -struct SoundSource -{ - int dummy; -}; - -namespace TFE_Audio -{ - enum - { - AUDIO_FREQ = 11025, - AUDIO_CHANNEL_COUNT = 2, - // Stereo frames per mix chunk (limited by the iMuse internal buffer of 512 samples). - AUDIO_CALLBACK_BUFFER_SIZE = 256, - BUFFERED_SILENT_FRAME_COUNT = 8, - AUDIO_BUFFER_SIZE = (AUDIO_CALLBACK_BUFFER_SIZE * AUDIO_CHANNEL_COUNT), - }; - - static f32 s_soundFxVolume = 1.0f; - static s32 s_soundFxScale = 192; // 8.8 fixed point (8-bit sfx -> 16-bit) - static s32 s_prefillChunks = 0; // chunks of silence to push ahead after (re)start - static bool s_paused = false; - static bool s_nullDevice = false; - static volatile s32 s_silentAudioFrames = 0; - static SemaphoreHandle_t s_lock = nullptr; - - // AUDIO_BUFFER_SIZE samples each (shared memory, see espbox_shared_audio()). - static s8* s_sfxBuffer = nullptr; - static s16* s_midiBuffer = nullptr; - static s16* s_mixBuffer = nullptr; - static constexpr size_t SFX_BYTES = AUDIO_BUFFER_SIZE * sizeof(s8); - static constexpr size_t PCM_BYTES = AUDIO_BUFFER_SIZE * sizeof(s16); - - static AudioThreadCallback s_audioThreadCallback = nullptr; - static std::unique_ptr s_task; - - // audioTask matches espp::Task's callback signature; its params can't take const. - // cppcheck-suppress constParameterCallback - static bool audioTask(std::mutex& m, std::condition_variable& cv, bool& task_notified) - { - TFE_Memory::DfAllocScope allocScope; - using namespace std::chrono; - static constexpr auto chunkPeriod = microseconds((1000000LL * AUDIO_CALLBACK_BUFFER_SIZE) / AUDIO_FREQ); - static auto nextChunk = steady_clock::now(); - - auto now = steady_clock::now(); - if (nextChunk < now - 4 * chunkPeriod) - { - // We fell far behind (e.g. a long load); don't try to catch up, but - // re-prime the output so the consumer has some slack again. - nextChunk = now; - s_prefillChunks = 2; - } - if (s_prefillChunks > 0) - { - // The box's audio task pulls a fixed slice every 1/60s and zero-fills - // whatever isn't queued yet, so stay a couple of chunks ahead of it. - memset(s_mixBuffer, 0, PCM_BYTES); - for (; s_prefillChunks > 0; s_prefillChunks--) - { - BoxEmu::get().play_audio(reinterpret_cast(s_mixBuffer), PCM_BYTES); - } - } - - bool haveSfx = false; - bool haveMidi = false; - if (!s_paused) - { - if (s_audioThreadCallback) - { - lock(); - s_audioThreadCallback(reinterpret_cast(s_sfxBuffer), AUDIO_CALLBACK_BUFFER_SIZE, 1.0f); - unlock(); - haveSfx = true; - } - memset(s_midiBuffer, 0, PCM_BYTES); - const int64_t synthStart = esp_timer_get_time(); - TFE_MidiPlayer::synthesizeMidi(s_midiBuffer, AUDIO_CALLBACK_BUFFER_SIZE, true); - const int64_t synthUs = esp_timer_get_time() - synthStart; - haveMidi = true; - - // Report how the music synthesis keeps up (every ~5 seconds of audio). - static int64_t s_synthTotalUs = 0, s_synthMaxUs = 0; - static s32 s_synthChunks = 0; - s_synthTotalUs += synthUs; - if (synthUs > s_synthMaxUs) { s_synthMaxUs = synthUs; } - if (++s_synthChunks >= 216) - { - printf("[DarkForces] audio: music synthesis avg %d us, max %d us per %d us chunk\n", - (int)(s_synthTotalUs / s_synthChunks), (int)s_synthMaxUs, (int)chunkPeriod.count()); - s_synthTotalUs = 0; s_synthMaxUs = 0; s_synthChunks = 0; - } - } - - if (s_silentAudioFrames > 0) - { - s_silentAudioFrames--; - haveSfx = false; - haveMidi = false; - } - - if (!haveSfx && !haveMidi) - { - memset(s_mixBuffer, 0, PCM_BYTES); - } - else - { - const s32 sfxScale = haveSfx ? s_soundFxScale : 0; - for (s32 i = 0; i < AUDIO_BUFFER_SIZE; i++) - { - // 8-bit sfx -> 16-bit with volume, plus the 16-bit music. - s32 sample = (s32(s_sfxBuffer[i]) * sfxScale) + (haveMidi ? s32(s_midiBuffer[i]) : 0); - if (sample > 32767) { sample = 32767; } - else if (sample < -32768) { sample = -32768; } - s_mixBuffer[i] = s16(sample); - } - } - - BoxEmu::get().play_audio(reinterpret_cast(s_mixBuffer), PCM_BYTES); - - nextChunk += chunkPeriod; - if (nextChunk > steady_clock::now()) - { - std::this_thread::sleep_until(nextChunk); - } - else - { - // Behind schedule: still block for a tick so lower priority tasks on this - // core (and its idle task) are never starved. - vTaskDelay(1); - } - return false; - } - - bool init(bool useNullDevice/*=false*/, s32 outputId/*=-1*/) - { - TFE_System::logWrite(LOG_MSG, "Startup", "TFE_AudioSystem::init"); - s_nullDevice = useNullDevice; - s_paused = false; - s_silentAudioFrames = 0; - s_audioThreadCallback = nullptr; - - TFE_Settings_Sound* soundSettings = TFE_Settings::getSoundSettings(); - setVolume(soundSettings->soundFxVolume); - - if (!s_lock) - { - s_lock = xSemaphoreCreateRecursiveMutex(); - } - - memset(s_sfxBuffer, 0, SFX_BYTES); - memset(s_midiBuffer, 0, PCM_BYTES); - memset(s_mixBuffer, 0, PCM_BYTES); - - if (s_nullDevice) - { - return false; - } - - BoxEmu::get().audio_sample_rate(AUDIO_FREQ); - s_prefillChunks = 2; - - s_task.reset(); - s_task = espp::Task::make_unique(espp::Task::Config{ - .callback = audioTask, - .task_config = { - .name = "df_audio", - .stack_size_bytes = 6 * 1024, - .priority = 10, - .core_id = 1, - } - }); - s_task->start(); - TFE_System::logWrite(LOG_MSG, "Audio", "Audio initialized at %d Hz, %d frames per chunk.", AUDIO_FREQ, AUDIO_CALLBACK_BUFFER_SIZE); - return true; - } - - void shutdown() - { - TFE_System::logWrite(LOG_MSG, "Audio", "Shutdown"); - s_task.reset(); - s_audioThreadCallback = nullptr; - } - - void stopAllSounds() {} - void selectDevice(s32 id) {} - void setUpsampleFilter(AudioUpsampleFilter filter) {} - AudioUpsampleFilter getUpsampleFilter() { return AUF_DEFAULT; } - - void setVolume(f32 volume) - { - if (volume < 0.0f) { volume = 0.0f; } - if (volume > 1.0f) { volume = 1.0f; } - s_soundFxVolume = volume; - s_soundFxScale = s32(volume * 192.0f); - } - - f32 getVolume() - { - return s_soundFxVolume; - } - - void pause() - { - s_paused = true; - } - - void resume() - { - s_paused = false; - } - - // Really the buffered audio will continue to process so time advances properly. - // But for 'BUFFERED_SILENT_FRAME_COUNT' audio will be silent. - // This allows the buffered data to be consumed without audio hitches. - void bufferedAudioClear() - { - s_silentAudioFrames = BUFFERED_SILENT_FRAME_COUNT; - } - - void setAudioThreadCallback(AudioThreadCallback callback) - { - lock(); - s_audioThreadCallback = callback; - unlock(); - } - - const OutputDeviceInfo* getOutputDeviceList(s32& count, s32& curOutput) - { - count = 0; - curOutput = 0; - return nullptr; - } - - void lock() - { - if (s_lock) { xSemaphoreTakeRecursive(s_lock, portMAX_DELAY); } - } - - void unlock() - { - if (s_lock) { xSemaphoreGiveRecursive(s_lock); } - } - - // Sound sources are not used by Dark Forces (everything goes through iMuse). These are - // stub implementations of the TFE_Audio API; the engine's declarations are non-const. - // cppcheck-suppress-begin constParameterPointer - bool playOneShot(SoundType type, f32 volume, const SoundBuffer* buffer, bool looping, SoundFinishedCallback finishedCallback, void* cbUserData, s32 cbArg) { return false; } - SoundSource* createSoundSource(SoundType type, f32 volume, const SoundBuffer* buffer, SoundFinishedCallback callback, void* userData) { return nullptr; } - s32 getSourceSlot(SoundSource* source) { return -1; } - SoundSource* getSourceFromSlot(s32 slot) { return nullptr; } - void playSource(SoundSource* source, bool looping) {} - void stopSource(SoundSource* source) {} - void freeSource(SoundSource* source) {} - void setSourceVolume(SoundSource* source, f32 volume) {} - void setSourceBuffer(SoundSource* source, const SoundBuffer* buffer) {} - bool isSourcePlaying(SoundSource* source) { return false; } - f32 getSourceVolume(SoundSource* source) { return 0.0f; } - // cppcheck-suppress-end constParameterPointer -} - -void espbox_shared_audio(bool alloc) -{ - ESPBOX_SHARED_ALLOC(TFE_Audio::s_sfxBuffer, TFE_Audio::AUDIO_BUFFER_SIZE); - ESPBOX_SHARED_ALLOC(TFE_Audio::s_midiBuffer, TFE_Audio::AUDIO_BUFFER_SIZE); - ESPBOX_SHARED_ALLOC(TFE_Audio::s_mixBuffer, TFE_Audio::AUDIO_BUFFER_SIZE); -} diff --git a/components/darkforces/src/platform/esp_memory.cpp b/components/darkforces/src/platform/esp_memory.cpp deleted file mode 100644 index 6d5c8715..00000000 --- a/components/darkforces/src/platform/esp_memory.cpp +++ /dev/null @@ -1,349 +0,0 @@ -// ESP32 (esp-box-emu) memory regions for The Force Engine. -// -// The desktop implementation reserves large fixed blocks (8MB per region) which -// does not fit the ESP32's PSRAM budget. This version simply tracks each -// allocation in an intrusive list so a region can still be cleared in one call; -// the memory itself comes from BoxEmu's 4MB ROM block (see esp_alloc.cpp). -#include -#include - -#include -#include "pool_allocator.h" -#include "esp_platform.h" -#include - -#include -#include - -#include -#include -#include - -struct MemoryBlock -{ - MemoryBlock* prev = nullptr; - MemoryBlock* next = nullptr; - u32 size = 0; - u32 caller = 0; // return address of the region_alloc() caller (memory attribution) - MemoryRegion* owner = nullptr; // region the block was allocated from (frees may name a different one) -}; - -struct MemoryRegion -{ - char name[32] = {}; - MemoryBlock* head = nullptr; - MemoryBlock* tail = nullptr; - u64 used = 0; - u64 count = 0; -}; - -namespace TFE_Memory -{ - // Regions are used from the game thread and from the iMuse/MIDI thread, and the - // underlying pool allocator is not thread safe: serialize all region operations - // (with the same lock as every other pool user). - typedef PoolLock RegionLock; - - // The 4MB ROM block is the region store; the PSRAM heap is only a fallback - // (reported as overflow) for when the block is full. - static size_t s_poolBytes = 0, s_heapBytes = 0; - - // Per-caller attribution of region memory (bytes currently allocated). - struct CallerStat { u32 pc = 0; size_t bytes = 0; size_t count = 0; }; - enum { CALLER_STAT_COUNT = 128 }; - static CallerStat* s_callers = nullptr; // CALLER_STAT_COUNT entries (shared memory) - static CallerStat* callerStat(u32 pc) - { - if (!s_callers) { return nullptr; } - for (s32 i = 0; i < CALLER_STAT_COUNT; i++) - { - CallerStat& c = s_callers[i]; - if (c.pc == pc) { return &c; } - if (c.pc == 0) { c.pc = pc; c.bytes = 0; c.count = 0; return &c; } - } - return nullptr; - } - static void callerAdd(u32 pc, size_t bytes) - { - CallerStat* c = callerStat(pc); - if (c) { c->bytes += bytes; c->count++; } - } - static void callerSub(u32 pc, size_t bytes) - { - CallerStat* c = callerStat(pc); - if (c && c->count) { c->bytes -= bytes; c->count--; } - } - static MemoryRegion* s_regions[2] = { nullptr, nullptr }; // first two regions created: game, level - - static void* regionMalloc(size_t size) - { - void* mem = lockedPoolAlloc(size); - if (mem) { s_poolBytes += size; return mem; } - noteRegionOverflow(size); - mem = heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); - if (mem) { s_heapBytes += size; } - return mem; - } - - static void regionFree(void* mem, size_t size) - { - if (pool_contains(mem)) { lockedPoolFree(mem); s_poolBytes -= size; } - else { heap_caps_free(mem); s_heapBytes -= size; } - } - - static MemoryBlock* newBlock(MemoryRegion* region, u32 size, u32 caller) - { - MemoryBlock* node = (MemoryBlock*)regionMalloc(sizeof(MemoryBlock) + size); - if (!node) { return nullptr; } - - node->size = size; - node->caller = caller; - node->owner = region; - callerAdd(caller, size); - node->next = nullptr; - node->prev = region->tail; - if (region->tail) { region->tail->next = node; } - else { region->head = node; } - region->tail = node; - region->used += size; - region->count++; - return node; - } - - static void freeBlock(MemoryRegion* region, MemoryBlock* node) - { - // The Landru (cutscene) code frees with whatever allocator is current, which - // is not always the region the block came from, and it keeps using some of - // those blocks afterwards (the desktop allocator ignores a free of a pointer - // that is not in the given region, so they stay valid there). Match that: - // leave the block alone; it is released when its own region is cleared or - // destroyed. (Unlinking it from the wrong list would corrupt both lists.) - if (node->owner && node->owner != region) - { - static s32 s_foreignFrees = 0; - if (s_foreignFrees < 8) - { - s_foreignFrees++; - printf("[DarkForces] region free ignored: %u B block from '%s' freed through '%s' (allocated at 0x%08x)\n", - (unsigned)node->size, node->owner->name, region ? region->name : "?", (unsigned)node->caller); - } - return; - } - if (node->prev) { node->prev->next = node->next; } - else { region->head = node->next; } - if (node->next) { node->next->prev = node->prev; } - else { region->tail = node->prev; } - region->used -= node->size; - region->count--; - callerSub(node->caller, node->size); - regionFree(node, sizeof(MemoryBlock) + node->size); - } - - static inline MemoryBlock* blockFromPtr(void* ptr) - { - return ((MemoryBlock*)ptr) - 1; - } - - static inline void* ptrFromBlock(MemoryBlock* node) - { - return (void*)(node + 1); - } - - MemoryRegion* region_create(const char* name, size_t blockSize, size_t maxSize) - { - RegionLock lock; - assert(name); - if (!name || !blockSize) { return nullptr; } - - MemoryRegion* region = (MemoryRegion*)malloc(sizeof(MemoryRegion)); - if (!region) - { - TFE_System::logWrite(LOG_ERROR, "MemoryRegion", "Failed to allocate region '%s'.", name); - return nullptr; - } - - strncpy(region->name, name, sizeof(region->name) - 1); - region->name[sizeof(region->name) - 1] = 0; - region->head = nullptr; - region->tail = nullptr; - region->used = 0; - region->count = 0; - if (!s_regions[0]) { s_regions[0] = region; } - else if (!s_regions[1]) { s_regions[1] = region; } - return region; - } - - void printRegionCallers() - { - RegionLock lock; - // Sort a copy by bytes and print the top entries; symbolize the pcs with addr2line. - if (!s_callers) { return; } - CallerStat* copy = (CallerStat*)heap_caps_malloc(sizeof(CallerStat) * CALLER_STAT_COUNT, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); - if (!copy) { return; } - memcpy(copy, s_callers, sizeof(CallerStat) * CALLER_STAT_COUNT); - for (int i = 0; i < 24; i++) - { - int best = -1; - for (int j = 0; j < CALLER_STAT_COUNT; j++) { if (copy[j].pc && copy[j].bytes && (best < 0 || copy[j].bytes > copy[best].bytes)) { best = j; } } - if (best < 0) { break; } - printf("[DarkForces] region caller 0x%08x: %u KB in %u blocks\n", (unsigned)copy[best].pc, (unsigned)(copy[best].bytes / 1024), (unsigned)copy[best].count); - copy[best].bytes = 0; - } - free(copy); - } - - void getRegionStats(size_t* poolBytes, size_t* heapBytes, size_t* gameBytes, size_t* levelBytes) - { - RegionLock lock; - *poolBytes = s_poolBytes; - *heapBytes = s_heapBytes; - *gameBytes = s_regions[0] ? (size_t)s_regions[0]->used : 0; - *levelBytes = s_regions[1] ? (size_t)s_regions[1]->used : 0; - } - - void region_clear(MemoryRegion* region) - { - RegionLock lock; - assert(region); - MemoryBlock* node = region->head; - while (node) - { - MemoryBlock* next = node->next; - callerSub(node->caller, node->size); - regionFree(node, sizeof(MemoryBlock) + node->size); - node = next; - } - region->head = nullptr; - region->tail = nullptr; - region->used = 0; - region->count = 0; - } - - void region_destroy(MemoryRegion* region) - { - RegionLock lock; - if (!region) { return; } - region_clear(region); - if (s_regions[0] == region) { s_regions[0] = nullptr; } - if (s_regions[1] == region) { s_regions[1] = nullptr; } - free(region); - } - - void* region_alloc(MemoryRegion* region, size_t size) - { - RegionLock lock; - assert(region); - if (!region || size == 0) { return nullptr; } - - MemoryBlock* node = newBlock(region, (u32)size, (u32)__builtin_return_address(0)); - if (node) - { - return ptrFromBlock(node); - } - - TFE_System::logWrite(LOG_ERROR, "MemoryRegion", "Failed to allocate %u bytes in region '%s' (used %u in %u blocks).", - (u32)size, region->name, (u32)region->used, (u32)region->count); - // Diagnostics: where the memory went (once; the game usually crashes right after). - static bool s_reported = false; - if (!s_reported) - { - s_reported = true; - printPoolSummary(); - printRegionCallers(); - } - return nullptr; - } - - void* region_realloc(MemoryRegion* region, void* ptr, size_t size) - { - RegionLock lock; - assert(region); - if (!ptr) { return region_alloc(region, size); } - if (size == 0) { return nullptr; } - - MemoryBlock* node = blockFromPtr(ptr); - const u32 prevSize = node->size; - if (prevSize >= size) - { - return ptr; - } - - // Grow within the region the block belongs to. - if (node->owner) { region = node->owner; } - MemoryBlock* newNode = newBlock(region, (u32)size, node->caller); - if (!newNode) { return nullptr; } - void* newMem = ptrFromBlock(newNode); - memcpy(newMem, ptr, prevSize); - freeBlock(region, node); - return newMem; - } - - void region_free(MemoryRegion* region, void* ptr) - { - RegionLock lock; - if (!ptr || !region) { return; } - freeBlock(region, blockFromPtr(ptr)); - } - - bool region_contains(MemoryRegion* region, const void* ptr) - { - RegionLock lock; - if (!region) { return false; } - for (MemoryBlock* node = region->head; node; node = node->next) - { - const u8* start = (const u8*)ptrFromBlock(node); - if ((const u8*)ptr >= start && (const u8*)ptr < start + node->size) { return true; } - } - return false; - } - - // The region_* functions implement the TFE_Memory API; the engine declares the - // MemoryRegion* / FileStream* parameters non-const, so they can't take const here. - // cppcheck-suppress-begin constParameterPointer - size_t region_getMemoryUsed(MemoryRegion* region) - { - return region ? region->used : 0; - } - - void region_getBlockInfo(MemoryRegion* region, size_t* blockCount, size_t* blockSize) - { - *blockCount = region ? region->count : 0; - *blockSize = 1; - } - - size_t region_getMemoryCapacity(MemoryRegion* region) - { - return heap_caps_get_free_size(MALLOC_CAP_SPIRAM) + region_getMemoryUsed(region); - } - - RelativePointer region_getRelativePointer(MemoryRegion* region, void* ptr) - { - return NULL_RELATIVE_POINTER; - } - - void* region_getRealPointer(MemoryRegion* region, RelativePointer ptr) - { - return nullptr; - } - - bool region_serializeToDisk(MemoryRegion* region, FileStream* file) - { - return false; - } - - MemoryRegion* region_restoreFromDisk(MemoryRegion* region, FileStream* file) - { - return nullptr; - } - // cppcheck-suppress-end constParameterPointer - - void region_test() - { - } -} - -void espbox_shared_regionStats(bool alloc) -{ - TFE_Memory::RegionLock lock; - ESPBOX_SHARED_ALLOC(TFE_Memory::s_callers, TFE_Memory::CALLER_STAT_COUNT); -} diff --git a/components/darkforces/src/platform/esp_platform.h b/components/darkforces/src/platform/esp_platform.h deleted file mode 100644 index f2c03997..00000000 --- a/components/darkforces/src/platform/esp_platform.h +++ /dev/null @@ -1,51 +0,0 @@ -#pragma once -// Shared ESP32 platform helpers for the Dark Forces port. -#include -#include - -namespace TFE_Memory -{ - // Serializes all access to the pool allocator (recursive). - struct PoolLock - { - PoolLock(); - ~PoolLock(); - }; - - // While at least one scope is active on a task, allocations made by Dark - // Forces code on that task go into the 4MB ROM block (see esp_alloc.cpp). - struct DfAllocScope - { - DfAllocScope(); - ~DfAllocScope(); - }; - - // Temporarily sends Dark Forces allocations on this task to the PSRAM heap - // (for objects that must outlive the session). - struct DfHeapScope - { - DfHeapScope(); - ~DfHeapScope(); - private: - int m_saved; - }; - - // Start / end a session: the pool allocator manages the block while Dark Forces runs. - // poolEnd() reports anything still allocated in the block. - bool poolBegin(uint8_t* base, size_t size); - void poolEnd(); - void getPoolStats(size_t* used, size_t* peak, size_t* overflowBytes); - // Print how the 4MB block is used: used / free bytes and block counts, largest free block. - void printPoolSummary(); - - // Raw, thread safe block allocations (no heap fallback; null when the block is full). - void* lockedPoolAlloc(size_t size); - void lockedPoolFree(void* ptr); - // Record an allocation that did not fit in the block and went to the PSRAM heap. - void noteRegionOverflow(size_t size); - - // Bytes currently allocated through the memory regions, split by backing store. - void getRegionStats(size_t* poolBytes, size_t* heapBytes, size_t* gameBytes, size_t* levelBytes); - // Print the biggest region_alloc() callers (bytes currently allocated). - void printRegionCallers(); -} diff --git a/components/darkforces/src/platform/esp_render.cpp b/components/darkforces/src/platform/esp_render.cpp deleted file mode 100644 index c9ab6109..00000000 --- a/components/darkforces/src/platform/esp_render.cpp +++ /dev/null @@ -1,246 +0,0 @@ -// ESP32 (esp-box-emu) render backend for The Force Engine. -// -// The Jedi classic renderer produces an 8-bit paletted 320x200 image in the -// virtual framebuffer. The BoxEmu display pipeline already knows how to -// palette-convert and scale 8-bit frames, so all this backend does is keep an -// RGB565 copy of the palette and hand the frame pointer to BoxEmu on swap(). -#include -#include - -#include "box-emu.hpp" -#include "pool_allocator.h" -#include "esp_platform.h" -#include - -#include - -#include -#include - -namespace TFE_RenderBackend -{ - static WindowState s_windowState; - static u32 s_virtualWidth = 320; - static u32 s_virtualHeight = 200; - static const u8* s_curFrameBuffer = nullptr; - static u32* s_paletteCpu = nullptr; // 256 entries (shared memory) - // RGB565 (native order, the display pipeline handles the LCD byte order). - static uint16_t* s_palette565 = nullptr; // 256 entries (shared memory) - static bool s_colorCorrection = false; - static u8 s_gammaTable[256]; - static u32 s_frameCount = 0; - // Display buffers (8-bit, virtual resolution). The renderer draws into its own - // buffer; swap() copies the finished frame here so the display task can convert - // and scale it while the next frame is being drawn. - static u8* s_displayBuffers[2] = { nullptr, nullptr }; - static u32 s_displayIndex = 0; - - static void freeDisplayBuffers() - { - for (u8*& buf : s_displayBuffers) - { - if (!buf) { continue; } - if (pool_contains(buf)) { TFE_Memory::lockedPoolFree(buf); } - else { free(buf); } - buf = nullptr; - } - } - - static void allocDisplayBuffers(size_t size) - { - freeDisplayBuffers(); - for (u8*& buf : s_displayBuffers) - { - buf = (u8*)TFE_Memory::lockedPoolAlloc(size); - if (!buf) { buf = (u8*)heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); } - if (buf) { memset(buf, 0, size); } - } - } - - static inline uint16_t toDisplayColor(u8 r, u8 g, u8 b) - { - return uint16_t(((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3)); - } - - bool init(const WindowState& state) - { - s_windowState = state; - s_curFrameBuffer = nullptr; - s_frameCount = 0; - BoxEmu::get().palette(s_palette565, 256); - return true; - } - - void destroy() - { - s_curFrameBuffer = nullptr; - BoxEmu::get().palette(nullptr); - freeDisplayBuffers(); - } - - bool getVsyncEnabled() { return false; } - void enableVsync(bool enable) {} - void setClearColor(const f32* color) {} - - void swap(bool blitVirtualDisplay) - { - if (s_curFrameBuffer && blitVirtualDisplay) - { - u8* dst = s_displayBuffers[s_displayIndex]; - if (dst) - { - memcpy(dst, s_curFrameBuffer, s_virtualWidth * s_virtualHeight); - s_displayIndex ^= 1; - } - BoxEmu::get().push_frame(dst ? dst : s_curFrameBuffer); - s_frameCount++; - } - s_curFrameBuffer = nullptr; - } - - u32 getFrameCount() - { - return s_frameCount; - } - - // captureScreenToMemory implements the TFE screenshot API (mem is engine-declared non-const). - // cppcheck-suppress constParameterPointer - void captureScreenToMemory(u32* mem) {} - void queueScreenshot(const char* screenshotPath) {} - void startGifRecording(const char* path) {} - void stopGifRecording() {} - void updateSettings() {} - void resize(s32 width, s32 height) {} - void enumerateDisplays() {} - s32 getDisplayCount() { return 1; } - s32 getDisplayIndex(s32 x, s32 y) { return 0; } - - bool getDisplayMonitorInfo(s32 displayIndex, MonitorInfo* monitorInfo) - { - monitorInfo->x = 0; - monitorInfo->y = 0; - monitorInfo->w = s_virtualWidth; - monitorInfo->h = s_virtualHeight; - return true; - } - - f32 getDisplayRefreshRate() { return 0.0f; } - void getCurrentMonitorInfo(MonitorInfo* monitorInfo) { getDisplayMonitorInfo(0, monitorInfo); } - void enableFullscreen(bool enable) {} - void clearWindow() {} - - void getDisplayInfo(DisplayInfo* displayInfo) - { - // Report the virtual resolution so that menu cursor math maps 1:1. - displayInfo->width = s_virtualWidth; - displayInfo->height = s_virtualHeight; - displayInfo->refreshRate = 0.0f; - } - - bool createVirtualDisplay(const VirtualDisplayInfo& vdispInfo) - { - s_virtualWidth = vdispInfo.width; - s_virtualHeight = vdispInfo.height; - BoxEmu::get().native_size(s_virtualWidth, s_virtualHeight); - allocDisplayBuffers(s_virtualWidth * s_virtualHeight); - return true; - } - - u32 getVirtualDisplayWidth2D() { return s_virtualWidth; } - u32 getVirtualDisplayWidth3D() { return s_virtualWidth; } - u32 getVirtualDisplayHeight() { return s_virtualHeight; } - u32 getVirtualDisplayOffset2D() { return 0; } - u32 getVirtualDisplayOffset3D() { return 0; } - void* getVirtualDisplayGpuPtr() { return nullptr; } - bool getWidescreen() { return false; } - bool getFrameBufferAsync() { return false; } - bool getGPUColorConvert() { return false; } - - void updateVirtualDisplay(const void* buffer, size_t size) - { - s_curFrameBuffer = (const u8*)buffer; - } - - void bindVirtualDisplay() {} - // clearVirtualDisplay implements the TFE render-backend API (color is engine-declared non-const). - // cppcheck-suppress constParameterPointer - void clearVirtualDisplay(f32* color, bool clearColor) {} - void copyToVirtualDisplay(RenderTargetHandle src) {} - void copyBackbufferToRenderTarget(RenderTargetHandle dst) {} - - void setPalette(const u32* palette) - { - // TFE palette entries are 0xAABBGGRR (R in the low byte). - memcpy(s_paletteCpu, palette, 256 * sizeof(u32)); - for (s32 i = 0; i < 256; i++) - { - const u32 c = palette[i]; - u8 r = u8(c & 0xff); - u8 g = u8((c >> 8) & 0xff); - u8 b = u8((c >> 16) & 0xff); - if (s_colorCorrection) - { - r = s_gammaTable[r]; - g = s_gammaTable[g]; - b = s_gammaTable[b]; - } - s_palette565[i] = toDisplayColor(r, g, b); - } - } - - const u32* getPalette() - { - return s_paletteCpu; - } - - const uint16_t* getDisplayPalette() - { - return s_palette565; - } - - const TextureGpu* getPaletteTexture() { return nullptr; } - - void setColorCorrection(bool enabled, const ColorCorrection* color, bool bloomChanged) - { - s_colorCorrection = enabled && color && color->gamma != 1.0f; - if (s_colorCorrection) - { - for (s32 i = 0; i < 256; i++) - { - f32 v = powf(f32(i) / 255.0f, 2.0f - color->gamma) * 255.0f; - s_gammaTable[i] = u8(v < 0.0f ? 0 : (v > 255.0f ? 255 : v)); - } - } - } - - void drawVirtualDisplay() {} - - // GPU functionality is not available; everything below is a no-op. - RenderTargetHandle createRenderTarget(u32 width, u32 height, bool hasDepthBuffer) { return RenderTargetHandle(nullptr); } - void freeRenderTarget(RenderTargetHandle handle) {} - void bindRenderTarget(RenderTargetHandle handle) {} - void clearRenderTarget(RenderTargetHandle handle, const f32* clearColor, f32 clearDepth) {} - void clearRenderTargetDepth(RenderTargetHandle handle, f32 clearDepth) {} - void copyRenderTarget(RenderTargetHandle dst, RenderTargetHandle src) {} - void unbindRenderTarget() {} - const TextureGpu* getRenderTargetTexture(RenderTargetHandle rtHandle) { return nullptr; } - void getRenderTargetDim(RenderTargetHandle rtHandle, u32* width, u32* height) { *width = 0; *height = 0; } - TextureGpu* createTexture(u32 width, u32 height, TexFormat format) { return nullptr; } - TextureGpu* createTextureArray(u32 width, u32 height, u32 layers, u32 channels) { return nullptr; } - TextureGpu* createTexture(u32 width, u32 height, const u32* data, MagFilter magFilter) { return nullptr; } - // freeTexture implements the TFE render-backend API (texture is engine-declared non-const). - // cppcheck-suppress constParameterPointer - void freeTexture(TextureGpu* texture) {} - void getTextureDim(TextureGpu* texture, u32* width, u32* height) { *width = 0; *height = 0; } - void* getGpuPtr(const TextureGpu* texture) { return nullptr; } - void drawIndexedTriangles(u32 triCount, u32 indexStride, u32 indexStart) {} - void drawLines(u32 lineCount) {} - void bloomPostEnable(bool enable) {} - void setupPostEffectChain(bool useDynamicTexture) {} -} // namespace - -void espbox_shared_render(bool alloc) -{ - ESPBOX_SHARED_ALLOC(TFE_RenderBackend::s_paletteCpu, 256); - ESPBOX_SHARED_ALLOC(TFE_RenderBackend::s_palette565, 256); -} diff --git a/components/darkforces/src/platform/esp_stubs.cpp b/components/darkforces/src/platform/esp_stubs.cpp deleted file mode 100644 index caa17267..00000000 --- a/components/darkforces/src/platform/esp_stubs.cpp +++ /dev/null @@ -1,354 +0,0 @@ -// ESP32 (esp-box-emu) stubs for The Force Engine subsystems that are not -// available on the ESP32: the developer console, the ImGui front end, image -// loading, zip/memory archives, the GPU/float renderers, the SF2 and system -// MIDI devices, accessibility captions, and the reticle. -// -// Adapted from the Amiga port's stubs (amiga/stubs_amiga.cpp). -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -namespace TFE_DarkForces -{ - extern void pauseLevelSound(); - extern void resumeLevelSound(); - extern JBool s_palModified; -} - -// Everything below implements The Force Engine's platform/stub API. The engine's -// (vendored) declarations take non-const pointers, so these definitions can't add -// const to their pointer parameters without diverging from the engine. -// cppcheck-suppress-begin constParameterPointer -///////////////////////////////////////////// -// Front end UI -///////////////////////////////////////////// -namespace TFE_FrontEndUI -{ - static bool s_exitToMenu = false; - - void init() { s_exitToMenu = false; } - void shutdown() {} - void initConsole() {} - bool toggleConsole() { return false; } - bool isConsoleOpen() { return false; } - bool isConsoleAnimating() { return false; } - bool isConfigMenuOpen() { return false; } - bool uiControlsEnabled() { return false; } - bool shouldClearScreen() { return false; } - void setCurrentGame(IGame* game) {} - void setAppState(AppState state) {} - AppState update() { return APP_STATE_GAME; } - void draw(bool drawFrontEnd, bool noGameData, bool setDefaults, bool showFps) {} - void setCanSave(bool canSave) {} - bool getCanSave() { return true; } - void toggleProfilerView() {} - - void logToConsole(const char* str) {} - - void enableConfigMenu() - { - // There is no configuration UI on the box; just make sure the palette is restored. - TFE_DarkForces::s_palModified = JTRUE; - } - - // "Quit" from the in-game escape menu: leave the game and return to the emulator menu. - void exitToMenu() - { - s_exitToMenu = true; - TFE_System::postQuitMessage(); - } - - bool exitToMenuRequested() - { - return s_exitToMenu; - } -} - -///////////////////////////////////////////// -// Console -///////////////////////////////////////////// -namespace TFE_Console -{ - void registerCVarInt(const char* name, u32 flags, s32* var, const char* helpString) {} - void registerCVarFloat(const char* name, u32 flags, f32* var, const char* helpString) {} - void registerCVarBool(const char* name, u32 flags, bool* var, const char* helpString) {} - void registerCVarString(const char* name, u32 flags, char* var, u32 maxLen, const char* helpString) {} - void registerCommand(const char* name, ConsoleFunc func, u32 argCount, const char* helpString, bool repeat) {} - - void addSerializedCVarInt(const char* name, s32 value) {} - void addSerializedCVarFloat(const char* name, f32 value) {} - void addSerializedCVarBool(const char* name, bool value) {} - void addSerializedCVarString(const char* name, const char* value) {} - - bool init() { return true; } - void destroy() {} - void update() {} - bool isOpen() { return false; } - bool isAnimating() { return false; } - void startOpen() {} - void startClose() {} - - void addToHistory(const char* str) - { - if (str) { printf("[TFE Console] %s\n", str); } - } - u32 getCVarCount() { return 0; } - const CVar* getCVarByIndex(u32 index) { return nullptr; } -} - -///////////////////////////////////////////// -// Messages -///////////////////////////////////////////// -namespace TFE_System -{ - const char* getMessage(TFE_Message msg) - { - switch (msg) - { - case TFE_MSG_SAVE: - return "Game Saved."; - case TFE_MSG_SECRET: - return "You found a secret!"; - case TFE_MSG_FLYMODE: - return "Fly Mode Toggle."; - case TFE_MSG_NOCLIP: - return "No Clip Toggle."; - case TFE_MSG_TESTER: - return "Testing Mode Toggle."; - default: - break; - } - return ""; - } - - bool loadMessages(const char* path) { return true; } - void freeMessages() {} -} - -///////////////////////////////////////////// -// Images (only used for save game thumbnails, which are disabled). -///////////////////////////////////////////// -namespace TFE_Image -{ - void init() {} - void shutdown() {} - - Image* get(const char* imagePath) - { - return nullptr; - } - - Image* loadFromMemory(const u8* buffer, size_t size) - { - return nullptr; - } - - void free(Image* image) {} - void freeAll() {} - - // These two are dead (save thumbnails are disabled) and deliberately alias the - // caller's const pixel buffer; the TFE Image signatures are non-const. - // cppcheck-suppress-begin dangerousTypeCast - size_t writeImageToMemory(u8*& output, u32 width, u32 height, const u32* pixelData) - { - output = (u8*)pixelData; - return width * height; - } - - void readImageFromMemory(Image* output, size_t size, const u32* pixelData) - { - output->width = TFE_SaveSystem::SAVE_IMAGE_WIDTH; - output->height = TFE_SaveSystem::SAVE_IMAGE_HEIGHT; - output->data = (u32*)pixelData; - } - // cppcheck-suppress-end dangerousTypeCast - - void writeImage(const char* path, u32 width, u32 height, u32* pixelData) - { - } -} - -///////////////////////////////////////////// -// Archives that are not supported (mods). -///////////////////////////////////////////// -ZipArchive::~ZipArchive() {} -bool ZipArchive::create(const char *archivePath) { return false; } -bool ZipArchive::open(const char *archivePath) { return false; } -void ZipArchive::close() {} -bool ZipArchive::openFile(const char *file) { return false; } -bool ZipArchive::openFile(u32 index) { return false; } -void ZipArchive::closeFile() {} -bool ZipArchive::fileExists(const char *file) { return false; } -bool ZipArchive::fileExists(u32 index) { return false; } -u32 ZipArchive::getFileIndex(const char* file) { return INVALID_FILE; } -size_t ZipArchive::getFileLength() { return 0;} -size_t ZipArchive::readFile(void* data, size_t size) { return 0; } -bool ZipArchive::seekFile(s32 offset, s32 origin) { return false; } -size_t ZipArchive::getLocInFile() { return 0; } -u32 ZipArchive::getFileCount() { return 0; } -const char* ZipArchive::getFileName(u32 index) { return nullptr; } -size_t ZipArchive::getFileLength(u32 index) { return 0; } -void ZipArchive::addFile(const char* fileName, const char* filePath) {} - -GobMemoryArchive::~GobMemoryArchive() {} -bool GobMemoryArchive::create(const char *archivePath) { return false; } -bool GobMemoryArchive::open(const char *archivePath) { return false; } -bool GobMemoryArchive::open(const u8* buffer, size_t size) { return false; } -void GobMemoryArchive::close() {} -bool GobMemoryArchive::openFile(const char *file) { return false; } -bool GobMemoryArchive::openFile(u32 index) { return false; } -void GobMemoryArchive::closeFile() {} -u32 GobMemoryArchive::getFileIndex(const char* file) { return INVALID_FILE; } -bool GobMemoryArchive::fileExists(const char *file) { return false; } -bool GobMemoryArchive::fileExists(u32 index) { return false; } -size_t GobMemoryArchive::getFileLength() { return 0; } -size_t GobMemoryArchive::readFile(void *data, size_t size) { return 0; } -bool GobMemoryArchive::seekFile(s32 offset, s32 origin) { return false; } -size_t GobMemoryArchive::getLocInFile() { return 0; } -u32 GobMemoryArchive::getFileCount() { return 0; } -const char* GobMemoryArchive::getFileName(u32 index) { return nullptr; } -size_t GobMemoryArchive::getFileLength(u32 index) { return 0; } -void GobMemoryArchive::addFile(const char* fileName, const char* filePath) {} - -///////////////////////////////////////////// -// GPU / floating point renderers (only the classic fixed point renderer is built). -///////////////////////////////////////////// -namespace TFE_Jedi -{ - Vec3f s_cameraPos; - Vec3f s_cameraDir; - namespace RClassic_GPU - { - void resetState() {} - void setupInitCameraAndLights(s32 width, s32 height) {} - void changeResolution(s32 width, s32 height) {} - void computeCameraTransform(RSector* sector, f32 pitch, f32 yaw, f32 camX, f32 camY, f32 camZ) {} - void transformPointByCamera(vec3_float* worldPoint, vec3_float* viewPoint) {} - void computeSkyOffsets() {} - } - - namespace RClassic_Float - { - void resetState() {} - void setupInitCameraAndLights(s32 width, s32 height) {} - void changeResolution(s32 width, s32 height) {} - void computeCameraTransform(RSector* sector, f32 pitch, f32 yaw, f32 camX, f32 camY, f32 camZ) {} - void computeSkyOffsets() {} - } - - void TFE_Sectors_Float::destroy() {} - void TFE_Sectors_Float::reset() {} - void TFE_Sectors_Float::prepare() {} - void TFE_Sectors_Float::draw(RSector* sector) {} - void TFE_Sectors_Float::subrendererChanged() {} - - void TFE_Sectors_GPU::destroy() {} - void TFE_Sectors_GPU::reset() {} - void TFE_Sectors_GPU::prepare() {} - void TFE_Sectors_GPU::draw(RSector* sector) {} - void TFE_Sectors_GPU::subrendererChanged() {} - void TFE_Sectors_GPU::flushCache() {} - TextureGpu* getColormap() { return nullptr; } - - void screenGPU_init() {} - void screenGPU_setHudTextureCallbacks(s32 count, TextureListCallback* callbacks) {} - void screenGPU_beginQuads(u32 width, u32 height) {} - void screenGPU_endQuads() {} - void screenGPU_beginLines(u32 width, u32 height) {} - void screenGPU_endLines() {} - void screenGPU_beginImageQuads(u32 width, u32 height) {} - void screenGPU_endImageQuads() {} - void screenGPU_addImageQuad(s32 x0, s32 z0, s32 x1, s32 z1, TextureGpu* texture) {} - void screenGPU_addImageQuad(s32 x0, s32 z0, s32 x1, s32 z1, f32 u0, f32 u1, TextureGpu* texture) {} - void screenGPU_drawPoint(ScreenRect* rect, s32 x, s32 z, u8 color) {} - void screenGPU_drawLine(ScreenRect* rect, s32 x0, s32 z0, s32 x1, s32 z1, u8 color) {} - void screenGPU_blitTextureLit(TextureData* texture, DrawRect* rect, s32 x0, s32 y0, u8 lightLevel, JBool forceTransparency) {} - void screenGPU_drawColoredQuad(fixed16_16 x0, fixed16_16 y0, fixed16_16 x1, fixed16_16 y1, u8 color) {} - void screenGPU_blitTextureScaled(TextureData* texture, DrawRect* rect, fixed16_16 x0, fixed16_16 y0, fixed16_16 xScale, fixed16_16 yScale, u8 lightLevel, JBool forceTransparency) {} - - void texturepacker_reset() {} -} - -///////////////////////////////////////////// -// MIDI devices other than OPL3. -///////////////////////////////////////////// -namespace TFE_Audio -{ - SoundFontDevice::~SoundFontDevice() {} - u32 SoundFontDevice::getOutputCount() { return 0; } - void SoundFontDevice::getOutputName(s32 index, char* buffer, u32 maxLength) { *buffer = 0; } - bool SoundFontDevice::selectOutput(s32 index) { return false; } - s32 SoundFontDevice::getActiveOutput(void) { return 0; } - void SoundFontDevice::exit() {} - const char* SoundFontDevice::getName() { return "SF2 (unavailable)"; } - bool SoundFontDevice::render(MidiSample* buffer, u32 sampleCount) { return false; } - bool SoundFontDevice::canRender() { return false; } - void SoundFontDevice::setVolume(f32 volume) {} - void SoundFontDevice::message(u8 type, u8 arg1, u8 arg2) {} - void SoundFontDevice::message(const u8* msg, u32 len) {} - void SoundFontDevice::noteAllOff() {} - - SystemMidiDevice::SystemMidiDevice() : m_midiout(nullptr), m_outputId(-1) {} - SystemMidiDevice::~SystemMidiDevice() {} - void SystemMidiDevice::exit() {} - const char* SystemMidiDevice::getName() { return "System MIDI (unavailable)"; } - void SystemMidiDevice::message(u8 type, u8 arg1, u8 arg2) {} - void SystemMidiDevice::message(const u8* msg, u32 len) {} - void SystemMidiDevice::noteAllOff() {} - void SystemMidiDevice::setVolume(f32 volume) {} - u32 SystemMidiDevice::getOutputCount() { return 0; } - void SystemMidiDevice::getOutputName(s32 index, char* buffer, u32 maxLength) { *buffer = 0; } - bool SystemMidiDevice::selectOutput(s32 index) { return false; } - s32 SystemMidiDevice::getActiveOutput(void) { return 0; } -}; - -///////////////////////////////////////////// -// Reticle (GPU only feature). -///////////////////////////////////////////// -bool reticle_init() { return false; } -void reticle_destroy() {} -void reticle_enable(bool enable) {} -void reticle_setShape(u32 index) {} -void reticle_setColor(const f32* color) {} -void reticle_setScale(f32 scale) {} -bool reticle_enabled() { return false; } -u32 reticle_getShape() { return 0; } -u32 reticle_getShapeCount() { return 0; } -void reticle_getColor(f32* color) { color[0] = color[1] = color[2] = color[3] = 1.0f; } -f32 reticle_getScale() { return 1.0f; } - -///////////////////////////////////////////// -// Accessibility (captions). -///////////////////////////////////////////// -namespace TFE_A11Y -{ - void init() {} - void clearCaptions() {} - void drawCaptions() {} - void drawExampleCaptions() {} - void focusCaptions() {} - void addCaption(Caption caption) {} - void onSoundPlay(char* name, CaptionEnv env) {} - bool cutsceneCaptionsEnabled() { return false; } - bool gameplayCaptionsEnabled() { return false; } -} -// cppcheck-suppress-end constParameterPointer diff --git a/components/darkforces/src/platform/esp_thread.cpp b/components/darkforces/src/platform/esp_thread.cpp deleted file mode 100644 index e2daa17b..00000000 --- a/components/darkforces/src/platform/esp_thread.cpp +++ /dev/null @@ -1,113 +0,0 @@ -// ESP32 (esp-box-emu) thread implementation for The Force Engine (FreeRTOS). -#include -#include -#include "esp_platform.h" - -#include -#include -#include - -class ThreadEsp : public Thread -{ -public: - ThreadEsp(const char* name, ThreadFunc func, void* userData); - virtual ~ThreadEsp(); - - virtual bool run(); - virtual void pause(); - virtual void resume(); - virtual void waitOnExit(void); - - ThreadFunc getFunc() const { return m_func; } - void* getUserData() const { return m_userData; } - -protected: - static void threadEntry(void* arg); - - TaskHandle_t m_task = nullptr; - SemaphoreHandle_t m_done = nullptr; -}; - -ThreadEsp::ThreadEsp(const char* name, ThreadFunc func, void* userData) - : Thread(name, func, userData), m_done(xSemaphoreCreateBinary()) -{ -} - -ThreadEsp::~ThreadEsp() -{ - if (m_isRunning) - { - // qualified call: a destructor must not dispatch virtually - ThreadEsp::waitOnExit(); - } - if (m_done) - { - vSemaphoreDelete(m_done); - m_done = nullptr; - } -} - -void ThreadEsp::threadEntry(void* arg) -{ - ThreadEsp* thread = (ThreadEsp*)arg; - { - // Engine threads allocate from the 4MB ROM block like the game task. - TFE_Memory::DfAllocScope allocScope; - thread->getFunc()(thread->getUserData()); - } - thread->m_isRunning = false; - xSemaphoreGive(thread->m_done); - vTaskDelete(nullptr); -} - -bool ThreadEsp::run(void) -{ - if (m_isRunning) { return true; } - m_isRunning = true; - // Engine threads (the MIDI/iMuse update thread) run on core 1 alongside the audio task, - // leaving core 0 to the game and display. - BaseType_t ok = xTaskCreatePinnedToCore(threadEntry, m_name, 8 * 1024, this, 8, &m_task, 1); - if (ok != pdPASS) - { - m_isRunning = false; - m_task = nullptr; - TFE_System::logWrite(LOG_ERROR, "Thread", "Cannot create thread '%s'.", m_name); - return false; - } - return true; -} - -void ThreadEsp::pause(void) -{ - if (m_task && m_isRunning && !m_isPaused) - { - vTaskSuspend(m_task); - m_isPaused = true; - } -} - -void ThreadEsp::resume(void) -{ - if (m_task && m_isRunning && m_isPaused) - { - vTaskResume(m_task); - m_isPaused = false; - } -} - -void ThreadEsp::waitOnExit(void) -{ - if (m_task && m_isRunning) - { - if (m_isPaused) { resume(); } - xSemaphoreTake(m_done, portMAX_DELAY); - } - m_task = nullptr; - m_isRunning = false; -} - -//factory -Thread* Thread::create(const char* name, ThreadFunc func, void* userData) -{ - return new ThreadEsp(name, func, userData); -} diff --git a/components/darkforces/tfe/SDL_endian.h b/components/darkforces/tfe/SDL_endian.h deleted file mode 100644 index e3f0b69e..00000000 --- a/components/darkforces/tfe/SDL_endian.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Minimal replacement for SDL_endian.h used by TFE_System/endian.h. - * - * The Amiga port shipped a big-endian version of this shim (68k); the ESP32 - * (Xtensa) is little-endian like the Dark Forces data files, so every - * "little endian to cpu" conversion is the identity and the "big endian to cpu" - * conversions swap. - */ -#ifndef SDL_endian_h_ -#define SDL_endian_h_ - -#include -typedef uint16_t Uint16; -typedef uint32_t Uint32; -typedef uint64_t Uint64; - -#define SDL_LIL_ENDIAN 1234 -#define SDL_BIG_ENDIAN 4321 -#define SDL_BYTEORDER SDL_LIL_ENDIAN -#define SDL_FORCE_INLINE inline -#define SDL_static_cast(x, y) ((x)(y)) - -#ifdef __cplusplus -extern "C" { -#endif - -SDL_FORCE_INLINE Uint16 -SDL_Swap16(Uint16 x) -{ - return SDL_static_cast(Uint16, ((x << 8) | (x >> 8))); -} - -SDL_FORCE_INLINE Uint32 -SDL_Swap32(Uint32 x) -{ - return SDL_static_cast(Uint32, ((x << 24) | ((x << 8) & 0x00FF0000) | - ((x >> 8) & 0x0000FF00) | (x >> 24))); -} - -SDL_FORCE_INLINE Uint64 -SDL_Swap64(Uint64 x) -{ - Uint32 hi, lo; - lo = SDL_static_cast(Uint32, x & 0xFFFFFFFF); - x >>= 32; - hi = SDL_static_cast(Uint32, x & 0xFFFFFFFF); - x = SDL_Swap32(lo); - x <<= 32; - x |= SDL_Swap32(hi); - return (x); -} - -SDL_FORCE_INLINE float -SDL_SwapFloat(float x) -{ - union - { - float f; - Uint32 ui32; - } swapper; - swapper.f = x; - swapper.ui32 = SDL_Swap32(swapper.ui32); - return swapper.f; -} - -#define SDL_SwapLE16(X) (X) -#define SDL_SwapLE32(X) (X) -#define SDL_SwapLE64(X) (X) -#define SDL_SwapFloatLE(X) (X) -#define SDL_SwapBE16(X) SDL_Swap16(X) -#define SDL_SwapBE32(X) SDL_Swap32(X) -#define SDL_SwapBE64(X) SDL_Swap64(X) -#define SDL_SwapFloatBE(X) SDL_SwapFloat(X) - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/components/darkforces/tfe/TFE_A11y/accessibility.h b/components/darkforces/tfe/TFE_A11y/accessibility.h deleted file mode 100644 index 362fca8e..00000000 --- a/components/darkforces/tfe/TFE_A11y/accessibility.h +++ /dev/null @@ -1,37 +0,0 @@ -#pragma once -#include -#include -using std::string; - -namespace TFE_A11Y { - enum CaptionEnv - { - CC_Gameplay, CC_Cutscene - }; - - enum CaptionType - { - CC_Voice, CC_Effect - }; - - struct Caption - { - string text; - s64 microsecondsRemaining; - CaptionType type; - CaptionEnv env; - }; - - void init(); - void clearCaptions(); - void drawCaptions(); - void drawExampleCaptions(); - void focusCaptions(); - void addCaption(Caption caption); - void onSoundPlay(char* name, CaptionEnv env); - - //True if captions or subtitles are enabled for cutscenes - bool cutsceneCaptionsEnabled(); - //True if captions or subtitles are enabled for gameplay - bool gameplayCaptionsEnabled(); -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Archive/archive.cpp b/components/darkforces/tfe/TFE_Archive/archive.cpp deleted file mode 100644 index 8495f9a3..00000000 --- a/components/darkforces/tfe/TFE_Archive/archive.cpp +++ /dev/null @@ -1,178 +0,0 @@ -#include - -#include "archive.h" -#include "gobArchive.h" -#include "lfdArchive.h" -#include "labArchive.h" -#include "zipArchive.h" -#include -#include -#include -#include - -namespace -{ - typedef std::map ArchiveMap; - static ArchiveMap s_archives[ARCHIVE_COUNT]; -} - -static const char* c_archiveExt[ARCHIVE_COUNT]= -{ - "GOB", // ARCHIVE_GOB - "LFD", // ARCHIVE_LFD - "LAB", // ARCHIVE_LAB - "ZIP", // ARCHIVE_ZIP -}; - -ArchiveType Archive::getArchiveTypeFromName(const char* path) -{ - const size_t len = strlen(path); - for (u32 i = 0; i < ARCHIVE_COUNT; i++) - { - if (strcasecmp(&path[len - 3], c_archiveExt[i]) == 0) - { - return ArchiveType(i); - } - } - return ARCHIVE_UNKNOWN; -} - -Archive* Archive::getArchive(ArchiveType type, const char* name, const char* path) -{ - ArchiveMap::iterator iArchive = s_archives[type].find(path); - if (iArchive != s_archives[type].end()) - { - return iArchive->second; - } - if (!FileUtil::exists(path)) - { - return nullptr; - } - - Archive* archive = nullptr; - switch (type) - { - case ARCHIVE_GOB: - { - archive = new GobArchive(); - } - break; - case ARCHIVE_LFD: - { - archive = new LfdArchive(); - } - break; - case ARCHIVE_LAB: - { - archive = new LabArchive(); - } - break; - case ARCHIVE_ZIP: - { - archive = new ZipArchive(); - } - break; - default: - assert(0); - break; - }; - - if (archive) - { - strcpy(archive->m_name, name); - archive->open(path); - archive->m_type = type; - (s_archives[type])[path] = archive; - } - return archive; -} - -void Archive::freeArchive(Archive* archive) -{ - if (!archive) { return; } - - const ArchiveType type = archive->m_type; - ArchiveMap::iterator iArchive = s_archives[type].find(archive->m_name); - if (iArchive != s_archives[archive->m_type].end()) - { - Archive* foundArchive = iArchive->second; - assert(foundArchive == archive); - foundArchive->close(); - delete foundArchive; - - s_archives[type].erase(iArchive); - } -} - -void Archive::freeAllArchives() -{ - for (u32 i = 0; i < ARCHIVE_COUNT; i++) - { - ArchiveMap::iterator iArchive = s_archives[i].begin(); - for (; iArchive != s_archives[i].end(); ++iArchive) - { - Archive* archive = iArchive->second; - archive->close(); - delete archive; - } - s_archives[i].clear(); - } -} - -Archive* Archive::createCustomArchive(ArchiveType type, const char* path) -{ - ArchiveMap::iterator iArchive = s_archives[type].find(path); - if (iArchive != s_archives[type].end()) - { - return iArchive->second; - } - - Archive* archive = nullptr; - switch (type) - { - case ARCHIVE_GOB: - { - archive = new GobArchive(); - } - break; - case ARCHIVE_LFD: - { - archive = new LfdArchive(); - } - break; - case ARCHIVE_LAB: - { - archive = new LabArchive(); - } - break; - case ARCHIVE_ZIP: - { - archive = new ZipArchive(); - } - break; - default: - assert(0); - break; - }; - - if (archive) - { - strcpy(archive->m_name, path); - archive->create(path); - archive->m_type = type; - (s_archives[type])[path] = archive; - } - return archive; -} - -void Archive::deleteCustomArchive(Archive* archive) -{ - if (!archive) { return; } - - ArchiveMap::iterator iArchive = s_archives[archive->m_type].find(archive->m_name); - if (iArchive != s_archives[archive->m_type].end()) - { - s_archives->erase(iArchive); - } - delete archive; -} diff --git a/components/darkforces/tfe/TFE_Archive/archive.h b/components/darkforces/tfe/TFE_Archive/archive.h deleted file mode 100644 index 2e860b7c..00000000 --- a/components/darkforces/tfe/TFE_Archive/archive.h +++ /dev/null @@ -1,75 +0,0 @@ -#pragma once -#include - -#include -#include - -enum ArchiveType -{ - ARCHIVE_GOB = 0, - ARCHIVE_LFD, - ARCHIVE_LAB, - ARCHIVE_ZIP, - ARCHIVE_COUNT, - ARCHIVE_UNKNOWN = ARCHIVE_COUNT -}; - -#define INVALID_FILE 0xffffffff - -class Archive -{ - // Public API handling the same archive in multiple locations. -public: - static Archive* getArchive(ArchiveType type, const char* name, const char* path); - static void freeArchive(Archive* archive); - static void freeAllArchives(); - - static Archive* createCustomArchive(ArchiveType type, const char* path); - static void deleteCustomArchive(Archive* archive); - - static ArchiveType getArchiveTypeFromName(const char* path); - - // Public Archive API -public: - Archive() : m_type(ARCHIVE_UNKNOWN) {} - Archive(ArchiveType type) : m_type(type) {} - virtual ~Archive() {} - - // Archive - virtual bool create(const char *archivePath) = 0; - virtual bool open(const char *archivePath) = 0; - virtual void close() = 0; - - const char* getName() { return m_name; } - const char* getPath() { return m_archivePath; } - - // File Access - virtual bool openFile(const char *file) = 0; - virtual bool openFile(u32 index) = 0; - virtual void closeFile() = 0; - - virtual bool fileExists(const char *file) = 0; - virtual bool fileExists(u32 index) = 0; - virtual u32 getFileIndex(const char* file) = 0; - - virtual size_t getFileLength() = 0; - virtual size_t readFile(void *data, size_t size) = 0; - virtual bool seekFile(s32 offset, s32 origin = SEEK_SET) = 0; - virtual size_t getLocInFile() = 0; - - // Directory - virtual u32 getFileCount() = 0; - virtual const char* getFileName(u32 index) = 0; - virtual size_t getFileLength(u32 index) = 0; - - // Edit - virtual void addFile(const char* fileName, const char* filePath) = 0; - - // Shared Private State -protected: - ArchiveType m_type; - char m_name[TFE_MAX_PATH]; - char m_archivePath[TFE_MAX_PATH]; - - s32 m_fileOffset; -}; diff --git a/components/darkforces/tfe/TFE_Archive/gobArchive.cpp b/components/darkforces/tfe/TFE_Archive/gobArchive.cpp deleted file mode 100644 index 578558ab..00000000 --- a/components/darkforces/tfe/TFE_Archive/gobArchive.cpp +++ /dev/null @@ -1,366 +0,0 @@ -#include - -#include -#include -#include "gobArchive.h" -#include -#include -#include -#ifdef TFE_ESPBOX -#include -#include -#endif - -GobArchive::~GobArchive() -{ - close(); -} - -bool GobArchive::create(const char *archivePath) -{ - m_archiveOpen = m_file.open(archivePath, Stream::MODE_WRITE); - m_curFile = -1; - m_fileOffset = 0; - if (!m_archiveOpen) { return false; } - - memset(&m_header, 0, sizeof(GOB_Header_t)); - m_header.GOB_MAGIC[0] = 'G'; - m_header.GOB_MAGIC[1] = 'O'; - m_header.GOB_MAGIC[2] = 'B'; - m_header.GOB_MAGIC[3] = '\n'; - m_header.MASTERX = sizeof(GOB_Header_t); - - m_fileList.MASTERN = 0; - m_fileList.entries = nullptr; - - m_file.writeBuffer(&m_header, sizeof(GOB_Header_t)); - m_file.writeBuffer(&m_fileList.MASTERN, sizeof(u32)); - - strcpy(m_archivePath, archivePath); - m_file.close(); - - return true; -} - -bool GobArchive::validate(const char *archivePath, s32 minFileCount) -{ - FileStream file; - if (!file.open(archivePath, Stream::MODE_READ)) - { - return false; - } - - // Read the directory. - GOB_Header_t header; - long MASTERN; - if (file.readBuffer(&header, sizeof(GOB_Header_t)) != sizeof(GOB_Header_t)) - { - file.close(); - return false; - } - header.MASTERX = TFE_Endian::le32_to_cpu(header.MASTERX); - file.seek(header.MASTERX); - file.readBuffer(&MASTERN, sizeof(long)); - MASTERN = TFE_Endian::le32_to_cpu(MASTERN); - file.close(); - - return MASTERN >= minFileCount; -} - -bool GobArchive::open(const char *archivePath) -{ - m_archiveOpen = m_file.open(archivePath, Stream::MODE_READ); - m_curFile = -1; - if (!m_archiveOpen) { return false; } - - // Read the directory. -#ifdef TFE_ESPBOX - // Validate every read: on a low memory box the SD card stack can fail reads, and a - // garbage entry count would overrun the directory allocation. - m_fileList.MASTERN = 0; - m_fileList.entries = nullptr; - const u32 headerBytes = m_file.readBuffer(&m_header, sizeof(GOB_Header_t)); - m_header.MASTERX = TFE_Endian::le32_to_cpu(m_header.MASTERX); - const bool seekOk = headerBytes == sizeof(GOB_Header_t) && m_file.seek(m_header.MASTERX); - const u32 countBytes = seekOk ? m_file.readBuffer(&m_fileList.MASTERN, sizeof(u32)) : 0; - m_fileList.MASTERN = TFE_Endian::le32_to_cpu(m_fileList.MASTERN); - if (countBytes != sizeof(u32) || memcmp(m_header.GOB_MAGIC, "GOB\n", 4) != 0 || m_fileList.MASTERN > 65536) - { - TFE_System::logWrite(LOG_ERROR, "GobArchive", "Cannot read the directory of '%s' (header %u B, count %u B, errno %d, free internal %u B, free PSRAM %u B).", - archivePath, headerBytes, countBytes, errno, - (u32)heap_caps_get_free_size(MALLOC_CAP_INTERNAL), (u32)heap_caps_get_free_size(MALLOC_CAP_SPIRAM)); - m_fileList.MASTERN = 0; - m_file.close(); - m_archiveOpen = false; - return false; - } -#else - m_file.readBuffer(&m_header, sizeof(GOB_Header_t)); - m_header.MASTERX = TFE_Endian::le32_to_cpu(m_header.MASTERX); - m_file.seek(m_header.MASTERX); - - m_file.readBuffer(&m_fileList.MASTERN, sizeof(u32)); - m_fileList.MASTERN = TFE_Endian::le32_to_cpu(m_fileList.MASTERN); -#endif - m_fileList.entries = new GOB_Entry_t[m_fileList.MASTERN]; -#ifdef TFE_ESPBOX - { - // Allocations are not zeroed (and may hold old ROM data): a short read must not - // leave unterminated names behind for getFileIndex() to run off the end of. - const u32 expected = sizeof(GOB_Entry_t) * m_fileList.MASTERN; - const u32 bytesRead = m_file.readBuffer(m_fileList.entries, sizeof(GOB_Entry_t), m_fileList.MASTERN); - if (bytesRead != expected) - { - TFE_System::logWrite(LOG_ERROR, "GobArchive", "Short read of the directory of '%s': %u of %u bytes (%u entries).", - archivePath, bytesRead, expected, m_fileList.MASTERN); - const u32 validEntries = bytesRead / sizeof(GOB_Entry_t); - memset(m_fileList.entries + validEntries, 0, sizeof(GOB_Entry_t) * (m_fileList.MASTERN - validEntries)); - } - for (u32 i = 0; i < m_fileList.MASTERN; i++) - { - m_fileList.entries[i].NAME[sizeof(m_fileList.entries[i].NAME) - 1] = 0; - } - } -#else - m_file.readBuffer(m_fileList.entries, sizeof(GOB_Entry_t), m_fileList.MASTERN); -#endif - for (s32 i = 0; i < m_fileList.MASTERN; i++) - { - m_fileList.entries[i].IX = TFE_Endian::le32_to_cpu(m_fileList.entries[i].IX); - m_fileList.entries[i].LEN = TFE_Endian::le32_to_cpu(m_fileList.entries[i].LEN); - } - - strcpy(m_archivePath, archivePath); -#ifndef TFE_ESPBOX - m_file.close(); -#endif - - return true; -} - -void GobArchive::close() -{ - m_file.close(); - m_archiveOpen = false; - delete[] m_fileList.entries; - m_fileList.entries = nullptr; -} - -// File Access -bool GobArchive::openFile(const char *file) -{ - if (!m_archiveOpen) { return false; } - -#ifndef TFE_ESPBOX - m_file.open(m_archivePath, Stream::MODE_READ); -#endif - m_curFile = -1; - m_fileOffset = 0; - - //search for this file. - for (u32 i = 0; i < m_fileList.MASTERN; i++) - { - if (strcasecmp(file, m_fileList.entries[i].NAME) == 0) - { - m_curFile = s32(i); - break; - } - } - - if (m_curFile == -1) - { -#ifndef TFE_ESPBOX - m_file.close(); -#endif - TFE_System::logWrite(LOG_ERROR, "GOB", "Failed to load \"%s\" from \"%s\"", file, m_archivePath); - } - else - { - m_file.seek(m_fileList.entries[m_curFile].IX); - } - return m_curFile > -1 ? true : false; -} - -bool GobArchive::openFile(u32 index) -{ - if (index >= getFileCount()) { return false; } - - m_curFile = s32(index); - m_fileOffset = 0; -#ifndef TFE_ESPBOX - m_file.open(m_archivePath, Stream::MODE_READ); -#endif - m_file.seek(m_fileList.entries[m_curFile].IX); - return true; -} - -void GobArchive::closeFile() -{ - m_curFile = -1; -#ifndef TFE_ESPBOX - m_file.close(); -#endif -} - -u32 GobArchive::getFileIndex(const char* file) -{ - if (!m_archiveOpen) { return INVALID_FILE; } - - //search for this file. - for (u32 i = 0; i < m_fileList.MASTERN; i++) - { - if (strcasecmp(file, m_fileList.entries[i].NAME) == 0) - { - return i; - } - } - return INVALID_FILE; -} - -bool GobArchive::fileExists(const char *file) -{ - if (!m_archiveOpen) { return false; } - m_curFile = -1; - - //search for this file. - for (u32 i = 0; i < m_fileList.MASTERN; i++) - { - if (strcasecmp(file, m_fileList.entries[i].NAME) == 0) - { - return true; - } - } - return false; -} - -bool GobArchive::fileExists(u32 index) -{ - if (index >= getFileCount()) { return false; } - return true; -} - -size_t GobArchive::getFileLength() -{ - if (m_curFile < 0) { return 0; } - return getFileLength(m_curFile); -} - -size_t GobArchive::readFile(void *data, size_t size) -{ - if (m_curFile < 0) { return false; } - if (size == 0) { size = m_fileList.entries[m_curFile].LEN; } - const size_t sizeToRead = std::min(size, (size_t)m_fileList.entries[m_curFile].LEN); - - u32 bytesRead = m_file.readBuffer(data, (u32)sizeToRead); - m_fileOffset += (s32)sizeToRead; - return bytesRead; -} - -bool GobArchive::seekFile(s32 offset, s32 origin) -{ - if (m_curFile < 0) { return false; } - size_t size = m_fileList.entries[m_curFile].LEN; - - switch (origin) - { - case SEEK_SET: - { - m_fileOffset = offset; - } break; - case SEEK_CUR: - { - m_fileOffset += offset; - } break; - case SEEK_END: - { - m_fileOffset = (s32)size - offset; - } break; - } - assert(m_fileOffset <= size && m_fileOffset >= 0); - if (m_fileOffset > size || m_fileOffset < 0) - { - m_fileOffset = 0; - return false; - } - - m_file.seek(m_fileList.entries[m_curFile].IX + m_fileOffset); - return true; -} - -size_t GobArchive::getLocInFile() -{ - return m_fileOffset; -} - -// Directory -u32 GobArchive::getFileCount() -{ - if (!m_archiveOpen) { return 0; } - return (u32)m_fileList.MASTERN; -} - -const char* GobArchive::getFileName(u32 index) -{ - if (!m_archiveOpen) { return nullptr; } - return m_fileList.entries[index].NAME; -} - -size_t GobArchive::getFileLength(u32 index) -{ - if (!m_archiveOpen) { return 0; } - return m_fileList.entries[index].LEN; -} - -// Edit -void GobArchive::addFile(const char* fileName, const char* filePath) -{ - FileStream file; - if (!file.open(filePath, Stream::MODE_READ)) - { - return; - } - const size_t len = file.getSize(); - const u32 newId = m_fileList.MASTERN; - m_fileList.MASTERN++; - GOB_Entry_t* newEntries = new GOB_Entry_t[m_fileList.MASTERN]; - memcpy(newEntries, m_fileList.entries, sizeof(GOB_Entry_t) * newId); - m_fileList.entries = newEntries; - - GOB_Entry_t* newFile = &m_fileList.entries[newId]; - memset(newFile, 0, sizeof(GOB_Entry_t)); - newFile->IX = newId > 0 ? m_fileList.entries[newId - 1].IX + m_fileList.entries[newId - 1].LEN : sizeof(GOB_Header_t); - newFile->LEN = u32(len); - strcpy(newFile->NAME, fileName); - m_header.MASTERX += newFile->LEN; - - // Read all of the file data. - std::vector> fileData(m_fileList.MASTERN); - if (m_file.open(m_archivePath, Stream::MODE_READ) && m_fileList.MASTERN >= 1) - { - for (u32 f = 0; f < m_fileList.MASTERN - 1; f++) - { - fileData[f].resize(m_fileList.entries[f].LEN); - m_file.seek(m_fileList.entries[f].IX); - m_file.readBuffer(fileData[f].data(), m_fileList.entries[f].LEN); - } - m_file.close(); - - fileData[newId].resize(len); - file.readBuffer(fileData[newId].data(), (u32)len); - file.close(); - } - - // Now write the new file. - if (m_file.open(m_archivePath, Stream::MODE_WRITE)) - { - m_file.writeBuffer(&m_header, sizeof(GOB_Header_t)); - for (u32 f = 0; f < m_fileList.MASTERN; f++) - { - m_file.writeBuffer(fileData[f].data(), m_fileList.entries[f].LEN); - } - assert(m_file.getLoc() == m_header.MASTERX); - m_file.writeBuffer(&m_fileList.MASTERN, sizeof(u32)); - m_file.writeBuffer(m_fileList.entries, sizeof(GOB_Entry_t), m_fileList.MASTERN); - m_file.close(); - } -} diff --git a/components/darkforces/tfe/TFE_Archive/gobArchive.h b/components/darkforces/tfe/TFE_Archive/gobArchive.h deleted file mode 100644 index 9ecd2a49..00000000 --- a/components/darkforces/tfe/TFE_Archive/gobArchive.h +++ /dev/null @@ -1,78 +0,0 @@ -#pragma once -#include -#include -#include -#include "archive.h" - -class GobMemoryArchive; - -class GobArchive : public Archive -{ -public: - friend GobMemoryArchive; -public: - GobArchive() : Archive(ARCHIVE_GOB), m_archiveOpen(false), m_curFile(-1) {} - ~GobArchive() override; - - // Archive - bool create(const char *archivePath) override; - bool open(const char *archivePath) override; - void close() override; - - // File Access - bool openFile(const char *file) override; - bool openFile(u32 index) override; - void closeFile() override; - - u32 getFileIndex(const char* file) override; - bool fileExists(const char *file) override; - bool fileExists(u32 index) override; - - size_t getFileLength() override; - size_t readFile(void *data, size_t size) override; - bool seekFile(s32 offset, s32 origin = SEEK_SET) override; - size_t getLocInFile() override; - - // Directory - u32 getFileCount() override; - const char* getFileName(u32 index) override; - size_t getFileLength(u32 index) override; - - // Validation - static bool validate(const char *archivePath, s32 minFileCount = 1); - - // Edit - void addFile(const char* fileName, const char* filePath) override; - -private: - #pragma pack(push) - #pragma pack(1) - - typedef struct - { - char GOB_MAGIC[4]; - u32 MASTERX; // offset to GOB_Index_t - } GOB_Header_t; - - typedef struct - { - u32 IX; // offset to the start of the file. - u32 LEN; // length of the file. - char NAME[13]; // file name. - } GOB_Entry_t; - - typedef struct - { - u32 MASTERN; // num files - GOB_Entry_t *entries; - } GOB_Index_t; - - #pragma pack(pop) - - FileStream m_file; - bool m_archiveOpen; - - GOB_Header_t m_header; - GOB_Index_t m_fileList; - s32 m_curFile; -}; diff --git a/components/darkforces/tfe/TFE_Archive/gobMemoryArchive.h b/components/darkforces/tfe/TFE_Archive/gobMemoryArchive.h deleted file mode 100644 index a15494ca..00000000 --- a/components/darkforces/tfe/TFE_Archive/gobMemoryArchive.h +++ /dev/null @@ -1,53 +0,0 @@ -#pragma once -// A GOB archive fully loaded into memory. - -#include -#include -#include -#include "archive.h" -#include "gobArchive.h" - -class GobMemoryArchive : public Archive -{ -public: - GobMemoryArchive() : Archive(ARCHIVE_GOB), m_buffer(nullptr), m_size(0), m_readLoc(0), m_archiveOpen(false), m_curFile(-1) {} - ~GobMemoryArchive() override; - - // Archive - bool create(const char *archivePath) override; - bool open(const char *archivePath) override; - bool open(const u8* buffer, size_t size); - void close() override; - - // File Access - bool openFile(const char *file) override; - bool openFile(u32 index) override; - void closeFile() override; - - u32 getFileIndex(const char* file) override; - bool fileExists(const char *file) override; - bool fileExists(u32 index) override; - - size_t getFileLength() override; - size_t readFile(void *data, size_t size) override; - bool seekFile(s32 offset, s32 origin = SEEK_SET) override; - size_t getLocInFile() override; - - // Directory - u32 getFileCount() override; - const char* getFileName(u32 index) override; - size_t getFileLength(u32 index) override; - - // Edit - void addFile(const char* fileName, const char* filePath) override; - -private: - const u8* m_buffer; - size_t m_size; - size_t m_readLoc; - bool m_archiveOpen; - - GobArchive::GOB_Header_t* m_header; - GobArchive::GOB_Index_t m_fileList; - s32 m_curFile; -}; diff --git a/components/darkforces/tfe/TFE_Archive/labArchive.cpp b/components/darkforces/tfe/TFE_Archive/labArchive.cpp deleted file mode 100644 index 4c8d92cd..00000000 --- a/components/darkforces/tfe/TFE_Archive/labArchive.cpp +++ /dev/null @@ -1,224 +0,0 @@ -#include - -#include -#include -#include "labArchive.h" -#include -#include - -LabArchive::~LabArchive() -{ - close(); -} - -bool LabArchive::create(const char *archivePath) -{ - // STUB: No facilities to write Lab files yet. - return false; -} - -bool LabArchive::open(const char *archivePath) -{ - m_archiveOpen = m_file.open(archivePath, Stream::MODE_READ); - m_curFile = -1; - m_fileOffset = 0; - if (!m_archiveOpen) { return false; } - - // Read the directory. - m_file.readBuffer(&m_header, sizeof(LAB_Header_t)); - m_header.version = TFE_Endian::le32_to_cpu(m_header.version); - m_header.fileCount = TFE_Endian::le32_to_cpu(m_header.fileCount); - m_header.stringTableSize = TFE_Endian::le32_to_cpu(m_header.stringTableSize); - m_stringTable = new char[m_header.stringTableSize + 1]; - m_entries = new LAB_Entry_t[m_header.fileCount]; - - // Read the file entries. - m_file.readBuffer(m_entries, sizeof(LAB_Entry_t), m_header.fileCount); - for (u32 i = 0; i < m_header.fileCount; i++) - { - m_entries[i].nameOffset = TFE_Endian::le32_to_cpu(m_entries[i].nameOffset); - m_entries[i].dataOffset = TFE_Endian::le32_to_cpu(m_entries[i].dataOffset); - m_entries[i].len = TFE_Endian::le32_to_cpu(m_entries[i].len); - } - - // Read string table. - m_file.readBuffer(m_stringTable, m_header.stringTableSize); - m_file.close(); - - strcpy(m_archivePath, archivePath); - - return true; -} - -void LabArchive::close() -{ - m_file.close(); - m_archiveOpen = false; - delete[] m_entries; - delete[] m_stringTable; -} - -// File Access -bool LabArchive::openFile(const char *file) -{ - if (!m_archiveOpen) { return false; } - - m_file.open(m_archivePath, Stream::MODE_READ); - m_curFile = -1; - m_fileOffset = 0; - - //search for this file. - for (u32 i = 0; i < m_header.fileCount; i++) - { - if (strcasecmp(file, &m_stringTable[m_entries[i].nameOffset]) == 0) - { - m_curFile = i; - break; - } - } - - if (m_curFile == -1) - { - m_file.close(); - TFE_System::logWrite(LOG_ERROR, "GOB", "Failed to load \"%s\" from \"%s\"", file, m_archivePath); - } - else - { - m_file.seek(m_entries[m_curFile].dataOffset); - } - return m_curFile > -1 ? true : false; -} - -bool LabArchive::openFile(u32 index) -{ - if (index >= getFileCount()) { return false; } - - m_curFile = s32(index); - m_fileOffset = 0; - m_file.open(m_archivePath, Stream::MODE_READ); - m_file.seek(m_entries[m_curFile].dataOffset); - return true; -} - -void LabArchive::closeFile() -{ - m_curFile = -1; - m_file.close(); -} - -u32 LabArchive::getFileIndex(const char* file) -{ - if (!m_archiveOpen) { return INVALID_FILE; } - m_curFile = -1; - - //search for this file. - for (u32 i = 0; i < m_header.fileCount; i++) - { - if (strcasecmp(file, &m_stringTable[m_entries[i].nameOffset]) == 0) - { - return i; - } - } - return INVALID_FILE; -} - -bool LabArchive::fileExists(const char *file) -{ - if (!m_archiveOpen) { return false; } - m_curFile = -1; - - //search for this file. - for (u32 i = 0; i < m_header.fileCount; i++) - { - if (strcasecmp(file, &m_stringTable[m_entries[i].nameOffset]) == 0) - { - return true; - } - } - return false; -} - -bool LabArchive::fileExists(u32 index) -{ - if (index >= getFileCount()) { return false; } - return true; -} - -size_t LabArchive::getFileLength() -{ - if (m_curFile < 0) { return 0; } - return getFileLength(m_curFile); -} - -size_t LabArchive::readFile(void *data, size_t size) -{ - if (m_curFile < 0) { return false; } - if (size == 0) { size = m_entries[m_curFile].len; } - const size_t sizeToRead = std::min(size, (size_t)m_entries[m_curFile].len); - - size_t bytesRead = m_file.readBuffer(data, (u32)sizeToRead); - m_fileOffset += (s32)sizeToRead; - return bytesRead; -} - -bool LabArchive::seekFile(s32 offset, s32 origin) -{ - if (m_curFile < 0) { return false; } - size_t size = m_entries[m_curFile].len; - - switch (origin) - { - case SEEK_SET: - { - m_fileOffset = offset; - } break; - case SEEK_CUR: - { - m_fileOffset += offset; - } break; - case SEEK_END: - { - m_fileOffset = (s32)size - offset; - } break; - } - assert(m_fileOffset <= size && m_fileOffset >= 0); - if (m_fileOffset > size || m_fileOffset < 0) - { - m_fileOffset = 0; - return false; - } - - m_file.seek(m_entries[m_curFile].dataOffset + m_fileOffset); - return true; -} - -size_t LabArchive::getLocInFile() -{ - return m_fileOffset; -} - -// Directory -u32 LabArchive::getFileCount() -{ - if (!m_archiveOpen) { return 0; } - return m_header.fileCount; -} - -const char* LabArchive::getFileName(u32 index) -{ - if (!m_archiveOpen) { return nullptr; } - return &m_stringTable[m_entries[index].nameOffset]; -} - -size_t LabArchive::getFileLength(u32 index) -{ - if (!m_archiveOpen) { return 0; } - return m_entries[index].len; -} - -// Edit -void LabArchive::addFile(const char* fileName, const char* filePath) -{ - // STUB: No ability to add files yet. - assert(0); -} diff --git a/components/darkforces/tfe/TFE_Archive/labArchive.h b/components/darkforces/tfe/TFE_Archive/labArchive.h deleted file mode 100644 index 67a6961b..00000000 --- a/components/darkforces/tfe/TFE_Archive/labArchive.h +++ /dev/null @@ -1,68 +0,0 @@ -#pragma once -#include -#include -#include -#include "archive.h" - -class LabArchive : public Archive -{ -public: - LabArchive() : Archive(ARCHIVE_LAB), m_archiveOpen(false), m_curFile(-1) {} - ~LabArchive() override; - - // Archive - bool create(const char *archivePath) override; - bool open(const char *archivePath) override; - void close() override; - - // File Access - bool openFile(const char *file) override; - bool openFile(u32 index) override; - void closeFile() override; - - u32 getFileIndex(const char* file) override; - bool fileExists(const char *file) override; - bool fileExists(u32 index) override; - - size_t getFileLength() override; - size_t readFile(void *data, size_t size) override; - bool seekFile(s32 offset, s32 origin = SEEK_SET) override; - size_t getLocInFile() override; - - // Directory - u32 getFileCount() override; - const char* getFileName(u32 index) override; - size_t getFileLength(u32 index) override; - - // Edit - void addFile(const char* fileName, const char* filePath) override; - -private: - #pragma pack(push) - #pragma pack(1) - struct LAB_Header_t - { - char LAB_MAGIC[4]; - u32 version; // 0x10000 for Outlaws - u32 fileCount; - u32 stringTableSize; - }; - - struct LAB_Entry_t - { - u32 nameOffset; - u32 dataOffset; - u32 len; - u8 typeId[4]; - }; - #pragma pack(pop) - - FileStream m_file; - bool m_archiveOpen; - - LAB_Header_t m_header; - char* m_stringTable; - LAB_Entry_t* m_entries; - - s32 m_curFile; -}; diff --git a/components/darkforces/tfe/TFE_Archive/lfdArchive.cpp b/components/darkforces/tfe/TFE_Archive/lfdArchive.cpp deleted file mode 100644 index 0d09298d..00000000 --- a/components/darkforces/tfe/TFE_Archive/lfdArchive.cpp +++ /dev/null @@ -1,256 +0,0 @@ -#include - -#include -#include -#include "lfdArchive.h" -#include -#include - -LfdArchive::~LfdArchive() -{ - close(); -} - -bool LfdArchive::create(const char *archivePath) -{ - m_archiveOpen = m_file.open(archivePath, Stream::MODE_WRITE); - m_curFile = -1; - m_fileOffset = 0; - if (!m_archiveOpen) { return false; } - - // Write the directory. - LFD_Entry_t root = { 0 }; - m_file.writeBuffer(&root, sizeof(LFD_Entry_t)); - m_fileList.MASTERN = 0; - m_fileList.entries = nullptr; - - strcpy(m_archivePath, archivePath); - m_file.close(); - - return true; -} - -bool LfdArchive::open(const char *archivePath) -{ - m_archiveOpen = m_file.open(archivePath, Stream::MODE_READ); - m_curFile = -1; - m_fileOffset = 0; - if (!m_archiveOpen) { return false; } - - // Read the directory. - LFD_Entry_t root, entry; - m_file.readBuffer(&root, sizeof(LFD_Entry_t)); - root.LENGTH = TFE_Endian::le32_to_cpu(root.LENGTH); - m_fileList.MASTERN = root.LENGTH / sizeof(LFD_Entry_t); - m_fileList.entries = new LFD_EntryFinal_t[m_fileList.MASTERN]; - - s32 IX = sizeof(LFD_Entry_t) + root.LENGTH; - for (s32 i = 0; i < m_fileList.MASTERN; i++) - { - m_file.readBuffer(&entry, sizeof(LFD_Entry_t)); - entry.LENGTH = TFE_Endian::le32_to_cpu(entry.LENGTH); - - char name[9] = { 0 }; - char ext[5] = { 0 }; - memcpy(name, entry.NAME, 8); - memcpy(ext, entry.TYPE, 4); - ext[4] = 0; - - sprintf(m_fileList.entries[i].NAME, "%s.%s", name, ext); - m_fileList.entries[i].LENGTH = entry.LENGTH; - m_fileList.entries[i].IX = IX + sizeof(LFD_Entry_t); - - IX += sizeof(LFD_Entry_t) + entry.LENGTH; - } - - strcpy(m_archivePath, archivePath); -#ifndef TFE_ESPBOX - m_file.close(); -#endif - - return true; -} - -void LfdArchive::close() -{ - m_file.close(); - m_archiveOpen = false; - - if (m_fileList.entries) - { - delete[] m_fileList.entries; - m_fileList.entries = nullptr; - } -} - -// File Access -bool LfdArchive::openFile(const char *file) -{ - if (!m_archiveOpen) { return false; } - -#ifndef TFE_ESPBOX - m_file.open(m_archivePath, Stream::MODE_READ); -#endif - m_curFile = -1; - m_fileOffset = 0; - - //search for this file. - for (s32 i = 0; i < m_fileList.MASTERN; i++) - { - if (strcasecmp(file, m_fileList.entries[i].NAME) == 0) - { - m_curFile = i; - break; - } - } - - if (m_curFile == -1) - { -#ifndef TFE_ESPBOX - m_file.close(); -#endif - TFE_System::logWrite(LOG_ERROR, "LFD", "Failed to load \"%s\" from \"%s\"", file, m_archivePath); - } - else - { - m_file.seek(m_fileList.entries[m_curFile].IX); - } - return m_curFile > -1 ? true : false; -} - -bool LfdArchive::openFile(u32 index) -{ - if (index >= getFileCount()) { return false; } - - m_curFile = s32(index); - m_fileOffset = 0; -#ifndef TFE_ESPBOX - m_file.open(m_archivePath, Stream::MODE_READ); -#endif - m_file.seek(m_fileList.entries[m_curFile].IX); - return true; -} - -void LfdArchive::closeFile() -{ - m_curFile = -1; -#ifndef TFE_ESPBOX - m_file.close(); -#endif -} - -u32 LfdArchive::getFileIndex(const char* file) -{ - if (!m_archiveOpen) { return INVALID_FILE; } - m_curFile = -1; - - //search for this file. - for (s32 i = 0; i < m_fileList.MASTERN; i++) - { - if (strcasecmp(file, m_fileList.entries[i].NAME) == 0) - { - return i; - } - } - return INVALID_FILE; -} - -bool LfdArchive::fileExists(const char *file) -{ - if (!m_archiveOpen) { return false; } - m_curFile = -1; - - //search for this file. - for (s32 i = 0; i < m_fileList.MASTERN; i++) - { - if (strcasecmp(file, m_fileList.entries[i].NAME) == 0) - { - return true; - } - } - return false; -} - -bool LfdArchive::fileExists(u32 index) -{ - if (index >= getFileCount()) { return false; } - return true; -} - -size_t LfdArchive::getFileLength() -{ - if (m_curFile < 0) { return 0; } - return getFileLength(m_curFile); -} - -size_t LfdArchive::readFile(void *data, size_t size) -{ - if (m_curFile < 0) { return false; } - if (size == 0) { size = m_fileList.entries[m_curFile].LENGTH; } - const size_t sizeToRead = std::min(size, (size_t)m_fileList.entries[m_curFile].LENGTH); - - size_t bytesRead = m_file.readBuffer(data, (u32)sizeToRead); - m_fileOffset += (s32)sizeToRead; - return bytesRead; -} - -bool LfdArchive::seekFile(s32 offset, s32 origin) -{ - if (m_curFile < 0) { return false; } - size_t size = m_fileList.entries[m_curFile].LENGTH; - - switch (origin) - { - case SEEK_SET: - { - m_fileOffset = offset; - } break; - case SEEK_CUR: - { - m_fileOffset += offset; - } break; - case SEEK_END: - { - m_fileOffset = (s32)size - offset; - } break; - } - assert(m_fileOffset <= size && m_fileOffset >= 0); - if (m_fileOffset > size || m_fileOffset < 0) - { - m_fileOffset = 0; - return false; - } - - m_file.seek(m_fileList.entries[m_curFile].IX + m_fileOffset); - return true; -} - -size_t LfdArchive::getLocInFile() -{ - return m_fileOffset; -} - -// Directory -u32 LfdArchive::getFileCount() -{ - if (!m_archiveOpen) { return 0; } - return (u32)m_fileList.MASTERN; -} - -const char* LfdArchive::getFileName(u32 index) -{ - if (!m_archiveOpen) { return nullptr; } - return m_fileList.entries[index].NAME; -} - -size_t LfdArchive::getFileLength(u32 index) -{ - if (!m_archiveOpen) { return 0; } - return m_fileList.entries[index].LENGTH; -} - -// Edit -void LfdArchive::addFile(const char* fileName, const char* filePath) -{ - -} diff --git a/components/darkforces/tfe/TFE_Archive/lfdArchive.h b/components/darkforces/tfe/TFE_Archive/lfdArchive.h deleted file mode 100644 index bafef5b8..00000000 --- a/components/darkforces/tfe/TFE_Archive/lfdArchive.h +++ /dev/null @@ -1,77 +0,0 @@ -#pragma once -/////////////////////////////////////////////// -// LFD Archives are very similar to GOB -// but have a different directory structure. -/////////////////////////////////////////////// - -#include -#include -#include -#include "archive.h" - -class LfdArchive : public Archive -{ -public: - LfdArchive() : Archive(ARCHIVE_LFD), m_archiveOpen(false), m_curFile(-1) {} - ~LfdArchive() override; - - // Archive - bool create(const char *archivePath) override; - bool open(const char *archivePath) override; - void close() override; - - // File Access - bool openFile(const char *file) override; - bool openFile(u32 index) override; - void closeFile() override; - - bool fileExists(const char *file) override; - bool fileExists(u32 index) override; - u32 getFileIndex(const char* file) override; - - size_t getFileLength() override; - size_t readFile(void *data, size_t size) override; - bool seekFile(s32 offset, s32 origin = SEEK_SET) override; - size_t getLocInFile() override; - - // Directory - u32 getFileCount() override; - const char* getFileName(u32 index) override; - size_t getFileLength(u32 index) override; - - // Edit - void addFile(const char* fileName, const char* filePath) override; - -private: - #pragma pack(push) - #pragma pack(1) - - typedef struct - { - char TYPE[4]; - char NAME[8]; - u32 LENGTH; //length of the file. - } LFD_Entry_t; - - typedef struct - { - char NAME[16]; - u32 LENGTH; //length of the file. - u32 IX; - } LFD_EntryFinal_t; - - typedef struct - { - u32 MASTERN; //num files - LFD_EntryFinal_t *entries; - } LFD_Index_t; - - #pragma pack(pop) - - FileStream m_file; - bool m_archiveOpen; - - LFD_Entry_t m_header; - LFD_Index_t m_fileList; - s32 m_curFile; -}; diff --git a/components/darkforces/tfe/TFE_Archive/zipArchive.h b/components/darkforces/tfe/TFE_Archive/zipArchive.h deleted file mode 100644 index b8b37f01..00000000 --- a/components/darkforces/tfe/TFE_Archive/zipArchive.h +++ /dev/null @@ -1,54 +0,0 @@ -#pragma once -#include "archive.h" -#include - -class ZipArchive : public Archive -{ -public: - ZipArchive() : Archive(ARCHIVE_ZIP), m_entryCount(0), m_curFile(INVALID_FILE), m_entries(nullptr), m_fileHandle(nullptr) {} - ~ZipArchive() override; - - // Archive - bool create(const char *archivePath) override; - bool open(const char *archivePath) override; - void close() override; - - // File Access - bool openFile(const char *file) override; - bool openFile(u32 index) override; - void closeFile() override; - - bool fileExists(const char *file) override; - bool fileExists(u32 index) override; - u32 getFileIndex(const char* file) override; - - size_t getFileLength() override; - size_t readFile(void *data, size_t size) override; - bool seekFile(s32 offset, s32 origin = SEEK_SET) override; - size_t getLocInFile() override; - - // Directory - u32 getFileCount() override; - const char* getFileName(u32 index) override; - size_t getFileLength(u32 index) override; - - // Edit - void addFile(const char* fileName, const char* filePath) override; - -private: - struct ZipEntry - { - std::string name; - size_t length; - bool isDir; - }; - - s32 m_entryCount; - u32 m_curFile; - ZipEntry* m_entries; - void* m_fileHandle; - - u8* m_tempBuffer = nullptr; - size_t m_tempBufferSize = 0; - bool m_entryRead; -}; diff --git a/components/darkforces/tfe/TFE_Asset/assetSystem.cpp b/components/darkforces/tfe/TFE_Asset/assetSystem.cpp deleted file mode 100644 index a285fb67..00000000 --- a/components/darkforces/tfe/TFE_Asset/assetSystem.cpp +++ /dev/null @@ -1,114 +0,0 @@ -#include "assetSystem.h" -#include -#include - -namespace TFE_AssetSystem -{ - static Archive* s_customArchive = nullptr; - - void setCustomArchive(Archive* archive) - { - s_customArchive = archive; - } - - void clearCustomArchive() - { - s_customArchive = nullptr; - } - - Archive* getCustomArchive() - { - return s_customArchive; - } - - Archive* openArchiveFile(const char* defaultArchive, ArchiveType type, const char* filename) - { - // First try reading from the custom Archive, if there is one. - if (s_customArchive) - { - const u32 index = s_customArchive->getFileIndex(filename); - if (index != INVALID_FILE && s_customArchive->openFile(index)) - { - return s_customArchive; - } - } - - // Otherwise read from the specified GOB archive. - char gobPath[TFE_MAX_PATH]; - TFE_Paths::appendPath(PATH_SOURCE_DATA, defaultArchive, gobPath); - Archive* archive = Archive::getArchive(type, defaultArchive, gobPath); - if (!archive) - { - TFE_System::logWrite(LOG_ERROR, "Archive", "Cannot open source archive file \"%s\"", gobPath); - return nullptr; - } - - if (!archive->openFile(filename)) - { - return nullptr; - } - return archive; - } - - bool readAssetFromArchive(const char* defaultArchive, ArchiveType type, const char* filename, std::vector& buffer) - { - Archive* archive = openArchiveFile(defaultArchive, type, filename); - if (archive) - { - // Read the file into memory for parsing. - const size_t len = archive->getFileLength(); - buffer.resize(len); - archive->readFile(buffer.data(), len); - archive->closeFile(); - return true; - } - return false; - } - - bool readAssetFromArchive(const char* defaultArchive, ArchiveType type, const char* filename, std::vector& buffer) - { - Archive* archive = openArchiveFile(defaultArchive, type, filename); - if (archive) - { - // Read the file into memory for parsing. - const size_t len = archive->getFileLength(); - buffer.resize(len); - archive->readFile(buffer.data(), len); - archive->closeFile(); - return true; - } - return false; - } - - bool readAssetFromArchive(const char* defaultArchive, const char* filename, std::vector& buffer) - { - const ArchiveType type = Archive::getArchiveTypeFromName(defaultArchive); - Archive* archive = openArchiveFile(defaultArchive, type, filename); - if (archive) - { - // Read the file into memory for parsing. - const size_t len = archive->getFileLength(); - buffer.resize(len); - archive->readFile(buffer.data(), len); - archive->closeFile(); - return true; - } - return false; - } - - bool readAssetFromArchive(const char* defaultArchive, const char* filename, std::vector& buffer) - { - const ArchiveType type = Archive::getArchiveTypeFromName(defaultArchive); - Archive* archive = openArchiveFile(defaultArchive, type, filename); - if (archive) - { - // Read the file into memory for parsing. - const size_t len = archive->getFileLength(); - buffer.resize(len); - archive->readFile(buffer.data(), len); - archive->closeFile(); - return true; - } - return false; - } -} diff --git a/components/darkforces/tfe/TFE_Asset/assetSystem.h b/components/darkforces/tfe/TFE_Asset/assetSystem.h deleted file mode 100644 index b86f0782..00000000 --- a/components/darkforces/tfe/TFE_Asset/assetSystem.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Asset System -// Handles global asset state, such as custom archive sources. -////////////////////////////////////////////////////////////////////// -#include -#include -#include - -namespace TFE_AssetSystem -{ - void setCustomArchive(Archive* archive); - void clearCustomArchive(); - - Archive* getCustomArchive(); - bool readAssetFromArchive(const char* defaultArchive, ArchiveType type, const char* filename, std::vector& buffer); - bool readAssetFromArchive(const char* defaultArchive, ArchiveType type, const char* filename, std::vector& buffer); - bool readAssetFromArchive(const char* defaultArchive, const char* filename, std::vector& buffer); - bool readAssetFromArchive(const char* defaultArchive, const char* filename, std::vector& buffer); -} diff --git a/components/darkforces/tfe/TFE_Asset/colormapAsset.h b/components/darkforces/tfe/TFE_Asset/colormapAsset.h deleted file mode 100644 index 62fac5ed..00000000 --- a/components/darkforces/tfe/TFE_Asset/colormapAsset.h +++ /dev/null @@ -1,34 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Level/Map -// Handles the following: -// 1. Parsing the level data (.LEV) -// 2. Runtime storage and manipulation of level data -// (vertices, lines, sectors) -////////////////////////////////////////////////////////////////////// -#include - -#define COLOR_COUNT 256 -#define LIGHT_LEVELS 32 -#define LIGHT_SOURCE_LEVELS 128 - -struct Palette256; - -struct ColorMap -{ - // Color(L,C) = colorMap[COLOR_COUNT * L + C] - // where L = light level (0 - LIGHT_LEVELS - 1) - // C = color (0 - COLOR_COUNT - 1) - u8 colorMap[COLOR_COUNT * LIGHT_LEVELS]; - // Light source ramp where 0 = closest, LIGHT_SOURCE_LEVELS - 1 = farthest. - u8 lightSourceRamp[LIGHT_SOURCE_LEVELS]; -}; - -namespace TFE_ColorMap -{ - ColorMap* allocate(const char* name); - ColorMap* get(const char* name); - void freeAll(); - - ColorMap* generateColorMap(const char* newFile, const Palette256* pal); -} diff --git a/components/darkforces/tfe/TFE_Asset/dfKeywords.cpp b/components/darkforces/tfe/TFE_Asset/dfKeywords.cpp deleted file mode 100644 index c4d65c92..00000000 --- a/components/darkforces/tfe/TFE_Asset/dfKeywords.cpp +++ /dev/null @@ -1,248 +0,0 @@ -#include - -#include "dfKeywords.h" -#include - -// These strings are taken directly from the Dark Forces EXE. -static const char* c_keywords[] = -{ - "VISIBLE:", - "SHADED:", - "LIGHT:", - "PARENT:", - "D_X:", - "D_Y:", - "D_Z:", - "D_PITCH:", - "D_YAW:", - "D_ROLL:", - "D_VIEW_PITCH:", - "D_VIEW_YAW:", - "D_VIEW_ROLL:", - "VIEW_PITCH:", - "VIEW_YAW:", - "VIEW_ROLL:", - "TYPE:", - "LOGIC:", - "VUE:", - "VUE_APPEND:", - "EYE:", - "BOSS:", - "UPDATE", - "EYE_D_XYZ:", - "EYE_D_PYR:", - "SYNC:", - "FRAME_RATE:", - "START:", - "STOP_Y:", - "STOP:", - "SPEED:", - "MASTER:", - "ANGLE:", - "PAUSE:", - "ADJOIN:", - "TEXTURE:", - "SLAVE:", - "TRIGGER_ACTION:", - "CONDITION:", - "CLIENT:", - "MESSAGE:", - "TEXT:", - "EVENT:", - "EVENT_MASK:", - "ENTITY_MASK:", - "OBJECT_MASK:", - "CENTER:", - "KEY", - "ADDON:", - "FLAGS:", - "SOUND:", - "PAGE:", - "SOUND", - "SYSTEM", - "SAFE", - "LEVEL", - "AMB_SOUND:", - "ELEVATOR", - "BASIC", - "BASIC_AUTO", - "ENCLOSED", - "INV", - "MID", - "DOOR", - "DOOR_INV", - "DOOR_MID", - "MORPH_SPIN1", - "MORPH_SPIN2", - "MORPH_MOVE1", - "MORPH_MOVE2", - "MOVE_CEILING", - "MOVE_FLOOR", - "MOVE_FC", - "MOVE_OFFSET", - "MOVE_WALL", - "ROTATE_WALL", - "SCROLL_WALL", - "SCROLL_FLOOR", - "SCROLL_CEILING", - "CHANGE_LIGHT", - "CHANGE_WALL_LIGHT", - "TRIGGER", - "SWITCH1", - "TOGGLE", - "SINGLE", - "STANDARD", - "TELEPORTER", - "ENTITY_ENTER", - "SECTOR", - "LINE", - "TARGET:", - "MOVE:", - "CHUTE", - "TRIGGER", // 93 -- repeated for some reason. - "NEXT_STOP", - "PREV_STOP", - "GOTO_STOP", - "MASTER_ON", - "MASTER_OFF", - "DONE", - "SET_BITS", - "CLEAR_BITS", - "COMPLETE", - "LIGHTS", - "WAKEUP", - "NONE", - "STORM", - "ENTITY", - "PLAYER", - "TROOP", - "STORM1", - "INT_DROID", - "PROBE_DROID", - "D_TROOP1", - "D_TROOP2", - "D_TROOP3", - "BOBA_FETT", - "COMMANDO", - "I_OFFICER", - "I_OFFICER1", - "I_OFFICER2", - "I_OFFICER3", - "I_OFFICER4", - "I_OFFICER5", - "I_OFFICER6", - "I_OFFICER7", - "I_OFFICER8", - "I_OFFICER9", - "I_OFFICERR", - "I_OFFICERY", - "I_OFFICERB", - "G_GUARD", - "REE_YEES", - "REE_YEES2", - "BOSSK", - "BARREL", - "LAND_MINE", - "KELL", - "SEWER1", - "REMOTE", - "TURRET", - "MOUSEBOT", - "WELDER", - "SCENERY", - "ANIM", - "KEY:", - "GENERATOR", - "TRUE", - "FALSE", - "3D", - "SPRITE", - "FRAME", - "SPIRIT", - "ITEM", - "DISPATCH", - "RADIUS:", - "HEIGHT:", - "BATTERY", - "BLUE", - "CANNON", - "CLEATS", - "CODE1", - "CODE2", - "CODE3", - "CODE4", - "CODE5", - "CODE6", - "CODE7", - "CODE8", - "CODE9", - "CONCUSSION", - "DETONATOR", - "DETONATORS", - "DT_WEAPON", - "DATATAPE", - "ENERGY", - "FUSION", - "GOGGLES", - "MASK", - "MINE", - "MINES", - "MISSILE", - "MISSILES", - "MORTAR", - "NAVA", - "PHRIK", - "PLANS", - "PLASMA", - "POWER", - "RED", - "RIFLE", - "SHELL", - "SHELLS", - "SHIELD", - "INVINCIBLE", - "REVIVE", - "SUPERCHARGE", - "LIFE", - "MEDKIT", - "PILE", - "YELLOW", - "AUTOGUN", - "DELAY:", - "INTERVAL:", - "MAX_ALIVE:", - "MIN_DIST:", - "MAX_DIST:", - "NUM_TERMINATE:", - "WANDER_TIME:", - "PLUGIN:", - "THINKER", - "FOLLOW", - "FOLLOW_Y", - "RANDOM_YAW", - "MOVER", - "SHAKER", - "PERSONALITY", - "SEQEND", - "M_TRIGGER", -}; - -#define KEYWORD_COUNT TFE_ARRAYSIZE(c_keywords) - -KEYWORD getKeywordIndex(const char* keywordString) -{ - s32 result = -1; - for (s32 i = 0; i < KEYWORD_COUNT; i++) - { - const char* keyword = c_keywords[i]; - if (toupper(keywordString[0]) == keyword[0]) - { - if (!strcasecmp(keywordString, keyword)) - { - result = i; - break; - } - } - } - return KEYWORD(result); -} diff --git a/components/darkforces/tfe/TFE_Asset/dfKeywords.h b/components/darkforces/tfe/TFE_Asset/dfKeywords.h deleted file mode 100644 index 20485904..00000000 --- a/components/darkforces/tfe/TFE_Asset/dfKeywords.h +++ /dev/null @@ -1,238 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Keyword Table. -// This table is used when parsing Dark Forces data files. The list of -// strings was extracted from the DF executable. -////////////////////////////////////////////////////////////////////// -#include -#include -#include - -// Keywords used by Dark Forces. -// Note: there are some repeats, so there are a few elements called KW_xxx2; for example KW_KEY2 -enum KEYWORD -{ - KW_UNKNOWN = -1, - KW_VISIBLE = 0, // not implemented in DF - KW_SHADED, // not implemented in DF - KW_LIGHT, // not implemented in DF - KW_PARENT, // not implemented in DF - KW_D_X, // not implemented in DF - KW_D_Y, // not implemented in DF - KW_D_Z, // not implemented in DF - KW_D_PITCH, // logics - KW_D_YAW, // logics - KW_D_ROLL, // logics - KW_D_VIEW_PITCH, // not implemented in DF - KW_D_VIEW_YAW, // not implemented in DF - KW_D_VIEW_ROLL, // not implemented in DF - KW_VIEW_PITCH, // not implemented in DF - KW_VIEW_YAW, // not implemented in DF - KW_VIEW_ROLL, // not implemented in DF - KW_TYPE, - KW_LOGIC, // "TYPE" and "LOGIC" are synonymous in DF - KW_VUE, // logics - KW_VUE_APPEND, // logics - KW_EYE, // logics - KW_BOSS, // logics - KW_UPDATE, // logics - KW_EYE_D_XYZ, // not implemented in DF - KW_EYE_D_PYR, // not implemented in DF - KW_SYNC, // not implemented in DF - KW_FRAME_RATE, // logics - KW_START, // INF - KW_STOP_Y, // not implemented in DF - KW_STOP, // INF - KW_SPEED, // INF - KW_MASTER, // INF - KW_ANGLE, // INF - KW_PAUSE, // logics - KW_ADJOIN, // INF - KW_TEXTURE, // INF - KW_SLAVE, // INF - KW_TRIGGER_ACTION, // not implemented in DF - KW_CONDITION, // not implemented in DF - KW_CLIENT, // INF - KW_MESSAGE, // INF - KW_TEXT, // INF - KW_EVENT, // INF - KW_EVENT_MASK, // INF - KW_ENTITY_MASK, // INF - KW_OBJECT_MASK, // INF - KW_CENTER, // INF - KW_KEY, // logics - KW_ADDON, // INF - KW_FLAGS, // INF - KW_SOUND_COLON, // INF - KW_PAGE, // INF - KW_SOUND, - KW_SYSTEM, // INF - KW_SAFE, - KW_LEVEL, // INF - KW_AMB_SOUND, // INF - KW_ELEVATOR, // INF - KW_BASIC, // INF - KW_BASIC_AUTO, // INF - KW_ENCLOSED, // INF (unimplemented) - KW_INV, // INF - KW_MID, // INF (unimplemented) - KW_DOOR, // INF - KW_DOOR_INV, // INF - KW_DOOR_MID, // INF - KW_MORPH_SPIN1, // INF - KW_MORPH_SPIN2, // INF - KW_MORPH_MOVE1, // INF - KW_MORPH_MOVE2, // INF - KW_MOVE_CEILING, // INF - KW_MOVE_FLOOR, // INF - KW_MOVE_FC, // INF - KW_MOVE_OFFSET, // INF - KW_MOVE_WALL, // INF - KW_ROTATE_WALL, // INF - KW_SCROLL_WALL, // INF - KW_SCROLL_FLOOR, // INF - KW_SCROLL_CEILING, // INF - KW_CHANGE_LIGHT, // INF - KW_CHANGE_WALL_LIGHT, // INF - KW_TRIGGER, // This is the trigger ID that will be found. - KW_SWITCH1, // INF - KW_TOGGLE, // INF - KW_SINGLE, // INF - KW_STANDARD, // INF - KW_TELEPORTER, // INF - KW_ENTITY_ENTER, // not implemented in DF - KW_SECTOR, // INF - KW_LINE, // INF - KW_TARGET, // INF - KW_MOVE, // INF for Teleporter basic, which is implemented but unused in game - KW_CHUTE, // INF - KW_TRIGGER2, // This is a repeat and should never be found directly. - KW_NEXT_STOP, // INF - KW_PREV_STOP, // INF - KW_GOTO_STOP, // INF - KW_MASTER_ON, // INF - KW_MASTER_OFF, // INF - KW_DONE, // INF - KW_SET_BITS, // INF - KW_CLEAR_BITS, // INF - KW_COMPLETE, // INF - KW_LIGHTS, // INF - KW_WAKEUP, // INF - KW_NONE, - KW_STORM, // not implemented in DF - KW_ENTITY, // not implemented in DF - KW_PLAYER, // logics - KW_TROOP, // logics (shared implementation with STORM1) - KW_STORM1, // logics - KW_INT_DROID, // logics - KW_PROBE_DROID, // logics - KW_D_TROOP1, // logics - KW_D_TROOP2, // logics - KW_D_TROOP3, // logics - KW_BOBA_FETT, // logics - KW_COMMANDO, // logics - KW_I_OFFICER, // logics - KW_I_OFFICER1, // logics - KW_I_OFFICER2, // logics - KW_I_OFFICER3, // logics - KW_I_OFFICER4, // logics - KW_I_OFFICER5, // logics - KW_I_OFFICER6, // logics - KW_I_OFFICER7, // logics - KW_I_OFFICER8, // logics - KW_I_OFFICER9, // logics - KW_I_OFFICERR, // logics - KW_I_OFFICERY, // logics - KW_I_OFFICERB, // logics - KW_G_GUARD, // logics - KW_REE_YEES, // logics - KW_REE_YEES2, // logics - KW_BOSSK, // logics - KW_BARREL, // logics - KW_LAND_MINE, // logics - KW_KELL, // logics - KW_SEWER1, // logics - KW_REMOTE, // logics - KW_TURRET, // logics - KW_MOUSEBOT, // logics - KW_WELDER, // logics - KW_SCENERY, // logics - KW_ANIM, // logics - KW_KEY_COLON, // INF - KW_GENERATOR, // logics - KW_TRUE, - KW_FALSE, - KW_3D, - KW_SPRITE, - KW_FRAME, - KW_SPIRIT, - KW_ITEM, // logics - KW_DISPATCH, // logics (dispatch) - KW_RADIUS, // logics - KW_HEIGHT, // logics - KW_BATTERY, // logics - KW_BLUE, // logics - KW_CANNON, // logics - KW_CLEATS, // logics - KW_CODE1, // logics - KW_CODE2, // logics - KW_CODE3, // logics - KW_CODE4, // logics - KW_CODE5, // logics - KW_CODE6, // logics - KW_CODE7, // logics - KW_CODE8, // logics - KW_CODE9, // logics - KW_CONCUSSION, // logics - KW_DETONATOR, // logics - KW_DETONATORS, // logics - KW_DT_WEAPON, // logics - KW_DATATAPE, // logics - KW_ENERGY, // logics - KW_FUSION, // logics - KW_GOGGLES, // logics - KW_MASK, // logics - KW_MINE, // logics - KW_MINES, // logics - KW_MISSILE, // logics - KW_MISSILES, // logics - KW_MORTAR, // logics - KW_NAVA, // logics - KW_PHRIK, // logics - KW_PLANS, // logics - KW_PLASMA, // logics - KW_POWER, // logics - KW_RED, // logics - KW_RIFLE, // logics - KW_SHELL, // logics - KW_SHELLS, // logics - KW_SHIELD, // logics - KW_INVINCIBLE, // logics - KW_REVIVE, // logics - KW_SUPERCHARGE, // logics - KW_LIFE, // logics - KW_MEDKIT, // logics - KW_PILE, // logics - KW_YELLOW, // logics - KW_AUTOGUN, // logics - KW_DELAY, // logics (generators) - KW_INTERVAL, // logics (generators) - KW_MAX_ALIVE, // logics (generators) - KW_MIN_DIST, // logics (generators) - KW_MAX_DIST, // logics (generators) - KW_NUM_TERMINATE, // logics (generators) - KW_WANDER_TIME, // logics (generators) - KW_PLUGIN, // logics (dispatch) - KW_THINKER, // logics (dispatch) - KW_FOLLOW, // logics (dispatch) - KW_FOLLOW_Y, // logics (dispatch) - KW_RANDOM_YAW, // logics (dispatch) - KW_MOVER, // logics (dispatch) - KW_SHAKER, // logics (dispatch) - KW_PERSONALITY, // not implemented in DF - KW_SEQEND, - KW_M_TRIGGER, // INF - KW_COUNT -}; - -extern KEYWORD getKeywordIndex(const char* keywordString); \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Asset/fontAsset.h b/components/darkforces/tfe/TFE_Asset/fontAsset.h deleted file mode 100644 index 8134cb09..00000000 --- a/components/darkforces/tfe/TFE_Asset/fontAsset.h +++ /dev/null @@ -1,35 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Level/Map -// Handles the following: -// 1. Parsing the level data (.LEV) -// 2. Runtime storage and manipulation of level data -// (vertices, lines, sectors) -////////////////////////////////////////////////////////////////////// -#include - -struct FontTFE -{ - u8 startChar; - u8 endChar; - u8 charCount; - u8 height; - - u8 maxWidth; - u8 pad[3]; - - u8 width[256]; - u8 step[256]; // x step which may be different than rendered width. - u32 imageOffset[256]; - - u8* imageData; -}; - -namespace TFE_Font -{ - FontTFE* get(const char* name); - FontTFE* getFromFont(const char* name, const char* archivePath); - // create the embedded system font - FontTFE* createSystemFont6x8(); - void freeAll(); -} diff --git a/components/darkforces/tfe/TFE_Asset/gameMessages.h b/components/darkforces/tfe/TFE_Asset/gameMessages.h deleted file mode 100644 index 8d8ec549..00000000 --- a/components/darkforces/tfe/TFE_Asset/gameMessages.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Level/Map -// Handles the following: -// 1. Parsing the level data (.LEV) -// 2. Runtime storage and manipulation of level data -// (vertices, lines, sectors) -////////////////////////////////////////////////////////////////////// -#include - -namespace TFE_GameMessages -{ - bool load(); - void unload(); - const char* getMessage(u32 msgId); -} diff --git a/components/darkforces/tfe/TFE_Asset/gifWriter.h b/components/darkforces/tfe/TFE_Asset/gifWriter.h deleted file mode 100644 index 4d0675e0..00000000 --- a/components/darkforces/tfe/TFE_Asset/gifWriter.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Image Loading -// TODO: Replace DeviL with libPNG? or STB_IMAGE? -// Can use std_image.h and std_image_write.h for reading and writing. -////////////////////////////////////////////////////////////////////// -#include - -namespace TFE_GIF -{ - bool startGif(const char* path, u32 width, u32 height, u32 fps); - void addFrame(const u8* imageData); - bool write(); -} diff --git a/components/darkforces/tfe/TFE_Asset/gmidAsset.h b/components/darkforces/tfe/TFE_Asset/gmidAsset.h deleted file mode 100644 index 2d48012d..00000000 --- a/components/darkforces/tfe/TFE_Asset/gmidAsset.h +++ /dev/null @@ -1,80 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Midi Asset -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include - -enum MidiTrackEventType -{ - MTK_TEMPO = 0, - MTK_MARKER, - MTK_MIDI, - MTK_IMUSE, - MTK_COUNT -}; - -struct MidiEvent -{ - u8 type; - s8 channel; - u8 data[2]; -}; - -struct MidiTempoEvent -{ - f32 msPerTick; // milliseconds per tick. -}; - -struct MidiMarker -{ - char name[256]; -}; - -struct MidiTrackEvent -{ - u32 tick; - MidiTrackEventType type; - u32 index; -}; - -struct Track -{ - char name[256]; - u16 id; - u16 pad16; - f32 msPerTick; // tempo at time 0. - u32 length; - - s32 loopStart; - s32 loopEnd; - - u32 ticksPerBeat; - u32 ticksPerMeasure; - - // Ordered event list. - std::vector eventList; - - // Event type arrays. - std::vector tempoEvents; - std::vector midiEvents; - std::vector markers; -}; - -struct GMidiAsset -{ - char name[32]; - u32 trackCount; - u32 length; - - std::vector tracks; -}; - -namespace TFE_GmidAsset -{ - GMidiAsset* get(const char* name); - void free(GMidiAsset* asset); - void freeAll(); -}; diff --git a/components/darkforces/tfe/TFE_Asset/imageAsset.h b/components/darkforces/tfe/TFE_Asset/imageAsset.h deleted file mode 100644 index 8bdc2c0e..00000000 --- a/components/darkforces/tfe/TFE_Asset/imageAsset.h +++ /dev/null @@ -1,30 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Image Loading -// TODO: Replace DeviL with libPNG? or STB_IMAGE? -// Can use std_image.h and std_image_write.h for reading and writing. -////////////////////////////////////////////////////////////////////// -#include - -struct Image -{ - u32 width = 0u; - u32 height = 0u; - u32* data = nullptr; -}; - -namespace TFE_Image -{ - void init(); - void shutdown(); - - Image* get(const char* imagePath); - Image* loadFromMemory(const u8* buffer, size_t size); - void free(Image* image); - void freeAll(); - - void writeImage(const char* path, u32 width, u32 height, u32* pixelData); - - size_t writeImageToMemory(u8*& output, u32 width, u32 height, const u32* pixelData); - void readImageFromMemory(Image* output, size_t size, const u32* pixelData); -} diff --git a/components/darkforces/tfe/TFE_Asset/infAsset.h b/components/darkforces/tfe/TFE_Asset/infAsset.h deleted file mode 100644 index f5f9ba04..00000000 --- a/components/darkforces/tfe/TFE_Asset/infAsset.h +++ /dev/null @@ -1,269 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine INF script -////////////////////////////////////////////////////////////////////// -#include -#include -#include - -enum Keys -{ - KEY_RED = (1 << 0), - KEY_YELLOW = (1 << 1), - KEY_BLUE = (1 << 2), - KEY_CODE_1 = (1 << 3), - KEY_CODE_2 = (1 << 4), - KEY_CODE_3 = (1 << 5), - KEY_CODE_4 = (1 << 6), - KEY_CODE_5 = (1 << 7), - KEY_CODE_6 = (1 << 8), - KEY_CODE_7 = (1 << 9), - KEY_CODE_8 = (1 << 10), - KEY_CODE_9 = (1 << 11), -}; - -enum InfItemType -{ - INF_ITEM_LEVEL = 0, - INF_ITEM_SECTOR, - INF_ITEM_LINE, - INF_ITEM_COUNT -}; - -enum InfClass -{ - INF_CLASS_ELEVATOR = 0, - INF_CLASS_TRIGGER, - INF_CLASS_TELEPORTER, - INF_CLASS_COUNT -}; - -enum InfSubClass -{ - // Elevators - ELEVATOR_CHANGE_LIGHT = 0, // Changes sector Ambient. - ELEVATOR_BASIC, // Change floor altitude of sector (can use Smart Object Reactions) - ELEVATOR_INV, // Change ceiling altitude of sector (can use Smart Object Reactions) - ELEVATOR_MOVE_FLOOR, // Change floor altitude of sector (can NOT use Smart Object Reactions) - ELEVATOR_MOVE_CEILING, // Change ceiling altitude of sector (can NOT use Smart Object Reactions) - ELEVATOR_MOVE_FC, // Changes both the floor and ceiling altitude, stop = floor alt. - ELEVATOR_SCROLL_FLOOR, // Scroll floor texture in texels (x8 = world units). Players move with floor by default. - ELEVATOR_SCROLL_CEILING, // Scroll the ceiling texture of the sector (in texels). - ELEVATOR_MOVE_OFFSET, // Change the second alt of sector. - ELEVATOR_BASIC_AUTO, // Same as BASIC except returns to Alt 0 after cycling through all stops. Needs to be triggered twice to go to first stop again. - - ELEVATOR_CHANGE_WALL_LIGHT, // Change LIGHT of any wall in sector with WF1_CHANGE_WALL_LIGHT set. (Does not work if sector ambient = 31). - ELEVATOR_MORPH_MOVE1, // Translate vertex positions of any walls with WF1_WALL_MORPHS set. If adjoined their mirrors will also move. By default the player will not move with the walls. Stop = distance on XZ plane relative to the wall. - ELEVATOR_MORPH_MOVE2, // Same as MORPH_MOVE1 but player will be moved by default. - - ELEVATOR_MORPH_SPIN1, // Rotate vertex positions of any walls with WF1_WALL_MORPHS set. If adjoined their mirrors will also move. By default the player will not spin with the walls. Stop = distance on XZ plane relative to the wall. - ELEVATOR_MORPH_SPIN2, // Same as MORPH_SPIN1 but player will be rotated by the walls by default. - ELEVATOR_MOVE_WALL, // Same as ELEVATOR_MORPH_MOVE1 but default event_mask = 0 - ELEVATOR_ROTATE_WALL, // Same as ELEVATOR_MORPH_SPIN1 but default event_mask = 0 - ELEVATOR_SCROLL_WALL, // Scroll textures on walls with WF1_SCROLL_??_TEX set. Stop values are distances in texels. - - ELEVATOR_DOOR, // Creates a default door, similar to SEC_FLAGS1_DOOR - ELEVATOR_DOOR_MID, // Split door (up and down). Sector altitudes are set for when the door is open. [addon: 0; addon: 1] - ELEVATOR_DOOR_INV, // The door opens downward but otherwise acts like ELEVATOR_DOOR - - // Triggers // If no message is specified, m_trigger is sent. - TRIGGER_STANDARD, // Can be applied to a sector or line but not switches. - TRIGGER, // Same as standard. - TRIGGER_SWITCH1, // Used for switches (wall must have a SIGN). When pressed, the texture will change to the second in the BM. The second cannot be pressed. - TRIGGER_SINGLE, // Same as SWITCH1 but can only be used once. - TRIGGER_TOGGLE, // Switch that can be toggled between states. - - // Chute - TELEPORTER_CHUTE, // Silent teleport that acts like falling through one sector to the next. - - // None - SUBCLASS_NONE, - - // Counts - ELEVATOR_COUNT = ELEVATOR_DOOR_INV + 1, - TRIGGER_COUNT = TRIGGER_TOGGLE - TRIGGER_STANDARD + 1, - TELEPORTER_COUNT = 1, -}; - -enum InfEventMask -{ - INF_EVENT_CROSS_LINE_FRONT = (1u << 0u), - INF_EVENT_CROSS_LINE_BACK = (1u << 1u), - INF_EVENT_ENTER_SECTOR = (1u << 2u), - INF_EVENT_LEAVE_SECTOR = (1u << 3u), - INF_EVENT_NUDGE_FRONT = (1u << 4u), // front of line or inside sector. - INF_EVENT_NUDGE_BACK = (1u << 5u), // back of line or outside sector. - INF_EVENT_EXPLOSION = (1u << 6u), - INF_EVENT_UNKNOWN = (1u << 7u), // skipped slot or unused event? - INF_EVENT_SHOOT_LINE = (1u << 8u), // Shoot or punch line. - INF_EVENT_LAND = (1u << 9u), // Land on floor - INF_EVENT_ANY = INF_EVENT_CROSS_LINE_FRONT | INF_EVENT_CROSS_LINE_BACK | INF_EVENT_ENTER_SECTOR | INF_EVENT_LEAVE_SECTOR | INF_EVENT_NUDGE_FRONT | INF_EVENT_NUDGE_BACK | INF_EVENT_EXPLOSION | INF_EVENT_SHOOT_LINE | INF_EVENT_LAND -}; - -//enum InfEntityMask -// Cannot use the enum{} because it seems to be forced to signed int32. -static const u32 INF_ENTITY_ENEMY = (1u << 0u); -static const u32 INF_ENTITY_WEAPON = (1u << 3u); -static const u32 INF_ENTITY_PLAYER = (1u << 31u); - -enum InfMoveFlags -{ - INF_MOVE_NONE = 0, - INF_MOVE_FLOOR = (1 << 0), - INF_MOVE_SECALT = (1 << 1), - INF_MOVE_UNKNOWN = (1 << 2), // check out the effect on FUELSTAT -}; - -enum SoundEffectIndex -{ - SFX_LEAVE_STOP = 0, - SFX_MOVING, - SFX_ARRIVE_STOP, -}; - -enum InfMessage -{ - INF_MSG_M_TRIGGER = 0, // Trigger an elevator (next stop) or another trigger. Param: EventValue (optional) - event value (matched with event_mask). - INF_MSG_GOTO_STOP, // Sends an elevator to the stop specified. Param: stopNumber. - INF_MSG_NEXT_STOP, // Sends an elevator to its next stop. Param: EventValue (optional) - event value (matched with event_mask). - INF_MSG_PREV_STOP, // Sends an elevator to its previous stop. Param: EventValue (optional) - event value (matched with event_mask). - INF_MSG_MASTER_ON, // Turns an elevator or trigger's master on. Also turns on generators in sector. Param: EventValue (optional) - event value (matched with event_mask). - INF_MSG_MASTER_OFF, // Turns an elevator or trigger's master off. Also turns off generators in sector. Param: EventValue (optional) - event value (matched with event_mask). - INF_MSG_CLEAR_BITS, // Clear bits from wall or sector. Param: flagNumber (1,2,3), bitsToClear. - INF_MSG_SET_BITS, // Set bits from wall or sector. Param: flagNumber (1,2,3), bitsToClear. - INF_MSG_COMPLETE, // Triggers GOL in PDA, moves elevator to next stop. Goal number (TRIG: num in GOL file). - INF_MSG_DONE, // Puts a switch on its first texture, making it usable again (unless it is TRIGGER_SINGLE). - INF_MSG_WAKEUP, // Vue with "Pause:true" will continue if this is sent to the 3D object's sector. - INF_MSG_LIGHTS, // Sets sector ambient, for all sectors, to the value in their flags3. - // Special elevator functions - INF_MSG_ADJOIN, // Param: sector1, line1, sector2, line2 - INF_MSG_PAGE, // Param: sound file - INF_MSG_TEXT, // Param: text number - INF_MSG_TEXTURE, // Copy floor or ceiling texture from another sector; Param: flag (0 = floor / 1 = ceil), donor (sectorId) - INF_MSG_INVALID, - INF_MSG_COUNT = INF_MSG_LIGHTS + 1 -}; - -enum InfStopValue0Type -{ - INF_STOP0_ABSOLUTE = 0, // Absolute value (height, light level, etc.) - INF_STOP0_RELATIVE, // Relative value - INF_STOP0_SECTORNAME, // Sector - INF_STOP0_COUNT -}; - -enum InfStopValue1Type -{ - INF_STOP1_TIME = 0, // Time an elevator remains at the stop (in seconds). - INF_STOP1_HOLD, // Hold at stop indefinitely. - INF_STOP1_TERMINATE, // Elevator will stay at the stop permanently. - INF_STOP1_COMPLETE, // Mission will be complete when reaching this stop. - INF_STOP1_COUNT -}; - -struct InfoMsgArg -{ - union - { - u32 uintValue; - s32 intValue; - char strValue[32]; - }; -}; - -struct InfArg -{ - union - { - s32 iValue; - f32 fValue; - }; -}; - -struct InfFunction -{ - u32 code; // func | clientCount << 8 | argCount << 16 (top bot available). - u32* client; // sectorId | (wallId << 16), where hasWall = wallId < 0xffff - InfArg* arg; -}; - -// A trigger will have 1 stop with code = 0 | funcCount << 8, time = 0 -struct InfStop -{ - u32 code; // InfStopValue0Type | InfStopValue1Type << 4 | funcCount << 8 - InfArg value0; - f32 time; // time at stop or 0. - InfFunction* func; -}; - -struct InfVariables -{ - bool master = true; // Determines if an elevator or trigger can function. - u32 event = 0; // Custom event value(s) for trigger. - s32 start = 0; // Determines which stop an elevator starts at on level load. - /////////////////////// Masks /////////////////////// - u32 event_mask = 0; // (InfEventMask) Determines if an event will operate on an elevator or trigger. Defaults: 52 (elev basic, inv, basic_auto), 60 (morph1/2, spin1/2), other elev 0; trigger 0xffffffff - u32 entity_mask = // (InfEntityMask) Defines the type of entities that can activate a Trigger. - INF_ENTITY_PLAYER; - //////////////////////// Flags & keys /////////////////////// - u32 key = 0; // Key required to activate an elevator (yellow, blue, red). - u32 flags = 0; // (InfMoveFlags) Determines whether the player moves with morphing or scrolling elevators. Defaults: 3 (scroll_floor, morph2, spin2) otherwise 0. - /////////////////////// Movement & rotation /////////////////////// - Vec2f center = // Center coordinates for rotation. - { 0.0f, 0.0f }; - f32 angle = 0.0f; // Direction of texture scrolling or horizontal elevators. For walls 0 = down others 0 = north. - f32 speed = 0.0f; // Speed an elevator moves between stops. 0 = instant. - f32 speed_addon[2]; // Addon for door_mid - /////////////////////// Sound /////////////////////// - s32 sound[3]; // VOC sound index. 0 is used for triggers, 0 - 2 for elevators. Note -1 means no sound at all. - /////////////////////// Target/Slave /////////////////////// - s32 target; // Target sector for teleport. -}; - -struct InfClassData -{ - u8 iclass, isubclass; - u16 stopCount; // Can have more than 256 stops. - u16 slaveCount; - s16 mergeStart; // start of merges - since these will still affect objects. - u32 stateIndex; // Used by the runtime to map to the runtime state. - - InfVariables var; - InfStop* stop; - u16* slaves; -}; - -struct InfItem -{ - u32 id; // sectorId | wallNum << 16; hasWall = wallNum < 0xffff - u8 type; - u8 classCount; - u8 pad[2]; - - InfClassData* classData; -}; - -struct InfData -{ - u32 itemCount; - s32 completeId; - s32 doorStart; - InfItem* item; -}; - -class MemoryPool; - -namespace TFE_InfAsset -{ - bool load(const char* name); - u32 countSectorFlagDoors(); - void setupDoors(); - void unload(); - - InfData* getInfData(); - const char* getClassName(u32 iclass); - const char* getSubclassName(u32 iclass, u32 sclass); - const char* getFuncName(u32 funcId); - - MemoryPool* getMemoryPool(bool clearPool); -}; diff --git a/components/darkforces/tfe/TFE_Asset/levelList.h b/components/darkforces/tfe/TFE_Asset/levelList.h deleted file mode 100644 index a171ff7d..00000000 --- a/components/darkforces/tfe/TFE_Asset/levelList.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Level/Map -// Handles the following: -// 1. Parsing the level data (.LEV) -// 2. Runtime storage and manipulation of level data -// (vertices, lines, sectors) -////////////////////////////////////////////////////////////////////// -#include - -namespace TFE_LevelList -{ - bool load(); - void unload(); - - u32 getLevelCount(); - const char* getLevelName(u32 index); - const char* getLevelFileName(u32 index); -} diff --git a/components/darkforces/tfe/TFE_Asset/levelObjectsAsset.h b/components/darkforces/tfe/TFE_Asset/levelObjectsAsset.h deleted file mode 100644 index 53a1a763..00000000 --- a/components/darkforces/tfe/TFE_Asset/levelObjectsAsset.h +++ /dev/null @@ -1,101 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Level Objects -// Handles the following: -// 1. Parsing the level data (.LEV) -// 2. Runtime storage and manipulation of level data -// (vertices, lines, sectors) -////////////////////////////////////////////////////////////////////// -#include -#include "logicTypes.h" -#include "vueAsset.h" -#include -#include - -typedef std::vector StringList; - -enum LogicCommonFlags -{ - LCF_EYE = (1 << 0), - LCF_BOSS = (1 << 1), - LCF_PAUSE = (1 << 2), - LCF_LOOP = (1 << 3), -}; - -enum Difficulty -{ - DIFF_EASY = (1 << 0), - DIFF_MEDIUM = (1 << 1), - DIFF_HARD = (1 << 2), -}; - -// Generates enemies once its sector is activated ("MASTER: ON" message). Continues until the numTerminate is reached or "MASTER: OFF" message is sent. -// Will not generate enemies when the player can see the generator. -struct EnemyGenerator -{ - LogicType type; // type of enemy to be generated. - f32 delay; // time in seconds that needs to pass from the start of a level before the generator starts operating. - f32 interval; // time in seconds between each generation. - f32 minDist; // min/max distance from player when enemy can be generated. - f32 maxDist; - s32 maxAlive; // maximum number of enemies from the generator allowed alive at the same time. - s32 numTerminate; // number of enemies to generate after which the generator will terminate. -1 = infinite spawns. - f32 wanderTime; // time in seconds that a generate enemy walks around before becoming inactive. -}; -// For Scripts -typedef EnemyGenerator GenParam; - -struct Logic -{ - LogicType type = LOGIC_INVALID; - u32 flags = 0; // logic specific flags. - f32 frameRate = 0.0f; - Vec3f rotation = { 0.0f, 0.0f, 0.0f }; - - VueAsset* vue = nullptr; - VueAsset* vueAppend = nullptr; - s32 vueId = -1; - s32 vueAppendId = -1; -}; -// For scripts -typedef Logic LogicParam; - -struct LevelObject -{ - // Render Data - ObjectClass oclass; - u32 dataOffset; - Vec3f pos; - Vec3f orientation; - s32 difficulty; - - // Common Variables. - u32 comFlags = 0; // common flags - see LogicCommonFlags. - f32 radius = -1.0f; - f32 height = 0.0f; - - // Logics - std::vector logics; - std::vector generators; -}; - -struct LevelObjectData -{ - StringList pods; - StringList sprites; - StringList frames; - StringList sounds; - - u32 objectCount; - std::vector objects; -}; - -namespace TFE_LevelObjects -{ - bool load(const char* name); - void unload(); - - void save(const char* name, const char* path); - - LevelObjectData* getLevelObjectData(); -}; diff --git a/components/darkforces/tfe/TFE_Asset/logicTypes.h b/components/darkforces/tfe/TFE_Asset/logicTypes.h deleted file mode 100644 index 35785f0b..00000000 --- a/components/darkforces/tfe/TFE_Asset/logicTypes.h +++ /dev/null @@ -1,343 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Logic Types -////////////////////////////////////////////////////////////////////// -#include - -enum LogicType -{ - // Player - LOGIC_PLAYER, // Player controlled object - // General - LOGIC_SHIELD, // 20 shield units 114 - LOGIC_BATTERY, // battery unit 211 - LOGIC_CLEATS, // ice cleats 304 - LOGIC_GOGGLES, // infra red goggles 303 - LOGIC_MASK, // gas mask 305 - LOGIC_MEDKIT, // med kit 311 - // Weapons - - LOGIC_RIFLE, // Blaster rifle / 15 energy units 100 / 101 - LOGIC_AUTOGUN, // Repeater Rifle / 30 power units 103 / 104 - LOGIC_FUSION, // Jeron fusion cutter / 50 power units 107 / 108 - LOGIC_MORTAR, // Mortar Gun / 3 mortar shells 105 / 106 - LOGIC_CONCUSSION, // Concussion Rifle / 100 power units 110 / 111 - LOGIC_CANNON, // Assault cannon / 30 plasma units 112 / 113 - // Ammo - - LOGIC_ENERGY, // 15 energy units 200 - LOGIC_DETONATOR, // 1 thermal detonator 203 - LOGIC_DETONATORS, // 5 thermal detonators 204 - LOGIC_POWER, // 10 power units 201 - LOGIC_MINE, // 1 mine 207 - LOGIC_MINES, //5 mines 208 - LOGIC_SHELL, // 1 mortar shell 205 - LOGIC_SHELLS, // 5 mortar shells 206 - LOGIC_PLASMA, // 20 Plasma units 202 - LOGIC_MISSILE, // 1 missile 209 - LOGIC_MISSILES, // 5 missiles 210 - // Bonuses - - LOGIC_SUPERCHARGE, // weapon supercharge 307 - LOGIC_INVINCIBLE, // shield supercharge 306 - LOGIC_LIFE, // extra life 310 - LOGIC_REVIVE, // revive 308 - // Keys - - LOGIC_BLUE, // blue key 302 - LOGIC_RED, // red key 300 - LOGIC_YELLOW, // yellow key 301 - LOGIC_CODE1, // code key 1 501 - LOGIC_CODE2, // code key 2 502 - LOGIC_CODE3, // code key 3 503 - LOGIC_CODE4, // code key 4 504 - LOGIC_CODE5, // code key 5 505 - LOGIC_CODE6, // code key 6 506 - LOGIC_CODE7, // code key 7 507 - LOGIC_CODE8, // code key 8 508 - LOGIC_CODE9, // code key 9 509 - // Goal items - - LOGIC_DATATAPE, // data tapes 406 - LOGIC_PLANS, // Death Star plans 400 - LOGIC_DT_WEAPON, // broken DT weapon 405 - LOGIC_NAVA, // Nava Card 402 - LOGIC_PHRIK, // Phrik metal 401 - LOGIC_PILE, // Your Gear 312 - // Enemy logics - LOGIC_GENERATOR, // Generate enemies. - // Imperials - - LOGIC_I_OFFICER, // Imperial officer - LOGIC_I_OFFICERR, // Officer with red key - LOGIC_I_OFFICERB, // Officer with blue key - LOGIC_I_OFFICERY, // Officer with yellow key - LOGIC_I_OFFICER1, // Officer with code key 1 - LOGIC_I_OFFICER2, // Officer with code key 2 - LOGIC_I_OFFICER3, // Officer with code key 3 - LOGIC_I_OFFICER4, // Officer with code key 4 - LOGIC_I_OFFICER5, // Officer with code key 5 - LOGIC_I_OFFICER6, // Officer with code key 6 - LOGIC_I_OFFICER7, // Officer with code key 7 - LOGIC_I_OFFICER8, // Officer with code key 8 - LOGIC_I_OFFICER9, // Officer with code key 9 - LOGIC_TROOP, // Stormtrooper - LOGIC_STORM1, // Stormtrooper - LOGIC_COMMANDO, // Imperial Commando - // Aliens - - LOGIC_BOSSK, // Bossk - LOGIC_G_GUARD, // Gammorean Guard - LOGIC_REE_YEES, // ReeYees with thermal detonators - LOGIC_REE_YEES2, // ReeYees w / o thermal detonators - LOGIC_SEWER1, // Sewer creature - // Robots - - LOGIC_INT_DROID, // Interrogator droid - LOGIC_PROBE_DROID, // Probe droid - LOGIC_REMOTE, // Remote - // Bosses - - LOGIC_BOBA_FETT, // Boba Fett - LOGIC_KELL, // Kell Dragon - LOGIC_D_TROOP1, // Phase 1 Dark Trooper - LOGIC_D_TROOP2, // Phase 2 Dark Trooper - LOGIC_D_TROOP3, // Phase 3 Dark Trooper(Mohc) - // Special sprite logics - LOGIC_SCENERY, // Displays first cell of wax 0, then all of wax 1 when attacked - LOGIC_ANIM, // Displays wax 0 over and over - LOGIC_BARREL, // Power Generating unit - LOGIC_LAND_MINE, // Land mine - // 3D object logics - LOGIC_TURRET, // gun turret - LOGIC_MOUSEBOT, // mousebot - LOGIC_WELDER, // welding arm - // 3D object motion logics - LOGIC_UPDATE, // to perpetually rotate a 3D, and - LOGIC_KEY, // to give a VUE motion to the 3D - // Final Count - LOGIC_COUNT, - LOGIC_INVALID = LOGIC_COUNT -}; - -static const u32 c_logicMsg[LOGIC_COUNT]= -{ - // Player - 0, // LOGIC_PLAYER - // General - 114, // LOGIC_SHIELD - 211, // LOGIC_BATTERY - 304, // LOGIC_CLEATS - 303, // LOGIC_GOGGLES - 305, // LOGIC_MASK - 311, // LOGIC_MEDKIT - // Weapons - - 100, // LOGIC_RIFLE - 103, // LOGIC_AUTOGUN - 107, // LOGIC_FUSION - 105, // LOGIC_MORTAR - 110, // LOGIC_CONCUSSION - 112, // LOGIC_CANNON - // Ammo - - 200, // LOGIC_ENERGY - 203, // LOGIC_DETONATOR - 204, // LOGIC_DETONATORS - 201, // LOGIC_POWER - 207, // LOGIC_MINE - 208, // LOGIC_MINES - 205, // LOGIC_SHELL - 206, // LOGIC_SHELLS - 202, // LOGIC_PLASMA - 209, // LOGIC_MISSILE - 210, // LOGIC_MISSILES - // Bonuses - - 307, // LOGIC_SUPERCHARGE - 306, // LOGIC_INVINCIBLE - 310, // LOGIC_LIFE - 308, // LOGIC_REVIVE - // Keys - - 302, // LOGIC_BLUE - 300, // LOGIC_RED - 301, // LOGIC_YELLOW - 501, // LOGIC_CODE1 - 502, // LOGIC_CODE2 - 503, // LOGIC_CODE3 - 504, // LOGIC_CODE4 - 505, // LOGIC_CODE5 - 506, // LOGIC_CODE6 - 507, // LOGIC_CODE7 - 508, // LOGIC_CODE8 - 509, // LOGIC_CODE9 - // Goal items - - 406, // LOGIC_DATATAPE - 400, // LOGIC_PLANS - 405, // LOGIC_DT_WEAPON - 402, // LOGIC_NAVA - 401, // LOGIC_PHRIK - 312, // LOGIC_PILE - // Enemy logics - 0, // LOGIC_GENERATOR - // Imperials - - 0, // LOGIC_I_OFFICER - 0, // LOGIC_I_OFFICERR - 0, // LOGIC_I_OFFICERB - 0, // LOGIC_I_OFFICERY - 0, // LOGIC_I_OFFICER1 - 0, // LOGIC_I_OFFICER2 - 0, // LOGIC_I_OFFICER3 - 0, // LOGIC_I_OFFICER4 - 0, // LOGIC_I_OFFICER5 - 0, // LOGIC_I_OFFICER6 - 0, // LOGIC_I_OFFICER7 - 0, // LOGIC_I_OFFICER8 - 0, // LOGIC_I_OFFICER9 - 0, // LOGIC_TROOP - 0, // LOGIC_STORM1 - 0, // LOGIC_COMMANDO - // Aliens - - 0, // LOGIC_BOSSK - 0, // LOGIC_G_GUARD - 0, // LOGIC_REE_YEES - 0, // LOGIC_REE_YEES2 - 0, // LOGIC_SEWER1 - // Robots - - 0, // LOGIC_INT_DROID - 0, // LOGIC_PROBE_DROID - 0, // LOGIC_REMOTE - // Bosses - - 0, // LOGIC_BOBA_FETT - 0, // LOGIC_KELL - 0, // LOGIC_D_TROOP1 - 0, // LOGIC_D_TROOP2 - 0, // LOGIC_D_TROOP3 - // Special sprite logics - 0, // LOGIC_SCENERY - 0, // LOGIC_ANIM - 0, // LOGIC_BARREL - 0, // LOGIC_LAND_MINE - // 3D object logics - 0, // LOGIC_TURRET - 0, // LOGIC_MOUSEBOT - 0, // LOGIC_WELDER - // 3D object motion logics - 0, // LOGIC_UPDATE - 0, // LOGIC_KEY -}; - -static const char* c_logicName[LOGIC_COUNT] = -{ - // Player - "PLAYER", // LOGIC_PLAYER - // General - "SHIELD", // LOGIC_SHIELD - "BATTERY", // LOGIC_BATTERY - "CLEATS", // LOGIC_CLEATS - "GOGGLES", // LOGIC_GOGGLES - "MASK", // LOGIC_MASK - "MEDKIT", // LOGIC_MEDKIT - // Weapons - - "RIFLE", // LOGIC_RIFLE - "AUTOGUN", // LOGIC_AUTOGUN - "FUSION", // LOGIC_FUSION - "MORTAR", // LOGIC_MORTAR - "CONCUSSION", // LOGIC_CONCUSSION - "CANNON", // LOGIC_CANNON - // Ammo - - "ENERGY", // LOGIC_ENERGY - "DETONATOR", // LOGIC_DETONATOR - "DETONATORS", // LOGIC_DETONATORS - "POWER", // LOGIC_POWER - "MINE", // LOGIC_MINE - "MINES", // LOGIC_MINES - "SHELL", // LOGIC_SHELL - "SHELLS", // LOGIC_SHELLS - "PLASMA", // LOGIC_PLASMA - "MISSILE", // LOGIC_MISSILE - "MISSILES", // LOGIC_MISSILES - // Bonuses - - "SUPERCHARGE", // LOGIC_SUPERCHARGE - "INVINCIBLE", // LOGIC_INVINCIBLE - "LIFE", // LOGIC_LIFE - "REVIVE", // LOGIC_REVIVE - // Keys - - "BLUE", // LOGIC_BLUE - "RED", // LOGIC_RED - "YELLOW", // LOGIC_YELLOW - "CODE1", // LOGIC_CODE1 - "CODE2", // LOGIC_CODE2 - "CODE3", // LOGIC_CODE3 - "CODE4", // LOGIC_CODE4 - "CODE5", // LOGIC_CODE5 - "CODE6", // LOGIC_CODE6 - "CODE7", // LOGIC_CODE7 - "CODE8", // LOGIC_CODE8 - "CODE9", // LOGIC_CODE9 - // Goal items - - "DATATAPE", // LOGIC_DATATAPE - "PLANS", // LOGIC_PLANS - "DT_WEAPON", // LOGIC_DT_WEAPON - "NAVA", // LOGIC_NAVA - "PHRIK", // LOGIC_PHRIK - "PILE", // LOGIC_PILE - // Enemy logics - "GENERATOR", // LOGIC_GENERATOR - // Imperials - - "I_OFFICER", // LOGIC_I_OFFICER - "I_OFFICERR", // LOGIC_I_OFFICERR - "I_OFFICERB", // LOGIC_I_OFFICERB - "I_OFFICERY", // LOGIC_I_OFFICERY - "I_OFFICER1", // LOGIC_I_OFFICER1 - "I_OFFICER2", // LOGIC_I_OFFICER2 - "I_OFFICER3", // LOGIC_I_OFFICER3 - "I_OFFICER4", // LOGIC_I_OFFICER4 - "I_OFFICER5", // LOGIC_I_OFFICER5 - "I_OFFICER6", // LOGIC_I_OFFICER6 - "I_OFFICER7", // LOGIC_I_OFFICER7 - "I_OFFICER8", // LOGIC_I_OFFICER8 - "I_OFFICER9", // LOGIC_I_OFFICER9 - "TROOP", // LOGIC_TROOP - "STORM1", // LOGIC_STORM1 - "COMMANDO", // LOGIC_COMMANDO - // Aliens - - "BOSSK", // LOGIC_BOSSK - "G_GUARD", // LOGIC_G_GUARD - "REE_YEES", // LOGIC_REE_YEES - "REE_YEES2", // LOGIC_REE_YEES2 - "SEWER1", // LOGIC_SEWER1 - // Robots - - "INT_DROID", // LOGIC_INT_DROID - "PROBE_DROID", // LOGIC_PROBE_DROID - "REMOTE", // LOGIC_REMOTE - // Bosses - - "BOBA_FETT", // LOGIC_BOBA_FETT - "KELL", // LOGIC_KELL - "D_TROOP1", // LOGIC_D_TROOP1 - "D_TROOP2", // LOGIC_D_TROOP2 - "D_TROOP3", // LOGIC_D_TROOP3 - // Special sprite logics - "SCENERY", // LOGIC_SCENERY - "ANIM", // LOGIC_ANIM - "BARREL", // LOGIC_BARREL - "LAND_MINE", // LOGIC_LAND_MINE - // 3D object logics - "TURRET", // LOGIC_TURRET - "MOUSEBOT", // LOGIC_MOUSEBOT - "WELDER", // LOGIC_WELDER - // 3D object motion logics - "UPDATE", // LOGIC_UPDATE - "KEY", // LOGIC_KEY -}; - - -enum ObjectClass -{ - CLASS_SPIRIT, - CLASS_SAFE, - CLASS_SPRITE, - CLASS_FRAME, - CLASS_3D, - CLASS_SOUND, - CLASS_COUNT, - CLASS_INAVLID = CLASS_COUNT -}; - -static const char* c_objectClassName[CLASS_COUNT] = -{ - "SPIRIT", // CLASS_SPIRIT - "SAFE", // CLASS_SAFE - "SPRITE", // CLASS_SPRITE - "FRAME", // CLASS_FRAME - "3D", // CLASS_3D - "SOUND", // CLASS_SOUND -}; diff --git a/components/darkforces/tfe/TFE_Asset/modelAsset.h b/components/darkforces/tfe/TFE_Asset/modelAsset.h deleted file mode 100644 index 0ec2e0a7..00000000 --- a/components/darkforces/tfe/TFE_Asset/modelAsset.h +++ /dev/null @@ -1,96 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Level/Map -// Handles the following: -// 1. Parsing the level data (.LEV) -// 2. Runtime storage and manipulation of level data -// (vertices, lines, sectors) -////////////////////////////////////////////////////////////////////// -#include -#include -#include - -struct Texture; - -enum PolygonShading -{ - SHADING_FLAT, - SHADING_GOURAUD, - SHADING_VERTEX, - SHADING_TEXTURE, - SHADING_GOURTEX, - SHADING_PLANE, - SHADING_COUNT -}; - -struct ModelPolygon -{ - u16 i0, i1, i2, i3; - u16 num; - u8 color; - u8 shading; -}; - -struct TexturePolygon -{ - u16 i0, i1, i2, i3; - u16 num; - u16 pad16; -}; - -struct Vertex3f -{ - u16 num; - u16 pad16; - f32 x, y, z; -}; - -struct Vertex2f -{ - u16 num; - u16 pad16; - f32 x, y; -}; - -struct ModelObject -{ - s16 textureIndex; - u16 pad16; - u32 vertexOffset; - - // Name. - std::string name; - - // 3D geometry. - std::vector vertices; - std::vector triangles; - std::vector quads; - - // 2D texture mapping. - std::vector textureVertices; - std::vector textureTriangles; - std::vector textureQuads; - - // Center for sorting. - Vec3f center; - f32 radius; -}; - -struct Model -{ - u32 objectCount; - u32 vertexCount; - u32 polygonCount; - std::vector textures; - std::vector objects; - - Vec3f localAabb[2]; - Vec3f center; - f32 radius; -}; - -namespace TFE_Model -{ - Model* get(const char* name); - void freeAll(); -}; diff --git a/components/darkforces/tfe/TFE_Asset/modelAsset_jedi.cpp b/components/darkforces/tfe/TFE_Asset/modelAsset_jedi.cpp deleted file mode 100644 index bafcef51..00000000 --- a/components/darkforces/tfe/TFE_Asset/modelAsset_jedi.cpp +++ /dev/null @@ -1,906 +0,0 @@ -#include - -#include "modelAsset_jedi.h" -#include -#include -#include -#include -#include -#include - -#include -#include -#include -// TODO: dependency on JediRenderer, this should be refactored... -#include - -#include -#include -#include - -using namespace TFE_Jedi; -extern MemoryRegion* s_gameRegion; -extern MemoryRegion* s_levelRegion; -static MemoryRegion* s_memRegion; - -#define model_alloc(size) TFE_Memory::region_alloc(s_memRegion, size) -#define model_free(ptr) TFE_Memory::region_free(s_memRegion, ptr) - -// Jedi code for processing models. -// TODO: Move model processing to its own file. -// TODO: Consider processed model binary caching - once models get large for mods, parsing and processiong -// will drastically slow down load times. -namespace TFE_Jedi_Object3d -{ - void vec3_computeNormalOffset(const vec3* vIn, const vec3* v0, vec3* vOut) - { - const fixed16_16 dx = vIn->x - v0->x; - const fixed16_16 dy = vIn->y - v0->y; - const fixed16_16 dz = vIn->z - v0->z; - fixed16_16 len; - - if (TFE_Settings::getGraphicsSettings()->fix3doNormalOverflow) - { - // Convert to floating point before calculating the length to avoid - // fixed-point overflow. - const f32 xf = fixed16ToFloat(dx); - const f32 yf = fixed16ToFloat(dy); - const f32 zf = fixed16ToFloat(dz); - const f32 lenf = sqrtf(xf*xf + yf*yf + zf*zf); - // Then convert back so the rest of the code stays the same. - len = floatToFixed16(lenf); - } - else - { - const fixed16_16 xSq = mul16(dx, dx); - const fixed16_16 ySq = mul16(dy, dy); - const fixed16_16 zSq = mul16(dz, dz); - len = fixedSqrt(xSq + ySq + zSq); - } - - // The Jedi 3D object renderer expect normals in the form of v0 + dir rather than just dir as used today. - vOut->x = v0->x; - vOut->y = v0->y; - vOut->z = v0->z; - if (len > 0) - { - vOut->x += div16(dx, len); - vOut->y += div16(dy, len); - vOut->z += div16(dz, len); - } - } - - void object3d_computePolygonNormal(const vec3* v0, const vec3* v1, const vec3* v2, vec3* out) - { - const fixed16_16 dx10 = v1->x - v0->x; - const fixed16_16 dy10 = v1->y - v0->y; - const fixed16_16 dz10 = v1->z - v0->z; - const fixed16_16 dx20 = v2->x - v0->x; - const fixed16_16 dy20 = v2->y - v0->y; - const fixed16_16 dz20 = v2->z - v0->z; - - out->x = v0->x + mul16(dz10, dy20) - mul16(dy10, dz20); - out->y = v0->y + mul16(dx10, dz20) - mul16(dz10, dx20); - out->z = v0->z + mul16(dy10, dx20) - mul16(dx10, dy20); - vec3_computeNormalOffset(out, v0, out); - } - - void object3d_computeVertexNormals(JediModel* model) - { - const s32 vertexCount = model->vertexCount; - const vec3* vertex = model->vertices; - - model->vertexNormals = (vec3*)model_alloc(vertexCount * sizeof(vec3)); - vec3* outNormal = model->vertexNormals; - if (!outNormal) - { - TFE_System::logWrite(LOG_ERROR, "ComputeVertexNormals", "Output normal pointer is NULL."); - return; - } - - // For each vertex, go through each polyon and see if it belongs. - // Add polygon normals for each polygon the vertex belongs to. - // Note: this is pretty brute force and will not scale well to high polygon models and is part of the reason why loading - // Dark Forces levels back in the day took so long... - for (s32 v = 0; v < vertexCount; v++, vertex++, outNormal++) - { - vec3 normal = { 0 }; - s32 ncount = 0; - vec3* cnrm = model->polygonNormals; - - const JmPolygon* polygon = model->polygons; - for (s32 p = 0; p < model->polygonCount; p++, polygon++, cnrm++) - { - const s32 polyVtxCount = polygon->vertexCount; - const s32* indices = polygon->indices; - for (s32 i = 0; i < polyVtxCount; i++) - { - if (v == indices[i]) - { - const vec3* v1 = &model->vertices[indices[1]]; - normal.x += cnrm->x - v1->x; - normal.y += cnrm->y - v1->y; - normal.z += cnrm->z - v1->z; - ncount++; - break; - } - } - } - - // The Jedi 3D object renderer expect normals in the form of v0 + dir rather than just dir as used today. - outNormal->x = vertex->x; - outNormal->y = vertex->y; - outNormal->z = vertex->z; - if (ncount > 0) - { - ncount = intToFixed16(ncount); - normal.x = div16(normal.x, ncount); - normal.y = div16(normal.y, ncount); - normal.z = div16(normal.z, ncount); - - const fixed16_16 lenSq = mul16(normal.x, normal.x) + mul16(normal.y, normal.y) + mul16(normal.z, normal.z); - const fixed16_16 len = fixedSqrt(lenSq); - if (len > 0) - { - outNormal->x += div16(normal.x, len); - outNormal->y += div16(normal.y, len); - outNormal->z += div16(normal.z, len); - } - } - } - } -} - -using namespace TFE_Jedi_Object3d; - -namespace TFE_Model_Jedi -{ - typedef std::map ModelMap; - typedef std::vector ModelList; - typedef std::map TextureMap; - typedef std::vector NameList; - static ModelMap s_models[POOL_COUNT]; - static ModelList s_modelList[POOL_COUNT]; - static NameList s_modelNames[POOL_COUNT]; - static std::vector s_buffer; - - // Remove 3DO limits. - static std::vector s_tmpVtx; - - bool parseModel(JediModel* model, const char* name, AssetPool pool); - - JediModel* get(const char* name, AssetPool pool) - { - ModelMap::iterator iModel = s_models[pool].find(name); - if (iModel != s_models[pool].end()) - { - return iModel->second; - } - - // It doesn't exist yet, try to load the model. - FilePath filePath; - if (!TFE_Paths::getFilePath(name, &filePath)) - { - return nullptr; - } - FileStream file; - if (!file.open(&filePath, Stream::MODE_READ)) - { - return nullptr; - } - size_t len = file.getSize(); - s_buffer.resize(len); - file.readBuffer(s_buffer.data(), u32(len)); - file.close(); - - s_memRegion = (pool == POOL_GAME) ? s_gameRegion : s_levelRegion; - JediModel* model = (JediModel*)model_alloc(sizeof(JediModel)); - memset(model, 0, sizeof(JediModel)); - - //////////////////////////////////////////////////////////////// - // Load and parse the model. - //////////////////////////////////////////////////////////////// - if (!parseModel(model, name, pool)) - { - return nullptr; - } - - //////////////////////////////////////////////////////////////// - // Post process the model. - //////////////////////////////////////////////////////////////// - // Compute culling normals. - model->polygonNormals = (vec3*)model_alloc(model->polygonCount * sizeof(vec3)); - - vec3* polygonNormal = model->polygonNormals; - JmPolygon* polygon = model->polygons; - for (s32 i = 0; i < model->polygonCount; i++, polygon++, polygonNormal++) - { - vec3* v0 = &model->vertices[polygon->indices[0]]; - vec3* v1 = &model->vertices[polygon->indices[1]]; - vec3* v2 = &model->vertices[polygon->indices[2]]; - object3d_computePolygonNormal(v1, v2, v0, polygonNormal); - } - - // Compute vertex normals if vertex lighting is required. - if (model->flags & MFLAG_VERTEX_LIT) - { - object3d_computeVertexNormals(model); - } - - // Compute the radius of the model (from <0,0,0>). - vec3* vertex = model->vertices; - fixed16_16 maxDist = 0; - for (s32 v = 0; v < model->vertexCount; v++, vertex++) - { - const fixed16_16 distSq = mul16(vertex->x,vertex->x) + mul16(vertex->y,vertex->y) + mul16(vertex->z,vertex->z); - const fixed16_16 dist = fixedSqrt(distSq); - if (dist > maxDist) - { - maxDist = dist; - } - } - model->radius = maxDist; - - // TODO (maybe): Cache binary models to disk so they can be - // directly loaded, which will reduce load time. - s_models[pool][name] = model; - s_modelList[pool].push_back(model); - s_modelNames[pool].push_back(name); - return model; - } - - bool getModelIndex(JediModel* model, s32* index, AssetPool* pool) - { - assert(index && pool); - if (!index || !pool) { return false; } - - for (s32 p = 0; p < POOL_COUNT; p++) - { - const size_t count = s_modelList[p].size(); - JediModel** list = s_modelList[p].data(); - for (size_t m = 0; m < count; m++) - { - if (list[m] == model) - { - *index = s32(m); - *pool = AssetPool(p); - return true; - } - } - } - return false; - } - - JediModel* getModelByIndex(s32 index, AssetPool pool) - { - if (pool >= POOL_COUNT || index >= (s32)s_modelList[pool].size()) - { - return nullptr; - } - return s_modelList[pool][index]; - } - - const std::vector& getModelList(AssetPool pool) - { - return s_modelList[pool]; - } - - void freePool(AssetPool pool) - { - // Memory will get freed with the memory region automatically. - s_models[pool].clear(); - -#ifndef TFE_ESPBOX - // free the memory of each models' drawId object - // (TFE_ESPBOX: the models live in the memory region, which may already have been - // cleared, and drawId is only ever set by the GPU renderer.) - const size_t count = s_modelList[pool].size(); - JediModel** models = s_modelList[pool].data(); - for (size_t i = 0; i < count; i++) - { - free(models[i]->drawId); - } -#endif - - s_modelList[pool].clear(); - s_modelNames[pool].clear(); - } - - void serializeModels(Stream* stream) - { - bool modeWrite = serialization_getMode() == SMODE_WRITE; - if (!modeWrite) - { - freePool(POOL_LEVEL); - } - - s32 count = (s32)s_modelNames[POOL_LEVEL].size(); - SERIALIZE(SaveVersionInit, count, 0); - - std::string* names = s_modelNames[POOL_LEVEL].data(); - std::string name; - for (s32 i = 0; i < count; i++) - { - u8 size; - if (modeWrite) - { - size = (u8)names[i].length(); - } - SERIALIZE(SaveVersionInit, size, 0); - - if (!modeWrite) - { - name.resize(size); - } - SERIALIZE_BUF(SaveVersionInit, modeWrite ? &names[i][0] : &name[0], size); - - if (!modeWrite) - { - get(name.c_str(), POOL_LEVEL); - } - } - } - - void freeAll() - { - for (s32 p = 0; p < POOL_COUNT; p++) - { - freePool(AssetPool(p)); - } - } - - void freeLevelData() - { - freePool(POOL_LEVEL); - } - - void allocatePolygon(JmPolygon* polygon, s32 vertexCount) - { - polygon->texture = 0; - polygon->shading = PSHADE_FLAT; - polygon->index = 0; - polygon->p08 = 0; - polygon->vertexCount = vertexCount; - polygon->uv = nullptr; - polygon->indices = (s32*)model_alloc(vertexCount * sizeof(s32)); - } - - bool parseModel(JediModel* model, const char* name, AssetPool pool) - { - if (s_buffer.empty()) { return false; } - const size_t len = s_buffer.size(); - - model->isBridge = 0; - model->vertexCount = 0; - model->vertices = nullptr; - model->polygonCount = 0; - model->polygons = nullptr; - model->vertexNormals = nullptr; - model->polygonNormals = nullptr; - model->flags = 0; - model->textureCount = 0; - model->textures = nullptr; - model->radius = 0; - model->drawId = nullptr; // invalid ID initially. - - // Check to see if the name has an underscore. - // If so, set the "isBridge" field. - const size_t nameLen = strlen(name); - for (size_t i = 0; i < nameLen; i++) - { - if (name[i] == '_') - { - model->isBridge = 1; - break; - } - } - - TFE_Parser parser; - size_t bufferPos = 0; - parser.init(s_buffer.data(), len); - const char* fileBuffer = s_buffer.data(); - parser.addCommentString("#"); - - // For now just do what the original code does. - // TODO: Make this more robust. - const char* buffer = parser.readLine(bufferPos, true); - if (!buffer) { return false; } - - s32 versionMajor, versionMinor; - if (sscanf(buffer, "3DO %d.%d", &versionMajor, &versionMinor) != 2) - { - TFE_System::logWrite(LOG_ERROR, "Object3D_Load", "'%s' has no valid name.", name); - assert(0); - return false; - } - if (versionMajor < 1 || (versionMajor == 1 && versionMinor < 2)) - { - TFE_System::logWrite(LOG_ERROR, "Object3D_Load", "'%s' has inavlid version", name); - assert(0); - return false; - } - - buffer = parser.readLine(bufferPos, true); - if (!buffer) { return false; } - char name3do[32]; - if (sscanf(buffer, "3DONAME %s", name3do) != 1) - { - TFE_System::logWrite(LOG_ERROR, "Object3D_Load", "'%s' has no valid 3DONAME.", name); - assert(0); - return false; - } - - buffer = parser.readLine(bufferPos, true); - if (!buffer) { return false; } - s32 objectCount; - if (sscanf(buffer, "OBJECTS %d", &objectCount) != 1) - { - TFE_System::logWrite(LOG_ERROR, "Object3D_Load", "'%s' has no objects.", name); - assert(0); - return false; - } - - buffer = parser.readLine(bufferPos, true); - if (!buffer) { return false; } - s32 vertexCount; - if (sscanf(buffer, "VERTICES %d", &vertexCount) != 1) - { - TFE_System::logWrite(LOG_ERROR, "Object3D_Load", "'%s' has no vertices.", name); - assert(0); - return false; - } - if (!TFE_Settings::getGraphicsSettings()->ignore3doLimits && vertexCount > MAX_VERTEX_COUNT_3DO) - { - TFE_System::logWrite(LOG_ERROR, "Object3D_Load", "'%s' has too many vertices: %d / %d.", name, vertexCount, MAX_VERTEX_COUNT_3DO); - assert(0); - return false; - } - model->vertices = (vec3*)model_alloc(vertexCount * sizeof(vec3)); - - buffer = parser.readLine(bufferPos, true); - if (!buffer) { return false; } - s32 polygonCount; - if (sscanf(buffer, "POLYGONS %d", &polygonCount) != 1) - { - TFE_System::logWrite(LOG_ERROR, "Object3D_Load", "'%s' has no polygons.", name); - assert(0); - return false; - } - if (!TFE_Settings::getGraphicsSettings()->ignore3doLimits && polygonCount > MAX_POLYGON_COUNT_3DO) - { - TFE_System::logWrite(LOG_ERROR, "Object3D_Load", "'%s' has too many polygons: %d / %d.", name, polygonCount, MAX_POLYGON_COUNT_3DO); - assert(0); - return false; - } - model->polygons = (JmPolygon*)model_alloc(polygonCount * sizeof(JmPolygon)); - - buffer = parser.readLine(bufferPos, true); - if (!buffer) { return false; } - char palette[32]; - if (sscanf(buffer, "PALETTE %s", palette) != 1) - { - TFE_System::logWrite(LOG_ERROR, "Object3D_Load", "'%s' has no PALETTE.", name); - assert(0); - return false; - } - - buffer = parser.readLine(bufferPos, true); - if (!buffer) { return false; } - s32 textureCount; - if (sscanf(buffer, "TEXTURES %d", &textureCount) != 1) - { - TFE_System::logWrite(LOG_ERROR, "Object3D_Load", "'%s' has no valid TEXTURES entry.", name); - assert(0); - return false; - } - - // Load textures. - MemoryRegion* prevMemRegion = TFE_Jedi::bitmap_getAllocator(); - TFE_Jedi::bitmap_setAllocator(s_memRegion); - model->textures = nullptr; - if (textureCount) - { - model->textures = (TextureData**)model_alloc(textureCount * sizeof(TextureData*)); - model->textureCount = textureCount; - TextureData** texture = model->textures; - for (s32 i = 0; i < textureCount; i++, texture++) - { - buffer = parser.readLine(bufferPos, true); - if (!buffer) { return false; } - - char textureName[256]; - if (sscanf(buffer, " TEXTURE: %s ", textureName) != 1) - { - TFE_System::logWrite(LOG_WARNING, "Object3D_Load", "'%s' unable to parse TEXTURE: entry.", name); - *texture = TFE_Jedi::bitmap_load("default.bm", 1, pool); - continue; - } - - *texture = nullptr; - if (strcasecmp(textureName, "")) - { - *texture = TFE_Jedi::bitmap_load(textureName, 1, pool); - if (!(*texture)) - { - *texture = TFE_Jedi::bitmap_load("default.bm", 1, pool); - } - } - } - } - TFE_Jedi::bitmap_setAllocator(prevMemRegion); - - bool nextLine = true; - s32 vertexOffset = 0; - for (s32 i = 0; i < objectCount; i++) - { - if (nextLine) - { - buffer = parser.readLine(bufferPos, true); - } - if (!buffer) { break; } - nextLine = true; - - char objName[32]; - if (sscanf(buffer, " OBJECT %s", objName) != 1) - { - // Some of the models have fewer object entries than objectCount (bad data, "fixed" by the code). - TFE_System::logWrite(LOG_WARNING, "Object3D_Load", "'%s' has too few objects, continuing anyway.", name); - break; - } - - buffer = parser.readLine(bufferPos, true); - if (!buffer) { return false; } - s32 textureId; - if (sscanf(buffer, " TEXTURE %d", &textureId) != 1) - { - TFE_System::logWrite(LOG_ERROR, "Object3D_Load", "'%s' unable to parse TEXTURE ID.", name); - assert(0); - return false; - } - TextureData* texture = nullptr; - if (textureId != -1 && model->textures) - { - texture = model->textures[textureId]; - } - - buffer = parser.readLine(bufferPos, true); - if (!buffer) { return false; } - if (sscanf(buffer, " VERTICES %d", &vertexCount) != 1) - { - TFE_System::logWrite(LOG_ERROR, "Object3D_Load", "'%s' unable to parse object VERTICES entry.", name); - assert(0); - return false; - } - // Apparently zero vertex objects are allowed, these simply refer back to the existing vertex offset. - if (vertexCount) - { - vertexOffset = model->vertexCount; - } - - while (1) - { - buffer = parser.readLine(bufferPos, true); - if (!buffer) - { - nextLine = false; - break; - } - - s32 index; - f32 x, y, z; - if (sscanf(buffer, " %d: %f %f %f", &index, &x, &y, &z) != 4) - { - nextLine = false; - break; - } - model->vertices[model->vertexCount].x = floatToFixed16(x); - model->vertices[model->vertexCount].y = floatToFixed16(y); - model->vertices[model->vertexCount].z = floatToFixed16(z); - model->vertexCount++; - } - - if (nextLine) - { - buffer = parser.readLine(bufferPos, true); - if (!buffer) { return false; } - } - nextLine = true; - - s32 triangleCount = 0, quadCount = 0; - s32 basePolygonCount = model->polygonCount; - if (sscanf(buffer, " TRIANGLES %d", &triangleCount) == 1) - { - s32 polygonCount = model->polygonCount; - while (1) - { - buffer = parser.readLine(bufferPos, true); - if (!buffer) - { - nextLine = false; - break; - } - - s32 num, a, b, c, color; - char shading[32]; - if (sscanf(buffer, " %d: %d %d %d %d %s ", &num, &a, &b, &c, &color, shading) != 6) - { - nextLine = false; - break; - } - - a += vertexOffset; - b += vertexOffset; - c += vertexOffset; - - JmPolygon* polygon = &model->polygons[model->polygonCount]; - allocatePolygon(polygon, 3); - - polygon->index = model->polygonCount; - polygon->texture = texture; - polygon->indices[0] = a; - polygon->indices[1] = b; - polygon->indices[2] = c; - polygon->color = color; - - model->polygonCount++; - - if (strcasecmp(shading, "FLAT") == 0) - { - polygon->shading = PSHADE_FLAT; - } - else if (strcasecmp(shading, "VERTEX") == 0) - { - polygon->shading = PSHADE_FLAT; - model->flags = MFLAG_DRAW_VERTICES; - } - else if (strcasecmp(shading, "TEXTURE") == 0) - { - polygon->shading = PSHADE_TEXTURE; - } - else if (strcasecmp(shading, "GOURAUD") == 0) - { - polygon->shading = PSHADE_GOURAUD; - model->flags |= MFLAG_VERTEX_LIT; - } - else if (strcasecmp(shading, "GOURTEX") == 0) - { - polygon->shading = PSHADE_GOURAUD_TEXTURE; - model->flags |= MFLAG_VERTEX_LIT; - } - else if (strcasecmp(shading, "PLANE") == 0) - { - polygon->shading = PSHADE_PLANE; - } - else - { - // ERROR! - TFE_System::logWrite(LOG_ERROR, "Object3D_Load", "Invalid polygon shading: %s", shading); - assert(0); - } - } - } - else if (sscanf(buffer, " QUADS %d", &quadCount) == 1) - { - s32 polygonCount = model->polygonCount; - while (1) - { - buffer = parser.readLine(bufferPos, true); - if (!buffer) - { - nextLine = false; - break; - } - - s32 num, a, b, c, d, color; - char shading[32]; - if (sscanf(buffer, " %d: %d %d %d %d %d %s", &num, &a, &b, &c, &d, &color, shading) != 7) - { - nextLine = false; - break; - } - a += vertexOffset; - b += vertexOffset; - c += vertexOffset; - d += vertexOffset; - - JmPolygon* polygon = &model->polygons[model->polygonCount]; - allocatePolygon(polygon, 4); - - polygon->index = model->polygonCount; - polygon->texture = texture; - polygon->indices[0] = a; - polygon->indices[1] = b; - polygon->indices[2] = c; - polygon->indices[3] = d; - polygon->color = color; - - model->polygonCount++; - - if (strcasecmp(shading, "FLAT") == 0) - { - polygon->shading = PSHADE_FLAT; - } - else if (strcasecmp(shading, "VERTEX") == 0) - { - polygon->shading = PSHADE_FLAT; - model->flags = MFLAG_DRAW_VERTICES; - } - else if (strcasecmp(shading, "TEXTURE") == 0) - { - polygon->shading = PSHADE_TEXTURE; - } - else if (strcasecmp(shading, "GOURAUD") == 0) - { - polygon->shading = PSHADE_GOURAUD; - model->flags |= MFLAG_VERTEX_LIT; - } - else if (strcasecmp(shading, "GOURTEX") == 0) - { - polygon->shading = PSHADE_GOURAUD_TEXTURE; - model->flags |= MFLAG_VERTEX_LIT; - } - else if (strcasecmp(shading, "PLANE") == 0) - { - polygon->shading = PSHADE_PLANE; - } - else - { - // ERROR! - TFE_System::logWrite(LOG_ERROR, "Object3D_Load", "Invalid polygon shading: %s", shading); - assert(0); - } - } - } - else // No polygons - { - TFE_System::logWrite(LOG_ERROR, "Object3D_Load", "'%s' object %s has no polygons.", name, objName); - return false; - } - - if (texture) - { - if (nextLine) - { - buffer = parser.readLine(bufferPos, true); - if (!buffer) { return false; } - } - nextLine = true; - - s32 texVertexCount; - if (sscanf(buffer, " TEXTURE VERTICES %d", &texVertexCount) != 1) - { - TFE_System::logWrite(LOG_ERROR, "Object3D_Load", "'%s' unable to parse TEXTURE VERTICES.", name); - assert(0); - return false; - } - - // pre-allocate; make sure it handles at least one primitive... - s_tmpVtx.resize(max(texVertexCount, 4) * 2); - - nextLine = true; - // Keep reading until the format no longer matches... - for (s32 v = 0; ; v++) - { - buffer = parser.readLine(bufferPos, true); - if (!buffer) { return false; } - - // Just in case the reported vertex count is too small. - // Unfortunately data errors like this are common. - if (v >= s_tmpVtx.size()) - { - s_tmpVtx.resize(v * 2); - } - - s32 num; - f32 x, y; - if (sscanf(buffer, " %d: %f %f", &num, &x, &y) != 3) - { - // Handle buggy input data. - nextLine = false; - break; - } - // clamp texture coordinate range. - if (x < 0.0f) { x = 0.0f; } - if (y < 0.0f) { y = 0.0f; } - if (x > 1.0f) { x = 1.0f; } - if (y > 1.0f) { y = 1.0f; } - - s_tmpVtx[v].x = floatToFixed16(x); - s_tmpVtx[v].y = floatToFixed16(y); - } - - if (nextLine) - { - buffer = parser.readLine(bufferPos, true); - if (!buffer) { return false; } - } - nextLine = true; - - s32 texTriangleCount; - s32 texQuadCount; - if (sscanf(buffer, " TEXTURE TRIANGLES %d", &texTriangleCount) == 1) - { - JmPolygon* polygon = &model->polygons[basePolygonCount]; - while (1) - { - buffer = parser.readLine(bufferPos, true); - if (!buffer) { break; } - - s32 num, a, b, c; - if (sscanf(buffer, " %d: %d %d %d", &num, &a, &b, &c) != 4) - { - nextLine = false; - break; - } - - polygon->uv = (vec2*)model_alloc(sizeof(vec2) * 3); - fixed16_16 texWidth = intToFixed16(texture->uvWidth); - fixed16_16 texHeight = intToFixed16(texture->uvHeight); - - polygon->uv[0].x = mul16(s_tmpVtx[a].x, texWidth); - polygon->uv[0].y = mul16(s_tmpVtx[a].y, texHeight); - polygon->uv[1].x = mul16(s_tmpVtx[b].x, texWidth); - polygon->uv[1].y = mul16(s_tmpVtx[b].y, texHeight); - polygon->uv[2].x = mul16(s_tmpVtx[c].x, texWidth); - polygon->uv[2].y = mul16(s_tmpVtx[c].y, texHeight); - - polygon++; - } - } - else if (sscanf(buffer, " TEXTURE QUADS %d", &texQuadCount) == 1) - { - JmPolygon* polygon = &model->polygons[basePolygonCount]; - while (1) - { - buffer = parser.readLine(bufferPos, true); - if (!buffer) { break; } - - s32 num, a, b, c, d; - if (sscanf(buffer, " %d: %d %d %d %d", &num, &a, &b, &c, &d) != 5) - { - nextLine = false; - break; - } - polygon->uv = (vec2*)model_alloc(sizeof(vec2) * 4); - fixed16_16 texWidth = intToFixed16(texture->uvWidth); - fixed16_16 texHeight = intToFixed16(texture->uvHeight); - - polygon->uv[0].x = mul16(s_tmpVtx[a].x, texWidth); - polygon->uv[0].y = mul16(s_tmpVtx[a].y, texHeight); - polygon->uv[1].x = mul16(s_tmpVtx[b].x, texWidth); - polygon->uv[1].y = mul16(s_tmpVtx[b].y, texHeight); - polygon->uv[2].x = mul16(s_tmpVtx[c].x, texWidth); - polygon->uv[2].y = mul16(s_tmpVtx[c].y, texHeight); - polygon->uv[3].x = mul16(s_tmpVtx[d].x, texWidth); - polygon->uv[3].y = mul16(s_tmpVtx[d].y, texHeight); - - polygon++; - } - } - } - } - - return true; - } -}; - -#ifdef TFE_ESPBOX -// The file read scratch buffer keeps the capacity of the largest file loaded; -// release it when the game is shut down (called from the platform glue). -void espbox_free_model_scratch() -{ - std::vector().swap(TFE_Model_Jedi::s_buffer); -} -#endif - -#ifdef TFE_ESPBOX -// Shutdown only: release this file's cached container storage so nothing is -// left in the 4MB ROM block when the session ends (see esp_alloc.cpp). -void espbox_release_model_caches() -{ - std::vector().swap(TFE_Model_Jedi::s_tmpVtx); - for (auto& names : TFE_Model_Jedi::s_modelNames) { TFE_Model_Jedi::NameList().swap(names); } - for (auto& map : TFE_Model_Jedi::s_models) { TFE_Model_Jedi::ModelMap().swap(map); } - for (auto& list : TFE_Model_Jedi::s_modelList) { TFE_Model_Jedi::ModelList().swap(list); } -} -#endif diff --git a/components/darkforces/tfe/TFE_Asset/modelAsset_jedi.h b/components/darkforces/tfe/TFE_Asset/modelAsset_jedi.h deleted file mode 100644 index 2208e299..00000000 --- a/components/darkforces/tfe/TFE_Asset/modelAsset_jedi.h +++ /dev/null @@ -1,82 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Jedi specific structures for 3DOs -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include - -#define MAX_VERTEX_COUNT_3DO 500 -#define MAX_POLYGON_COUNT_3DO 400 - -struct TextureData; - -enum PolygonShadingFlags -{ - PSHADE_FLAT = 0, - PSHADE_GOURAUD = 1, - PSHADE_TEXTURE = 2, - PSHADE_GOURAUD_TEXTURE = PSHADE_GOURAUD | PSHADE_TEXTURE, - PSHADE_PLANE = 4, -}; - -enum ModelFlags -{ - MFLAG_VERTEX_LIT = (1 << 1), - MFLAG_DRAW_VERTICES = (1 << 2), -}; - -struct vec2 -{ - s32 x, y; -}; - -struct vec3 -{ - s32 x, y, z; -}; - -// sizeof(Polygon) = 36 -struct JmPolygon -{ - s32 index; - s32 shading; - s32 p08; - s32 color; - TextureData* texture; - s32 vertexCount; - s32* indices; - vec2* uv; - union { s32 zAve; f32 zAvef; }; - s32 p24; -}; - -struct JediModel -{ - s32 isBridge; // this 3D object is a 3D "bridge" which gets special sorting. All 3D objects with '_' in their name get this flag. - s32 vertexCount; - vec3* vertices; - s32 polygonCount; - JmPolygon* polygons; - vec3* vertexNormals; - vec3* polygonNormals; - s32 flags; - s32 textureCount; - TextureData** textures; - s32 radius; - void* drawId; // TFE: Added for the GPU renderer. -}; - -namespace TFE_Model_Jedi -{ - JediModel* get(const char* name, AssetPool pool = POOL_LEVEL); - const std::vector& getModelList(AssetPool pool); - void freeAll(); - void freeLevelData(); - - bool getModelIndex(JediModel* model, s32* index, AssetPool* pool); - JediModel* getModelByIndex(s32 index, AssetPool pool); - - void serializeModels(Stream* stream); -} diff --git a/components/darkforces/tfe/TFE_Asset/msf_gif.h b/components/darkforces/tfe/TFE_Asset/msf_gif.h deleted file mode 100644 index 348b1b18..00000000 --- a/components/darkforces/tfe/TFE_Asset/msf_gif.h +++ /dev/null @@ -1,608 +0,0 @@ -/* -HOW TO USE: - - In exactly one translation unit (.c or .cpp file), #define MSF_GIF_IMPL before including the header, like so: - - #define MSF_GIF_IMPL - #include "msf_gif.h" - - Everywhere else, just include the header like normal. - - -USAGE EXAMPLE: - - int width = 480, height = 320, centisecondsPerFrame = 5, bitDepth = 16; - MsfGifState gifState = {}; - msf_gif_begin(&gifState, width, height); - msf_gif_frame(&gifState, ..., centisecondsPerFrame, bitDepth, width * 4); //frame 1 - msf_gif_frame(&gifState, ..., centisecondsPerFrame, bitDepth, width * 4); //frame 2 - msf_gif_frame(&gifState, ..., centisecondsPerFrame, bitDepth, width * 4); //frame 3, etc... - MsfGifResult result = msf_gif_end(&gifState); - FILE * fp = fopen("MyGif.gif", "wb"); - fwrite(result.data, result.dataSize, 1, fp); - fclose(fp); - msf_gif_free(result); - -Detailed function documentation can be found in the header section below. - - -REPLACING MALLOC: - - This library uses malloc+realloc+free internally for memory allocation. - To facilitate integration with custom memory allocators, these calls go through macros, which can be redefined. - The expected function signature equivalents of the macros are as follows: - - void * MSF_GIF_MALLOC(void * context, size_t newSize) - void * MSF_GIF_REALLOC(void * context, void * oldMemory, size_t oldSize, size_t newSize) - void MSF_GIF_FREE(void * context, void * oldMemory, size_t oldSize) - - If your allocator needs a context pointer, you can set the `customAllocatorContext` field of the MsfGifState struct - before calling msf_gif_begin(), and it will be passed to all subsequent allocator macro calls. - -See end of file for license information. -*/ - -//version 2.1 - -#ifndef MSF_GIF_H -#define MSF_GIF_H - -#include -#include - -typedef struct { - void * data; - size_t dataSize; - - size_t allocSize; //internal use - void * contextPointer; //internal use -} MsfGifResult; - -typedef struct { //internal use - uint32_t * pixels; - int depth, count, rbits, gbits, bbits; -} MsfCookedFrame; - -typedef struct { - MsfCookedFrame previousFrame; - uint8_t * listHead; - uint8_t * listTail; - int width, height; - void * customAllocatorContext; -} MsfGifState; - -#ifdef __cplusplus -extern "C" { -#endif //__cplusplus - -/** - * @param width Image width in pixels. - * @param height Image height in pixels. - * @return Non-zero on success, 0 on error. - */ -int msf_gif_begin(MsfGifState * handle, int width, int height); - -/** - * @param pixelData Pointer to raw framebuffer data. Rows must be contiguous in memory, in RGBA8 format. - * Note: This function does NOT free `pixelData`. You must free it yourself afterwards. - * @param centiSecondsPerFrame How many hundredths of a second this frame should be displayed for. - * Note: This being specified in centiseconds is a limitation of the GIF format. - * @param maxBitDepth Limits how many bits per pixel can be used when quantizing the gif. - * The actual bit depth chosen for a given frame will be less than or equal to - * the supplied maximum, depending on the variety of colors used in the frame. - * `maxBitDepth` will be clamped between 1 and 16. The recommended default is 16. - * Lowering this value can result in faster exports and smaller gifs, - * but the quality may suffer. - * Please experiment with this value to find what works best for your application. - * @param pitchInBytes The number of bytes from the beginning of one row of pixels to the beginning of the next. - * If you want to flip the image, just pass in a negative pitch. - * @return Non-zero on success, 0 on error. - */ -int msf_gif_frame(MsfGifState * handle, uint8_t * pixelData, int centiSecondsPerFame, int maxBitDepth, int pitchInBytes); - -/** - * @return A block of memory containing the gif file data, or NULL on error. - * You are responsible for freeing this via `msf_gif_free()`. - */ -MsfGifResult msf_gif_end(MsfGifState * handle); - -/** - * @param result The MsfGifResult struct, verbatim as it was returned from `msf_gif_end()`. - */ -void msf_gif_free(MsfGifResult result); - -#ifdef __cplusplus -} -#endif //__cplusplus - -#endif //MSF_GIF_H - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -/// IMPLEMENTATION /// -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -#ifdef MSF_GIF_IMPL -#ifndef MSF_GIF_ALREADY_IMPLEMENTED_IN_THIS_TRANSLATION_UNIT -#define MSF_GIF_ALREADY_IMPLEMENTED_IN_THIS_TRANSLATION_UNIT - -#ifndef MSF_GIF_BUFFER_INIT_SIZE -#define MSF_GIF_BUFFER_INIT_SIZE 1024 * 1024 * 4 //4MB by default, you can increase this if you want to realloc less -#endif - -//ensure the library user has either defined all of malloc/realloc/free, or none -#if defined(MSF_GIF_MALLOC) && defined(MSF_GIF_REALLOC) && defined(MSF_GIF_FREE) //ok -#elif !defined(MSF_GIF_MALLOC) && !defined(MSF_GIF_REALLOC) && !defined(MSF_GIF_FREE) //ok -#else -#error "You must either define all of MSF_GIF_MALLOC, MSF_GIF_REALLOC, and MSF_GIF_FREE, or define none of them" -#endif - -//provide default allocator definitions that redirect to the standard global allocator -#if !defined(MSF_GIF_MALLOC) -#include //malloc, etc. -#define MSF_GIF_MALLOC(contextPointer, newSize) malloc(newSize) -#define MSF_GIF_REALLOC(contextPointer, oldMemory, oldSize, newSize) realloc(oldMemory, newSize) -#define MSF_GIF_FREE(contextPointer, oldMemory, oldSize) free(oldMemory) -#endif - -//instrumentation for capturing profiling traces (useless for the library user, but useful for the library author) -#ifdef MSF_GIF_ENABLE_TRACING -#define MsfTimeFunc TimeFunc -#define MsfTimeLoop TimeLoop -#define msf_init_profiling_thread init_profiling_thread -#else -#define MsfTimeFunc -#define MsfTimeLoop(name) -#define msf_init_profiling_thread() -#endif //MSF_GIF_ENABLE_TRACING - -#include //memcpy - -//TODO: use compiler-specific notation to force-inline functions currently marked inline -#if defined(__GNUC__) //gcc, clang -static inline int msf_bit_log(int i) { return 32 - __builtin_clz(i); } -#elif defined(_MSC_VER) //msvc -#include -static inline int msf_bit_log(int i) { unsigned long idx; _BitScanReverse(&idx, i); return idx + 1; } -#else //fallback implementation for other compilers -//from https://stackoverflow.com/a/31718095/3064745 - thanks! -static inline int msf_bit_log(int i) { - static const int MultiplyDeBruijnBitPosition[32] = { - 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, - 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31, - }; - i |= i >> 1; - i |= i >> 2; - i |= i >> 4; - i |= i >> 8; - i |= i >> 16; - return MultiplyDeBruijnBitPosition[(uint32_t)(i * 0x07C4ACDDU) >> 27] + 1; -} -#endif -static inline int msf_imin(int a, int b) { return a < b? a : b; } -static inline int msf_imax(int a, int b) { return b < a? a : b; } - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -/// Frame Cooking /// -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -#if (defined (__SSE2__) || defined (_M_X64) || _M_IX86_FP == 2) && !defined(MSF_GIF_NO_SSE2) -#include -#endif - -static MsfCookedFrame msf_cook_frame(void * allocContext, uint8_t * raw, uint8_t * used, - int width, int height, int pitch, int depth) -{ MsfTimeFunc - //bit depth for each channel - const static int rdepths[17] = { 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5 }; - const static int gdepths[17] = { 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6 }; - const static int bdepths[17] = { 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5 }; - - const static int ditherKernel[16] = { - 0 << 12, 8 << 12, 2 << 12, 10 << 12, - 12 << 12, 4 << 12, 14 << 12, 6 << 12, - 3 << 12, 11 << 12, 1 << 12, 9 << 12, - 15 << 12, 7 << 12, 13 << 12, 5 << 12, - }; - - uint32_t * cooked = (uint32_t *) MSF_GIF_MALLOC(allocContext, width * height * sizeof(uint32_t)); - if (!cooked) { MsfCookedFrame blank = {0}; return blank; } - - int count = 0; - MsfTimeLoop("do") do { - int rbits = rdepths[depth], gbits = gdepths[depth], bbits = bdepths[depth]; - int paletteSize = 1 << (rbits + gbits + bbits); - memset(used, 0, paletteSize * sizeof(uint8_t)); - - //TODO: document what this math does and why it's correct - int rdiff = (1 << (8 - rbits)) - 1; - int gdiff = (1 << (8 - gbits)) - 1; - int bdiff = (1 << (8 - bbits)) - 1; - short rmul = (short) ((255.0f - rdiff) / 255.0f * 257); - short gmul = (short) ((255.0f - gdiff) / 255.0f * 257); - short bmul = (short) ((255.0f - bdiff) / 255.0f * 257); - - int gmask = ((1 << gbits) - 1) << rbits; - int bmask = ((1 << bbits) - 1) << rbits << gbits; - - MsfTimeLoop("cook") for (int y = 0; y < height; ++y) { - int x = 0; - - #if (defined (__SSE2__) || defined (_M_X64) || _M_IX86_FP == 2) && !defined(MSF_GIF_NO_SSE2) - __m128i k = _mm_loadu_si128((__m128i *) &ditherKernel[(y & 3) * 4]); - __m128i k2 = _mm_or_si128(_mm_srli_epi32(k, rbits), _mm_slli_epi32(_mm_srli_epi32(k, bbits), 16)); - // MsfTimeLoop("SIMD") - for (; x < width - 3; x += 4) { - uint8_t * pixels = &raw[y * pitch + x * 4]; - __m128i p = _mm_loadu_si128((__m128i *) pixels); - - __m128i rb = _mm_and_si128(p, _mm_set1_epi32(0x00FF00FF)); - __m128i rb1 = _mm_mullo_epi16(rb, _mm_set_epi16(bmul, rmul, bmul, rmul, bmul, rmul, bmul, rmul)); - __m128i rb2 = _mm_adds_epu16(rb1, k2); - __m128i r3 = _mm_srli_epi32(_mm_and_si128(rb2, _mm_set1_epi32(0x0000FFFF)), 16 - rbits); - __m128i b3 = _mm_and_si128(_mm_srli_epi32(rb2, 32 - rbits - gbits - bbits), _mm_set1_epi32(bmask)); - - __m128i g = _mm_and_si128(_mm_srli_epi32(p, 8), _mm_set1_epi32(0x000000FF)); - __m128i g1 = _mm_mullo_epi16(g, _mm_set1_epi32(gmul)); - __m128i g2 = _mm_adds_epu16(g1, _mm_srli_epi32(k, gbits)); - __m128i g3 = _mm_and_si128(_mm_srli_epi32(g2, 16 - rbits - gbits), _mm_set1_epi32(gmask)); - - //TODO: does storing this as a __m128i then reading it back as a uint32_t violate strict aliasing? - uint32_t * c = &cooked[y * width + x]; - __m128i out = _mm_or_si128(_mm_or_si128(r3, g3), b3); - _mm_storeu_si128((__m128i *) c, out); - } - #endif - - //scalar cleanup loop - // MsfTimeLoop("scalar") - for (; x < width; ++x) { - uint8_t * p = &raw[y * pitch + x * 4]; - int dx = x & 3, dy = y & 3; - int k = ditherKernel[dy * 4 + dx]; - cooked[y * width + x] = - (msf_imin(65535, p[2] * bmul + (k >> bbits)) >> (16 - rbits - gbits - bbits) & bmask) | - (msf_imin(65535, p[1] * gmul + (k >> gbits)) >> (16 - rbits - gbits ) & gmask) | - msf_imin(65535, p[0] * rmul + (k >> rbits)) >> (16 - rbits ); - } - } - - count = 0; - MsfTimeLoop("mark and count") for (int i = 0; i < width * height; ++i) { - used[cooked[i]] = 1; - } - - //count used colors - MsfTimeLoop("count") for (int j = 0; j < paletteSize; ++j) { - count += used[j]; - } - } while (count >= 256 && --depth); - - MsfCookedFrame ret = { cooked, depth, count, rdepths[depth], gdepths[depth], bdepths[depth] }; - return ret; -} - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -/// Frame Compression /// -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -typedef struct { - uint8_t * next; - size_t size; -} MsfBufferHeader; - -static inline int msf_put_code(uint8_t * * writeHead, uint32_t * blockBits, int len, uint32_t code) { - //insert new code into block buffer - int idx = *blockBits / 8; - int bit = *blockBits % 8; - (*writeHead)[idx + 0] |= code << bit ; - (*writeHead)[idx + 1] |= code >> ( 8 - bit); - (*writeHead)[idx + 2] |= code >> (16 - bit); - *blockBits += len; - - //prep the next block buffer if the current one is full - if (*blockBits >= 256 * 8) { - *blockBits -= 255 * 8; - (*writeHead) += 256; - (*writeHead)[2] = (*writeHead)[1]; - (*writeHead)[1] = (*writeHead)[0]; - (*writeHead)[0] = 255; - memset((*writeHead) + 4, 0, 256); - } - - return 1; -} - -typedef struct { - int16_t * data; - int len; - int stride; -} MsfStridedList; - -static inline void msf_lzw_reset(MsfStridedList * lzw, int tableSize, int stride) { MsfTimeFunc - memset(lzw->data, 0xFF, 4096 * stride * sizeof(int16_t)); - lzw->len = tableSize + 2; - lzw->stride = stride; -} - -static uint8_t * msf_compress_frame(void * allocContext, int width, int height, int centiSeconds, - MsfCookedFrame frame, MsfCookedFrame previous, uint8_t * used) -{ MsfTimeFunc - //NOTE: we reserve enough memory for theoretical the worst case upfront because it's a reasonable amount, - // and prevents us from ever having to check size or realloc during compression - int maxBufSize = sizeof(MsfBufferHeader) + 32 + 256 * 3 + width * height * 3 / 2; //headers + color table + data - uint8_t * allocation = (uint8_t *) MSF_GIF_MALLOC(allocContext, maxBufSize); - if (!allocation) { return NULL; } - uint8_t * writeBase = allocation + sizeof(MsfBufferHeader); - uint8_t * writeHead = writeBase; - int lzwAllocSize = 4096 * (frame.count + 1) * sizeof(int16_t); - MsfStridedList lzw = { (int16_t *) MSF_GIF_MALLOC(allocContext, lzwAllocSize) }; - if (!lzw.data) { MSF_GIF_FREE(allocContext, allocation, maxBufSize); return NULL; } - - //allocate tlb - int totalBits = frame.rbits + frame.gbits + frame.bbits; - int tlbSize = 1 << totalBits; - uint8_t tlb[1 << 16]; //only 64k, so stack allocating is fine - - //generate palette - typedef struct { uint8_t r, g, b; } Color3; - Color3 table[256] = { {0} }; - int tableIdx = 1; //we start counting at 1 because 0 is the transparent color - MsfTimeLoop("table") for (int i = 0; i < tlbSize; ++i) { - if (used[i]) { - tlb[i] = tableIdx; - int rmask = (1 << frame.rbits) - 1; - int gmask = (1 << frame.gbits) - 1; - //isolate components - int r = i & rmask; - int g = i >> frame.rbits & gmask; - int b = i >> (frame.rbits + frame.gbits); - //shift into highest bits - r <<= 8 - frame.rbits; - g <<= 8 - frame.gbits; - b <<= 8 - frame.bbits; - table[tableIdx].r = r | r >> frame.rbits | r >> (frame.rbits * 2) | r >> (frame.rbits * 3); - table[tableIdx].g = g | g >> frame.gbits | g >> (frame.gbits * 2) | g >> (frame.gbits * 3); - table[tableIdx].b = b | b >> frame.bbits | b >> (frame.bbits * 2) | b >> (frame.bbits * 3); - ++tableIdx; - } - } - - //SPEC: "Because of some algorithmic constraints however, black & white images which have one color bit - // must be indicated as having a code size of 2." - int tableBits = msf_imax(2, msf_bit_log(tableIdx - 1)); - int tableSize = 1 << tableBits; - //NOTE: we don't just compare `depth` field here because it will be wrong for the first frame and we will segfault - int hasSamePal = frame.rbits == previous.rbits && frame.gbits == previous.gbits && frame.bbits == previous.bbits; - - //NOTE: because __attribute__((__packed__)) is annoyingly compiler-specific, we do this unreadable weirdness - char headerBytes[19] = "\x21\xF9\x04\x05\0\0\0\0" "\x2C\0\0\0\0\0\0\0\0\x80"; - memcpy(&headerBytes[4], ¢iSeconds, 2); - memcpy(&headerBytes[13], &width, 2); - memcpy(&headerBytes[15], &height, 2); - headerBytes[17] |= tableBits - 1; - memcpy(writeHead, headerBytes, 18); - writeHead += 18; - - //local color table - memcpy(writeHead, table, tableSize * sizeof(Color3)); - writeHead += tableSize * sizeof(Color3); - *writeHead++ = tableBits; - - //prep block - memset(writeHead, 0, 260); - writeHead[0] = 255; - uint32_t blockBits = 8; //relative to block.head - - //SPEC: "Encoders should output a Clear code as the first code of each image data stream." - msf_lzw_reset(&lzw, tableSize, tableIdx); - msf_put_code(&writeHead, &blockBits, msf_bit_log(lzw.len - 1), tableSize); - - int lastCode = hasSamePal && frame.pixels[0] == previous.pixels[0]? 0 : tlb[frame.pixels[0]]; - MsfTimeLoop("compress") for (int i = 1; i < width * height; ++i) { - //PERF: branching vs. branchless version of this line is observed to have no discernable impact on speed - int color = hasSamePal && frame.pixels[i] == previous.pixels[i]? 0 : tlb[frame.pixels[i]]; - //PERF: branchless version must use && otherwise it will segfault on frame 1, but it's well-predicted so OK - // int color = (!(hasSamePal && frame.pixels[i] == previous.pixels[i])) * tlb[frame.pixels[i]]; - int code = (&lzw.data[lastCode * lzw.stride])[color]; - if (code < 0) { - //write to code stream - int codeBits = msf_bit_log(lzw.len - 1); - msf_put_code(&writeHead, &blockBits, codeBits, lastCode); - - if (lzw.len > 4095) { - //reset buffer code table - msf_put_code(&writeHead, &blockBits, codeBits, tableSize); - msf_lzw_reset(&lzw, tableSize, tableIdx); - } else { - (&lzw.data[lastCode * lzw.stride])[color] = lzw.len; - ++lzw.len; - } - - lastCode = color; - } else { - lastCode = code; - } - } - - MSF_GIF_FREE(allocContext, lzw.data, lzwAllocSize); - MSF_GIF_FREE(allocContext, previous.pixels, width * height * sizeof(uint32_t)); - - //write code for leftover index buffer contents, then the end code - msf_put_code(&writeHead, &blockBits, msf_imin(12, msf_bit_log(lzw.len - 1)), lastCode); - msf_put_code(&writeHead, &blockBits, msf_imin(12, msf_bit_log(lzw.len)), tableSize + 1); - - //flush remaining data - if (blockBits > 8) { - int bytes = (blockBits + 7) / 8; //round up - writeHead[0] = bytes - 1; - writeHead += bytes; - } - *writeHead++ = 0; //terminating block - - //filling in buffer header and shrink buffer to fit data - MsfBufferHeader * header = (MsfBufferHeader *) allocation; - header->next = NULL; - header->size = writeHead - writeBase; - uint8_t * moved = (uint8_t *) MSF_GIF_REALLOC(allocContext, allocation, maxBufSize, writeHead - allocation); - if (!moved) { MSF_GIF_FREE(allocContext, allocation, maxBufSize); return NULL; } - return moved; -} - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -/// Incremental API /// -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -int msf_gif_begin(MsfGifState * handle, int width, int height) { MsfTimeFunc - MsfCookedFrame empty = {0}; //god I hate MSVC... - handle->previousFrame = empty; - handle->width = width; - handle->height = height; - - //setup header buffer header (lol) - handle->listHead = (uint8_t *) MSF_GIF_MALLOC(handle->customAllocatorContext, sizeof(MsfBufferHeader) + 32); - if (!handle->listHead) { return 0; } - handle->listTail = handle->listHead; - MsfBufferHeader * header = (MsfBufferHeader *) handle->listHead; - header->next = NULL; - header->size = 32; - - //NOTE: because __attribute__((__packed__)) is annoyingly compiler-specific, we do this unreadable weirdness - char headerBytes[33] = "GIF89a\0\0\0\0\x10\0\0" "\x21\xFF\x0BNETSCAPE2.0\x03\x01\0\0\0"; - memcpy(&headerBytes[6], &width, 2); - memcpy(&headerBytes[8], &height, 2); - memcpy(handle->listHead + sizeof(MsfBufferHeader), headerBytes, 32); - return 1; -} - -int msf_gif_frame(MsfGifState * handle, uint8_t * pixelData, int centiSecondsPerFame, int maxBitDepth, int pitchInBytes) -{ MsfTimeFunc - if (!handle->listHead) { return 0; } - - maxBitDepth = msf_imax(1, msf_imin(16, maxBitDepth)); - if (pitchInBytes == 0) pitchInBytes = handle->width * 4; - if (pitchInBytes < 0) pixelData -= pitchInBytes * (handle->height - 1); - - uint8_t used[1 << 16]; //only 64k, so stack allocating is fine - MsfCookedFrame frame = - msf_cook_frame(handle->customAllocatorContext, pixelData, used, handle->width, handle->height, pitchInBytes, - msf_imin(maxBitDepth, handle->previousFrame.depth + 160 / msf_imax(1, handle->previousFrame.count))); - //TODO: de-duplicate cleanup code - if (!frame.pixels) { - MSF_GIF_FREE(handle->customAllocatorContext, - handle->previousFrame.pixels, handle->width * handle->height * sizeof(uint32_t)); - for (uint8_t * node = handle->listHead; node;) { - MsfBufferHeader * header = (MsfBufferHeader *) node; - node = header->next; - MSF_GIF_FREE(handle->customAllocatorContext, header, sizeof(MsfBufferHeader) + header->size); - } - handle->listHead = handle->listTail = NULL; - return 0; - } - - uint8_t * buffer = msf_compress_frame(handle->customAllocatorContext, - handle->width, handle->height, centiSecondsPerFame, frame, handle->previousFrame, used); - ((MsfBufferHeader *) handle->listTail)->next = buffer; - handle->listTail = buffer; - if (!buffer) { - MSF_GIF_FREE(handle->customAllocatorContext, frame.pixels, handle->width * handle->height * sizeof(uint32_t)); - MSF_GIF_FREE(handle->customAllocatorContext, - handle->previousFrame.pixels, handle->width * handle->height * sizeof(uint32_t)); - for (uint8_t * node = handle->listHead; node;) { - MsfBufferHeader * header = (MsfBufferHeader *) node; - node = header->next; - MSF_GIF_FREE(handle->customAllocatorContext, header, sizeof(MsfBufferHeader) + header->size); - } - handle->listHead = handle->listTail = NULL; - return 0; - } - - handle->previousFrame = frame; - return 1; -} - -MsfGifResult msf_gif_end(MsfGifState * handle) { MsfTimeFunc - if (!handle->listHead) { MsfGifResult empty = {0}; return empty; } - - MSF_GIF_FREE(handle->customAllocatorContext, - handle->previousFrame.pixels, handle->width * handle->height * sizeof(uint32_t)); - - //first pass: determine total size - size_t total = 1; //1 byte for trailing marker - for (uint8_t * node = handle->listHead; node;) { - MsfBufferHeader * header = (MsfBufferHeader *) node; - node = header->next; - total += header->size; - } - - //second pass: write data - uint8_t * buffer = (uint8_t *) MSF_GIF_MALLOC(handle->customAllocatorContext, total); - if (buffer) { - uint8_t * writeHead = buffer; - for (uint8_t * node = handle->listHead; node;) { - MsfBufferHeader * header = (MsfBufferHeader *) node; - memcpy(writeHead, node + sizeof(MsfBufferHeader), header->size); - writeHead += header->size; - node = header->next; - } - *writeHead++ = 0x3B; - } - - //third pass: free buffers - for (uint8_t * node = handle->listHead; node;) { - MsfBufferHeader * header = (MsfBufferHeader *) node; - node = header->next; - MSF_GIF_FREE(handle->customAllocatorContext, header, sizeof(MsfBufferHeader) + header->size); - } - - MsfGifResult ret = { buffer, total, total, handle->customAllocatorContext }; - return ret; -} - -void msf_gif_free(MsfGifResult result) { - if (result.data) { MSF_GIF_FREE(result.contextPointer, result.data, result.allocSize); } -} - -#endif //MSF_GIF_ALREADY_IMPLEMENTED_IN_THIS_TRANSLATION_UNIT -#endif //MSF_GIF_IMPL - -/* ------------------------------------------------------------------------------- -This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------- -ALTERNATIVE A - MIT License -Copyright (c) 2020 Miles Fogle -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. ------------------------------------------------------------------------------- -ALTERNATIVE B - Public Domain (www.unlicense.org) -This is free and unencumbered software released into the public domain. -Anyone is free to copy, modify, publish, use, compile, sell, or distribute this -software, either in source code form or as a compiled binary, for any purpose, -commercial or non-commercial, and by any means. -In jurisdictions that recognize copyright laws, the author or authors of this -software dedicate any and all copyright interest in the software to the public -domain. We make this dedication for the benefit of the public at large and to -the detriment of our heirs and successors. We intend this dedication to be an -overt act of relinquishment in perpetuity of all present and future rights to -this software under copyright law. -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 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. ------------------------------------------------------------------------------- -*/ diff --git a/components/darkforces/tfe/TFE_Asset/paletteAsset.h b/components/darkforces/tfe/TFE_Asset/paletteAsset.h deleted file mode 100644 index 1b4d2626..00000000 --- a/components/darkforces/tfe/TFE_Asset/paletteAsset.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Level/Map -// Handles the following: -// 1. Parsing the level data (.LEV) -// 2. Runtime storage and manipulation of level data -// (vertices, lines, sectors) -////////////////////////////////////////////////////////////////////// -#include - -struct Palette256 -{ - u32 colors[256]; -}; - -namespace TFE_Palette -{ - void createDefault256(); - Palette256* get256(const char* name); - Palette256* getPalFromPltt(const char* name, const char* archivePath); - Palette256* getDefault256(); - void freeAll(); -} diff --git a/components/darkforces/tfe/TFE_Asset/spriteAsset.h b/components/darkforces/tfe/TFE_Asset/spriteAsset.h deleted file mode 100644 index aadbfad8..00000000 --- a/components/darkforces/tfe/TFE_Asset/spriteAsset.h +++ /dev/null @@ -1,61 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Level/Map -// Handles the following: -// 1. Parsing the level data (.LEV) -// 2. Runtime storage and manipulation of level data -// (vertices, lines, sectors) -////////////////////////////////////////////////////////////////////// -#include - -struct SpriteAngle -{ - s16 frameCount; - s16 frameIndex[32]; -}; - -struct SpriteAnim -{ - s32 worldWidth; - s32 worldHeight; - s32 frameRate; - - s32 angleCount; - s16 rect[4]; - SpriteAngle angles[32]; -}; - -struct Frame -{ - s32 InsertX; // Insertion point, X coordinate - // Negative values shift the cell left; Positive values shift the cell right - s32 InsertY; // Insertion point, Y coordinate - // Negative values shift the cell up; Positive values shift the cell down - s32 Flip; // 0 = not flipped - // 1 = flipped horizontally - - s32 width; - s32 height; - s16 rect[4]; - u8* image; -}; - -struct Sprite -{ - s32 animationCount; - - // Structure. - SpriteAnim* anim; - Frame* frames; - u8* imageData; - s16 rect[4]; - - // Memory. - u8* memory; -}; -namespace TFE_Sprite -{ - Frame* getFrame(const char* name); - Sprite* getSprite(const char* name); - void freeAll(); -} diff --git a/components/darkforces/tfe/TFE_Asset/spriteAsset_Jedi.cpp b/components/darkforces/tfe/TFE_Asset/spriteAsset_Jedi.cpp deleted file mode 100644 index f5e72678..00000000 --- a/components/darkforces/tfe/TFE_Asset/spriteAsset_Jedi.cpp +++ /dev/null @@ -1,553 +0,0 @@ -#include - -#include "spriteAsset_Jedi.h" -#include -#include -#include -#include -#include -#include -#include -#include -// TODO: dependency on JediRenderer, this should be refactored... -#include -// -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_Sprite_Jedi -{ - typedef std::map FrameMap; - typedef std::map SpriteMap; - typedef std::vector FrameList; - typedef std::vector SpriteList; - typedef std::vector NameList; - - static FrameMap s_frames[POOL_COUNT]; - static SpriteMap s_sprites[POOL_COUNT]; - static FrameList s_frameList[POOL_COUNT]; - static SpriteList s_spriteList[POOL_COUNT]; - static NameList s_frameNames[POOL_COUNT]; - static NameList s_spriteNames[POOL_COUNT]; - static std::vector s_buffer; - - JediFrame* getFrame(const char* name, AssetPool pool) - { - FrameMap::iterator iFrame = s_frames[pool].find(name); - if (iFrame != s_frames[pool].end()) - { - return iFrame->second; - } - - // It doesn't exist yet, try to load the frame. - FilePath filePath; - if (!TFE_Paths::getFilePath(name, &filePath)) - { - return nullptr; - } - FileStream file; - if (!file.open(&filePath, Stream::MODE_READ)) - { - return nullptr; - } - size_t len = file.getSize(); - s_buffer.resize(len); - file.readBuffer(s_buffer.data(), u32(len)); - file.close(); - - const u8* data = s_buffer.data(); - - // Determine ahead of time how much we need to allocate. - WaxFrame* base_frame = (WaxFrame*)data; - base_frame->offsetX = TFE_Endian::le32_to_cpu(base_frame->offsetX); - base_frame->offsetY = TFE_Endian::le32_to_cpu(base_frame->offsetY); - base_frame->flip = TFE_Endian::le32_to_cpu(base_frame->flip); - base_frame->cellOffset = TFE_Endian::le32_to_cpu(base_frame->cellOffset); - base_frame->widthWS = TFE_Endian::le32_to_cpu(base_frame->widthWS); - base_frame->heightWS = TFE_Endian::le32_to_cpu(base_frame->heightWS); - - WaxCell* base_cell = WAX_CellPtr(data, base_frame); - base_cell->sizeX = TFE_Endian::le32_to_cpu(base_cell->sizeX); - base_cell->sizeY = TFE_Endian::le32_to_cpu(base_cell->sizeY); - base_cell->compressed = TFE_Endian::le32_to_cpu(base_cell->compressed); - base_cell->dataSize = TFE_Endian::le32_to_cpu(base_cell->dataSize); - base_cell->columnOffset = TFE_Endian::le32_to_cpu(base_cell->columnOffset); - const u32 columnSize = base_cell->sizeX * sizeof(u32); - - // This is a "load in place" format in the original code. - // We are going to allocate new memory and copy the data. - u8* assetPtr = (u8*)malloc(s_buffer.size() + columnSize); - JediFrame* asset = (JediFrame*)assetPtr; - - memcpy(asset, data, s_buffer.size()); - - WaxFrame* frame = asset; - WaxCell* cell = WAX_CellPtr(asset, frame); - - // After load, the frame data has to be fixed up before rendering. - // frame sizes remain in fixed point. - frame->widthWS = div16(intToFixed16(cell->sizeX), SPRITE_SCALE_FIXED); - frame->heightWS = div16(intToFixed16(cell->sizeY), SPRITE_SCALE_FIXED); - - const s32 offsetX = -intToFixed16(frame->offsetX); - const s32 offsetY = intToFixed16(cell->sizeY) + intToFixed16(frame->offsetY); - frame->offsetX = div16(offsetX, SPRITE_SCALE_FIXED); - frame->offsetY = div16(offsetY, SPRITE_SCALE_FIXED); - - if (cell->compressed == 1) - { - // Update the column offset, it starts right after the cell data. - cell->columnOffset = frame->cellOffset + sizeof(WaxCell); - u32* columns = (u32*)((u8*)asset + cell->columnOffset); - for (s32 c = 0; c < cell->sizeX; c++) - { - columns[c] = TFE_Endian::le32_to_cpu(columns[c]); - } - } - else - { - u32* columns = (u32*)((u8*)asset + s_buffer.size()); - // Local pointer. - cell->columnOffset = u32((u8*)columns - (u8*)asset); - // Calculate column offsets. - for (s32 c = 0; c < cell->sizeX; c++) - { - columns[c] = cell->sizeY * c; - } - } - - s_frames[pool][name] = asset; - s_frameList[pool].push_back(asset); - s_frameNames[pool].push_back(name); - return asset; - } - - static std::vector s_cellOffsets; - - bool isUniqueCell(u32 offset) - { - const size_t count = s_cellOffsets.size(); - const u32* offsetList = s_cellOffsets.data(); - for (u32 i = 0; i < count; i++) - { - if (offsetList[i] == offset) { return false; } - } - s_cellOffsets.push_back(offset); - - return true; - } - - void sprite_serializeSpritesAndFrames(Stream* stream) - { - const bool modeWrite = serialization_getMode() == SMODE_WRITE; - - if (!modeWrite) - { - freeLevelData(); - } - - s32 frameCount, spriteCount; - if (modeWrite) - { - frameCount = (s32)s_frameNames[POOL_LEVEL].size(); - spriteCount = (s32)s_spriteNames[POOL_LEVEL].size(); - } - SERIALIZE(SaveVersionInit, frameCount, 0); - SERIALIZE(SaveVersionInit, spriteCount, 0); - - std::string* frameNames = s_frameNames[POOL_LEVEL].data(); - std::string* spriteNames = s_spriteNames[POOL_LEVEL].data(); - std::string name; - for (s32 i = 0; i < frameCount; i++) - { - u8 size; - if (modeWrite) - { - size = (u8)frameNames[i].length(); - } - SERIALIZE(SaveVersionInit, size, 0); - - if (!modeWrite) - { - name.resize(size); - } - SERIALIZE_BUF(SaveVersionInit, modeWrite ? &frameNames[i][0] : &name[0], size); - - if (serialization_getMode() == SMODE_READ) - { - getFrame(name.c_str(), POOL_LEVEL); - } - } - for (s32 i = 0; i < spriteCount; i++) - { - u8 size; - if (modeWrite) - { - size = (u8)spriteNames[i].length(); - } - SERIALIZE(SaveVersionInit, size, 0); - if (!modeWrite) - { - name.resize(size); - } - SERIALIZE_BUF(SaveVersionInit, modeWrite ? &spriteNames[i][0] : &name[0], size); - - if (serialization_getMode() == SMODE_READ) - { - getWax(name.c_str(), POOL_LEVEL); - } - } - } - - JediWax* getWax(const char* name, AssetPool pool) - { - SpriteMap::iterator iSprite = s_sprites[pool].find(name); - if (iSprite != s_sprites[pool].end()) - { - return iSprite->second; - } - - // It doesn't exist yet, try to load the frame. - FilePath filePath; - if (!TFE_Paths::getFilePath(name, &filePath)) - { - return nullptr; - } - FileStream file; - if (!file.open(&filePath, Stream::MODE_READ)) - { - return nullptr; - } - size_t len = file.getSize(); - s_buffer.resize(len); - file.readBuffer(s_buffer.data(), u32(len)); - file.close(); - - const u8* data = s_buffer.data(); - Wax* srcWax = (Wax*)data; - srcWax->version = TFE_Endian::le32_to_cpu(srcWax->version); - srcWax->animCount = TFE_Endian::le32_to_cpu(srcWax->animCount); - srcWax->frameCount = TFE_Endian::le32_to_cpu(srcWax->frameCount); - srcWax->cellCount = TFE_Endian::le32_to_cpu(srcWax->cellCount); - srcWax->xScale = TFE_Endian::le32_to_cpu(srcWax->xScale); - srcWax->yScale = TFE_Endian::le32_to_cpu(srcWax->yScale); - srcWax->xtraLight = TFE_Endian::le32_to_cpu(srcWax->xtraLight); - for (s32 animIdx = 0; animIdx < WAX_MAX_ANIM; animIdx++) - { - srcWax->animOffsets[animIdx] = TFE_Endian::le32_to_cpu(srcWax->animOffsets[animIdx]); - } - - // every animation is filled out until the end, so no animations = no wax. - if (!srcWax->animOffsets[0]) - { - return nullptr; - } - s_cellOffsets.clear(); - - // First determine the size to allocate (note that this will overallocate a bit because cells are shared). - std::vector swappedAnims; - std::vector swappedViews; - std::vector swappedFrames; - std::vector swappedCells; - u32 sizeToAlloc = sizeof(JediWax) + (u32)s_buffer.size(); - const s32* animOffset = srcWax->animOffsets; - for (s32 animIdx = 0; animIdx < 32 && animOffset[animIdx]; animIdx++) - { - WaxAnim* anim = (WaxAnim*)(data + animOffset[animIdx]); - if (animOffset[animIdx] && std::find(swappedAnims.begin(), swappedAnims.end(), animOffset[animIdx]) == swappedAnims.end()) - { - swappedAnims.push_back(animOffset[animIdx]); - anim->worldWidth = TFE_Endian::le32_to_cpu(anim->worldWidth); - anim->worldHeight = TFE_Endian::le32_to_cpu(anim->worldHeight); - anim->frameRate = TFE_Endian::le32_to_cpu(anim->frameRate); - anim->frameCount = TFE_Endian::le32_to_cpu(anim->frameCount); - for (s32 v = 0; v < WAX_MAX_VIEWS; v++) - { - anim->viewOffsets[v] = TFE_Endian::le32_to_cpu(anim->viewOffsets[v]); - } - } - const s32* viewOffsets = anim->viewOffsets; - for (s32 v = 0; v < 32; v++) - { - WaxView* view = (WaxView*)(data + viewOffsets[v]); - if (viewOffsets[v] && std::find(swappedViews.begin(), swappedViews.end(), viewOffsets[v]) == swappedViews.end()) - { - swappedViews.push_back(viewOffsets[v]); - for (s32 f = 0; f < WAX_MAX_FRAMES; f++) - { - view->frameOffsets[f] = TFE_Endian::le32_to_cpu(view->frameOffsets[f]); - } - } - const s32* frameOffset = view->frameOffsets; - for (s32 f = 0; f < 32 && frameOffset[f]; f++) - { - WaxFrame* frame = (WaxFrame*)(data + frameOffset[f]); - if (frameOffset[f] && std::find(swappedFrames.begin(), swappedFrames.end(), frameOffset[f]) == swappedFrames.end()) - { - swappedFrames.push_back(frameOffset[f]); - frame->offsetX = TFE_Endian::le32_to_cpu(frame->offsetX); - frame->offsetY = TFE_Endian::le32_to_cpu(frame->offsetY); - frame->flip = TFE_Endian::le32_to_cpu(frame->flip); - frame->cellOffset = TFE_Endian::le32_to_cpu(frame->cellOffset); - frame->widthWS = TFE_Endian::le32_to_cpu(frame->widthWS); - frame->heightWS = TFE_Endian::le32_to_cpu(frame->heightWS); - } - WaxCell* cell = frame->cellOffset ? (WaxCell*)(data + frame->cellOffset) : nullptr; - if (frame->cellOffset && std::find(swappedCells.begin(), swappedCells.end(), frame->cellOffset) == swappedCells.end()) - { - swappedCells.push_back(frame->cellOffset); - cell->sizeX = TFE_Endian::le32_to_cpu(cell->sizeX); - cell->sizeY = TFE_Endian::le32_to_cpu(cell->sizeY); - cell->compressed = TFE_Endian::le32_to_cpu(cell->compressed); - cell->dataSize = TFE_Endian::le32_to_cpu(cell->dataSize); - cell->columnOffset = TFE_Endian::le32_to_cpu(cell->columnOffset); - if (cell->compressed == 1) - { - u32* columns = (u32*)(data + frame->cellOffset + sizeof(WaxCell)); - for (s32 c = 0; c < cell->sizeX; c++) - { - columns[c] = TFE_Endian::le32_to_cpu(columns[c]); - } - } - } - if (cell && cell->compressed == 0 && isUniqueCell(frame->cellOffset)) - { - sizeToAlloc += cell->sizeX * sizeof(u32); - } - } - } - } - - // Allocate and copy the data (this is a "copy in place" format... mostly. - JediWax* asset = (JediWax*)malloc(sizeToAlloc); - Wax* dstWax = asset; - memcpy(dstWax, srcWax, s_buffer.size()); - - // Loop through animation list until we reach 32 (maximum count) or a null animation. - // This means that animations are contiguous. - fixed16_16 scaledWidth, scaledHeight; - - u32 cellOffsetPtr = 0; - fixed16_16 worldWidth, worldHeight; - - s32 animIdx = 0; - for (; animIdx < 32 && animOffset[animIdx]; animIdx++) - { - WaxAnim* dstAnim = (WaxAnim*)((u8*)asset + animOffset[animIdx]); - - if (animIdx == 0) - { - scaledWidth = div16(SPRITE_SCALE_FIXED, dstAnim->worldWidth); - scaledHeight = div16(SPRITE_SCALE_FIXED, dstAnim->worldHeight); - - worldWidth = dstAnim->worldWidth; - worldHeight = dstAnim->worldHeight; - - dstWax->xScale = dstAnim->worldWidth; - dstWax->yScale = dstAnim->worldHeight; - } - else - { - dstAnim->worldWidth = worldWidth; - dstAnim->worldHeight = worldHeight; - } - - const s32* viewOffsets = dstAnim->viewOffsets; - for (s32 v = 0; v < 32; v++) - { - const WaxView* dstView = (WaxView*)((u8*)asset + viewOffsets[v]); - const s32* frameOffset = dstView->frameOffsets; - s32 frameCount = 0; - for (s32 f = 0; f < 32 && frameOffset[f]; f++, frameCount++) - { - const WaxFrame* srcFrame = (WaxFrame*)(data + frameOffset[f]); - WaxFrame* dstFrame = (WaxFrame*)((u8*)asset + frameOffset[f]); - - // Some frames are shared between animations, so we need to read from the source, unmodified data. - dstFrame->offsetX = round16(mul16(dstAnim->worldWidth, intToFixed16(srcFrame->offsetX))); - dstFrame->offsetY = round16(mul16(dstAnim->worldHeight, intToFixed16(srcFrame->offsetY))); - - WaxCell* dstCell = dstFrame->cellOffset ? (WaxCell*)((u8*)asset + dstFrame->cellOffset) : nullptr; - if (dstCell) - { - dstFrame->widthWS = div16(intToFixed16(dstCell->sizeX), scaledWidth); - dstFrame->heightWS = div16(intToFixed16(dstCell->sizeY), scaledHeight); - assert(dstFrame->widthWS != 0 && dstFrame->heightWS != 0); - - if (dstCell->columnOffset == 0) - { - if (dstCell->compressed == 1) - { - // Update the column offset, it starts right after the cell data. - dstCell->columnOffset = dstFrame->cellOffset + sizeof(WaxCell); - } - else - { - u32* columns = (u32*)((u8*)asset + s_buffer.size() + cellOffsetPtr); - cellOffsetPtr += dstCell->sizeX * sizeof(u32); - - // Local pointer. - dstCell->columnOffset = u32((u8*)columns - (u8*)asset); - // Calculate column offsets. - for (s32 c = 0; c < dstCell->sizeX; c++) - { - columns[c] = dstCell->sizeY * c; - } - } - } - - dstFrame->offsetX = div16(-intToFixed16(dstFrame->offsetX), SPRITE_SCALE_FIXED); - const s32 adjOffsetY = mul16(intToFixed16(dstCell->sizeY), dstAnim->worldHeight) + intToFixed16(dstFrame->offsetY); - dstFrame->offsetY = div16(adjOffsetY, SPRITE_SCALE_FIXED); - } - } - if (v == 0) - { - dstAnim->frameCount = frameCount; - assert(frameCount); - } - else - { - assert(frameCount == dstAnim->frameCount); - } - } - } - asset->animCount = animIdx; - - s_sprites[pool][name] = asset; - s_spriteList[pool].push_back(asset); - s_spriteNames[pool].push_back(name); - return asset; - } - - const std::vector& getWaxList(AssetPool pool) - { - return s_spriteList[pool]; - } - - const std::vector& getFrameList(AssetPool pool) - { - return s_frameList[pool]; - } - - void freePool(AssetPool pool) - { - const size_t frameCount = s_frameList[pool].size(); - JediFrame** frameList = s_frameList[pool].data(); - for (size_t i = 0; i < frameCount; i++) - { - free(frameList[i]); - } - s_frames[pool].clear(); - s_frameList[pool].clear(); - s_frameNames[pool].clear(); - - const size_t waxCount = s_spriteList[pool].size(); - JediWax** waxList = s_spriteList[pool].data(); - for (size_t i = 0; i < waxCount; i++) - { - free(waxList[i]); - } - s_sprites[pool].clear(); - s_spriteList[pool].clear(); - s_spriteNames[pool].clear(); - } - - void freeAll() - { - for (s32 p = 0; p < POOL_COUNT; p++) - { - freePool(AssetPool(p)); - } - } - - void freeLevelData() - { - freePool(POOL_LEVEL); - } - - bool getWaxIndex(JediWax* wax, s32* index, AssetPool* pool) - { - for (s32 p = 0; p < POOL_COUNT; p++) - { - const size_t waxCount = s_spriteList[p].size(); - JediWax** waxList = s_spriteList[p].data(); - for (size_t i = 0; i < waxCount; i++) - { - if (waxList[i] == wax) - { - *index = s32(i); - *pool = AssetPool(p); - return true; - } - } - } - return false; - } - - JediWax* getWaxByIndex(s32 index, AssetPool pool) - { - if (pool >= POOL_COUNT || index >= (s32)s_spriteList[pool].size()) - { - return nullptr; - } - return s_spriteList[pool][index]; - } - - bool getFrameIndex(JediFrame* frame, s32* index, AssetPool* pool) - { - for (s32 p = 0; p < POOL_COUNT; p++) - { - const size_t frameCount = s_frameList[p].size(); - JediFrame** frameList = s_frameList[p].data(); - for (size_t i = 0; i < frameCount; i++) - { - if (frameList[i] == frame) - { - *index = s32(i); - *pool = AssetPool(p); - return true; - } - } - } - return false; - } - - JediFrame* getFrameByIndex(s32 index, AssetPool pool) - { - if (pool >= POOL_COUNT || index >= (s32)s_frameList[pool].size()) - { - return nullptr; - } - return s_frameList[pool][index]; - } -} - -#ifdef TFE_ESPBOX -// The file read scratch buffer keeps the capacity of the largest file loaded; -// release it when the game is shut down (called from the platform glue). -void espbox_free_sprite_scratch() -{ - std::vector().swap(TFE_Sprite_Jedi::s_buffer); -} -#endif - -#ifdef TFE_ESPBOX -// Shutdown only: release this file's cached container storage so nothing is -// left in the 4MB ROM block when the session ends (see esp_alloc.cpp). -void espbox_release_sprite_caches() -{ - std::vector().swap(TFE_Sprite_Jedi::s_cellOffsets); - for (auto& names : TFE_Sprite_Jedi::s_frameNames) { TFE_Sprite_Jedi::NameList().swap(names); } - for (auto& names : TFE_Sprite_Jedi::s_spriteNames) { TFE_Sprite_Jedi::NameList().swap(names); } - for (auto& map : TFE_Sprite_Jedi::s_frames) { TFE_Sprite_Jedi::FrameMap().swap(map); } - for (auto& map : TFE_Sprite_Jedi::s_sprites) { TFE_Sprite_Jedi::SpriteMap().swap(map); } - for (auto& list : TFE_Sprite_Jedi::s_frameList) { TFE_Sprite_Jedi::FrameList().swap(list); } - for (auto& list : TFE_Sprite_Jedi::s_spriteList) { TFE_Sprite_Jedi::SpriteList().swap(list); } -} -#endif diff --git a/components/darkforces/tfe/TFE_Asset/spriteAsset_Jedi.h b/components/darkforces/tfe/TFE_Asset/spriteAsset_Jedi.h deleted file mode 100644 index e17634b4..00000000 --- a/components/darkforces/tfe/TFE_Asset/spriteAsset_Jedi.h +++ /dev/null @@ -1,108 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Update sprite asset based on reverse engineering. -// Switch to this once the Jedi Renderer completely replaces the -// existing renderer. -////////////////////////////////////////////////////////////////////// -#include -#include -#include - -// The original DOS code relied on 32-bit pointers and just swapped offsets for pointers at load time. -// In order to keep the original data intact, the original 32-bit offsets are kept but pointer -// translation is done at runtime. -// -// Note that this will cause extra overhead and should be refactored in the future. - -#define WAX_MAX_ANIM 32 -#define WAX_MAX_VIEWS 32 -#define WAX_MAX_FRAMES 32 -#define WAX_DECOMPRESS_SIZE 1024 - -#pragma pack(push) -#pragma pack(1) -struct WaxCell -{ - s32 sizeX; - s32 sizeY; - s32 compressed; - s32 dataSize; - u32 columnOffset; - s32 textureId; // TFE: Replace padding with textureID for the GPU renderer. -}; - -struct WaxFrame -{ - s32 offsetX; - s32 offsetY; - s32 flip; - s32 cellOffset; - s32 widthWS; - s32 heightWS; - s32 pad1; - s32 pad2; -}; - -struct WaxView -{ - s32 pad1; - s32 pad2; - s32 pad3; - s32 pad4; - - s32 frameOffsets[WAX_MAX_FRAMES]; -}; - -struct WaxAnim -{ - s32 worldWidth; - s32 worldHeight; - s32 frameRate; - s32 frameCount; - s32 pad2; - s32 pad3; - s32 pad4; - - s32 viewOffsets[WAX_MAX_VIEWS]; -}; - -struct Wax -{ - s32 version; // constant = 0x00100100 - s32 animCount; - s32 frameCount; - s32 cellCount; - s32 xScale; - s32 yScale; - s32 xtraLight; - s32 pad4; - s32 animOffsets[WAX_MAX_ANIM]; -}; -#pragma pack(pop) - -#define WAX_AnimPtr(waxPtr, animId) ((waxPtr)->animOffsets[(animId)] ? (WaxAnim*)((u8*)(waxPtr) + (waxPtr)->animOffsets[(animId)]) : nullptr) -#define WAX_ViewPtr(waxPtr, jAnim, viewId) ((jAnim)->viewOffsets[(viewId)] ? (WaxView*)((u8*)(waxPtr) + (jAnim)->viewOffsets[(viewId)]) : nullptr) -#define WAX_FramePtr(waxPtr, jView, frameId) ((jView)->frameOffsets[(frameId)] ? (WaxFrame*)((u8*)(waxPtr) + (jView)->frameOffsets[(frameId)]) : nullptr) -#define WAX_CellPtr(waxPtr, jFrame) ((jFrame)->cellOffset ? (WaxCell*)((u8*)(waxPtr) + (jFrame)->cellOffset) : nullptr) - -typedef Wax JediWax; -typedef WaxFrame JediFrame; - -namespace TFE_Sprite_Jedi -{ - JediFrame* getFrame(const char* name, AssetPool pool = POOL_LEVEL); - JediWax* getWax(const char* name, AssetPool pool = POOL_LEVEL); - void freeAll(); - void freeLevelData(); - - const std::vector& getWaxList(AssetPool pool = POOL_LEVEL); - const std::vector& getFrameList(AssetPool pool = POOL_LEVEL); - - bool getWaxIndex(JediWax* wax, s32* index, AssetPool* pool); - JediWax* getWaxByIndex(s32 index, AssetPool pool); - - bool getFrameIndex(JediFrame* frame, s32* index, AssetPool* pool); - JediFrame* getFrameByIndex(s32 index, AssetPool pool); - - void sprite_serializeSpritesAndFrames(Stream* stream); -} diff --git a/components/darkforces/tfe/TFE_Asset/textureAsset.h b/components/darkforces/tfe/TFE_Asset/textureAsset.h deleted file mode 100644 index 00147c88..00000000 --- a/components/darkforces/tfe/TFE_Asset/textureAsset.h +++ /dev/null @@ -1,70 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Level/Map -// Handles the following: -// 1. Parsing the level data (.LEV) -// 2. Runtime storage and manipulation of level data -// (vertices, lines, sectors) -////////////////////////////////////////////////////////////////////// -#include -#include "paletteAsset.h" - -enum TextureOpacity -{ - TEX_OPACITY_NORMAL = 0, - TEX_OPACITY_TRANS, - TEX_OPACITY_WEAPON, - TEX_OPACITY_COUNT -}; - -enum TextureLayout -{ - TEX_LAYOUT_VERT = 0, // default for most textures - TEX_LAYOUT_HORZ, // "normal" horizontal layout (used for menus, cutscenes, etc.). -}; - -struct TextureFrame -{ - s16 width; - s16 height; - - s16 uvWidth; // width and height to use when computing uvs. - s16 uvHeight; - - s16 offsetX; - s16 offsetY; - - u8 logSizeY; - u8 pad[3]; - - TextureOpacity opacity; - u8* image; -}; - -struct Texture -{ - char name[32]; - - u16 frameCount; // 1 for regular textures. - u16 frameRate; - - u8* memory; - TextureFrame* frames; - - TextureLayout layout; -}; - -struct Image; - -namespace TFE_Texture -{ - Texture* get(const char* name); - Texture* getFromDelt(const char* name, const char* archivePath); - Texture* getFromAnim(const char* name, const char* archivePath); - Texture* getFromPCX(const char* name, const char* archivePath); - Palette256* getPreviousPalette(); - void free(Texture* texture); - void freeAll(); - - Texture* convertImageToTexture_8bit(const char* name, const Image* image, const char* paletteName); -} diff --git a/components/darkforces/tfe/TFE_Asset/vocAsset.h b/components/darkforces/tfe/TFE_Asset/vocAsset.h deleted file mode 100644 index 27b81611..00000000 --- a/components/darkforces/tfe/TFE_Asset/vocAsset.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Level/Map -// Handles the following: -// 1. Parsing the level data (.LEV) -// 2. Runtime storage and manipulation of level data -// (vertices, lines, sectors) -////////////////////////////////////////////////////////////////////// -#include - -struct SoundBuffer; - -namespace TFE_VocAsset -{ - SoundBuffer* get(const char* name); - void freeAll(); - - s32 getIndex(const char* name); - SoundBuffer* getFromIndex(s32 index); - - bool parseVoc(SoundBuffer* voc, u8* buffer); -}; diff --git a/components/darkforces/tfe/TFE_Asset/vueAsset.cpp b/components/darkforces/tfe/TFE_Asset/vueAsset.cpp deleted file mode 100644 index ca102464..00000000 --- a/components/darkforces/tfe/TFE_Asset/vueAsset.cpp +++ /dev/null @@ -1,215 +0,0 @@ -#include - -#include "vueAsset.h" -#include -#include -#include -#include -#include -#include -#include - -namespace TFE_VueAsset -{ - typedef std::map VueMap; - static VueMap s_vueAssets; - static std::vector s_buffer; - static const char* c_defaultGob = "DARK.GOB"; - - bool parseVue(VueAsset* vue); - - VueAsset* get(const char* name) - { - VueMap::iterator iVue = s_vueAssets.find(name); - if (iVue != s_vueAssets.end()) - { - return iVue->second; - } - - // It doesn't exist yet, try to load the font. - if (!TFE_AssetSystem::readAssetFromArchive(c_defaultGob, ARCHIVE_GOB, name, s_buffer)) - { - return nullptr; - } - - VueAsset* vue = new VueAsset; - if (!parseVue(vue)) - { - delete vue; - return nullptr; - } - - s_vueAssets[name] = vue; - strcpy(vue->name, name); - return vue; - } - - void freeAll() - { - VueMap::iterator iVue = s_vueAssets.begin(); - for (; iVue != s_vueAssets.end(); ++iVue) - { - VueAsset* vue = iVue->second; - for (u32 i = 0; i < vue->transformCount; i++) - { - delete[] vue->transformNames[i]; - } - delete[] vue->transformNames; - delete[] vue->transforms; - delete vue; - } - s_vueAssets.clear(); - } - - s32 getTransformIndex(const VueAsset* vue, const char* name) - { - if (!name || !vue) { return -1; } - - for (u32 i = 0; i < vue->transformCount; i++) - { - if (strcasecmp(name, vue->transformNames[i]) == 0) - { - return s32(i); - } - } - return -1; - } - - const VueTransform* getTransform(const VueAsset* vue, s32 transformIndex, s32 frameIndex) - { - if (!vue) { return nullptr; } - return &vue->transforms[frameIndex * vue->transformCount + transformIndex]; - } - - const char* getTransformName(const VueAsset* vue, s32 transformIndex) - { - if (!vue) { return nullptr; } - return vue->transformNames[transformIndex]; - } - - //////////////////////////////////////// - //////////// Internal ////////////////// - //////////////////////////////////////// - bool parseVue(VueAsset* vue) - { - if (s_buffer.empty()) { return false; } - - const size_t len = s_buffer.size(); - - TFE_Parser parser; - size_t bufferPos = 0; - parser.init(s_buffer.data(), len); - parser.addCommentString("//"); - parser.addCommentString("#"); - parser.enableBlockComments(); - - std::vector transformNames; - std::vector transforms; - - s32 frameIndex = -1; - u32 frameCount = 0; - u32 transformIndex = 0; - - while (bufferPos < len) - { - const char* line = parser.readLine(bufferPos); - if (!line) { break; } - - TokenList tokens; - parser.tokenizeLine(line, tokens); - if (tokens.size() < 1) { continue; } - - char* endPtr = nullptr; - if (strcasecmp("frame", tokens[0].c_str()) == 0) - { - frameIndex++; - s32 frameId = frameIndex; - if (tokens.size() > 1u) - { - frameId = strtol(tokens[1].c_str(), &endPtr, 10); - } - // Are we allowed to skip frames? - assert(frameId == frameIndex); - transformIndex = 0; - frameCount++; - } - else if (strcasecmp("transform", tokens[0].c_str()) == 0) - { - // if no frame is specified, then assume that this is a frame. - if (frameIndex < 0) - { - frameIndex++; - frameCount++; - } - assert(tokens.size() == 14u); - const char* transformName = tokens.size() > 1 ? tokens[1].c_str() : ""; - Mat3 rotScale = { 1, 0, 0, 0, 1, 0, 0, 0, 1 }; - if (tokens.size() > 10) - { - for (u32 i = 0; i < 9; i++) - { - Vec3f& row = rotScale.m[i / 3]; - row.m[i % 3] = (f32)strtod(tokens[2 + i].c_str(), &endPtr); - } - } - Vec3f translation = { 0 }; - if (tokens.size() > 13) - { - for (u32 i = 0; i < 3; i++) - { - translation.m[i] = (f32)strtod(tokens[11 + i].c_str(), &endPtr); - } - translation.y = -translation.y; - } - - if (frameIndex == 0) - { - transformNames.push_back(transformName); - } - else - { - assert(strcasecmp(transformNames[transformIndex].c_str(), transformName) == 0); - } - transforms.push_back({ rotScale, translation }); - transformIndex++; - } - } - - // Allocate and fill in the data. - vue->frameCount = frameCount; - vue->transformCount = (u32)transformNames.size(); - vue->transformNames = new char*[vue->transformCount]; - vue->transforms = new VueTransform[vue->transformCount * vue->frameCount]; - assert(vue->transformCount * vue->frameCount == transforms.size()); - - for (u32 i = 0; i < vue->transformCount; i++) - { - vue->transformNames[i] = new char[transformNames[i].size()]; - strcpy(vue->transformNames[i], transformNames[i].c_str()); - } - memcpy(vue->transforms, transforms.data(), sizeof(VueTransform)*transforms.size()); - // Fixup transforms - Vues were authored in 3Ds MAX with a different coordinate system than Dark Forces uses - // (Z up for example). By fixing the transforms up during load the rest of the code doesn't need to be aware of these differences. - const u32 count = vue->transformCount * vue->frameCount; - for (u32 i = 0; i < count; i++) - { - vue->transforms[i].translation = { vue->transforms[i].translation.x, -vue->transforms[i].translation.z, -vue->transforms[i].translation.y }; - - const Mat3 matVue = vue->transforms[i].rotScale; - vue->transforms[i].rotScale.m0 = { matVue.m0.x, matVue.m2.x, matVue.m1.x }; - vue->transforms[i].rotScale.m1 = {-matVue.m0.z,-matVue.m2.z,-matVue.m1.z }; - vue->transforms[i].rotScale.m2 = { matVue.m0.y, matVue.m2.y, matVue.m1.y }; - } - - return true; - } -} - -#ifdef TFE_ESPBOX -// The file read scratch buffer keeps the capacity of the largest file loaded; -// release it when the game is shut down (called from the platform glue). -void espbox_free_vue_scratch() -{ - std::vector().swap(TFE_VueAsset::s_buffer); -} -#endif diff --git a/components/darkforces/tfe/TFE_Asset/vueAsset.h b/components/darkforces/tfe/TFE_Asset/vueAsset.h deleted file mode 100644 index 33cb4d9a..00000000 --- a/components/darkforces/tfe/TFE_Asset/vueAsset.h +++ /dev/null @@ -1,36 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Level/Map -// Handles the following: -// 1. Parsing the level data (.LEV) -// 2. Runtime storage and manipulation of level data -// (vertices, lines, sectors) -////////////////////////////////////////////////////////////////////// -#include -#include -#include - -struct VueTransform -{ - Mat3 rotScale; - Vec3f translation; -}; - -struct VueAsset -{ - char name[64]; - u32 frameCount; - u32 transformCount; - char** transformNames; - VueTransform* transforms; // [frameCount * transformCount] -}; - -namespace TFE_VueAsset -{ - VueAsset* get(const char* name); - void freeAll(); - - s32 getTransformIndex(const VueAsset* vue, const char* name); - const VueTransform* getTransform(const VueAsset* vue, s32 transformIndex, s32 frameIndex); - const char* getTransformName(const VueAsset* vue, s32 transformIndex); -}; diff --git a/components/darkforces/tfe/TFE_Audio/MidiSynth/fm4Opl3Device.cpp b/components/darkforces/tfe/TFE_Audio/MidiSynth/fm4Opl3Device.cpp deleted file mode 100644 index 272b016e..00000000 --- a/components/darkforces/tfe/TFE_Audio/MidiSynth/fm4Opl3Device.cpp +++ /dev/null @@ -1,615 +0,0 @@ -/////////////////////////////////////////////////////////////// -// The low-level driver code that interfaces with the OPL3 -// device (virtual device in this case) was reverse-engineered -// from the iMuse driver interface code. -// -// I moved the driver level code into the OPL3 device instead -// of as part of iMuse for several reasons: -// * The OPL3 device can be handled using the same abstraction -// as the SF2 and System midi devices. -// * It avoids the need to add addition complexity to the iMuse -// library in TFE, which is already quite large. -/////////////////////////////////////////////////////////////// -#include "fm4Opl3Device.h" -#include "fm4Tables.h" -#include "opl3.h" -#include -#include -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_Audio -{ - // Registers and Values used by the OPL3 driver. Note that this doesn't include everything possible. - enum Opl3Reg - { - REG_MODE_REGISTER = 0x05, - REG_KBD_SPLIT_REGISTER = 0x08, - REG_ENABLE_WAVE_SELECT = 0x20, - REG_KSL_LEVEL = 0x40, - REG_ATTACK_DECAY = 0x60, - REG_SUSTAIN_RELEASE = 0x80, - REG_FNUM_LOW = 0xa0, - REG_KEYON_BLOCK = 0xb0, - REG_PERCUSSION_REGISTER = 0xbd, - REG_FEEDBACK_CONNECTION = 0xc0, - REG_WAVE_SELECT = 0xe0, - }; - enum Opl3Value - { - VALUE_ENABLE = 0x01, - VALUE_KEYON_BIT = 0x20, - VALUE_LEVEL_MASK = 0x3f, - VALUE_KEYBOARD_SPLIT = 0x40, - - VALUE_VOICE_LEFT = 0x10, - VALUE_VOICE_RIGHT = 0x20, - }; - - enum InternalConstants - { - FM4_Port = 0x388, - FM4_MaxVolume = 127, - FM4_OutputCount = 1, - FM4_SampleRate = 44100, - FM4_DrumChannel = 9, - FM4_PitchCenter = 0x2000, - FM4_MaxAtten = 0x3f, - FM4_TimbreCount = 167, - FM4_BankRemapMax = 27, - FM4_BankCenter = 68, - }; - const f32 c_outputScale = 1.5f / 32768.0f; // slight volume boost to compete with other midi outputs. - - static const char* c_Opl3_Name = "OPL3"; - static const char* c_Output_Name = "FM4 Driver"; - - // This is stored internally, there will only be one FM chip (for now). -#ifdef TFE_ESPBOX - static opl3_chip* s_fmChip = nullptr; // shared memory - #define FM_CHIP s_fmChip - #define FM_CHIP_CLEAR() do { if (s_fmChip) { memset(s_fmChip, 0, sizeof(*s_fmChip)); } } while (0) -#else - static opl3_chip s_fmChip = { 0 }; - #define FM_CHIP (&s_fmChip) - #define FM_CHIP_CLEAR() (s_fmChip = { 0 }) -#endif - - Fm4Opl3Device::~Fm4Opl3Device() - { - exit(); - } - - u32 Fm4Opl3Device::getOutputCount() - { - return FM4_OutputCount; - } - - void Fm4Opl3Device::getOutputName(s32 index, char* buffer, u32 maxLength) - { - // Only output 0 exists. - strncpy(buffer, c_Output_Name, maxLength); - buffer[strlen(c_Output_Name)] = 0; - } - - bool Fm4Opl3Device::selectOutput(s32 index) - { - if (!m_streamActive) - { - beginStream(FM4_SampleRate); - } - return m_streamActive; - } - - s32 Fm4Opl3Device::getActiveOutput(void) - { - // Only output 0 exists. - return 0; - } - - void Fm4Opl3Device::fm4_reset() - { - // Reset all of the registers. - for (s32 i = 0; i < FM4_RegisterCount; i++) - { - fm4_sendOutput(FM4_OutLeft, i, 0); - fm4_sendOutput(FM4_OutRight, i, 0); - } - // Initialize and enable. - fm4_sendOutput(FM4_OutRight, REG_KBD_SPLIT_REGISTER, VALUE_KEYBOARD_SPLIT); - fm4_sendOutput(FM4_OutRight, REG_PERCUSSION_REGISTER, 0x00); - fm4_sendOutput(FM4_OutLeft, REG_MODE_REGISTER, VALUE_ENABLE); - } - - void Fm4Opl3Device::beginStream(s32 sampleRate) - { - assert(!m_streamActive); - FM_CHIP_CLEAR(); - memset(m_registers, 0, FM4_RegisterCount * FM4_OutCount); - - OPL3_Reset(FM_CHIP, sampleRate); - fm4_reset(); - - // Initialize channels - for (s32 i = 0; i < MIDI_CHANNEL_COUNT; i++) - { - m_channels[i].priority = 0; - m_channels[i].noteReq = 1; - m_channels[i].refCount = 0; - m_channels[i].port = 0; - m_channels[i].timbre = 0; - m_channels[i].volume = 0x7f; - m_channels[i].pan = 64; - m_channels[i].pitch = FM4_PitchCenter; - } - m_fmVoicePitchRight = &m_registers[REG_KEYON_BLOCK]; - m_fmVoicePitchLeft = &m_registers[REG_KEYON_BLOCK + FM4_RegisterCount]; - m_fmVoiceLevel = &m_registers[REG_KSL_LEVEL]; - - // Initialize the voice list. - m_voiceList.active = nullptr; - m_voiceList.free = nullptr; - memset(m_voices, 0, sizeof(Fm4Voice) * FM4_VoiceCount); - for (s32 i = 0; i < FM4_VoiceCount; i++) - { - m_voices[i].id = i; - IM_LIST_ADD(m_voiceList.free, &m_voices[i]); - } - - m_volumeScaled = m_volume * c_outputScale; - m_streamActive = true; - } - - void Fm4Opl3Device::exit() - { - FM_CHIP_CLEAR(); - m_streamActive = false; - } - - const char* Fm4Opl3Device::getName() - { - return c_Opl3_Name; - } - - bool Fm4Opl3Device::render(MidiSample* buffer, u32 sampleCount) - { - if (!m_streamActive) { return false; } - -#ifdef TFE_ESPBOX - // Integer output: volume is applied as a 8.8 fixed point scale. - const s32 volScale = s32(m_volume * 256.0f); - for (u32 i = 0; i < sampleCount; i++) - { - s16 buf[2]; - OPL3_GenerateResampled(FM_CHIP, buf); - *buffer++ = s16(clamp((s32(buf[0]) * volScale) >> 8, INT16_MIN, INT16_MAX)); - *buffer++ = s16(clamp((s32(buf[1]) * volScale) >> 8, INT16_MIN, INT16_MAX)); - } -#else - for (u32 i = 0; i < sampleCount; i++) - { - s16 buf[2]; - OPL3_GenerateResampled(FM_CHIP, buf); - - s16 left = clamp(s32(buf[0]), INT16_MIN, INT16_MAX); - s16 right = clamp(s32(buf[1]), INT16_MIN, INT16_MAX); - *buffer++ = f32(left) * m_volumeScaled; - *buffer++ = f32(right) * m_volumeScaled; - } -#endif - return true; - } - - bool Fm4Opl3Device::canRender() - { - return m_streamActive; - } - - void Fm4Opl3Device::setVolume(f32 volume) - { - m_volume = volume; - m_volumeScaled = m_volume * c_outputScale; - } - - // Raw midi commands. - void Fm4Opl3Device::message(u8 type, u8 arg1, u8 arg2) - { - if (!m_streamActive) { return; } - const u8 msgType = type & 0xf0; - const u8 channel = type & 0x0f; - - switch (msgType) - { - case MID_NOTE_OFF: - fm4_noteOff(channel, arg1); - break; - case MID_NOTE_ON: - fm4_noteOn(channel, arg1, arg2); - break; - case MID_CONTROL_CHANGE: - fm4_controlChange(channel, arg1, arg2); - break; - case MID_PROGRAM_CHANGE: - fm4_programChange(channel, arg1); - break; - case MID_PITCH_BEND: - // No-op - break; - } - } - - void Fm4Opl3Device::message(const u8* msg, u32 len) - { - message(msg[0], msg[1], len >= 2 ? msg[2] : 0); - } - - void Fm4Opl3Device::noteAllOff() - { - if (!m_streamActive) { return; } - - Fm4Voice* voice = m_voiceList.active; - while (voice) - { - Fm4Voice* next = voice->next; - - fm4_voiceOff(voice->id); - IM_LIST_REM(m_voiceList.active, voice); - IM_LIST_ADD(m_voiceList.free, voice); - - voice = next; - } - - for (s32 i = 0; i < MIDI_CHANNEL_COUNT; i++) - { - m_channels[i].refCount = 0; - m_channels[i].noteReq = 1; - } - } - - ///////////////////////////////////////////// - // Low-level driver implementation. - ///////////////////////////////////////////// - s32 Fm4Opl3Device::fm4_getVelocityToVolumeMapping(s32 velocity) - { - assert(velocity >= 0 && velocity < 64); - return s_fmVelocityToVolumeMapping[velocity]; - } - - void Fm4Opl3Device::fm4_setVoiceVolumeSide(FmOutputChannel outChannel, s32 voice, s32 offset, s32 volume) - { - const s32 outIndex = outChannel + NoteLevelRight; - const s32 regOffset = outChannel * FM4_RegisterCount; - const s32 level = m_noteOutput[voice*NoteOut_Count + outIndex]; - const s32 fullVolume = fm4_getVelocityToVolumeMapping(((level + 1) * volume) >> 7); - - // The new level factors in the previous level. - const s32 prevLevel = m_fmVoiceLevel[offset + regOffset]; - const s32 newLevel = (prevLevel | FM4_MaxAtten) - fullVolume; - // This will update m_fmVoiceLevel[offset] to the new level since m_fmVoiceLevel is a pointer into the register array. - fm4_sendOutput(outChannel, offset + REG_KSL_LEVEL, newLevel); - } - - void Fm4Opl3Device::fm4_setVoiceVolume(s32 voice, s32 volume) - { - const s32 offset = s_fmVoiceOperators[1][voice]; - fm4_setVoiceVolumeSide(FM4_OutRight, voice, offset, volume); - fm4_setVoiceVolumeSide(FM4_OutLeft, voice, offset, volume); - - s32* output = &m_noteOutput[voice*NoteOut_Count]; - /* - if (output[NoteTimbre0_Right] == 1) - { - assert(0); - } - if (output[NoteTimbre0_Left] == 1) - { - assert(0); - } - */ - } - - void Fm4Opl3Device::fm4_controlChange(s32 channelId, s32 arg1, s32 arg2) - { - Fm4Channel* channel = &m_channels[channelId]; - Fm4Voice* voice = m_voiceList.active; - switch (arg1) - { - case MID_VOLUME_MSB: - { - channel->volume = arg2; - while (voice) - { - if (voice->channelId == channelId) - { - fm4_setVoiceVolume(voice->id, arg2); - } - voice = voice->next; - } - } break; - case MID_PAN_MSB: - { - channel->pan = arg2; - } break; - case MID_GPC2_MSB: - { - channel->noteReq = arg2; - } break; - case MID_GPC3_MSB: - { - channel->priority = arg2; - } break; - } - } - - void Fm4Opl3Device::fm4_programChange(s32 channelId, s32 timbre) - { - m_channels[channelId].timbre = timbre; - } - - void Fm4Opl3Device::fm4_noteOn(s32 channelId, s32 key, s32 velocity) - { - Fm4Channel* channel = &m_channels[channelId]; - - if (channelId == FM4_DrumChannel) - { - channel->timbre = fm4_keyToDrumTimbre(key); - if (channel->timbre >= 128) - { - channel->pitch = FM4_PitchCenter; - } - } - - Fm4Voice* voice = fm4_allocVoice(channel); - if (!voice) { return; } - voice->channel = channel; - voice->channelId = channelId; - voice->key = key; - - channel->refCount++; - channel->port = channel->refCount > channel->noteReq ? 1 : 0; - fm4_voiceOn(voice->id, channelId, key, velocity, channel->timbre, channel->volume, channel->pan, channel->pitch); - } - - void Fm4Opl3Device::fm4_noteOff(s32 channelId, s32 key) - { - Fm4Voice* voice = m_voiceList.active; - while (voice) - { - Fm4Voice* next = voice->next; - if (channelId == voice->channelId && voice->key == key) - { - fm4_voiceOff(voice->id); - m_channels[channelId].refCount--; - m_channels[channelId].port = m_channels[channelId].refCount > m_channels[channelId].noteReq ? 1 : 0; - - IM_LIST_REM(m_voiceList.active, voice); - IM_LIST_ADD(m_voiceList.free, voice); - break; - } - voice = next; - } - } - - s32 Fm4Opl3Device::fm4_keyToDrumTimbre(s32 key) - { - return (s8)s_fmKeyToDrumTimbre[key] + 128; - } - - Fm4Opl3Device::Fm4Voice* Fm4Opl3Device::fm4_allocVoice(Fm4Channel* channel) - { - Fm4Voice* voice = m_voiceList.free; - Fm4Voice* newVoice = nullptr; - while (voice) - { - Fm4Voice* next = voice->next; - if (next) - { - voice = next; - } - else - { - IM_LIST_REM(m_voiceList.free, voice); - newVoice = voice; - break; - } - } - - if (!newVoice) - { - Fm4Voice* bestChoice = &m_voiceTemp; - bestChoice->channel = channel; - voice = m_voiceList.active; - - while (voice) - { - Fm4Channel* vchannel = voice->channel; - Fm4Channel* bchannel = bestChoice->channel; - - if (vchannel->port == bchannel->port) - { - if (bchannel->priority >= vchannel->priority) - { - bestChoice = voice; - } - } - else if (vchannel->port) - { - bestChoice = voice; - } - voice = voice->next; - } - - if (bestChoice != &m_voiceTemp) - { - fm4_voiceOff(bestChoice->id); - m_channels[bestChoice->channelId].refCount--; - m_channels[bestChoice->channelId].port = m_channels[bestChoice->channelId].refCount > m_channels[bestChoice->channelId].noteReq ? 1 : 0; - - IM_LIST_REM(m_voiceList.active, bestChoice); - newVoice = bestChoice; - } - } - - if (newVoice) - { - IM_LIST_ADD(m_voiceList.active, newVoice); - } - return newVoice; - } - - void Fm4Opl3Device::fm4_voiceOff(s32 voice) - { - fm4_sendOutput(FM4_OutRight, voice + REG_KEYON_BLOCK, m_fmVoicePitchRight[voice] & 0xdfu); - fm4_sendOutput(FM4_OutLeft, voice + REG_KEYON_BLOCK, m_fmVoicePitchLeft[voice] & 0xdfu); - } - - void Fm4Opl3Device::fm4_sendOutput(s32 port, u16 reg, u8 value) - { - const u32 regIndex = reg + port*FM4_RegisterCount; - if (m_registers[regIndex] == value) { return; } - - m_registers[regIndex] = value; - OPL3_WriteRegBuffered(FM_CHIP, regIndex, value); - } - - void Fm4Opl3Device::fm4_setVoicePitch(s32 voice, s32 key, s32 pitchOffset) - { - s32 index = max(0, key + (pitchOffset >> 8) - 7); - u8 freqIndex = s_fmKeyPitchToFreqIndex[index] + ((pitchOffset >> 4) & 0x0f); - s32 pitch = s_fmFreqIndexToPitch[freqIndex]; - s32 pitchLo = pitch & 0xff; - s32 pitchHi = ((m_fmVoicePitchRight[voice] & 0x20) | (s_fmKeyPitchHi[index] << 2)) + (pitch >> 8); - - fm4_sendOutput(FM4_OutRight, voice + REG_FNUM_LOW, pitchLo); - fm4_sendOutput(FM4_OutRight, voice + REG_KEYON_BLOCK, pitchHi); - fm4_sendOutput(FM4_OutLeft, voice + REG_FNUM_LOW, pitchLo); - fm4_sendOutput(FM4_OutLeft, voice + REG_KEYON_BLOCK, pitchHi); - } - - void Fm4Opl3Device::fm4_setVoiceDelta(s32 voice, s32 l0, s32 l1, s32 l2, s32 l3) - { - const s32 offOp1 = REG_KSL_LEVEL + s_fmVoiceOperators[0][voice]; - const s32 offOp2 = REG_KSL_LEVEL + s_fmVoiceOperators[1][voice]; - - const s32 delta0 = m_registers[offOp1] - l0; - const s32 delta1 = m_registers[offOp2] - l1; - const s32 delta2 = m_registers[offOp1 + FM4_RegisterCount] - l2; - const s32 delta3 = m_registers[offOp2 + FM4_RegisterCount] - l3; - - fm4_sendOutput(FM4_OutRight, offOp1, delta0); - fm4_sendOutput(FM4_OutRight, offOp2, delta1); - fm4_sendOutput(FM4_OutLeft, offOp1, delta2); - fm4_sendOutput(FM4_OutLeft, offOp2, delta3); - - fm4_sendOutput(FM4_OutRight, voice + REG_KEYON_BLOCK, (m_fmVoicePitchRight[voice] | VALUE_KEYON_BIT) & 0xffu); - fm4_sendOutput(FM4_OutLeft, voice + REG_KEYON_BLOCK, (m_fmVoicePitchLeft[voice] | VALUE_KEYON_BIT) & 0xffu); - } - - void Fm4Opl3Device::fm4_setVoiceTimbre(FmOutputChannel outChannel, s32 voice, TimbreBank* bank) - { - s32 offOp1 = s_fmVoiceOperators[0][voice]; - s32 offOp2 = s_fmVoiceOperators[1][voice]; - fm4_sendOutput(outChannel, REG_KSL_LEVEL + offOp1, VALUE_LEVEL_MASK); - fm4_sendOutput(outChannel, REG_KSL_LEVEL + offOp2, VALUE_LEVEL_MASK); - - // Op1 - fm4_sendOutput(outChannel, REG_ENABLE_WAVE_SELECT + offOp1, bank->op1.waveEnable); - fm4_sendOutput(outChannel, REG_KSL_LEVEL + offOp1, bank->op1.level | VALUE_LEVEL_MASK); - fm4_sendOutput(outChannel, REG_ATTACK_DECAY + offOp1, (~u32(bank->op1.attackDelay))&0xffu); - fm4_sendOutput(outChannel, REG_SUSTAIN_RELEASE + offOp1, (~u32(bank->op1.sustainRelease))&0xffu); - fm4_sendOutput(outChannel, REG_WAVE_SELECT + offOp1, bank->op1.waveSelect); - - // Op2 - fm4_sendOutput(outChannel, REG_ENABLE_WAVE_SELECT + offOp2, bank->op2.waveEnable); - fm4_sendOutput(outChannel, REG_KSL_LEVEL + offOp2, bank->op2.level | VALUE_LEVEL_MASK); - fm4_sendOutput(outChannel, REG_ATTACK_DECAY + offOp2, (~u32(bank->op2.attackDelay))&0xffu); - fm4_sendOutput(outChannel, REG_SUSTAIN_RELEASE + offOp2, (~u32(bank->op2.sustainRelease))&0xffu); - fm4_sendOutput(outChannel, REG_WAVE_SELECT + offOp2, bank->op2.waveSelect); - - fm4_sendOutput(outChannel, REG_FEEDBACK_CONNECTION + voice, bank->feedback | (outChannel == FM4_OutRight ? VALUE_VOICE_RIGHT : VALUE_VOICE_LEFT)); - } - - s32 Fm4Opl3Device::fm4_timbreToLevel(FmOutputChannel outChannel, s32 timbre, s32 remapIndex) - { - if (timbre < FM4_TimbreCount) - { - const TimbreBank* bank = fm4_getBankPtr(outChannel, timbre); - if (remapIndex <= FM4_BankRemapMax) - { - s32 offset = s_fmBankAdjust[remapIndex].offset; - s32 div = s_fmBankAdjust[remapIndex].div; - s32 mask = s_fmBankAdjust[remapIndex].mask; - return (bank->data[offset] & mask) >> div; - } - else if (remapIndex == FM4_BankCenter) - { - return bank->centerLevel; - } - } - return 0; - } - - TimbreBank* Fm4Opl3Device::fm4_getBankPtr(FmOutputChannel outChannel, s32 timbre) - { - assert(timbre < FM4_TimbreCount); - TimbreBank* bank = (outChannel == FM4_OutRight) ? s_timbreBanksRight : s_timbreBanksLeft; - return &bank[timbre]; - } - - void Fm4Opl3Device::fm4_voiceOnSide(FmOutputChannel outChannel, s32 voice, s32 timbre, s32 velocity, s32 volume, s32* output, s32& v0, s32& v1) - { - const s32 offset = outChannel; - - output[NoteTimbre0_Right+offset] = fm4_timbreToLevel(outChannel, timbre, FM4_BankRemapMax-1); - output[NoteTimbre1_Right+offset] = (fm4_timbreToLevel(outChannel, timbre, FM4_BankCenter) << 2) - 1; - - v1 = ((fm4_timbreToLevel(outChannel, timbre, 1) + 1) * velocity) >> 6; - v1 += fm4_timbreToLevel(outChannel, timbre, 0); - v1 = min(v1, FM4_MaxAtten); - output[NoteLevelRight +offset] = v1; - - v0 = ((fm4_timbreToLevel(outChannel, timbre, 14) + 1) * velocity) >> 6; - v0 += fm4_timbreToLevel(outChannel, timbre, 13); - v0 = min(v0, FM4_MaxAtten); - output[NoteLevel2Right+offset] = v0; - - v1 = fm4_getVelocityToVolumeMapping(((v1 + 1) * volume) >> 7); - if (output[2+offset] == 1) - { - v0 = fm4_getVelocityToVolumeMapping(((v0 + 1) * volume) >> 7); - } - TimbreBank* bankPtr = fm4_getBankPtr(outChannel, timbre); - fm4_setVoiceTimbre(outChannel, voice, bankPtr); - } - - void Fm4Opl3Device::fm4_voiceOn(s32 voice, s32 channelId, s32 key, s32 velocity, s32 timbre, s32 volume, s32 pan, s32 pitch) - { - // Remap velocity. - assert((velocity >> 1) < 64); - velocity = fm4_getVelocityToVolumeMapping(velocity >> 1) * 2; - - s32* output = &m_noteOutput[voice * NoteOut_Count]; - output[NoteChannelId] = channelId; - output[NoteKey] = key; - - s32 v0, v1, v2, v3; - fm4_voiceOnSide(FM4_OutRight, voice, timbre, velocity, volume, output, v0, v1); - fm4_voiceOnSide(FM4_OutLeft, voice, timbre, velocity, volume, output, v2, v3); - - // Pitch - s32 pitchOffset = (pitch - FM4_PitchCenter) >> 1; - fm4_setVoicePitch(voice, key, pitchOffset); - fm4_setVoiceDelta(voice, v0, v1, v2, v3); - } -}; -#ifdef TFE_ESPBOX -void espbox_shared_fm4(bool alloc) -{ - ESPBOX_SHARED_ALLOC(TFE_Audio::s_fmChip, 1); -} -#endif diff --git a/components/darkforces/tfe/TFE_Audio/MidiSynth/fm4Opl3Device.h b/components/darkforces/tfe/TFE_Audio/MidiSynth/fm4Opl3Device.h deleted file mode 100644 index 9faa0442..00000000 --- a/components/darkforces/tfe/TFE_Audio/MidiSynth/fm4Opl3Device.h +++ /dev/null @@ -1,144 +0,0 @@ -/////////////////////////////////////////////////////////////// -// The low-level driver code that interfaces with the OPL3 -// device (virtual device in this case) was reverse-engineered -// from the iMuse driver interface code. -// -// I moved the driver level code into the OPL3 device instead -// of as part of iMuse for several reasons: -// * The OPL3 device can be handled using the same abstraction -// as the SF2 and System midi devices. -// * It avoids the need to add addition complexity to the iMuse -// library in TFE, which is already quite large. -/////////////////////////////////////////////////////////////// -#pragma once -#include -#include -#include - -namespace TFE_Audio -{ - struct TimbreBank; - - class Fm4Opl3Device : public MidiDevice - { - public: - Fm4Opl3Device() : m_streamActive(false), m_volume(1.0f), m_volumeScaled(1.0f), m_fmVoicePitchRight(nullptr), m_fmVoicePitchLeft(nullptr), m_fmVoiceLevel(nullptr) {} - ~Fm4Opl3Device() override; - - MidiDeviceType getType() override { return MIDI_TYPE_OPL3; } - - void exit() override; - bool hasGlobalVolumeCtrl() override { return true; } - const char* getName() override; - - bool render(MidiSample* buffer, u32 sampleCount) override; - bool canRender() override; - - void message(u8 type, u8 arg1, u8 arg2) override; - void message(const u8* msg, u32 len) override; - void noteAllOff() override; - void setVolume(f32 volume) override; - - u32 getOutputCount() override; - void getOutputName(s32 index, char* buffer, u32 maxLength) override; - bool selectOutput(s32 index) override; - s32 getActiveOutput(void) override; - - private: - enum - { - FM4_VoiceCount = 9, - FM4_RegisterCount = 256, - }; - enum FmOutputChannel - { - FM4_OutRight = 0, - FM4_OutLeft, - FM4_OutCount, - }; - enum NoteOutputId - { - NoteChannelId = 0, - NoteKey, - NoteTimbre0_Right, - NoteTimbre0_Left, - NoteLevelRight, - NoteLevelLeft, - NoteLevel2Right, - NoteLevel2Left, - NoteTimbre1_Right, - NoteTimbre1_Left, - NoteOut_Count - }; - - struct Fm4Channel - { - s32 priority; - s32 noteReq; - s32 refCount; - s32 port; - - s32 timbre; - s32 volume; - s32 pan; - s32 pitch; - }; - - struct Fm4Voice - { - Fm4Voice* prev; - Fm4Voice* next; - Fm4Channel* channel; - s32 channelId; - s32 key; - s32 id; - }; - - struct Fm4VoiceList - { - Fm4Voice* active; - Fm4Voice* free; - }; - - void beginStream(s32 sampleRate); - // Low level message API. - void fm4_controlChange(s32 channelId, s32 arg1, s32 arg2); - void fm4_programChange(s32 channelId, s32 timbre); - void fm4_noteOn(s32 channel, s32 key, s32 velocity); - void fm4_noteOff(s32 channel, s32 key); - - Fm4Voice* fm4_allocVoice(Fm4Channel* channel); - - void fm4_reset(); - void fm4_sendOutput(s32 port, u16 reg, u8 value); - void fm4_setVoiceVolume(s32 voice, s32 volume); - void fm4_setVoicePitch(s32 voice, s32 key, s32 pitchOffset); - void fm4_setVoiceDelta(s32 voice, s32 l0, s32 l1, s32 l2, s32 l3); - void fm4_setVoiceTimbre(FmOutputChannel outChannel, s32 voice, TimbreBank* bank); - s32 fm4_keyToDrumTimbre(s32 key); - s32 fm4_timbreToLevel(FmOutputChannel outChannel, s32 timbre, s32 remapIndex); - TimbreBank* fm4_getBankPtr(FmOutputChannel outChannel, s32 timbre); - - void fm4_voiceOn(s32 voice, s32 channelId, s32 key, s32 velocity, s32 timbre, s32 volume, s32 pan, s32 pitch); - void fm4_voiceOff(s32 voice); - - void fm4_voiceOnSide(FmOutputChannel outChannel, s32 voice, s32 timbre, s32 velocity, s32 volume, s32* output, s32& v0, s32& v1); - void fm4_setVoiceVolumeSide(FmOutputChannel outChannel, s32 voice, s32 offset, s32 volume); - s32 fm4_getVelocityToVolumeMapping(s32 velocity); - - bool m_streamActive; - f32 m_volume; - f32 m_volumeScaled; - Fm4Channel m_channels[MIDI_CHANNEL_COUNT]; - Fm4Voice m_voices[FM4_VoiceCount]; - Fm4Voice m_voiceTemp; - Fm4VoiceList m_voiceList; - - u8 m_registers[FM4_RegisterCount * FM4_OutCount]; - s32 m_noteOutput[FM4_VoiceCount * NoteOut_Count]; - - u8* m_fmVoicePitchRight; - u8* m_fmVoicePitchLeft; - u8* m_fmVoiceLevel; - }; -}; \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Audio/MidiSynth/fm4Tables.h b/components/darkforces/tfe/TFE_Audio/MidiSynth/fm4Tables.h deleted file mode 100644 index efd24751..00000000 --- a/components/darkforces/tfe/TFE_Audio/MidiSynth/fm4Tables.h +++ /dev/null @@ -1,473 +0,0 @@ -#pragma once -#include - -namespace TFE_Audio -{ -#pragma pack(push) -#pragma pack(1) - struct TimbreBankOp - { - u8 waveEnable; - u8 level; - u8 attackDelay; - u8 sustainRelease; - u8 waveSelect; - }; - struct TimbreBank - { - union - { - struct - { - TimbreBankOp op1; - TimbreBankOp op2; - u8 feedback; - u8 centerLevel; - }; - u8 data[12]; - }; - }; -#pragma pack(pop) - - struct fmVelocityAdjust - { - s32 offset; - s32 div; - s32 mask; - }; - - static s32 s_fmFreqIndexToPitch[192] = - { - 0x0102, 0x0102, 0x0103, 0x0104, 0x0105, 0x0106, 0x0107, 0x0108, 0x0109, 0x010A, 0x010B, 0x010C, 0x010D, 0x010E, 0x010F, 0x0110, - 0x0111, 0x0112, 0x0113, 0x0114, 0x0115, 0x0116, 0x0117, 0x0118, 0x0119, 0x011A, 0x011B, 0x011C, 0x011D, 0x011E, 0x011F, 0x0120, - 0x0121, 0x0122, 0x0123, 0x0124, 0x0125, 0x0126, 0x0127, 0x0129, 0x012A, 0x012B, 0x012C, 0x012D, 0x012E, 0x012F, 0x0130, 0x0131, - 0x0132, 0x0133, 0x0135, 0x0136, 0x0137, 0x0138, 0x0139, 0x013A, 0x013B, 0x013C, 0x013E, 0x013F, 0x0140, 0x0141, 0x0142, 0x0143, - 0x0144, 0x0146, 0x0147, 0x0148, 0x0149, 0x014A, 0x014C, 0x014D, 0x014E, 0x014F, 0x0151, 0x0152, 0x0153, 0x0154, 0x0155, 0x0157, - 0x0158, 0x0159, 0x015A, 0x015C, 0x015D, 0x015E, 0x015F, 0x0161, 0x0162, 0x0163, 0x0165, 0x0166, 0x0167, 0x0168, 0x016A, 0x016B, - 0x016C, 0x016E, 0x016F, 0x0170, 0x0172, 0x0173, 0x0174, 0x0176, 0x0177, 0x0178, 0x017A, 0x017B, 0x017D, 0x017E, 0x017F, 0x0181, - 0x0182, 0x0183, 0x0185, 0x0186, 0x0188, 0x0189, 0x018B, 0x018C, 0x018D, 0x018F, 0x0190, 0x0192, 0x0193, 0x0195, 0x0196, 0x0198, - 0x0199, 0x019B, 0x019C, 0x019E, 0x019F, 0x01A1, 0x01A2, 0x01A4, 0x01A5, 0x01A7, 0x01A8, 0x01AA, 0x01AB, 0x01AD, 0x01AE, 0x01B0, - 0x01B1, 0x01B3, 0x01B5, 0x01B6, 0x01B8, 0x01B9, 0x01BB, 0x01BD, 0x01BE, 0x01C0, 0x01C1, 0x01C3, 0x01C5, 0x01C6, 0x01C8, 0x01CA, - 0x01CB, 0x01CD, 0x01CF, 0x01D0, 0x01D2, 0x01D4, 0x01D5, 0x01D7, 0x01D9, 0x01DA, 0x01DC, 0x01DE, 0x01E0, 0x01E1, 0x01E3, 0x01E5, - 0x01E6, 0x01E8, 0x01EA, 0x01EC, 0x01EE, 0x01EF, 0x01F1, 0x01F3, 0x01F5, 0x01F7, 0x01F8, 0x01FA, 0x01FC, 0x01FE, 0x0200, 0x0202 - }; - static s32 s_fmVelocityToVolumeMapping[64] = - { - 0x00, 0x04, 0x07, 0x0b, 0x0d, 0x10, 0x12, 0x14, 0x16, 0x18, 0x1a, 0x1b, 0x1d, 0x1e, 0x1f, 0x21, - 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2c, 0x2d, 0x2e, 0x2f, 0x2f, - 0x30, 0x31, 0x31, 0x32, 0x33, 0x33, 0x34, 0x35, 0x35, 0x36, 0x36, 0x37, 0x37, 0x38, 0x38, 0x39, - 0x39, 0x3a, 0x3a, 0x3b, 0x3b, 0x3c, 0x3c, 0x3c, 0x3d, 0x3d, 0x3e, 0x3e, 0x3f, 0x3f, 0x3f, 0x3f - }; - static u8 s_fmKeyPitchToFreqIndex[128] = - { - 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xA0, 0xB0, 0x00, 0x10, 0x20, 0x30, - 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xA0, 0xB0, 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, - 0x80, 0x90, 0xA0, 0xB0, 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xA0, 0xB0, - 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xA0, 0xB0, 0x00, 0x10, 0x20, 0x30, - 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xA0, 0xB0, 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, - 0x80, 0x90, 0xA0, 0xB0, 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xA0, 0xB0, - 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xA0, 0xB0, 0x00, 0x10, 0x20, 0x30, - 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xA0, 0xB0, 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70 - }; - static u8 s_fmKeyPitchHi[128] = - { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, - 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, - 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, - 0x05, 0x05, 0x05, 0x05, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, - 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, - }; - static u8 s_fmKeyToDrumTimbre[128] = - { - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, - 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0xFF, 0xFF, 0x17, 0x18, 0x19, 0x1A, - 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x21, 0x22, 0x23, 0xFF, 0xFF, - 0x24, 0x25, 0xFF, 0xFF, 0xFF, 0x26, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - }; - - static s32 s_fmVoiceOperators[2][9] = - { - { 0x00, 0x01, 0x02, 0x08, 0x09, 0x0a, 0x10, 0x11, 0x12 }, - { 0x03, 0x04, 0x05, 0x0b, 0x0c, 0x0d, 0x13, 0x14, 0x15 } - }; - - static fmVelocityAdjust s_fmBankAdjust[28] = - { - { 0x06, 0x00, 0x3F }, - { 0x09, 0x03, 0xF8 }, - { 0x06, 0x06, 0xC0 }, - { 0x05, 0x00, 0x0F }, - { 0x07, 0x04, 0xF0 }, - { 0x07, 0x00, 0x0F }, - { 0x08, 0x04, 0xF0 }, - { 0x08, 0x00, 0x0F }, - { 0x09, 0x00, 0x07 }, - { 0x05, 0x07, 0x80 }, - { 0x05, 0x06, 0x40 }, - { 0x05, 0x05, 0x20 }, - { 0x05, 0x04, 0x10 }, - { 0x01, 0x00, 0x3F }, - { 0x04, 0x03, 0xF8 }, - { 0x01, 0x06, 0xC0 }, - { 0x00, 0x00, 0x0F }, - { 0x02, 0x04, 0xF0 }, - { 0x02, 0x00, 0x0F }, - { 0x03, 0x04, 0xF0 }, - { 0x03, 0x00, 0x0F }, - { 0x04, 0x00, 0x07 }, - { 0x00, 0x07, 0x80 }, - { 0x00, 0x06, 0x40 }, - { 0x00, 0x05, 0x20 }, - { 0x00, 0x04, 0x10 }, - { 0x0A, 0x00, 0x01 }, - { 0x0A, 0x01, 0x0E } - }; - - static TimbreBank s_timbreBanksRight[167] = - { - { /*op1*/0x12, 0xA3, 0x00, 0xCD, 0x30, /*op2*/0x12, 0x8E, 0x4E, 0x8A, 0xF8, /*shared*/0x0E, 0x23 }, - { /*op1*/0x22, 0x53, 0x0E, 0x8A, 0x60, /*op2*/0x14, 0x06, 0x1D, 0x7A, 0xB8, /*shared*/0x06, 0x00 }, - { /*op1*/0x06, 0x04, 0x1C, 0x79, 0x90, /*op2*/0x02, 0x00, 0x4C, 0x79, 0xB0, /*shared*/0x0A, 0x00 }, - { /*op1*/0xC2, 0x8E, 0x0C, 0x89, 0x92, /*op2*/0xC2, 0x16, 0x0C, 0x49, 0xF9, /*shared*/0x08, 0x23 }, - { /*op1*/0xC2, 0x19, 0x0D, 0x6A, 0x48, /*op2*/0xC4, 0x16, 0x4D, 0x69, 0xF8, /*shared*/0x04, 0x00 }, - { /*op1*/0x06, 0x1E, 0x1C, 0x99, 0x00, /*op2*/0x02, 0x0C, 0x4C, 0x79, 0xF8, /*shared*/0x0C, 0x00 }, - { /*op1*/0x84, 0x4E, 0x3B, 0x5A, 0xB3, /*op2*/0x81, 0x0E, 0x3C, 0x5A, 0xFB, /*shared*/0x0F, 0x00 }, - { /*op1*/0xC6, 0x01, 0x2D, 0xA7, 0x91, /*op2*/0xC2, 0x06, 0x0C, 0x7A, 0xF1, /*shared*/0x06, 0x00 }, - { /*op1*/0x8C, 0x80, 0x05, 0xEA, 0xB1, /*op2*/0x82, 0x0A, 0x3C, 0xAA, 0xC8, /*shared*/0x07, 0x00 }, - { /*op1*/0x85, 0x40, 0x0D, 0xEC, 0xE1, /*op2*/0x84, 0x58, 0x3E, 0xCB, 0xF8, /*shared*/0x01, 0x00 }, - { /*op1*/0x8A, 0x80, 0x0B, 0xDC, 0xB0, /*op2*/0x84, 0x58, 0x3D, 0xEA, 0xF8, /*shared*/0x01, 0x00 }, // 10 - { /*op1*/0xCB, 0x50, 0x0A, 0xDD, 0x48, /*op2*/0x82, 0x8E, 0x0C, 0x79, 0xE0, /*shared*/0x0E, 0x1B }, - { /*op1*/0x2A, 0x0E, 0x17, 0x89, 0x50, /*op2*/0x22, 0x0C, 0x1B, 0x09, 0xE0, /*shared*/0x0A, 0x00 }, - { /*op1*/0xE7, 0x9B, 0x08, 0x08, 0x4A, /*op2*/0xE2, 0x06, 0x0A, 0x08, 0xE0, /*shared*/0x0A, 0x00 }, - { /*op1*/0xC5, 0x1A, 0x0F, 0x0D, 0x10, /*op2*/0x84, 0x0A, 0x00, 0xEC, 0xB8, /*shared*/0x04, 0x00 }, - { /*op1*/0x75, 0x00, 0x0E, 0xCB, 0xB2, /*op2*/0xE2, 0x1E, 0x0A, 0xC9, 0xF9, /*shared*/0x0A, 0x10 }, - { /*op1*/0xE1, 0x1B, 0x38, 0xD9, 0xD8, /*op2*/0xE4, 0x9E, 0x4A, 0xD9, 0xFA, /*shared*/0x09, 0x00 }, - { /*op1*/0x06, 0x5B, 0x0B, 0xE7, 0xF8, /*op2*/0xE1, 0xA5, 0x1C, 0xF9, 0xF9, /*shared*/0x07, 0x00 }, - { /*op1*/0xE2, 0x13, 0x0C, 0xF7, 0xF9, /*op2*/0xE3, 0x5B, 0x4F, 0xC7, 0xFA, /*shared*/0x05, 0x00 }, - { /*op1*/0x01, 0x8C, 0x9F, 0xDA, 0xE0, /*op2*/0xE4, 0x50, 0x9F, 0xDA, 0xD2, /*shared*/0x09, 0x00 }, - { /*op1*/0x06, 0x48, 0x7D, 0xAA, 0x81, /*op2*/0xE2, 0x1E, 0x4F, 0xA9, 0xFA, /*shared*/0x0C, 0x00 }, // 20 - { /*op1*/0xE5, 0x4B, 0x8D, 0xB8, 0x82, /*op2*/0xA2, 0x0F, 0x3F, 0xC7, 0xC1, /*shared*/0x0C, 0x00 }, - { /*op1*/0xF2, 0x2A, 0x9F, 0xDB, 0x01, /*op2*/0xE1, 0x04, 0x8F, 0xD7, 0xC2, /*shared*/0x0A, 0x00 }, - { /*op1*/0xE4, 0x88, 0x9C, 0x50, 0xC8, /*op2*/0xE2, 0x18, 0x70, 0xC4, 0xF8, /*shared*/0x0B, 0x00 }, - { /*op1*/0x02, 0x88, 0x09, 0xA7, 0x80, /*op2*/0xC1, 0x1C, 0x3D, 0x88, 0xFA, /*shared*/0x02, 0x18 }, - { /*op1*/0x42, 0x55, 0x3E, 0x8C, 0x48, /*op2*/0xC4, 0x0B, 0x0D, 0xA9, 0xE1, /*shared*/0x04, 0x18 }, - { /*op1*/0xC2, 0x00, 0x2B, 0x17, 0xA1, /*op2*/0xC2, 0x1E, 0x4D, 0x97, 0xF8, /*shared*/0x00, 0x19 }, - { /*op1*/0xC6, 0x01, 0x2D, 0x77, 0x90, /*op2*/0xC2, 0x06, 0x0E, 0x97, 0xF1, /*shared*/0x06, 0x00 }, - { /*op1*/0xC2, 0x0C, 0x06, 0x06, 0xA9, /*op2*/0xC2, 0x3F, 0x09, 0x86, 0xF9, /*shared*/0x0A, 0x0A }, - { /*op1*/0xE2, 0x32, 0x6D, 0x9A, 0x00, /*op2*/0xE4, 0x20, 0x0E, 0x98, 0xF9, /*shared*/0x0A, 0x00 }, - { /*op1*/0xE2, 0x30, 0x7F, 0xAA, 0x01, /*op2*/0xE4, 0x17, 0x5D, 0x78, 0xFB, /*shared*/0x08, 0x00 }, // 30 - { /*op1*/0xC4, 0x29, 0x4F, 0xCA, 0x03, /*op2*/0xC8, 0x0D, 0x0C, 0xB7, 0xF9, /*shared*/0x00, 0x0B }, - { /*op1*/0xC2, 0x40, 0x3C, 0x96, 0xB0, /*op2*/0xC4, 0xDE, 0x0E, 0xC7, 0xF8, /*shared*/0x00, 0x20 }, - { /*op1*/0x32, 0x13, 0x2D, 0xD9, 0x78, /*op2*/0xE2, 0x18, 0x2E, 0xB8, 0xF8, /*shared*/0x08, 0x00 }, - { /*op1*/0xE2, 0x8E, 0x0A, 0xE9, 0x98, /*op2*/0xE4, 0x18, 0x5E, 0xB8, 0xF8, /*shared*/0x06, 0x28 }, - { /*op1*/0xF2, 0x0A, 0x0D, 0xD7, 0x80, /*op2*/0xE4, 0x1F, 0x5E, 0xB8, 0xF8, /*shared*/0x0A, 0x00 }, - { /*op1*/0xF2, 0x09, 0x4B, 0xD6, 0x90, /*op2*/0xE4, 0x1F, 0x1C, 0xB8, 0xF8, /*shared*/0x0A, 0x28 }, - { /*op1*/0x62, 0x11, 0x0C, 0xE6, 0x78, /*op2*/0xE4, 0x1F, 0x0C, 0xC8, 0xF8, /*shared*/0x0A, 0x00 }, - { /*op1*/0xC2, 0x31, 0x59, 0xD9, 0x11, /*op2*/0xC2, 0x1A, 0x7C, 0xB8, 0xF8, /*shared*/0x0C, 0x00 }, - { /*op1*/0xE2, 0xEA, 0x8D, 0x66, 0x20, /*op2*/0xE2, 0x1F, 0x0E, 0x68, 0xF8, /*shared*/0x08, 0x00 }, - { /*op1*/0xA2, 0x40, 0x5D, 0xBA, 0x7B, /*op2*/0xE2, 0x00, 0x8F, 0xD8, 0xF1, /*shared*/0x00, 0x00 }, // 40 - { /*op1*/0xE2, 0x40, 0x3D, 0xDA, 0x73, /*op2*/0xE1, 0x00, 0x7E, 0xD8, 0xF2, /*shared*/0x04, 0x00 }, - { /*op1*/0x62, 0x00, 0x6D, 0xFA, 0xB9, /*op2*/0xE2, 0x00, 0x8F, 0xC8, 0xF1, /*shared*/0x04, 0x00 }, - { /*op1*/0xE1, 0x00, 0x4E, 0xDB, 0x92, /*op2*/0xE3, 0x18, 0x6F, 0xE9, 0xFA, /*shared*/0x00, 0x00 }, - { /*op1*/0x62, 0xA0, 0x7D, 0xCD, 0x19, /*op2*/0x62, 0x91, 0x9E, 0xE7, 0x80, /*shared*/0x00, 0x00 }, - { /*op1*/0xD2, 0xA2, 0x8A, 0x8A, 0x31, /*op2*/0xD2, 0x0C, 0x0A, 0xCA, 0xF8, /*shared*/0x08, 0x04 }, - { /*op1*/0x12, 0x56, 0x2A, 0xCC, 0x3A, /*op2*/0x12, 0x90, 0x7D, 0xCC, 0xF8, /*shared*/0x0E, 0x03 }, - { /*op1*/0x00, 0xBC, 0x17, 0xAB, 0x12, /*op2*/0x03, 0xC9, 0x5B, 0xBA, 0xF8, /*shared*/0x06, 0x04 }, - { /*op1*/0x22, 0x9F, 0x7D, 0xCD, 0x21, /*op2*/0x62, 0x8B, 0x9E, 0xE7, 0xF8, /*shared*/0x0C, 0x00 }, - { /*op1*/0x62, 0x9E, 0x7D, 0xCD, 0x19, /*op2*/0x62, 0x96, 0x9E, 0xE7, 0x80, /*shared*/0x00, 0x00 }, - { /*op1*/0xE2, 0x45, 0x7F, 0xFB, 0xA0, /*op2*/0xF2, 0x04, 0x9F, 0xFB, 0xF9, /*shared*/0x0A, 0x00 }, // 50 - { /*op1*/0xE4, 0xA0, 0xCE, 0x5B, 0x02, /*op2*/0xE2, 0x32, 0x7F, 0xFB, 0x79, /*shared*/0x04, 0x00 }, - { /*op1*/0xE4, 0x99, 0xAC, 0xC9, 0x21, /*op2*/0xE2, 0x9E, 0x9D, 0xE9, 0xF8, /*shared*/0x00, 0x00 }, - { /*op1*/0xEA, 0xA0, 0xAC, 0x67, 0x02, /*op2*/0xE2, 0x00, 0x7C, 0x7A, 0xF8, /*shared*/0x06, 0x00 }, - { /*op1*/0xE7, 0x94, 0xAD, 0xB7, 0x03, /*op2*/0xE2, 0x00, 0x7C, 0xBA, 0xF8, /*shared*/0x00, 0x00 }, - { /*op1*/0xC3, 0x3F, 0x4B, 0xE9, 0xFA, /*op2*/0xC1, 0x3F, 0x9B, 0xF9, 0xFB, /*shared*/0x0B, 0x06 }, - { /*op1*/0x22, 0x1C, 0x8D, 0xE9, 0x10, /*op2*/0x32, 0x08, 0xAE, 0xD9, 0xF8, /*shared*/0x0E, 0x00 }, - { /*op1*/0x22, 0x9E, 0x8D, 0xEC, 0x10, /*op2*/0x34, 0x89, 0xAD, 0xD8, 0xF8, /*shared*/0x0E, 0x00 }, - { /*op1*/0xF2, 0x00, 0xAF, 0x88, 0xB0, /*op2*/0xF2, 0x54, 0x6E, 0xC9, 0xF8, /*shared*/0x0A, 0x00 }, - { /*op1*/0xF2, 0x2A, 0x9F, 0x98, 0x01, /*op2*/0xE2, 0x84, 0x4E, 0x78, 0xD8, /*shared*/0x0E, 0x00 }, - { /*op1*/0x22, 0x9C, 0x9D, 0xEA, 0x10, /*op2*/0x22, 0x07, 0x9C, 0xE8, 0xF8, /*shared*/0x0E, 0x00 }, // 60 - { /*op1*/0xE2, 0x2A, 0x7F, 0xB8, 0x01, /*op2*/0xE4, 0x00, 0x0D, 0xC5, 0xF8, /*shared*/0x0C, 0x00 }, - { /*op1*/0xE4, 0x28, 0x8E, 0xE8, 0x01, /*op2*/0xF2, 0x00, 0x4D, 0xD6, 0xF9, /*shared*/0x0C, 0x00 }, - { /*op1*/0xB2, 0x93, 0xAE, 0xAA, 0x49, /*op2*/0xB2, 0x0F, 0xAE, 0xE9, 0xF8, /*shared*/0x0E, 0x00 }, - { /*op1*/0xE2, 0x6B, 0x6E, 0x99, 0x01, /*op2*/0xE2, 0x1F, 0x8D, 0xC8, 0xFA, /*shared*/0x08, 0x00 }, - { /*op1*/0xE2, 0x2E, 0x20, 0xD9, 0x01, /*op2*/0xF2, 0x0F, 0x90, 0xF8, 0xF0, /*shared*/0x0E, 0x00 }, - { /*op1*/0xE4, 0x28, 0x7E, 0xF8, 0x01, /*op2*/0xE2, 0x23, 0x8E, 0xE8, 0xF9, /*shared*/0x08, 0x00 }, - { /*op1*/0xB8, 0x28, 0x9E, 0x98, 0x01, /*op2*/0x62, 0x00, 0x3D, 0xC8, 0xF9, /*shared*/0x08, 0x00 }, - { /*op1*/0x62, 0x11, 0x8E, 0xC9, 0x49, /*op2*/0xE3, 0x15, 0x7E, 0xD8, 0xFA, /*shared*/0x0A, 0x00 }, - { /*op1*/0xE2, 0x04, 0x7F, 0xFE, 0x80, /*op2*/0xE6, 0x98, 0x8F, 0xF9, 0xF9, /*shared*/0x08, 0x00 }, - { /*op1*/0xE2, 0x16, 0x7D, 0xDA, 0x51, /*op2*/0xEA, 0x1E, 0x8D, 0xD8, 0xF9, /*shared*/0x06, 0x00 }, // 70 - { /*op1*/0xA4, 0x96, 0x9D, 0xD9, 0x40, /*op2*/0xA2, 0x8C, 0x9E, 0xE8, 0xF8, /*shared*/0x0C, 0x00 }, - { /*op1*/0xF2, 0x93, 0x64, 0xC9, 0x90, /*op2*/0xE2, 0x1E, 0x7E, 0xC8, 0xF8, /*shared*/0x04, 0x00 }, - { /*op1*/0xB2, 0x65, 0x6D, 0xE9, 0x10, /*op2*/0xA2, 0x07, 0x9D, 0xE8, 0xF8, /*shared*/0x08, 0x00 }, - { /*op1*/0xE4, 0x00, 0x77, 0xC5, 0xA8, /*op2*/0xE2, 0x00, 0x9E, 0xD7, 0xE0, /*shared*/0x06, 0x00 }, - { /*op1*/0xE4, 0x80, 0x86, 0xB9, 0xC8, /*op2*/0xE2, 0x05, 0x9F, 0xD7, 0xF0, /*shared*/0x0A, 0x00 }, - { /*op1*/0xE2, 0x00, 0x68, 0x68, 0xAA, /*op2*/0xE2, 0x08, 0x9B, 0xB3, 0xF8, /*shared*/0x08, 0x00 }, - { /*op1*/0xE4, 0x00, 0xA6, 0x87, 0x81, /*op2*/0xE2, 0x0A, 0x7E, 0xC9, 0xF8, /*shared*/0x06, 0x00 }, - { /*op1*/0xE4, 0x80, 0x9A, 0xB8, 0x90, /*op2*/0xE2, 0x00, 0x9E, 0xF9, 0xC0, /*shared*/0x09, 0x00 }, - { /*op1*/0xE2, 0x80, 0x8E, 0x64, 0xD0, /*op2*/0xE2, 0x28, 0x6F, 0x73, 0xF8, /*shared*/0x01, 0x00 }, - { /*op1*/0xE8, 0x00, 0x4D, 0x99, 0xA8, /*op2*/0xE6, 0x80, 0x00, 0xF8, 0xF8, /*shared*/0x0C, 0x00 }, // 80 - { /*op1*/0xE3, 0x0C, 0x4F, 0xB9, 0xC3, /*op2*/0xE2, 0x15, 0x0F, 0xC8, 0xF9, /*shared*/0x06, 0x00 }, - { /*op1*/0xE4, 0x00, 0x09, 0x68, 0x92, /*op2*/0xE2, 0x2B, 0x9E, 0xF3, 0xF8, /*shared*/0x0E, 0x00 }, - { /*op1*/0xE1, 0x0A, 0x9F, 0xCA, 0xB2, /*op2*/0xE2, 0x25, 0x0E, 0x89, 0xF8, /*shared*/0x06, 0x00 }, - { /*op1*/0xE1, 0x06, 0x7F, 0xD1, 0xC2, /*op2*/0xE6, 0x1F, 0x3F, 0xD0, 0xF9, /*shared*/0x06, 0x00 }, - { /*op1*/0xE5, 0x5E, 0xAE, 0xBB, 0x03, /*op2*/0xE2, 0x1C, 0x2E, 0xD9, 0xF9, /*shared*/0x06, 0x00 }, - { /*op1*/0xF3, 0x29, 0x7F, 0xD7, 0xF9, /*op2*/0xF1, 0x21, 0x3F, 0xD7, 0xFA, /*shared*/0x0B, 0x00 }, - { /*op1*/0xE2, 0x68, 0x2E, 0xCB, 0x30, /*op2*/0xE4, 0x3C, 0x5F, 0xEA, 0x78, /*shared*/0x08, 0x00 }, - { /*op1*/0x28, 0x49, 0x0C, 0xCB, 0x40, /*op2*/0xE2, 0x11, 0x5B, 0xD9, 0x48, /*shared*/0x05, 0x00 }, - { /*op1*/0xE2, 0x02, 0xDE, 0xAB, 0x90, /*op2*/0xE2, 0x5E, 0xCF, 0xBA, 0xF9, /*shared*/0x04, 0x00 }, - { /*op1*/0xE2, 0x26, 0x7D, 0xCB, 0x31, /*op2*/0xE2, 0x1E, 0x0E, 0xB9, 0xF8, /*shared*/0x0A, 0x00 }, // 90 - { /*op1*/0xEA, 0x0C, 0xAD, 0xAB, 0x61, /*op2*/0xE2, 0x16, 0x7E, 0xBA, 0xF8, /*shared*/0x0A, 0x00 }, - { /*op1*/0xEB, 0x80, 0x8C, 0xCB, 0x72, /*op2*/0xE2, 0x06, 0x9F, 0xCA, 0xF8, /*shared*/0x08, 0x00 }, - { /*op1*/0xE6, 0x9C, 0xCD, 0xBB, 0x31, /*op2*/0xE1, 0x5F, 0x4E, 0xCA, 0xFA, /*shared*/0x0A, 0x00 }, - { /*op1*/0xEA, 0x89, 0x9D, 0xAB, 0x82, /*op2*/0xE2, 0x1E, 0x9F, 0xBA, 0xF8, /*shared*/0x0A, 0x00 }, - { /*op1*/0x2A, 0x48, 0xED, 0xCA, 0x80, /*op2*/0x22, 0x0C, 0xBF, 0xBA, 0xF9, /*shared*/0x00, 0x00 }, - { /*op1*/0xEA, 0x40, 0x98, 0xB9, 0x90, /*op2*/0xE2, 0x0A, 0x0E, 0xC8, 0xF8, /*shared*/0x0C, 0x00 }, - { /*op1*/0xE1, 0x1A, 0xBF, 0xAB, 0xF2, /*op2*/0xE3, 0x5D, 0xCE, 0xAA, 0xF9, /*shared*/0x09, 0x00 }, - { /*op1*/0xC9, 0x06, 0x0B, 0x0B, 0xA0, /*op2*/0xC2, 0x5E, 0x0C, 0x0A, 0xF8, /*shared*/0x0C, 0x1C }, - { /*op1*/0x64, 0x1C, 0x39, 0xBA, 0x10, /*op2*/0x62, 0x4C, 0x5C, 0xDA, 0xF8, /*shared*/0x0E, 0x00 }, - { /*op1*/0xCC, 0x00, 0x7D, 0xDA, 0x80, /*op2*/0xC2, 0x00, 0x5E, 0x9B, 0xB0, /*shared*/0x0C, 0x00 }, // 100 - { /*op1*/0xE4, 0xC6, 0xEE, 0xCB, 0x93, /*op2*/0xE2, 0x16, 0xDE, 0xDA, 0xF8, /*shared*/0x08, 0x00 }, - { /*op1*/0xDA, 0x00, 0x8F, 0xAC, 0xA2, /*op2*/0xE2, 0x1E, 0x8D, 0x8A, 0xF9, /*shared*/0x02, 0x00 }, - { /*op1*/0x62, 0x88, 0x6C, 0x7C, 0x80, /*op2*/0xE6, 0x20, 0x0F, 0xDB, 0xF9, /*shared*/0x08, 0x00 }, - { /*op1*/0xC8, 0x08, 0xBD, 0x5B, 0x8B, /*op2*/0xC2, 0x61, 0x0D, 0xAB, 0xF9, /*shared*/0x08, 0x12 }, - { /*op1*/0x75, 0x00, 0x0E, 0xCB, 0xB2, /*op2*/0xE2, 0x1E, 0x0A, 0xC9, 0xF9, /*shared*/0x0A, 0x10 }, - { /*op1*/0x41, 0x00, 0x0E, 0xEA, 0xA3, /*op2*/0xC2, 0x00, 0x08, 0xCA, 0xF8, /*shared*/0x08, 0x07 }, - { /*op1*/0xC1, 0x40, 0x0C, 0x59, 0xD2, /*op2*/0xC2, 0x80, 0x3C, 0xAB, 0xF8, /*shared*/0x08, 0x0D }, - { /*op1*/0x4B, 0x00, 0x0A, 0xF5, 0xC1, /*op2*/0xC2, 0x19, 0x0C, 0xE9, 0xF8, /*shared*/0x08, 0x07 }, - { /*op1*/0x62, 0x00, 0x7F, 0xD8, 0xA8, /*op2*/0xEA, 0x00, 0x8F, 0xD8, 0xF9, /*shared*/0x0A, 0x00 }, - { /*op1*/0xE1, 0x00, 0x7F, 0xD9, 0xAA, /*op2*/0xE1, 0x00, 0x8F, 0xD8, 0xFA, /*shared*/0x06, 0x00 }, // 110 - { /*op1*/0xE1, 0x00, 0x7F, 0xD9, 0xAA, /*op2*/0xE1, 0x00, 0x8F, 0xD8, 0xFA, /*shared*/0x06, 0x00 }, - { /*op1*/0xCF, 0x40, 0x09, 0xEA, 0xA8, /*op2*/0xC4, 0x00, 0x0C, 0xDB, 0xC8, /*shared*/0x08, 0x02 }, - { /*op1*/0xCF, 0x40, 0x0C, 0xAA, 0xA8, /*op2*/0xC4, 0x00, 0x18, 0xF9, 0xC8, /*shared*/0x0C, 0x02 }, - { /*op1*/0xC9, 0x0E, 0x88, 0xD9, 0x7A, /*op2*/0xC2, 0x08, 0x1A, 0xEA, 0xD8, /*shared*/0x0C, 0x05 }, - { /*op1*/0x03, 0x00, 0x15, 0x00, 0xC8, /*op2*/0x02, 0x00, 0x08, 0x00, 0xF8, /*shared*/0x09, 0x02 }, - { /*op1*/0x01, 0x00, 0x47, 0xD7, 0xD8, /*op2*/0x01, 0x3F, 0x0C, 0xFB, 0xF8, /*shared*/0x0A, 0x04 }, - { /*op1*/0x00, 0x00, 0x36, 0x67, 0xF8, /*op2*/0x01, 0x3F, 0x0E, 0xFA, 0xF8, /*shared*/0x00, 0x05 }, - { /*op1*/0x02, 0x00, 0x36, 0x68, 0xF8, /*op2*/0x01, 0x3F, 0x0E, 0xFA, 0xF8, /*shared*/0x00, 0x05 }, - { /*op1*/0xCB, 0x00, 0xAF, 0x00, 0xFA, /*op2*/0xC0, 0x00, 0xC0, 0x06, 0xFB, /*shared*/0x0E, 0x0F }, - { /*op1*/0x05, 0x0D, 0x80, 0xA6, 0xFB, /*op2*/0x0B, 0x38, 0xA9, 0xD8, 0x00, /*shared*/0x0E, 0x04 }, // 120 - { /*op1*/0x0F, 0x00, 0x90, 0xFA, 0xD0, /*op2*/0x06, 0x00, 0xA7, 0x39, 0xA8, /*shared*/0x0E, 0x06 }, - { /*op1*/0xC9, 0x15, 0xDD, 0xFF, 0xF8, /*op2*/0x00, 0x00, 0xE7, 0xFC, 0xD8, /*shared*/0x0E, 0x38 }, - { /*op1*/0x48, 0x3C, 0x30, 0xF6, 0x03, /*op2*/0x0A, 0x38, 0x97, 0xE8, 0x00, /*shared*/0x0E, 0x04 }, - { /*op1*/0x07, 0x80, 0x0B, 0xC8, 0xC9, /*op2*/0x02, 0x3F, 0x0C, 0xEA, 0xF8, /*shared*/0x0F, 0x05 }, - { /*op1*/0x00, 0x21, 0x66, 0x40, 0x03, /*op2*/0x00, 0x3F, 0x47, 0x00, 0x00, /*shared*/0x0E, 0x02 }, - { /*op1*/0x08, 0x00, 0x0B, 0x3C, 0xF8, /*op2*/0x08, 0x3F, 0x06, 0xF3, 0x00, /*shared*/0x0E, 0x02 }, - { /*op1*/0x00, 0x3F, 0x4C, 0xFB, 0x00, /*op2*/0x00, 0x3F, 0x0A, 0xE9, 0xF8, /*shared*/0x0E, 0x05 }, - { /*op1*/0x1A, 0x3F, 0x15, 0x05, 0xF8, /*op2*/0x02, 0x21, 0x2B, 0xE4, 0xF8, /*shared*/0x0E, 0x06 }, - { /*op1*/0x04, 0x3F, 0x42, 0x00, 0x00, /*op2*/0x02, 0x06, 0x1A, 0xE9, 0xE0, /*shared*/0x0E, 0x07 }, - { /*op1*/0x0A, 0x3F, 0x0B, 0x01, 0xF8, /*op2*/0x1F, 0x1C, 0x46, 0xD0, 0xF8, /*shared*/0x0E, 0x01 }, // 130 - { /*op1*/0x01, 0x3C, 0x0F, 0xFF, 0x80, /*op2*/0x14, 0x06, 0x68, 0xB9, 0xC0, /*shared*/0x0E, 0x02 }, - { /*op1*/0x0F, 0x3F, 0x0B, 0x00, 0xF8, /*op2*/0x1F, 0x0F, 0x19, 0xD0, 0xF8, /*shared*/0x0E, 0x02 }, - { /*op1*/0x01, 0x3C, 0x0F, 0xFF, 0x80, /*op2*/0x14, 0x06, 0x68, 0xB9, 0xC0, /*shared*/0x0E, 0x02 }, - { /*op1*/0x01, 0x3F, 0x42, 0x85, 0x7A, /*op2*/0x02, 0x0B, 0x0A, 0xD8, 0xF8, /*shared*/0x0A, 0x03 }, - { /*op1*/0xCF, 0x7F, 0x08, 0xFF, 0xFA, /*op2*/0x00, 0xC7, 0x2D, 0xF7, 0xE3, /*shared*/0x0E, 0x02 }, - { /*op1*/0x01, 0x3F, 0x42, 0x85, 0x7A, /*op2*/0x02, 0x0B, 0x0A, 0xD8, 0xF8, /*shared*/0x0A, 0x03 }, - { /*op1*/0xCF, 0x7F, 0x08, 0xCF, 0xFA, /*op2*/0x00, 0x45, 0x2A, 0xF8, 0x93, /*shared*/0x0E, 0x0C }, - { /*op1*/0x01, 0x3F, 0x42, 0x85, 0x7A, /*op2*/0x02, 0x0B, 0x0A, 0xD8, 0xF8, /*shared*/0x0A, 0x03 }, - { /*op1*/0xCF, 0x7F, 0x08, 0xCD, 0xFA, /*op2*/0x00, 0x40, 0x1A, 0x69, 0xC3, /*shared*/0x0E, 0x0C }, - { /*op1*/0x01, 0x3F, 0x42, 0x85, 0x7A, /*op2*/0x02, 0x0B, 0x0A, 0xD8, 0xF8, /*shared*/0x0A, 0x03 }, // 140 - { /*op1*/0x01, 0x3F, 0x42, 0x85, 0x7A, /*op2*/0x02, 0x0B, 0x0A, 0xD8, 0xF8, /*shared*/0x0A, 0x03 }, - { /*op1*/0xCF, 0x3F, 0x2B, 0xFB, 0xFA, /*op2*/0xC0, 0x1E, 0x1A, 0xCA, 0xFB, /*shared*/0x0E, 0x10 }, - { /*op1*/0x01, 0x3F, 0x42, 0x85, 0x7A, /*op2*/0x02, 0x0B, 0x0A, 0xD8, 0xF8, /*shared*/0x0A, 0x03 }, - { /*op1*/0xCF, 0x3F, 0x0F, 0x5E, 0xF8, /*op2*/0xC6, 0x13, 0x00, 0xCA, 0xFB, /*shared*/0x04, 0x03 }, - { /*op1*/0xCF, 0x3F, 0x7E, 0x9D, 0xF8, /*op2*/0xC8, 0xC0, 0x0A, 0xBA, 0xE8, /*shared*/0x0E, 0x06 }, - { /*op1*/0xCF, 0x3F, 0x4D, 0x9F, 0xF8, /*op2*/0xC6, 0x00, 0x08, 0xDA, 0xB3, /*shared*/0x04, 0x04 }, - { /*op1*/0xCF, 0x3F, 0x5D, 0xAA, 0xF2, /*op2*/0xC0, 0xA4, 0x67, 0x99, 0xF8, /*shared*/0x0A, 0x02 }, - { /*op1*/0xCF, 0x3F, 0x4A, 0xFD, 0xF8, /*op2*/0xCF, 0x00, 0x59, 0xEA, 0xF8, /*shared*/0x0E, 0x02 }, - { /*op1*/0x0F, 0x18, 0x0A, 0xFA, 0xAB, /*op2*/0x06, 0x07, 0x06, 0x39, 0xF8, /*shared*/0x0A, 0x02 }, - { /*op1*/0xCF, 0x3F, 0x2B, 0xFC, 0xF8, /*op2*/0xCC, 0xC6, 0x0B, 0xEA, 0xFB, /*shared*/0x0E, 0x10 }, // 150 - { /*op1*/0x05, 0x1A, 0x04, 0x00, 0xF8, /*op2*/0x12, 0x10, 0x0C, 0xEA, 0xF8, /*shared*/0x0E, 0x07 }, - { /*op1*/0x04, 0x19, 0x04, 0x00, 0xF8, /*op2*/0x12, 0x10, 0x2C, 0xEA, 0xF8, /*shared*/0x0E, 0x04 }, - { /*op1*/0x04, 0x0A, 0x04, 0x00, 0xD8, /*op2*/0x01, 0x07, 0x0D, 0xFA, 0xE8, /*shared*/0x0E, 0x07 }, - { /*op1*/0x15, 0x14, 0x05, 0x00, 0xF9, /*op2*/0x01, 0x07, 0x5C, 0xE9, 0xF8, /*shared*/0x0E, 0x05 }, - { /*op1*/0x10, 0x10, 0x05, 0x08, 0xF8, /*op2*/0x01, 0x08, 0x0D, 0xEA, 0xF8, /*shared*/0x0E, 0x05 }, - { /*op1*/0x11, 0x00, 0x06, 0x87, 0xFB, /*op2*/0x02, 0x40, 0x09, 0x59, 0xD0, /*shared*/0x0E, 0x08 }, - { /*op1*/0x13, 0x26, 0x04, 0x6A, 0xFB, /*op2*/0x01, 0x00, 0x08, 0x5A, 0xF8, /*shared*/0x0E, 0x08 }, - { /*op1*/0xCF, 0x4E, 0x0C, 0xAA, 0xA0, /*op2*/0xC4, 0x00, 0x18, 0xF9, 0xA8, /*shared*/0x04, 0x02 }, - { /*op1*/0xCF, 0x4E, 0x0C, 0xAA, 0xA0, /*op2*/0xC3, 0x00, 0x18, 0xF8, 0xA8, /*shared*/0x04, 0x02 }, - { /*op1*/0xCB, 0x3F, 0x8F, 0x00, 0xFA, /*op2*/0xC5, 0x00, 0x98, 0xD6, 0xBB, /*shared*/0x0E, 0x0D }, // 160 - { /*op1*/0x0C, 0x18, 0x87, 0xB3, 0xFB, /*op2*/0x19, 0x10, 0x55, 0x75, 0xF8, /*shared*/0x0E, 0x02 }, - { /*op1*/0x05, 0x11, 0x15, 0x00, 0xC8, /*op2*/0x02, 0x08, 0x08, 0x00, 0xB8, /*shared*/0x09, 0x02 }, - { /*op1*/0x04, 0x08, 0x15, 0x00, 0x90, /*op2*/0x01, 0x08, 0x08, 0x00, 0xC0, /*shared*/0x08, 0x02 }, - { /*op1*/0xDA, 0x00, 0x53, 0x30, 0xD0, /*op2*/0x07, 0x1E, 0x49, 0xC4, 0xFA, /*shared*/0x03, 0x00 }, - { /*op1*/0x1C, 0x00, 0x07, 0xBC, 0xD8, /*op2*/0x0C, 0x14, 0x0B, 0x6A, 0xFA, /*shared*/0x0B, 0x03 }, - { /*op1*/0x0A, 0x0E, 0x7F, 0x00, 0xF9, /*op2*/0x13, 0x20, 0x28, 0x03, 0xF8, /*shared*/0x06, 0x00 }, - }; - static TimbreBank s_timbreBanksLeft[167] = - { - { /*op1*/0x12, 0xA6, 0x00, 0xCD, 0x30, /*op2*/0x12, 0x8E, 0x4E, 0x8A, 0xF8, /*shared*/0x0C, 0x23 }, - { /*op1*/0x22, 0x5A, 0x0E, 0x8A, 0x40, /*op2*/0x14, 0x2F, 0x0E, 0x7A, 0x88, /*shared*/0x06, 0x00 }, - { /*op1*/0x04, 0x28, 0x5D, 0xB8, 0x01, /*op2*/0x02, 0x18, 0x3C, 0x70, 0x90, /*shared*/0x0A, 0x00 }, - { /*op1*/0x04, 0x28, 0x5D, 0xB8, 0x01, /*op2*/0x02, 0x18, 0x3C, 0x70, 0x90, /*shared*/0x0A, 0x00 }, - { /*op1*/0xC4, 0x4E, 0x3C, 0x6A, 0x48, /*op2*/0xC4, 0x04, 0x2C, 0xC9, 0xB0, /*shared*/0x06, 0x00 }, - { /*op1*/0x04, 0xC8, 0x1C, 0x6B, 0x70, /*op2*/0x02, 0x80, 0x4C, 0x89, 0xA1, /*shared*/0x0C, 0x00 }, - { /*op1*/0x01, 0x00, 0x01, 0x00, 0x00, /*op2*/0x81, 0x48, 0x3B, 0x89, 0x65, /*shared*/0x01, 0x00 }, - { /*op1*/0x84, 0x40, 0x3B, 0x5A, 0x83, /*op2*/0x81, 0x00, 0x3B, 0x5A, 0x9B, /*shared*/0x01, 0x00 }, - { /*op1*/0x00, 0x00, 0x00, 0x00, 0x00, /*op2*/0x8F, 0x14, 0x34, 0x8B, 0xB0, /*shared*/0x09, 0x00 }, - { /*op1*/0x8A, 0x40, 0x09, 0x2B, 0x00, /*op2*/0x84, 0xFF, 0x3C, 0x6A, 0x00, /*shared*/0x05, 0x00 }, - { /*op1*/0x8A, 0xC0, 0x0C, 0xDC, 0x00, /*op2*/0x84, 0x58, 0x3D, 0xDA, 0xF8, /*shared*/0x01, 0x00 }, // 10 - { /*op1*/0x0A, 0x55, 0x28, 0xAD, 0x48, /*op2*/0x82, 0x8E, 0x0C, 0x79, 0xE0, /*shared*/0x00, 0x1B }, - { /*op1*/0x2A, 0x1A, 0x19, 0x8A, 0x00, /*op2*/0x22, 0x38, 0x0B, 0x0A, 0x00, /*shared*/0x0A, 0x00 }, - { /*op1*/0xE7, 0x9B, 0x08, 0x08, 0x4A, /*op2*/0xE2, 0x2F, 0x0A, 0x08, 0x68, /*shared*/0x0A, 0x00 }, - { /*op1*/0xC5, 0x12, 0x0F, 0x0D, 0x10, /*op2*/0x84, 0x0B, 0x00, 0xEB, 0xC0, /*shared*/0x0E, 0x00 }, - { /*op1*/0x86, 0x40, 0x5D, 0x5A, 0x81, /*op2*/0x81, 0x00, 0x0B, 0x5A, 0xFB, /*shared*/0x00, 0x00 }, - { /*op1*/0xE6, 0x40, 0x0A, 0xA7, 0x04, /*op2*/0xE2, 0x97, 0x3D, 0x79, 0xF9, /*shared*/0x01, 0x00 }, - { /*op1*/0xC9, 0x02, 0x16, 0x9A, 0xAB, /*op2*/0xC4, 0x15, 0x46, 0xBA, 0xF8, /*shared*/0x04, 0x00 }, - { /*op1*/0xE9, 0x04, 0x2A, 0x48, 0x45, /*op2*/0xE4, 0x12, 0x6C, 0x39, 0xF8, /*shared*/0x08, 0x00 }, - { /*op1*/0x02, 0x80, 0x9F, 0xDA, 0x00, /*op2*/0xE3, 0x50, 0x9F, 0xD9, 0xFA, /*shared*/0x03, 0x00 }, - { /*op1*/0x00, 0x00, 0x00, 0x00, 0x00, /*op2*/0xE5, 0x0E, 0x9F, 0xD6, 0xF9, /*shared*/0x07, 0x00 }, // 20 - { /*op1*/0x06, 0x4C, 0xAC, 0x56, 0x31, /*op2*/0x02, 0x08, 0x8D, 0x46, 0xDC, /*shared*/0x00, 0x00 }, - { /*op1*/0xF2, 0x00, 0x9F, 0xDB, 0xA9, /*op2*/0xE1, 0x00, 0x8F, 0xD7, 0xBA, /*shared*/0x0A, 0x00 }, - { /*op1*/0xE6, 0x00, 0x00, 0x50, 0x00, /*op2*/0xE6, 0x12, 0x7C, 0xA9, 0xF2, /*shared*/0x07, 0x00 }, - { /*op1*/0x02, 0xA3, 0x0D, 0xDA, 0x01, /*op2*/0xC2, 0x35, 0x5D, 0x58, 0x00, /*shared*/0x06, 0x18 }, - { /*op1*/0x42, 0x54, 0x6F, 0xEB, 0x61, /*op2*/0xD4, 0x02, 0x2E, 0xA9, 0xC8, /*shared*/0x00, 0x18 }, - { /*op1*/0xC2, 0x00, 0x08, 0xB3, 0x99, /*op2*/0xC2, 0x06, 0x2B, 0x58, 0xFA, /*shared*/0x08, 0x19 }, - { /*op1*/0xC4, 0x00, 0x2D, 0xA7, 0x91, /*op2*/0xC2, 0x02, 0x0E, 0xA7, 0xD1, /*shared*/0x00, 0x00 }, - { /*op1*/0xC2, 0x0C, 0x06, 0x06, 0xA9, /*op2*/0xC2, 0x3F, 0x09, 0x86, 0xF9, /*shared*/0x0A, 0x0A }, - { /*op1*/0xC2, 0x2F, 0x6F, 0x79, 0x00, /*op2*/0xC8, 0x0F, 0x5E, 0x98, 0xB9, /*shared*/0x0A, 0x00 }, - { /*op1*/0xC2, 0x30, 0x4F, 0xCA, 0x01, /*op2*/0xC4, 0x0D, 0x0E, 0xB8, 0xFB, /*shared*/0x08, 0x00 }, // 30 - { /*op1*/0xC4, 0x29, 0x4F, 0xCA, 0x03, /*op2*/0xC8, 0x0D, 0x0C, 0xB7, 0xF9, /*shared*/0x00, 0x0B }, - { /*op1*/0xC2, 0x04, 0x58, 0xC9, 0x90, /*op2*/0xC2, 0x94, 0x2C, 0xB9, 0xF0, /*shared*/0x00, 0x20 }, - { /*op1*/0x32, 0x13, 0x2D, 0xD7, 0x58, /*op2*/0xE2, 0x0F, 0x2E, 0xB8, 0xF8, /*shared*/0x0A, 0x00 }, - { /*op1*/0x22, 0x86, 0x0D, 0xD7, 0xA0, /*op2*/0xE4, 0x18, 0x5E, 0xB8, 0xF8, /*shared*/0x06, 0x28 }, - { /*op1*/0xD2, 0x06, 0x9A, 0xD7, 0xA0, /*op2*/0xC2, 0x1F, 0x59, 0xB8, 0xF8, /*shared*/0x04, 0x00 }, - { /*op1*/0xF2, 0x09, 0x4B, 0xD6, 0x90, /*op2*/0xE4, 0x1F, 0x1C, 0xB8, 0xF8, /*shared*/0x0A, 0x28 }, - { /*op1*/0x62, 0x11, 0x0C, 0xE6, 0x78, /*op2*/0xE4, 0x1F, 0x0C, 0xC8, 0xF8, /*shared*/0x0A, 0x00 }, - { /*op1*/0xE2, 0x12, 0x3D, 0xE6, 0x68, /*op2*/0xE4, 0x1F, 0x7D, 0xB8, 0xF8, /*shared*/0x0A, 0x00 }, - { /*op1*/0xE2, 0x13, 0x3D, 0xE6, 0x68, /*op2*/0xE4, 0x1F, 0x5D, 0xB8, 0xF9, /*shared*/0x08, 0x00 }, - { /*op1*/0xA2, 0x40, 0x5D, 0xBA, 0x7B, /*op2*/0xE2, 0x00, 0x8F, 0xD8, 0xF1, /*shared*/0x00, 0x00 }, // 40 - { /*op1*/0xE2, 0x40, 0x3D, 0xDA, 0x73, /*op2*/0xE1, 0x00, 0x7E, 0xD8, 0xF2, /*shared*/0x04, 0x00 }, - { /*op1*/0x62, 0x00, 0x6D, 0xFA, 0xB9, /*op2*/0xE2, 0x00, 0x8F, 0xC8, 0xF1, /*shared*/0x04, 0x00 }, - { /*op1*/0xE1, 0x00, 0x4E, 0xDB, 0xCA, /*op2*/0xE2, 0x00, 0x6F, 0xE9, 0xFA, /*shared*/0x06, 0x00 }, - { /*op1*/0x62, 0xA0, 0x7D, 0xCD, 0x19, /*op2*/0x62, 0x91, 0x9E, 0xE7, 0x80, /*shared*/0x00, 0x00 }, - { /*op1*/0xD2, 0x9B, 0x8A, 0xCA, 0x30, /*op2*/0xD2, 0x0C, 0x0A, 0xBB, 0xF9, /*shared*/0x00, 0x04 }, - { /*op1*/0x12, 0x8F, 0x2A, 0xCC, 0x3C, /*op2*/0x12, 0x90, 0x7D, 0xCB, 0xF8, /*shared*/0x0E, 0x03 }, - { /*op1*/0x00, 0xBC, 0x17, 0xAB, 0x12, /*op2*/0x03, 0xC9, 0x5B, 0xBA, 0xF8, /*shared*/0x06, 0x04 }, - { /*op1*/0xA2, 0x9C, 0x7D, 0xCD, 0x21, /*op2*/0xA4, 0xC7, 0x9E, 0xE7, 0xF8, /*shared*/0x0E, 0x00 }, - { /*op1*/0x62, 0x9E, 0x7D, 0xCD, 0x19, /*op2*/0x62, 0x96, 0x9E, 0xE7, 0x80, /*shared*/0x00, 0x00 }, - { /*op1*/0xE2, 0x40, 0x8F, 0xFA, 0xA0, /*op2*/0xF2, 0x04, 0x7F, 0xFA, 0xF9, /*shared*/0x0A, 0x00 }, // 50 - { /*op1*/0xE4, 0xA0, 0xCE, 0x5B, 0x02, /*op2*/0xE2, 0x32, 0x7F, 0xFB, 0x79, /*shared*/0x04, 0x00 }, - { /*op1*/0xE2, 0x94, 0xAC, 0xC9, 0x21, /*op2*/0xE2, 0x9E, 0x9D, 0xE9, 0xF8, /*shared*/0x0E, 0x00 }, - { /*op1*/0xEA, 0xA0, 0xAC, 0x67, 0x02, /*op2*/0xE2, 0x00, 0x7C, 0x7A, 0xF8, /*shared*/0x06, 0x00 }, - { /*op1*/0xE7, 0x94, 0xAD, 0xB7, 0x03, /*op2*/0xE2, 0x00, 0x7C, 0xBA, 0xF8, /*shared*/0x00, 0x00 }, - { /*op1*/0xC3, 0x3F, 0x4B, 0xE9, 0xFA, /*op2*/0xC1, 0x3F, 0x9B, 0xF9, 0xFB, /*shared*/0x0B, 0x06 }, - { /*op1*/0x22, 0x16, 0x9B, 0xA9, 0x10, /*op2*/0x32, 0x08, 0xAC, 0xD9, 0xFC, /*shared*/0x02, 0x00 }, - { /*op1*/0x22, 0xA1, 0x7C, 0xDC, 0x10, /*op2*/0x34, 0x89, 0xAD, 0xD8, 0xF8, /*shared*/0x0C, 0x00 }, - { /*op1*/0xD2, 0x00, 0x7B, 0x88, 0xA8, /*op2*/0xD2, 0x4C, 0x69, 0xE9, 0xF8, /*shared*/0x06, 0x00 }, - { /*op1*/0xD2, 0x02, 0x85, 0x89, 0xC8, /*op2*/0xD2, 0x94, 0x77, 0x49, 0xF9, /*shared*/0x08, 0x00 }, - { /*op1*/0x22, 0x9F, 0x9D, 0xEA, 0x10, /*op2*/0x22, 0x07, 0x9C, 0xE8, 0xF8, /*shared*/0x06, 0x00 }, // 60 - { /*op1*/0xE2, 0x2A, 0x7F, 0xB8, 0x01, /*op2*/0xE4, 0x00, 0x0D, 0xC5, 0xF8, /*shared*/0x0C, 0x00 }, - { /*op1*/0xE4, 0x28, 0x8E, 0xE8, 0x01, /*op2*/0xF2, 0x00, 0x4D, 0xD6, 0xF9, /*shared*/0x0C, 0x00 }, - { /*op1*/0xB2, 0x8E, 0xBA, 0xDA, 0x3D, /*op2*/0xB2, 0x0F, 0xAE, 0xE9, 0xF8, /*shared*/0x0E, 0x00 }, - { /*op1*/0xB4, 0x26, 0x6E, 0x98, 0x01, /*op2*/0x62, 0x00, 0x7D, 0xC8, 0xF9, /*shared*/0x00, 0x00 }, - { /*op1*/0xD2, 0x10, 0x69, 0x18, 0xCF, /*op2*/0xD4, 0x14, 0x5B, 0x04, 0xFD, /*shared*/0x0A, 0x00 }, - { /*op1*/0xE4, 0x28, 0x7E, 0xF8, 0x01, /*op2*/0xE2, 0x23, 0x8E, 0xE8, 0xF9, /*shared*/0x08, 0x00 }, - { /*op1*/0xB8, 0x28, 0x9E, 0x98, 0x01, /*op2*/0x62, 0x00, 0x3D, 0xC8, 0xF9, /*shared*/0x08, 0x00 }, - { /*op1*/0x62, 0x00, 0x8E, 0xC9, 0x79, /*op2*/0xE6, 0x00, 0x7E, 0xD8, 0xD0, /*shared*/0x0A, 0x00 }, - { /*op1*/0xC2, 0x00, 0x97, 0xF9, 0x90, /*op2*/0xC9, 0x80, 0x69, 0x98, 0xA0, /*shared*/0x00, 0x00 }, - { /*op1*/0x02, 0x04, 0x8A, 0xD8, 0x80, /*op2*/0x0C, 0x12, 0x85, 0xD8, 0xF8, /*shared*/0x0A, 0x00 }, // 70 - { /*op1*/0xA8, 0x8E, 0x9D, 0xD9, 0x40, /*op2*/0xA2, 0x8C, 0x9E, 0xE8, 0xF8, /*shared*/0x00, 0x00 }, - { /*op1*/0xE4, 0x80, 0x6C, 0xD9, 0x60, /*op2*/0xE2, 0x00, 0x8D, 0xC8, 0xF8, /*shared*/0x00, 0x00 }, - { /*op1*/0xA2, 0x6C, 0x79, 0xB9, 0x00, /*op2*/0xA2, 0x07, 0x9D, 0xE8, 0xF8, /*shared*/0x0A, 0x00 }, - { /*op1*/0xE4, 0x00, 0x77, 0xC5, 0xA8, /*op2*/0xE2, 0x00, 0x9E, 0xD7, 0xE0, /*shared*/0x06, 0x00 }, - { /*op1*/0xC2, 0x80, 0x94, 0x09, 0x78, /*op2*/0xC2, 0x00, 0x97, 0x97, 0xF8, /*shared*/0x04, 0x00 }, - { /*op1*/0xC2, 0x00, 0x86, 0x68, 0xA0, /*op2*/0xC2, 0x00, 0x77, 0x47, 0xE0, /*shared*/0x04, 0x00 }, - { /*op1*/0xE2, 0x00, 0x89, 0x40, 0x79, /*op2*/0xE2, 0x00, 0x7E, 0xC9, 0x90, /*shared*/0x06, 0x00 }, - { /*op1*/0xE6, 0x80, 0x9D, 0xB8, 0x51, /*op2*/0xE2, 0x00, 0x9E, 0xF9, 0xA0, /*shared*/0x01, 0x00 }, - { /*op1*/0xE2, 0x80, 0x8E, 0x64, 0xD0, /*op2*/0xE2, 0x28, 0x6F, 0x73, 0xF8, /*shared*/0x01, 0x00 }, - { /*op1*/0xE8, 0x00, 0x7D, 0x99, 0xA8, /*op2*/0xE6, 0x80, 0x80, 0xF8, 0xF8, /*shared*/0x0C, 0x00 }, // 80 - { /*op1*/0xE6, 0x00, 0x9F, 0xB9, 0xD9, /*op2*/0xE1, 0x00, 0x8F, 0xC8, 0xF9, /*shared*/0x02, 0x00 }, - { /*op1*/0xE4, 0x00, 0x09, 0x68, 0x92, /*op2*/0xE2, 0x2B, 0x9E, 0xF3, 0xF8, /*shared*/0x0E, 0x00 }, - { /*op1*/0xC4, 0x00, 0x99, 0xE8, 0x73, /*op2*/0xE2, 0x25, 0x6F, 0x93, 0xF8, /*shared*/0x0E, 0x00 }, - { /*op1*/0xE2, 0x00, 0x4F, 0xDA, 0xC8, /*op2*/0xE2, 0x00, 0x0F, 0xD8, 0xD0, /*shared*/0x06, 0x00 }, - { /*op1*/0xEC, 0x60, 0x9D, 0xC7, 0x00, /*op2*/0xE2, 0x21, 0x7F, 0xC9, 0xF8, /*shared*/0x06, 0x00 }, - { /*op1*/0xE3, 0x00, 0x0F, 0xF7, 0xF9, /*op2*/0xE1, 0x3F, 0x0F, 0xA7, 0x01, /*shared*/0x0D, 0x00 }, - { /*op1*/0xE4, 0xA9, 0x0F, 0xA8, 0x02, /*op2*/0xE2, 0x3C, 0x5F, 0xDA, 0x78, /*shared*/0x0E, 0x00 }, - { /*op1*/0x28, 0x49, 0x0C, 0xCB, 0x40, /*op2*/0xE2, 0x11, 0x5B, 0xD9, 0x48, /*shared*/0x05, 0x00 }, - { /*op1*/0xE1, 0x00, 0xDF, 0x8A, 0xAA, /*op2*/0xE2, 0x5E, 0xCF, 0xBA, 0xFA, /*shared*/0x08, 0x00 }, - { /*op1*/0xE2, 0x00, 0x0B, 0x68, 0xC0, /*op2*/0xE2, 0x01, 0x9E, 0xB8, 0xF8, /*shared*/0x0A, 0x00 }, // 90 - { /*op1*/0xEA, 0x00, 0xAE, 0xAB, 0x91, /*op2*/0xE2, 0x00, 0xAE, 0xBA, 0xD8, /*shared*/0x08, 0x00 }, - { /*op1*/0xEB, 0xC3, 0x9C, 0xCB, 0xA2, /*op2*/0xE2, 0x4C, 0xAE, 0xCA, 0xFA, /*shared*/0x08, 0x00 }, - { /*op1*/0xE2, 0x80, 0x8E, 0xCB, 0xC0, /*op2*/0xE2, 0x90, 0xAE, 0xCA, 0xFB, /*shared*/0x0A, 0x00 }, - { /*op1*/0xE4, 0x00, 0x9E, 0xAA, 0x79, /*op2*/0xE1, 0x43, 0x0F, 0xBA, 0xFA, /*shared*/0x04, 0x00 }, - { /*op1*/0xE3, 0x80, 0xDB, 0xCA, 0x40, /*op2*/0xE2, 0x08, 0xDF, 0xBA, 0xC1, /*shared*/0x04, 0x00 }, - { /*op1*/0xEA, 0x00, 0x68, 0xB8, 0x90, /*op2*/0xE2, 0x0A, 0x8E, 0xB8, 0xF8, /*shared*/0x0C, 0x00 }, - { /*op1*/0x62, 0x00, 0xCE, 0x9A, 0xA8, /*op2*/0xE2, 0x45, 0xCF, 0xCA, 0xA0, /*shared*/0x0A, 0x00 }, - { /*op1*/0xCD, 0x00, 0x0B, 0x00, 0x90, /*op2*/0xC2, 0x58, 0x0C, 0x00, 0xF8, /*shared*/0x0C, 0x1C }, - { /*op1*/0x64, 0x18, 0xBB, 0xAA, 0x10, /*op2*/0x62, 0x4C, 0x5C, 0xDA, 0xF8, /*shared*/0x0E, 0x00 }, - { /*op1*/0xE6, 0x0A, 0x4C, 0xC9, 0x60, /*op2*/0xE2, 0x07, 0x0C, 0x7A, 0xB8, /*shared*/0x08, 0x00 }, // 100 - { /*op1*/0xED, 0x48, 0xDE, 0xD8, 0xB4, /*op2*/0xE1, 0x00, 0xDD, 0xAA, 0xA9, /*shared*/0x00, 0x00 }, - { /*op1*/0xEF, 0x00, 0x8C, 0xAA, 0x67, /*op2*/0x25, 0x00, 0x9D, 0xAB, 0xC1, /*shared*/0x08, 0x00 }, - { /*op1*/0x62, 0x84, 0xBB, 0xAA, 0xCA, /*op2*/0xCF, 0x41, 0xAC, 0xDA, 0xF8, /*shared*/0x08, 0x00 }, - { /*op1*/0xC2, 0x03, 0x6A, 0x5B, 0xA4, /*op2*/0xC2, 0x0D, 0x2A, 0xBB, 0xFC, /*shared*/0x00, 0x12 }, - { /*op1*/0x62, 0x00, 0x04, 0x9A, 0xE8, /*op2*/0xE2, 0x00, 0x0A, 0x48, 0xFD, /*shared*/0x04, 0x10 }, - { /*op1*/0x41, 0x00, 0x0E, 0xEA, 0xA3, /*op2*/0xC2, 0x00, 0x08, 0xCA, 0xF8, /*shared*/0x08, 0x07 }, - { /*op1*/0xC1, 0x40, 0x0C, 0x59, 0xD2, /*op2*/0xC2, 0x80, 0x3C, 0xAB, 0xF8, /*shared*/0x08, 0x0D }, - { /*op1*/0x4B, 0x00, 0x0A, 0xF5, 0xC1, /*op2*/0xC2, 0x19, 0x0C, 0xE9, 0xF8, /*shared*/0x08, 0x07 }, - { /*op1*/0x62, 0x00, 0x7F, 0xD8, 0xA8, /*op2*/0xEA, 0x00, 0x8F, 0xD8, 0xF9, /*shared*/0x0A, 0x00 }, - { /*op1*/0xE1, 0x00, 0x7F, 0xD9, 0xAA, /*op2*/0xE1, 0x00, 0x8F, 0xD8, 0xFA, /*shared*/0x06, 0x00 }, // 110 - { /*op1*/0xE1, 0x00, 0x7F, 0xD9, 0xAA, /*op2*/0xE1, 0x00, 0x8F, 0xD8, 0xFA, /*shared*/0x06, 0x00 }, - { /*op1*/0xCF, 0x40, 0x09, 0xEA, 0xA8, /*op2*/0xC4, 0x00, 0x0C, 0xDB, 0xC8, /*shared*/0x08, 0x02 }, - { /*op1*/0xCF, 0x40, 0x0C, 0xAA, 0xA8, /*op2*/0xC4, 0x00, 0x18, 0xF9, 0xC8, /*shared*/0x0C, 0x02 }, - { /*op1*/0xC5, 0x00, 0x98, 0xD9, 0x92, /*op2*/0xC1, 0x16, 0x6E, 0xF9, 0xE8, /*shared*/0x06, 0x05 }, - { /*op1*/0x03, 0x00, 0x15, 0x00, 0xC8, /*op2*/0x02, 0x00, 0x08, 0x00, 0xF8, /*shared*/0x09, 0x02 }, - { /*op1*/0x02, 0x3F, 0x05, 0x08, 0xF8, /*op2*/0x03, 0x3F, 0x3C, 0xF9, 0xF8, /*shared*/0x0A, 0x06 }, - { /*op1*/0x00, 0x00, 0x36, 0x67, 0xF8, /*op2*/0x01, 0x3F, 0x0E, 0xFA, 0xF8, /*shared*/0x00, 0x05 }, - { /*op1*/0x02, 0x00, 0x36, 0x68, 0xF8, /*op2*/0x01, 0x3F, 0x0E, 0xFA, 0xF8, /*shared*/0x00, 0x05 }, - { /*op1*/0xCB, 0x00, 0xAF, 0x00, 0xFA, /*op2*/0xC0, 0x00, 0xC0, 0x06, 0xFB, /*shared*/0x0E, 0x0F }, - { /*op1*/0x05, 0x0D, 0x80, 0xA6, 0xFB, /*op2*/0x0B, 0x38, 0xA9, 0xD8, 0x00, /*shared*/0x0E, 0x04 }, // 120 - { /*op1*/0x0F, 0x00, 0x90, 0xFA, 0xD0, /*op2*/0x06, 0x00, 0xA7, 0x39, 0xA8, /*shared*/0x0E, 0x06 }, - { /*op1*/0xC9, 0x15, 0xDD, 0xFF, 0xF8, /*op2*/0x00, 0x00, 0xE7, 0xFC, 0xD8, /*shared*/0x0E, 0x38 }, - { /*op1*/0x48, 0x3C, 0x30, 0xF6, 0x03, /*op2*/0x0A, 0x38, 0x97, 0xE8, 0x00, /*shared*/0x0E, 0x04 }, - { /*op1*/0x07, 0x80, 0x0B, 0xC8, 0xC9, /*op2*/0x02, 0x3F, 0x0C, 0xEA, 0xF8, /*shared*/0x0F, 0x05 }, - { /*op1*/0x00, 0x21, 0x66, 0x40, 0x03, /*op2*/0x00, 0x3F, 0x47, 0x00, 0x00, /*shared*/0x0E, 0x02 }, - { /*op1*/0x08, 0x00, 0x0B, 0x3C, 0xF8, /*op2*/0x08, 0x3F, 0x06, 0xF3, 0x00, /*shared*/0x0E, 0x02 }, - { /*op1*/0x00, 0x3F, 0x4C, 0xFB, 0x00, /*op2*/0x00, 0x3F, 0x0A, 0xE9, 0xF8, /*shared*/0x0E, 0x05 }, - { /*op1*/0x11, 0x18, 0x15, 0x00, 0xF8, /*op2*/0x12, 0x00, 0x2B, 0x03, 0xF8, /*shared*/0x06, 0x06 }, - { /*op1*/0x04, 0x3F, 0x42, 0x00, 0x00, /*op2*/0x02, 0x06, 0x1A, 0xE9, 0xE0, /*shared*/0x0E, 0x07 }, - { /*op1*/0x04, 0x18, 0x06, 0x01, 0xB0, /*op2*/0x10, 0x00, 0x07, 0x00, 0x90, /*shared*/0x00, 0x01 }, // 130 - { /*op1*/0x01, 0x3C, 0x0F, 0xFF, 0x80, /*op2*/0x14, 0x06, 0x68, 0xB9, 0xC0, /*shared*/0x0E, 0x02 }, - { /*op1*/0x0E, 0x32, 0x76, 0x03, 0xF8, /*op2*/0x1F, 0x0F, 0x77, 0xD4, 0xFC, /*shared*/0x0E, 0x02 }, - { /*op1*/0x01, 0x3C, 0x0F, 0xFF, 0x80, /*op2*/0x14, 0x06, 0x68, 0xB9, 0xC0, /*shared*/0x0E, 0x02 }, - { /*op1*/0x01, 0x3F, 0x42, 0x85, 0x7A, /*op2*/0x02, 0x0B, 0x0A, 0xD8, 0xF8, /*shared*/0x0A, 0x03 }, - { /*op1*/0xD2, 0x7F, 0x04, 0x0F, 0xFA, /*op2*/0x10, 0xCD, 0x24, 0x07, 0xFB, /*shared*/0x0E, 0x02 }, - { /*op1*/0x01, 0x3F, 0x42, 0x85, 0x7A, /*op2*/0x02, 0x0B, 0x0A, 0xD8, 0xF8, /*shared*/0x0A, 0x03 }, - { /*op1*/0xCF, 0x7F, 0x05, 0x07, 0xFA, /*op2*/0x00, 0x40, 0x25, 0x08, 0xC3, /*shared*/0x0E, 0x0C }, - { /*op1*/0x01, 0x3F, 0x42, 0x85, 0x7A, /*op2*/0x02, 0x0B, 0x0A, 0xD8, 0xF8, /*shared*/0x0A, 0x03 }, - { /*op1*/0xD2, 0x7F, 0x04, 0x0F, 0xFA, /*op2*/0x10, 0xCD, 0x24, 0x07, 0xFB, /*shared*/0x0E, 0x02 }, - { /*op1*/0x01, 0x3F, 0x42, 0x85, 0x7A, /*op2*/0x02, 0x0B, 0x0A, 0xD8, 0xF8, /*shared*/0x0A, 0x03 }, // 140 - { /*op1*/0x01, 0x3F, 0x42, 0x85, 0x7A, /*op2*/0x02, 0x0B, 0x0A, 0xD8, 0xF8, /*shared*/0x0A, 0x03 }, - { /*op1*/0xCF, 0x3F, 0x2B, 0xFB, 0xFA, /*op2*/0xC0, 0x1E, 0x1A, 0xCA, 0xFB, /*shared*/0x0E, 0x10 }, - { /*op1*/0x01, 0x3F, 0x42, 0x85, 0x7A, /*op2*/0x02, 0x0B, 0x0A, 0xD8, 0xF8, /*shared*/0x0A, 0x03 }, - { /*op1*/0xCF, 0x3F, 0x04, 0x57, 0xF8, /*op2*/0xC5, 0x13, 0x06, 0x05, 0xFF, /*shared*/0x04, 0x03 }, - { /*op1*/0xCF, 0x3F, 0x77, 0x09, 0xF8, /*op2*/0xC2, 0xC0, 0x08, 0xB5, 0xEA, /*shared*/0x0E, 0x06 }, - { /*op1*/0xCF, 0x3F, 0x47, 0x06, 0xF8, /*op2*/0xCD, 0x00, 0x07, 0x05, 0xB3, /*shared*/0x04, 0x04 }, - { /*op1*/0xCF, 0x3F, 0x9A, 0x69, 0xF8, /*op2*/0xCF, 0x88, 0x88, 0x48, 0xFA, /*shared*/0x00, 0x02 }, - { /*op1*/0xCF, 0x3F, 0x48, 0x06, 0xF8, /*op2*/0xCF, 0x00, 0x54, 0x04, 0xF9, /*shared*/0x0E, 0x02 }, - { /*op1*/0x03, 0x18, 0x04, 0x09, 0xAC, /*op2*/0x05, 0x07, 0x08, 0x07, 0xF8, /*shared*/0x04, 0x02 }, - { /*op1*/0xCF, 0x3F, 0x25, 0x06, 0xF8, /*op2*/0xCC, 0xD7, 0x05, 0x02, 0xF8, /*shared*/0x0E, 0x10 }, // 150 - { /*op1*/0x01, 0x00, 0x09, 0x08, 0x40, /*op2*/0x13, 0x00, 0x2A, 0x0A, 0xD8, /*shared*/0x00, 0x07 }, - { /*op1*/0x04, 0x00, 0x07, 0x08, 0x40, /*op2*/0x12, 0x00, 0x29, 0x08, 0xE0, /*shared*/0x00, 0x04 }, - { /*op1*/0x04, 0x00, 0x03, 0x09, 0x93, /*op2*/0x02, 0x00, 0x28, 0x09, 0xE8, /*shared*/0x08, 0x07 }, - { /*op1*/0x05, 0x00, 0x03, 0x03, 0x49, /*op2*/0x02, 0x00, 0x58, 0x08, 0xE0, /*shared*/0x08, 0x05 }, - { /*op1*/0x10, 0x00, 0x0C, 0x0C, 0x48, /*op2*/0x02, 0x00, 0x08, 0xB9, 0xE0, /*shared*/0x00, 0x05 }, - { /*op1*/0x15, 0x00, 0x04, 0x87, 0xFB, /*op2*/0x02, 0x40, 0x09, 0x59, 0xD0, /*shared*/0x0E, 0x08 }, - { /*op1*/0x12, 0x26, 0x03, 0x6A, 0xFB, /*op2*/0x02, 0x00, 0x06, 0x5A, 0xC0, /*shared*/0x0E, 0x08 }, - { /*op1*/0xCF, 0x4E, 0x05, 0xA6, 0xA0, /*op2*/0xC6, 0x00, 0x16, 0xF8, 0x60, /*shared*/0x04, 0x02 }, - { /*op1*/0xCF, 0x4E, 0x06, 0xAA, 0xA0, /*op2*/0xC5, 0x00, 0x19, 0xF9, 0x90, /*shared*/0x04, 0x02 }, - { /*op1*/0xC0, 0x00, 0xF0, 0x00, 0x00, /*op2*/0xC0, 0x00, 0xF0, 0x00, 0x00, /*shared*/0x00, 0x0D }, // 160 - { /*op1*/0x0C, 0x18, 0x87, 0xB3, 0xFB, /*op2*/0x1B, 0x10, 0x57, 0x75, 0xF8, /*shared*/0x0E, 0x02 }, - { /*op1*/0x02, 0x11, 0x13, 0x00, 0xC8, /*op2*/0x02, 0x00, 0x05, 0x00, 0x80, /*shared*/0x09, 0x02 }, - { /*op1*/0x03, 0x08, 0x14, 0x00, 0x90, /*op2*/0x02, 0x00, 0x07, 0x00, 0xA8, /*shared*/0x00, 0x02 }, - { /*op1*/0xD2, 0x00, 0x56, 0x30, 0x90, /*op2*/0x06, 0x00, 0x46, 0x56, 0x62, /*shared*/0x09, 0x00 }, - { /*op1*/0x18, 0x00, 0x07, 0xBC, 0x88, /*op2*/0x09, 0x00, 0x0B, 0x6A, 0xBA, /*shared*/0x0B, 0x03 }, // 165 - { /*op1*/0x01, 0x0E, 0x54, 0x00, 0xF9, /*op2*/0x15, 0x03, 0x27, 0x03, 0xF8, /*shared*/0x06, 0x00 }, - }; -}; \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Audio/MidiSynth/opl3.c b/components/darkforces/tfe/TFE_Audio/MidiSynth/opl3.c deleted file mode 100644 index 8bd740ec..00000000 --- a/components/darkforces/tfe/TFE_Audio/MidiSynth/opl3.c +++ /dev/null @@ -1,1539 +0,0 @@ -/* Nuked OPL3 - * Copyright (C) 2013-2020 Nuke.YKT - * - * This file is part of Nuked OPL3. - * - * Nuked OPL3 is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 - * of the License, or (at your option) any later version. - * - * Nuked OPL3 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Nuked OPL3. If not, see . - - * Nuked OPL3 emulator. - * Thanks: - * MAME Development Team(Jarek Burczynski, Tatsuyuki Satoh): - * Feedback and Rhythm part calculation information. - * forums.submarine.org.uk(carbon14, opl3): - * Tremolo and phase generator calculation information. - * OPLx decapsulated(Matthew Gambrell, Olli Niemitalo): - * OPL2 ROMs. - * siliconpr0n.org(John McMaster, digshadow): - * YMF262 and VRC VII decaps and die shots. - * - * version: 1.8 - */ - -#include -#include -#include -#include "opl3.h" - -#if OPL_ENABLE_STEREOEXT && !defined OPL_SIN -#ifndef _USE_MATH_DEFINES -#define _USE_MATH_DEFINES 1 -#endif -#include -/* input: [0, 256), output: [0, 65536] */ -#define OPL_SIN(x) ((int32_t)(sin((x) * M_PI / 512.0) * 65536.0)) -#endif - -/* Quirk: Some FM channels are output one sample later on the left side than the right. */ -#ifndef OPL_QUIRK_CHANNELSAMPLEDELAY -#define OPL_QUIRK_CHANNELSAMPLEDELAY (!OPL_ENABLE_STEREOEXT) -#endif - -#define RSM_FRAC 10 - -/* Channel types */ - -enum { - ch_2op = 0, - ch_4op = 1, - ch_4op2 = 2, - ch_drum = 3 -}; - -/* Envelope key types */ - -enum { - egk_norm = 0x01, - egk_drum = 0x02 -}; - - -#ifdef TFE_ESPBOX -/* The synthesizer reads these tables for every sample: keep them in internal RAM - rather than in flash-mapped rodata. */ -#include "esp_attr.h" -#define TFE_OPL3_TABLE_ATTR DRAM_ATTR -#else -#define TFE_OPL3_TABLE_ATTR -#endif - -/* - logsin table -*/ - -static const uint16_t TFE_OPL3_TABLE_ATTR logsinrom[256] = { - 0x859, 0x6c3, 0x607, 0x58b, 0x52e, 0x4e4, 0x4a6, 0x471, - 0x443, 0x41a, 0x3f5, 0x3d3, 0x3b5, 0x398, 0x37e, 0x365, - 0x34e, 0x339, 0x324, 0x311, 0x2ff, 0x2ed, 0x2dc, 0x2cd, - 0x2bd, 0x2af, 0x2a0, 0x293, 0x286, 0x279, 0x26d, 0x261, - 0x256, 0x24b, 0x240, 0x236, 0x22c, 0x222, 0x218, 0x20f, - 0x206, 0x1fd, 0x1f5, 0x1ec, 0x1e4, 0x1dc, 0x1d4, 0x1cd, - 0x1c5, 0x1be, 0x1b7, 0x1b0, 0x1a9, 0x1a2, 0x19b, 0x195, - 0x18f, 0x188, 0x182, 0x17c, 0x177, 0x171, 0x16b, 0x166, - 0x160, 0x15b, 0x155, 0x150, 0x14b, 0x146, 0x141, 0x13c, - 0x137, 0x133, 0x12e, 0x129, 0x125, 0x121, 0x11c, 0x118, - 0x114, 0x10f, 0x10b, 0x107, 0x103, 0x0ff, 0x0fb, 0x0f8, - 0x0f4, 0x0f0, 0x0ec, 0x0e9, 0x0e5, 0x0e2, 0x0de, 0x0db, - 0x0d7, 0x0d4, 0x0d1, 0x0cd, 0x0ca, 0x0c7, 0x0c4, 0x0c1, - 0x0be, 0x0bb, 0x0b8, 0x0b5, 0x0b2, 0x0af, 0x0ac, 0x0a9, - 0x0a7, 0x0a4, 0x0a1, 0x09f, 0x09c, 0x099, 0x097, 0x094, - 0x092, 0x08f, 0x08d, 0x08a, 0x088, 0x086, 0x083, 0x081, - 0x07f, 0x07d, 0x07a, 0x078, 0x076, 0x074, 0x072, 0x070, - 0x06e, 0x06c, 0x06a, 0x068, 0x066, 0x064, 0x062, 0x060, - 0x05e, 0x05c, 0x05b, 0x059, 0x057, 0x055, 0x053, 0x052, - 0x050, 0x04e, 0x04d, 0x04b, 0x04a, 0x048, 0x046, 0x045, - 0x043, 0x042, 0x040, 0x03f, 0x03e, 0x03c, 0x03b, 0x039, - 0x038, 0x037, 0x035, 0x034, 0x033, 0x031, 0x030, 0x02f, - 0x02e, 0x02d, 0x02b, 0x02a, 0x029, 0x028, 0x027, 0x026, - 0x025, 0x024, 0x023, 0x022, 0x021, 0x020, 0x01f, 0x01e, - 0x01d, 0x01c, 0x01b, 0x01a, 0x019, 0x018, 0x017, 0x017, - 0x016, 0x015, 0x014, 0x014, 0x013, 0x012, 0x011, 0x011, - 0x010, 0x00f, 0x00f, 0x00e, 0x00d, 0x00d, 0x00c, 0x00c, - 0x00b, 0x00a, 0x00a, 0x009, 0x009, 0x008, 0x008, 0x007, - 0x007, 0x007, 0x006, 0x006, 0x005, 0x005, 0x005, 0x004, - 0x004, 0x004, 0x003, 0x003, 0x003, 0x002, 0x002, 0x002, - 0x002, 0x001, 0x001, 0x001, 0x001, 0x001, 0x001, 0x001, - 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000 -}; - -/* - exp table -*/ - -static const uint16_t TFE_OPL3_TABLE_ATTR exprom[256] = { - 0x7fa, 0x7f5, 0x7ef, 0x7ea, 0x7e4, 0x7df, 0x7da, 0x7d4, - 0x7cf, 0x7c9, 0x7c4, 0x7bf, 0x7b9, 0x7b4, 0x7ae, 0x7a9, - 0x7a4, 0x79f, 0x799, 0x794, 0x78f, 0x78a, 0x784, 0x77f, - 0x77a, 0x775, 0x770, 0x76a, 0x765, 0x760, 0x75b, 0x756, - 0x751, 0x74c, 0x747, 0x742, 0x73d, 0x738, 0x733, 0x72e, - 0x729, 0x724, 0x71f, 0x71a, 0x715, 0x710, 0x70b, 0x706, - 0x702, 0x6fd, 0x6f8, 0x6f3, 0x6ee, 0x6e9, 0x6e5, 0x6e0, - 0x6db, 0x6d6, 0x6d2, 0x6cd, 0x6c8, 0x6c4, 0x6bf, 0x6ba, - 0x6b5, 0x6b1, 0x6ac, 0x6a8, 0x6a3, 0x69e, 0x69a, 0x695, - 0x691, 0x68c, 0x688, 0x683, 0x67f, 0x67a, 0x676, 0x671, - 0x66d, 0x668, 0x664, 0x65f, 0x65b, 0x657, 0x652, 0x64e, - 0x649, 0x645, 0x641, 0x63c, 0x638, 0x634, 0x630, 0x62b, - 0x627, 0x623, 0x61e, 0x61a, 0x616, 0x612, 0x60e, 0x609, - 0x605, 0x601, 0x5fd, 0x5f9, 0x5f5, 0x5f0, 0x5ec, 0x5e8, - 0x5e4, 0x5e0, 0x5dc, 0x5d8, 0x5d4, 0x5d0, 0x5cc, 0x5c8, - 0x5c4, 0x5c0, 0x5bc, 0x5b8, 0x5b4, 0x5b0, 0x5ac, 0x5a8, - 0x5a4, 0x5a0, 0x59c, 0x599, 0x595, 0x591, 0x58d, 0x589, - 0x585, 0x581, 0x57e, 0x57a, 0x576, 0x572, 0x56f, 0x56b, - 0x567, 0x563, 0x560, 0x55c, 0x558, 0x554, 0x551, 0x54d, - 0x549, 0x546, 0x542, 0x53e, 0x53b, 0x537, 0x534, 0x530, - 0x52c, 0x529, 0x525, 0x522, 0x51e, 0x51b, 0x517, 0x514, - 0x510, 0x50c, 0x509, 0x506, 0x502, 0x4ff, 0x4fb, 0x4f8, - 0x4f4, 0x4f1, 0x4ed, 0x4ea, 0x4e7, 0x4e3, 0x4e0, 0x4dc, - 0x4d9, 0x4d6, 0x4d2, 0x4cf, 0x4cc, 0x4c8, 0x4c5, 0x4c2, - 0x4be, 0x4bb, 0x4b8, 0x4b5, 0x4b1, 0x4ae, 0x4ab, 0x4a8, - 0x4a4, 0x4a1, 0x49e, 0x49b, 0x498, 0x494, 0x491, 0x48e, - 0x48b, 0x488, 0x485, 0x482, 0x47e, 0x47b, 0x478, 0x475, - 0x472, 0x46f, 0x46c, 0x469, 0x466, 0x463, 0x460, 0x45d, - 0x45a, 0x457, 0x454, 0x451, 0x44e, 0x44b, 0x448, 0x445, - 0x442, 0x43f, 0x43c, 0x439, 0x436, 0x433, 0x430, 0x42d, - 0x42a, 0x428, 0x425, 0x422, 0x41f, 0x41c, 0x419, 0x416, - 0x414, 0x411, 0x40e, 0x40b, 0x408, 0x406, 0x403, 0x400 -}; - -/* - freq mult table multiplied by 2 - - 1/2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 12, 12, 15, 15 -*/ - -static const uint8_t TFE_OPL3_TABLE_ATTR mt[16] = { - 1, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 20, 24, 24, 30, 30 -}; - -/* - ksl table -*/ - -static const uint8_t TFE_OPL3_TABLE_ATTR kslrom[16] = { - 0, 32, 40, 45, 48, 51, 53, 55, 56, 58, 59, 60, 61, 62, 63, 64 -}; - -static const uint8_t TFE_OPL3_TABLE_ATTR kslshift[4] = { - 8, 1, 2, 0 -}; - -/* - envelope generator constants -*/ - -static const uint8_t TFE_OPL3_TABLE_ATTR eg_incstep[4][4] = { - { 0, 0, 0, 0 }, - { 1, 0, 0, 0 }, - { 1, 0, 1, 0 }, - { 1, 1, 1, 0 } -}; - -/* - address decoding -*/ - -static const int8_t TFE_OPL3_TABLE_ATTR ad_slot[0x20] = { - 0, 1, 2, 3, 4, 5, -1, -1, 6, 7, 8, 9, 10, 11, -1, -1, - 12, 13, 14, 15, 16, 17, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 -}; - -static const uint8_t TFE_OPL3_TABLE_ATTR ch_slot[18] = { - 0, 1, 2, 6, 7, 8, 12, 13, 14, 18, 19, 20, 24, 25, 26, 30, 31, 32 -}; - -#if OPL_ENABLE_STEREOEXT -/* - stereo extension panning table -*/ - -static int32_t panpot_lut[256]; -static uint8_t panpot_lut_build = 0; -#endif - -/* - Envelope generator -*/ - -typedef int16_t(*envelope_sinfunc)(uint16_t phase, uint16_t envelope); -typedef void(*envelope_genfunc)(opl3_slot *slott); - -static int16_t OPL3_EnvelopeCalcExp(uint32_t level) -{ - if (level > 0x1fff) - { - level = 0x1fff; - } - return (exprom[level & 0xff] << 1) >> (level >> 8); -} - -static int16_t OPL3_EnvelopeCalcSin0(uint16_t phase, uint16_t envelope) -{ - uint16_t out = 0; - uint16_t neg = 0; - phase &= 0x3ff; - if (phase & 0x200) - { - neg = 0xffff; - } - if (phase & 0x100) - { - out = logsinrom[(phase & 0xff) ^ 0xff]; - } - else - { - out = logsinrom[phase & 0xff]; - } - return OPL3_EnvelopeCalcExp(out + (envelope << 3)) ^ neg; -} - -static int16_t OPL3_EnvelopeCalcSin1(uint16_t phase, uint16_t envelope) -{ - uint16_t out = 0; - phase &= 0x3ff; - if (phase & 0x200) - { - out = 0x1000; - } - else if (phase & 0x100) - { - out = logsinrom[(phase & 0xff) ^ 0xff]; - } - else - { - out = logsinrom[phase & 0xff]; - } - return OPL3_EnvelopeCalcExp(out + (envelope << 3)); -} - -static int16_t OPL3_EnvelopeCalcSin2(uint16_t phase, uint16_t envelope) -{ - uint16_t out = 0; - phase &= 0x3ff; - if (phase & 0x100) - { - out = logsinrom[(phase & 0xff) ^ 0xff]; - } - else - { - out = logsinrom[phase & 0xff]; - } - return OPL3_EnvelopeCalcExp(out + (envelope << 3)); -} - -static int16_t OPL3_EnvelopeCalcSin3(uint16_t phase, uint16_t envelope) -{ - uint16_t out = 0; - phase &= 0x3ff; - if (phase & 0x100) - { - out = 0x1000; - } - else - { - out = logsinrom[phase & 0xff]; - } - return OPL3_EnvelopeCalcExp(out + (envelope << 3)); -} - -static int16_t OPL3_EnvelopeCalcSin4(uint16_t phase, uint16_t envelope) -{ - uint16_t out = 0; - uint16_t neg = 0; - phase &= 0x3ff; - if ((phase & 0x300) == 0x100) - { - neg = 0xffff; - } - if (phase & 0x200) - { - out = 0x1000; - } - else if (phase & 0x80) - { - out = logsinrom[((phase ^ 0xff) << 1) & 0xff]; - } - else - { - out = logsinrom[(phase << 1) & 0xff]; - } - return OPL3_EnvelopeCalcExp(out + (envelope << 3)) ^ neg; -} - -static int16_t OPL3_EnvelopeCalcSin5(uint16_t phase, uint16_t envelope) -{ - uint16_t out = 0; - phase &= 0x3ff; - if (phase & 0x200) - { - out = 0x1000; - } - else if (phase & 0x80) - { - out = logsinrom[((phase ^ 0xff) << 1) & 0xff]; - } - else - { - out = logsinrom[(phase << 1) & 0xff]; - } - return OPL3_EnvelopeCalcExp(out + (envelope << 3)); -} - -static int16_t OPL3_EnvelopeCalcSin6(uint16_t phase, uint16_t envelope) -{ - uint16_t neg = 0; - phase &= 0x3ff; - if (phase & 0x200) - { - neg = 0xffff; - } - return OPL3_EnvelopeCalcExp(envelope << 3) ^ neg; -} - -static int16_t OPL3_EnvelopeCalcSin7(uint16_t phase, uint16_t envelope) -{ - uint16_t out = 0; - uint16_t neg = 0; - phase &= 0x3ff; - if (phase & 0x200) - { - neg = 0xffff; - phase = (phase & 0x1ff) ^ 0x1ff; - } - out = phase << 3; - return OPL3_EnvelopeCalcExp(out + (envelope << 3)) ^ neg; -} - -static const envelope_sinfunc TFE_OPL3_TABLE_ATTR envelope_sin[8] = { - OPL3_EnvelopeCalcSin0, - OPL3_EnvelopeCalcSin1, - OPL3_EnvelopeCalcSin2, - OPL3_EnvelopeCalcSin3, - OPL3_EnvelopeCalcSin4, - OPL3_EnvelopeCalcSin5, - OPL3_EnvelopeCalcSin6, - OPL3_EnvelopeCalcSin7 -}; - -enum envelope_gen_num -{ - envelope_gen_num_attack = 0, - envelope_gen_num_decay = 1, - envelope_gen_num_sustain = 2, - envelope_gen_num_release = 3 -}; - -static void OPL3_EnvelopeUpdateKSL(opl3_slot *slot) -{ - int16_t ksl = (kslrom[slot->channel->f_num >> 6] << 2) - - ((0x08 - slot->channel->block) << 5); - if (ksl < 0) - { - ksl = 0; - } - slot->eg_ksl = (uint8_t)ksl; -} - -static void OPL3_EnvelopeCalc(opl3_slot *slot) -{ - uint8_t nonzero; - uint8_t rate; - uint8_t rate_hi; - uint8_t rate_lo; - uint8_t reg_rate = 0; - uint8_t ks; - uint8_t eg_shift, shift; - uint16_t eg_rout; - int16_t eg_inc; - uint8_t eg_off; - uint8_t reset = 0; - slot->eg_out = slot->eg_rout + (slot->reg_tl << 2) - + (slot->eg_ksl >> kslshift[slot->reg_ksl]) + *slot->trem; - if (slot->key && slot->eg_gen == envelope_gen_num_release) - { - reset = 1; - reg_rate = slot->reg_ar; - } - else - { - switch (slot->eg_gen) - { - case envelope_gen_num_attack: - reg_rate = slot->reg_ar; - break; - case envelope_gen_num_decay: - reg_rate = slot->reg_dr; - break; - case envelope_gen_num_sustain: - if (!slot->reg_type) - { - reg_rate = slot->reg_rr; - } - break; - case envelope_gen_num_release: - reg_rate = slot->reg_rr; - break; - } - } - slot->pg_reset = reset; - ks = slot->channel->ksv >> ((slot->reg_ksr ^ 1) << 1); - nonzero = (reg_rate != 0); - rate = ks + (reg_rate << 2); - rate_hi = rate >> 2; - rate_lo = rate & 0x03; - if (rate_hi & 0x10) - { - rate_hi = 0x0f; - } - eg_shift = rate_hi + slot->chip->eg_add; - shift = 0; - if (nonzero) - { - if (rate_hi < 12) - { - if (slot->chip->eg_state) - { - switch (eg_shift) - { - case 12: - shift = 1; - break; - case 13: - shift = (rate_lo >> 1) & 0x01; - break; - case 14: - shift = rate_lo & 0x01; - break; - default: - break; - } - } - } - else - { - shift = (rate_hi & 0x03) + eg_incstep[rate_lo][slot->chip->timer & 0x03]; - if (shift & 0x04) - { - shift = 0x03; - } - if (!shift) - { - shift = slot->chip->eg_state; - } - } - } - eg_rout = slot->eg_rout; - eg_inc = 0; - eg_off = 0; - /* Instant attack */ - if (reset && rate_hi == 0x0f) - { - eg_rout = 0x00; - } - /* Envelope off */ - if ((slot->eg_rout & 0x1f8) == 0x1f8) - { - eg_off = 1; - } - if (slot->eg_gen != envelope_gen_num_attack && !reset && eg_off) - { - eg_rout = 0x1ff; - } - switch (slot->eg_gen) - { - case envelope_gen_num_attack: - if (!slot->eg_rout) - { - slot->eg_gen = envelope_gen_num_decay; - } - else if (slot->key && shift > 0 && rate_hi != 0x0f) - { - eg_inc = ~slot->eg_rout >> (4 - shift); - } - break; - case envelope_gen_num_decay: - if ((slot->eg_rout >> 4) == slot->reg_sl) - { - slot->eg_gen = envelope_gen_num_sustain; - } - else if (!eg_off && !reset && shift > 0) - { - eg_inc = 1 << (shift - 1); - } - break; - case envelope_gen_num_sustain: - case envelope_gen_num_release: - if (!eg_off && !reset && shift > 0) - { - eg_inc = 1 << (shift - 1); - } - break; - } - slot->eg_rout = (eg_rout + eg_inc) & 0x1ff; - /* Key off */ - if (reset) - { - slot->eg_gen = envelope_gen_num_attack; - } - if (!slot->key) - { - slot->eg_gen = envelope_gen_num_release; - } -} - -static void OPL3_EnvelopeKeyOn(opl3_slot *slot, uint8_t type) -{ - slot->key |= type; -} - -static void OPL3_EnvelopeKeyOff(opl3_slot *slot, uint8_t type) -{ - slot->key &= ~type; -} - -/* - Phase Generator -*/ - -static void OPL3_PhaseGenerate(opl3_slot *slot) -{ - opl3_chip *chip; - uint16_t f_num; - uint32_t basefreq; - uint8_t rm_xor, n_bit; - uint32_t noise; - uint16_t phase; - - chip = slot->chip; - f_num = slot->channel->f_num; - if (slot->reg_vib) - { - int8_t range; - uint8_t vibpos; - - range = (f_num >> 7) & 7; - vibpos = slot->chip->vibpos; - - if (!(vibpos & 3)) - { - range = 0; - } - else if (vibpos & 1) - { - range >>= 1; - } - range >>= slot->chip->vibshift; - - if (vibpos & 4) - { - range = -range; - } - f_num += range; - } - basefreq = (f_num << slot->channel->block) >> 1; - phase = (uint16_t)(slot->pg_phase >> 9); - if (slot->pg_reset) - { - slot->pg_phase = 0; - } - slot->pg_phase += (basefreq * mt[slot->reg_mult]) >> 1; - /* Rhythm mode */ - noise = chip->noise; - slot->pg_phase_out = phase; - if (slot->slot_num == 13) /* hh */ - { - chip->rm_hh_bit2 = (phase >> 2) & 1; - chip->rm_hh_bit3 = (phase >> 3) & 1; - chip->rm_hh_bit7 = (phase >> 7) & 1; - chip->rm_hh_bit8 = (phase >> 8) & 1; - } - if (slot->slot_num == 17 && (chip->rhy & 0x20)) /* tc */ - { - chip->rm_tc_bit3 = (phase >> 3) & 1; - chip->rm_tc_bit5 = (phase >> 5) & 1; - } - if (chip->rhy & 0x20) - { - rm_xor = (chip->rm_hh_bit2 ^ chip->rm_hh_bit7) - | (chip->rm_hh_bit3 ^ chip->rm_tc_bit5) - | (chip->rm_tc_bit3 ^ chip->rm_tc_bit5); - switch (slot->slot_num) - { - case 13: /* hh */ - slot->pg_phase_out = rm_xor << 9; - if (rm_xor ^ (noise & 1)) - { - slot->pg_phase_out |= 0xd0; - } - else - { - slot->pg_phase_out |= 0x34; - } - break; - case 16: /* sd */ - slot->pg_phase_out = (chip->rm_hh_bit8 << 9) - | ((chip->rm_hh_bit8 ^ (noise & 1)) << 8); - break; - case 17: /* tc */ - slot->pg_phase_out = (rm_xor << 9) | 0x80; - break; - default: - break; - } - } - n_bit = ((noise >> 14) ^ noise) & 0x01; - chip->noise = (noise >> 1) | (n_bit << 22); -} - -/* - Slot -*/ - -static void OPL3_SlotWrite20(opl3_slot *slot, uint8_t data) -{ - if ((data >> 7) & 0x01) - { - slot->trem = &slot->chip->tremolo; - } - else - { - slot->trem = (uint8_t*)&slot->chip->zeromod; - } - slot->reg_vib = (data >> 6) & 0x01; - slot->reg_type = (data >> 5) & 0x01; - slot->reg_ksr = (data >> 4) & 0x01; - slot->reg_mult = data & 0x0f; -} - -static void OPL3_SlotWrite40(opl3_slot *slot, uint8_t data) -{ - slot->reg_ksl = (data >> 6) & 0x03; - slot->reg_tl = data & 0x3f; - OPL3_EnvelopeUpdateKSL(slot); -} - -static void OPL3_SlotWrite60(opl3_slot *slot, uint8_t data) -{ - slot->reg_ar = (data >> 4) & 0x0f; - slot->reg_dr = data & 0x0f; -} - -static void OPL3_SlotWrite80(opl3_slot *slot, uint8_t data) -{ - slot->reg_sl = (data >> 4) & 0x0f; - if (slot->reg_sl == 0x0f) - { - slot->reg_sl = 0x1f; - } - slot->reg_rr = data & 0x0f; -} - -static void OPL3_SlotWriteE0(opl3_slot *slot, uint8_t data) -{ - slot->reg_wf = data & 0x07; - if (slot->chip->newm == 0x00) - { - slot->reg_wf &= 0x03; - } -} - -static void OPL3_SlotGenerate(opl3_slot *slot) -{ - slot->out = envelope_sin[slot->reg_wf](slot->pg_phase_out + *slot->mod, slot->eg_out); -} - -static void OPL3_SlotCalcFB(opl3_slot *slot) -{ - if (slot->channel->fb != 0x00) - { - slot->fbmod = (slot->prout + slot->out) >> (0x09 - slot->channel->fb); - } - else - { - slot->fbmod = 0; - } - slot->prout = slot->out; -} - -/* - Channel -*/ - -static void OPL3_ChannelSetupAlg(opl3_channel *channel); - -static void OPL3_ChannelUpdateRhythm(opl3_chip *chip, uint8_t data) -{ - opl3_channel *channel6; - opl3_channel *channel7; - opl3_channel *channel8; - uint8_t chnum; - - chip->rhy = data & 0x3f; - if (chip->rhy & 0x20) - { - channel6 = &chip->channel[6]; - channel7 = &chip->channel[7]; - channel8 = &chip->channel[8]; - channel6->out[0] = &channel6->slots[1]->out; - channel6->out[1] = &channel6->slots[1]->out; - channel6->out[2] = &chip->zeromod; - channel6->out[3] = &chip->zeromod; - channel7->out[0] = &channel7->slots[0]->out; - channel7->out[1] = &channel7->slots[0]->out; - channel7->out[2] = &channel7->slots[1]->out; - channel7->out[3] = &channel7->slots[1]->out; - channel8->out[0] = &channel8->slots[0]->out; - channel8->out[1] = &channel8->slots[0]->out; - channel8->out[2] = &channel8->slots[1]->out; - channel8->out[3] = &channel8->slots[1]->out; - for (chnum = 6; chnum < 9; chnum++) - { - chip->channel[chnum].chtype = ch_drum; - } - OPL3_ChannelSetupAlg(channel6); - OPL3_ChannelSetupAlg(channel7); - OPL3_ChannelSetupAlg(channel8); - /* hh */ - if (chip->rhy & 0x01) - { - OPL3_EnvelopeKeyOn(channel7->slots[0], egk_drum); - } - else - { - OPL3_EnvelopeKeyOff(channel7->slots[0], egk_drum); - } - /* tc */ - if (chip->rhy & 0x02) - { - OPL3_EnvelopeKeyOn(channel8->slots[1], egk_drum); - } - else - { - OPL3_EnvelopeKeyOff(channel8->slots[1], egk_drum); - } - /* tom */ - if (chip->rhy & 0x04) - { - OPL3_EnvelopeKeyOn(channel8->slots[0], egk_drum); - } - else - { - OPL3_EnvelopeKeyOff(channel8->slots[0], egk_drum); - } - /* sd */ - if (chip->rhy & 0x08) - { - OPL3_EnvelopeKeyOn(channel7->slots[1], egk_drum); - } - else - { - OPL3_EnvelopeKeyOff(channel7->slots[1], egk_drum); - } - /* bd */ - if (chip->rhy & 0x10) - { - OPL3_EnvelopeKeyOn(channel6->slots[0], egk_drum); - OPL3_EnvelopeKeyOn(channel6->slots[1], egk_drum); - } - else - { - OPL3_EnvelopeKeyOff(channel6->slots[0], egk_drum); - OPL3_EnvelopeKeyOff(channel6->slots[1], egk_drum); - } - } - else - { - for (chnum = 6; chnum < 9; chnum++) - { - chip->channel[chnum].chtype = ch_2op; - OPL3_ChannelSetupAlg(&chip->channel[chnum]); - OPL3_EnvelopeKeyOff(chip->channel[chnum].slots[0], egk_drum); - OPL3_EnvelopeKeyOff(chip->channel[chnum].slots[1], egk_drum); - } - } -} - -static void OPL3_ChannelWriteA0(opl3_channel *channel, uint8_t data) -{ - if (channel->chip->newm && channel->chtype == ch_4op2) - { - return; - } - channel->f_num = (channel->f_num & 0x300) | data; - channel->ksv = (channel->block << 1) - | ((channel->f_num >> (0x09 - channel->chip->nts)) & 0x01); - OPL3_EnvelopeUpdateKSL(channel->slots[0]); - OPL3_EnvelopeUpdateKSL(channel->slots[1]); - if (channel->chip->newm && channel->chtype == ch_4op) - { - channel->pair->f_num = channel->f_num; - channel->pair->ksv = channel->ksv; - OPL3_EnvelopeUpdateKSL(channel->pair->slots[0]); - OPL3_EnvelopeUpdateKSL(channel->pair->slots[1]); - } -} - -static void OPL3_ChannelWriteB0(opl3_channel *channel, uint8_t data) -{ - if (channel->chip->newm && channel->chtype == ch_4op2) - { - return; - } - channel->f_num = (channel->f_num & 0xff) | ((data & 0x03) << 8); - channel->block = (data >> 2) & 0x07; - channel->ksv = (channel->block << 1) - | ((channel->f_num >> (0x09 - channel->chip->nts)) & 0x01); - OPL3_EnvelopeUpdateKSL(channel->slots[0]); - OPL3_EnvelopeUpdateKSL(channel->slots[1]); - if (channel->chip->newm && channel->chtype == ch_4op) - { - channel->pair->f_num = channel->f_num; - channel->pair->block = channel->block; - channel->pair->ksv = channel->ksv; - OPL3_EnvelopeUpdateKSL(channel->pair->slots[0]); - OPL3_EnvelopeUpdateKSL(channel->pair->slots[1]); - } -} - -static void OPL3_ChannelSetupAlg(opl3_channel *channel) -{ - if (channel->chtype == ch_drum) - { - if (channel->ch_num == 7 || channel->ch_num == 8) - { - channel->slots[0]->mod = &channel->chip->zeromod; - channel->slots[1]->mod = &channel->chip->zeromod; - return; - } - switch (channel->alg & 0x01) - { - case 0x00: - channel->slots[0]->mod = &channel->slots[0]->fbmod; - channel->slots[1]->mod = &channel->slots[0]->out; - break; - case 0x01: - channel->slots[0]->mod = &channel->slots[0]->fbmod; - channel->slots[1]->mod = &channel->chip->zeromod; - break; - } - return; - } - if (channel->alg & 0x08) - { - return; - } - if (channel->alg & 0x04) - { - channel->pair->out[0] = &channel->chip->zeromod; - channel->pair->out[1] = &channel->chip->zeromod; - channel->pair->out[2] = &channel->chip->zeromod; - channel->pair->out[3] = &channel->chip->zeromod; - switch (channel->alg & 0x03) - { - case 0x00: - channel->pair->slots[0]->mod = &channel->pair->slots[0]->fbmod; - channel->pair->slots[1]->mod = &channel->pair->slots[0]->out; - channel->slots[0]->mod = &channel->pair->slots[1]->out; - channel->slots[1]->mod = &channel->slots[0]->out; - channel->out[0] = &channel->slots[1]->out; - channel->out[1] = &channel->chip->zeromod; - channel->out[2] = &channel->chip->zeromod; - channel->out[3] = &channel->chip->zeromod; - break; - case 0x01: - channel->pair->slots[0]->mod = &channel->pair->slots[0]->fbmod; - channel->pair->slots[1]->mod = &channel->pair->slots[0]->out; - channel->slots[0]->mod = &channel->chip->zeromod; - channel->slots[1]->mod = &channel->slots[0]->out; - channel->out[0] = &channel->pair->slots[1]->out; - channel->out[1] = &channel->slots[1]->out; - channel->out[2] = &channel->chip->zeromod; - channel->out[3] = &channel->chip->zeromod; - break; - case 0x02: - channel->pair->slots[0]->mod = &channel->pair->slots[0]->fbmod; - channel->pair->slots[1]->mod = &channel->chip->zeromod; - channel->slots[0]->mod = &channel->pair->slots[1]->out; - channel->slots[1]->mod = &channel->slots[0]->out; - channel->out[0] = &channel->pair->slots[0]->out; - channel->out[1] = &channel->slots[1]->out; - channel->out[2] = &channel->chip->zeromod; - channel->out[3] = &channel->chip->zeromod; - break; - case 0x03: - channel->pair->slots[0]->mod = &channel->pair->slots[0]->fbmod; - channel->pair->slots[1]->mod = &channel->chip->zeromod; - channel->slots[0]->mod = &channel->pair->slots[1]->out; - channel->slots[1]->mod = &channel->chip->zeromod; - channel->out[0] = &channel->pair->slots[0]->out; - channel->out[1] = &channel->slots[0]->out; - channel->out[2] = &channel->slots[1]->out; - channel->out[3] = &channel->chip->zeromod; - break; - } - } - else - { - switch (channel->alg & 0x01) - { - case 0x00: - channel->slots[0]->mod = &channel->slots[0]->fbmod; - channel->slots[1]->mod = &channel->slots[0]->out; - channel->out[0] = &channel->slots[1]->out; - channel->out[1] = &channel->chip->zeromod; - channel->out[2] = &channel->chip->zeromod; - channel->out[3] = &channel->chip->zeromod; - break; - case 0x01: - channel->slots[0]->mod = &channel->slots[0]->fbmod; - channel->slots[1]->mod = &channel->chip->zeromod; - channel->out[0] = &channel->slots[0]->out; - channel->out[1] = &channel->slots[1]->out; - channel->out[2] = &channel->chip->zeromod; - channel->out[3] = &channel->chip->zeromod; - break; - } - } -} - -static void OPL3_ChannelUpdateAlg(opl3_channel *channel) -{ - channel->alg = channel->con; - if (channel->chip->newm) - { - if (channel->chtype == ch_4op) - { - channel->pair->alg = 0x04 | (channel->con << 1) | (channel->pair->con); - channel->alg = 0x08; - OPL3_ChannelSetupAlg(channel->pair); - } - else if (channel->chtype == ch_4op2) - { - channel->alg = 0x04 | (channel->pair->con << 1) | (channel->con); - channel->pair->alg = 0x08; - OPL3_ChannelSetupAlg(channel); - } - else - { - OPL3_ChannelSetupAlg(channel); - } - } - else - { - OPL3_ChannelSetupAlg(channel); - } -} - -static void OPL3_ChannelWriteC0(opl3_channel *channel, uint8_t data) -{ - channel->fb = (data & 0x0e) >> 1; - channel->con = data & 0x01; - OPL3_ChannelUpdateAlg(channel); - if (channel->chip->newm) - { - channel->cha = ((data >> 4) & 0x01) ? ~0 : 0; - channel->chb = ((data >> 5) & 0x01) ? ~0 : 0; - channel->chc = ((data >> 6) & 0x01) ? ~0 : 0; - channel->chd = ((data >> 7) & 0x01) ? ~0 : 0; - } - else - { - channel->cha = channel->chb = (uint16_t)~0; - // TODO: Verify on real chip if DAC2 output is disabled in compat mode - channel->chc = channel->chd = 0; - } -#if OPL_ENABLE_STEREOEXT - if (!channel->chip->stereoext) - { - channel->leftpan = channel->cha << 16; - channel->rightpan = channel->chb << 16; - } -#endif -} - -#if OPL_ENABLE_STEREOEXT -static void OPL3_ChannelWriteD0(opl3_channel* channel, uint8_t data) -{ - if (channel->chip->stereoext) - { - channel->leftpan = panpot_lut[data ^ 0xff]; - channel->rightpan = panpot_lut[data]; - } -} -#endif - -static void OPL3_ChannelKeyOn(opl3_channel *channel) -{ - if (channel->chip->newm) - { - if (channel->chtype == ch_4op) - { - OPL3_EnvelopeKeyOn(channel->slots[0], egk_norm); - OPL3_EnvelopeKeyOn(channel->slots[1], egk_norm); - OPL3_EnvelopeKeyOn(channel->pair->slots[0], egk_norm); - OPL3_EnvelopeKeyOn(channel->pair->slots[1], egk_norm); - } - else if (channel->chtype == ch_2op || channel->chtype == ch_drum) - { - OPL3_EnvelopeKeyOn(channel->slots[0], egk_norm); - OPL3_EnvelopeKeyOn(channel->slots[1], egk_norm); - } - } - else - { - OPL3_EnvelopeKeyOn(channel->slots[0], egk_norm); - OPL3_EnvelopeKeyOn(channel->slots[1], egk_norm); - } -} - -static void OPL3_ChannelKeyOff(opl3_channel *channel) -{ - if (channel->chip->newm) - { - if (channel->chtype == ch_4op) - { - OPL3_EnvelopeKeyOff(channel->slots[0], egk_norm); - OPL3_EnvelopeKeyOff(channel->slots[1], egk_norm); - OPL3_EnvelopeKeyOff(channel->pair->slots[0], egk_norm); - OPL3_EnvelopeKeyOff(channel->pair->slots[1], egk_norm); - } - else if (channel->chtype == ch_2op || channel->chtype == ch_drum) - { - OPL3_EnvelopeKeyOff(channel->slots[0], egk_norm); - OPL3_EnvelopeKeyOff(channel->slots[1], egk_norm); - } - } - else - { - OPL3_EnvelopeKeyOff(channel->slots[0], egk_norm); - OPL3_EnvelopeKeyOff(channel->slots[1], egk_norm); - } -} - -static void OPL3_ChannelSet4Op(opl3_chip *chip, uint8_t data) -{ - uint8_t bit; - uint8_t chnum; - for (bit = 0; bit < 6; bit++) - { - chnum = bit; - if (bit >= 3) - { - chnum += 9 - 3; - } - if ((data >> bit) & 0x01) - { - chip->channel[chnum].chtype = ch_4op; - chip->channel[chnum + 3].chtype = ch_4op2; - OPL3_ChannelUpdateAlg(&chip->channel[chnum]); - } - else - { - chip->channel[chnum].chtype = ch_2op; - chip->channel[chnum + 3].chtype = ch_2op; - OPL3_ChannelUpdateAlg(&chip->channel[chnum]); - OPL3_ChannelUpdateAlg(&chip->channel[chnum+3]); - } - } -} - -static int16_t OPL3_ClipSample(int32_t sample) -{ - if (sample > 32767) - { - sample = 32767; - } - else if (sample < -32768) - { - sample = -32768; - } - return (int16_t)sample; -} - -static void OPL3_ProcessSlot(opl3_slot *slot) -{ - OPL3_SlotCalcFB(slot); - OPL3_EnvelopeCalc(slot); - OPL3_PhaseGenerate(slot); - OPL3_SlotGenerate(slot); -} - -inline void OPL3_Generate4Ch(opl3_chip *chip, int16_t *buf4) -{ - opl3_channel *channel; - opl3_writebuf *writebuf; - int16_t **out; - int32_t mix[2]; - uint8_t ii; - int16_t accm; - uint8_t shift = 0; - - buf4[1] = OPL3_ClipSample(chip->mixbuff[1]); - buf4[3] = OPL3_ClipSample(chip->mixbuff[3]); - -#if OPL_QUIRK_CHANNELSAMPLEDELAY - for (ii = 0; ii < 15; ii++) -#else - for (ii = 0; ii < 36; ii++) -#endif - { - OPL3_ProcessSlot(&chip->slot[ii]); - } - - mix[0] = mix[1] = 0; - for (ii = 0; ii < 18; ii++) - { - channel = &chip->channel[ii]; - out = channel->out; - accm = *out[0] + *out[1] + *out[2] + *out[3]; -#if OPL_ENABLE_STEREOEXT - mix[0] += (int16_t)((accm * channel->leftpan) >> 16); -#else - mix[0] += (int16_t)(accm & channel->cha); - #endif - mix[1] += (int16_t)(accm & channel->chc); - } - chip->mixbuff[0] = mix[0]; - chip->mixbuff[2] = mix[1]; - -#if OPL_QUIRK_CHANNELSAMPLEDELAY - for (ii = 15; ii < 18; ii++) - { - OPL3_ProcessSlot(&chip->slot[ii]); - } -#endif - - buf4[0] = OPL3_ClipSample(chip->mixbuff[0]); - buf4[2] = OPL3_ClipSample(chip->mixbuff[2]); - -#if OPL_QUIRK_CHANNELSAMPLEDELAY - for (ii = 18; ii < 33; ii++) - { - OPL3_ProcessSlot(&chip->slot[ii]); - } -#endif - - mix[0] = mix[1] = 0; - for (ii = 0; ii < 18; ii++) - { - channel = &chip->channel[ii]; - out = channel->out; - accm = *out[0] + *out[1] + *out[2] + *out[3]; -#if OPL_ENABLE_STEREOEXT - mix[0] += (int16_t)((accm * channel->rightpan) >> 16); -#else - mix[0] += (int16_t)(accm & channel->chb); - #endif - mix[1] += (int16_t)(accm & channel->chd); - } - chip->mixbuff[1] = mix[0]; - chip->mixbuff[3] = mix[1]; - -#if OPL_QUIRK_CHANNELSAMPLEDELAY - for (ii = 33; ii < 36; ii++) - { - OPL3_ProcessSlot(&chip->slot[ii]); - } -#endif - - if ((chip->timer & 0x3f) == 0x3f) - { - chip->tremolopos = (chip->tremolopos + 1) % 210; - } - if (chip->tremolopos < 105) - { - chip->tremolo = chip->tremolopos >> chip->tremoloshift; - } - else - { - chip->tremolo = (210 - chip->tremolopos) >> chip->tremoloshift; - } - - if ((chip->timer & 0x3ff) == 0x3ff) - { - chip->vibpos = (chip->vibpos + 1) & 7; - } - - chip->timer++; - - chip->eg_add = 0; - if (chip->eg_timer) - { - while (shift < 36 && ((chip->eg_timer >> shift) & 1) == 0) - { - shift++; - } - if (shift > 12) - { - chip->eg_add = 0; - } - else - { - chip->eg_add = shift + 1; - } - } - - if (chip->eg_timerrem || chip->eg_state) - { - if (chip->eg_timer == 0xfffffffff) - { - chip->eg_timer = 0; - chip->eg_timerrem = 1; - } - else - { - chip->eg_timer++; - chip->eg_timerrem = 0; - } - } - - chip->eg_state ^= 1; - - while ((writebuf = &chip->writebuf[chip->writebuf_cur]), writebuf->time <= chip->writebuf_samplecnt) - { - if (!(writebuf->reg & 0x200)) - { - break; - } - writebuf->reg &= 0x1ff; - OPL3_WriteReg(chip, writebuf->reg, writebuf->data); - chip->writebuf_cur = (chip->writebuf_cur + 1) % OPL_WRITEBUF_SIZE; - } - chip->writebuf_samplecnt++; -} - -void OPL3_Generate(opl3_chip *chip, int16_t *buf) -{ - int16_t samples[4]; - OPL3_Generate4Ch(chip, samples); - buf[0] = samples[0]; - buf[1] = samples[1]; -} - -void OPL3_Generate4ChResampled(opl3_chip *chip, int16_t *buf4) -{ - while (chip->samplecnt >= chip->rateratio) - { - chip->oldsamples[0] = chip->samples[0]; - chip->oldsamples[1] = chip->samples[1]; - chip->oldsamples[2] = chip->samples[2]; - chip->oldsamples[3] = chip->samples[3]; - OPL3_Generate4Ch(chip, chip->samples); - chip->samplecnt -= chip->rateratio; - } - buf4[0] = (int16_t)((chip->oldsamples[0] * (chip->rateratio - chip->samplecnt) - + chip->samples[0] * chip->samplecnt) / chip->rateratio); - buf4[1] = (int16_t)((chip->oldsamples[1] * (chip->rateratio - chip->samplecnt) - + chip->samples[1] * chip->samplecnt) / chip->rateratio); - buf4[2] = (int16_t)((chip->oldsamples[2] * (chip->rateratio - chip->samplecnt) - + chip->samples[2] * chip->samplecnt) / chip->rateratio); - buf4[3] = (int16_t)((chip->oldsamples[3] * (chip->rateratio - chip->samplecnt) - + chip->samples[3] * chip->samplecnt) / chip->rateratio); - chip->samplecnt += 1 << RSM_FRAC; -} - -void OPL3_GenerateResampled(opl3_chip *chip, int16_t *buf) -{ - int16_t samples[4]; - OPL3_Generate4ChResampled(chip, samples); - buf[0] = samples[0]; - buf[1] = samples[1]; -} - -void OPL3_Reset(opl3_chip *chip, uint32_t samplerate) -{ - opl3_slot *slot; - opl3_channel *channel; - uint8_t slotnum; - uint8_t channum; - uint8_t local_ch_slot; - - memset(chip, 0, sizeof(opl3_chip)); - for (slotnum = 0; slotnum < 36; slotnum++) - { - slot = &chip->slot[slotnum]; - slot->chip = chip; - slot->mod = &chip->zeromod; - slot->eg_rout = 0x1ff; - slot->eg_out = 0x1ff; - slot->eg_gen = envelope_gen_num_release; - slot->trem = (uint8_t*)&chip->zeromod; - slot->slot_num = slotnum; - } - for (channum = 0; channum < 18; channum++) - { - channel = &chip->channel[channum]; - local_ch_slot = ch_slot[channum]; - channel->slots[0] = &chip->slot[local_ch_slot]; - channel->slots[1] = &chip->slot[local_ch_slot + 3]; - chip->slot[local_ch_slot].channel = channel; - chip->slot[local_ch_slot + 3].channel = channel; - if ((channum % 9) < 3) - { - channel->pair = &chip->channel[channum + 3]; - } - else if ((channum % 9) < 6) - { - channel->pair = &chip->channel[channum - 3]; - } - channel->chip = chip; - channel->out[0] = &chip->zeromod; - channel->out[1] = &chip->zeromod; - channel->out[2] = &chip->zeromod; - channel->out[3] = &chip->zeromod; - channel->chtype = ch_2op; - channel->cha = 0xffff; - channel->chb = 0xffff; -#if OPL_ENABLE_STEREOEXT - channel->leftpan = 0x10000; - channel->rightpan = 0x10000; -#endif - channel->ch_num = channum; - OPL3_ChannelSetupAlg(channel); - } - chip->noise = 1; - chip->rateratio = (samplerate << RSM_FRAC) / 49716; - chip->tremoloshift = 4; - chip->vibshift = 1; - -#if OPL_ENABLE_STEREOEXT - if (!panpot_lut_build) - { - int32_t i; - for (i = 0; i < 256; i++) - { - panpot_lut[i] = OPL_SIN(i); - } - panpot_lut_build = 1; - } -#endif -} - -void OPL3_WriteReg(opl3_chip *chip, uint16_t reg, uint8_t v) -{ - uint8_t high = (reg >> 8) & 0x01; - uint8_t regm = reg & 0xff; - switch (regm & 0xf0) - { - case 0x00: - if (high) - { - switch (regm & 0x0f) - { - case 0x04: - OPL3_ChannelSet4Op(chip, v); - break; - case 0x05: - chip->newm = v & 0x01; -#if OPL_ENABLE_STEREOEXT - chip->stereoext = (v >> 1) & 0x01; -#endif - break; - } - } - else - { - switch (regm & 0x0f) - { - case 0x08: - chip->nts = (v >> 6) & 0x01; - break; - } - } - break; - case 0x20: - case 0x30: - if (ad_slot[regm & 0x1f] >= 0) - { - OPL3_SlotWrite20(&chip->slot[18 * high + ad_slot[regm & 0x1f]], v); - } - break; - case 0x40: - case 0x50: - if (ad_slot[regm & 0x1f] >= 0) - { - OPL3_SlotWrite40(&chip->slot[18 * high + ad_slot[regm & 0x1f]], v); - } - break; - case 0x60: - case 0x70: - if (ad_slot[regm & 0x1f] >= 0) - { - OPL3_SlotWrite60(&chip->slot[18 * high + ad_slot[regm & 0x1f]], v); - } - break; - case 0x80: - case 0x90: - if (ad_slot[regm & 0x1f] >= 0) - { - OPL3_SlotWrite80(&chip->slot[18 * high + ad_slot[regm & 0x1f]], v); - } - break; - case 0xe0: - case 0xf0: - if (ad_slot[regm & 0x1f] >= 0) - { - OPL3_SlotWriteE0(&chip->slot[18 * high + ad_slot[regm & 0x1f]], v); - } - break; - case 0xa0: - if ((regm & 0x0f) < 9) - { - OPL3_ChannelWriteA0(&chip->channel[9 * high + (regm & 0x0f)], v); - } - break; - case 0xb0: - if (regm == 0xbd && !high) - { - chip->tremoloshift = (((v >> 7) ^ 1) << 1) + 2; - chip->vibshift = ((v >> 6) & 0x01) ^ 1; - OPL3_ChannelUpdateRhythm(chip, v); - } - else if ((regm & 0x0f) < 9) - { - OPL3_ChannelWriteB0(&chip->channel[9 * high + (regm & 0x0f)], v); - if (v & 0x20) - { - OPL3_ChannelKeyOn(&chip->channel[9 * high + (regm & 0x0f)]); - } - else - { - OPL3_ChannelKeyOff(&chip->channel[9 * high + (regm & 0x0f)]); - } - } - break; - case 0xc0: - if ((regm & 0x0f) < 9) - { - OPL3_ChannelWriteC0(&chip->channel[9 * high + (regm & 0x0f)], v); - } - break; -#if OPL_ENABLE_STEREOEXT - case 0xd0: - if ((regm & 0x0f) < 9) - { - OPL3_ChannelWriteD0(&chip->channel[9 * high + (regm & 0x0f)], v); - } - break; -#endif - } -} - -void OPL3_WriteRegBuffered(opl3_chip *chip, uint16_t reg, uint8_t v) -{ - uint64_t time1, time2; - opl3_writebuf *writebuf; - uint32_t writebuf_last; - - writebuf_last = chip->writebuf_last; - writebuf = &chip->writebuf[writebuf_last]; - - if (writebuf->reg & 0x200) - { - OPL3_WriteReg(chip, writebuf->reg & 0x1ff, writebuf->data); - - chip->writebuf_cur = (writebuf_last + 1) % OPL_WRITEBUF_SIZE; - chip->writebuf_samplecnt = writebuf->time; - } - - writebuf->reg = reg | 0x200; - writebuf->data = v; - time1 = chip->writebuf_lasttime + OPL_WRITEBUF_DELAY; - time2 = chip->writebuf_samplecnt; - - if (time1 < time2) - { - time1 = time2; - } - - writebuf->time = time1; - chip->writebuf_lasttime = time1; - chip->writebuf_last = (writebuf_last + 1) % OPL_WRITEBUF_SIZE; -} - -void OPL3_Generate4ChStream(opl3_chip *chip, int16_t *sndptr1, int16_t *sndptr2, uint32_t numsamples) -{ - uint_fast32_t i; - int16_t samples[4]; - - for(i = 0; i < numsamples; i++) - { - OPL3_Generate4ChResampled(chip, samples); - sndptr1[0] = samples[0]; - sndptr1[1] = samples[1]; - sndptr2[0] = samples[2]; - sndptr2[1] = samples[3]; - sndptr1 += 2; - sndptr2 += 2; - } -} - -void OPL3_GenerateStream(opl3_chip *chip, int16_t *sndptr, uint32_t numsamples) -{ - uint_fast32_t i; - - for(i = 0; i < numsamples; i++) - { - OPL3_GenerateResampled(chip, sndptr); - sndptr += 2; - } -} diff --git a/components/darkforces/tfe/TFE_Audio/MidiSynth/opl3.h b/components/darkforces/tfe/TFE_Audio/MidiSynth/opl3.h deleted file mode 100644 index ade8a835..00000000 --- a/components/darkforces/tfe/TFE_Audio/MidiSynth/opl3.h +++ /dev/null @@ -1,174 +0,0 @@ -/* Nuked OPL3 - * Copyright (C) 2013-2020 Nuke.YKT - * - * This file is part of Nuked OPL3. - * - * Nuked OPL3 is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 - * of the License, or (at your option) any later version. - * - * Nuked OPL3 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Nuked OPL3. If not, see . - - * Nuked OPL3 emulator. - * Thanks: - * MAME Development Team(Jarek Burczynski, Tatsuyuki Satoh): - * Feedback and Rhythm part calculation information. - * forums.submarine.org.uk(carbon14, opl3): - * Tremolo and phase generator calculation information. - * OPLx decapsulated(Matthew Gambrell, Olli Niemitalo): - * OPL2 ROMs. - * siliconpr0n.org(John McMaster, digshadow): - * YMF262 and VRC VII decaps and die shots. - * - * version: 1.8 - */ -// Modified for TFE. - -#pragma once - -#ifdef __cplusplus -extern "C" { -#endif - -#include - -#ifndef OPL_ENABLE_STEREOEXT -#define OPL_ENABLE_STEREOEXT 1 -#endif - -#define OPL_WRITEBUF_SIZE 1024 -#define OPL_WRITEBUF_DELAY 2 - -typedef struct _opl3_slot opl3_slot; -typedef struct _opl3_channel opl3_channel; -typedef struct _opl3_chip opl3_chip; - -struct _opl3_slot -{ - opl3_channel *channel; - opl3_chip *chip; - int16_t out; - int16_t fbmod; - int16_t *mod; - int16_t prout; - uint16_t eg_rout; - uint16_t eg_out; - uint8_t eg_inc; - uint8_t eg_gen; - uint8_t eg_rate; - uint8_t eg_ksl; - uint8_t *trem; - uint8_t reg_vib; - uint8_t reg_type; - uint8_t reg_ksr; - uint8_t reg_mult; - uint8_t reg_ksl; - uint8_t reg_tl; - uint8_t reg_ar; - uint8_t reg_dr; - uint8_t reg_sl; - uint8_t reg_rr; - uint8_t reg_wf; - uint8_t key; - uint32_t pg_reset; - uint32_t pg_phase; - uint16_t pg_phase_out; - uint8_t slot_num; -}; - -struct _opl3_channel -{ - opl3_slot *slots[2]; - opl3_channel *pair; - opl3_chip *chip; - int16_t *out[4]; - -#if OPL_ENABLE_STEREOEXT - int32_t leftpan; - int32_t rightpan; -#endif - - uint8_t chtype; - uint16_t f_num; - uint8_t block; - uint8_t fb; - uint8_t con; - uint8_t alg; - uint8_t ksv; - uint16_t cha, chb; - uint16_t chc, chd; - uint8_t ch_num; -}; - -typedef struct _opl3_writebuf -{ - uint64_t time; - uint16_t reg; - uint8_t data; -} opl3_writebuf; - -struct _opl3_chip -{ - opl3_channel channel[18]; - opl3_slot slot[36]; - uint16_t timer; - uint64_t eg_timer; - uint8_t eg_timerrem; - uint8_t eg_state; - uint8_t eg_add; - uint8_t newm; - uint8_t nts; - uint8_t rhy; - uint8_t vibpos; - uint8_t vibshift; - uint8_t tremolo; - uint8_t tremolopos; - uint8_t tremoloshift; - uint32_t noise; - int16_t zeromod; - int32_t mixbuff[4]; - uint8_t rm_hh_bit2; - uint8_t rm_hh_bit3; - uint8_t rm_hh_bit7; - uint8_t rm_hh_bit8; - uint8_t rm_tc_bit3; - uint8_t rm_tc_bit5; - -#if OPL_ENABLE_STEREOEXT - uint8_t stereoext; -#endif - - /* OPL3L */ - int32_t rateratio; - int32_t samplecnt; - int16_t oldsamples[4]; - int16_t samples[4]; - - uint64_t writebuf_samplecnt; - uint32_t writebuf_cur; - uint32_t writebuf_last; - uint64_t writebuf_lasttime; - opl3_writebuf writebuf[OPL_WRITEBUF_SIZE]; -}; - -void OPL3_Generate(opl3_chip *chip, int16_t *buf); -void OPL3_GenerateResampled(opl3_chip *chip, int16_t *buf); -void OPL3_Reset(opl3_chip *chip, uint32_t samplerate); -void OPL3_WriteReg(opl3_chip *chip, uint16_t reg, uint8_t v); -void OPL3_WriteRegBuffered(opl3_chip *chip, uint16_t reg, uint8_t v); -void OPL3_GenerateStream(opl3_chip *chip, int16_t *sndptr, uint32_t numsamples); - -void OPL3_Generate4Ch(opl3_chip *chip, int16_t *buf4); -void OPL3_Generate4ChResampled(opl3_chip *chip, int16_t *buf4); -void OPL3_Generate4ChStream(opl3_chip *chip, int16_t *sndptr1, int16_t *sndptr2, uint32_t numsamples); - -#ifdef __cplusplus -} -#endif diff --git a/components/darkforces/tfe/TFE_Audio/MidiSynth/soundFontDevice.h b/components/darkforces/tfe/TFE_Audio/MidiSynth/soundFontDevice.h deleted file mode 100644 index 4be1ffef..00000000 --- a/components/darkforces/tfe/TFE_Audio/MidiSynth/soundFontDevice.h +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once -#include -#include -#include - -struct tsf; - -namespace TFE_Audio -{ - class SoundFontDevice : public MidiDevice - { - public: - SoundFontDevice() : m_soundFont(nullptr), m_outputId(-1) {} - ~SoundFontDevice() override; - - MidiDeviceType getType() override { return MIDI_TYPE_SF2; } - - void exit() override; - bool hasGlobalVolumeCtrl() override { return true; } - const char* getName() override; - - bool render(MidiSample* buffer, u32 sampleCount) override; - bool canRender() override; - - void message(u8 type, u8 arg1, u8 arg2) override; - void message(const u8* msg, u32 len) override; - void noteAllOff() override; - void setVolume(f32 volume) override; - - u32 getOutputCount() override; - void getOutputName(s32 index, char* buffer, u32 maxLength) override; - bool selectOutput(s32 index) override; - s32 getActiveOutput(void) override; - - private: - bool beginStream(const char* soundFont, s32 sampleRate); - - tsf* m_soundFont; - s32 m_outputId; - FileList m_outputs; - }; -}; \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Audio/MidiSynth/tsf.h b/components/darkforces/tfe/TFE_Audio/MidiSynth/tsf.h deleted file mode 100644 index c94ba0de..00000000 --- a/components/darkforces/tfe/TFE_Audio/MidiSynth/tsf.h +++ /dev/null @@ -1,1898 +0,0 @@ -/* TinySoundFont - v0.9 - SoundFont2 synthesizer - https://github.com/schellingb/TinySoundFont - no warranty implied; use at your own risk - Do this: - #define TSF_IMPLEMENTATION - before you include this file in *one* C or C++ file to create the implementation. - // i.e. it should look like this: - #include ... - #include ... - #define TSF_IMPLEMENTATION - #include "tsf.h" - - [OPTIONAL] #define TSF_NO_STDIO to remove stdio dependency - [OPTIONAL] #define TSF_MALLOC, TSF_REALLOC, and TSF_FREE to avoid stdlib.h - [OPTIONAL] #define TSF_MEMCPY, TSF_MEMSET to avoid string.h - [OPTIONAL] #define TSF_POW, TSF_POWF, TSF_EXPF, TSF_LOG, TSF_TAN, TSF_LOG10, TSF_SQRT to avoid math.h - - NOT YET IMPLEMENTED - - Support for ChorusEffectsSend and ReverbEffectsSend generators - - Better low-pass filter without lowering performance too much - - Support for modulators - - LICENSE (MIT) - - Copyright (C) 2017, 2018 Bernhard Schelling - Based on SFZero, Copyright (C) 2012 Steve Folta (https://github.com/stevefolta/SFZero) - - 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. - -*/ - -#ifndef TSF_INCLUDE_TSF_INL -#define TSF_INCLUDE_TSF_INL - -#ifdef __cplusplus -extern "C" { -# define CPP_DEFAULT0 = 0 -#else -# define CPP_DEFAULT0 -#endif - -//define this if you want the API functions to be static -#ifdef TSF_STATIC -#define TSFDEF static -#else -#define TSFDEF extern -#endif - -// The load functions will return a pointer to a struct tsf which all functions -// thereafter take as the first parameter. -// On error the tsf_load* functions will return NULL most likely due to invalid -// data (or if the file did not exist in tsf_load_filename). -typedef struct tsf tsf; - -#ifndef TSF_NO_STDIO -// Directly load a SoundFont from a .sf2 file path -TSFDEF tsf* tsf_load_filename(const char* filename); -#endif - -// Load a SoundFont from a block of memory -TSFDEF tsf* tsf_load_memory(const void* buffer, int size); - -// Stream structure for the generic loading -struct tsf_stream -{ - // Custom data given to the functions as the first parameter - void* data; - - // Function pointer will be called to read 'size' bytes into ptr (returns number of read bytes) - int (*read)(void* data, void* ptr, unsigned int size); - - // Function pointer will be called to skip ahead over 'count' bytes (returns 1 on success, 0 on error) - int (*skip)(void* data, unsigned int count); -}; - -// Generic SoundFont loading method using the stream structure above -TSFDEF tsf* tsf_load(struct tsf_stream* stream); - -// Copy a tsf instance from an existing one, use tsf_close to close it as well. -// All copied tsf instances and their original instance are linked, and share the underlying soundfont. -// This allows loading a soundfont only once, but using it for multiple independent playbacks. -// (This function isn't thread-safe without locking.) -TSFDEF tsf* tsf_copy(tsf* f); - -// Free the memory related to this tsf instance -TSFDEF void tsf_close(tsf* f); - -// Stop all playing notes immediately and reset all channel parameters -TSFDEF void tsf_reset(tsf* f); - -// Returns the preset index from a bank and preset number, or -1 if it does not exist in the loaded SoundFont -TSFDEF int tsf_get_presetindex(const tsf* f, int bank, int preset_number); - -// Returns the number of presets in the loaded SoundFont -TSFDEF int tsf_get_presetcount(const tsf* f); - -// Returns the name of a preset index >= 0 and < tsf_get_presetcount() -TSFDEF const char* tsf_get_presetname(const tsf* f, int preset_index); - -// Returns the name of a preset by bank and preset number -TSFDEF const char* tsf_bank_get_presetname(const tsf* f, int bank, int preset_number); - -// Supported output modes by the render methods -enum TSFOutputMode -{ - // Two channels with single left/right samples one after another - TSF_STEREO_INTERLEAVED, - // Two channels with all samples for the left channel first then right - TSF_STEREO_UNWEAVED, - // A single channel (stereo instruments are mixed into center) - TSF_MONO, -}; - -// Thread safety: -// -// 1. Rendering / voices: -// -// Your audio output which calls the tsf_render* functions will most likely -// run on a different thread than where the playback tsf_note* functions -// are called. In which case some sort of concurrency control like a -// mutex needs to be used so they are not called at the same time. -// Alternatively, you can pre-allocate a maximum number of voices that can -// play simultaneously by calling tsf_set_max_voices after loading. -// That way memory re-allocation will not happen during tsf_note_on and -// TSF should become mostly thread safe. -// There is a theoretical chance that ending notes would negatively influence -// a voice that is rendering at the time but it is hard to say. -// Also be aware, this has not been tested much. -// -// 2. Channels: -// -// Calls to tsf_channel_set_... functions may allocate new channels -// if no channel with that number was previously used. Make sure to -// create all channels at the beginning as required if you call tsf_render* -// from a different thread. - -// Setup the parameters for the voice render methods -// outputmode: if mono or stereo and how stereo channel data is ordered -// samplerate: the number of samples per second (output frequency) -// global_gain_db: volume gain in decibels (>0 means higher, <0 means lower) -TSFDEF void tsf_set_output(tsf* f, enum TSFOutputMode outputmode, int samplerate, float global_gain_db CPP_DEFAULT0); - -// Set the global gain as a volume factor -// global_gain: the desired volume where 1.0 is 100% -TSFDEF void tsf_set_volume(tsf* f, float global_gain); - -// Set the maximum number of voices to play simultaneously -// Depending on the soundfond, one note can cause many new voices to be started, -// so don't keep this number too low or otherwise sounds may not play. -// max_voices: maximum number to pre-allocate and set the limit to -// (tsf_set_max_voices returns 0 if allocation failed, otherwise 1) -TSFDEF int tsf_set_max_voices(tsf* f, int max_voices); - -// Start playing a note -// preset_index: preset index >= 0 and < tsf_get_presetcount() -// key: note value between 0 and 127 (60 being middle C) -// vel: velocity as a float between 0.0 (equal to note off) and 1.0 (full) -// bank: instrument bank number (alternative to preset_index) -// preset_number: preset number (alternative to preset_index) -// (tsf_note_on returns 0 if the allocation of a new voice failed, otherwise 1) -// (tsf_bank_note_on returns 0 if preset does not exist or allocation failed, otherwise 1) -TSFDEF int tsf_note_on(tsf* f, int preset_index, int key, float vel); -TSFDEF int tsf_bank_note_on(tsf* f, int bank, int preset_number, int key, float vel); - -// Stop playing a note -// (bank_note_off returns 0 if preset does not exist, otherwise 1) -TSFDEF void tsf_note_off(tsf* f, int preset_index, int key); -TSFDEF int tsf_bank_note_off(tsf* f, int bank, int preset_number, int key); - -// Stop playing all notes (end with sustain and release) -TSFDEF void tsf_note_off_all(tsf* f); - -// Returns the number of active voices -TSFDEF int tsf_active_voice_count(tsf* f); - -// Render output samples into a buffer -// You can either render as signed 16-bit values (tsf_render_short) or -// as 32-bit float values (tsf_render_float) -// buffer: target buffer of size samples * output_channels * sizeof(type) -// samples: number of samples to render -// flag_mixing: if 0 clear the buffer first, otherwise mix into existing data -TSFDEF void tsf_render_short(tsf* f, short* buffer, int samples, int flag_mixing CPP_DEFAULT0); -TSFDEF void tsf_render_float(tsf* f, float* buffer, int samples, int flag_mixing CPP_DEFAULT0); - -// Higher level channel based functions, set up channel parameters -// channel: channel number -// preset_index: preset index >= 0 and < tsf_get_presetcount() -// preset_number: preset number (alternative to preset_index) -// flag_mididrums: 0 for normal channels, otherwise apply MIDI drum channel rules -// bank: instrument bank number (alternative to preset_index) -// pan: stereo panning value from 0.0 (left) to 1.0 (right) (default 0.5 center) -// volume: linear volume scale factor (default 1.0 full) -// pitch_wheel: pitch wheel position 0 to 16383 (default 8192 unpitched) -// pitch_range: range of the pitch wheel in semitones (default 2.0, total +/- 2 semitones) -// tuning: tuning of all playing voices in semitones (default 0.0, standard (A440) tuning) -// (tsf_set_preset_number and set_bank_preset return 0 if preset does not exist, otherwise 1) -// (tsf_channel_set_... return 0 if a new channel needed allocation and that failed, otherwise 1) -TSFDEF int tsf_channel_set_presetindex(tsf* f, int channel, int preset_index); -TSFDEF int tsf_channel_set_presetnumber(tsf* f, int channel, int preset_number, int flag_mididrums CPP_DEFAULT0); -TSFDEF int tsf_channel_set_bank(tsf* f, int channel, int bank); -TSFDEF int tsf_channel_set_bank_preset(tsf* f, int channel, int bank, int preset_number); -TSFDEF int tsf_channel_set_pan(tsf* f, int channel, float pan); -TSFDEF int tsf_channel_set_volume(tsf* f, int channel, float volume); -TSFDEF int tsf_channel_set_pitchwheel(tsf* f, int channel, int pitch_wheel); -TSFDEF int tsf_channel_set_pitchrange(tsf* f, int channel, float pitch_range); -TSFDEF int tsf_channel_set_tuning(tsf* f, int channel, float tuning); - -// Start or stop playing notes on a channel (needs channel preset to be set) -// channel: channel number -// key: note value between 0 and 127 (60 being middle C) -// vel: velocity as a float between 0.0 (equal to note off) and 1.0 (full) -// (tsf_channel_note_on returns 0 on allocation failure of new voice, otherwise 1) -TSFDEF int tsf_channel_note_on(tsf* f, int channel, int key, float vel); -TSFDEF void tsf_channel_note_off(tsf* f, int channel, int key); -TSFDEF void tsf_channel_note_off_all(tsf* f, int channel); //end with sustain and release -TSFDEF void tsf_channel_sounds_off_all(tsf* f, int channel); //end immediately - -// Apply a MIDI control change to the channel (not all controllers are supported!) -// (tsf_channel_midi_control returns 0 on allocation failure of new channel, otherwise 1) -TSFDEF int tsf_channel_midi_control(tsf* f, int channel, int controller, int control_value); - -// Get current values set on the channels -TSFDEF int tsf_channel_get_preset_index(tsf* f, int channel); -TSFDEF int tsf_channel_get_preset_bank(tsf* f, int channel); -TSFDEF int tsf_channel_get_preset_number(tsf* f, int channel); -TSFDEF float tsf_channel_get_pan(tsf* f, int channel); -TSFDEF float tsf_channel_get_volume(tsf* f, int channel); -TSFDEF int tsf_channel_get_pitchwheel(tsf* f, int channel); -TSFDEF float tsf_channel_get_pitchrange(tsf* f, int channel); -TSFDEF float tsf_channel_get_tuning(tsf* f, int channel); - -#ifdef __cplusplus -# undef CPP_DEFAULT0 -} -#endif - -// end header -// --------------------------------------------------------------------------------------------------------- -#endif //TSF_INCLUDE_TSF_INL - -#ifdef TSF_IMPLEMENTATION -#undef TSF_IMPLEMENTATION - -// The lower this block size is the more accurate the effects are. -// Increasing the value significantly lowers the CPU usage of the voice rendering. -// If LFO affects the low-pass filter it can be hearable even as low as 8. -#ifndef TSF_RENDER_EFFECTSAMPLEBLOCK -#define TSF_RENDER_EFFECTSAMPLEBLOCK 64 -#endif - -// When using tsf_render_short, to do the conversion a buffer of a fixed size is -// allocated on the stack. On low memory platforms this could be made smaller. -// Increasing this above 512 should not have a significant impact on performance. -// The value should be a multiple of TSF_RENDER_EFFECTSAMPLEBLOCK. -#ifndef TSF_RENDER_SHORTBUFFERBLOCK -#define TSF_RENDER_SHORTBUFFERBLOCK 512 -#endif - -// Grace release time for quick voice off (avoid clicking noise) -#define TSF_FASTRELEASETIME 0.01f - -#if !defined(TSF_MALLOC) || !defined(TSF_FREE) || !defined(TSF_REALLOC) -# include -# define TSF_MALLOC malloc -# define TSF_FREE free -# define TSF_REALLOC realloc -#endif - -#if !defined(TSF_MEMCPY) || !defined(TSF_MEMSET) -# include -# define TSF_MEMCPY memcpy -# define TSF_MEMSET memset -#endif - -#if !defined(TSF_POW) || !defined(TSF_POWF) || !defined(TSF_EXPF) || !defined(TSF_LOG) || !defined(TSF_TAN) || !defined(TSF_LOG10) || !defined(TSF_SQRT) -# include -# if !defined(__cplusplus) && !defined(NAN) && !defined(powf) && !defined(expf) && !defined(sqrtf) -# define powf (float)pow // deal with old math.h -# define expf (float)exp // files that come without -# define sqrtf (float)sqrt // powf, expf and sqrtf -# endif -# define TSF_POW pow -# define TSF_POWF powf -# define TSF_EXPF expf -# define TSF_LOG log -# define TSF_TAN tan -# define TSF_LOG10 log10 -# define TSF_SQRTF sqrtf -#endif - -#ifndef TSF_NO_STDIO -# include -#endif - -#define TSF_TRUE 1 -#define TSF_FALSE 0 -#define TSF_BOOL char -#define TSF_PI 3.14159265358979323846264338327950288 -#define TSF_NULL 0 - -#ifdef __cplusplus -extern "C" { -#endif - -typedef char tsf_fourcc[4]; -typedef signed char tsf_s8; -typedef unsigned char tsf_u8; -typedef unsigned short tsf_u16; -typedef signed short tsf_s16; -typedef unsigned int tsf_u32; -typedef char tsf_char20[20]; - -#define TSF_FourCCEquals(value1, value2) (value1[0] == value2[0] && value1[1] == value2[1] && value1[2] == value2[2] && value1[3] == value2[3]) - -struct tsf -{ - struct tsf_preset* presets; - float* fontSamples; - struct tsf_voice* voices; - struct tsf_channels* channels; - - int presetNum; - int voiceNum; - int maxVoiceNum; - unsigned int voicePlayIndex; - - enum TSFOutputMode outputmode; - float outSampleRate; - float globalGainDB; - int* refCount; -}; - -#ifndef TSF_NO_STDIO -static int tsf_stream_stdio_read(FILE* f, void* ptr, unsigned int size) { return (int)fread(ptr, 1, size, f); } -static int tsf_stream_stdio_skip(FILE* f, unsigned int count) { return !fseek(f, count, SEEK_CUR); } -TSFDEF tsf* tsf_load_filename(const char* filename) -{ - tsf* res; - struct tsf_stream stream = { TSF_NULL, (int(*)(void*,void*,unsigned int))&tsf_stream_stdio_read, (int(*)(void*,unsigned int))&tsf_stream_stdio_skip }; - #if __STDC_WANT_SECURE_LIB__ - FILE* f = TSF_NULL; fopen_s(&f, filename, "rb"); - #else - FILE* f = fopen(filename, "rb"); - #endif - if (!f) - { - //if (e) *e = TSF_FILENOTFOUND; - return TSF_NULL; - } - stream.data = f; - res = tsf_load(&stream); - fclose(f); - return res; -} -#endif - -struct tsf_stream_memory { const char* buffer; unsigned int total, pos; }; -static int tsf_stream_memory_read(struct tsf_stream_memory* m, void* ptr, unsigned int size) { if (size > m->total - m->pos) size = m->total - m->pos; TSF_MEMCPY(ptr, m->buffer+m->pos, size); m->pos += size; return size; } -static int tsf_stream_memory_skip(struct tsf_stream_memory* m, unsigned int count) { if (m->pos + count > m->total) return 0; m->pos += count; return 1; } -TSFDEF tsf* tsf_load_memory(const void* buffer, int size) -{ - struct tsf_stream stream = { TSF_NULL, (int(*)(void*,void*,unsigned int))&tsf_stream_memory_read, (int(*)(void*,unsigned int))&tsf_stream_memory_skip }; - struct tsf_stream_memory f = { 0, 0, 0 }; - f.buffer = (const char*)buffer; - f.total = size; - stream.data = &f; - return tsf_load(&stream); -} - -enum { TSF_LOOPMODE_NONE, TSF_LOOPMODE_CONTINUOUS, TSF_LOOPMODE_SUSTAIN }; - -enum { TSF_SEGMENT_NONE, TSF_SEGMENT_DELAY, TSF_SEGMENT_ATTACK, TSF_SEGMENT_HOLD, TSF_SEGMENT_DECAY, TSF_SEGMENT_SUSTAIN, TSF_SEGMENT_RELEASE, TSF_SEGMENT_DONE }; - -struct tsf_hydra -{ - struct tsf_hydra_phdr *phdrs; struct tsf_hydra_pbag *pbags; struct tsf_hydra_pmod *pmods; - struct tsf_hydra_pgen *pgens; struct tsf_hydra_inst *insts; struct tsf_hydra_ibag *ibags; - struct tsf_hydra_imod *imods; struct tsf_hydra_igen *igens; struct tsf_hydra_shdr *shdrs; - int phdrNum, pbagNum, pmodNum, pgenNum, instNum, ibagNum, imodNum, igenNum, shdrNum; -}; - -union tsf_hydra_genamount { struct { tsf_u8 lo, hi; } range; tsf_s16 shortAmount; tsf_u16 wordAmount; }; -struct tsf_hydra_phdr { tsf_char20 presetName; tsf_u16 preset, bank, presetBagNdx; tsf_u32 library, genre, morphology; }; -struct tsf_hydra_pbag { tsf_u16 genNdx, modNdx; }; -struct tsf_hydra_pmod { tsf_u16 modSrcOper, modDestOper; tsf_s16 modAmount; tsf_u16 modAmtSrcOper, modTransOper; }; -struct tsf_hydra_pgen { tsf_u16 genOper; union tsf_hydra_genamount genAmount; }; -struct tsf_hydra_inst { tsf_char20 instName; tsf_u16 instBagNdx; }; -struct tsf_hydra_ibag { tsf_u16 instGenNdx, instModNdx; }; -struct tsf_hydra_imod { tsf_u16 modSrcOper, modDestOper; tsf_s16 modAmount; tsf_u16 modAmtSrcOper, modTransOper; }; -struct tsf_hydra_igen { tsf_u16 genOper; union tsf_hydra_genamount genAmount; }; -struct tsf_hydra_shdr { tsf_char20 sampleName; tsf_u32 start, end, startLoop, endLoop, sampleRate; tsf_u8 originalPitch; tsf_s8 pitchCorrection; tsf_u16 sampleLink, sampleType; }; - -#define TSFR(FIELD) stream->read(stream->data, &i->FIELD, sizeof(i->FIELD)); -static void tsf_hydra_read_phdr(struct tsf_hydra_phdr* i, struct tsf_stream* stream) { TSFR(presetName) TSFR(preset) TSFR(bank) TSFR(presetBagNdx) TSFR(library) TSFR(genre) TSFR(morphology) } -static void tsf_hydra_read_pbag(struct tsf_hydra_pbag* i, struct tsf_stream* stream) { TSFR(genNdx) TSFR(modNdx) } -static void tsf_hydra_read_pmod(struct tsf_hydra_pmod* i, struct tsf_stream* stream) { TSFR(modSrcOper) TSFR(modDestOper) TSFR(modAmount) TSFR(modAmtSrcOper) TSFR(modTransOper) } -static void tsf_hydra_read_pgen(struct tsf_hydra_pgen* i, struct tsf_stream* stream) { TSFR(genOper) TSFR(genAmount) } -static void tsf_hydra_read_inst(struct tsf_hydra_inst* i, struct tsf_stream* stream) { TSFR(instName) TSFR(instBagNdx) } -static void tsf_hydra_read_ibag(struct tsf_hydra_ibag* i, struct tsf_stream* stream) { TSFR(instGenNdx) TSFR(instModNdx) } -static void tsf_hydra_read_imod(struct tsf_hydra_imod* i, struct tsf_stream* stream) { TSFR(modSrcOper) TSFR(modDestOper) TSFR(modAmount) TSFR(modAmtSrcOper) TSFR(modTransOper) } -static void tsf_hydra_read_igen(struct tsf_hydra_igen* i, struct tsf_stream* stream) { TSFR(genOper) TSFR(genAmount) } -static void tsf_hydra_read_shdr(struct tsf_hydra_shdr* i, struct tsf_stream* stream) { TSFR(sampleName) TSFR(start) TSFR(end) TSFR(startLoop) TSFR(endLoop) TSFR(sampleRate) TSFR(originalPitch) TSFR(pitchCorrection) TSFR(sampleLink) TSFR(sampleType) } -#undef TSFR - -struct tsf_riffchunk { tsf_fourcc id; tsf_u32 size; }; -struct tsf_envelope { float delay, attack, hold, decay, sustain, release, keynumToHold, keynumToDecay; }; -struct tsf_voice_envelope { float level, slope; int samplesUntilNextSegment; short segment, midiVelocity; struct tsf_envelope parameters; TSF_BOOL segmentIsExponential, isAmpEnv; }; -struct tsf_voice_lowpass { double QInv, a0, a1, b1, b2, z1, z2; TSF_BOOL active; }; -struct tsf_voice_lfo { int samplesUntil; float level, delta; }; - -struct tsf_region -{ - int loop_mode; - unsigned int sample_rate; - unsigned char lokey, hikey, lovel, hivel; - unsigned int group, offset, end, loop_start, loop_end; - int transpose, tune, pitch_keycenter, pitch_keytrack; - float attenuation, pan; - struct tsf_envelope ampenv, modenv; - int initialFilterQ, initialFilterFc; - int modEnvToPitch, modEnvToFilterFc, modLfoToFilterFc, modLfoToVolume; - float delayModLFO; - int freqModLFO, modLfoToPitch; - float delayVibLFO; - int freqVibLFO, vibLfoToPitch; -}; - -struct tsf_preset -{ - tsf_char20 presetName; - tsf_u16 preset, bank; - struct tsf_region* regions; - int regionNum; -}; - -struct tsf_voice -{ - int playingPreset, playingKey, playingChannel; - struct tsf_region* region; - double pitchInputTimecents, pitchOutputFactor; - double sourceSamplePosition; - float noteGainDB, panFactorLeft, panFactorRight; - unsigned int playIndex, loopStart, loopEnd; - struct tsf_voice_envelope ampenv, modenv; - struct tsf_voice_lowpass lowpass; - struct tsf_voice_lfo modlfo, viblfo; -}; - -struct tsf_channel -{ - unsigned short presetIndex, bank, pitchWheel, midiPan, midiVolume, midiExpression, midiRPN, midiData; - float panOffset, gainDB, pitchRange, tuning; -}; - -struct tsf_channels -{ - void (*setupVoice)(tsf* f, struct tsf_voice* voice); - int channelNum, activeChannel; - struct tsf_channel channels[1]; -}; - -static double tsf_timecents2Secsd(double timecents) { return TSF_POW(2.0, timecents / 1200.0); } -static float tsf_timecents2Secsf(float timecents) { return TSF_POWF(2.0f, timecents / 1200.0f); } -static float tsf_cents2Hertz(float cents) { return 8.176f * TSF_POWF(2.0f, cents / 1200.0f); } -static float tsf_decibelsToGain(float db) { return (db > -100.f ? TSF_POWF(10.0f, db * 0.05f) : 0); } -static float tsf_gainToDecibels(float gain) { return (gain <= .00001f ? -100.f : (float)(20.0 * TSF_LOG10(gain))); } - -static TSF_BOOL tsf_riffchunk_read(struct tsf_riffchunk* parent, struct tsf_riffchunk* chunk, struct tsf_stream* stream) -{ - TSF_BOOL IsRiff, IsList; - if (parent && sizeof(tsf_fourcc) + sizeof(tsf_u32) > parent->size) return TSF_FALSE; - if (!stream->read(stream->data, &chunk->id, sizeof(tsf_fourcc)) || *chunk->id <= ' ' || *chunk->id >= 'z') return TSF_FALSE; - if (!stream->read(stream->data, &chunk->size, sizeof(tsf_u32))) return TSF_FALSE; - if (parent && sizeof(tsf_fourcc) + sizeof(tsf_u32) + chunk->size > parent->size) return TSF_FALSE; - if (parent) parent->size -= sizeof(tsf_fourcc) + sizeof(tsf_u32) + chunk->size; - IsRiff = TSF_FourCCEquals(chunk->id, "RIFF"), IsList = TSF_FourCCEquals(chunk->id, "LIST"); - if (IsRiff && parent) return TSF_FALSE; //not allowed - if (!IsRiff && !IsList) return TSF_TRUE; //custom type without sub type - if (!stream->read(stream->data, &chunk->id, sizeof(tsf_fourcc)) || *chunk->id <= ' ' || *chunk->id >= 'z') return TSF_FALSE; - chunk->size -= sizeof(tsf_fourcc); - return TSF_TRUE; -} - -static void tsf_region_clear(struct tsf_region* i, TSF_BOOL for_relative) -{ - TSF_MEMSET(i, 0, sizeof(struct tsf_region)); - i->hikey = i->hivel = 127; - i->pitch_keycenter = 60; // C4 - if (for_relative) return; - - i->pitch_keytrack = 100; - - i->pitch_keycenter = -1; - - // SF2 defaults in timecents. - i->ampenv.delay = i->ampenv.attack = i->ampenv.hold = i->ampenv.decay = i->ampenv.release = -12000.0f; - i->modenv.delay = i->modenv.attack = i->modenv.hold = i->modenv.decay = i->modenv.release = -12000.0f; - - i->initialFilterFc = 13500; - - i->delayModLFO = -12000.0f; - i->delayVibLFO = -12000.0f; -} - -static void tsf_region_operator(struct tsf_region* region, tsf_u16 genOper, union tsf_hydra_genamount* amount, struct tsf_region* merge_region) -{ - enum - { - _GEN_TYPE_MASK = 0x0F, - GEN_FLOAT = 0x01, - GEN_INT = 0x02, - GEN_UINT_ADD = 0x03, - GEN_UINT_ADD15 = 0x04, - GEN_KEYRANGE = 0x05, - GEN_VELRANGE = 0x06, - GEN_LOOPMODE = 0x07, - GEN_GROUP = 0x08, - GEN_KEYCENTER = 0x09, - - _GEN_LIMIT_MASK = 0xF0, - GEN_INT_LIMIT12K = 0x10, //min -12000, max 12000 - GEN_INT_LIMITFC = 0x20, //min 1500, max 13500 - GEN_INT_LIMITQ = 0x30, //min 0, max 960 - GEN_INT_LIMIT960 = 0x40, //min -960, max 960 - GEN_INT_LIMIT16K4500 = 0x50, //min -16000, max 4500 - GEN_FLOAT_LIMIT12K5K = 0x60, //min -12000, max 5000 - GEN_FLOAT_LIMIT12K8K = 0x70, //min -12000, max 8000 - GEN_FLOAT_LIMIT1200 = 0x80, //min -1200, max 1200 - GEN_FLOAT_LIMITPAN = 0x90, //* .001f, min -.5f, max .5f, - GEN_FLOAT_LIMITATTN = 0xA0, //* .1f, min 0, max 144.0 - GEN_FLOAT_MAX1000 = 0xB0, //min 0, max 1000 - GEN_FLOAT_MAX1440 = 0xC0, //min 0, max 1440 - - _GEN_MAX = 59, - }; - #define _TSFREGIONOFFSET(TYPE, FIELD) (unsigned char)(((TYPE*)&((struct tsf_region*)0)->FIELD) - (TYPE*)0) - #define _TSFREGIONENVOFFSET(TYPE, ENV, FIELD) (unsigned char)(((TYPE*)&((&(((struct tsf_region*)0)->ENV))->FIELD)) - (TYPE*)0) - static const struct { unsigned char mode, offset; } genMetas[_GEN_MAX] = - { - { GEN_UINT_ADD , _TSFREGIONOFFSET(unsigned int, offset ) }, // 0 StartAddrsOffset - { GEN_UINT_ADD , _TSFREGIONOFFSET(unsigned int, end ) }, // 1 EndAddrsOffset - { GEN_UINT_ADD , _TSFREGIONOFFSET(unsigned int, loop_start ) }, // 2 StartloopAddrsOffset - { GEN_UINT_ADD , _TSFREGIONOFFSET(unsigned int, loop_end ) }, // 3 EndloopAddrsOffset - { GEN_UINT_ADD15 , _TSFREGIONOFFSET(unsigned int, offset ) }, // 4 StartAddrsCoarseOffset - { GEN_INT | GEN_INT_LIMIT12K , _TSFREGIONOFFSET( int, modLfoToPitch ) }, // 5 ModLfoToPitch - { GEN_INT | GEN_INT_LIMIT12K , _TSFREGIONOFFSET( int, vibLfoToPitch ) }, // 6 VibLfoToPitch - { GEN_INT | GEN_INT_LIMIT12K , _TSFREGIONOFFSET( int, modEnvToPitch ) }, // 7 ModEnvToPitch - { GEN_INT | GEN_INT_LIMITFC , _TSFREGIONOFFSET( int, initialFilterFc ) }, // 8 InitialFilterFc - { GEN_INT | GEN_INT_LIMITQ , _TSFREGIONOFFSET( int, initialFilterQ ) }, // 9 InitialFilterQ - { GEN_INT | GEN_INT_LIMIT12K , _TSFREGIONOFFSET( int, modLfoToFilterFc ) }, //10 ModLfoToFilterFc - { GEN_INT | GEN_INT_LIMIT12K , _TSFREGIONOFFSET( int, modEnvToFilterFc ) }, //11 ModEnvToFilterFc - { GEN_UINT_ADD15 , _TSFREGIONOFFSET(unsigned int, end ) }, //12 EndAddrsCoarseOffset - { GEN_INT | GEN_INT_LIMIT960 , _TSFREGIONOFFSET( int, modLfoToVolume ) }, //13 ModLfoToVolume - { 0 , (0 ) }, // Unused - { 0 , (0 ) }, //15 ChorusEffectsSend (unsupported) - { 0 , (0 ) }, //16 ReverbEffectsSend (unsupported) - { GEN_FLOAT | GEN_FLOAT_LIMITPAN , _TSFREGIONOFFSET( float, pan ) }, //17 Pan - { 0 , (0 ) }, // Unused - { 0 , (0 ) }, // Unused - { 0 , (0 ) }, // Unused - { GEN_FLOAT | GEN_FLOAT_LIMIT12K5K , _TSFREGIONOFFSET( float, delayModLFO ) }, //21 DelayModLFO - { GEN_INT | GEN_INT_LIMIT16K4500 , _TSFREGIONOFFSET( int, freqModLFO ) }, //22 FreqModLFO - { GEN_FLOAT | GEN_FLOAT_LIMIT12K5K , _TSFREGIONOFFSET( float, delayVibLFO ) }, //23 DelayVibLFO - { GEN_INT | GEN_INT_LIMIT16K4500 , _TSFREGIONOFFSET( int, freqVibLFO ) }, //24 FreqVibLFO - { GEN_FLOAT | GEN_FLOAT_LIMIT12K5K , _TSFREGIONENVOFFSET( float, modenv, delay ) }, //25 DelayModEnv - { GEN_FLOAT | GEN_FLOAT_LIMIT12K8K , _TSFREGIONENVOFFSET( float, modenv, attack ) }, //26 AttackModEnv - { GEN_FLOAT | GEN_FLOAT_LIMIT12K5K , _TSFREGIONENVOFFSET( float, modenv, hold ) }, //27 HoldModEnv - { GEN_FLOAT | GEN_FLOAT_LIMIT12K8K , _TSFREGIONENVOFFSET( float, modenv, decay ) }, //28 DecayModEnv - { GEN_FLOAT | GEN_FLOAT_MAX1000 , _TSFREGIONENVOFFSET( float, modenv, sustain ) }, //29 SustainModEnv - { GEN_FLOAT | GEN_FLOAT_LIMIT12K8K , _TSFREGIONENVOFFSET( float, modenv, release ) }, //30 ReleaseModEnv - { GEN_FLOAT | GEN_FLOAT_LIMIT1200 , _TSFREGIONENVOFFSET( float, modenv, keynumToHold ) }, //31 KeynumToModEnvHold - { GEN_FLOAT | GEN_FLOAT_LIMIT1200 , _TSFREGIONENVOFFSET( float, modenv, keynumToDecay) }, //32 KeynumToModEnvDecay - { GEN_FLOAT | GEN_FLOAT_LIMIT12K5K , _TSFREGIONENVOFFSET( float, ampenv, delay ) }, //33 DelayVolEnv - { GEN_FLOAT | GEN_FLOAT_LIMIT12K8K , _TSFREGIONENVOFFSET( float, ampenv, attack ) }, //34 AttackVolEnv - { GEN_FLOAT | GEN_FLOAT_LIMIT12K5K , _TSFREGIONENVOFFSET( float, ampenv, hold ) }, //35 HoldVolEnv - { GEN_FLOAT | GEN_FLOAT_LIMIT12K8K , _TSFREGIONENVOFFSET( float, ampenv, decay ) }, //36 DecayVolEnv - { GEN_FLOAT | GEN_FLOAT_MAX1440 , _TSFREGIONENVOFFSET( float, ampenv, sustain ) }, //37 SustainVolEnv - { GEN_FLOAT | GEN_FLOAT_LIMIT12K8K , _TSFREGIONENVOFFSET( float, ampenv, release ) }, //38 ReleaseVolEnv - { GEN_FLOAT | GEN_FLOAT_LIMIT1200 , _TSFREGIONENVOFFSET( float, ampenv, keynumToHold ) }, //39 KeynumToVolEnvHold - { GEN_FLOAT | GEN_FLOAT_LIMIT1200 , _TSFREGIONENVOFFSET( float, ampenv, keynumToDecay) }, //40 KeynumToVolEnvDecay - { 0 , (0 ) }, // Instrument (special) - { 0 , (0 ) }, // Reserved - { GEN_KEYRANGE , (0 ) }, //43 KeyRange - { GEN_VELRANGE , (0 ) }, //44 VelRange - { GEN_UINT_ADD15 , _TSFREGIONOFFSET(unsigned int, loop_start ) }, //45 StartloopAddrsCoarseOffset - { 0 , (0 ) }, //46 Keynum (special) - { 0 , (0 ) }, //47 Velocity (special) - { GEN_FLOAT | GEN_FLOAT_LIMITATTN , _TSFREGIONOFFSET( float, attenuation ) }, //48 InitialAttenuation - { 0 , (0 ) }, // Reserved - { GEN_UINT_ADD15 , _TSFREGIONOFFSET(unsigned int, loop_end ) }, //50 EndloopAddrsCoarseOffset - { GEN_INT , _TSFREGIONOFFSET( int, transpose ) }, //51 CoarseTune - { GEN_INT , _TSFREGIONOFFSET( int, tune ) }, //52 FineTune - { 0 , (0 ) }, // SampleID (special) - { GEN_LOOPMODE , _TSFREGIONOFFSET( int, loop_mode ) }, //54 SampleModes - { 0 , (0 ) }, // Reserved - { GEN_INT , _TSFREGIONOFFSET( int, pitch_keytrack ) }, //56 ScaleTuning - { GEN_GROUP , _TSFREGIONOFFSET(unsigned int, group ) }, //57 ExclusiveClass - { GEN_KEYCENTER , _TSFREGIONOFFSET( int, pitch_keycenter ) }, //58 OverridingRootKey - }; - #undef _TSFREGIONOFFSET - #undef _TSFREGIONENVOFFSET - if (amount) - { - int offset; - if (genOper >= _GEN_MAX) return; - offset = genMetas[genOper].offset; - switch (genMetas[genOper].mode & _GEN_TYPE_MASK) - { - case GEN_FLOAT: (( float*)region)[offset] = amount->shortAmount; return; - case GEN_INT: (( int*)region)[offset] = amount->shortAmount; return; - case GEN_UINT_ADD: ((unsigned int*)region)[offset] += amount->shortAmount; return; - case GEN_UINT_ADD15: ((unsigned int*)region)[offset] += amount->shortAmount<<15; return; - case GEN_KEYRANGE: region->lokey = amount->range.lo; region->hikey = amount->range.hi; return; - case GEN_VELRANGE: region->lovel = amount->range.lo; region->hivel = amount->range.hi; return; - case GEN_LOOPMODE: region->loop_mode = ((amount->wordAmount&3) == 3 ? TSF_LOOPMODE_SUSTAIN : ((amount->wordAmount&3) == 1 ? TSF_LOOPMODE_CONTINUOUS : TSF_LOOPMODE_NONE)); return; - case GEN_GROUP: region->group = amount->wordAmount; return; - case GEN_KEYCENTER: region->pitch_keycenter = amount->shortAmount; return; - } - } - else //merge regions and clamp values - { - for (genOper = 0; genOper != _GEN_MAX; genOper++) - { - int offset = genMetas[genOper].offset; - switch (genMetas[genOper].mode & _GEN_TYPE_MASK) - { - case GEN_FLOAT: - { - float *val = &((float*)region)[offset], vfactor, vmin, vmax; - *val += ((float*)merge_region)[offset]; - switch (genMetas[genOper].mode & _GEN_LIMIT_MASK) - { - case GEN_FLOAT_LIMIT12K5K: vfactor = 1.0f; vmin = -12000.0f; vmax = 5000.0f; break; - case GEN_FLOAT_LIMIT12K8K: vfactor = 1.0f; vmin = -12000.0f; vmax = 8000.0f; break; - case GEN_FLOAT_LIMIT1200: vfactor = 1.0f; vmin = -1200.0f; vmax = 1200.0f; break; - case GEN_FLOAT_LIMITPAN: vfactor = 0.001f; vmin = -0.5f; vmax = 0.5f; break; - case GEN_FLOAT_LIMITATTN: vfactor = 0.1f; vmin = 0.0f; vmax = 144.0f; break; - case GEN_FLOAT_MAX1000: vfactor = 1.0f; vmin = 0.0f; vmax = 1000.0f; break; - case GEN_FLOAT_MAX1440: vfactor = 1.0f; vmin = 0.0f; vmax = 1440.0f; break; - default: continue; - } - *val *= vfactor; - if (*val < vmin) *val = vmin; - else if (*val > vmax) *val = vmax; - continue; - } - case GEN_INT: - { - int *val = &((int*)region)[offset], vmin, vmax; - *val += ((int*)merge_region)[offset]; - switch (genMetas[genOper].mode & _GEN_LIMIT_MASK) - { - case GEN_INT_LIMIT12K: vmin = -12000; vmax = 12000; break; - case GEN_INT_LIMITFC: vmin = 1500; vmax = 13500; break; - case GEN_INT_LIMITQ: vmin = 0; vmax = 960; break; - case GEN_INT_LIMIT960: vmin = -960; vmax = 960; break; - case GEN_INT_LIMIT16K4500: vmin = -16000; vmax = 4500; break; - default: continue; - } - if (*val < vmin) *val = vmin; - else if (*val > vmax) *val = vmax; - continue; - } - case GEN_UINT_ADD: - { - ((unsigned int*)region)[offset] += ((unsigned int*)merge_region)[offset]; - continue; - } - } - } - } -} - -static void tsf_region_envtosecs(struct tsf_envelope* p, TSF_BOOL sustainIsGain) -{ - // EG times need to be converted from timecents to seconds. - // Pin very short EG segments. Timecents don't get to zero, and our EG is - // happier with zero values. - p->delay = (p->delay < -11950.0f ? 0.0f : tsf_timecents2Secsf(p->delay)); - p->attack = (p->attack < -11950.0f ? 0.0f : tsf_timecents2Secsf(p->attack)); - p->release = (p->release < -11950.0f ? 0.0f : tsf_timecents2Secsf(p->release)); - - // If we have dynamic hold or decay times depending on key number we need - // to keep the values in timecents so we can calculate it during startNote - if (!p->keynumToHold) p->hold = (p->hold < -11950.0f ? 0.0f : tsf_timecents2Secsf(p->hold)); - if (!p->keynumToDecay) p->decay = (p->decay < -11950.0f ? 0.0f : tsf_timecents2Secsf(p->decay)); - - if (p->sustain < 0.0f) p->sustain = 0.0f; - else if (sustainIsGain) p->sustain = tsf_decibelsToGain(-p->sustain / 10.0f); - else p->sustain = 1.0f - (p->sustain / 1000.0f); -} - -static int tsf_load_presets(tsf* res, struct tsf_hydra *hydra, unsigned int fontSampleCount) -{ - enum { GenInstrument = 41, GenKeyRange = 43, GenVelRange = 44, GenSampleID = 53 }; - // Read each preset. - struct tsf_hydra_phdr *pphdr, *pphdrMax; - res->presetNum = hydra->phdrNum - 1; - res->presets = (struct tsf_preset*)TSF_MALLOC(res->presetNum * sizeof(struct tsf_preset)); - if (!res->presets) return 0; - else { int i; for (i = 0; i != res->presetNum; i++) res->presets[i].regions = TSF_NULL; } - for (pphdr = hydra->phdrs, pphdrMax = pphdr + hydra->phdrNum - 1; pphdr != pphdrMax; pphdr++) - { - int sortedIndex = 0, region_index = 0; - struct tsf_hydra_phdr *otherphdr; - struct tsf_preset* preset; - struct tsf_hydra_pbag *ppbag, *ppbagEnd; - struct tsf_region globalRegion; - for (otherphdr = hydra->phdrs; otherphdr != pphdrMax; otherphdr++) - { - if (otherphdr == pphdr || otherphdr->bank > pphdr->bank) continue; - else if (otherphdr->bank < pphdr->bank) sortedIndex++; - else if (otherphdr->preset > pphdr->preset) continue; - else if (otherphdr->preset < pphdr->preset) sortedIndex++; - else if (otherphdr < pphdr) sortedIndex++; - } - - preset = &res->presets[sortedIndex]; - TSF_MEMCPY(preset->presetName, pphdr->presetName, sizeof(preset->presetName)); - preset->presetName[sizeof(preset->presetName)-1] = '\0'; //should be zero terminated in source file but make sure - preset->bank = pphdr->bank; - preset->preset = pphdr->preset; - preset->regionNum = 0; - - //count regions covered by this preset - for (ppbag = hydra->pbags + pphdr->presetBagNdx, ppbagEnd = hydra->pbags + pphdr[1].presetBagNdx; ppbag != ppbagEnd; ppbag++) - { - unsigned char plokey = 0, phikey = 127, plovel = 0, phivel = 127; - struct tsf_hydra_pgen *ppgen, *ppgenEnd; struct tsf_hydra_inst *pinst; struct tsf_hydra_ibag *pibag, *pibagEnd; struct tsf_hydra_igen *pigen, *pigenEnd; - for (ppgen = hydra->pgens + ppbag->genNdx, ppgenEnd = hydra->pgens + ppbag[1].genNdx; ppgen != ppgenEnd; ppgen++) - { - if (ppgen->genOper == GenKeyRange) { plokey = ppgen->genAmount.range.lo; phikey = ppgen->genAmount.range.hi; continue; } - if (ppgen->genOper == GenVelRange) { plovel = ppgen->genAmount.range.lo; phivel = ppgen->genAmount.range.hi; continue; } - if (ppgen->genOper != GenInstrument) continue; - if (ppgen->genAmount.wordAmount >= hydra->instNum) continue; - pinst = hydra->insts + ppgen->genAmount.wordAmount; - for (pibag = hydra->ibags + pinst->instBagNdx, pibagEnd = hydra->ibags + pinst[1].instBagNdx; pibag != pibagEnd; pibag++) - { - unsigned char ilokey = 0, ihikey = 127, ilovel = 0, ihivel = 127; - for (pigen = hydra->igens + pibag->instGenNdx, pigenEnd = hydra->igens + pibag[1].instGenNdx; pigen != pigenEnd; pigen++) - { - if (pigen->genOper == GenKeyRange) { ilokey = pigen->genAmount.range.lo; ihikey = pigen->genAmount.range.hi; continue; } - if (pigen->genOper == GenVelRange) { ilovel = pigen->genAmount.range.lo; ihivel = pigen->genAmount.range.hi; continue; } - if (pigen->genOper == GenSampleID && ihikey >= plokey && ilokey <= phikey && ihivel >= plovel && ilovel <= phivel) preset->regionNum++; - } - } - } - } - - preset->regions = (struct tsf_region*)TSF_MALLOC(preset->regionNum * sizeof(struct tsf_region)); - if (!preset->regions) - { - int i; for (i = 0; i != res->presetNum; i++) TSF_FREE(res->presets[i].regions); - TSF_FREE(res->presets); - return 0; - } - tsf_region_clear(&globalRegion, TSF_TRUE); - - // Zones. - for (ppbag = hydra->pbags + pphdr->presetBagNdx, ppbagEnd = hydra->pbags + pphdr[1].presetBagNdx; ppbag != ppbagEnd; ppbag++) - { - struct tsf_hydra_pgen *ppgen, *ppgenEnd; struct tsf_hydra_inst *pinst; struct tsf_hydra_ibag *pibag, *pibagEnd; struct tsf_hydra_igen *pigen, *pigenEnd; - struct tsf_region presetRegion = globalRegion; - int hadGenInstrument = 0; - - // Generators. - for (ppgen = hydra->pgens + ppbag->genNdx, ppgenEnd = hydra->pgens + ppbag[1].genNdx; ppgen != ppgenEnd; ppgen++) - { - // Instrument. - if (ppgen->genOper == GenInstrument) - { - struct tsf_region instRegion; - tsf_u16 whichInst = ppgen->genAmount.wordAmount; - if (whichInst >= hydra->instNum) continue; - - tsf_region_clear(&instRegion, TSF_FALSE); - pinst = &hydra->insts[whichInst]; - for (pibag = hydra->ibags + pinst->instBagNdx, pibagEnd = hydra->ibags + pinst[1].instBagNdx; pibag != pibagEnd; pibag++) - { - // Generators. - struct tsf_region zoneRegion = instRegion; - int hadSampleID = 0; - for (pigen = hydra->igens + pibag->instGenNdx, pigenEnd = hydra->igens + pibag[1].instGenNdx; pigen != pigenEnd; pigen++) - { - if (pigen->genOper == GenSampleID) - { - struct tsf_hydra_shdr* pshdr; - - //preset region key and vel ranges are a filter for the zone regions - if (zoneRegion.hikey < presetRegion.lokey || zoneRegion.lokey > presetRegion.hikey) continue; - if (zoneRegion.hivel < presetRegion.lovel || zoneRegion.lovel > presetRegion.hivel) continue; - if (presetRegion.lokey > zoneRegion.lokey) zoneRegion.lokey = presetRegion.lokey; - if (presetRegion.hikey < zoneRegion.hikey) zoneRegion.hikey = presetRegion.hikey; - if (presetRegion.lovel > zoneRegion.lovel) zoneRegion.lovel = presetRegion.lovel; - if (presetRegion.hivel < zoneRegion.hivel) zoneRegion.hivel = presetRegion.hivel; - - //sum regions - tsf_region_operator(&zoneRegion, 0, TSF_NULL, &presetRegion); - - // EG times need to be converted from timecents to seconds. - tsf_region_envtosecs(&zoneRegion.ampenv, TSF_TRUE); - tsf_region_envtosecs(&zoneRegion.modenv, TSF_FALSE); - - // LFO times need to be converted from timecents to seconds. - zoneRegion.delayModLFO = (zoneRegion.delayModLFO < -11950.0f ? 0.0f : tsf_timecents2Secsf(zoneRegion.delayModLFO)); - zoneRegion.delayVibLFO = (zoneRegion.delayVibLFO < -11950.0f ? 0.0f : tsf_timecents2Secsf(zoneRegion.delayVibLFO)); - - // Fixup sample positions - pshdr = &hydra->shdrs[pigen->genAmount.wordAmount]; - zoneRegion.offset += pshdr->start; - zoneRegion.end += pshdr->end; - zoneRegion.loop_start += pshdr->startLoop; - zoneRegion.loop_end += pshdr->endLoop; - if (pshdr->endLoop > 0) zoneRegion.loop_end -= 1; - if (zoneRegion.pitch_keycenter == -1) zoneRegion.pitch_keycenter = pshdr->originalPitch; - zoneRegion.tune += pshdr->pitchCorrection; - zoneRegion.sample_rate = pshdr->sampleRate; - if (zoneRegion.end && zoneRegion.end < fontSampleCount) zoneRegion.end++; - else zoneRegion.end = fontSampleCount; - - preset->regions[region_index] = zoneRegion; - region_index++; - hadSampleID = 1; - } - else tsf_region_operator(&zoneRegion, pigen->genOper, &pigen->genAmount, TSF_NULL); - } - - // Handle instrument's global zone. - if (pibag == hydra->ibags + pinst->instBagNdx && !hadSampleID) - instRegion = zoneRegion; - - // Modulators (TODO) - //if (ibag->instModNdx < ibag[1].instModNdx) addUnsupportedOpcode("any modulator"); - } - hadGenInstrument = 1; - } - else tsf_region_operator(&presetRegion, ppgen->genOper, &ppgen->genAmount, TSF_NULL); - } - - // Modulators (TODO) - //if (pbag->modNdx < pbag[1].modNdx) addUnsupportedOpcode("any modulator"); - - // Handle preset's global zone. - if (ppbag == hydra->pbags + pphdr->presetBagNdx && !hadGenInstrument) - globalRegion = presetRegion; - } - } - return 1; -} - -static int tsf_load_samples(float** fontSamples, unsigned int* fontSampleCount, struct tsf_riffchunk *chunkSmpl, struct tsf_stream* stream) -{ - // Read sample data into float format buffer. - float* out; unsigned int samplesLeft, samplesToRead, samplesToConvert; - samplesLeft = *fontSampleCount = chunkSmpl->size / sizeof(short); - out = *fontSamples = (float*)TSF_MALLOC(samplesLeft * sizeof(float)); - if (!out) return 0; - for (; samplesLeft; samplesLeft -= samplesToRead) - { - short sampleBuffer[1024], *in = sampleBuffer;; - samplesToRead = (samplesLeft > 1024 ? 1024 : samplesLeft); - stream->read(stream->data, sampleBuffer, samplesToRead * sizeof(short)); - - // Convert from signed 16-bit to float. - for (samplesToConvert = samplesToRead; samplesToConvert > 0; --samplesToConvert) - // If we ever need to compile for big-endian platforms, we'll need to byte-swap here. - *out++ = (float)(*in++ / 32767.0); - } - return 1; -} - -static void tsf_voice_envelope_nextsegment(struct tsf_voice_envelope* e, short active_segment, float outSampleRate) -{ - switch (active_segment) - { - case TSF_SEGMENT_NONE: - e->samplesUntilNextSegment = (int)(e->parameters.delay * outSampleRate); - if (e->samplesUntilNextSegment > 0) - { - e->segment = TSF_SEGMENT_DELAY; - e->segmentIsExponential = TSF_FALSE; - e->level = 0.0; - e->slope = 0.0; - return; - } - /* fall through */ - case TSF_SEGMENT_DELAY: - e->samplesUntilNextSegment = (int)(e->parameters.attack * outSampleRate); - if (e->samplesUntilNextSegment > 0) - { - if (!e->isAmpEnv) - { - //mod env attack duration scales with velocity (velocity of 1 is full duration, max velocity is 0.125 times duration) - e->samplesUntilNextSegment = (int)(e->parameters.attack * ((145 - e->midiVelocity) / 144.0f) * outSampleRate); - } - e->segment = TSF_SEGMENT_ATTACK; - e->segmentIsExponential = TSF_FALSE; - e->level = 0.0f; - e->slope = 1.0f / e->samplesUntilNextSegment; - return; - } - /* fall through */ - case TSF_SEGMENT_ATTACK: - e->samplesUntilNextSegment = (int)(e->parameters.hold * outSampleRate); - if (e->samplesUntilNextSegment > 0) - { - e->segment = TSF_SEGMENT_HOLD; - e->segmentIsExponential = TSF_FALSE; - e->level = 1.0f; - e->slope = 0.0f; - return; - } - /* fall through */ - case TSF_SEGMENT_HOLD: - e->samplesUntilNextSegment = (int)(e->parameters.decay * outSampleRate); - if (e->samplesUntilNextSegment > 0) - { - e->segment = TSF_SEGMENT_DECAY; - e->level = 1.0f; - if (e->isAmpEnv) - { - // I don't truly understand this; just following what LinuxSampler does. - float mysterySlope = -9.226f / e->samplesUntilNextSegment; - e->slope = TSF_EXPF(mysterySlope); - e->segmentIsExponential = TSF_TRUE; - if (e->parameters.sustain > 0.0f) - { - // Again, this is following LinuxSampler's example, which is similar to - // SF2-style decay, where "decay" specifies the time it would take to - // get to zero, not to the sustain level. The SFZ spec is not that - // specific about what "decay" means, so perhaps it's really supposed - // to specify the time to reach the sustain level. - e->samplesUntilNextSegment = (int)(TSF_LOG(e->parameters.sustain) / mysterySlope); - } - } - else - { - e->slope = -1.0f / e->samplesUntilNextSegment; - e->samplesUntilNextSegment = (int)(e->parameters.decay * (1.0f - e->parameters.sustain) * outSampleRate); - e->segmentIsExponential = TSF_FALSE; - } - return; - } - /* fall through */ - case TSF_SEGMENT_DECAY: - e->segment = TSF_SEGMENT_SUSTAIN; - e->level = e->parameters.sustain; - e->slope = 0.0f; - e->samplesUntilNextSegment = 0x7FFFFFFF; - e->segmentIsExponential = TSF_FALSE; - return; - case TSF_SEGMENT_SUSTAIN: - e->segment = TSF_SEGMENT_RELEASE; - e->samplesUntilNextSegment = (int)((e->parameters.release <= 0 ? TSF_FASTRELEASETIME : e->parameters.release) * outSampleRate); - if (e->isAmpEnv) - { - // I don't truly understand this; just following what LinuxSampler does. - float mysterySlope = -9.226f / e->samplesUntilNextSegment; - e->slope = TSF_EXPF(mysterySlope); - e->segmentIsExponential = TSF_TRUE; - } - else - { - e->slope = -e->level / e->samplesUntilNextSegment; - e->segmentIsExponential = TSF_FALSE; - } - return; - case TSF_SEGMENT_RELEASE: - default: - e->segment = TSF_SEGMENT_DONE; - e->segmentIsExponential = TSF_FALSE; - e->level = e->slope = 0.0f; - e->samplesUntilNextSegment = 0x7FFFFFF; - } -} - -static void tsf_voice_envelope_setup(struct tsf_voice_envelope* e, struct tsf_envelope* new_parameters, int midiNoteNumber, short midiVelocity, TSF_BOOL isAmpEnv, float outSampleRate) -{ - e->parameters = *new_parameters; - if (e->parameters.keynumToHold) - { - e->parameters.hold += e->parameters.keynumToHold * (60.0f - midiNoteNumber); - e->parameters.hold = (e->parameters.hold < -10000.0f ? 0.0f : tsf_timecents2Secsf(e->parameters.hold)); - } - if (e->parameters.keynumToDecay) - { - e->parameters.decay += e->parameters.keynumToDecay * (60.0f - midiNoteNumber); - e->parameters.decay = (e->parameters.decay < -10000.0f ? 0.0f : tsf_timecents2Secsf(e->parameters.decay)); - } - e->midiVelocity = midiVelocity; - e->isAmpEnv = isAmpEnv; - tsf_voice_envelope_nextsegment(e, TSF_SEGMENT_NONE, outSampleRate); -} - -static void tsf_voice_envelope_process(struct tsf_voice_envelope* e, int numSamples, float outSampleRate) -{ - if (e->slope) - { - if (e->segmentIsExponential) e->level *= TSF_POWF(e->slope, (float)numSamples); - else e->level += (e->slope * numSamples); - } - if ((e->samplesUntilNextSegment -= numSamples) <= 0) - tsf_voice_envelope_nextsegment(e, e->segment, outSampleRate); -} - -static void tsf_voice_lowpass_setup(struct tsf_voice_lowpass* e, float Fc) -{ - // Lowpass filter from http://www.earlevel.com/main/2012/11/26/biquad-c-source-code/ - double K = TSF_TAN(TSF_PI * Fc), KK = K * K; - double norm = 1 / (1 + K * e->QInv + KK); - e->a0 = KK * norm; - e->a1 = 2 * e->a0; - e->b1 = 2 * (KK - 1) * norm; - e->b2 = (1 - K * e->QInv + KK) * norm; -} - -static float tsf_voice_lowpass_process(struct tsf_voice_lowpass* e, double In) -{ - double Out = In * e->a0 + e->z1; e->z1 = In * e->a1 + e->z2 - e->b1 * Out; e->z2 = In * e->a0 - e->b2 * Out; return (float)Out; -} - -static void tsf_voice_lfo_setup(struct tsf_voice_lfo* e, float delay, int freqCents, float outSampleRate) -{ - e->samplesUntil = (int)(delay * outSampleRate); - e->delta = (4.0f * tsf_cents2Hertz((float)freqCents) / outSampleRate); - e->level = 0; -} - -static void tsf_voice_lfo_process(struct tsf_voice_lfo* e, int blockSamples) -{ - if (e->samplesUntil > blockSamples) { e->samplesUntil -= blockSamples; return; } - e->level += e->delta * blockSamples; - if (e->level > 1.0f) { e->delta = -e->delta; e->level = 2.0f - e->level; } - else if (e->level < -1.0f) { e->delta = -e->delta; e->level = -2.0f - e->level; } -} - -static void tsf_voice_kill(struct tsf_voice* v) -{ - v->playingPreset = -1; -} - -static void tsf_voice_end(tsf* f, struct tsf_voice* v) -{ - // if maxVoiceNum is set, assume that voice rendering and note queuing are on separate threads - // so to minimize the chance that voice rendering would advance the segment at the same time - // we just do it twice here and hope that it sticks - int repeats = (f->maxVoiceNum ? 2 : 1); - while (repeats--) - { - tsf_voice_envelope_nextsegment(&v->ampenv, TSF_SEGMENT_SUSTAIN, f->outSampleRate); - tsf_voice_envelope_nextsegment(&v->modenv, TSF_SEGMENT_SUSTAIN, f->outSampleRate); - if (v->region->loop_mode == TSF_LOOPMODE_SUSTAIN) - { - // Continue playing, but stop looping. - v->loopEnd = v->loopStart; - } - } -} - -static void tsf_voice_endquick(tsf* f, struct tsf_voice* v) -{ - // if maxVoiceNum is set, assume that voice rendering and note queuing are on separate threads - // so to minimize the chance that voice rendering would advance the segment at the same time - // we just do it twice here and hope that it sticks - int repeats = (f->maxVoiceNum ? 2 : 1); - while (repeats--) - { - v->ampenv.parameters.release = 0.0f; tsf_voice_envelope_nextsegment(&v->ampenv, TSF_SEGMENT_SUSTAIN, f->outSampleRate); - v->modenv.parameters.release = 0.0f; tsf_voice_envelope_nextsegment(&v->modenv, TSF_SEGMENT_SUSTAIN, f->outSampleRate); - } -} - -static void tsf_voice_calcpitchratio(struct tsf_voice* v, float pitchShift, float outSampleRate) -{ - double note = v->playingKey + v->region->transpose + v->region->tune / 100.0; - double adjustedPitch = v->region->pitch_keycenter + (note - v->region->pitch_keycenter) * (v->region->pitch_keytrack / 100.0); - if (pitchShift) adjustedPitch += pitchShift; - v->pitchInputTimecents = adjustedPitch * 100.0; - v->pitchOutputFactor = v->region->sample_rate / (tsf_timecents2Secsd(v->region->pitch_keycenter * 100.0) * outSampleRate); -} - -static void tsf_voice_render(tsf* f, struct tsf_voice* v, float* outputBuffer, int numSamples) -{ - struct tsf_region* region = v->region; - float* input = f->fontSamples; - float* outL = outputBuffer; - float* outR = (f->outputmode == TSF_STEREO_UNWEAVED ? outL + numSamples : TSF_NULL); - - // Cache some values, to give them at least some chance of ending up in registers. - TSF_BOOL updateModEnv = (region->modEnvToPitch || region->modEnvToFilterFc); - TSF_BOOL updateModLFO = (v->modlfo.delta && (region->modLfoToPitch || region->modLfoToFilterFc || region->modLfoToVolume)); - TSF_BOOL updateVibLFO = (v->viblfo.delta && (region->vibLfoToPitch)); - TSF_BOOL isLooping = (v->loopStart < v->loopEnd); - unsigned int tmpLoopStart = v->loopStart, tmpLoopEnd = v->loopEnd; - double tmpSampleEndDbl = (double)region->end, tmpLoopEndDbl = (double)tmpLoopEnd + 1.0; - double tmpSourceSamplePosition = v->sourceSamplePosition; - struct tsf_voice_lowpass tmpLowpass = v->lowpass; - - TSF_BOOL dynamicLowpass = (region->modLfoToFilterFc || region->modEnvToFilterFc); - float tmpSampleRate = f->outSampleRate, tmpInitialFilterFc, tmpModLfoToFilterFc, tmpModEnvToFilterFc; - - TSF_BOOL dynamicPitchRatio = (region->modLfoToPitch || region->modEnvToPitch || region->vibLfoToPitch); - double pitchRatio; - float tmpModLfoToPitch, tmpVibLfoToPitch, tmpModEnvToPitch; - - TSF_BOOL dynamicGain = (region->modLfoToVolume != 0); - float noteGain = 0, tmpModLfoToVolume; - - if (dynamicLowpass) tmpInitialFilterFc = (float)region->initialFilterFc, tmpModLfoToFilterFc = (float)region->modLfoToFilterFc, tmpModEnvToFilterFc = (float)region->modEnvToFilterFc; - else tmpInitialFilterFc = 0, tmpModLfoToFilterFc = 0, tmpModEnvToFilterFc = 0; - - if (dynamicPitchRatio) pitchRatio = 0, tmpModLfoToPitch = (float)region->modLfoToPitch, tmpVibLfoToPitch = (float)region->vibLfoToPitch, tmpModEnvToPitch = (float)region->modEnvToPitch; - else pitchRatio = tsf_timecents2Secsd(v->pitchInputTimecents) * v->pitchOutputFactor, tmpModLfoToPitch = 0, tmpVibLfoToPitch = 0, tmpModEnvToPitch = 0; - - if (dynamicGain) tmpModLfoToVolume = (float)region->modLfoToVolume * 0.1f; - else noteGain = tsf_decibelsToGain(v->noteGainDB), tmpModLfoToVolume = 0; - - while (numSamples) - { - float gainMono, gainLeft, gainRight; - int blockSamples = (numSamples > TSF_RENDER_EFFECTSAMPLEBLOCK ? TSF_RENDER_EFFECTSAMPLEBLOCK : numSamples); - numSamples -= blockSamples; - - if (dynamicLowpass) - { - float fres = tmpInitialFilterFc + v->modlfo.level * tmpModLfoToFilterFc + v->modenv.level * tmpModEnvToFilterFc; - float lowpassFc = (fres <= 13500 ? tsf_cents2Hertz(fres) / tmpSampleRate : 1.0f); - tmpLowpass.active = (lowpassFc < 0.499f); - if (tmpLowpass.active) tsf_voice_lowpass_setup(&tmpLowpass, lowpassFc); - } - - if (dynamicPitchRatio) - pitchRatio = tsf_timecents2Secsd(v->pitchInputTimecents + (v->modlfo.level * tmpModLfoToPitch + v->viblfo.level * tmpVibLfoToPitch + v->modenv.level * tmpModEnvToPitch)) * v->pitchOutputFactor; - - if (dynamicGain) - noteGain = tsf_decibelsToGain(v->noteGainDB + (v->modlfo.level * tmpModLfoToVolume)); - - gainMono = noteGain * v->ampenv.level; - - // Update EG. - tsf_voice_envelope_process(&v->ampenv, blockSamples, tmpSampleRate); - if (updateModEnv) tsf_voice_envelope_process(&v->modenv, blockSamples, tmpSampleRate); - - // Update LFOs. - if (updateModLFO) tsf_voice_lfo_process(&v->modlfo, blockSamples); - if (updateVibLFO) tsf_voice_lfo_process(&v->viblfo, blockSamples); - - switch (f->outputmode) - { - case TSF_STEREO_INTERLEAVED: - gainLeft = gainMono * v->panFactorLeft, gainRight = gainMono * v->panFactorRight; - while (blockSamples-- && tmpSourceSamplePosition < tmpSampleEndDbl) - { - unsigned int pos = (unsigned int)tmpSourceSamplePosition, nextPos = (pos >= tmpLoopEnd && isLooping ? tmpLoopStart : pos + 1); - - // Simple linear interpolation. - float alpha = (float)(tmpSourceSamplePosition - pos), val = (input[pos] * (1.0f - alpha) + input[nextPos] * alpha); - - // Low-pass filter. - if (tmpLowpass.active) val = tsf_voice_lowpass_process(&tmpLowpass, val); - - *outL++ += val * gainLeft; - *outL++ += val * gainRight; - - // Next sample. - tmpSourceSamplePosition += pitchRatio; - if (tmpSourceSamplePosition >= tmpLoopEndDbl && isLooping) tmpSourceSamplePosition -= (tmpLoopEnd - tmpLoopStart + 1.0); - } - break; - - case TSF_STEREO_UNWEAVED: - gainLeft = gainMono * v->panFactorLeft, gainRight = gainMono * v->panFactorRight; - while (blockSamples-- && tmpSourceSamplePosition < tmpSampleEndDbl) - { - unsigned int pos = (unsigned int)tmpSourceSamplePosition, nextPos = (pos >= tmpLoopEnd && isLooping ? tmpLoopStart : pos + 1); - - // Simple linear interpolation. - float alpha = (float)(tmpSourceSamplePosition - pos), val = (input[pos] * (1.0f - alpha) + input[nextPos] * alpha); - - // Low-pass filter. - if (tmpLowpass.active) val = tsf_voice_lowpass_process(&tmpLowpass, val); - - *outL++ += val * gainLeft; - *outR++ += val * gainRight; - - // Next sample. - tmpSourceSamplePosition += pitchRatio; - if (tmpSourceSamplePosition >= tmpLoopEndDbl && isLooping) tmpSourceSamplePosition -= (tmpLoopEnd - tmpLoopStart + 1.0); - } - break; - - case TSF_MONO: - while (blockSamples-- && tmpSourceSamplePosition < tmpSampleEndDbl) - { - unsigned int pos = (unsigned int)tmpSourceSamplePosition, nextPos = (pos >= tmpLoopEnd && isLooping ? tmpLoopStart : pos + 1); - - // Simple linear interpolation. - float alpha = (float)(tmpSourceSamplePosition - pos), val = (input[pos] * (1.0f - alpha) + input[nextPos] * alpha); - - // Low-pass filter. - if (tmpLowpass.active) val = tsf_voice_lowpass_process(&tmpLowpass, val); - - *outL++ += val * gainMono; - - // Next sample. - tmpSourceSamplePosition += pitchRatio; - if (tmpSourceSamplePosition >= tmpLoopEndDbl && isLooping) tmpSourceSamplePosition -= (tmpLoopEnd - tmpLoopStart + 1.0); - } - break; - } - - if (tmpSourceSamplePosition >= tmpSampleEndDbl || v->ampenv.segment == TSF_SEGMENT_DONE) - { - tsf_voice_kill(v); - return; - } - } - - v->sourceSamplePosition = tmpSourceSamplePosition; - if (tmpLowpass.active || dynamicLowpass) v->lowpass = tmpLowpass; -} - -TSFDEF tsf* tsf_load(struct tsf_stream* stream) -{ - tsf* res = TSF_NULL; - struct tsf_riffchunk chunkHead; - struct tsf_riffchunk chunkList; - struct tsf_hydra hydra; - float* fontSamples = TSF_NULL; - unsigned int fontSampleCount = 0; - - if (!tsf_riffchunk_read(TSF_NULL, &chunkHead, stream) || !TSF_FourCCEquals(chunkHead.id, "sfbk")) - { - //if (e) *e = TSF_INVALID_NOSF2HEADER; - return res; - } - - // Read hydra and locate sample data. - TSF_MEMSET(&hydra, 0, sizeof(hydra)); - while (tsf_riffchunk_read(&chunkHead, &chunkList, stream)) - { - struct tsf_riffchunk chunk; - if (TSF_FourCCEquals(chunkList.id, "pdta")) - { - while (tsf_riffchunk_read(&chunkList, &chunk, stream)) - { - #define HandleChunk(chunkName) (TSF_FourCCEquals(chunk.id, #chunkName) && !(chunk.size % chunkName##SizeInFile)) \ - { \ - int num = chunk.size / chunkName##SizeInFile, i; \ - hydra.chunkName##Num = num; \ - hydra.chunkName##s = (struct tsf_hydra_##chunkName*)TSF_MALLOC(num * sizeof(struct tsf_hydra_##chunkName)); \ - if (!hydra.chunkName##s) goto out_of_memory; \ - for (i = 0; i < num; ++i) tsf_hydra_read_##chunkName(&hydra.chunkName##s[i], stream); \ - } - enum - { - phdrSizeInFile = 38, pbagSizeInFile = 4, pmodSizeInFile = 10, - pgenSizeInFile = 4, instSizeInFile = 22, ibagSizeInFile = 4, - imodSizeInFile = 10, igenSizeInFile = 4, shdrSizeInFile = 46 - }; - if HandleChunk(phdr) else if HandleChunk(pbag) else if HandleChunk(pmod) - else if HandleChunk(pgen) else if HandleChunk(inst) else if HandleChunk(ibag) - else if HandleChunk(imod) else if HandleChunk(igen) else if HandleChunk(shdr) - else stream->skip(stream->data, chunk.size); - #undef HandleChunk - } - } - else if (TSF_FourCCEquals(chunkList.id, "sdta")) - { - while (tsf_riffchunk_read(&chunkList, &chunk, stream)) - { - if (TSF_FourCCEquals(chunk.id, "smpl") && !fontSamples && chunk.size >= sizeof(short)) - { - if (!tsf_load_samples(&fontSamples, &fontSampleCount, &chunk, stream)) goto out_of_memory; - } - else stream->skip(stream->data, chunk.size); - } - } - else stream->skip(stream->data, chunkList.size); - } - if (!hydra.phdrs || !hydra.pbags || !hydra.pmods || !hydra.pgens || !hydra.insts || !hydra.ibags || !hydra.imods || !hydra.igens || !hydra.shdrs) - { - //if (e) *e = TSF_INVALID_INCOMPLETE; - } - else if (fontSamples == TSF_NULL) - { - //if (e) *e = TSF_INVALID_NOSAMPLEDATA; - } - else - { - res = (tsf*)TSF_MALLOC(sizeof(tsf)); - if (!res) goto out_of_memory; - TSF_MEMSET(res, 0, sizeof(tsf)); - if (!tsf_load_presets(res, &hydra, fontSampleCount)) goto out_of_memory; - res->fontSamples = fontSamples; - fontSamples = TSF_NULL; //don't free below - res->outSampleRate = 44100.0f; - } - if (0) - { - out_of_memory: - TSF_FREE(res); - res = TSF_NULL; - //if (e) *e = TSF_OUT_OF_MEMORY; - } - TSF_FREE(hydra.phdrs); TSF_FREE(hydra.pbags); TSF_FREE(hydra.pmods); - TSF_FREE(hydra.pgens); TSF_FREE(hydra.insts); TSF_FREE(hydra.ibags); - TSF_FREE(hydra.imods); TSF_FREE(hydra.igens); TSF_FREE(hydra.shdrs); - TSF_FREE(fontSamples); - return res; -} - -TSFDEF tsf* tsf_copy(tsf* f) -{ - tsf* res; - if (!f) return TSF_NULL; - if (!f->refCount) - { - f->refCount = (int*)TSF_MALLOC(sizeof(int)); - if (!f->refCount) return TSF_NULL; - *f->refCount = 1; - } - res = (tsf*)TSF_MALLOC(sizeof(tsf)); - if (!res) return TSF_NULL; - TSF_MEMCPY(res, f, sizeof(tsf)); - res->voices = TSF_NULL; - res->voiceNum = 0; - res->channels = TSF_NULL; - (*res->refCount)++; - return res; -} - -TSFDEF void tsf_close(tsf* f) -{ - if (!f) return; - if (!f->refCount || !--(*f->refCount)) - { - struct tsf_preset *preset = f->presets, *presetEnd = preset + f->presetNum; - for (; preset != presetEnd; preset++) TSF_FREE(preset->regions); - TSF_FREE(f->presets); - TSF_FREE(f->fontSamples); - TSF_FREE(f->refCount); - } - TSF_FREE(f->channels); - TSF_FREE(f->voices); - TSF_FREE(f); -} - -TSFDEF void tsf_reset(tsf* f) -{ - struct tsf_voice *v = f->voices, *vEnd = v + f->voiceNum; - for (; v != vEnd; v++) - if (v->playingPreset != -1 && (v->ampenv.segment < TSF_SEGMENT_RELEASE || v->ampenv.parameters.release)) - tsf_voice_endquick(f, v); - if (f->channels) { TSF_FREE(f->channels); f->channels = TSF_NULL; } -} - -TSFDEF int tsf_get_presetindex(const tsf* f, int bank, int preset_number) -{ - const struct tsf_preset *presets; - int i, iMax; - for (presets = f->presets, i = 0, iMax = f->presetNum; i < iMax; i++) - if (presets[i].preset == preset_number && presets[i].bank == bank) - return i; - return -1; -} - -TSFDEF int tsf_get_presetcount(const tsf* f) -{ - return f->presetNum; -} - -TSFDEF const char* tsf_get_presetname(const tsf* f, int preset) -{ - return (preset < 0 || preset >= f->presetNum ? TSF_NULL : f->presets[preset].presetName); -} - -TSFDEF const char* tsf_bank_get_presetname(const tsf* f, int bank, int preset_number) -{ - return tsf_get_presetname(f, tsf_get_presetindex(f, bank, preset_number)); -} - -TSFDEF void tsf_set_output(tsf* f, enum TSFOutputMode outputmode, int samplerate, float global_gain_db) -{ - f->outputmode = outputmode; - f->outSampleRate = (float)(samplerate >= 1 ? samplerate : 44100.0f); - f->globalGainDB = global_gain_db; -} - -TSFDEF void tsf_set_volume(tsf* f, float global_volume) -{ - f->globalGainDB = (global_volume == 1.0f ? 0 : -tsf_gainToDecibels(1.0f / global_volume)); -} - -TSFDEF int tsf_set_max_voices(tsf* f, int max_voices) -{ - int i = f->voiceNum; - int newVoiceNum = (f->voiceNum > max_voices ? f->voiceNum : max_voices); - struct tsf_voice *newVoices = (struct tsf_voice*)TSF_REALLOC(f->voices, newVoiceNum * sizeof(struct tsf_voice)); - if (!newVoices) return 0; - f->voices = newVoices; - f->voiceNum = f->maxVoiceNum = newVoiceNum; - for (; i < max_voices; i++) - f->voices[i].playingPreset = -1; - return 1; -} - -TSFDEF int tsf_note_on(tsf* f, int preset_index, int key, float vel) -{ - short midiVelocity = (short)(vel * 127); - int voicePlayIndex; - struct tsf_region *region, *regionEnd; - - if (preset_index < 0 || preset_index >= f->presetNum) return 1; - if (vel <= 0.0f) { tsf_note_off(f, preset_index, key); return 1; } - - // Play all matching regions. - voicePlayIndex = f->voicePlayIndex++; - for (region = f->presets[preset_index].regions, regionEnd = region + f->presets[preset_index].regionNum; region != regionEnd; region++) - { - struct tsf_voice *voice, *v, *vEnd; TSF_BOOL doLoop; float lowpassFilterQDB, lowpassFc; - if (key < region->lokey || key > region->hikey || midiVelocity < region->lovel || midiVelocity > region->hivel) continue; - - voice = TSF_NULL, v = f->voices, vEnd = v + f->voiceNum; - if (region->group) - { - for (; v != vEnd; v++) - if (v->playingPreset == preset_index && v->region->group == region->group) tsf_voice_endquick(f, v); - else if (v->playingPreset == -1 && !voice) voice = v; - } - else for (; v != vEnd; v++) if (v->playingPreset == -1) { voice = v; break; } - - if (!voice) - { - struct tsf_voice* newVoices; - if (f->maxVoiceNum) - { - // voices have been pre-allocated and limited to a maximum, unable to start playing this voice - continue; - } - f->voiceNum += 4; - newVoices = (struct tsf_voice*)TSF_REALLOC(f->voices, f->voiceNum * sizeof(struct tsf_voice)); - if (!newVoices) return 0; - f->voices = newVoices; - voice = &f->voices[f->voiceNum - 4]; - voice[1].playingPreset = voice[2].playingPreset = voice[3].playingPreset = -1; - } - - voice->region = region; - voice->playingPreset = preset_index; - voice->playingKey = key; - voice->playIndex = voicePlayIndex; - voice->noteGainDB = f->globalGainDB - region->attenuation - tsf_gainToDecibels(1.0f / vel); - - if (f->channels) - { - f->channels->setupVoice(f, voice); - } - else - { - tsf_voice_calcpitchratio(voice, 0, f->outSampleRate); - // The SFZ spec is silent about the pan curve, but a 3dB pan law seems common. This sqrt() curve matches what Dimension LE does; Alchemy Free seems closer to sin(adjustedPan * pi/2). - voice->panFactorLeft = TSF_SQRTF(0.5f - region->pan); - voice->panFactorRight = TSF_SQRTF(0.5f + region->pan); - } - - // Offset/end. - voice->sourceSamplePosition = region->offset; - - // Loop. - doLoop = (region->loop_mode != TSF_LOOPMODE_NONE && region->loop_start < region->loop_end); - voice->loopStart = (doLoop ? region->loop_start : 0); - voice->loopEnd = (doLoop ? region->loop_end : 0); - - // Setup envelopes. - tsf_voice_envelope_setup(&voice->ampenv, ®ion->ampenv, key, midiVelocity, TSF_TRUE, f->outSampleRate); - tsf_voice_envelope_setup(&voice->modenv, ®ion->modenv, key, midiVelocity, TSF_FALSE, f->outSampleRate); - - // Setup lowpass filter. - lowpassFc = (region->initialFilterFc <= 13500 ? tsf_cents2Hertz((float)region->initialFilterFc) / f->outSampleRate : 1.0f); - lowpassFilterQDB = region->initialFilterQ / 10.0f; - voice->lowpass.QInv = 1.0 / TSF_POW(10.0, (lowpassFilterQDB / 20.0)); - voice->lowpass.z1 = voice->lowpass.z2 = 0; - voice->lowpass.active = (lowpassFc < 0.499f); - if (voice->lowpass.active) tsf_voice_lowpass_setup(&voice->lowpass, lowpassFc); - - // Setup LFO filters. - tsf_voice_lfo_setup(&voice->modlfo, region->delayModLFO, region->freqModLFO, f->outSampleRate); - tsf_voice_lfo_setup(&voice->viblfo, region->delayVibLFO, region->freqVibLFO, f->outSampleRate); - } - return 1; -} - -TSFDEF int tsf_bank_note_on(tsf* f, int bank, int preset_number, int key, float vel) -{ - int preset_index = tsf_get_presetindex(f, bank, preset_number); - if (preset_index == -1) return 0; - return tsf_note_on(f, preset_index, key, vel); -} - -TSFDEF void tsf_note_off(tsf* f, int preset_index, int key) -{ - struct tsf_voice *v = f->voices, *vEnd = v + f->voiceNum, *vMatchFirst = TSF_NULL, *vMatchLast = TSF_NULL; - for (; v != vEnd; v++) - { - //Find the first and last entry in the voices list with matching preset, key and look up the smallest play index - if (v->playingPreset != preset_index || v->playingKey != key || v->ampenv.segment >= TSF_SEGMENT_RELEASE) continue; - else if (!vMatchFirst || v->playIndex < vMatchFirst->playIndex) vMatchFirst = vMatchLast = v; - else if (v->playIndex == vMatchFirst->playIndex) vMatchLast = v; - } - if (!vMatchFirst) return; - for (v = vMatchFirst; v <= vMatchLast; v++) - { - //Stop all voices with matching preset, key and the smallest play index which was enumerated above - if (v != vMatchFirst && v != vMatchLast && - (v->playIndex != vMatchFirst->playIndex || v->playingPreset != preset_index || v->playingKey != key || v->ampenv.segment >= TSF_SEGMENT_RELEASE)) continue; - tsf_voice_end(f, v); - } -} - -TSFDEF int tsf_bank_note_off(tsf* f, int bank, int preset_number, int key) -{ - int preset_index = tsf_get_presetindex(f, bank, preset_number); - if (preset_index == -1) return 0; - tsf_note_off(f, preset_index, key); - return 1; -} - -TSFDEF void tsf_note_off_all(tsf* f) -{ - struct tsf_voice *v = f->voices, *vEnd = v + f->voiceNum; - for (; v != vEnd; v++) if (v->playingPreset != -1 && v->ampenv.segment < TSF_SEGMENT_RELEASE) - tsf_voice_end(f, v); -} - -TSFDEF int tsf_active_voice_count(tsf* f) -{ - int count = 0; - struct tsf_voice *v = f->voices, *vEnd = v + f->voiceNum; - for (; v != vEnd; v++) if (v->playingPreset != -1) count++; - return count; -} - -TSFDEF void tsf_render_short(tsf* f, short* buffer, int samples, int flag_mixing) -{ - float outputSamples[TSF_RENDER_SHORTBUFFERBLOCK]; - int channels = (f->outputmode == TSF_MONO ? 1 : 2), maxChannelSamples = TSF_RENDER_SHORTBUFFERBLOCK / channels; - while (samples > 0) - { - int channelSamples = (samples > maxChannelSamples ? maxChannelSamples : samples); - short* bufferEnd = buffer + channelSamples * channels; - float *floatSamples = outputSamples; - tsf_render_float(f, floatSamples, channelSamples, TSF_FALSE); - samples -= channelSamples; - - if (flag_mixing) - while (buffer != bufferEnd) - { - float v = *floatSamples++; - int vi = *buffer + (v < -1.00004566f ? (int)-32768 : (v > 1.00001514f ? (int)32767 : (int)(v * 32767.5f))); - *buffer++ = (vi < -32768 ? (short)-32768 : (vi > 32767 ? (short)32767 : (short)vi)); - } - else - while (buffer != bufferEnd) - { - float v = *floatSamples++; - *buffer++ = (v < -1.00004566f ? (short)-32768 : (v > 1.00001514f ? (short)32767 : (short)(v * 32767.5f))); - } - } -} - -TSFDEF void tsf_render_float(tsf* f, float* buffer, int samples, int flag_mixing) -{ - struct tsf_voice *v = f->voices, *vEnd = v + f->voiceNum; - if (!flag_mixing) TSF_MEMSET(buffer, 0, (f->outputmode == TSF_MONO ? 1 : 2) * sizeof(float) * samples); - for (; v != vEnd; v++) - if (v->playingPreset != -1) - tsf_voice_render(f, v, buffer, samples); -} - -static void tsf_channel_setup_voice(tsf* f, struct tsf_voice* v) -{ - struct tsf_channel* c = &f->channels->channels[f->channels->activeChannel]; - float newpan = v->region->pan + c->panOffset; - v->playingChannel = f->channels->activeChannel; - v->noteGainDB += c->gainDB; - tsf_voice_calcpitchratio(v, (c->pitchWheel == 8192 ? c->tuning : ((c->pitchWheel / 16383.0f * c->pitchRange * 2.0f) - c->pitchRange + c->tuning)), f->outSampleRate); - if (newpan <= -0.5f) { v->panFactorLeft = 1.0f; v->panFactorRight = 0.0f; } - else if (newpan >= 0.5f) { v->panFactorLeft = 0.0f; v->panFactorRight = 1.0f; } - else { v->panFactorLeft = TSF_SQRTF(0.5f - newpan); v->panFactorRight = TSF_SQRTF(0.5f + newpan); } -} - -static struct tsf_channel* tsf_channel_init(tsf* f, int channel) -{ - int i; - if (f->channels && channel < f->channels->channelNum) return &f->channels->channels[channel]; - if (!f->channels) - { - f->channels = (struct tsf_channels*)TSF_MALLOC(sizeof(struct tsf_channels) + sizeof(struct tsf_channel) * channel); - if (!f->channels) return NULL; - f->channels->setupVoice = &tsf_channel_setup_voice; - f->channels->channelNum = 0; - f->channels->activeChannel = 0; - } - else - { - struct tsf_channels *newChannels = (struct tsf_channels*)TSF_REALLOC(f->channels, sizeof(struct tsf_channels) + sizeof(struct tsf_channel) * channel); - if (!newChannels) return NULL; - f->channels = newChannels; - } - i = f->channels->channelNum; - f->channels->channelNum = channel + 1; - for (; i <= channel; i++) - { - struct tsf_channel* c = &f->channels->channels[i]; - c->presetIndex = c->bank = 0; - c->pitchWheel = c->midiPan = 8192; - c->midiVolume = c->midiExpression = 16383; - c->midiRPN = 0xFFFF; - c->midiData = 0; - c->panOffset = 0.0f; - c->gainDB = 0.0f; - c->pitchRange = 2.0f; - c->tuning = 0.0f; - } - return &f->channels->channels[channel]; -} - -static void tsf_channel_applypitch(tsf* f, int channel, struct tsf_channel* c) -{ - struct tsf_voice *v, *vEnd; - float pitchShift = (c->pitchWheel == 8192 ? c->tuning : ((c->pitchWheel / 16383.0f * c->pitchRange * 2.0f) - c->pitchRange + c->tuning)); - for (v = f->voices, vEnd = v + f->voiceNum; v != vEnd; v++) - if (v->playingChannel == channel && v->playingPreset != -1) - tsf_voice_calcpitchratio(v, pitchShift, f->outSampleRate); -} - -TSFDEF int tsf_channel_set_presetindex(tsf* f, int channel, int preset_index) -{ - struct tsf_channel *c = tsf_channel_init(f, channel); - if (!c) return 0; - c->presetIndex = (unsigned short)preset_index; - return 1; -} - -TSFDEF int tsf_channel_set_presetnumber(tsf* f, int channel, int preset_number, int flag_mididrums) -{ - int preset_index; - struct tsf_channel *c = tsf_channel_init(f, channel); - if (!c) return 0; - if (flag_mididrums) - { - preset_index = tsf_get_presetindex(f, 128 | (c->bank & 0x7FFF), preset_number); - if (preset_index == -1) preset_index = tsf_get_presetindex(f, 128, preset_number); - if (preset_index == -1) preset_index = tsf_get_presetindex(f, 128, 0); - if (preset_index == -1) preset_index = tsf_get_presetindex(f, (c->bank & 0x7FFF), preset_number); - } - else preset_index = tsf_get_presetindex(f, (c->bank & 0x7FFF), preset_number); - if (preset_index == -1) preset_index = tsf_get_presetindex(f, 0, preset_number); - if (preset_index != -1) - { - c->presetIndex = (unsigned short)preset_index; - return 1; - } - return 0; -} - -TSFDEF int tsf_channel_set_bank(tsf* f, int channel, int bank) -{ - struct tsf_channel *c = tsf_channel_init(f, channel); - if (!c) return 0; - c->bank = (unsigned short)bank; - return 1; -} - -TSFDEF int tsf_channel_set_bank_preset(tsf* f, int channel, int bank, int preset_number) -{ - int preset_index; - struct tsf_channel *c = tsf_channel_init(f, channel); - if (!c) return 0; - preset_index = tsf_get_presetindex(f, bank, preset_number); - if (preset_index == -1) return 0; - c->presetIndex = (unsigned short)preset_index; - c->bank = (unsigned short)bank; - return 1; -} - -TSFDEF int tsf_channel_set_pan(tsf* f, int channel, float pan) -{ - struct tsf_voice *v, *vEnd; - struct tsf_channel *c = tsf_channel_init(f, channel); - if (!c) return 0; - for (v = f->voices, vEnd = v + f->voiceNum; v != vEnd; v++) - if (v->playingChannel == channel && v->playingPreset != -1) - { - float newpan = v->region->pan + pan - 0.5f; - if (newpan <= -0.5f) { v->panFactorLeft = 1.0f; v->panFactorRight = 0.0f; } - else if (newpan >= 0.5f) { v->panFactorLeft = 0.0f; v->panFactorRight = 1.0f; } - else { v->panFactorLeft = TSF_SQRTF(0.5f - newpan); v->panFactorRight = TSF_SQRTF(0.5f + newpan); } - } - c->panOffset = pan - 0.5f; - return 1; -} - -TSFDEF int tsf_channel_set_volume(tsf* f, int channel, float volume) -{ - float gainDB = tsf_gainToDecibels(volume), gainDBChange; - struct tsf_voice *v, *vEnd; - struct tsf_channel *c = tsf_channel_init(f, channel); - if (!c) return 0; - if (gainDB == c->gainDB) return 1; - for (v = f->voices, vEnd = v + f->voiceNum, gainDBChange = gainDB - c->gainDB; v != vEnd; v++) - if (v->playingChannel == channel && v->playingPreset != -1) - v->noteGainDB += gainDBChange; - c->gainDB = gainDB; - return 1; -} - -TSFDEF int tsf_channel_set_pitchwheel(tsf* f, int channel, int pitch_wheel) -{ - struct tsf_channel *c = tsf_channel_init(f, channel); - if (!c) return 0; - if (c->pitchWheel == pitch_wheel) return 1; - c->pitchWheel = (unsigned short)pitch_wheel; - tsf_channel_applypitch(f, channel, c); - return 1; -} - -TSFDEF int tsf_channel_set_pitchrange(tsf* f, int channel, float pitch_range) -{ - struct tsf_channel *c = tsf_channel_init(f, channel); - if (!c) return 0; - if (c->pitchRange == pitch_range) return 1; - c->pitchRange = pitch_range; - if (c->pitchWheel != 8192) tsf_channel_applypitch(f, channel, c); - return 1; -} - -TSFDEF int tsf_channel_set_tuning(tsf* f, int channel, float tuning) -{ - struct tsf_channel *c = tsf_channel_init(f, channel); - if (!c) return 0; - if (c->tuning == tuning) return 1; - c->tuning = tuning; - tsf_channel_applypitch(f, channel, c); - return 1; -} - -TSFDEF int tsf_channel_note_on(tsf* f, int channel, int key, float vel) -{ - if (!f->channels || channel >= f->channels->channelNum) return 1; - f->channels->activeChannel = channel; - return tsf_note_on(f, f->channels->channels[channel].presetIndex, key, vel); -} - -TSFDEF void tsf_channel_note_off(tsf* f, int channel, int key) -{ - struct tsf_voice *v = f->voices, *vEnd = v + f->voiceNum, *vMatchFirst = TSF_NULL, *vMatchLast = TSF_NULL; - for (; v != vEnd; v++) - { - //Find the first and last entry in the voices list with matching channel, key and look up the smallest play index - if (v->playingPreset == -1 || v->playingChannel != channel || v->playingKey != key || v->ampenv.segment >= TSF_SEGMENT_RELEASE) continue; - else if (!vMatchFirst || v->playIndex < vMatchFirst->playIndex) vMatchFirst = vMatchLast = v; - else if (v->playIndex == vMatchFirst->playIndex) vMatchLast = v; - } - if (!vMatchFirst) return; - for (v = vMatchFirst; v <= vMatchLast; v++) - { - //Stop all voices with matching channel, key and the smallest play index which was enumerated above - if (v != vMatchFirst && v != vMatchLast && - (v->playIndex != vMatchFirst->playIndex || v->playingPreset == -1 || v->playingChannel != channel || v->playingKey != key || v->ampenv.segment >= TSF_SEGMENT_RELEASE)) continue; - tsf_voice_end(f, v); - } -} - -TSFDEF void tsf_channel_note_off_all(tsf* f, int channel) -{ - struct tsf_voice *v = f->voices, *vEnd = v + f->voiceNum; - for (; v != vEnd; v++) - if (v->playingPreset != -1 && v->playingChannel == channel && v->ampenv.segment < TSF_SEGMENT_RELEASE) - tsf_voice_end(f, v); -} - -TSFDEF void tsf_channel_sounds_off_all(tsf* f, int channel) -{ - struct tsf_voice *v = f->voices, *vEnd = v + f->voiceNum; - for (; v != vEnd; v++) - if (v->playingPreset != -1 && v->playingChannel == channel && (v->ampenv.segment < TSF_SEGMENT_RELEASE || v->ampenv.parameters.release)) - tsf_voice_endquick(f, v); -} - -TSFDEF int tsf_channel_midi_control(tsf* f, int channel, int controller, int control_value) -{ - struct tsf_channel* c = tsf_channel_init(f, channel); - if (!c) return 0; - switch (controller) - { - case 7 /*VOLUME_MSB*/ : c->midiVolume = (unsigned short)((c->midiVolume & 0x7F ) | (control_value << 7)); goto TCMC_SET_VOLUME; - case 39 /*VOLUME_LSB*/ : c->midiVolume = (unsigned short)((c->midiVolume & 0x3F80) | control_value); goto TCMC_SET_VOLUME; - case 11 /*EXPRESSION_MSB*/ : c->midiExpression = (unsigned short)((c->midiExpression & 0x7F ) | (control_value << 7)); goto TCMC_SET_VOLUME; - case 43 /*EXPRESSION_LSB*/ : c->midiExpression = (unsigned short)((c->midiExpression & 0x3F80) | control_value); goto TCMC_SET_VOLUME; - case 10 /*PAN_MSB*/ : c->midiPan = (unsigned short)((c->midiPan & 0x7F ) | (control_value << 7)); goto TCMC_SET_PAN; - case 42 /*PAN_LSB*/ : c->midiPan = (unsigned short)((c->midiPan & 0x3F80) | control_value); goto TCMC_SET_PAN; - case 6 /*DATA_ENTRY_MSB*/ : c->midiData = (unsigned short)((c->midiData & 0x7F) | (control_value << 7)); goto TCMC_SET_DATA; - case 38 /*DATA_ENTRY_LSB*/ : c->midiData = (unsigned short)((c->midiData & 0x3F80) | control_value); goto TCMC_SET_DATA; - case 0 /*BANK_SELECT_MSB*/ : c->bank = (unsigned short)(0x8000 | control_value); return 1; //bank select MSB alone acts like LSB - case 32 /*BANK_SELECT_LSB*/ : c->bank = (unsigned short)((c->bank & 0x8000 ? ((c->bank & 0x7F) << 7) : 0) | control_value); return 1; - case 101 /*RPN_MSB*/ : c->midiRPN = (unsigned short)(((c->midiRPN == 0xFFFF ? 0 : c->midiRPN) & 0x7F ) | (control_value << 7)); return 1; - case 100 /*RPN_LSB*/ : c->midiRPN = (unsigned short)(((c->midiRPN == 0xFFFF ? 0 : c->midiRPN) & 0x3F80) | control_value); return 1; - case 98 /*NRPN_LSB*/ : c->midiRPN = 0xFFFF; return 1; - case 99 /*NRPN_MSB*/ : c->midiRPN = 0xFFFF; return 1; - case 120 /*ALL_SOUND_OFF*/ : tsf_channel_sounds_off_all(f, channel); return 1; - case 123 /*ALL_NOTES_OFF*/ : tsf_channel_note_off_all(f, channel); return 1; - case 121 /*ALL_CTRL_OFF*/ : - c->midiVolume = c->midiExpression = 16383; - c->midiPan = 8192; - c->bank = 0; - c->midiRPN = 0xFFFF; - c->midiData = 0; - tsf_channel_set_volume(f, channel, 1.0f); - tsf_channel_set_pan(f, channel, 0.5f); - tsf_channel_set_pitchrange(f, channel, 2.0f); - tsf_channel_set_tuning(f, channel, 0); - return 1; - } - return 1; -TCMC_SET_VOLUME: - //Raising to the power of 3 seems to result in a decent sounding volume curve for MIDI - tsf_channel_set_volume(f, channel, TSF_POWF((c->midiVolume / 16383.0f) * (c->midiExpression / 16383.0f), 3.0f)); - return 1; -TCMC_SET_PAN: - tsf_channel_set_pan(f, channel, c->midiPan / 16383.0f); - return 1; -TCMC_SET_DATA: - if (c->midiRPN == 0) tsf_channel_set_pitchrange(f, channel, (c->midiData >> 7) + 0.01f * (c->midiData & 0x7F)); - else if (c->midiRPN == 1) tsf_channel_set_tuning(f, channel, (int)c->tuning + ((float)c->midiData - 8192.0f) / 8192.0f); //fine tune - else if (c->midiRPN == 2 && controller == 6) tsf_channel_set_tuning(f, channel, ((float)control_value - 64.0f) + (c->tuning - (int)c->tuning)); //coarse tune - return 1; -} - -TSFDEF int tsf_channel_get_preset_index(tsf* f, int channel) -{ - return (f->channels && channel < f->channels->channelNum ? f->channels->channels[channel].presetIndex : 0); -} - -TSFDEF int tsf_channel_get_preset_bank(tsf* f, int channel) -{ - return (f->channels && channel < f->channels->channelNum ? (f->channels->channels[channel].bank & 0x7FFF) : 0); -} - -TSFDEF int tsf_channel_get_preset_number(tsf* f, int channel) -{ - return (f->channels && channel < f->channels->channelNum ? f->presets[f->channels->channels[channel].presetIndex].preset : 0); -} - -TSFDEF float tsf_channel_get_pan(tsf* f, int channel) -{ - return (f->channels && channel < f->channels->channelNum ? f->channels->channels[channel].panOffset - 0.5f : 0.5f); -} - -TSFDEF float tsf_channel_get_volume(tsf* f, int channel) -{ - return (f->channels && channel < f->channels->channelNum ? tsf_decibelsToGain(f->channels->channels[channel].gainDB) : 1.0f); -} - -TSFDEF int tsf_channel_get_pitchwheel(tsf* f, int channel) -{ - return (f->channels && channel < f->channels->channelNum ? f->channels->channels[channel].pitchWheel : 8192); -} - -TSFDEF float tsf_channel_get_pitchrange(tsf* f, int channel) -{ - return (f->channels && channel < f->channels->channelNum ? f->channels->channels[channel].pitchRange : 2.0f); -} - -TSFDEF float tsf_channel_get_tuning(tsf* f, int channel) -{ - return (f->channels && channel < f->channels->channelNum ? f->channels->channels[channel].tuning : 0.0f); -} - -#ifdef __cplusplus -} -#endif - -#endif //TSF_IMPLEMENTATION diff --git a/components/darkforces/tfe/TFE_Audio/audioDevice.h b/components/darkforces/tfe/TFE_Audio/audioDevice.h deleted file mode 100644 index ffede656..00000000 --- a/components/darkforces/tfe/TFE_Audio/audioDevice.h +++ /dev/null @@ -1,52 +0,0 @@ -#pragma once -#include -#include -#include "audioOutput.h" -#include - -#ifdef _WIN32 -#define WIN32_LEAN_AND_MEAN 1 -#include - -#define MUTEX_INITIALIZE(A) InitializeCriticalSection(A) -#define MUTEX_DESTROY(A) DeleteCriticalSection(A) -#define MUTEX_LOCK(A) EnterCriticalSection(A) -#define MUTEX_TRYLOCK(A) TryEnterCriticalSection(A) -#define MUTEX_UNLOCK(A) LeaveCriticalSection(A) - -typedef CRITICAL_SECTION Mutex; -#undef min -#undef max -#else -#include - -#include - -#define MUTEX_INITIALIZE(A) pthread_mutex_init(A, NULL) -#define MUTEX_DESTROY(A) pthread_mutex_destroy(A) -#define MUTEX_LOCK(A) pthread_mutex_lock(A) -#define MUTEX_TRYLOCK(A) pthread_mutex_trylock(A) -#define MUTEX_UNLOCK(A) pthread_mutex_unlock(A) - -typedef pthread_mutex_t Mutex; -#endif - -static const u32 AUDIO_STATUS_INPUT_OVERFLOW = 0x1; // Input data was discarded because of an overflow condition at the driver. -static const u32 AUDIO_STATUS_OUTPUT_UNDERFLOW = 0x2; // The output buffer ran low, likely causing a gap in the output sound. - -typedef s32(*StreamCallback)(void* outputBuffer, void* inputBuffer, u32 nFrames, f64 streamTime, u32 status, void* userData); - -namespace TFE_AudioDevice -{ - bool init(u32 audioFrameSize = 256u, s32 deviceId=-1, bool useNullDevice=false); - void destroy(); - - bool startOutput(StreamCallback callback, void* userData = 0, u32 channels = 2, u32 sampleRate = 44100); - void stopOutput(); - - s32 getDefaultOutputDevice(); - s32 getOutputDeviceId(); - s32 getOutputDeviceCount(); - - const OutputDeviceInfo* getOutputDeviceList(s32& count, s32& curOutput); -}; diff --git a/components/darkforces/tfe/TFE_Audio/audioFilters.h b/components/darkforces/tfe/TFE_Audio/audioFilters.h deleted file mode 100644 index 02c3f957..00000000 --- a/components/darkforces/tfe/TFE_Audio/audioFilters.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once -#include - -enum AudioUpsampleFilter -{ - AUF_NONE = 0, - AUF_LINEAR, - AUF_COUNT, - AUF_DEFAULT = AUF_LINEAR -}; - -namespace TFE_Audio -{ - void upsample4x_point(f32* output, const f32* input, s32 inputSampleCount); - void upsample4x_linear(f32* output, const f32* input, s32 inputSampleCount); -} diff --git a/components/darkforces/tfe/TFE_Audio/audioOutput.h b/components/darkforces/tfe/TFE_Audio/audioOutput.h deleted file mode 100644 index f50a0be4..00000000 --- a/components/darkforces/tfe/TFE_Audio/audioOutput.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once -#include -#include - -struct OutputDeviceInfo -{ - std::string name; - u32 id; -}; \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Audio/audioSystem.h b/components/darkforces/tfe/TFE_Audio/audioSystem.h deleted file mode 100644 index 0202b0fc..00000000 --- a/components/darkforces/tfe/TFE_Audio/audioSystem.h +++ /dev/null @@ -1,99 +0,0 @@ -#pragma once -#include -#include -#include "audioOutput.h" -#include "audioFilters.h" - -// Source data type. The sound data will be converted to float time during mixing. -enum SoundDataType -{ - SOUND_DATA_8BIT = 0, - SOUND_DATA_16BIT, - SOUND_DATA_FLOAT, -}; - -// Optional sound buffer flags, not used by the audio system directly but may be set by the assets - -// VOC files have loops points embedded for example. -enum SoundBufferFlags -{ - SBUFFER_FLAG_NONE = 0, - SBUFFER_FLAG_LOOPING = (1 << 0), -}; - -struct SoundBuffer -{ - SoundDataType type; - u32 id = 0; // Used by the asset system. - u32 flags; - u32 size; - u32 sampleRate; - u32 loopStart; - u32 loopEnd; - - u8* data; -}; - -struct SoundSource; -// Type of sound effect, used for sources. -// This determines how source simulation is handled. -enum SoundType -{ - SOUND_2D = 0, // Mono 2D sound effect. - SOUND_3D, // 3D positional sound effect. -}; - -#define MONO_SEPERATION 0.5f -#define MAX_SOUND_SOURCES 128 - -typedef void(*SoundFinishedCallback)(void* userData, s32 arg); -typedef void(*AudioThreadCallback)(f32* buffer, u32 bufferSize, f32 systemVolume); - -namespace TFE_Audio -{ - // constants - // Attenuation factors. Sounds closer than c_closeDistance are played at full volume and sounds farther than c_clipDistance are clipped. - // The system smoothly interpolates between the extremes. - static const f32 c_closeDistance = 20.0f; - static const f32 c_clipDistance = 140.0f; - - // functions - bool init(bool useNullDevice = false, s32 outputId = -1); - void shutdown(); - void stopAllSounds(); - void selectDevice(s32 id); - - void setUpsampleFilter(AudioUpsampleFilter filter = AUF_DEFAULT); - AudioUpsampleFilter getUpsampleFilter(); - - void setVolume(f32 volume); - f32 getVolume(); - void pause(); - void resume(); - - void lock(); - void unlock(); - - void bufferedAudioClear(); - - void setAudioThreadCallback(AudioThreadCallback callback = nullptr); - const OutputDeviceInfo* getOutputDeviceList(s32& count, s32& curOutput); - - // One shot, play and forget. Only do this if the client needs no control until stopAllSounds() is called. - // Note that looping one shots are valid though may generate too many sound sources if not used carefully. - bool playOneShot(SoundType type, f32 volume, const SoundBuffer* buffer, bool looping, - SoundFinishedCallback finishedCallback = nullptr, void* cbUserData = nullptr, s32 cbArg = 0); - - // Sound source that the client holds onto. - SoundSource* createSoundSource(SoundType type, f32 volume, const SoundBuffer* buffer, SoundFinishedCallback callback = nullptr, void* userData = nullptr); - void playSource(SoundSource* source, bool looping = false); - void stopSource(SoundSource* source); - void freeSource(SoundSource* source); - void setSourceVolume(SoundSource* source, f32 volume); - // This will restart the sound and change the buffer. - void setSourceBuffer(SoundSource* source, const SoundBuffer* buffer); - - bool isSourcePlaying(SoundSource* source); - f32 getSourceVolume(SoundSource* source); - s32 getSourceSlot(SoundSource* source); - SoundSource* getSourceFromSlot(s32 slot); -} diff --git a/components/darkforces/tfe/TFE_Audio/midi.h b/components/darkforces/tfe/TFE_Audio/midi.h deleted file mode 100644 index f4c7b653..00000000 --- a/components/darkforces/tfe/TFE_Audio/midi.h +++ /dev/null @@ -1,139 +0,0 @@ -#pragma once - -// Midi Message = MidiMessageType + Channel, data byte 1, data byte 2 -// Examples assume: u8 channelId = 0x00 - 0x0f (16 channels) -// Example: TFE_MidiDevice::sendMessage(MID_NOTE_ON + channelId, note, velocity); -// TFE_MidiDevice::sendMessage(MID_CONTROL_CHANGE + channelId, MID_VOLUME_MSB, 100); - -#define CHANNEL_MAX_VOLUME 127 - -// Channel message type -enum MidiMessageType -{ - // Channel (0x00 - 0x0f) // Data 1, Data 2 - MID_NOTE_OFF = 0x80, // Note Number, Velocity - MID_NOTE_ON = 0x90, // Note Number, Velocity - MID_KEY_PRESSURE = 0xA0, // Note Number, Pressure - MID_CONTROL_CHANGE = 0xB0, // Controller Number (see MidiController below), Data - MID_PROGRAM_CHANGE = 0xC0, // Program Number, Unused - MID_CHANNEL_PRESSURE = 0xD0, // Pressure, Unused - MID_PITCH_BEND = 0xE0, // LSB, MSB - // System - MID_EXCLUSIVE_START = 0xF0, // Manufacturers ID, data - MID_QUARTER_FRAME = 0xF1, // Data, ... - MID_SONG_POINTER = 0xF2, // LSB, MSB - MID_SONG_SELECT = 0xF3, // Song Number - MID_TUNE_REQUEST = 0xF6, - MID_EXCLUSIVE_END = 0xF7, - MID_TIMING_CLOCK = 0xF8, - MID_MEASURE_END = 0xF9, - MID_START = 0xFA, - MID_CONTINUE = 0xFB, - MID_STOP = 0xFC, - MID_ACTIVE_SENSING = 0xFE, - MID_RESET = 0xFF, -}; - -enum MetaType -{ - META_SEQ_NUMBER = 0x00, - META_TEXT_EVENT, - META_COPYRIGHT_NOTICE, - META_SEQ_NAME, - META_INSTR_NAME, - META_LYRIC_TEXT, - META_MARKER_TEXT, - META_CUE_POINT, - META_MIDI_CHANNEL_PREFIX = 0x20, - META_END_OF_TRACK = 0x2f, - META_TEMPO = 0x51, - META_SMPTE_OFFSET = 0x54, - META_TIME_SIG = 0x58, - META_KEY_SIG = 0x59, - META_SEQ_SPECIFIC = 0x7f -}; - -// Midi controller numbers -enum MidiController -{ - MID_BANK_SELECT_MSB = 0, - MID_MODULATIONWHEEL_MSB, - MID_BREATH_MSB, - MID_FOOT_MSB = 4, - MID_PORTAMENTO_TIME_MSB, - MID_DATA_ENTRY_MSB, - MID_VOLUME_MSB, - MID_BALANCE_MSB, - MID_PAN_MSB = 10, - MID_EXPRESSION_MSB, - MID_EFFECTS1_MSB, - MID_EFFECTS2_MSB, - MID_GPC1_MSB = 16, - MID_GPC2_MSB, - MID_GPC3_MSB, - MID_GPC4_MSB, - MID_BANK_SELECT_LSB = 32, - MID_MODULATIONWHEEL_LSB, - MID_BREATH_LSB, - MID_FOOT_LSB = 36, - MID_PORTAMENTO_TIME_LSB, - MID_DATA_ENTRY_LSB, - MID_VOLUME_LSB, - MID_BALANCE_LSB, - MID_PAN_LSB = 42, - MID_EXPRESSION_LSB, - MID_EFFECTS1_LSB, - MID_EFFECTS2_LSB, - MID_GPC1_LSB = 48, - MID_GPC2_LSB, - MID_GPC3_LSB, - MID_GPC4_LSB, - MID_SUSTAIN_SWITCH = 64, - MID_PORTAMENTO_SWITCH, - MID_SOSTENUTO_SWITCH, - MID_SOFT_PEDAL_SWITCH, - MID_LEGATO_SWITCH, - MID_HOLD2_SWITCH, - MID_SOUND_CTRL1, - MID_SOUND_CTRL2, - MID_SOUND_CTRL3, - MID_SOUND_CTRL4, - MID_SOUND_CTRL5, - MID_SOUND_CTRL6, - MID_SOUND_CTRL7, - MID_SOUND_CTRL8, - MID_SOUND_CTRL9, - MID_SOUND_CTRL10, - MID_GPC5, - MID_GPC6, - MID_GPC7, - MID_GPC8, - MID_PORTAMENTO_CTRL, - MID_FX_REVERB = 91, - MID_FX_TREMOLO, - MID_FX_CHORUS, - MID_FX_CELESTE_DETUNE, - MID_FX_PHASER, - MID_DATA_ENTRY_INCR, - MID_DATA_ENTRY_DECR, - MID_NRPN_LSB, - MID_NRPN_MSB, - MID_RPN_LSB, - MID_RPN_MSB, - MID_ALL_SOUND_OFF = 120, - MID_ALL_CTRL_OFF, - MID_LOCAL_CONTROL, - MID_ALL_NOTES_OFF, - MID_OMNI_OFF, - MID_OMNI_ON, - MID_POLY_OFF, - MID_POLY_ON -}; - -enum MidiInstruments -{ - // General midi supports instruments 0 - 127 - MIDI_INSTRUMENT_COUNT = 128, - // General midi supports 16 channels (also called "voices") - MIDI_CHANNEL_COUNT = 16, -}; diff --git a/components/darkforces/tfe/TFE_Audio/midiDevice.h b/components/darkforces/tfe/TFE_Audio/midiDevice.h deleted file mode 100644 index 77577a38..00000000 --- a/components/darkforces/tfe/TFE_Audio/midiDevice.h +++ /dev/null @@ -1,50 +0,0 @@ -#pragma once -#include -#include - -enum MidiDeviceType -{ - MIDI_TYPE_SYSTEM = 0, // System midi device (hardware, midi server, GM midi on Windows). - MIDI_TYPE_SF2, // Use the Sound Font 2 (SF2) midi synthesizer. - MIDI_TYPE_OPL3, // Use OPL3 emulation (like DosBox). - MIDI_TYPE_COUNT, - MIDI_TYPE_DEFAULT = MIDI_TYPE_OPL3 -}; - -// On the ESP32 the synthesizers render 16-bit integer stereo samples directly -// (no floating point mixing stage). -#ifdef TFE_ESPBOX -typedef s16 MidiSample; -#else -typedef f32 MidiSample; -#endif - -namespace TFE_Audio -{ - class MidiDevice - { - public: - MidiDevice() {} - virtual ~MidiDevice() {} - - virtual MidiDeviceType getType() = 0; - - virtual void exit() = 0; - virtual bool hasGlobalVolumeCtrl() = 0; - virtual const char* getName() = 0; - - virtual u32 getOutputCount() = 0; - virtual void getOutputName(s32 index, char* buffer, u32 maxLength) = 0; - virtual bool selectOutput(s32 index) = 0; - virtual s32 getActiveOutput(void) = 0; - - virtual bool render(MidiSample* buffer, u32 sampleCount) = 0; - virtual bool canRender() = 0; - - virtual void message(u8 type, u8 arg1, u8 arg2 = 0) = 0; - virtual void message(const u8* msg, u32 len) = 0; - - virtual void noteAllOff() = 0; - virtual void setVolume(f32 volume) = 0; - }; -}; diff --git a/components/darkforces/tfe/TFE_Audio/midiPlayer.cpp b/components/darkforces/tfe/TFE_Audio/midiPlayer.cpp deleted file mode 100644 index 813fffcc..00000000 --- a/components/darkforces/tfe/TFE_Audio/midiPlayer.cpp +++ /dev/null @@ -1,609 +0,0 @@ -#include "midiPlayer.h" -#include -#include "midiDevice.h" -#include "audioDevice.h" -#include "systemMidiDevice.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef _WIN32 -#define WIN32_LEAN_AND_MEAN 1 -#include -#undef min -#undef max -#endif - -using namespace TFE_Audio; - -namespace TFE_MidiPlayer -{ - enum MidiPlayerCmd - { - MIDI_PAUSE, - MIDI_RESUME, - MIDI_CHANGE_VOL, - MIDI_STOP_NOTES, - MIDI_COUNT - }; - - struct MidiCmd - { - MidiPlayerCmd cmd; - f32 newVolume; - }; - - enum { MAX_MIDI_CMD = 256 }; -#ifdef TFE_ESPBOX - static MidiCmd* s_midiCmdBuffer = nullptr; // MAX_MIDI_CMD entries (shared memory) -#else - static MidiCmd s_midiCmdBuffer[MAX_MIDI_CMD]; -#endif - static u32 s_midiCmdCount = 0; - static f64 s_maxNoteLength = 16.0; // defaults to 16 seconds. - - struct MidiCallback - { - void(*callback)(void) = nullptr; // callback function to call. - f64 timeStep = 0.0; // delay between calls, this acts like an interrupt handler. - f64 accumulator = 0.0; // current accumulator. - }; - - static const f32 c_musicVolumeScale = 0.75f; - static f32 s_masterVolume = 1.0f; - static f32 s_masterVolumeScaled = s_masterVolume * c_musicVolumeScale; - static Thread* s_thread = nullptr; - -#ifdef TFE_ESPBOX - static bool s_runMusicThread; -#else - static atomic_bool s_runMusicThread; -#endif - static u8 s_channelSrcVolume[MIDI_CHANNEL_COUNT] = { 0 }; - static Mutex s_mutex; - - static MidiDevice* s_midiDevice = nullptr; - static MidiCallback s_midiCallback = {}; - - static std::vector s_sampleBuffer; - static MidiSample* s_sampleBufferPtr = nullptr; - - // Hanging note detection. - struct Instrument - { - u32 channelMask; - f64 time[MIDI_CHANNEL_COUNT]; - }; -#ifdef TFE_ESPBOX - static Instrument* s_instrOn = nullptr; // MIDI_INSTRUMENT_COUNT entries (shared memory) -#else - static Instrument s_instrOn[MIDI_INSTRUMENT_COUNT] = { 0 }; -#endif - static f64 s_curNoteTime = 0.0; - - TFE_THREADRET midiUpdateFunc(void* userData); - void stopAllNotes(); - void changeVolume(); - void allocateMidiDevice(MidiDeviceType type); - - // Console Functions - void setMusicVolumeConsole(const ConsoleArgList& args); - void getMusicVolumeConsole(const ConsoleArgList& args); - - static const char* c_midiDeviceTypes[] = - { - "System Midi", // MIDI_TYPE_SYSTEM - "SF2 Synthesized Midi", // MIDI_TYPE_SF2 - "OPL3 Synthesized Midi",// MIDI_TYPE_OPL3 - }; - - bool init(s32 midiDeviceIndex, MidiDeviceType type) - { - TFE_System::logWrite(LOG_MSG, "Startup", "TFE_MidiPlayer::init"); - - bool res = false; - allocateMidiDevice(type); - - if (s_midiDevice) - { - res = true; - if (!s_midiDevice->selectOutput(midiDeviceIndex)) - { - if (!s_midiDevice->selectOutput(0)) - { - TFE_System::logWrite(LOG_ERROR, "Midi", "Cannot load soundfont '%s'.", "SoundFonts/SYNTHGM.sf2"); - res = false; - } - } - } - -#ifdef TFE_ESPBOX - s_runMusicThread = true; - if (!res) - { - // TODO this is a bit of a hack to let the MIDI thread sleep - allocateMidiDevice(MIDI_TYPE_COUNT); - } -#else - s_runMusicThread.store(true); -#endif - MUTEX_INITIALIZE(&s_mutex); - - s_thread = Thread::create("MidiThread", midiUpdateFunc, nullptr); - if (s_thread) - { - s_thread->run(); - } - - CCMD("setMusicVolume", setMusicVolumeConsole, 1, "Sets the music volume, range is 0.0 to 1.0"); - CCMD("getMusicVolume", getMusicVolumeConsole, 0, "Get the current music volume where 0 = silent, 1 = maximum."); - - TFE_Settings_Sound* soundSettings = TFE_Settings::getSoundSettings(); - setVolume(soundSettings->musicVolume); - setMaximumNoteLength(); - - return res && s_thread; - } - - void destroy() - { - TFE_System::logWrite(LOG_MSG, "MidiPlayer", "Shutdown"); - // Destroy the thread before shutting down the Midi Device. -#ifdef TFE_ESPBOX - s_runMusicThread = false; -#else - s_runMusicThread.store(false); -#endif - if (s_thread->isPaused()) - { - s_thread->resume(); - } - s_thread->waitOnExit(); - - delete s_thread; - delete s_midiDevice; -#ifdef TFE_ESPBOX - s_thread = nullptr; - s_midiDevice = nullptr; -#endif - - MUTEX_DESTROY(&s_mutex); - } - - MidiDevice* getMidiDevice() - { - return s_midiDevice; - } - - const char* getMidiDeviceTypeName(MidiDeviceType type) - { - return c_midiDeviceTypes[type]; - } - - void setDeviceType(MidiDeviceType type) - { - allocateMidiDevice(type); - if (s_midiDevice) - { - if (!s_midiDevice->selectOutput(-1)) // -1 will select the default. - { - TFE_System::logWrite(LOG_ERROR, "Midi", "Cannot select midi output."); - } - } - } - - MidiDeviceType getDeviceType() - { - if (s_midiDevice) - { - return s_midiDevice->getType(); - } - return MIDI_TYPE_DEFAULT; - } - - ////////////////////////////////////////////////// - // Command Buffer - ////////////////////////////////////////////////// - MidiCmd* midiAllocCmd() - { - if (s_midiCmdCount >= MAX_MIDI_CMD) { return nullptr; } - MidiCmd* cmd = &s_midiCmdBuffer[s_midiCmdCount]; - s_midiCmdCount++; - return cmd; - } - - void midiClearCmdBuffer() - { - s_midiCmdCount = 0; - } - - ////////////////////////////////////////////////// - // Command Interface - ////////////////////////////////////////////////// - void setVolume(f32 volume) - { - MUTEX_LOCK(&s_mutex); - MidiCmd* midiCmd = midiAllocCmd(); - if (midiCmd) - { - midiCmd->cmd = MIDI_CHANGE_VOL; - midiCmd->newVolume = volume; - } - MUTEX_UNLOCK(&s_mutex); - } - - // Set the length in seconds that a note is allowed to play for in seconds. - void setMaximumNoteLength(f32 dt) - { - s_maxNoteLength = f64(dt); - } - - void pauseThread() - { - if (s_thread) - { - s_thread->pause(); - } - } - - void resumeThread() - { - if (s_thread) - { - s_thread->resume(); - } - } - - void pause() - { - MUTEX_LOCK(&s_mutex); - MidiCmd* midiCmd = midiAllocCmd(); - if (midiCmd) - { - midiCmd->cmd = MIDI_PAUSE; - } - MUTEX_UNLOCK(&s_mutex); - } - - void resume() - { - MUTEX_LOCK(&s_mutex); - MidiCmd* midiCmd = midiAllocCmd(); - if (midiCmd) - { - midiCmd->cmd = MIDI_RESUME; - } - MUTEX_UNLOCK(&s_mutex); - } - - void stopMidiSound() - { - MUTEX_LOCK(&s_mutex); - MidiCmd* midiCmd = midiAllocCmd(); - if (midiCmd) - { - midiCmd->cmd = MIDI_STOP_NOTES; - } - MUTEX_UNLOCK(&s_mutex); - } - - void synthesizeMidi(MidiSample* buffer, u32 stereoSampleCount, bool updateBuffer) - { - // In some cases, such as when using the System Midi Device, the midi audio is generated externally so - // rendering is not required. - if (s_midiDevice && s_midiDevice->canRender()) - { -#ifdef TFE_ESPBOX - MUTEX_LOCK(&s_mutex); - if (s_midiDevice && s_midiDevice->canRender()) - { - s_midiDevice->render(buffer, stereoSampleCount); - } - MUTEX_UNLOCK(&s_mutex); -#else - // Stereo samples -> actual samples. - const s32 linearSampleCount = (s32)stereoSampleCount * 2; - // Make sure the sample buffer is large enough, this should only happen once. - if (linearSampleCount > (s32)s_sampleBuffer.size() || !s_sampleBufferPtr) - { - s_sampleBuffer.resize(linearSampleCount); - s_sampleBufferPtr = s_sampleBuffer.data(); - } - - MUTEX_LOCK(&s_mutex); - // This is checked again, in case it was immediately changed in another thread; such as when changing midi devices or outputs. - if (s_midiDevice && s_midiDevice->canRender()) - { - // The midi device takes the number of stereo samples. - s_midiDevice->render(s_sampleBufferPtr, stereoSampleCount); - // Accumulate midi samples with existing audio samples (from soundFX). - if (updateBuffer) - { - for (s32 i = 0; i < linearSampleCount; i++) - { - buffer[i] += s_sampleBufferPtr[i]; - } - } - } - MUTEX_UNLOCK(&s_mutex); -#endif - } - } - - f32 getVolume() - { - return s_masterVolume; - } - - void midiSetCallback(void(*callback)(void), f64 timeStep) - { - MUTEX_LOCK(&s_mutex); - s_midiCallback.callback = callback; - s_midiCallback.timeStep = timeStep; - s_midiCallback.accumulator = 0.0; - - for (u32 i = 0; i < MIDI_CHANNEL_COUNT; i++) - { - s_channelSrcVolume[i] = CHANNEL_MAX_VOLUME; - } - changeVolume(); - MUTEX_UNLOCK(&s_mutex); - } - - void midiClearCallback() - { - MUTEX_LOCK(&s_mutex); - s_midiCallback.callback = nullptr; - s_midiCallback.timeStep = 0.0; - s_midiCallback.accumulator = 0.0; - MUTEX_UNLOCK(&s_mutex); - } - - ////////////////////////////////////////////////// - // Internal - ////////////////////////////////////////////////// - void changeVolume() - { - if (s_midiDevice && s_midiDevice->hasGlobalVolumeCtrl()) - { - s_midiDevice->setVolume(s_masterVolumeScaled); - } - else if (s_midiDevice) - { - for (u32 i = 0; i < MIDI_CHANNEL_COUNT; i++) - { - s_midiDevice->message(MID_CONTROL_CHANGE + i, MID_VOLUME_MSB, u8(s_channelSrcVolume[i] * s_masterVolumeScaled)); - } - } - } - - void stopAllNotes() - { - // Some devices don't support "all notes off" - so do it manually. - for (s32 i = 0; i < MIDI_INSTRUMENT_COUNT; i++) - { - // Skip any instruments not being used. - if (!s_instrOn[i].channelMask) { continue; } - - // Look for used channels. - for (u32 c = 0; c < MIDI_CHANNEL_COUNT; c++) - { - const u32 channelMask = 1u << c; - if (s_instrOn[i].channelMask & channelMask) - { - // Turn off the note. - if (s_midiDevice) { s_midiDevice->message(MID_NOTE_OFF | c, i); } - - // Reset the instrument channel information. - s_instrOn[i].channelMask &= ~channelMask; - s_instrOn[i].time[c] = 0.0; - } - } - } - - if (s_midiDevice) { s_midiDevice->noteAllOff(); } - memset(s_instrOn, 0, sizeof(Instrument) * MIDI_INSTRUMENT_COUNT); - s_curNoteTime = 0.0; - } - - void sendMessageDirect(u8 type, u8 arg1, u8 arg2) - { - u8 msg[] = { type, arg1, arg2 }; - u8 msgType = (type & 0xf0); - u8 len; - - len = (msgType == MID_PROGRAM_CHANGE) ? 2 : 3; - - if (msgType == MID_CONTROL_CHANGE && arg1 == MID_VOLUME_MSB && s_midiDevice && !s_midiDevice->hasGlobalVolumeCtrl()) - { - const s32 channelIndex = type & 0x0f; - s_channelSrcVolume[channelIndex] = arg2; - msg[2] = u8(s_channelSrcVolume[channelIndex] * s_masterVolumeScaled); - } - if (s_midiDevice) { s_midiDevice->message(msg, len); } - - // Record currently playing instruments and the note-on times. - if (msgType == MID_NOTE_OFF || msgType == MID_NOTE_ON) - { - const u8 instr = arg1; - const u8 channel = type & 0x0f; - if (msgType == MID_NOTE_OFF || (msgType == MID_NOTE_ON && arg2 == 0)) // note on + velocity = 0 is the same as note off. - { - s_instrOn[instr].channelMask &= ~(1 << channel); - s_instrOn[instr].time[channel] = 0.0; - } - else // MID_NOTE_ON - { - s_instrOn[instr].channelMask |= (1 << channel); - s_instrOn[instr].time[channel] = s_curNoteTime; - } - } - } - - void detectHangingNotes() - { - for (s32 i = 0; i < MIDI_INSTRUMENT_COUNT; i++) - { - // Skip any instruments not being used. - if (!s_instrOn[i].channelMask) { continue; } - - // Look for used channels. - for (u32 c = 0; c < MIDI_CHANNEL_COUNT; c++) - { - const u32 channelMask = 1u << c; - if ((s_instrOn[i].channelMask & channelMask) && (s_curNoteTime - s_instrOn[i].time[c] > s_maxNoteLength)) - { - // Turn off the note. - sendMessageDirect(MID_NOTE_OFF | c, i); - - // Reset the instrument channel information. - s_instrOn[i].channelMask &= ~channelMask; - s_instrOn[i].time[c] = 0.0; - } - } - } - } - - // Thread Function - TFE_THREADRET midiUpdateFunc(void* userData) - { - bool runThread = true; - bool wasPlaying = false; - bool isPlaying = false; - bool isPaused = false; - s32 loopStart = -1; - u64 localTime = 0; - u64 localTimeCallback = 0; - f64 dt = 0.0; - while (runThread) - { - MUTEX_LOCK(&s_mutex); - - // Read from the command buffer. - MidiCmd* midiCmd = s_midiCmdBuffer; - for (u32 i = 0; i < s_midiCmdCount; i++, midiCmd++) - { - switch (midiCmd->cmd) - { - case MIDI_PAUSE: - { - localTimeCallback = 0; - isPaused = true; - stopAllNotes(); - } break; - case MIDI_RESUME: - { - isPaused = false; - } break; - case MIDI_CHANGE_VOL: - { - s_masterVolume = midiCmd->newVolume; - s_masterVolumeScaled = s_masterVolume * c_musicVolumeScale; - changeVolume(); - } break; - case MIDI_STOP_NOTES: - { - stopAllNotes(); - // Reset callback time. - localTimeCallback = 0; - s_midiCallback.accumulator = 0.0; - } break; - } - } - s_midiCmdCount = 0; - - // Process the midi callback, if it exists. -#ifdef TFE_ESPBOX - if (!s_midiDevice) isPaused = true; -#endif - if (s_midiCallback.callback && !isPaused) - { - s_midiCallback.accumulator += TFE_System::updateThreadLocal(&localTimeCallback); - while (s_midiCallback.callback && s_midiCallback.accumulator >= s_midiCallback.timeStep) - { - s_midiCallback.callback(); - s_midiCallback.accumulator -= s_midiCallback.timeStep; - s_curNoteTime += s_midiCallback.timeStep; - } - - // Check for hanging notes. - detectHangingNotes(); - } - MUTEX_UNLOCK(&s_mutex); -#ifdef TFE_ESPBOX - // Sleep between updates so the thread doesn't spin (iMuse runs at ~144Hz, FreeRTOS tick is 1ms). - TFE_System::sleep((s_midiCallback.callback && !isPaused) ? 2 : 50); -#endif -#ifdef TFE_ESPBOX - runThread = s_runMusicThread; -#else - runThread = s_runMusicThread.load(); -#endif - }; - - return (TFE_THREADRET)0; - } - - // Console Functions - void setMusicVolumeConsole(const ConsoleArgList& args) - { - if (args.size() < 2) { return; } - f32 volume = TFE_Console::getFloatArg(args[1]); - setVolume(volume); - - TFE_Settings_Sound* soundSettings = TFE_Settings::getSoundSettings(); - soundSettings->musicVolume = volume; - TFE_Settings::writeToDisk(); - } - - void getMusicVolumeConsole(const ConsoleArgList& args) - { - char res[256]; - sprintf(res, "Sound Volume: %2.3f", s_masterVolume); - TFE_Console::addToHistory(res); - } - - void allocateMidiDevice(MidiDeviceType type) - { - delete s_midiDevice; - s_midiDevice = nullptr; - - switch (type) - { - case MIDI_TYPE_SYSTEM: - s_midiDevice = new SystemMidiDevice(); - break; - case MIDI_TYPE_SF2: - s_midiDevice = new SoundFontDevice(); - break; - case MIDI_TYPE_OPL3: - s_midiDevice = new Fm4Opl3Device(); - break; - default: - TFE_System::logWrite(LOG_ERROR, "Midi", "Invalid midi type selected: %d", (s32)type); - } - } -} - -#ifdef TFE_ESPBOX -void espbox_shared_midiPlayer(bool alloc) -{ - ESPBOX_SHARED_ALLOC(TFE_MidiPlayer::s_midiCmdBuffer, TFE_MidiPlayer::MAX_MIDI_CMD); - ESPBOX_SHARED_ALLOC(TFE_MidiPlayer::s_instrOn, MIDI_INSTRUMENT_COUNT); -} -#endif - -#ifdef TFE_ESPBOX -// Shutdown only: release this file's cached container storage so nothing is -// left in the 4MB ROM block when the session ends (see esp_alloc.cpp). -void espbox_release_midiPlayer_caches() -{ - std::vector().swap(TFE_MidiPlayer::s_sampleBuffer); -} -#endif diff --git a/components/darkforces/tfe/TFE_Audio/midiPlayer.h b/components/darkforces/tfe/TFE_Audio/midiPlayer.h deleted file mode 100644 index a2efcd26..00000000 --- a/components/darkforces/tfe/TFE_Audio/midiPlayer.h +++ /dev/null @@ -1,52 +0,0 @@ -#pragma once -#include -#include "midiDevice.h" -struct GMidiAsset; - -namespace TFE_MidiPlayer -{ - bool init(s32 midiDeviceIndex, MidiDeviceType type = MIDI_TYPE_SYSTEM); - void setDeviceType(MidiDeviceType type); - MidiDeviceType getDeviceType(); - void destroy(); - - TFE_Audio::MidiDevice* getMidiDevice(); - const char* getMidiDeviceTypeName(MidiDeviceType type); - - /////////////////////////////////////////////////////////// - // Commands - // Commands are queued for processing by the midi thread. - /////////////////////////////////////////////////////////// - - // Change the overall music volume. - void setVolume(f32 volume); - // Set the maximum length in seconds that a note is allowed to play for in seconds. - void setMaximumNoteLength(f32 dt = 16.0f); - - // Send a direct midi message. - // Note: this should be called from the midi thread. - void sendMessageDirect(u8 type, u8 arg1=0, u8 arg2=0); - - // Callback - void midiSetCallback(void(*callback)(void) = nullptr, f64 timeStep = 0.0); - void midiClearCallback(); - - void pauseThread(); - void resumeThread(); - - // Pause the midi player, which also stops all sound channels. - void pause(); - // Resume midi playback from where it left off. - void resume(); - // Stop all notes. - void stopMidiSound(); - - void synthesizeMidi(MidiSample* buffer, u32 stereoSampleCount, bool updateBuffer = true); - - /////////////////////////////////////////////////////////// - // Reads - // Reads are not synced, so there may be latency in the - // results if not being read from an iMuse callback. - /////////////////////////////////////////////////////////// - f32 getVolume(); -}; diff --git a/components/darkforces/tfe/TFE_Audio/systemMidiDevice.h b/components/darkforces/tfe/TFE_Audio/systemMidiDevice.h deleted file mode 100644 index 9c736138..00000000 --- a/components/darkforces/tfe/TFE_Audio/systemMidiDevice.h +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once -#include -#include "midiDevice.h" - -class RtMidiOut; - -namespace TFE_Audio -{ - class SystemMidiDevice : public MidiDevice - { - public: - SystemMidiDevice(); - ~SystemMidiDevice() override; - - MidiDeviceType getType() override { return MIDI_TYPE_SYSTEM; } - - void exit() override; - // The system device does not have proper global volume control. - bool hasGlobalVolumeCtrl() override { return false; } - const char* getName() override; - - // The System Midi device outputs commands to midi hardware or external programs and so never renders sound to the audio thread. - bool render(MidiSample* buffer, u32 sampleCount) override { return false; } - bool canRender() override { return false; } - - void message(u8 type, u8 arg1, u8 arg2) override; - void message(const u8* msg, u32 len) override; - void noteAllOff() override; - void setVolume(f32 volume) override; - - u32 getOutputCount() override; - void getOutputName(s32 index, char* buffer, u32 maxLength) override; - bool selectOutput(s32 index) override; - s32 getActiveOutput(void) override; - - private: - RtMidiOut* m_midiout; - - s32 m_outputId; - FileList m_outputs; - }; -} diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/actor.cpp b/components/darkforces/tfe/TFE_DarkForces/Actor/actor.cpp deleted file mode 100644 index bcbb16c0..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/actor.cpp +++ /dev/null @@ -1,2144 +0,0 @@ -#include - -#include "actor.h" -#include "actorInternal.h" -#include "../logic.h" -#include "../gameMusic.h" -#include "../sound.h" -#include "animTables.h" -#include "actorModule.h" -#include "mousebot.h" -#include "dragon.h" -#include "bobaFett.h" -#include "welder.h" -#include "turret.h" -#include "phaseOne.h" -#include "phaseTwo.h" -#include "phaseThree.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - /////////////////////////////////////////// - // Internal State - /////////////////////////////////////////// - ActorInternalState s_istate = { 0 }; - List* s_physicsActors = nullptr; - - /////////////////////////////////////////// - // Shared State - /////////////////////////////////////////// - ActorState s_actorState = { 0 }; - SoundSourceId s_alertSndSrc[ALERT_COUNT]; - SoundSourceId s_officerAlertSndSrc[OFFICER_ALERT_COUNT]; - SoundSourceId s_stormAlertSndSrc[STORM_ALERT_COUNT]; - SoundSourceId s_agentSndSrc[AGENTSND_COUNT]; - - /////////////////////////////////////////// - // Forward Declarations - /////////////////////////////////////////// - void actorLogicTaskFunc(MessageType msg); - void actorLogicMsgFunc(MessageType msg); - void actorPhysicsTaskFunc(MessageType msg); - u32 actorLogicSetupFunc(Logic* logic, KEYWORD key); - - extern ThinkerModule* actor_createFlyingModule(Logic* logic); - extern ThinkerModule* actor_createFlyingModule_Remote(Logic* logic); - - /////////////////////////////////////////// - // API Implementation - /////////////////////////////////////////// - void actor_clearState() - { - memset(&s_istate, 0, sizeof(ActorInternalState)); - memset(&s_actorState, 0, sizeof(ActorState)); - s_istate.objCollisionEnabled = JTRUE; - list_clear(s_physicsActors); - - // Clear specific actor state. - mousebot_clear(); - welder_clear(); - } - - void actor_exitState() - { - actor_clearState(); - phaseOne_exit(); - phaseTwo_exit(); - phaseThree_exit(); - bobaFett_exit(); - kellDragon_exit(); - mousebot_exit(); - turret_exit(); - welder_exit(); - } - - void actor_loadSounds() - { - s_alertSndSrc[ALERT_GAMOR] = sound_load("gamor-3.voc", SOUND_PRIORITY_MED5); - s_alertSndSrc[ALERT_REEYEE] = sound_load("reeyee-1.voc", SOUND_PRIORITY_MED5); - s_alertSndSrc[ALERT_BOSSK] = sound_load("bossk-1.voc", SOUND_PRIORITY_MED5); - s_alertSndSrc[ALERT_CREATURE] = sound_load("creatur1.voc", SOUND_PRIORITY_MED5); - s_alertSndSrc[ALERT_PROBE] = sound_load("probe-1.voc", SOUND_PRIORITY_MED5); - s_alertSndSrc[ALERT_INTDROID] = sound_load("intalert.voc", SOUND_PRIORITY_MED5); - - s_officerAlertSndSrc[0] = sound_load("ranofc02.voc", SOUND_PRIORITY_MED5); - s_officerAlertSndSrc[1] = sound_load("ranofc04.voc", SOUND_PRIORITY_MED5); - s_officerAlertSndSrc[2] = sound_load("ranofc05.voc", SOUND_PRIORITY_MED5); - s_officerAlertSndSrc[3] = sound_load("ranofc06.voc", SOUND_PRIORITY_MED5); - - s_stormAlertSndSrc[0] = sound_load("ransto01.voc", SOUND_PRIORITY_MED5); - s_stormAlertSndSrc[1] = sound_load("ransto02.voc", SOUND_PRIORITY_MED5); - s_stormAlertSndSrc[2] = sound_load("ransto03.voc", SOUND_PRIORITY_MED5); - s_stormAlertSndSrc[3] = sound_load("ransto04.voc", SOUND_PRIORITY_MED5); - s_stormAlertSndSrc[4] = sound_load("ransto05.voc", SOUND_PRIORITY_MED5); - s_stormAlertSndSrc[5] = sound_load("ransto06.voc", SOUND_PRIORITY_MED5); - s_stormAlertSndSrc[6] = sound_load("ransto07.voc", SOUND_PRIORITY_MED5); - s_stormAlertSndSrc[7] = sound_load("ransto08.voc", SOUND_PRIORITY_MED5); - - // Attacks, hurt, death. - s_agentSndSrc[AGENTSND_REMOTE_2] = sound_load("remote-2.voc", SOUND_PRIORITY_LOW0); - s_agentSndSrc[AGENTSND_AXE_1] = sound_load("axe-1.voc", SOUND_PRIORITY_LOW0); - s_agentSndSrc[AGENTSND_INTSTUN] = sound_load("intstun.voc", SOUND_PRIORITY_LOW0); - s_agentSndSrc[AGENTSND_PROBFIRE_11] = sound_load("probfir1.voc", SOUND_PRIORITY_LOW0); - s_agentSndSrc[AGENTSND_PROBFIRE_12] = sound_load("probfir1.voc", SOUND_PRIORITY_LOW0); - s_agentSndSrc[AGENTSND_CREATURE2] = sound_load("creatur2.voc", SOUND_PRIORITY_LOW0); - s_agentSndSrc[AGENTSND_PROBFIRE_13] = sound_load("probfir1.voc", SOUND_PRIORITY_LOW0); - s_agentSndSrc[AGENTSND_STORM_HURT] = sound_load("st-hrt-1.voc", SOUND_PRIORITY_MED5); - s_agentSndSrc[AGENTSND_GAMOR_2] = sound_load("gamor-2.voc", SOUND_PRIORITY_MED5); - s_agentSndSrc[AGENTSND_REEYEE_2] = sound_load("reeyee-2.voc", SOUND_PRIORITY_MED5); - s_agentSndSrc[AGENTSND_BOSSK_3] = sound_load("bossk-3.voc", SOUND_PRIORITY_MED5); - s_agentSndSrc[AGENTSND_CREATURE_HURT] = sound_load("creathrt.voc", SOUND_PRIORITY_MED5); - s_agentSndSrc[AGENTSND_STORM_DIE] = sound_load("st-die-1.voc", SOUND_PRIORITY_MED5); - s_agentSndSrc[AGENTSND_REEYEE_3] = sound_load("reeyee-3.voc", SOUND_PRIORITY_MED5); - s_agentSndSrc[AGENTSND_BOSSK_DIE] = sound_load("bosskdie.voc", SOUND_PRIORITY_MED5); - s_agentSndSrc[AGENTSND_GAMOR_1] = sound_load("gamor-1.voc", SOUND_PRIORITY_MED5); - s_agentSndSrc[AGENTSND_CREATURE_DIE] = sound_load("creatdie.voc", SOUND_PRIORITY_MED5); - s_agentSndSrc[AGENTSND_EEEK_3] = sound_load("eeek-3.voc", SOUND_PRIORITY_MED5); - s_agentSndSrc[AGENTSND_SMALL_EXPLOSION] = sound_load("ex-small.voc", SOUND_PRIORITY_MED5); - s_agentSndSrc[AGENTSND_PROBE_ALM] = sound_load("probalm.voc", SOUND_PRIORITY_MED5); - s_agentSndSrc[AGENTSND_TINY_EXPLOSION] = sound_load("ex-tiny1.voc", SOUND_PRIORITY_MED5); - - sound_setBaseVolume(s_agentSndSrc[AGENTSND_REMOTE_2], 40); - - // Pre-cache all sounds, to make sure sound order is consistent. - bobaFett_precache(); - kellDragon_precache(); - mousebot_precache(); - phaseOne_precache(); - phaseTwo_precache(); - phaseThree_precache(); - turret_precache(); - welder_precache(); - } - - void actor_allocatePhysicsActorList() - { - s_physicsActors = list_allocate(sizeof(PhysicsActor*), 80); - } - - void actor_addPhysicsActorToWorld(PhysicsActor* actor) - { - PhysicsActor** actorPtr = (PhysicsActor**)list_addItem(s_physicsActors); - *actorPtr = actor; - - actor->vel = { 0, 0, 0 }; - actor->moveSndId = NULL_SOUND; - actor->parent = actorPtr; - } - - void actor_removePhysicsActorFromWorld(PhysicsActor* phyActor) - { - list_removeItem(s_physicsActors, phyActor->parent); - } - - void actor_createTask() - { - s_istate.actorDispatch = allocator_create(sizeof(ActorDispatch)); - s_istate.actorTask = createSubTask("actor", actorLogicTaskFunc, actorLogicMsgFunc); - s_istate.actorPhysicsTask = createSubTask("physics", actorPhysicsTaskFunc); - } - - ActorDispatch* actor_createDispatch(SecObject* obj, LogicSetupFunc* setupFunc) - { - ActorDispatch* dispatch = (ActorDispatch*)allocator_newItem(s_istate.actorDispatch); - memset(dispatch->modules, 0, sizeof(ActorModule*) * 6); - - dispatch->moveMod = nullptr; - dispatch->animTable = nullptr; - dispatch->delay = 72; // Delay in ticks - dispatch->alertSndSrc = NULL_SOUND; - dispatch->alertSndID = NULL_SOUND; - dispatch->fov = 9557; // ~210 degrees - dispatch->awareRange = FIXED(20); - dispatch->vel = { 0 }; - dispatch->lastPlayerPos = { 0 }; - dispatch->freeTask = nullptr; - dispatch->flags = 4; - - if (obj) - { - obj_addLogic(obj, (Logic*)dispatch, LOGIC_DISPATCH, s_istate.actorTask, actorLogicCleanupFunc); - } - if (setupFunc) - { - *setupFunc = actorLogicSetupFunc; - } - - s_actorState.curLogic = (Logic*)dispatch; - return dispatch; - } - - JBool actorLogicSetupFunc(Logic* logic, KEYWORD key) - { - ActorDispatch* dispatch = (ActorDispatch*)logic; - ActorModule* module = nullptr; - - if (key == KW_PLUGIN) - { - KEYWORD pluginType = getKeywordIndex(s_objSeqArg1); - KEYWORD thinkerType = getKeywordIndex(s_objSeqArg2); - - switch (pluginType) - { - case KW_MOVER: - { - dispatch->moveMod = actor_createMovementModule(dispatch); - } break; - case KW_SHAKER: - { - module = (ActorModule*)actor_createAttackModule(dispatch); - } break; - case KW_THINKER: - { - if (thinkerType == KW_FOLLOW_Y) - { - module = (ActorModule*)actor_createFlyingModule((Logic*)dispatch); - } - else if (thinkerType == KW_RANDOM_YAW) - { - module = (ActorModule*)actor_createFlyingModule_Remote((Logic*)dispatch); - } - else if (thinkerType != KW_FOLLOW) - { - return JFALSE; - } - } break; - default: - { - return JFALSE; - } - } - - actor_addModule(dispatch, module); - return JTRUE; - } - return JFALSE; - } - - void actor_initModule(ActorModule* module, Logic* logic) - { - module->func = nullptr; - module->msgFunc = nullptr; - module->attribFunc = nullptr; - module->freeFunc = nullptr; - module->nextTick = 0; - module->obj = logic->obj; - } - - fixed16_16 actor_initAttackModule(AttackModule* attackMod, Logic* logic) - { - actor_initModule(&attackMod->header, logic); - - attackMod->target.speedRotation = 0; - attackMod->target.speed = 0; - attackMod->target.speedVert = 0; - attackMod->timing.delay = 218; - attackMod->timing.searchDelay = 218; - attackMod->timing.meleeDelay = 0; - attackMod->timing.rangedDelay = 291; - attackMod->timing.losDelay = 43695; - attackMod->anim.frameRate = 5; - attackMod->anim.frameCount = ONE_16; - attackMod->anim.prevTick = 0; - attackMod->anim.state = STATE_DELAY; - attackMod->fireSpread = FIXED(30); - attackMod->accuracyNextTick = 0; - attackMod->fireOffset.x = 0; - attackMod->fireOffset.z = 0; - - attackMod->target.flags &= ~TARGET_ALL; - attackMod->anim.flags |= 3; - attackMod->timing.nextTick = s_curTick + 0x4446; // ~120 seconds - - SecObject* obj = attackMod->header.obj; - // world width and height was set from the sprite data. - attackMod->fireOffset.y = -((TFE_Jedi::abs(obj->worldHeight) >> 1) + ONE_16); - - attackMod->projType = PROJ_RIFLE_BOLT; - attackMod->attackSecSndSrc = 0; - attackMod->attackPrimSndSrc = 0; - attackMod->meleeRange = 0; - attackMod->minDist = 0; - attackMod->maxDist = FIXED(160); - attackMod->meleeDmg = 0; - attackMod->meleeRate = FIXED(230); - attackMod->attackFlags = ATTFLAG_RANGED | ATTFLAG_LIT_RNG; - - return attackMod->fireOffset.y; - } - - void actor_setDeathCollisionFlags() - { - ActorDispatch* logic = (ActorDispatch*)s_actorState.curLogic; - MovementModule* moveMod = logic->moveMod; - moveMod->collisionFlags |= 2; - // Added to disable auto-aim when dying. - logic->logic.obj->flags &= ~OBJ_FLAG_AIM; - } - - // Returns JTRUE if the object is on the floor, or JFALSE is not on the floor or moving too fast. - JBool actor_onFloor() - { - ActorDispatch* logic = (ActorDispatch*)s_actorState.curLogic; - SecObject* obj = logic->logic.obj; - RSector* sector = obj->sector; - - if (sector->secHeight > 0 && obj->posWS.y > sector->floorHeight) - { - return JTRUE; - } - fixed16_16 absVelX = TFE_Jedi::abs(logic->vel.x); - fixed16_16 absVelZ = TFE_Jedi::abs(logic->vel.z); - if (absVelX >= FIXED(5) && absVelZ >= FIXED(5)) - { - return JFALSE; - } - - fixed16_16 ceilHeight, floorHeight; - sector_getObjFloorAndCeilHeight(sector, obj->posWS.y, &floorHeight, &ceilHeight); - return (obj->posWS.y < floorHeight) ? JFALSE : JTRUE; - } - - JBool actor_arrivedAtTarget(ActorTarget* target, SecObject* obj) - { - if ((target->flags & TARGET_MOVE_XZ) && (target->pos.x != obj->posWS.x || target->pos.z != obj->posWS.z)) - { - return JFALSE; - } - if ((target->flags & TARGET_MOVE_Y) && (target->pos.y != obj->posWS.y)) - { - return JFALSE; - } - if ((target->flags & TARGET_MOVE_ROT) && (target->yaw != obj->yaw || target->pitch != obj->pitch || target->roll != obj->roll)) - { - return JFALSE; - } - return JTRUE; - } - - angle14_32 actor_offsetTarget(fixed16_16* targetX, fixed16_16* targetZ, fixed16_16 targetOffset, fixed16_16 targetVariation, angle14_32 angle, angle14_32 angleVariation) - { - if (angleVariation) - { - angle += floor16(random(intToFixed16(angleVariation) * 2) - intToFixed16(angleVariation)); - } - angle &= ANGLE_MASK; - - fixed16_16 dist; - if (targetVariation) - { - dist = targetOffset + random(targetVariation * 2) - targetVariation; - } - else - { - dist = targetOffset; - } - - fixed16_16 cosAngle, sinAngle; - sinCosFixed(angle, &sinAngle, &cosAngle); - *targetX += mul16(dist, sinAngle); - *targetZ += mul16(dist, cosAngle); - return angle; - } - - // returns JTRUE on collision else JFALSE. - JBool actor_handleSteps(MovementModule* moveMod, ActorTarget* target) - { - SecObject* obj = moveMod->header.obj; - if (moveMod->physics.responseStep || moveMod->collisionWall) - { - if (!(moveMod->collisionFlags & 1)) - { - RWall* wall = moveMod->physics.wall ? moveMod->physics.wall : moveMod->collisionWall; - if (!wall) - { - return moveMod->physics.collidedObj ? JTRUE : JFALSE; - } - - RSector* nextSector = wall->nextSector; - if (nextSector) - { - RSector* sector = wall->sector; - fixed16_16 floorHeight = min(nextSector->floorHeight, sector->floorHeight); - fixed16_16 ceilHeight = max(nextSector->ceilingHeight, sector->ceilingHeight); - fixed16_16 gap = floorHeight - ceilHeight; - fixed16_16 objHeight = obj->worldHeight + ONE_16; - // If the object can fit. - if (gap > objHeight) - { - target->pos.y = floorHeight - (TFE_Jedi::abs(gap) >> 1) + (TFE_Jedi::abs(obj->worldHeight) >> 1); - target->flags |= 2; - return JFALSE; - } - } - } - return JTRUE; - } - return JFALSE; - } - - JBool actorLogic_isStopFlagSet() - { - ActorDispatch* logic = (ActorDispatch*)s_actorState.curLogic; - return (logic->flags & 8) ? JTRUE : JFALSE; - } - - void actor_changeDirFromCollision(MovementModule* moveMod, ActorTarget* target, Tick* prevColTick) - { - SecObject* obj = moveMod->header.obj; - Tick delta = Tick(s_curTick - (*prevColTick)); - angle14_32 newAngle; - if (delta < 145) - { - newAngle = random_next() & ANGLE_MASK; - } - else - { - angle14_32 rAngle = moveMod->physics.responseAngle + (s_curTick & 0xff) - 128; - angle14_32 angleDiff = getAngleDifference(obj->yaw, rAngle) & 8191; - if (angleDiff > 4095) - { - newAngle = moveMod->physics.responseAngle - 8191; - } - else - { - newAngle = moveMod->physics.responseAngle; - } - newAngle &= ANGLE_MASK; - } - - fixed16_16 dirX, dirZ; - sinCosFixed(newAngle, &dirX, &dirZ); - target->pos.x = obj->posWS.x + (dirX << 7); - target->pos.z = obj->posWS.z + (dirZ << 7); - - target->flags = (target->flags | TARGET_MOVE_XZ | TARGET_MOVE_ROT) & (~TARGET_MOVE_Y); - target->yaw = newAngle; - target->pitch = 0; - target->roll = 0; - - *prevColTick = s_curTick; - } - - void actor_jumpToTarget(PhysicsActor* physicsActor, SecObject* obj, vec3_fixed target, fixed16_16 speed, angle14_32 angleOffset) - { - fixed16_16 dist = distApprox(obj->posWS.x, obj->posWS.z, target.x, target.z); - fixed16_16 distOverSpeed = div16(dist, speed); - fixed16_16 impulse = mul16(s_gravityAccel, distOverSpeed >> 1); - - fixed16_16 dy = obj->posWS.y - target.y; - angle14_32 pitch = vec2ToAngle(dy, dist); - angle14_32 finalPitch = (angleOffset + pitch + arcCosFixed(div16(impulse, speed), pitch)) & ANGLE_MASK; - - // This simplifies to: (dy/dist + 1.0) * speed - fixed16_16 dyOverDistBySpeed = div16(dy + dist, distOverSpeed); - - fixed16_16 sinYaw, cosYaw; - fixed16_16 sinPitch, cosPitch; - sinCosFixed(obj->yaw, &sinYaw, &cosYaw); - sinCosFixed(finalPitch, &sinPitch, &cosPitch); - - physicsActor->vel.x = mul16(sinYaw, dyOverDistBySpeed); - physicsActor->vel.z = mul16(cosYaw, dyOverDistBySpeed); - physicsActor->vel.y = -mul16(sinPitch, dyOverDistBySpeed); - - physicsActor->vel.x = mul16(cosPitch, physicsActor->vel.x); - physicsActor->vel.z = mul16(cosPitch, physicsActor->vel.z); - } - - void actor_leadTarget(ProjectileLogic* proj) - { - SecObject* projObj = proj->logic.obj; - - fixed16_16 dist = distApprox(projObj->posWS.x, projObj->posWS.z, s_playerObject->posWS.x, s_playerObject->posWS.z); - fixed16_16 travelTime = div16(dist, proj->speed); - vec3_fixed playerVel; - player_getVelocity(&playerVel); - - vec3_fixed target = - { - s_playerObject->posWS.x + mul16(playerVel.x, travelTime), - s_playerObject->posWS.y + mul16(playerVel.y, travelTime) + ONE_16 - s_playerObject->worldHeight, - s_playerObject->posWS.z + mul16(playerVel.z, travelTime) - }; - proj_aimAtTarget(proj, target); - } - - void actor_removeRandomCorpse() - { - if (s_levelState.sectorCount <= 0) - { - return; - } - s32 randomSect = floor16(random(intToFixed16(s_levelState.sectorCount - 1))); - RSector* sector; - for (u32 attempt = 0; attempt < s_levelState.sectorCount; attempt++, randomSect++) - { - if (randomSect >= (s32)s_levelState.sectorCount) - { - sector = &s_levelState.sectors[0]; - randomSect = 0; - } - else - { - sector = &s_levelState.sectors[randomSect]; - } - - SecObject** objList = sector->objectList; - for (s32 i = 0, idx = 0; i < sector->objectCount && idx < sector->objectCapacity; idx++) - { - SecObject* obj = objList[idx]; - if (obj) - { - if ((obj->entityFlags & ETFLAG_CORPSE) && !(obj->entityFlags & ETFLAG_KEEP_CORPSE) && !actor_canSeeObject(obj, s_playerObject)) - { - freeObject(obj); - return; - } - i++; - } - } - } - } - - void actor_handleBossDeath(PhysicsActor* physicsActor) - { - SecObject* obj = physicsActor->moveMod.header.obj; - if (obj->flags & OBJ_FLAG_BOSS) - { - if (obj->entityFlags & ETFLAG_GENERAL_MOHC) - { - if (s_levelState.mohcSector) - { - message_sendToSector(s_levelState.mohcSector, nullptr, 0, MSG_TRIGGER); - } - } - else if (s_levelState.bossSector) - { - message_sendToSector(s_levelState.bossSector, nullptr, 0, MSG_TRIGGER); - } - } - } - - void actor_updatePlayerVisiblity(JBool playerVis, fixed16_16 posX, fixed16_16 posZ) - { - ActorDispatch* logic = (ActorDispatch*)s_actorState.curLogic; - - // Update player visibility flag. - logic->flags &= ~8; - logic->flags |= ((playerVis & 1) << 3); // flag 8 = player visible. - - if (playerVis) - { - logic->lastPlayerPos.x = posX; - logic->lastPlayerPos.z = posZ; - } - } - - ActorDispatch* actor_getCurrentLogic() - { - return (ActorDispatch*)s_actorState.curLogic; - } - - JBool defaultDamageFunc(ActorModule* module, MovementModule* moveMod) - { - DamageModule* damageMod = (DamageModule*)module; - AttackModule* attackMod = &damageMod->attackMod; - SecObject* obj = attackMod->header.obj; - RSector* sector = obj->sector; - - if (!(attackMod->anim.flags & 2)) - { - if (obj->type == OBJ_TYPE_SPRITE) - { - actor_setCurAnimation(&attackMod->anim); - } - moveMod->updateTargetFunc(moveMod, &attackMod->target); - return JFALSE; - } - - if (damageMod->hp <= 0) - { - if (!actor_onFloor()) - { - if (obj->type == OBJ_TYPE_SPRITE) - { - actor_setCurAnimation(&attackMod->anim); - } - moveMod->updateTargetFunc(moveMod, &attackMod->target); - return JFALSE; - } - spawnHitEffect(damageMod->dieEffect, sector, obj->posWS, obj); - - // If the secHeight is <= 0, then it is not a water sector. - if (sector->secHeight - 1 < 0) - { - if (damageMod->itemDropId != ITEM_NONE) - { - SecObject* item = item_create(damageMod->itemDropId); - item->posWS = obj->posWS; - sector_addObject(sector, item); - - CollisionInfo colInfo = - { - item, // obj - FIXED(2), 0, FIXED(2), // offset - ONE_16, COL_INFINITY, ONE_16, 0, // botOffset, yPos, height, u1c - nullptr, 0, nullptr, - item->worldWidth, 0, - JFALSE, - 0, 0, 0, 0, 0 - }; - handleCollision(&colInfo); - - fixed16_16 ceilHeight, floorHeight; - sector_getObjFloorAndCeilHeight(item->sector, item->posWS.y, &floorHeight, &ceilHeight); - item->posWS.y = floorHeight; - - // Free the object if it winds in a water sector. - if (item->sector->secHeight - 1 >= 0) - { - freeObject(item); - } - } - s32 animIndex = actor_getAnimationIndex(4); - if (animIndex != -1) - { - RSector* sector = obj->sector; - SecObject* corpse = allocateObject(); - sprite_setData(corpse, obj->wax); - corpse->frame = 0; - corpse->anim = animIndex; - corpse->posWS.x = obj->posWS.x; - corpse->posWS.y = (sector->colSecHeight < obj->posWS.y) ? sector->colSecHeight : obj->posWS.y; - corpse->posWS.z = obj->posWS.z; - corpse->worldHeight = 0; - corpse->worldWidth = 0; - corpse->entityFlags |= ETFLAG_CORPSE; - sector_addObject(obj->sector, corpse); - } - } - actor_kill(); - return 0; - } - return 0xffffffff; - } - - JBool defaultDamageMsgFunc(s32 msg, ActorModule* module, MovementModule* moveMod) - { - DamageModule* damageMod = (DamageModule*)module; - AttackModule* attackMod = &damageMod->attackMod; - SecObject* obj = attackMod->header.obj; - RSector* sector = obj->sector; - - if (msg == MSG_DAMAGE) - { - if (damageMod->hp > 0) - { - ProjectileLogic* proj = (ProjectileLogic*)s_msgEntity; - fixed16_16 dmg = proj->dmg; - // Reduce damage by half if an enemy is shooting another enemy. - if (proj->prevObj) - { - u32 moduleProj = proj->prevObj->entityFlags & ETFLAG_AI_ACTOR; - u32 moduleCur = obj->entityFlags & ETFLAG_AI_ACTOR; - if (moduleProj == moduleCur) - { - dmg = proj->dmg >> 1; - } - } - damageMod->hp -= dmg; - if (damageMod->stopOnHit || damageMod->hp <= 0) - { - attackMod->target.flags |= TARGET_FREEZE; - } - - LogicAnimation* anim = &attackMod->anim; - vec3_fixed pushVel; - computeDamagePushVelocity(proj, &pushVel); - if (damageMod->hp <= 0) - { - ActorDispatch* logic = (ActorDispatch*)s_actorState.curLogic; - actor_addVelocity(pushVel.x*4, pushVel.y*2, pushVel.z*4); - actor_setDeathCollisionFlags(); - sound_stop(logic->alertSndID); - sound_playCued(damageMod->dieSndSrc, obj->posWS); - attackMod->anim.flags |= 8; - if (proj->type == PROJ_PUNCH && obj->type == OBJ_TYPE_SPRITE) - { - actor_setupAnimation(2, anim); - } - else if (obj->type == OBJ_TYPE_SPRITE) - { - actor_setupAnimation(3, anim); - } - } - else - { - // Keep the y velocity from accumulating forever. - ActorDispatch* logic = (ActorDispatch*)s_actorState.curLogic; - if (logic->vel.y < 0) - { - pushVel.y = 0; - } - - actor_addVelocity(pushVel.x*2, pushVel.y, pushVel.z*2); - sound_stop(damageMod->hurtSndID); - damageMod->hurtSndID = sound_playCued(damageMod->hurtSndSrc, obj->posWS); - if (obj->type == OBJ_TYPE_SPRITE) - { - actor_setupAnimation(12, anim); - } - } - } - - if (obj->type == OBJ_TYPE_SPRITE) - { - actor_setCurAnimation(&attackMod->anim); - } - moveMod->updateTargetFunc(moveMod, &attackMod->target); - return JFALSE; - } - else if (msg == MSG_EXPLOSION) - { - if (damageMod->hp > 0) - { - fixed16_16 dmg = s_msgArg1; - fixed16_16 force = s_msgArg2; - damageMod->hp -= dmg; - if (damageMod->stopOnHit || damageMod->hp <= 0) - { - attackMod->target.flags |= TARGET_FREEZE; - } - - vec3_fixed dir; - vec3_fixed pos = { obj->posWS.x, obj->posWS.y - obj->worldHeight, obj->posWS.z }; - computeExplosionPushDir(&pos, &dir); - - vec3_fixed vel = { mul16(force, dir.x), mul16(force, dir.y), mul16(force, dir.z) }; - LogicAnimation* anim = &attackMod->anim; - ActorDispatch* logic = (ActorDispatch*)s_actorState.curLogic; - if (damageMod->hp <= 0) - { - actor_addVelocity(vel.x, vel.y, vel.z); - actor_setDeathCollisionFlags(); - sound_stop(logic->alertSndID); - sound_playCued(damageMod->dieSndSrc, obj->posWS); - attackMod->target.flags |= 8; - if (obj->type == OBJ_TYPE_SPRITE) - { - actor_setupAnimation(3, anim); - } - } - else - { - actor_addVelocity(vel.x>>1, vel.y>>1, vel.z>>1); - sound_stop(damageMod->hurtSndID); - damageMod->hurtSndID = sound_playCued(damageMod->hurtSndSrc, obj->posWS); - if (obj->type == OBJ_TYPE_SPRITE) - { - actor_setupAnimation(12, anim); - } - } - } - if (obj->type == OBJ_TYPE_SPRITE) - { - actor_setCurAnimation(&attackMod->anim); - } - moveMod->updateTargetFunc(moveMod, &attackMod->target); - return JFALSE; - } - else if (msg == MSG_TERMINAL_VEL || msg == MSG_CRUSH) - { - if (damageMod->hp > 0) - { - damageMod->hp = 0; - attackMod->target.flags |= TARGET_FREEZE; - - LogicAnimation* anim = &attackMod->anim; - ActorDispatch* logic = (ActorDispatch*)s_actorState.curLogic; - - actor_setDeathCollisionFlags(); - sound_stop(logic->alertSndID); - sound_playCued(damageMod->dieSndSrc, obj->posWS); - attackMod->anim.flags |= 8; - if (obj->type == OBJ_TYPE_SPRITE) - { - actor_setupAnimation(3, anim); - } - } - } - - return JFALSE; - } - - DamageModule* actor_createDamageModule(ActorDispatch* dispatch) - { - DamageModule* damageMod = (DamageModule*)level_alloc(sizeof(DamageModule)); - memset(damageMod, 0, sizeof(DamageModule)); - - AttackModule* attackMod = &damageMod->attackMod; - actor_initAttackModule(attackMod, (Logic*)dispatch); - attackMod->header.func = defaultDamageFunc; - attackMod->header.msgFunc = defaultDamageMsgFunc; - attackMod->header.nextTick = 0xffffffff; - attackMod->header.type = ACTMOD_DAMAGE; - - // Default values. - damageMod->hp = FIXED(4); - damageMod->itemDropId = ITEM_NONE; - damageMod->hurtSndSrc = NULL_SOUND; - damageMod->dieSndSrc = NULL_SOUND; - damageMod->hurtSndID = NULL_SOUND; - damageMod->stopOnHit = JTRUE; - damageMod->dieEffect = HEFFECT_NONE; - - return damageMod; - } - - JBool defaultAttackFunc(ActorModule* module, MovementModule* moveMod) - { - DamageModule* damageMod = (DamageModule*)module; - AttackModule* attackMod = &damageMod->attackMod; - ActorDispatch* logic = (ActorDispatch*)s_actorState.curLogic; - SecObject* obj = attackMod->header.obj; - LogicAnimation* anim = &attackMod->anim; - s32 state = attackMod->anim.state; - - switch (state) - { - case STATE_DELAY: - { - if (attackMod->anim.flags & 2) - { - // Clear attack based lighting. - obj->flags &= ~OBJ_FLAG_FULLBRIGHT; - attackMod->anim.state = STATE_ANIMATEATTACK; - - // Update the shooting accuracy. - if (attackMod->accuracyNextTick < s_curTick) - { - if (attackMod->fireSpread) - { - attackMod->fireSpread -= mul16(FIXED(2), s_deltaTime); - if (attackMod->fireSpread < FIXED(9)) - { - attackMod->fireSpread = FIXED(9); - } - attackMod->accuracyNextTick = s_curTick + 145; - } - else - { - attackMod->accuracyNextTick = 0xffffffff; - } - } - attackMod->target.flags &= ~TARGET_ALL_MOVE; - // Next AI update. - return s_curTick + random(attackMod->timing.delay); - } - } break; - case STATE_ANIMATEATTACK: - { - gameMusic_sustainFight(); - if (s_playerDying) - { - if (s_curTick >= s_reviveTick) - { - attackMod->anim.flags |= 2; - attackMod->anim.state = STATE_DELAY; - return attackMod->timing.delay; - } - } - - if (!actor_canSeeObjFromDist(obj, s_playerObject)) - { - actor_updatePlayerVisiblity(JFALSE, 0, 0); - attackMod->anim.flags |= 2; - attackMod->anim.state = STATE_DELAY; - if (attackMod->timing.nextTick < s_curTick) - { - attackMod->timing.delay = attackMod->timing.searchDelay; - actor_setupInitAnimation(); - } - return attackMod->timing.delay; - } - else - { - actor_updatePlayerVisiblity(JTRUE, s_eyePos.x, s_eyePos.z); - attackMod->timing.nextTick = s_curTick + attackMod->timing.losDelay; - fixed16_16 dist = distApprox(s_playerObject->posWS.x, s_playerObject->posWS.z, obj->posWS.x, obj->posWS.z); - fixed16_16 yDiff = TFE_Jedi::abs(obj->posWS.y - obj->worldHeight - s_eyePos.y); - angle14_32 vertAngle = vec2ToAngle(yDiff, dist); - - fixed16_16 baseYDiff = TFE_Jedi::abs(s_playerObject->posWS.y - obj->posWS.y); - dist += baseYDiff; - - if (vertAngle < 2275 && dist <= attackMod->maxDist) // ~50 degrees - { - if (attackMod->attackFlags & ATTFLAG_MELEE) - { - if (dist <= attackMod->meleeRange) - { - attackMod->anim.state = STATE_FIRE1; - attackMod->timing.delay = attackMod->timing.meleeDelay; - } - else if (!(attackMod->attackFlags & ATTFLAG_RANGED) || dist < attackMod->minDist) - { - attackMod->anim.flags |= 2; - attackMod->anim.state = STATE_DELAY; - return attackMod->timing.delay; - } - else - { - attackMod->anim.state = STATE_FIRE2; - attackMod->timing.delay = attackMod->timing.rangedDelay; - } - } - else - { - if (dist < attackMod->minDist) - { - attackMod->anim.flags |= 2; - attackMod->anim.state = STATE_DELAY; - return attackMod->timing.delay; - } - attackMod->anim.state = STATE_FIRE1; - attackMod->timing.delay = attackMod->timing.rangedDelay; - } - - if (obj->type == OBJ_TYPE_SPRITE) - { - if (attackMod->anim.state == STATE_FIRE1) - { - actor_setupAnimation(1, &attackMod->anim); - } - else - { - actor_setupAnimation(7, &attackMod->anim); - } - } - - attackMod->target.pos.x = obj->posWS.x; - attackMod->target.pos.z = obj->posWS.z; - attackMod->target.yaw = vec2ToAngle(s_eyePos.x - obj->posWS.x, s_eyePos.z - obj->posWS.z); - attackMod->target.pitch = obj->pitch; - attackMod->target.roll = obj->roll; - attackMod->target.flags |= (TARGET_MOVE_XZ | TARGET_MOVE_ROT); - } - else - { - attackMod->anim.flags |= 2; - attackMod->anim.state = STATE_DELAY; - return attackMod->timing.delay; - } - } - } break; - case STATE_FIRE1: - { - if (!(attackMod->anim.flags & 2)) - { - break; - } - - if (attackMod->attackFlags & ATTFLAG_MELEE) - { - attackMod->anim.state = STATE_ANIMATE1; - fixed16_16 dy = TFE_Jedi::abs(obj->posWS.y - s_playerObject->posWS.y); - fixed16_16 dist = dy + distApprox(s_playerObject->posWS.x, s_playerObject->posWS.z, obj->posWS.x, obj->posWS.z); - if (dist < attackMod->meleeRange) - { - sound_playCued(attackMod->attackSecSndSrc, obj->posWS); - player_applyDamage(attackMod->meleeDmg, 0, JTRUE); - if (attackMod->attackFlags & ATTFLAG_LIT_MELEE) - { - obj->flags |= OBJ_FLAG_FULLBRIGHT; - } - } - break; - } - - // Ranged Attack! - if (attackMod->attackFlags & ATTFLAG_LIT_RNG) - { - obj->flags |= OBJ_FLAG_FULLBRIGHT; - } - - attackMod->anim.state = STATE_ANIMATE1; - ProjectileLogic* proj = (ProjectileLogic*)createProjectile(attackMod->projType, obj->sector, obj->posWS.x, attackMod->fireOffset.y + obj->posWS.y, obj->posWS.z, obj); - sound_playCued(attackMod->attackPrimSndSrc, obj->posWS); - - proj->prevColObj = obj; - proj->prevObj = obj; - proj->excludeObj = obj; - - SecObject* projObj = proj->logic.obj; - projObj->yaw = obj->yaw; - - // Handle x and z fire offset. - if (attackMod->fireOffset.x | attackMod->fireOffset.z) - { - proj->delta.x = attackMod->fireOffset.x; - proj->delta.z = attackMod->fireOffset.z; - proj_handleMovement(proj); - } - - // Aim at the target. - vec3_fixed target = { s_eyePos.x, s_eyePos.y + ONE_16, s_eyePos.z }; - proj_aimAtTarget(proj, target); - - if (attackMod->fireSpread) - { - proj->vel.x += random(attackMod->fireSpread*2) - attackMod->fireSpread; - proj->vel.y += random(attackMod->fireSpread*2) - attackMod->fireSpread; - proj->vel.z += random(attackMod->fireSpread*2) - attackMod->fireSpread; - } - } break; - case STATE_ANIMATE1: - { - if (obj->type == OBJ_TYPE_SPRITE) - { - actor_setupAnimation(6, anim); - } - attackMod->anim.state = STATE_DELAY; - } break; - case STATE_FIRE2: - { - if (!(attackMod->anim.flags & 2)) - { - break; - } - if (attackMod->attackFlags & ATTFLAG_LIT_RNG) - { - obj->flags |= OBJ_FLAG_FULLBRIGHT; - } - - attackMod->anim.state = STATE_ANIMATE2; - ProjectileLogic* proj = (ProjectileLogic*)createProjectile(attackMod->projType, obj->sector, obj->posWS.x, attackMod->fireOffset.y + obj->posWS.y, obj->posWS.z, obj); - sound_playCued(attackMod->attackPrimSndSrc, obj->posWS); - proj->prevColObj = obj; - proj->excludeObj = obj; - - SecObject* projObj = proj->logic.obj; - projObj->yaw = obj->yaw; - if (attackMod->projType == PROJ_THERMAL_DET) - { - proj->bounceCnt = 0; - proj->duration = 0xffffffff; - vec3_fixed target = { s_playerObject->posWS.x, s_eyePos.y + ONE_16, s_playerObject->posWS.z }; - proj_aimArcing(proj, target, proj->speed); - - if (attackMod->fireOffset.x | attackMod->fireOffset.z) - { - proj->delta.x = attackMod->fireOffset.x; - proj->delta.z = attackMod->fireOffset.z; - proj_handleMovement(proj); - } - } - else - { - if (attackMod->fireOffset.x | attackMod->fireOffset.z) - { - proj->delta.x = attackMod->fireOffset.x; - proj->delta.z = attackMod->fireOffset.z; - proj_handleMovement(proj); - } - vec3_fixed target = { s_eyePos.x, s_eyePos.y + ONE_16, s_eyePos.z }; - proj_aimAtTarget(proj, target); - if (attackMod->fireSpread) - { - proj->vel.x += random(attackMod->fireSpread*2) - attackMod->fireSpread; - proj->vel.y += random(attackMod->fireSpread*2) - attackMod->fireSpread; - proj->vel.z += random(attackMod->fireSpread*2) - attackMod->fireSpread; - } - } - } break; - case STATE_ANIMATE2: - { - if (obj->type == OBJ_TYPE_SPRITE) - { - actor_setupAnimation(8, anim); - } - attackMod->anim.state = STATE_DELAY; - } break; - } - - if (obj->type == OBJ_TYPE_SPRITE) - { - actor_setCurAnimation(&attackMod->anim); - } - moveMod->updateTargetFunc(moveMod, &attackMod->target); - return attackMod->timing.delay; - } - - JBool defaultAttackMsgFunc(s32 msg, ActorModule* module, MovementModule* moveMod) - { - DamageModule* damageMod = (DamageModule*)module; - AttackModule* attackMod = &damageMod->attackMod; - ActorDispatch* logic = (ActorDispatch*)s_actorState.curLogic; - if (msg == MSG_WAKEUP) - { - attackMod->timing.nextTick = s_curTick + attackMod->timing.losDelay; - } - if (logic->flags & 1) - { - return attackMod->timing.delay; - } - return 0xffffffff; - } - - AttackModule* actor_createAttackModule(ActorDispatch* dispatch) - { - AttackModule* attackMod = (AttackModule*)level_alloc(sizeof(AttackModule)); - memset(attackMod, 0, sizeof(AttackModule)); - - actor_initAttackModule(attackMod, (Logic*)dispatch); - attackMod->header.type = ACTMOD_ATTACK; - attackMod->header.func = defaultAttackFunc; - attackMod->header.msgFunc = defaultAttackMsgFunc; - return attackMod; - } - - JBool defaultThinkerFunc(ActorModule* module, MovementModule* moveMod) - { - ThinkerModule* thinkerMod = (ThinkerModule*)module; - SecObject* obj = thinkerMod->header.obj; - - if (thinkerMod->anim.state == 1) - { - ActorTarget* target = &thinkerMod->target; - JBool arrivedAtTarget = actor_arrivedAtTarget(target, obj); - if (thinkerMod->nextTick < s_curTick || arrivedAtTarget) - { - if (arrivedAtTarget) - { - thinkerMod->playerLastSeen = 0xffffffff; - } - thinkerMod->anim.state = STATE_FIRE1; - } - else - { - if (actorLogic_isStopFlagSet()) - { - if (thinkerMod->playerLastSeen != 0xffffffff) - { - thinkerMod->nextTick = 0; - thinkerMod->maxWalkTime = thinkerMod->startDelay; - thinkerMod->playerLastSeen = 0xffffffff; - } - } - else - { - thinkerMod->playerLastSeen = s_curTick + 0x1111; - } - - ActorTarget* target = &thinkerMod->target; - if (actor_handleSteps(moveMod, target)) - { - actor_changeDirFromCollision(moveMod, target, &thinkerMod->prevColTick); - if (!actorLogic_isStopFlagSet()) - { - thinkerMod->maxWalkTime += 218; - if (thinkerMod->maxWalkTime > 1456) - { - thinkerMod->maxWalkTime = 291; - } - thinkerMod->nextTick = s_curTick + thinkerMod->maxWalkTime; - } - } - } - } - else if (thinkerMod->anim.state == 2) - { - ActorDispatch* logic = actor_getCurrentLogic(); - fixed16_16 targetX, targetZ; - if (thinkerMod->playerLastSeen < s_curTick) - { - targetX = logic->lastPlayerPos.x; - targetZ = logic->lastPlayerPos.z; - } - else - { - targetX = s_eyePos.x; - targetZ = s_eyePos.z; - } - - fixed16_16 targetOffset; - if (!actorLogic_isStopFlagSet()) - { - // Offset the target by |dx| / 4 - // This is obviously a typo and bug in the DOS code and should be min(|dx|, |dz|) - // but the original code is min(|dx|, |dx|) => |dx| - fixed16_16 dx = TFE_Jedi::abs(s_playerObject->posWS.x - obj->posWS.x); - targetOffset = dx >> 2; - } - else - { - // Offset the target by the targetOffset. - targetOffset = thinkerMod->targetOffset; - } - - fixed16_16 dx = obj->posWS.x - targetX; - fixed16_16 dz = obj->posWS.z - targetZ; - angle14_32 angle = vec2ToAngle(dx, dz); - - thinkerMod->target.pos.x = targetX; - thinkerMod->target.pos.z = targetZ; - thinkerMod->target.flags = (thinkerMod->target.flags | TARGET_MOVE_XZ) & (~TARGET_MOVE_Y); - actor_offsetTarget(&thinkerMod->target.pos.x, &thinkerMod->target.pos.z, targetOffset, thinkerMod->targetVariation, angle, thinkerMod->approachVariation); - - dx = thinkerMod->target.pos.x - obj->posWS.x; - dz = thinkerMod->target.pos.z - obj->posWS.z; - thinkerMod->target.pitch = 0; - thinkerMod->target.roll = 0; - thinkerMod->target.yaw = vec2ToAngle(dx, dz); - thinkerMod->target.flags |= TARGET_MOVE_ROT; - - if (!(logic->flags & 2)) - { - if (obj->type == OBJ_TYPE_SPRITE) - { - actor_setupAnimation(0, &thinkerMod->anim); - } - logic->flags |= 2; - } - thinkerMod->anim.state = STATE_ANIMATEATTACK; - thinkerMod->nextTick = s_curTick + thinkerMod->maxWalkTime; - - if (obj->entityFlags & ETFLAG_REMOTE) - { - if (!(logic->flags & 1) && (logic->flags & 2)) - { - sound_playCued(s_agentSndSrc[AGENTSND_REMOTE_2], obj->posWS); - } - } - } - - if (obj->type == OBJ_TYPE_SPRITE) - { - actor_setCurAnimation(&thinkerMod->anim); - } - moveMod->updateTargetFunc(moveMod, &thinkerMod->target); - return 0; - } - - void actor_thinkerModuleInit(ThinkerModule* thinkerMod) - { - memset(thinkerMod, 0, sizeof(ThinkerModule)); - - thinkerMod->target.speedRotation = 0; - thinkerMod->target.speed = FIXED(4); - thinkerMod->target.speedVert = FIXED(10); - thinkerMod->delay = 72; - thinkerMod->nextTick = 0; - thinkerMod->playerLastSeen = 0xffffffff; - thinkerMod->anim.state = STATE_FIRE1; - thinkerMod->maxWalkTime = 728; // ~5 seconds between decision points. - thinkerMod->anim.frameRate = 5; - thinkerMod->anim.frameCount = ONE_16; - - thinkerMod->anim.prevTick = 0; - thinkerMod->prevColTick = 0; - thinkerMod->target.flags = 0; - thinkerMod->anim.flags = 0; - } - - ThinkerModule* actor_createThinkerModule(ActorDispatch* dispatch) - { - ThinkerModule* thinkerMod = (ThinkerModule*)level_alloc(sizeof(ThinkerModule)); - actor_thinkerModuleInit(thinkerMod); - actor_initModule((ActorModule*)thinkerMod, (Logic*)dispatch); - - thinkerMod->header.func = defaultThinkerFunc; - thinkerMod->header.type = ACTMOD_THINKER; - thinkerMod->targetOffset = FIXED(3); - thinkerMod->targetVariation = 0; - thinkerMod->approachVariation = 4096; // 90 degrees. - - return thinkerMod; - } - - void actor_setupInitAnimation() - { - ActorDispatch* logic = (ActorDispatch*)s_actorState.curLogic; - logic->flags = (logic->flags | 1) & 0xfd; - logic->nextTick = s_curTick + logic->delay; - - SecObject* obj = logic->logic.obj; - obj->anim = actor_getAnimationIndex(5); - obj->frame = 0; - } - - void actor_addModule(ActorDispatch* dispatch, ActorModule* module) - { - if (!module) { return; } - for (s32 i = 0; i < ACTOR_MAX_MODULES; i++) - { - if (!dispatch->modules[i]) - { - dispatch->modules[i] = module; - return; - } - } - } - - JBool actor_handleMovementAndCollision(MovementModule* moveMod) - { - SecObject* obj = moveMod->header.obj; - vec3_fixed desiredMove = { 0, 0, 0 }; - vec3_fixed move = { 0, 0, 0 }; - - moveMod->collisionWall = nullptr; - if (!(moveMod->target.flags & TARGET_FREEZE)) - { - if (moveMod->target.flags & TARGET_MOVE_XZ) - { - desiredMove.x = moveMod->target.pos.x - obj->posWS.x; - desiredMove.z = moveMod->target.pos.z - obj->posWS.z; - } - if (!(moveMod->collisionFlags & 1)) - { - if (moveMod->target.flags & TARGET_MOVE_Y) - { - desiredMove.y = moveMod->target.pos.y - obj->posWS.y; - } - } - move.z = move.y = move.x = 0; - if (desiredMove.x | desiredMove.z) - { - fixed16_16 dirZ, dirX; - fixed16_16 frameMove = mul16(moveMod->target.speed, s_deltaTime); - computeDirAndLength(desiredMove.x, desiredMove.z, &dirX, &dirZ); - - if (desiredMove.x && dirX) - { - fixed16_16 deltaX = mul16(frameMove, dirX); - fixed16_16 absDx = (desiredMove.x < 0) ? -desiredMove.x : desiredMove.x; - move.x = clamp(deltaX, -absDx, absDx); - } - if (desiredMove.z && dirZ) - { - fixed16_16 deltaZ = mul16(frameMove, dirZ); - fixed16_16 absDz = (desiredMove.z < 0) ? -desiredMove.z : desiredMove.z; - move.z = clamp(deltaZ, -absDz, absDz); - } - } - if (desiredMove.y) - { - fixed16_16 deltaY = mul16(moveMod->target.speedVert, s_deltaTime); - if (desiredMove.y < 0) { deltaY = -deltaY; } - - fixed16_16 absDy = (desiredMove.y < 0) ? -desiredMove.y : desiredMove.y; - move.y = clamp(deltaY, -absDy, absDy); - } - } - - if (moveMod->delta.y) - { - move.y += moveMod->delta.y; - } - CollisionInfo* physics = &moveMod->physics; - fixed16_16 dirX, dirZ; - if (move.x | move.y | move.z) - { - physics->offsetX = move.x; - physics->offsetY = move.y; - physics->offsetZ = move.z; - handleCollision(physics); - - if (physics->responseStep) - { - RWall* wall = physics->wall; - if (wall) - { - RSector* nextSector = wall->nextSector; - RSector* triggerSector = (nextSector) ? nextSector : wall->sector; - if (obj->entityFlags & ETFLAG_SMART_OBJ) - { - message_sendToSector(triggerSector, obj, 0, MSG_TRIGGER); - } - } - // Handles a single collision response + resolution step. - if (moveMod->collisionFlags & 4) - { - moveMod->collisionWall = wall; - dirX = physics->responseDir.x; - dirZ = physics->responseDir.z; - handleCollisionResponseSimple(dirX, dirZ, &physics->offsetX, &physics->offsetZ); - handleCollision(physics); - } - } - } - - // Apply the per-frame delta computed from the actor's velocity. - if (moveMod->delta.x | moveMod->delta.z) - { - physics->flags |= 1; - physics->offsetX = moveMod->delta.x; - physics->offsetY = 0; - physics->offsetZ = moveMod->delta.z; - handleCollision(physics); - - // Handles a single collision response + resolution step from velocity delta. - if ((moveMod->collisionFlags & 4) && physics->responseStep) - { - moveMod->collisionWall = physics->wall; - dirX = physics->responseDir.x; - dirZ = physics->responseDir.z; - handleCollisionResponseSimple(dirX, dirZ, &physics->offsetX, &physics->offsetZ); - handleCollision(physics); - } - } - - return JTRUE; - } - - angle14_32 computeAngleChange(angle14_32 desiredChange, angle14_32 maxChange) - { - if (!desiredChange) { return 0; } - angle14_32 change = desiredChange; - if (change > maxChange) - { - change = maxChange; - } - else - { - change = -maxChange; - if (change <= desiredChange) - { - change = desiredChange; - } - } - return change; - } - - void actor_applyTransform(MovementModule* moveMod) - { - SecObject* obj = moveMod->header.obj; - if (moveMod->target.flags & TARGET_FREEZE) - { - return; - } - - const angle14_32 speedRotation = moveMod->target.speedRotation & 0xffff; - if (speedRotation == 0) - { - obj->pitch = moveMod->target.pitch; - obj->yaw = moveMod->target.yaw; - obj->roll = moveMod->target.roll; - if (obj->type & OBJ_TYPE_3D) - { - obj3d_computeTransform(obj); - } - } - else - { - const angle14_32 pitchDiff = getAngleDifference(obj->pitch, moveMod->target.pitch); - const angle14_32 yawDiff = getAngleDifference(obj->yaw, moveMod->target.yaw); - const angle14_32 rollDiff = getAngleDifference(obj->roll, moveMod->target.roll); - if (yawDiff | pitchDiff | rollDiff) - { - const fixed16_16 angularSpd = mul16(intToFixed16(speedRotation), s_deltaTime); - const angle14_32 angleChange = floor16(angularSpd); - obj->yaw = (obj->yaw + computeAngleChange(yawDiff, angleChange)) & ANGLE_MASK; - - if (obj->type & OBJ_TYPE_3D) - { - obj->pitch = (obj->pitch + computeAngleChange(pitchDiff, angleChange)) & ANGLE_MASK; - obj->roll = (obj->roll + computeAngleChange(rollDiff, angleChange)) & ANGLE_MASK; - obj3d_computeTransform(obj); - } - } - } - } - - JBool defaultActorFunc(ActorModule* module, MovementModule* moveMod) - { - moveMod->physics.wall = nullptr; - moveMod->physics.u24 = 0; - - if (moveMod->target.flags & TARGET_MOVE_ROT) - { - actor_applyTransform(moveMod); - } - - if ((moveMod->target.flags & TARGET_MOVE_XZ) || (moveMod->target.flags & TARGET_MOVE_Y) || moveMod->delta.x || moveMod->delta.y || moveMod->delta.z) - { - actor_handleMovementAndCollision(moveMod); - } - moveMod->target.flags &= ~TARGET_ALL_MOVE; - return JFALSE; - } - - // Updates the actor target with the passed in target based on the flags. - JBool defaultUpdateTargetFunc(MovementModule* moveMod, ActorTarget* target) - { - if (target->flags & 8) - { - moveMod->target.flags |= 8; - } - else - { - moveMod->target.flags &= ~TARGET_FREEZE; - if (target->flags & TARGET_MOVE_XZ) - { - moveMod->target.pos.x = target->pos.x; - moveMod->target.pos.z = target->pos.z; - moveMod->target.speed = target->speed; - moveMod->target.flags |= TARGET_MOVE_XZ; - } - if (target->flags & TARGET_MOVE_Y) - { - moveMod->target.pos.y = target->pos.y; - moveMod->target.speedVert = target->speedVert; - moveMod->target.flags |= TARGET_MOVE_Y; - } - if (target->flags & TARGET_MOVE_ROT) - { - moveMod->target.pitch = target->pitch; - moveMod->target.yaw = target->yaw; - moveMod->target.roll = target->roll; - moveMod->target.speedRotation = target->speedRotation; - moveMod->target.flags |= TARGET_MOVE_ROT; - } - } - return JFALSE; - } - - void actor_setupSmartObj(MovementModule* moveMod) - { - SecObject* obj = moveMod->header.obj; - - moveMod->physics.botOffset = 0x38000; // 3.5 - moveMod->physics.yPos = FIXED(4); - moveMod->physics.height = obj->worldHeight; - moveMod->physics.width = obj->worldWidth; - moveMod->physics.responseStep = JFALSE; - moveMod->target.speed = ONE_16; - moveMod->target.speedVert = ONE_16; - moveMod->target.speedRotation = FIXED(45); - moveMod->target.flags &= ~TARGET_ALL; - moveMod->delta = { 0, 0, 0 }; - moveMod->collisionWall = nullptr; - moveMod->unused = 0; - - moveMod->collisionFlags = (moveMod->collisionFlags | 3) & 0xfffffffb; - obj->entityFlags |= ETFLAG_SMART_OBJ; - } - - JBool actor_canSeeObject(SecObject* actorObj, SecObject* obj) - { - vec3_fixed p0 = { actorObj->posWS.x, actorObj->posWS.y - actorObj->worldHeight, actorObj->posWS.z }; - vec3_fixed p1 = { obj->posWS.x, obj->posWS.y, obj->posWS.z }; - if (collision_canHitObject(actorObj->sector, obj->sector, p0, p1, 0)) - { - return JTRUE; - } - if (s_collision_wallHit) - { - return JFALSE; - } - - vec3_fixed p2 = { obj->posWS.x, obj->posWS.y - obj->worldHeight, obj->posWS.z }; - return collision_canHitObject(actorObj->sector, obj->sector, p0, p2, 0); - } - - JBool actor_canSeeObjFromDist(SecObject* actorObj, SecObject* obj) - { - fixed16_16 approxDist = distApprox(actorObj->posWS.x, actorObj->posWS.z, obj->posWS.x, obj->posWS.z); - // Crouching makes the target harder to see. - if (obj->worldHeight < FIXED(3)) - { - approxDist *= 2; - } - if (!s_headlampActive) - { - RSector* sector1 = obj->sector; - fixed16_16 ambient = sector1->ambient; - if (ambient > FIXED(22)) - { - ambient = FIXED(31); - } - // Adds up to 248 units to the approximate distande: 248 when ambient = 0, 0 when ambient = 31 - approxDist += FIXED(248) - (ambient << 3); - } - else - { - approxDist -= s_baseAtten * 2; - } - - if (approxDist < FIXED(256)) - { - // Since random() is unsigned, the real visible range is [200, 256) because of the conditional above. - fixed16_16 rndDist = random(FIXED(256)) + FIXED(200); - if (approxDist < rndDist) - { - return actor_canSeeObject(actorObj, obj); - } - } - return JFALSE; - } - - JBool actor_isObjectVisible(SecObject* actorObj, SecObject* obj, angle14_32 fov, fixed16_16 closeDist) - { - fixed16_16 approxDist = distApprox(actorObj->posWS.x, actorObj->posWS.z, obj->posWS.x, obj->posWS.z); - if (approxDist <= closeDist) - { - return actor_canSeeObjFromDist(actorObj, obj); - } - - fixed16_16 dx = obj->posWS.x - actorObj->posWS.x; - fixed16_16 dz = obj->posWS.z - actorObj->posWS.z; - angle14_32 yaw0 = actorObj->yaw; - angle14_32 obj0To1Angle = vec2ToAngle(dx, dz); - angle14_32 angleDiff = getAngleDifference(obj0To1Angle, yaw0); - angle14_32 right = fov >> 1; - angle14_32 left = -(fov >> 1); - if (angleDiff > left && angleDiff < right) - { - return actor_canSeeObjFromDist(actorObj, obj); - } - return JFALSE; - } - - MovementModule* actor_createMovementModule(ActorDispatch* dispatch) - { - MovementModule* moveMod = (MovementModule*)level_alloc(sizeof(MovementModule)); - memset(moveMod, 0, sizeof(MovementModule)); - - actor_initModule((ActorModule*)moveMod, (Logic*)dispatch); - actor_setupSmartObj(moveMod); - - moveMod->header.func = defaultActorFunc; - moveMod->header.freeFunc = nullptr; - moveMod->header.type = ACTMOD_MOVE; - moveMod->updateTargetFunc = defaultUpdateTargetFunc; - // Overwrites width even though it was set in actor_setupSmartObj() - moveMod->physics.width = 0x18000; // 1.5 units - moveMod->physics.wall = nullptr; - moveMod->physics.u24 = 0; - moveMod->physics.obj = moveMod->header.obj; - - return moveMod; - } - - void actorLogicCleanupFunc(Logic* logic) - { - ActorDispatch* dispatch = (ActorDispatch*)logic; - for (s32 i = 0; i < ACTOR_MAX_MODULES; i++) - { - ActorModule* module = dispatch->modules[ACTOR_MAX_MODULES - 1 - i]; - if (module) - { - if (module->freeFunc) - { - module->freeFunc(module); - } - else - { - level_free(module); - } - } - } - - if (dispatch->freeTask) - { - s_msgEntity = dispatch->logic.obj; - task_runAndReturn(dispatch->freeTask, MSG_FREE); - } - - ActorModule* moveMod = (ActorModule*)dispatch->moveMod; - if (moveMod && moveMod->freeFunc) - { - moveMod->freeFunc(moveMod); - } - deleteLogicAndObject((Logic*)dispatch); - allocator_deleteItem(s_istate.actorDispatch, dispatch); - } - - JBool actor_advanceAnimation(LogicAnimation* anim, SecObject* obj) - { - if (!anim->prevTick) - { - anim->prevTick = s_frameTicks[anim->frameRate]; - anim->flags &= ~AFLAG_READY; - - obj->frame = floor16(anim->startFrame); - anim->frame = anim->startFrame; - } - else - { - anim->frame += s_frameTicks[anim->frameRate] - anim->prevTick; - anim->prevTick = s_frameTicks[anim->frameRate]; - - fixed16_16 endFrame = anim->startFrame + anim->frameCount; - if (anim->frame >= endFrame) - { - if (anim->flags & AFLAG_PLAYED) - { - endFrame -= ONE_16; - anim->frame = endFrame; - obj->frame = floor16(endFrame); - return JTRUE; - } - - while (anim->frame >= endFrame) - { - anim->frame -= anim->frameCount; - } - } - obj->frame = floor16(anim->frame); - } - return JFALSE; - } - - // Get the animation index for the current 'action' from s_curLogic. - s32 actor_getAnimationIndex(s32 action) - { - ActorDispatch* logic = (ActorDispatch*)s_actorState.curLogic; - SecObject* obj = logic->logic.obj; - if (obj->type == OBJ_TYPE_SPRITE && logic->animTable) - { - return logic->animTable[action]; - } - return -1; - } - - void actor_setupAnimation(s32 animIdx, LogicAnimation* aiAnim) - { - ActorDispatch* actorLogic = (ActorDispatch*)s_actorState.curLogic; - const s32* animTable = actorLogic->animTable; - SecObject* obj = actorLogic->logic.obj; - - aiAnim->flags |= AFLAG_READY; - if (obj->type & OBJ_TYPE_SPRITE) - { - aiAnim->prevTick = 0; - aiAnim->animId = animTable[animIdx]; - aiAnim->startFrame = 0; - aiAnim->frame = 0; - assert(obj->wax); - if (aiAnim->animId != -1 && obj->wax) - { - // In DOS there is no check but for some reason it doesn't crash. - // On Windows this crashes if animId is too large, so clamp. - s32 animId = min(aiAnim->animId, obj->wax->animCount - 1); - WaxAnim* anim = WAX_AnimPtr(obj->wax, animId); - assert(anim); - if (anim) - { - aiAnim->frameCount = intToFixed16(anim->frameCount); - aiAnim->frameRate = anim->frameRate; - if (anim->frameRate >= 12) - { - aiAnim->frameRate = 12; - } - aiAnim->flags &= ~AFLAG_READY; - } - } - } - } - - void actor_setupBossAnimation(SecObject* obj, s32 animId, LogicAnimation* anim) - { - anim->flags |= AFLAG_READY; - if (obj->type == OBJ_TYPE_SPRITE) - { - const Wax* wax = obj->wax; - // In DOS there is no check but for some reason it doesn't crash with an animId that is too large. - // On Windows this crashes if animId is too large, so clamp. - animId = wax ? min(animId, wax->animCount - 1) : -1; - - anim->prevTick = 0; - anim->animId = animId; - anim->startFrame = 0; - if (animId != -1) - { - WaxAnim* waxAnim = WAX_AnimPtr(wax, animId); - assert(waxAnim); - - anim->frameCount = intToFixed16(waxAnim->frameCount); - anim->frameRate = waxAnim->frameRate; - if (anim->frameRate >= 12) - { - anim->frameRate = 12; - } - anim->flags &= ~AFLAG_READY; - } - } - } - - void actor_setAnimFrameRange(LogicAnimation* anim, s32 startFrame, s32 endFrame) - { - anim->frameCount = intToFixed16(endFrame - startFrame + 1); - anim->startFrame = intToFixed16(startFrame); - } - - void actor_setCurAnimation(LogicAnimation* aiAnim) - { - if (aiAnim->animId != -1) - { - s_actorState.curAnimation = aiAnim; - } - } - - JBool actor_canDie(PhysicsActor* phyActor) - { - SecObject* obj = phyActor->moveMod.header.obj; - RSector* sector = obj->sector; - if (sector->secHeight <= 0 && obj->posWS.y <= sector->floorHeight) - { - if (TFE_Jedi::abs(phyActor->vel.x) >= FIXED(5) || TFE_Jedi::abs(phyActor->vel.z) >= FIXED(5)) - { - return JFALSE; - } - - fixed16_16 ceilHeight, floorHeight; - sector_getObjFloorAndCeilHeight(sector, obj->posWS.y, &floorHeight, &ceilHeight); - if (obj->posWS.y < floorHeight) - { - return JFALSE; - } - } - return JTRUE; - } - - // Kill the actor, this clears the current logic so the rest of the task function proceeds correctly. - void actor_kill() - { - actorLogicCleanupFunc(s_actorState.curLogic); - s_actorState.curLogic = nullptr; - } - - // Removes logics other than the current Logic. - void actor_removeLogics(SecObject* obj) - { - Logic** logicList = (Logic**)allocator_getHead((Allocator*)obj->logic); - while (logicList) - { - Logic* logic = *logicList; - if (logic != s_actorState.curLogic) - { - if (logic->cleanupFunc) { logic->cleanupFunc(logic); } - } - logicList = (Logic**)allocator_getNext((Allocator*)obj->logic); - }; - } - - void actor_addVelocity(fixed16_16 pushX, fixed16_16 pushY, fixed16_16 pushZ) - { - ActorDispatch* actorLogic = (ActorDispatch*)s_actorState.curLogic; - actorLogic->vel.x += pushX; - actorLogic->vel.y += pushY; - actorLogic->vel.z += pushZ; - } - - void actor_hitEffectMsgFunc(MessageType msg, void* logic) - { - ActorDispatch* dispatch = (ActorDispatch*)logic; - s_actorState.curLogic = (Logic*)logic; - SecObject* obj = s_actorState.curLogic->obj; - for (s32 i = 0; i < ACTOR_MAX_MODULES; i++) - { - ActorModule* module = dispatch->modules[ACTOR_MAX_MODULES - 1 - i]; - if (module && module->msgFunc) - { - const Tick nextTick = module->msgFunc(msg, module, dispatch->moveMod); - if (nextTick != 0xffffffff) - { - module->nextTick = nextTick; - } - } - } - - if (msg == MSG_WAKEUP) - { - if (dispatch->flags & 1) - { - gameMusic_startFight(); - } - - if ((dispatch->flags & 4) && (dispatch->flags & 1)) - { - if (s_actorState.nextAlertTick < s_curTick) - { - if (dispatch->flags & 16) // Officer alert list. - { - dispatch->alertSndID = sound_playCued(s_officerAlertSndSrc[s_actorState.officerAlertIndex], obj->posWS); - s_actorState.officerAlertIndex++; - if (s_actorState.officerAlertIndex >= 4) - { - s_actorState.officerAlertIndex = 0; - } - } - else if (dispatch->flags & 32) // Storm trooper alert list - { - dispatch->alertSndID = sound_playCued(s_stormAlertSndSrc[s_actorState.stormtrooperAlertIndex], obj->posWS); - s_actorState.stormtrooperAlertIndex++; - if (s_actorState.stormtrooperAlertIndex >= 8) - { - s_actorState.stormtrooperAlertIndex = 0; - } - } - else // Single alert. - { - dispatch->alertSndID = sound_playCued(dispatch->alertSndSrc, obj->posWS); - } - s_actorState.nextAlertTick = s_curTick + 291; // ~2 seconds between alerts - } - dispatch->flags &= 0xfffffffe; - } - } - else if (msg == MSG_DAMAGE || msg == MSG_EXPLOSION) - { - if (dispatch->flags & 1) - { - gameMusic_startFight(); - } - dispatch->flags &= ~1; - s_actorState.curAnimation = nullptr; - } - } - - void actor_sendTerminalVelMsg(SecObject* obj) - { - message_sendToObj(obj, MSG_TERMINAL_VEL, actor_hitEffectMsgFunc); - } - - void actor_handlePhysics(MovementModule* moveMod, vec3_fixed* vel) - { - SecObject* obj = moveMod->physics.obj; - assert(obj && obj->sector); - - moveMod->delta = { 0, 0, 0 }; - if (vel->x) { moveMod->delta.x = mul16(vel->x, s_deltaTime); } - if (vel->y) { moveMod->delta.y = mul16(vel->y, s_deltaTime); } - if (vel->z) { moveMod->delta.z = mul16(vel->z, s_deltaTime); } - - fixed16_16 friction = ONE_16 - s_deltaTime*2; - if (moveMod->collisionFlags & ACTORCOL_GRAVITY) - { - fixed16_16 ceilHeight, floorHeight; - sector_getObjFloorAndCeilHeight(obj->sector, obj->posWS.y, &floorHeight, &ceilHeight); - - // Add gravity to our velocity if the object is not on the floor. - if (obj->posWS.y < floorHeight) - { - vel->y += mul16(s_gravityAccel, s_deltaTime); - } - - JBool vertCollision = JFALSE; - JBool hitCeiling = JFALSE; - // Did the object hit the ceiling? - if (vel->y < 0 && obj->posWS.y <= ceilHeight + moveMod->physics.height) - { - vertCollision = JTRUE; - hitCeiling = JTRUE; - } - // Or the floor? - else if (obj->posWS.y >= floorHeight) - { - vertCollision = JTRUE; - hitCeiling = JFALSE; - } - - // Die once falling fast enough. - if (vel->y > FIXED(160)) - { - actor_sendTerminalVelMsg(obj); - } - - if (vertCollision) - { - // Clear out the yVel if the object hits the floor or ceiling. - if ((hitCeiling && vel->y < 0) || (!hitCeiling && vel->y >= 0)) - { - vel->y = 0; - } - } - else if (vel->y < 0 || obj->posWS.y < floorHeight) - { - friction = ONE_16 - s_deltaTime / 2; - } - } - else - { - vel->y = mul16(vel->y, friction); - } - vel->x = mul16(vel->x, friction); - vel->z = mul16(vel->z, friction); - - if (TFE_Jedi::abs(vel->x) < ACTOR_MIN_VELOCITY) { vel->x = 0; } - if (TFE_Jedi::abs(vel->y) < ACTOR_MIN_VELOCITY) { vel->y = 0; } - if (TFE_Jedi::abs(vel->z) < ACTOR_MIN_VELOCITY) { vel->z = 0; } - } - - void actorLogicMsgFunc(MessageType msg) - { - if (msg == MSG_FREE) - { - actorLogicCleanupFunc((Logic*)s_msgTarget); - } - else - { - actor_hitEffectMsgFunc(msg, s_msgTarget); - } - } - - void actorLogicTaskFunc(MessageType msg) - { - task_begin; - while (msg != MSG_FREE_TASK) - { - entity_yield(TASK_NO_DELAY); - if (msg == MSG_RUN_TASK) - { - ActorDispatch* dispatch = (ActorDispatch*)allocator_getHead(s_istate.actorDispatch); - while (dispatch) - { - SecObject* obj = dispatch->logic.obj; - const u32 flags = dispatch->flags; - if ((flags & 1) && (flags & 4)) - { - if (dispatch->nextTick < s_curTick) - { - dispatch->nextTick = s_curTick + dispatch->delay; - if (actor_isObjectVisible(obj, s_playerObject, dispatch->fov, dispatch->awareRange)) - { - message_sendToObj(obj, MSG_WAKEUP, actor_hitEffectMsgFunc); - gameMusic_startFight(); - collision_effectObjectsInRangeXZ(obj->sector, FIXED(150), obj->posWS, hitEffectWakeupFunc, obj, ETFLAG_AI_ACTOR); - } - } - } - else - { - s_actorState.curLogic = (Logic*)dispatch; - s_actorState.curAnimation = nullptr; - for (s32 i = 0; i < ACTOR_MAX_MODULES; i++) - { - ActorModule* module = dispatch->modules[ACTOR_MAX_MODULES - 1 - i]; - if (module && module->func && module->nextTick < s_curTick) - { - module->nextTick = module->func(module, dispatch->moveMod); - } - } - - if (s_actorState.curLogic && !(dispatch->flags & 1)) - { - MovementModule* moveMod = dispatch->moveMod; - if (moveMod && moveMod->header.func) - { - actor_handlePhysics(moveMod, &dispatch->vel); - moveMod->header.func((ActorModule*)moveMod, moveMod); - } - - if ((obj->type & OBJ_TYPE_SPRITE) && s_actorState.curAnimation) - { - obj->anim = s_actorState.curAnimation->animId; - if (actor_advanceAnimation(s_actorState.curAnimation, obj)) - { - // The animation has finished. - s_actorState.curAnimation->flags |= AFLAG_READY; - } - } - } - } - - dispatch = (ActorDispatch*)allocator_getNext(s_istate.actorDispatch); - } - } - } - task_end; - } - - // This is really a list of bosses: - // TODO: Rename "physics" actor as appopriate. - void actorPhysicsTaskFunc(MessageType msg) - { - task_begin; - while (msg != MSG_FREE_TASK) - { - task_localBlockBegin; - PhysicsActor** phyObjPtr = (PhysicsActor**)list_getHead(s_physicsActors); - while (phyObjPtr) - { - PhysicsActor* phyObj = *phyObjPtr; - phyObj->moveMod.physics.wall = nullptr; - phyObj->moveMod.physics.u24 = 0; - if (phyObj->moveMod.target.flags & TARGET_MOVE_ROT) - { - actor_applyTransform(&phyObj->moveMod); - } - actor_handlePhysics(&phyObj->moveMod, &phyObj->vel); - - if ((phyObj->moveMod.target.flags & TARGET_MOVE_XZ) || (phyObj->moveMod.target.flags & TARGET_MOVE_Y) || phyObj->vel.x || phyObj->vel.y || phyObj->vel.z) - { - actor_handleMovementAndCollision(&phyObj->moveMod); - CollisionInfo* physics = &phyObj->moveMod.physics; - if (physics->responseStep) - { - handleCollisionResponseSimple(physics->responseDir.x, physics->responseDir.z, &phyObj->vel.x, &phyObj->vel.z); - } - } - - SecObject* obj = phyObj->moveMod.header.obj; - LogicAnimation* anim = &phyObj->anim; - if (obj->type & OBJ_TYPE_SPRITE) - { - if (!(anim->flags & AFLAG_READY)) - { - obj->anim = anim->animId; - if (actor_advanceAnimation(anim, obj)) - { - anim->flags |= AFLAG_READY; - } - } - } - - phyObjPtr = (PhysicsActor**)list_getNext(s_physicsActors); - } - task_localBlockEnd; - do - { - entity_yield(TASK_NO_DELAY); - } while (msg != MSG_RUN_TASK); - } - task_end; - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/actor.h b/components/darkforces/tfe/TFE_DarkForces/Actor/actor.h deleted file mode 100644 index 6dc88c99..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/actor.h +++ /dev/null @@ -1,215 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Core Actor/AI functionality. -// ----------------------------- -// AI in Dark Forces is handled by a central "dispatcher" with a -// a number of "modules" attached that handle specific functionality. -// This is basically a primitive ECS-style system. -// -// Each module has function pointers to handle updates, message, damage, -// and destruction. During the AI update, the dispatch will loop over -// each module and call its update function. There is also some communication -// between modules to keep redundant data up to date. -// -// Dispatcher (ActorDispatcher in TFE): -// + ActorModule modules[] -// + MovementModule moveMod -- this could have been added to the list -// but every AI actor has it. -// -// For example, a Stormtrooper is: -// Dispatcher -// + Damage Module - -// Holds HP, drop item, hurt and die sounds. This is the -// getting hurt and dying functionality. -// + Attack Module - -// Handles attacking functionality, and includes the -// projectile type, melee range, etc. -// + Thinker Module - -// Handles overall state and sets targets for movement. -// + Movement Module - -// Handles the actual movement, collision detection and -// response, basic animation. -////////////////////////////////////////////////////////////////////// -#include "actorModule.h" -#include "../sound.h" -#include -#include -#include - -/////////////////////////////////////////// -// Constants -/////////////////////////////////////////// -enum ActorAlert -{ - ALERT_GAMOR = 0, - ALERT_REEYEE, - ALERT_BOSSK, - ALERT_CREATURE, - ALERT_PROBE, - ALERT_INTDROID, - ALERT_COUNT -}; -enum AgentActionSounds -{ - AGENTSND_REMOTE_2 = 0, - AGENTSND_AXE_1, - AGENTSND_INTSTUN, - AGENTSND_PROBFIRE_11, - AGENTSND_PROBFIRE_12, - AGENTSND_CREATURE2, - AGENTSND_PROBFIRE_13, - AGENTSND_STORM_HURT, - AGENTSND_GAMOR_2, - AGENTSND_REEYEE_2, - AGENTSND_BOSSK_3, - AGENTSND_CREATURE_HURT, - AGENTSND_STORM_DIE, - AGENTSND_REEYEE_3, - AGENTSND_BOSSK_DIE, - AGENTSND_GAMOR_1, - AGENTSND_CREATURE_DIE, - AGENTSND_EEEK_3, - AGENTSND_SMALL_EXPLOSION, - AGENTSND_PROBE_ALM, - AGENTSND_TINY_EXPLOSION, - AGENTSND_COUNT -}; - -enum -{ - OFFICER_ALERT_COUNT = 4, - STORM_ALERT_COUNT = 8, - ACTOR_MIN_VELOCITY = 0x1999, // < 0.1 - ACTOR_MAX_MODULES = 6, -}; - -enum ActorCollisionFlags -{ - ACTORCOL_GRAVITY = FLAG_BIT(1), -}; - -// Forward Declarations. -struct ActorModule; -struct MovementModule; -struct AttackModule; -struct DamageModule; -struct ThinkerModule; -struct LogicAnimation; -struct PhysicsActor; -struct ActorTarget; - -// Logic for 'actors' - -// an Actor is something with animated 'actions' that can move around in the world. -// The "Dispatch" logic is the core actor, so rename to match. -struct ActorDispatch -{ - Logic logic; - - ActorModule* modules[ACTOR_MAX_MODULES]; - MovementModule* moveMod; - const s32* animTable; - - Tick delay; - Tick nextTick; - - SoundSourceId alertSndSrc; - SoundEffectId alertSndID; - - angle14_32 fov; - fixed16_16 awareRange; - - vec3_fixed vel; - vec2_fixed lastPlayerPos; - - Task* freeTask; - u32 flags; -}; - -struct ActorState -{ - LogicAnimation* curAnimation; - Logic* curLogic; - AttackModule* attackMod; - Tick nextAlertTick; - u32 officerAlertIndex; - u32 stormtrooperAlertIndex; -}; - -// Clear and set flags in a visually simple way. -#define FLAGS_CLEAR_SET(flags, flagsToClear, flagsToSet) \ -flags &= ~(flagsToClear); \ -flags |= (flagsToSet) - -namespace TFE_DarkForces -{ - void actor_clearState(); - void actor_exitState(); - - void actor_loadSounds(); - void actor_allocatePhysicsActorList(); - void actor_addPhysicsActorToWorld(PhysicsActor* actor); - void actor_removePhysicsActorFromWorld(PhysicsActor* phyActor); - void actor_createTask(); - - ActorDispatch* actor_createDispatch(SecObject* obj, LogicSetupFunc* setupFunc); - DamageModule* actor_createDamageModule(ActorDispatch* dispatch); - MovementModule* actor_createMovementModule(ActorDispatch* dispatch); - void actor_addModule(ActorDispatch* dispatch, ActorModule* module); - - void actor_hitEffectMsgFunc(MessageType msg, void* logic); - void actor_kill(); - void actor_initModule(ActorModule* module, Logic* logic); - JBool actor_canDie(PhysicsActor* phyActor); - JBool actor_handleSteps(MovementModule* moveMod, ActorTarget* target); - JBool actor_arrivedAtTarget(ActorTarget* target, SecObject* obj); - JBool actor_canSeeObjFromDist(SecObject* actorObj, SecObject* obj); - JBool actor_canSeeObject(SecObject* actorObj, SecObject* obj); - - s32 actor_getAnimationIndex(s32 action); - void actor_setupAnimation(s32 animIdx, LogicAnimation* aiAnim); - void actor_setupBossAnimation(SecObject* obj, s32 animId, LogicAnimation* anim); - void actor_setAnimFrameRange(LogicAnimation* anim, s32 startFrame, s32 endFrame); - void actor_addVelocity(fixed16_16 pushX, fixed16_16 pushY, fixed16_16 pushZ); - void actor_removeLogics(SecObject* obj); - void actor_setupSmartObj(MovementModule* moveMod); - void actor_setCurAnimation(LogicAnimation* aiAnim); - void actor_updatePlayerVisiblity(JBool playerVis, fixed16_16 posX, fixed16_16 posZ); - void actor_changeDirFromCollision(MovementModule* moveMod, ActorTarget* target, Tick* prevColTick); - void actor_jumpToTarget(PhysicsActor* physicsActor, SecObject* obj, vec3_fixed target, fixed16_16 speed, angle14_32 angleOffset); - void actor_leadTarget(ProjectileLogic* proj); - void actor_handleBossDeath(PhysicsActor* physicsActor); - void actor_removeRandomCorpse(); - - angle14_32 actor_offsetTarget(fixed16_16* targetX, fixed16_16* targetZ, fixed16_16 targetOffset, fixed16_16 targetVariation, angle14_32 angle, angle14_32 angleVariation); - - AttackModule* actor_createAttackModule(ActorDispatch* dispatch); - ThinkerModule* actor_createThinkerModule(ActorDispatch* dispatch); - void actor_thinkerModuleInit(ThinkerModule* thinkerMod); - void actor_setupInitAnimation(); - void actor_setDeathCollisionFlags(); - - // Returns JTRUE if 'actorObj' can see 'obj' - // The object must be as close or closer than 'closeDist' or be within the fov of the 'actorObj'. - // Also the distance between actorObj and obj must be less than 200 - 256 units (randomized), and this value is - // adjusted based on the darkness level of the area where 'obj' is (so it is harder to see objects in the dark). - // Conversely the headlamp will make 'obj' visible from further away. - JBool actor_isObjectVisible(SecObject* actorObj, SecObject* obj, angle14_32 fov, fixed16_16 closeDist); - - extern ActorState s_actorState; - extern SoundSourceId s_alertSndSrc[ALERT_COUNT]; - extern SoundSourceId s_officerAlertSndSrc[OFFICER_ALERT_COUNT]; - extern SoundSourceId s_stormAlertSndSrc[STORM_ALERT_COUNT]; - extern SoundSourceId s_agentSndSrc[AGENTSND_COUNT]; - - extern JBool s_aiActive; - // Special yield macro for entities so that LAREDLITE works. - #define entity_yield(t) \ - do \ - { \ - task_yield(s_aiActive ? t : 290); \ - } while (!s_aiActive); - - // Helper macro to get local object distance from player - #define playerDist(obj) fixedSqrt(player_getSquaredDistance(local(obj))) -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/actorInternal.h b/components/darkforces/tfe/TFE_DarkForces/Actor/actorInternal.h deleted file mode 100644 index 0962b016..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/actorInternal.h +++ /dev/null @@ -1,76 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Core Actor/AI functionality. -// ----------------------------- -// AI in Dark Forces is handled by a central "dispatcher" with a -// a number of "modules" attached that handle specific functionality. -// This is basically a primitive ECS-style system. -// -// Each module has function pointers to handle updates, message, damage, -// and destruction. During the AI update, the dispatch will loop over -// each module and call its update function. There is also some communication -// between modules to keep redundant data up to date. -// -// Dispatcher (ActorDispatcher in TFE): -// + ActorModule modules[] -// + MovementModule moveMod -- this could have been added to the list -// but every AI actor has it. -// -// For example, a Stormtrooper is: -// Dispatcher -// + Damage Module - -// Holds HP, drop item, hurt and die sounds. This is the -// getting hurt and dying functionality. -// + Attack Module - -// Handles attacking functionality, and includes the -// projectile type, melee range, etc. -// + Thinker Module - -// Handles overall state and sets targets for movement. -// + Movement Module - -// Handles the actual movement, collision detection and -// response, basic animation. -////////////////////////////////////////////////////////////////////// -#include "actorModule.h" -#include "../sound.h" -#include -#include -#include - -namespace TFE_DarkForces -{ - /////////////////////////////////////////// - // Internal State - /////////////////////////////////////////// - struct ActorInternalState - { - Allocator* actorDispatch; - Task* actorTask; - Task* actorPhysicsTask; - JBool objCollisionEnabled; - }; - extern ActorInternalState s_istate; - extern List* s_physicsActors; - - void actorLogicCleanupFunc(Logic* logic); - JBool defaultActorFunc(ActorModule* module, MovementModule* moveMod); - JBool defaultUpdateTargetFunc(MovementModule* moveMod, ActorTarget* target); - JBool defaultAttackFunc(ActorModule* module, MovementModule* moveMod); - JBool defaultAttackMsgFunc(s32 msg, ActorModule* module, MovementModule* moveMod); - JBool defaultDamageFunc(ActorModule* module, MovementModule* moveMod); - JBool defaultDamageMsgFunc(s32 msg, ActorModule* module, MovementModule* moveMod); - JBool defaultThinkerFunc(ActorModule* module, MovementModule* moveMod); - JBool flyingModuleFunc(ActorModule* module, MovementModule* moveMod); - JBool flyingModuleFunc_Remote(ActorModule* module, MovementModule* moveMod); - - // Alternate Damage functions - JBool sceneryLogicFunc(ActorModule* module, MovementModule* moveMod); - JBool sceneryMsgFunc(s32 msg, ActorModule* module, MovementModule* moveMod); - JBool exploderFunc(ActorModule* module, MovementModule* moveMod); - JBool exploderMsgFunc(s32 msg, ActorModule* module, MovementModule* moveMod); - JBool sewerCreatureAiFunc(ActorModule* module, MovementModule* moveMod); - JBool sewerCreatureAiMsgFunc(s32 msg, ActorModule* module, MovementModule* moveMod); - - // Alternate Attack function. - JBool sewerCreatureEnemyFunc(ActorModule* module, MovementModule* moveMod); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/actorModule.h b/components/darkforces/tfe/TFE_DarkForces/Actor/actorModule.h deleted file mode 100644 index a789aceb..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/actorModule.h +++ /dev/null @@ -1,214 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// AI Actor structures - see actor.h for a full explaination. -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "actor.h" - -using namespace TFE_Jedi; -using namespace TFE_DarkForces; - -struct ActorModule; -struct MovementModule; -struct ActorTarget; -struct Task; - -enum LogicAnimFlags -{ - AFLAG_PLAYED = FLAG_BIT(0), - AFLAG_READY = FLAG_BIT(1), -}; - -enum LogicAnimState : u32 -{ - STATE_DELAY = 0u, - STATE_ANIMATEATTACK, - STATE_FIRE1, - STATE_ANIMATE1, - STATE_FIRE2, - STATE_ANIMATE2, - STATE_COUNT -}; - -typedef JBool(*ActorFunc)(ActorModule*, MovementModule*); -typedef JBool(*ActorMsgFunc)(s32 msg, ActorModule*, MovementModule*); -typedef void(*ActorAttribFunc)(ActorModule*); -typedef u32(*ActorTargetFunc)(MovementModule*, ActorTarget*); -typedef void(*ActorFreeFunc)(void*); - -struct LogicAnimation -{ - s32 frameRate; - fixed16_16 frameCount; - Tick prevTick; - fixed16_16 frame; - fixed16_16 startFrame; - u32 flags; - s32 animId; - LogicAnimState state; -}; - -struct ActorTiming -{ - Tick delay; - Tick searchDelay; - Tick meleeDelay; - Tick rangedDelay; - Tick losDelay; // time to search for line of sight (LOS). - Tick nextTick; -}; - -enum ActorModuleType : u32 -{ - ACTMOD_MOVE = 0, - ACTMOD_ATTACK, - ACTMOD_DAMAGE, - ACTMOD_THINKER, - ACTMOD_FLYER, - ACTMOD_FLYER_REMOTE, - ACTMOD_COUNT, - ACTMOD_INVALID = ACTMOD_COUNT -}; - -enum TargetFlags -{ - TARGET_MOVE_XZ = FLAG_BIT(0), - TARGET_MOVE_Y = FLAG_BIT(1), - TARGET_MOVE_ROT = FLAG_BIT(2), - TARGET_FREEZE = FLAG_BIT(3), - TARGET_ALL_MOVE = TARGET_MOVE_XZ | TARGET_MOVE_Y | TARGET_MOVE_ROT, - TARGET_ALL = TARGET_ALL_MOVE | TARGET_FREEZE -}; - -enum AttackFlags -{ - ATTFLAG_NONE = 0, - ATTFLAG_MELEE = FLAG_BIT(0), // Has melee attacks - ATTFLAG_RANGED = FLAG_BIT(1), // Has ranged attacks - ATTFLAG_LIT_MELEE = FLAG_BIT(2), // Lights up when melee attacks - ATTFLAG_LIT_RNG = FLAG_BIT(3), // Lights up when range attacks - ATTFLAG_ALL = ATTFLAG_MELEE | ATTFLAG_RANGED | ATTFLAG_LIT_MELEE | ATTFLAG_LIT_RNG -}; - -struct ActorModule -{ - ActorModuleType type; - - ActorFunc func; - ActorMsgFunc msgFunc; - ActorAttribFunc attribFunc; - ActorFreeFunc freeFunc; - - Tick nextTick; - SecObject* obj; -}; - -struct ActorTarget -{ - vec3_fixed pos; - angle14_16 pitch; - angle14_16 yaw; - angle14_16 roll; - s16 pad; - - fixed16_16 speed; - fixed16_16 speedVert; - fixed16_16 speedRotation; - u32 flags; -}; - -struct AttackModule -{ - ActorModule header; - ActorTarget target; - ActorTiming timing; - LogicAnimation anim; - - fixed16_16 fireSpread; - Tick accuracyNextTick; - vec3_fixed fireOffset; - - ProjectileType projType; - SoundSourceId attackSecSndSrc; - SoundSourceId attackPrimSndSrc; - fixed16_16 meleeRange; - fixed16_16 minDist; - fixed16_16 maxDist; - fixed16_16 meleeDmg; - fixed16_16 meleeRate; - u32 attackFlags; // see AttackFlags above. -}; - -struct MovementModule -{ - ActorModule header; - ActorTargetFunc updateTargetFunc; - CollisionInfo physics; - ActorTarget target; - - vec3_fixed delta; - RWall* collisionWall; - u32 unused; // member in structure but not actually used, other than being initialized. - u32 collisionFlags; -}; - -struct ThinkerModule -{ - ActorModule header; - ActorTarget target; - - Tick delay; - Tick maxWalkTime; - Tick startDelay; - LogicAnimation anim; - - Tick nextTick; - Tick playerLastSeen; - Tick prevColTick; - - fixed16_16 targetOffset; - fixed16_16 targetVariation; - angle14_32 approachVariation; -}; - -struct DamageModule -{ - AttackModule attackMod; - fixed16_16 hp; - ItemId itemDropId; - - // Sound source IDs - SoundSourceId hurtSndSrc; - SoundSourceId dieSndSrc; - // Currently playing hurt sound effect ID. - SoundEffectId hurtSndID; - - JBool stopOnHit; - HitEffectID dieEffect; -}; - -struct PhysicsActor -{ - MovementModule moveMod; - LogicAnimation anim; - PhysicsActor** parent; - - vec3_fixed vel; - SoundEffectId moveSndId; - - vec2_fixed lastPlayerPos; - - fixed16_16 hp; - Task* actorTask; - JBool alive; - s32 state; -}; \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/actorSerialization.cpp b/components/darkforces/tfe/TFE_DarkForces/Actor/actorSerialization.cpp deleted file mode 100644 index 0ec72e26..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/actorSerialization.cpp +++ /dev/null @@ -1,470 +0,0 @@ -#include - -#include "actor.h" -#include "actorInternal.h" -#include "actorSerialization.h" -#include "../logic.h" -#include "../gameMusic.h" -#include "../sound.h" -#include "animTables.h" -#include "actorModule.h" -#include "mousebot.h" -#include "dragon.h" -#include "bobaFett.h" -#include "welder.h" -#include "turret.h" -#include "phaseOne.h" -#include "phaseTwo.h" -#include "phaseThree.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - typedef void(*ActorModuleSerializeFn)(Stream*, ActorModule*&, ActorDispatch*); - static const ActorModuleSerializeFn c_moduleSerFn[]= - { - actor_serializeMovementModule, // ACTMOD_MOVE - actor_serializeAttackModule, // ACTMOD_ATTACK - actor_serializeDamageModule, // ACTMOD_DAMAGE - actor_serializeThinkerModule, // ACTMOD_THINKER - actor_serializeFlyerModule, // ACTMOD_FLYER - actor_serializeFlyerRemoteModule, // ACTMOD_FLYER_REMOTE - nullptr, // ACTMOD_INVALID - }; - - void actorDispatch_serialize(Logic*& logic, SecObject* obj, Stream* stream) - { - ActorDispatch* dispatch = nullptr; - if (serialization_getMode() == SMODE_WRITE) - { - dispatch = (ActorDispatch*)logic; - } - else - { - dispatch = (ActorDispatch*)allocator_newItem(s_istate.actorDispatch); - memset(dispatch, 0, sizeof(ActorDispatch)); - - logic = (Logic*)dispatch; - logic->task = s_istate.actorTask; - logic->cleanupFunc = actorLogicCleanupFunc; - // This is needed for the modules. - logic->obj = obj; - } - - serialization_serializeDfSound(stream, SaveVersionInit, &dispatch->alertSndSrc); - SERIALIZE(SaveVersionInit, dispatch->delay, 72); - SERIALIZE(SaveVersionInit, dispatch->nextTick, 0); - SERIALIZE(SaveVersionInit, dispatch->fov, 9557); // ~210 degrees - SERIALIZE(SaveVersionInit, dispatch->awareRange, FIXED(20)); - SERIALIZE(SaveVersionInit, dispatch->vel, {0}); - SERIALIZE(SaveVersionInit, dispatch->lastPlayerPos, {0}); - SERIALIZE(SaveVersionInit, dispatch->flags, 4); - // Animation Table. - s32 animTableIndex = -1; - if (serialization_getMode() == SMODE_WRITE) - { - animTableIndex = animTables_getIndex(dispatch->animTable); - } - SERIALIZE(SaveVersionInit, animTableIndex, -1); - if (serialization_getMode() == SMODE_READ) - { - dispatch->animTable = animTables_getTable(animTableIndex); - } - // Movement module. - u8 hasMoveMod = dispatch->moveMod ? 1 : 0; - ActorModule* moveMod = (serialization_getMode() == SMODE_WRITE) ? (ActorModule*)dispatch->moveMod : nullptr; - SERIALIZE(SaveVersionInit, hasMoveMod, 0); - if (hasMoveMod) - { - actor_serializeMovementModule(stream, moveMod, dispatch); - } - if (serialization_getMode() == SMODE_READ) - { - dispatch->moveMod = (MovementModule*)moveMod; - } - // Module list. - s32 moduleCount = 0; - if (serialization_getMode() == SMODE_WRITE) - { - for (s32 i = 0; i < ACTOR_MAX_MODULES; i++) - { - if (!dispatch->modules[i]) { break; } - moduleCount++; - } - } - SERIALIZE(SaveVersionInit, moduleCount, 0); - for (s32 i = 0; i < moduleCount; i++) - { - ActorModule* mod = dispatch->modules[i]; - ActorModuleType type; - if (serialization_getMode() == SMODE_WRITE) - { - type = mod->type; - } - SERIALIZE(SaveVersionInit, type, ACTMOD_INVALID); - type = type < ACTMOD_INVALID ? type : ACTMOD_INVALID; - if (c_moduleSerFn[type]) - { - c_moduleSerFn[type](stream, dispatch->modules[i], dispatch); - } - else - { - TFE_System::logWrite(LOG_ERROR, "Actor", "Actor serialization failed - unknown module %d.", type); - assert(0); - } - if (serialization_getMode() == SMODE_READ && dispatch->modules[i]) - { - dispatch->modules[i]->type = type; - } - } - if (serialization_getMode() == SMODE_READ) - { - // This will be filled in a fixup pass if needed. - dispatch->freeTask = nullptr; - } - } - - void actor_serializeObject(Stream* stream, SecObject*& obj) - { - s32 objId; - if (serialization_getMode() == SMODE_WRITE) - { - objId = obj ? obj->serializeIndex : -1; - } - SERIALIZE(SaveVersionInit, objId, -1); - if (serialization_getMode() == SMODE_READ) - { - obj = objId >= 0 ? objData_getObjectBySerializationId(objId) : nullptr; - } - } - - void actor_serializeWall(Stream* stream, RWall*& wall) - { - RSector* wallSector = nullptr; - s32 wallId = -1; - if (serialization_getMode() == SMODE_WRITE) - { - wallSector = wall ? wall->sector : nullptr; - wallId = wall ? wall->id : -1; - } - serialization_serializeSectorPtr(stream, SaveVersionInit, wallSector); - SERIALIZE(SaveVersionInit, wallId, -1); - if (serialization_getMode() == SMODE_READ) - { - wall = nullptr; - if (wallSector && wallId >= 0) - { - wall = &wallSector->walls[wallId]; - } - } - } - - void actor_serializeCollisionInfo(Stream* stream, CollisionInfo* colInfo) - { - actor_serializeObject(stream, colInfo->obj); - actor_serializeObject(stream, colInfo->collidedObj); - actor_serializeWall(stream, colInfo->wall); - - SERIALIZE(SaveVersionInit, colInfo->offsetX, 0); - SERIALIZE(SaveVersionInit, colInfo->offsetY, 0); - SERIALIZE(SaveVersionInit, colInfo->offsetZ, 0); - SERIALIZE(SaveVersionInit, colInfo->botOffset, 0); - SERIALIZE(SaveVersionInit, colInfo->yPos, 0); - SERIALIZE(SaveVersionInit, colInfo->height, 0); - SERIALIZE(SaveVersionInit, colInfo->u24, 0); - SERIALIZE(SaveVersionInit, colInfo->width, 0); - SERIALIZE(SaveVersionInit, colInfo->flags, 0); - SERIALIZE(SaveVersionInit, colInfo->responseStep, 0); - SERIALIZE(SaveVersionInit, colInfo->responseDir, {0}); - SERIALIZE(SaveVersionInit, colInfo->responsePos, {0}); - SERIALIZE(SaveVersionInit, colInfo->responseAngle, 0); - - if (serialization_getMode() == SMODE_READ) - { - colInfo->unused = 0; - } - } - - void actor_serializeTarget(Stream* stream, ActorTarget* target) - { - SERIALIZE(SaveVersionInit, target->pos, {0}); - SERIALIZE(SaveVersionInit, target->pitch, 0); - SERIALIZE(SaveVersionInit, target->yaw, 0); - SERIALIZE(SaveVersionInit, target->roll, 0); - SERIALIZE(SaveVersionInit, target->speed, 0); - SERIALIZE(SaveVersionInit, target->speedVert, 0); - SERIALIZE(SaveVersionInit, target->speedRotation, 0); - SERIALIZE(SaveVersionInit, target->flags, 0); - - if (serialization_getMode() == SMODE_READ) - { - target->pad = 0; - } - } - - void actor_serializeTiming(Stream* stream, ActorTiming* timing) - { - SERIALIZE(SaveVersionInit, timing->delay, 0); - SERIALIZE(SaveVersionInit, timing->searchDelay, 0); - SERIALIZE(SaveVersionInit, timing->meleeDelay, 0); - SERIALIZE(SaveVersionInit, timing->rangedDelay, 0); - SERIALIZE(SaveVersionInit, timing->losDelay, 0); - SERIALIZE(SaveVersionInit, timing->nextTick, 0); - } - - void actor_serializeLogicAnim(Stream* stream, LogicAnimation* anim) - { - SERIALIZE(SaveVersionInit, anim->frameRate, 0); - SERIALIZE(SaveVersionInit, anim->frameCount, 0); - SERIALIZE(SaveVersionInit, anim->prevTick, 0); - SERIALIZE(SaveVersionInit, anim->frame, 0); - SERIALIZE(SaveVersionInit, anim->startFrame, 0); - SERIALIZE(SaveVersionInit, anim->flags, 0); - SERIALIZE(SaveVersionInit, anim->animId, 0); - SERIALIZE(SaveVersionInit, anim->state, STATE_DELAY); - } - - void actor_serializeMovementModuleBase(Stream* stream, MovementModule* moveMod) - { - actor_serializeCollisionInfo(stream, &moveMod->physics); - actor_serializeTarget(stream, &moveMod->target); - SERIALIZE(SaveVersionInit, moveMod->delta, { 0 }); - actor_serializeWall(stream, moveMod->collisionWall); - SERIALIZE(SaveVersionInit, moveMod->collisionFlags, 0); - } - - void actor_serializeMovementModule(Stream* stream, ActorModule*& mod, ActorDispatch* dispatch) - { - MovementModule* moveMod; - if (serialization_getMode() == SMODE_READ) - { - moveMod = (MovementModule*)level_alloc(sizeof(MovementModule)); - memset(moveMod, 0, sizeof(MovementModule)); - actor_initModule((ActorModule*)moveMod, (Logic*)dispatch); - mod = (ActorModule*)moveMod; - - moveMod->header.type = ACTMOD_MOVE; - moveMod->header.func = defaultActorFunc; - moveMod->header.freeFunc = nullptr; - moveMod->updateTargetFunc = defaultUpdateTargetFunc; - } - else - { - moveMod = (MovementModule*)mod; - assert(moveMod->header.func == defaultActorFunc || !moveMod->header.func); - assert(moveMod->updateTargetFunc == defaultUpdateTargetFunc || !moveMod->updateTargetFunc); - assert(moveMod->header.freeFunc == nullptr); - } - actor_serializeMovementModuleBase(stream, moveMod); - } - - void actor_serializeAttackModuleBase(Stream* stream, AttackModule* attackMod, ActorDispatch* dispatch) - { - actor_serializeTarget(stream, &attackMod->target); - actor_serializeTiming(stream, &attackMod->timing); - actor_serializeLogicAnim(stream, &attackMod->anim); - SERIALIZE(SaveVersionInit, attackMod->fireSpread, 0); - SERIALIZE(SaveVersionInit, attackMod->accuracyNextTick, 0); - SERIALIZE(SaveVersionInit, attackMod->fireOffset, {0}); - SERIALIZE(SaveVersionInit, attackMod->projType, PROJ_COUNT); - serialization_serializeDfSound(stream, SaveVersionInit, &attackMod->attackSecSndSrc); - serialization_serializeDfSound(stream, SaveVersionInit, &attackMod->attackPrimSndSrc); - SERIALIZE(SaveVersionInit, attackMod->meleeRange, 0); - SERIALIZE(SaveVersionInit, attackMod->minDist, 0); - SERIALIZE(SaveVersionInit, attackMod->maxDist, 0); - SERIALIZE(SaveVersionInit, attackMod->meleeDmg, 0); - SERIALIZE(SaveVersionInit, attackMod->meleeRate, 0); - SERIALIZE(SaveVersionInit, attackMod->attackFlags, 0); - } - - void actor_serializeAttackModule(Stream* stream, ActorModule*& mod, ActorDispatch* dispatch) - { - AttackModule* attackMod = nullptr; - s32 funcIdx = 0; - if (serialization_getMode() == SMODE_WRITE) - { - attackMod = (AttackModule*)mod; - funcIdx = attackMod->header.func == defaultAttackFunc ? 0 : 1; - } - SERIALIZE(SaveVersionInit, funcIdx, 0); - if (serialization_getMode() == SMODE_READ) - { - attackMod = (AttackModule*)level_alloc(sizeof(AttackModule)); - mod = (ActorModule*)attackMod; - memset(attackMod, 0, sizeof(AttackModule)); - actor_initModule(mod, (Logic*)dispatch); - - attackMod->header.func = funcIdx == 0 ? defaultAttackFunc : sewerCreatureEnemyFunc; - attackMod->header.freeFunc = nullptr; - attackMod->header.msgFunc = defaultAttackMsgFunc; - attackMod->header.type = ACTMOD_ATTACK; - } - else if (attackMod) - { - assert(attackMod->header.func == defaultAttackFunc || attackMod->header.func == sewerCreatureEnemyFunc); - assert(attackMod->header.msgFunc == defaultAttackMsgFunc); - assert(attackMod->header.freeFunc == nullptr); - } - assert(attackMod); - - actor_serializeAttackModuleBase(stream, attackMod, dispatch); - } - - const ActorFunc c_actorDamageFunc[] = - { - defaultDamageFunc, - sceneryLogicFunc, - exploderFunc, - sewerCreatureAiFunc, - }; - - const ActorMsgFunc c_actorDamageMsgFunc[] = - { - defaultDamageMsgFunc, - sceneryMsgFunc, - exploderMsgFunc, - sewerCreatureAiMsgFunc, - }; - - s32 actor_getDamageFuncIndex(ActorFunc func) - { - for (s32 i = 0; i < TFE_ARRAYSIZE(c_actorDamageFunc); i++) - { - if (c_actorDamageFunc[i] == func) { return i; } - } - return -1; - } - - s32 actor_getDamageMsgFuncIndex(ActorMsgFunc func) - { - for (s32 i = 0; i < TFE_ARRAYSIZE(c_actorDamageMsgFunc); i++) - { - if (c_actorDamageMsgFunc[i] == func) { return i; } - } - return -1; - } - - ActorFunc actor_getDamageFunc(s32 index) - { - if (index < 0 || index >= TFE_ARRAYSIZE(c_actorDamageFunc)) { return nullptr; } - return c_actorDamageFunc[index]; - } - - ActorMsgFunc actor_getDamageMsgFunc(s32 index) - { - if (index < 0 || index >= TFE_ARRAYSIZE(c_actorDamageMsgFunc)) { return nullptr; } - return c_actorDamageMsgFunc[index]; - } - - void actor_serializeDamageModule(Stream* stream, ActorModule*& mod, ActorDispatch* dispatch) - { - DamageModule* damageMod = nullptr; - s32 dmgFuncIndex = -1, dmgFuncMsgIndex = -1; - if (serialization_getMode() == SMODE_WRITE) - { - damageMod = (DamageModule*)mod; - dmgFuncIndex = actor_getDamageFuncIndex(damageMod->attackMod.header.func); - dmgFuncMsgIndex = actor_getDamageMsgFuncIndex(damageMod->attackMod.header.msgFunc); - assert(dmgFuncIndex >= 0 && dmgFuncMsgIndex >= 0); - } - SERIALIZE(SaveVersionInit, dmgFuncIndex, -1); - SERIALIZE(SaveVersionInit, dmgFuncMsgIndex, -1); - if (serialization_getMode() == SMODE_READ) - { - damageMod = (DamageModule*)level_alloc(sizeof(DamageModule)); - mod = (ActorModule*)damageMod; - memset(damageMod, 0, sizeof(DamageModule)); - actor_initModule(mod, (Logic*)dispatch); - - damageMod->attackMod.header.func = actor_getDamageFunc(dmgFuncIndex); - damageMod->attackMod.header.msgFunc = actor_getDamageMsgFunc(dmgFuncMsgIndex); - damageMod->attackMod.header.freeFunc = nullptr; - damageMod->attackMod.header.type = ACTMOD_DAMAGE; - assert(damageMod->attackMod.header.func && damageMod->attackMod.header.msgFunc); - } - assert(damageMod); - - actor_serializeAttackModuleBase(stream, &damageMod->attackMod, dispatch); - SERIALIZE(SaveVersionInit, damageMod->hp, 0); - SERIALIZE(SaveVersionInit, damageMod->itemDropId, ITEM_AUTOGUN); - serialization_serializeDfSound(stream, SaveVersionInit, &damageMod->hurtSndSrc); - serialization_serializeDfSound(stream, SaveVersionInit, &damageMod->dieSndSrc); - SERIALIZE(SaveVersionInit, damageMod->stopOnHit, JFALSE); - SERIALIZE(SaveVersionInit, damageMod->dieEffect, HEFFECT_CANNON_EXP); - } - - void actor_serializeThinkerModule(Stream* stream, ActorModule*& mod, ActorDispatch* dispatch) - { - ThinkerModule* thinkerMod; - if (serialization_getMode() == SMODE_READ) - { - thinkerMod = (ThinkerModule*)level_alloc(sizeof(ThinkerModule)); - mod = (ActorModule*)thinkerMod; - memset(thinkerMod, 0, sizeof(ThinkerModule)); - actor_initModule(mod, (Logic*)dispatch); - - thinkerMod->header.func = defaultThinkerFunc; - thinkerMod->header.type = ACTMOD_THINKER; - } - else - { - thinkerMod = (ThinkerModule*)mod; - assert(thinkerMod->header.func == defaultThinkerFunc || thinkerMod->header.func == flyingModuleFunc - || thinkerMod->header.func == flyingModuleFunc_Remote); - assert(thinkerMod->header.msgFunc == nullptr); - assert(thinkerMod->header.freeFunc == nullptr); - } - - actor_serializeTarget(stream, &thinkerMod->target); - SERIALIZE(SaveVersionInit, thinkerMod->delay, 0); - SERIALIZE(SaveVersionInit, thinkerMod->maxWalkTime, 0); - SERIALIZE(SaveVersionInit, thinkerMod->startDelay, 0); - actor_serializeLogicAnim(stream, &thinkerMod->anim); - - SERIALIZE(SaveVersionInit, thinkerMod->nextTick, 0); - SERIALIZE(SaveVersionInit, thinkerMod->playerLastSeen, 0); - SERIALIZE(SaveVersionInit, thinkerMod->prevColTick, 0); - - SERIALIZE(SaveVersionInit, thinkerMod->targetOffset, 0); - SERIALIZE(SaveVersionInit, thinkerMod->targetVariation, 0); - SERIALIZE(SaveVersionInit, thinkerMod->approachVariation, 0); - } - - void actor_serializeFlyerModule(Stream* stream, ActorModule*& mod, ActorDispatch* dispatch) - { - actor_serializeThinkerModule(stream, mod, dispatch); - if (serialization_getMode() == SMODE_READ) - { - ThinkerModule* thinkerMod = (ThinkerModule*)mod; - thinkerMod->header.func = flyingModuleFunc; - thinkerMod->header.type = ACTMOD_FLYER; - } - } - - void actor_serializeFlyerRemoteModule(Stream* stream, ActorModule*& mod, ActorDispatch* dispatch) - { - actor_serializeThinkerModule(stream, mod, dispatch); - if (serialization_getMode() == SMODE_READ) - { - ThinkerModule* thinkerMod = (ThinkerModule*)mod; - thinkerMod->header.func = flyingModuleFunc_Remote; - thinkerMod->header.type = ACTMOD_FLYER_REMOTE; - } - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/actorSerialization.h b/components/darkforces/tfe/TFE_DarkForces/Actor/actorSerialization.h deleted file mode 100644 index b9cce2a8..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/actorSerialization.h +++ /dev/null @@ -1,59 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Core Actor/AI functionality. -// ----------------------------- -// AI in Dark Forces is handled by a central "dispatcher" with a -// a number of "modules" attached that handle specific functionality. -// This is basically a primitive ECS-style system. -// -// Each module has function pointers to handle updates, message, damage, -// and destruction. During the AI update, the dispatch will loop over -// each module and call its update function. There is also some communication -// between modules to keep redundant data up to date. -// -// Dispatcher (ActorDispatcher in TFE): -// + ActorModule modules[] -// + MovementModule moveMod -- this could have been added to the list -// but every AI actor has it. -// -// For example, a Stormtrooper is: -// Dispatcher -// + Damage Module - -// Holds HP, drop item, hurt and die sounds. This is the -// getting hurt and dying functionality. -// + Attack Module - -// Handles attacking functionality, and includes the -// projectile type, melee range, etc. -// + Thinker Module - -// Handles overall state and sets targets for movement. -// + Movement Module - -// Handles the actual movement, collision detection and -// response, basic animation. -////////////////////////////////////////////////////////////////////// -#include "actorModule.h" -#include "../sound.h" -#include -#include -#include - -namespace TFE_DarkForces -{ - void actorDispatch_serialize(Logic*& logic, SecObject* obj, Stream* stream); - - // Helper Functions - void actor_serializeObject(Stream* stream, SecObject*& obj); - void actor_serializeWall(Stream* stream, RWall*& wall); - void actor_serializeCollisionInfo(Stream* stream, CollisionInfo* colInfo); - void actor_serializeTarget(Stream* stream, ActorTarget* target); - void actor_serializeMovementModule(Stream* stream, ActorModule*& mod, ActorDispatch* dispatch); - void actor_serializeAttackModule(Stream* stream, ActorModule*& mod, ActorDispatch* dispatch); - void actor_serializeDamageModule(Stream* stream, ActorModule*& mod, ActorDispatch* dispatch); - void actor_serializeThinkerModule(Stream* stream, ActorModule*& mod, ActorDispatch* dispatch); - void actor_serializeFlyerModule(Stream* stream, ActorModule*& mod, ActorDispatch* dispatch); - void actor_serializeFlyerRemoteModule(Stream* stream, ActorModule*& mod, ActorDispatch* dispatch); - - void actor_serializeTiming(Stream* stream, ActorTiming* timing); - void actor_serializeLogicAnim(Stream* stream, LogicAnimation* anim); - void actor_serializeMovementModuleBase(Stream* stream, MovementModule* moveMod); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/animTables.cpp b/components/darkforces/tfe/TFE_DarkForces/Actor/animTables.cpp deleted file mode 100644 index e0e7aa4d..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/animTables.cpp +++ /dev/null @@ -1,77 +0,0 @@ -#include "animTables.h" - -namespace TFE_DarkForces -{ - // Enemies - const s32 s_reeyeesAnimTable[] = - { 0, 1, 2, 3, 4, 5, -1, 7, 8, -1, -1, -1, 12, -1, -1, -1 }; - const s32 s_bosskAnimTable[] = - { 0, 1, 2, 3, 4, 5, 6, -1, -1, -1, -1, -1, 12, -1, -1, -1 }; - const s32 s_gamorAnimTable[] = - { 0, 1, 2, 3, 4, 5, -1, -1, -1, -1, -1, -1, 12, -1, -1, -1 }; - // Exploders - const s32 s_mineBarrelAnimTable[] = - { 0, -1, 1, 1, -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; - // Flyers - const s32 s_intDroidAnimTable[] = - { 0, 1, 2, 3, 4, 5, -1, 7, -1, -1, -1, -1, 12, -1, -1, -1 }; - const s32 s_probeDroidAnimTable[] = - { 0, 1, 2, 3, 4, 5, -1, -1, -1, -1, -1, -1, 12, -1, -1, -1 }; - const s32 s_remoteAnimTable[] = - { 0, 0, 2, 3, -1, 0, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1 }; - // Scenery - const s32 s_sceneryAnimTable[] = - { 0, -1, -1, -1, 1, 0, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1 }; - // Sewer Creature - const s32 s_sewerCreatureAnimTable[] = - { -1, 1, 2, 3, 4, 5, 6, -1, -1, -1, -1, -1, -1, -1, 12, 13 }; - // Troopers - const s32 s_officerAnimTable[] = - { 0, 6, 2, 3, 4, 5, 1, -1, -1, -1, -1, -1, 12, -1, -1, -1 }; - const s32 s_troopAnimTable[] = - { 0, 1, 3, 2, 4, 5, -1, -1, -1, -1, -1, -1, 12, -1, -1, -1 }; - const s32 s_commandoAnimTable[] = - { 0, 1, 2, 3, 4, 5, 6, -1, -1, -1, -1, -1, 12, -1, -1, -1 }; - - // Internal State. - static const s32* const s_animTables[] = - { - s_reeyeesAnimTable, - s_bosskAnimTable, - s_gamorAnimTable, - s_mineBarrelAnimTable, - s_intDroidAnimTable, - s_probeDroidAnimTable, - s_remoteAnimTable, - s_sceneryAnimTable, - s_sewerCreatureAnimTable, - s_officerAnimTable, - s_troopAnimTable, - s_commandoAnimTable, - }; - static const s32 s_animTableCount = TFE_ARRAYSIZE(s_animTables); - - // Serialization helpers. - s32 animTables_getIndex(const s32* table) - { - if (!table) { return -1; } - for (s32 i = 0; i < s_animTableCount; i++) - { - if (s_animTables[i] == table) - { - return i; - } - } - assert(0); - return -1; - } - - const s32* animTables_getTable(s32 index) - { - if (index < 0 || index >= s_animTableCount) - { - return nullptr; - } - return s_animTables[index]; - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/animTables.h b/components/darkforces/tfe/TFE_DarkForces/Actor/animTables.h deleted file mode 100644 index fdabc37b..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/animTables.h +++ /dev/null @@ -1,39 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Core Actor/AI functionality. -// ----------------------------- -// Shared animation tables for AI -////////////////////////////////////////////////////////////////////// -#include "actorModule.h" -#include "../sound.h" -#include -#include -#include - -namespace TFE_DarkForces -{ - // Accessors for serialization. - s32 animTables_getIndex(const s32* table); - const s32* animTables_getTable(s32 index); - - // Animation Tables, used directly by AI actors. - // Enemies - extern const s32 s_reeyeesAnimTable[]; - extern const s32 s_bosskAnimTable[]; - extern const s32 s_gamorAnimTable[]; - // Exploders - extern const s32 s_mineBarrelAnimTable[]; - // Flyers - extern const s32 s_intDroidAnimTable[]; - extern const s32 s_probeDroidAnimTable[]; - extern const s32 s_remoteAnimTable[]; - // Scenery - extern const s32 s_sceneryAnimTable[]; - // Sewer Creature - extern const s32 s_sewerCreatureAnimTable[]; - // Troopers - extern const s32 s_officerAnimTable[]; - extern const s32 s_troopAnimTable[]; - extern const s32 s_commandoAnimTable[]; -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/bobaFett.cpp b/components/darkforces/tfe/TFE_DarkForces/Actor/bobaFett.cpp deleted file mode 100644 index 165d553e..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/bobaFett.cpp +++ /dev/null @@ -1,973 +0,0 @@ -#include - -#include "bobaFett.h" -#include "actorModule.h" -#include "actorSerialization.h" -#include "../logic.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace TFE_DarkForces -{ - enum BobaFettStates - { - BOBASTATE_DEFAULT = 0, - BOBASTATE_MOVE_AND_ATTACK = 1, - BOBASTATE_DYING = 2, - BOBASTATE_SEARCH = 3, - BOBASTATE_COUNT - }; - - enum AttackPhase : u32 - { - ATTACK_POINT = 0, - ATTACK_CIRCLE = 1, - ATTACK_FIGURE8 = 2, - ATTACK_COUNT = 3, - ATTACK_NEWMODE = 4, - ATTACK_POINT1 = 5, - ATTACK_CIRCLE1 = 6, - ATTACK_FIGURE8_1 = 7, - }; - - enum SearchPhase : u32 - { - SEARCH_FIND = 0, - SEARCH_RAND, - SEARCH_CONTINUE - }; - - enum Timing : u32 - { - SHOOT_DELAY_RANGE_VANILLA = 291, - SHOOT_DELAY_RANGE_ENH = 145, - }; - - struct BobaFettMoveState - { - vec3_fixed target; - fixed16_16 yAccel; - SoundSourceId soundSrc; - angle14_32 thrustPitchRange; - fixed16_16 thrustPitch; - fixed16_16 thrustScale; - fixed16_16 accel; - }; - - struct BobaFett - { - Logic logic; - PhysicsActor actor; - - s32 unused; - BobaFettMoveState moveState; - SoundEffectId hitSndId; - }; - - struct BobaFettShared - { - SoundSourceId boba1SndID = NULL_SOUND; - SoundSourceId boba3SndID = NULL_SOUND; - SoundSourceId boba2SndID = NULL_SOUND; - SoundSourceId boba4SndID = NULL_SOUND; - SoundSourceId bobaRocket2SndID = NULL_SOUND; - s32 bobaFettNum = 0; - }; - - static BobaFett* s_curBobaFett = nullptr; - static BobaFettShared s_shared = {}; - extern s32 s_lastMaintainVolume; - - void bobaFett_exit() - { - s_shared = {}; - } - - void bobaFett_precache() - { - s_shared.boba1SndID = sound_load("boba-1.voc", SOUND_PRIORITY_MED5); - s_shared.boba3SndID = sound_load("boba-3.voc", SOUND_PRIORITY_LOW0); - s_shared.boba2SndID = sound_load("boba-2.voc", SOUND_PRIORITY_LOW0); - s_shared.boba4SndID = sound_load("boba-4.voc", SOUND_PRIORITY_MED5); - s_shared.bobaRocket2SndID = sound_load("rocket-2.voc", SOUND_PRIORITY_LOW5); - } - - void bobaFett_handleDamage(MessageType msg) - { - struct LocalContext - { - BobaFett* bobaFett; - SecObject* obj; - PhysicsActor* physicsActor; - LogicAnimation* anim; - LogicAnimation tmp; - }; - task_begin_ctx; - - local(bobaFett) = s_curBobaFett; - local(obj) = local(bobaFett)->logic.obj; - local(physicsActor) = &local(bobaFett)->actor; - local(anim) = &local(physicsActor)->anim; - - if (local(physicsActor)->alive) - { - task_localBlockBegin; - ProjectileLogic* proj = (ProjectileLogic*)s_msgEntity; - local(physicsActor)->hp -= proj->dmg; - task_localBlockEnd; - - if (local(physicsActor)->hp <= 0) - { - local(physicsActor)->state = BOBASTATE_DYING; - msg = MSG_RUN_TASK; - task_setMessage(msg); - } - else - { - sound_stop(local(bobaFett)->hitSndId); - local(bobaFett)->hitSndId = sound_playCued(s_shared.boba3SndID, local(obj)->posWS); - - // Save Animation - memcpy(&local(tmp), local(anim), sizeof(LogicAnimation) - 4); - - local(anim)->flags |= AFLAG_PLAYED; - local(anim)->frameRate = 6; - actor_setupBossAnimation(local(obj), 12, local(anim)); - - // Wait for animation to finish. - do - { - entity_yield(TASK_NO_DELAY); - } while (msg != MSG_RUN_TASK || !(local(anim)->flags & AFLAG_READY)); - - memcpy(local(anim), &local(tmp), sizeof(LogicAnimation) - 4); - actor_setupBossAnimation(local(obj), local(anim)->animId, local(anim)); - - msg = MSG_DAMAGE; - task_setMessage(msg); - } - } // if (alive) - task_end; - } - - void bobaFett_handleExplosion(MessageType msg) - { - struct LocalContext - { - BobaFett* bobaFett; - SecObject* obj; - PhysicsActor* physicsActor; - LogicAnimation* anim; - LogicAnimation tmp; - }; - task_begin_ctx; - - local(bobaFett) = s_curBobaFett; - local(obj) = local(bobaFett)->logic.obj; - local(physicsActor) = &local(bobaFett)->actor; - local(anim) = &local(physicsActor)->anim; - - if (local(physicsActor)->alive) - { - task_localBlockBegin; - fixed16_16 dmg = s_msgArg1; - local(physicsActor)->hp -= dmg; - task_localBlockEnd; - - if (local(physicsActor)->hp <= 0) - { - local(physicsActor)->state = BOBASTATE_DYING; - msg = MSG_RUN_TASK; - task_setMessage(msg); - } - else - { - sound_stop(local(bobaFett)->hitSndId); - local(bobaFett)->hitSndId = sound_playCued(s_shared.boba3SndID, local(obj)->posWS); - - // Save Animation - memcpy(&local(tmp), local(anim), sizeof(LogicAnimation) - 4); - - local(anim)->flags |= AFLAG_PLAYED; - local(anim)->frameRate = 6; - actor_setupBossAnimation(local(obj), 12, local(anim)); - - // Wait for animation to finish. - do - { - entity_yield(TASK_NO_DELAY); - } while (msg != MSG_RUN_TASK || !(local(anim)->flags & AFLAG_READY)); - - memcpy(local(anim), &local(tmp), sizeof(LogicAnimation) - 4); - actor_setupBossAnimation(local(obj), local(anim)->animId, local(anim)); - - msg = MSG_EXPLOSION; - task_setMessage(msg); - } - } // if (alive) - task_end; - } - - void bobaFett_handleMsg(MessageType msg) - { - struct LocalContext - { - BobaFett* bobaFett; - }; - task_begin_ctx; - local(bobaFett) = s_curBobaFett; - - if (msg == MSG_DAMAGE) - { - s_curBobaFett = local(bobaFett); - task_callTaskFunc(bobaFett_handleDamage); - } - else if (msg == MSG_EXPLOSION) - { - s_curBobaFett = local(bobaFett); - task_callTaskFunc(bobaFett_handleExplosion); - } - task_end; - } - - fixed16_16 bobaFett_thrust(fixed16_16 yTarget, fixed16_16 yPos, fixed16_16 yVel, fixed16_16 curThrust, angle14_32* thrustPitchRange) - { - fixed16_16 target = -yTarget; - fixed16_16 pos = -yPos; - fixed16_16 vel = -yVel; - if (pos != target) - { - vel += mul16(s_gravityAccel, s_deltaTime); - fixed16_16 dy = target - pos; - if (vel != dy) - { - vel = max(0, dy - vel); - *thrustPitchRange = clamp(ONE_16 - (vel - 0x13333), 0, ONE_16); - vel = min(ONE_16, vel); - - fixed16_16 maxChange = mul16(TFE_Jedi::abs(dy) + FIXED(4), s_deltaTime); - return clamp(vel - curThrust, -maxChange, maxChange) + curThrust; - } - } - return 0; - } - - void bobaFett_handleForces(PhysicsActor* physicsActor, fixed16_16 thrustScale, angle14_32 thrustPitch, fixed16_16 thrustMax, SoundSourceId soundSrc) - { - SecObject* obj = physicsActor->moveMod.header.obj; - if (thrustScale) - { - physicsActor->moveSndId = sound_maintain(physicsActor->moveSndId, soundSrc, obj->posWS); - if (s_lastMaintainVolume) - { - s32 vol = floor16(mul16(mul16(thrustScale, thrustScale), intToFixed16(s_lastMaintainVolume))); - sound_setVolume(physicsActor->moveSndId, vol); - } - - const fixed16_16 thrust = mul16(mul16(thrustScale, thrustMax), s_deltaTime); - - // Vertical thrust. - fixed16_16 sinPitch, cosPitch; - sinCosFixed(thrustPitch, &sinPitch, &cosPitch); - fixed16_16 yThrust = mul16(cosPitch, thrust); - fixed16_16 hThrust = mul16(sinPitch, thrust); - - // Horizontal thrust. - fixed16_16 sinYaw, cosYaw; - sinCosFixed(obj->yaw, &sinYaw, &cosYaw); - fixed16_16 xThrust = mul16(hThrust, sinYaw); - fixed16_16 zThrust = mul16(hThrust, cosYaw); - - // Velocity adjustment. - physicsActor->vel.x += xThrust; - physicsActor->vel.y -= yThrust; - physicsActor->vel.z += zThrust; - } - else if (physicsActor->moveSndId) - { - sound_stop(physicsActor->moveSndId); - physicsActor->moveSndId = NULL_SOUND; - } - } - - void bobaFett_handleFlying(PhysicsActor* physicsActor, BobaFettMoveState* moveState) - { - SecObject* obj = physicsActor->moveMod.header.obj; - - fixed16_16 dx = moveState->target.x - obj->posWS.x; - fixed16_16 dz = moveState->target.z - obj->posWS.z; - angle14_32 targetAngle = vec2ToAngle(dx, dz); - angle14_32 velAngle = vec2ToAngle(physicsActor->vel.x, physicsActor->vel.z); - - angle14_32 adjustedTargetAngle = targetAngle - velAngle; - if (adjustedTargetAngle != 0) - { - angle14_32 maxFrameRotation = floor16(mul16(FIXED(4551), s_deltaTime)); - angle14_32 angleDelta = clamp(getAngleDifference(obj->yaw, targetAngle), -maxFrameRotation, maxFrameRotation); - obj->yaw = (obj->yaw + angleDelta) & ANGLE_MASK; - } - - // Adjust the vertical movement angle. - fixed16_16 dist = distApprox(obj->posWS.x, obj->posWS.z, moveState->target.x, moveState->target.z); - fixed16_16 scaledDist = min(ONE_16, dist >> 7); - fixed16_16 newThrustPitch = mul16(scaledDist, FIXED(100)); - - fixed16_16 cosVelAngle, sinVelAngle; - sinCosFixed(velAngle, &cosVelAngle, &sinVelAngle); - - newThrustPitch -= (mul16(physicsActor->vel.z, cosVelAngle) + mul16(physicsActor->vel.x, sinVelAngle)); - newThrustPitch = clamp(div16(newThrustPitch, FIXED(100)), moveState->thrustPitchRange, -moveState->thrustPitchRange); - - fixed16_16 targetThrustPitch = floor16(mul16(newThrustPitch, FIXED(2048))); - fixed16_16 maxThrustPitchDelta = floor16(mul16(FIXED(1365), s_deltaTime)); - fixed16_16 thrustPitchDelta = clamp(targetThrustPitch - moveState->thrustPitch, -maxThrustPitchDelta, maxThrustPitchDelta); - moveState->thrustPitch += thrustPitchDelta; - - // Change the Y velocity offset and vertical angle range. - moveState->thrustScale = bobaFett_thrust(moveState->target.y, obj->posWS.y, physicsActor->vel.y, moveState->thrustScale, &moveState->thrustPitchRange); - if (moveState->accel) - { - fixed16_16 sinYaw, cosYaw; - sinCosFixed(obj->yaw + 4095, &sinYaw, &cosYaw); - - fixed16_16 velDelta = mul16(moveState->accel, s_deltaTime); - physicsActor->vel.x += mul16(velDelta, sinYaw); - physicsActor->vel.z += mul16(velDelta, cosYaw); - } - - // Handle velocity adjustments based on forces. - bobaFett_handleForces(physicsActor, moveState->thrustScale, moveState->thrustPitch, moveState->yAccel, moveState->soundSrc); - } - - void bobaFett_handleMovement(BobaFett* bobaFett) - { - PhysicsActor* physicsActor = &bobaFett->actor; - SecObject* obj = bobaFett->logic.obj; - RSector* sector = obj->sector; - fixed16_16 targetHeight = sector->ceilingHeight + obj->worldHeight; - fixed16_16 minHeight = sector->floorHeight; - RWall* wall = collision_wallCollisionFromPath(sector, obj->posWS.x, obj->posWS.z, bobaFett->moveState.target.x, bobaFett->moveState.target.z); - if (wall) - { - RSector* nextSector = wall->nextSector; - if (nextSector) - { - targetHeight = max(targetHeight, nextSector->ceilingHeight + obj->worldHeight); - minHeight = min(minHeight, nextSector->floorHeight); - } - } - - if (targetHeight < bobaFett->moveState.target.y) - { - targetHeight = bobaFett->moveState.target.y; - } - if (targetHeight >= minHeight) - { - targetHeight = minHeight; - } - bobaFett->moveState.target.y = targetHeight; - - bobaFett_handleFlying(physicsActor, &bobaFett->moveState); - } - - void bobaFett_handleMoveAndAttack(MessageType msg) - { - struct LocalContext - { - BobaFett* bobaFett; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - BobaFettMoveState* moveState; - - AttackPhase phase; - Tick nextAimedShotTick; - Tick nextShootTick; - Tick nextChangeHeightTick; - Tick nextPhaseChangeTick; - Tick nextSwapAccelTick; - fixed16_16 accel; - fixed16_16 heightTarget; - }; - task_begin_ctx; - - local(bobaFett) = s_curBobaFett; - local(obj) = local(bobaFett)->logic.obj; - local(physicsActor) = &local(bobaFett)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - local(moveState) = &local(bobaFett)->moveState; - - local(phase) = ATTACK_NEWMODE; - local(nextAimedShotTick) = s_curTick + - floor16(random(FIXED(TFE_Settings::getGameSettings()->df_bobaFettFacePlayer ? SHOOT_DELAY_RANGE_ENH : SHOOT_DELAY_RANGE_VANILLA))); - local(nextChangeHeightTick) = 0; - local(nextShootTick) = 0; - local(nextPhaseChangeTick) = 0; - local(nextSwapAccelTick) = 0; - local(heightTarget) = 0; - local(accel) = 0; - - while (local(physicsActor)->state == BOBASTATE_MOVE_AND_ATTACK) - { - do - { - entity_yield(TASK_NO_DELAY); - s_curBobaFett = local(bobaFett); - task_callTaskFunc(bobaFett_handleMsg); - } while (msg != MSG_RUN_TASK); - if (local(physicsActor)->state != BOBASTATE_MOVE_AND_ATTACK) { break; } - - task_localBlockBegin; - fixed16_16 dx = s_playerObject->posWS.x - local(obj)->posWS.x; - fixed16_16 dz = s_playerObject->posWS.z - local(obj)->posWS.z; - angle14_32 angle = vec2ToAngle(dx, dz) & ANGLE_MASK; - - if (local(phase) == ATTACK_POINT || local(phase) == ATTACK_POINT1) - { - local(target)->yaw = angle; - local(target)->flags |= TARGET_MOVE_ROT; - - fixed16_16 sinYaw, cosYaw; - sinCosFixed(local(obj)->yaw, &sinYaw, &cosYaw); - - if (local(phase) == ATTACK_POINT) - { - local(nextPhaseChangeTick) = s_curTick + 728; - local(moveState)->thrustPitch = ONE_16; - local(moveState)->thrustScale = ONE_16; - local(phase) = ATTACK_POINT1; - - local(physicsActor)->vel.y -= FIXED(15); - local(physicsActor)->vel.x += mul16(FIXED(80), sinYaw); - local(physicsActor)->vel.z += mul16(FIXED(80), cosYaw); - } - - // Phase == ATTACK_POINT1 - local(moveState)->target.x = s_playerObject->posWS.x + mul16(FIXED(10), sinYaw); - local(moveState)->target.y = s_playerObject->posWS.y - FIXED(5); - local(moveState)->target.z = s_playerObject->posWS.z + mul16(FIXED(10), cosYaw); - } - else if (local(phase) == ATTACK_CIRCLE || local(phase) == ATTACK_CIRCLE1) - { - // TFE: Optional feature. - if (TFE_Settings::getGameSettings()->df_bobaFettFacePlayer) - { - local(target)->yaw = angle; - local(target)->flags |= TARGET_MOVE_ROT; - } - - if (local(phase) == ATTACK_CIRCLE) - { - local(nextPhaseChangeTick) = s_curTick + 1456; - local(accel) = (s_curTick & 1) ? -FIXED(15) : FIXED(15); - local(phase) = ATTACK_CIRCLE1; - } - - // Phase == ATTACK_CIRCLE1 - local(moveState)->accel = FIXED(15); - local(moveState)->target.x = s_playerObject->posWS.x; - local(moveState)->target.y = local(heightTarget); - local(moveState)->target.z = s_playerObject->posWS.z; - } - else if (local(phase) == ATTACK_FIGURE8 || local(phase) == ATTACK_FIGURE8_1) - { - // TFE: Optional feature. - if (TFE_Settings::getGameSettings()->df_bobaFettFacePlayer) - { - local(target)->yaw = angle; - local(target)->flags |= TARGET_MOVE_ROT; - } - - if (local(phase) == ATTACK_FIGURE8) - { - local(nextPhaseChangeTick) = s_curTick + 2184; - local(nextSwapAccelTick) = s_curTick + - (TFE_Settings::getGameSettings()->df_bobaFettFacePlayer ? SHOOT_DELAY_RANGE_ENH : SHOOT_DELAY_RANGE_VANILLA); - local(phase) = ATTACK_FIGURE8_1; - local(accel) = FIXED(50); - } - - // Phase == ATTACK_FIGURE8_1 - local(moveState)->accel = local(accel); - local(moveState)->target.x = s_playerObject->posWS.x; - local(moveState)->target.y = local(heightTarget); - local(moveState)->target.z = s_playerObject->posWS.z; - - if (local(nextSwapAccelTick) < s_curTick) - { - local(accel) = -local(accel); - local(nextSwapAccelTick) = s_curTick + - (TFE_Settings::getGameSettings()->df_bobaFettFacePlayer ? SHOOT_DELAY_RANGE_ENH : SHOOT_DELAY_RANGE_VANILLA); - } - } - else if (local(phase) == ATTACK_NEWMODE) - { - local(phase) = (s_curTick & 1) ? ATTACK_POINT : (AttackPhase)floor16(random(FIXED(ATTACK_COUNT))); - local(nextPhaseChangeTick) = 0xffffffff; - } - - bobaFett_handleMovement(local(bobaFett)); - local(moveState)->accel = 0; - - if (local(nextPhaseChangeTick) < s_curTick) - { - local(phase) = ATTACK_NEWMODE; - } - - const angle14_32 angleDiff = getAngleDifference(angle, local(obj)->yaw); - if (angleDiff < 1592) - { - if (local(nextAimedShotTick) < s_curTick && actor_canSeeObject(local(obj), s_playerObject)) - { - local(nextAimedShotTick) = s_curTick + floor16(random(FIXED(TFE_Settings::getGameSettings()->df_bobaFettFacePlayer ? SHOOT_DELAY_RANGE_ENH : SHOOT_DELAY_RANGE_VANILLA))); - ProjectileLogic* proj = (ProjectileLogic*)createProjectile(PROJ_BOBAFET_BALL, local(obj)->sector, local(obj)->posWS.x, local(obj)->posWS.y - FIXED(4), local(obj)->posWS.z, local(obj)); - proj->prevColObj = local(obj); - proj->excludeObj = local(obj); - - sound_playCued(s_shared.boba2SndID, local(obj)->posWS); - SecObject* projObj = proj->logic.obj; - projObj->yaw = angle; - actor_leadTarget(proj); - } - - fixed16_16 dist = distApprox(s_playerObject->posWS.x, s_playerObject->posWS.z, local(obj)->posWS.x, local(obj)->posWS.z); - if (dist < FIXED(25) && local(nextShootTick) < s_curTick && actor_canSeeObject(local(obj), s_playerObject)) - { - local(nextShootTick) = s_curTick + 36; - ProjectileLogic* proj = (ProjectileLogic*)createProjectile(PROJ_BOBAFET_BALL, local(obj)->sector, local(obj)->posWS.x, local(obj)->posWS.y - FIXED(4), local(obj)->posWS.z, local(obj)); - proj->prevColObj = local(obj); - proj->excludeObj = local(obj); - - sound_playCued(s_shared.boba2SndID, local(obj)->posWS); - SecObject* projObj = proj->logic.obj; - projObj->yaw = angle; - proj_aimAtTarget(proj, s_playerObject->posWS); - proj->duration = s_curTick + 145; - } - } // if (angleDiff < 1592) - - if (local(nextChangeHeightTick) < s_curTick) // Pick a target height - { - local(nextChangeHeightTick) = s_curTick + floor16(random(FIXED(728))); - RSector* sector = local(obj)->sector; - fixed16_16 height = sector->floorHeight - sector->ceilingHeight; - local(heightTarget) = sector->floorHeight - random(height); - } - - fixed16_16 top = s_playerObject->posWS.y - s_playerObject->worldHeight; - if (top > local(heightTarget)) - { - top = local(heightTarget); - } - if (top <= s_playerObject->posWS.y - FIXED(25)) - { - top = s_playerObject->posWS.y - FIXED(25); - } - local(heightTarget) = top; - task_localBlockEnd; - } // while (state == BOBASTATE_MOVE_AND_ATTACK) - task_end; - } - - void bobaFett_handleDyingState(MessageType msg) - { - struct LocalContext - { - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - }; - task_begin_ctx; - - local(obj) = s_curBobaFett->logic.obj; - local(physicsActor) = &s_curBobaFett->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - - local(target)->flags |= TARGET_FREEZE; - sound_stop(local(physicsActor)->moveSndId); - sound_playCued(s_shared.boba4SndID, local(obj)->posWS); - - local(anim)->flags |= AFLAG_PLAYED; - local(anim)->frameRate = 8; - actor_setupBossAnimation(local(obj), 2, local(anim)); - - // Wait for the animation to finish. - do - { - entity_yield(TASK_NO_DELAY); - } while (msg != MSG_RUN_TASK || !(local(anim)->flags & AFLAG_READY)); - - task_localBlockBegin; - SecObject* corpse = allocateObject(); - sprite_setData(corpse, local(obj)->wax); - corpse->frame = 0; - corpse->anim = 4; - corpse->posWS = local(obj)->posWS; - corpse->worldWidth = 0; - corpse->worldHeight = 0; - corpse->entityFlags |= (ETFLAG_CORPSE | ETFLAG_KEEP_CORPSE); - sector_addObject(local(obj)->sector, corpse); - - local(physicsActor)->alive = JFALSE; - actor_handleBossDeath(local(physicsActor)); - task_localBlockEnd; - - task_end; - } - - void bobaFett_handleSearch(MessageType msg) - { - struct LocalContext - { - BobaFett* bobaFett; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - SearchPhase phase; - Tick nextCheckForPlayerTick; - Tick changeStateTick; - Tick nextChangePhaseTick; - }; - task_begin_ctx; - - local(bobaFett) = s_curBobaFett; - local(obj) = local(bobaFett)->logic.obj; - local(physicsActor) = &local(bobaFett)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - - local(phase) = SEARCH_FIND; - local(nextCheckForPlayerTick) = 0; - local(changeStateTick) = s_curTick + 8739; - local(nextChangePhaseTick) = s_curTick + 1456; - local(physicsActor)->moveMod.collisionFlags |= 4; - - while (local(physicsActor)->state == BOBASTATE_SEARCH) - { - do - { - entity_yield(TASK_NO_DELAY); - s_curBobaFett = local(bobaFett); - task_callTaskFunc(bobaFett_handleMsg); - } while (msg != MSG_RUN_TASK); - if (local(physicsActor)->state != BOBASTATE_SEARCH) { break; } - - if (local(phase) == SEARCH_FIND) - { - local(bobaFett)->moveState.target.x = s_playerObject->posWS.x; - local(bobaFett)->moveState.target.y = s_eyePos.y + FIXED(3); - local(bobaFett)->moveState.target.z = s_playerObject->posWS.z; - } - else if (local(phase) == SEARCH_RAND) - { - local(bobaFett)->moveState.target.x = local(obj)->posWS.x; - local(bobaFett)->moveState.target.z = local(obj)->posWS.z; - actor_offsetTarget(&local(bobaFett)->moveState.target.x, &local(bobaFett)->moveState.target.z, FIXED(80), FIXED(40), random_next(), 0x1fff); - local(phase) = SEARCH_CONTINUE; - } - // else SEARCH_CONTINUE : Continue with current target. - - bobaFett_handleMovement(local(bobaFett)); - - if (local(nextChangePhaseTick) < s_curTick) - { - local(phase) = (s_curTick & 1) ? SEARCH_FIND : SEARCH_RAND; - local(nextChangePhaseTick) = s_curTick + 1456; - } - - if (local(nextCheckForPlayerTick) < s_curTick) - { - if (!s_playerDying && actor_canSeeObject(local(obj), s_playerObject)) - { - local(physicsActor)->state = BOBASTATE_MOVE_AND_ATTACK; - } - else - { - local(nextCheckForPlayerTick) = s_curTick + 145; - } - } - if (local(changeStateTick) < s_curTick) - { - local(physicsActor)->state = BOBASTATE_DEFAULT; - } - } // while (state == BOBASTATE_SEARCH) - - local(physicsActor)->moveMod.collisionFlags |= 4; - task_end; - } - - void bobaFett_handleDefault(MessageType msg) - { - struct LocalContext - { - BobaFett* bobaFett; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - Tick nextCheckForPlayerTick; - Tick changeStateTick; - }; - task_begin_ctx; - - local(bobaFett) = s_curBobaFett; - local(obj) = local(bobaFett)->logic.obj; - local(physicsActor) = &local(bobaFett)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - - while (local(physicsActor)->state == BOBASTATE_DEFAULT) - { - do - { - entity_yield(145); - s_curBobaFett = local(bobaFett); - task_callTaskFunc(bobaFett_handleMsg); - - if (msg == MSG_DAMAGE || msg == MSG_EXPLOSION) - { - task_makeActive(local(physicsActor)->actorTask); - local(physicsActor)->state = BOBASTATE_MOVE_AND_ATTACK; - task_yield(0); - break; - } - } while (msg != MSG_RUN_TASK); - if (local(physicsActor)->state != BOBASTATE_DEFAULT) { break; } - - if (actor_canSeeObject(local(obj), s_playerObject)) - { - sound_playCued(s_shared.boba1SndID, local(obj)->posWS); - local(physicsActor)->state = BOBASTATE_SEARCH; - actor_setupBossAnimation(local(obj), 0, local(anim)); - } - } // while (state == BOBASTATE_DEFAULT) - task_end; - } - - void bobaFettTaskFunc(MessageType msg) - { - struct LocalContext - { - BobaFett* bobaFett; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - }; - task_begin_ctx; - - local(bobaFett) = (BobaFett*)task_getUserData(); - local(obj) = local(bobaFett)->logic.obj; - local(physicsActor) = &local(bobaFett)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - - while (local(physicsActor)->alive) - { - msg = MSG_RUN_TASK; - task_setMessage(msg); - - if (local(physicsActor)->state == BOBASTATE_MOVE_AND_ATTACK) - { - s_curBobaFett = local(bobaFett); - task_callTaskFunc(bobaFett_handleMoveAndAttack); - } - else if (local(physicsActor)->state == BOBASTATE_DYING) - { - s_curBobaFett = local(bobaFett); - task_callTaskFunc(bobaFett_handleDyingState); - } - else if (local(physicsActor)->state == BOBASTATE_SEARCH) - { - s_curBobaFett = local(bobaFett); - task_callTaskFunc(bobaFett_handleSearch); - } - else // Default - { - s_curBobaFett = local(bobaFett); - task_callTaskFunc(bobaFett_handleDefault); - } - } // while (alive) - - // Dead - while (msg != MSG_RUN_TASK) - { - task_yield(TASK_NO_DELAY); - } - - actor_removePhysicsActorFromWorld(local(physicsActor)); - deleteLogicAndObject(&local(bobaFett)->logic); - level_free(local(bobaFett)); - - while (msg != MSG_RUN_TASK) - { - task_yield(TASK_NO_DELAY); - } - task_end; - } - - void bobaFettCleanupFunc(Logic* logic) - { - BobaFett* bobaFett = (BobaFett*)logic; - PhysicsActor* physicsActor = &bobaFett->actor; - - actor_removePhysicsActorFromWorld(physicsActor); - deleteLogicAndObject(&bobaFett->logic); - level_free(bobaFett); - task_free(physicsActor->actorTask); - } - - void bobaFett_serialize(Logic*& logic, SecObject* obj, Stream* stream) - { - BobaFett* bobaFett = nullptr; - bool write = serialization_getMode() == SMODE_WRITE; - PhysicsActor* physicsActor = nullptr; - Task* bobaFettTask = nullptr; - if (write) - { - bobaFett = (BobaFett*)logic; - physicsActor = &bobaFett->actor; - } - else - { - bobaFett = (BobaFett*)level_alloc(sizeof(BobaFett)); - memset(bobaFett, 0, sizeof(BobaFett)); - physicsActor = &bobaFett->actor; - logic = (Logic*)bobaFett; - - // Task - char name[32]; - sprintf(name, "BobaFett%d", s_shared.bobaFettNum); - s_shared.bobaFettNum++; - - bobaFettTask = createSubTask(name, bobaFettTaskFunc); - task_setUserData(bobaFettTask, bobaFett); - - // Logic - logic->task = bobaFettTask; - logic->cleanupFunc = bobaFettCleanupFunc; - logic->type = LOGIC_BOBA_FETT; - logic->obj = obj; - } - actor_serializeMovementModuleBase(stream, &physicsActor->moveMod); - actor_serializeLogicAnim(stream, &physicsActor->anim); - if (!write) - { - // Clear out functions, the mousebot handles all of this internally. - physicsActor->moveMod.header.obj = obj; - physicsActor->moveMod.header.func = nullptr; - physicsActor->moveMod.header.freeFunc = nullptr; - physicsActor->moveMod.header.attribFunc = nullptr; - physicsActor->moveMod.header.msgFunc = nullptr; - physicsActor->moveMod.header.type = ACTMOD_MOVE; - physicsActor->moveMod.updateTargetFunc = nullptr; - - actor_addPhysicsActorToWorld(physicsActor); - - physicsActor->moveMod.header.obj = obj; - physicsActor->moveMod.physics.obj = obj; - physicsActor->actorTask = bobaFettTask; - - bobaFett->hitSndId = NULL_SOUND; - bobaFett->unused = 0; - bobaFett->moveState.soundSrc = s_shared.bobaRocket2SndID; - } - SERIALIZE(SaveVersionInit, physicsActor->vel, { 0 }); - SERIALIZE(SaveVersionInit, physicsActor->lastPlayerPos, { 0 }); - SERIALIZE(SaveVersionInit, physicsActor->alive, JTRUE); - SERIALIZE(SaveVersionInit, physicsActor->hp, FIXED(200)); - SERIALIZE(SaveVersionInit, physicsActor->state, BOBASTATE_DEFAULT); - - SERIALIZE(SaveVersionInit, bobaFett->moveState.target, { 0 }); - SERIALIZE(SaveVersionInit, bobaFett->moveState.yAccel, 0); - SERIALIZE(SaveVersionInit, bobaFett->moveState.thrustPitchRange, 0); - SERIALIZE(SaveVersionInit, bobaFett->moveState.thrustPitch, 0); - SERIALIZE(SaveVersionInit, bobaFett->moveState.thrustScale, 0); - SERIALIZE(SaveVersionInit, bobaFett->moveState.accel, 0); - } - - Logic* bobaFett_setup(SecObject* obj, LogicSetupFunc* setupFunc) - { - BobaFett* bobaFett = (BobaFett*)level_alloc(sizeof(BobaFett)); - memset(bobaFett, 0, sizeof(BobaFett)); - - PhysicsActor* physicsActor = &bobaFett->actor; - - // Give the name of the task a number so I can tell them apart when debugging. - char name[32]; - sprintf(name, "BobaFett%d", s_shared.bobaFettNum); - s_shared.bobaFettNum++; - Task* task = createSubTask(name, bobaFettTaskFunc); - task_setUserData(task, bobaFett); - - obj->entityFlags = ETFLAG_AI_ACTOR; - obj->worldHeight = FIXED(7); - - physicsActor->alive = JTRUE; - physicsActor->hp = FIXED(200); - physicsActor->state = BOBASTATE_DEFAULT; - physicsActor->actorTask = task; - - bobaFett->unused = 0; - bobaFett->hitSndId = 0; - bobaFett->moveState.yAccel = FIXED(220); - bobaFett->moveState.thrustPitchRange = ONE_16; - bobaFett->moveState.thrustPitch = 0; - bobaFett->moveState.thrustScale = 0; - bobaFett->moveState.soundSrc = s_shared.bobaRocket2SndID; - bobaFett->moveState.accel = 0; - bobaFett->logic.obj = obj; - actor_addPhysicsActorToWorld(physicsActor); - - physicsActor->moveMod.header.obj = obj; - physicsActor->moveMod.physics.obj = obj; - actor_setupSmartObj(&physicsActor->moveMod); - - physicsActor->moveMod.physics.width = FIXED(2); - physicsActor->moveMod.physics.botOffset = 0; - - physicsActor->moveMod.collisionFlags &= 0xfffffff8; - physicsActor->moveMod.collisionFlags |= 6; - physicsActor->moveMod.physics.yPos = COL_INFINITY; - physicsActor->moveMod.physics.height = obj->worldHeight; - - LogicAnimation* anim = &physicsActor->anim; - anim->frameRate = 5; - anim->frameCount = ONE_16; - anim->prevTick = 0; - anim->flags |= AFLAG_READY; - anim->flags &= ~AFLAG_PLAYED; - actor_setupBossAnimation(obj, 5, anim); - - ActorTarget* target = &physicsActor->moveMod.target; - target->speedRotation = 6826; - - obj_addLogic(obj, (Logic*)bobaFett, LOGIC_BOBA_FETT, task, bobaFettCleanupFunc); - - if (setupFunc) - { - *setupFunc = nullptr; - } - return (Logic*)bobaFett; - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/bobaFett.h b/components/darkforces/tfe/TFE_DarkForces/Actor/bobaFett.h deleted file mode 100644 index f33bc048..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/bobaFett.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Handles the Phase Two Dark Trooper AI. -////////////////////////////////////////////////////////////////////// -#include -#include -#include "actor.h" - -namespace TFE_DarkForces -{ - void bobaFett_exit(); - void bobaFett_precache(); - Logic* bobaFett_setup(SecObject* obj, LogicSetupFunc* setupFunc); - void bobaFett_serialize(Logic*& logic, SecObject* obj, Stream* stream); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/dragon.cpp b/components/darkforces/tfe/TFE_DarkForces/Actor/dragon.cpp deleted file mode 100644 index 4330e02a..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/dragon.cpp +++ /dev/null @@ -1,1128 +0,0 @@ -#include - -#include "dragon.h" -#include "actorModule.h" -#include "actorSerialization.h" -#include "../logic.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace TFE_DarkForces -{ - struct KellDragon - { - Logic logic; - PhysicsActor actor; - - s32 animIndex; - fixed16_16 painLevel; - SoundEffectId painSndId; - JBool retreat; - Tick nextTick; - s32 pad; - }; - - struct DragonMoveAnim - { - s32 framerate; - fixed16_16 speed; - }; - - struct DragonShared - { - SoundSourceId kellSound0 = NULL_SOUND; - SoundSourceId kellSound1 = NULL_SOUND; - SoundSourceId kellSound2 = NULL_SOUND; - SoundSourceId kellSound3 = NULL_SOUND; - SoundSourceId kellSound4 = NULL_SOUND; - s32 dragonNum = 0; - }; - - static const fixed16_16 s_kellDragon_NearDist = FIXED(25); - static const fixed16_16 s_kellDragon_MedDist = FIXED(45); - static const fixed16_16 s_kellDragon_FarDist = FIXED(60); - - static const DragonMoveAnim s_kellDragonAnim[4] = - { - { 5, FIXED(9) }, - { 7, FIXED(12) }, - { 8, FIXED(16) }, - { 10, FIXED(24) }, - }; - - static KellDragon* s_curDragon = nullptr; - static DragonShared s_shared = {}; - - void kellDragon_exit() - { - s_shared = {}; - } - - void kellDragon_precache() - { - s_shared.kellSound0 = sound_load("kell-1.voc", SOUND_PRIORITY_MED5); - s_shared.kellSound2 = sound_load("kell-8.voc", SOUND_PRIORITY_LOW0); - s_shared.kellSound4 = sound_load("kell-5.voc", SOUND_PRIORITY_LOW0); - s_shared.kellSound1 = sound_load("kelljump.voc", SOUND_PRIORITY_LOW0); - s_shared.kellSound3 = sound_load("kell-7.voc", SOUND_PRIORITY_MED5); - } - - void kellDragon_handleDamage(MessageType msg) - { - struct LocalContext - { - KellDragon* dragon; - SecObject* obj; - PhysicsActor* physicsActor; - LogicAnimation* anim; - LogicAnimation tmpAnim; - }; - task_begin_ctx; - - local(dragon) = s_curDragon; - local(obj) = local(dragon)->logic.obj; - local(physicsActor) = &local(dragon)->actor; - local(anim) = &local(physicsActor)->anim; - - if (local(physicsActor)->alive) - { - task_localBlockBegin; - ProjectileLogic* proj = (ProjectileLogic*)s_msgEntity; - local(physicsActor)->hp -= proj->dmg; - local(dragon)->painLevel = min(FIXED(100), local(dragon)->painLevel + FIXED(20)); - task_localBlockEnd; - - if (local(physicsActor)->hp <= 0) - { - local(physicsActor)->state = 5; - msg = MSG_RUN_TASK; - } - else - { - sound_stop(local(dragon)->painSndId); - local(dragon)->painSndId = sound_playCued(s_shared.kellSound2, local(obj)->posWS); - - if (random(100) <= 20) - { - task_localBlockBegin; - ActorTarget* target = &local(physicsActor)->moveMod.target; - target->flags |= 8; - memcpy(&local(tmpAnim), local(anim), sizeof(LogicAnimation) - 4); - - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 12, local(anim)); - local(anim)->frameRate = 8; - task_localBlockEnd; - - do - { - entity_yield(TASK_NO_DELAY); - } while (!(local(anim)->flags & AFLAG_READY) || msg != MSG_RUN_TASK); - - task_localBlockBegin; - memcpy(local(anim), &local(tmpAnim), sizeof(LogicAnimation) - 4); - actor_setupBossAnimation(local(obj), local(anim)->animId, local(anim)); - - ActorTarget* target = &local(physicsActor)->moveMod.target; - target->flags &= 0xfffffff7; - task_localBlockEnd; - } - msg = MSG_DAMAGE; - } - } - task_setMessage(msg); - task_end; - } - - void kellDragon_handleExplosion(MessageType msg) - { - struct LocalContext - { - KellDragon* dragon; - SecObject* obj; - PhysicsActor* physicsActor; - LogicAnimation* anim; - ActorTarget* target; - LogicAnimation tmp; - vec3_fixed vel; - }; - task_begin_ctx; - - local(dragon) = s_curDragon; - local(obj) = local(dragon)->logic.obj; - local(physicsActor) = &local(dragon)->actor; - local(anim) = &local(physicsActor)->anim; - local(target) = &local(physicsActor)->moveMod.target; - - if (local(physicsActor)->alive) - { - task_localBlockBegin; - fixed16_16 dmg = s_msgArg1; - fixed16_16 force = s_msgArg2; - - local(physicsActor)->hp -= dmg; - local(dragon)->painLevel = min(FIXED(100), local(dragon)->painLevel + FIXED(40)); - - vec3_fixed pushVel; - vec3_fixed pos = { local(obj)->posWS.x, local(obj)->posWS.y - local(obj)->worldHeight, local(obj)->posWS.z }; - computeExplosionPushDir(&pos, &pushVel); - local(vel) = { mul16(force, pushVel.x), mul16(force, pushVel.y), mul16(force, pushVel.z) }; - task_localBlockEnd; - - if (local(physicsActor)->hp <= 0) - { - local(physicsActor)->state = 5; - local(physicsActor)->vel = local(vel); - msg = MSG_RUN_TASK; - } - else - { - // Add one if the value is negative. - local(vel).x += (local(vel).x < 0 ? 1 : 0); - local(vel).y += (local(vel).y < 0 ? 1 : 0); - local(vel).z += (local(vel).z < 0 ? 1 : 0); - local(physicsActor)->vel.x = local(vel).x >> 1; - local(physicsActor)->vel.y = local(vel).y >> 1; - local(physicsActor)->vel.z = local(vel).z >> 1; - - sound_stop(local(dragon)->painSndId); - local(dragon)->painSndId = sound_playCued(s_shared.kellSound2, local(obj)->posWS); - - if (random(100) <= 20) - { - local(target)->flags |= TARGET_FREEZE; - - // Save the animation. - memcpy(&local(tmp), local(anim), sizeof(LogicAnimation) - 4); - - // Set the animation to 12. - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 12, local(anim)); - local(anim)->frameRate = 8; - - do - { - entity_yield(TASK_NO_DELAY); - } while (msg != MSG_RUN_TASK || !(local(anim)->flags & AFLAG_READY)); - - // Restore the animation. - memcpy(local(anim), &local(tmp), sizeof(LogicAnimation) - 4); - actor_setupBossAnimation(local(obj), local(anim)->animId, local(anim)); - local(target)->flags &= ~TARGET_FREEZE; - } - msg = MSG_EXPLOSION; - } - } - task_setMessage(msg); - task_end; - } - - void kellDragon_handleMsg(MessageType msg) - { - task_begin; - if (msg == MSG_DAMAGE) - { - task_callTaskFunc(kellDragon_handleDamage); - } - else if (msg == MSG_EXPLOSION) - { - task_callTaskFunc(kellDragon_handleExplosion); - } - task_end; - } - - JBool kellDragon_canSeePlayer(KellDragon* dragon) - { - SecObject* obj = dragon->logic.obj; - JBool canSee = actor_canSeeObject(obj, s_playerObject); - if (canSee) - { - PhysicsActor* physicsActor = &dragon->actor; - physicsActor->lastPlayerPos.x = s_playerObject->posWS.x; - physicsActor->lastPlayerPos.z = s_playerObject->posWS.z; - } - return canSee; - } - - // Returns JTRUE if the new animation index has changed. - JBool kellDragon_setAnimIndex(KellDragon* dragon, s32 baseAnimIndex) - { - SecObject* obj = dragon->logic.obj; - PhysicsActor* physicsActor = &dragon->actor; - fixed16_16 dist = distApprox(s_playerObject->posWS.x, s_playerObject->posWS.z, obj->posWS.x, obj->posWS.z); - - fixed16_16 value = 0; - if (dist >= s_kellDragon_FarDist) - { - value = FIXED(3); - } - else if (dist >= s_kellDragon_MedDist) - { - value = FIXED(2); - } - else if (dist >= s_kellDragon_NearDist) - { - value = ONE_16; - } - fixed16_16 scale = mul16(div16(dragon->painLevel, FIXED(100)), FIXED(4)); - - // if hp == max, result = 0; if hp = 0, result = 1 - fixed16_16 frac = div16(FIXED(180) - physicsActor->hp, FIXED(180)); - scale += mul16(frac, FIXED(4)); - - // floor(2.0 * (painLevel/100.0 + (180 - hp)/180) + min(3, floor(dist/20.0)) + 0.5) + index - s32 animIndex = baseAnimIndex + floor16(value + div16(scale, FIXED(2)) + HALF_16); - animIndex = min(3, animIndex); - if (animIndex != dragon->animIndex) - { - dragon->animIndex = animIndex; - return JTRUE; - } - return JFALSE; - } - - void kellDragon_setAnimFramerate(LogicAnimation* anim, s32 framerate) - { - anim->frameRate = framerate; - anim->prevTick = s_frameTicks[framerate]; - } - - void kellDragon_computeTarget(SecObject* obj, KellDragon* dragon, ActorTarget* target) - { - fixed16_16 sinYaw, cosYaw; - sinCosFixed(obj->yaw, &sinYaw, &cosYaw); - - target->flags |= 4; - target->speedRotation = 6826; - - fixed16_16 animSpeed = s_kellDragonAnim[dragon->animIndex].speed; - target->pos.x = obj->posWS.x + mul16(sinYaw, animSpeed); - target->pos.z = obj->posWS.z + mul16(cosYaw, animSpeed); - target->flags |= 1; - } - - void kellDragon_handleState1(MessageType msg) - { - struct LocalContext - { - KellDragon* dragon; - SecObject* obj; - PhysicsActor* physicsActor; - LogicAnimation* anim; - ActorTarget* target; - u32 prevColTick; - JBool yawAligned; - }; - task_begin_ctx; - - local(dragon) = s_curDragon; - local(obj) = local(dragon)->logic.obj; - local(physicsActor) = &local(dragon)->actor; - local(anim) = &local(physicsActor)->anim; - local(target) = &local(physicsActor)->moveMod.target; - local(prevColTick) = 0; - local(yawAligned) = JFALSE; - - local(anim)->flags &= ~AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 0, local(anim)); - - task_localBlockBegin; - s32 baseAnimIndex = (random(100) <= 60) ? 3 : 0; - if (kellDragon_setAnimIndex(local(dragon), baseAnimIndex)) - { - kellDragon_setAnimFramerate(local(anim), s_kellDragonAnim[local(dragon)->animIndex].framerate); - local(target)->speed = s_kellDragonAnim[local(dragon)->animIndex].speed; - } - task_localBlockEnd; - - while (local(physicsActor)->state == 1) - { - do - { - entity_yield(TASK_NO_DELAY); - if (msg == MSG_DAMAGE) - { - s_curDragon = local(dragon); - task_callTaskFunc(kellDragon_handleDamage); - } - else if (msg == MSG_EXPLOSION) - { - s_curDragon = local(dragon); - task_callTaskFunc(kellDragon_handleExplosion); - } - } while (msg != MSG_RUN_TASK); - if (local(physicsActor)->state != 1) { break; } - - if (!s_playerDying && kellDragon_canSeePlayer(local(dragon))) - { - JBool jump = JFALSE; - if (local(obj)->yaw == local(target)->yaw) - { - if (!local(yawAligned)) - { - jump = (random(100) <= 50) ? JTRUE : JFALSE; - } - local(yawAligned) = JTRUE; - } - else - { - local(yawAligned) = JFALSE; - } - - fixed16_16 dy = TFE_Jedi::abs(local(obj)->posWS.y - s_playerObject->posWS.y); - fixed16_16 dist = dy + distApprox(s_playerObject->posWS.x, s_playerObject->posWS.z, local(obj)->posWS.x, local(obj)->posWS.z); - if (dist <= FIXED(20) && local(obj)->yaw == local(target)->yaw) - { - local(physicsActor)->state = 4; - } - else if (dist <= FIXED(55) && jump && local(obj)->yaw == local(target)->yaw) - { - if (dy <= FIXED(10)) - { - local(physicsActor)->state = 3; - } - } - } - else if (!s_playerDying) - { - local(physicsActor)->state = 6; - } - if (local(physicsActor)->state != 1) { break; } - - if (kellDragon_setAnimIndex(local(dragon), 0)) - { - kellDragon_setAnimFramerate(local(anim), s_kellDragonAnim[local(dragon)->animIndex].framerate); - local(target)->speed = s_kellDragonAnim[local(dragon)->animIndex].speed; - } - - local(target)->flags &= ~TARGET_FREEZE; - if (actor_handleSteps(&local(physicsActor)->moveMod, local(target))) - { - actor_changeDirFromCollision(&local(physicsActor)->moveMod, local(target), &local(prevColTick)); - local(dragon)->retreat = JTRUE; - local(target)->speedRotation = 11377; // ~250 degrees per second. - local(dragon)->nextTick = s_curTick + 72; - } - else if (local(dragon)->retreat) - { - if (s_curTick >= local(dragon)->nextTick) - { - local(dragon)->retreat = JFALSE; - fixed16_16 dx = s_playerObject->posWS.x - local(obj)->posWS.x; - fixed16_16 dz = s_playerObject->posWS.z - local(obj)->posWS.z; - local(target)->yaw = vec2ToAngle(dx, dz); - kellDragon_computeTarget(local(obj), local(dragon), local(target)); - } - } - else if (!s_playerDying) - { - fixed16_16 dx = s_playerObject->posWS.x - local(obj)->posWS.x; - fixed16_16 dz = s_playerObject->posWS.z - local(obj)->posWS.z; - local(target)->yaw = vec2ToAngle(dx, dz); - kellDragon_computeTarget(local(obj), local(dragon), local(target)); - } - else - { - local(target)->yaw = random(16338); - kellDragon_computeTarget(local(obj), local(dragon), local(target)); - } - } - - local(anim)->flags |= AFLAG_READY; - task_end; - } - - void kellDragon_handleRetreat(MessageType msg) - { - struct LocalContext - { - KellDragon* dragon; - SecObject* obj; - PhysicsActor* physicsActor; - LogicAnimation* anim; - ActorTarget* target; - }; - task_begin_ctx; - - local(dragon) = s_curDragon; - local(obj) = local(dragon)->logic.obj; - local(physicsActor) = &local(dragon)->actor; - local(anim) = &local(physicsActor)->anim; - local(target) = &local(physicsActor)->moveMod.target; - local(anim)->flags &= ~AFLAG_PLAYED; - - task_localBlockBegin; - actor_setupBossAnimation(local(obj), 0, local(anim)); - s32 baseAnimIndex = (random(100) <= 60) ? 3 : 0; - if (kellDragon_setAnimIndex(local(dragon), baseAnimIndex)) - { - kellDragon_setAnimFramerate(local(anim), s_kellDragonAnim[local(dragon)->animIndex].framerate); - local(target)->speed = s_kellDragonAnim[local(dragon)->animIndex].speed; - } - task_localBlockEnd; - - while (local(physicsActor)->state == 2) - { - do - { - entity_yield(TASK_NO_DELAY); - if (msg == MSG_DAMAGE) - { - s_curDragon = local(dragon); - task_callTaskFunc(kellDragon_handleDamage); - } - else if (msg == MSG_EXPLOSION) - { - s_curDragon = local(dragon); - task_callTaskFunc(kellDragon_handleExplosion); - } - } while (msg != MSG_RUN_TASK); - if (local(physicsActor)->state != 2) { break; } - - if (!local(dragon)->retreat) - { - fixed16_16 dx = s_playerObject->posWS.x - local(obj)->posWS.x; - fixed16_16 dz = s_playerObject->posWS.z - local(obj)->posWS.z; - local(target)->yaw = (vec2ToAngle(dx, dz) + 0x2000) & ANGLE_MASK; - - fixed16_16 sinYaw, cosYaw; - sinCosFixed(local(target)->yaw, &sinYaw, &cosYaw); - - local(target)->flags |= TARGET_MOVE_ROT; - local(target)->speedRotation = 0; - - fixed16_16 animSpeed = s_kellDragonAnim[local(dragon)->animIndex].speed; - local(target)->pos.x = local(obj)->posWS.x + mul16(sinYaw, animSpeed); - local(target)->pos.z = local(obj)->posWS.z + mul16(cosYaw, animSpeed); - local(target)->flags |= TARGET_MOVE_XZ; - - local(dragon)->retreat = JTRUE; - local(dragon)->nextTick = s_curTick + 72; - } - else if (s_curTick >= local(dragon)->nextTick) - { - local(physicsActor)->state = 1; - local(dragon)->retreat = JFALSE; - } - } // while (state == 2) - - local(anim)->flags |= AFLAG_READY; - task_end; - } - - void kellDragon_handleJumping(MessageType msg) - { - struct LocalContext - { - KellDragon* dragon; - SecObject* obj; - PhysicsActor* physicsActor; - LogicAnimation* anim; - ActorTarget* target; - }; - task_begin_ctx; - - local(dragon) = s_curDragon; - local(obj) = local(dragon)->logic.obj; - local(physicsActor) = &local(dragon)->actor; - local(anim) = &local(physicsActor)->anim; - local(target) = &local(physicsActor)->moveMod.target; - - while (local(physicsActor)->state == 3) - { - do - { - entity_yield(TASK_NO_DELAY); - if (msg == MSG_DAMAGE) - { - s_curDragon = local(dragon); - task_callTaskFunc(kellDragon_handleDamage); - } - else if (msg == MSG_EXPLOSION) - { - s_curDragon = local(dragon); - task_callTaskFunc(kellDragon_handleExplosion); - } - } while (msg != MSG_RUN_TASK); - if (local(physicsActor)->state != 3) { break; } - - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 9, local(anim)); - local(anim)->frameRate = 8; - sound_playCued(s_shared.kellSound1, local(obj)->posWS); - - // Wait for the animation to finish playing. - do - { - entity_yield(TASK_NO_DELAY); - if (msg == MSG_DAMAGE) - { - s_curDragon = local(dragon); - task_callTaskFunc(kellDragon_handleDamage); - } - else if (msg == MSG_EXPLOSION) - { - s_curDragon = local(dragon); - task_callTaskFunc(kellDragon_handleExplosion); - } - } while (msg != MSG_RUN_TASK || !(local(anim)->flags & AFLAG_READY)); - - task_localBlockBegin; - local(target)->pos.x = s_playerObject->posWS.x; - local(target)->pos.z = s_playerObject->posWS.z; - local(target)->flags |= TARGET_MOVE_XZ; - - fixed16_16 dx = s_playerObject->posWS.x - local(obj)->posWS.x; - fixed16_16 dz = s_playerObject->posWS.z - local(obj)->posWS.z; - local(target)->yaw = vec2ToAngle(dx, dz); - local(obj)->yaw = local(target)->yaw; - local(target)->flags |= TARGET_MOVE_ROT; - - actor_jumpToTarget(local(physicsActor), local(obj), s_playerObject->posWS, FIXED(100), -455); - task_localBlockEnd; - - // Wait for the actor to land. - do - { - entity_yield(TASK_NO_DELAY); - if (msg == MSG_DAMAGE) - { - s_curDragon = local(dragon); - task_callTaskFunc(kellDragon_handleDamage); - } - else if (msg == MSG_EXPLOSION) - { - s_curDragon = local(dragon); - task_callTaskFunc(kellDragon_handleExplosion); - } - } while (msg != MSG_RUN_TASK || local(physicsActor)->vel.y != 0); - - // Remove any excess horizontal velocity and setup the next animation. - local(target)->flags |= TARGET_FREEZE; - local(physicsActor)->vel.x = 0; - local(physicsActor)->vel.z = 0; - actor_setupBossAnimation(local(obj), 11, local(anim)); - local(anim)->frameRate = 8; - sound_playCued(s_shared.kellSound4, local(obj)->posWS); - - // Wait for the animation to finish playing. - do - { - entity_yield(TASK_NO_DELAY); - if (msg == MSG_DAMAGE) - { - s_curDragon = local(dragon); - task_callTaskFunc(kellDragon_handleDamage); - } - else if (msg == MSG_EXPLOSION) - { - s_curDragon = local(dragon); - task_callTaskFunc(kellDragon_handleExplosion); - } - } while (msg != MSG_RUN_TASK || !(local(anim)->flags & AFLAG_READY)); - - // Bite! - fixed16_16 dy = TFE_Jedi::abs(local(obj)->posWS.y - s_playerObject->posWS.y); - fixed16_16 dist = dy + distApprox(s_playerObject->posWS.x, s_playerObject->posWS.z, local(obj)->posWS.x, local(obj)->posWS.z); - if (dist <= FIXED(20)) - { - player_applyDamage(FIXED(20), 0, JTRUE); - } - local(physicsActor)->state = 1; - } // while (state == 3) - task_end; - } - - void kellDragon_handleState4(MessageType msg) - { - struct LocalContext - { - KellDragon* dragon; - SecObject* obj; - PhysicsActor* physicsActor; - LogicAnimation* anim; - ActorTarget* target; - }; - task_begin_ctx; - - local(dragon) = s_curDragon; - local(obj) = local(dragon)->logic.obj; - local(physicsActor) = &local(dragon)->actor; - local(anim) = &local(physicsActor)->anim; - local(target) = &local(physicsActor)->moveMod.target; - - while (local(physicsActor)->state == 4) - { - do - { - entity_yield(TASK_NO_DELAY); - if (msg == MSG_DAMAGE) - { - s_curDragon = local(dragon); - task_callTaskFunc(kellDragon_handleDamage); - } - else if (msg == MSG_EXPLOSION) - { - s_curDragon = local(dragon); - task_callTaskFunc(kellDragon_handleExplosion); - } - } while (msg != MSG_RUN_TASK); - if (local(physicsActor)->state != 4) { break; } - - if (s_playerDying) - { - local(physicsActor)->state = 1; - break; - } - - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 1, local(anim)); - local(anim)->frameRate = 8; - - // Wait for the animation to finish playing. - do - { - entity_yield(TASK_NO_DELAY); - if (msg == MSG_DAMAGE) - { - s_curDragon = local(dragon); - task_callTaskFunc(kellDragon_handleDamage); - } - else if (msg == MSG_EXPLOSION) - { - s_curDragon = local(dragon); - task_callTaskFunc(kellDragon_handleExplosion); - } - } while (msg != MSG_RUN_TASK || !(local(anim)->flags & AFLAG_READY)); - - sound_playCued(s_shared.kellSound4, local(obj)->posWS); - fixed16_16 dy = TFE_Jedi::abs(local(obj)->posWS.y - s_playerObject->posWS.y); - fixed16_16 dist = dy + distApprox(s_playerObject->posWS.x, s_playerObject->posWS.z, local(obj)->posWS.x, local(obj)->posWS.z); - if (dist <= FIXED(20)) - { - // Bite! - player_applyDamage(FIXED(20), 0, JTRUE); - if (random(100) <= 30) - { - local(physicsActor)->state = 2; - } - } - else - { - local(physicsActor)->state = 1; - } - } - - local(target)->flags &= ~TARGET_FREEZE; - task_end; - } - - void kellDragon_handleDyingState(MessageType msg) - { - struct LocalContext - { - KellDragon* dragon; - SecObject* obj; - PhysicsActor* physicsActor; - LogicAnimation* anim; - ActorTarget* target; - }; - task_begin_ctx; - - local(dragon) = s_curDragon; - local(obj) = local(dragon)->logic.obj; - local(physicsActor) = &local(dragon)->actor; - local(anim) = &local(physicsActor)->anim; - local(target) = &local(physicsActor)->moveMod.target; - - local(target)->flags |= TARGET_FREEZE; - sound_playCued(s_shared.kellSound3, local(obj)->posWS); - - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 2, local(anim)); - local(anim)->frameRate = 8; - - // Wait for the death animation to finish. - do - { - entity_yield(TASK_NO_DELAY); - } while (msg != MSG_RUN_TASK || !(local(anim)->flags & AFLAG_READY)); - - // Then wait until we can actually die... - do - { - entity_yield(TASK_NO_DELAY); - } while (msg != MSG_RUN_TASK || !actor_canDie(local(physicsActor))); - - task_localBlockBegin; - RSector* sector = local(obj)->sector; - if (sector->secHeight - 1 < 0) - { - SecObject* corpse = allocateObject(); - sprite_setData(corpse, local(obj)->wax); - corpse->frame = 0; - corpse->anim = 4; - corpse->posWS = local(obj)->posWS; - corpse->worldWidth = 0; - corpse->worldHeight = 0; - corpse->entityFlags |= (ETFLAG_CORPSE | ETFLAG_KEEP_CORPSE); - sector_addObject(sector, corpse); - } - local(physicsActor)->alive = JFALSE; - actor_handleBossDeath(local(physicsActor)); - task_localBlockEnd; - task_end; - } - - void kellDragon_handleState6(MessageType msg) - { - struct LocalContext - { - KellDragon* dragon; - SecObject* obj; - PhysicsActor* physicsActor; - LogicAnimation* anim; - ActorTarget* target; - - JBool arrived; - Tick prevColTick; - Tick nextTick; - Tick nextTick2; - Tick delay; - fixed16_16 speedRotation; - }; - task_begin_ctx; - - local(dragon) = s_curDragon; - local(obj) = local(dragon)->logic.obj; - local(physicsActor) = &local(dragon)->actor; - local(anim) = &local(physicsActor)->anim; - local(target) = &local(physicsActor)->moveMod.target; - - local(arrived) = JTRUE; - local(prevColTick) = 0; - local(nextTick) = 0; - local(nextTick2) = s_curTick + 0x1111; - local(delay) = 72; - local(speedRotation) = local(target)->speedRotation; - - local(anim)->flags &= ~AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 0, local(anim)); - local(target)->flags &= ~TARGET_FREEZE; - local(target)->speedRotation = 0x3000; - - while (local(physicsActor)->state == 6) - { - do - { - entity_yield(TASK_NO_DELAY); - if (msg == MSG_DAMAGE) - { - s_curDragon = local(dragon); - task_callTaskFunc(kellDragon_handleDamage); - } - else if (msg == MSG_EXPLOSION) - { - s_curDragon = local(dragon); - task_callTaskFunc(kellDragon_handleExplosion); - } - } while (msg != MSG_RUN_TASK); - if (local(physicsActor)->state != 6 || s_playerDying) { break; } - - JBool canSee = actor_canSeeObject(local(obj), s_playerObject); - if (canSee) - { - local(physicsActor)->lastPlayerPos.x = s_playerObject->posWS.x; - local(physicsActor)->lastPlayerPos.z = s_playerObject->posWS.z; - local(physicsActor)->state = 1; - break; - } - - JBool arrivedAtTarget = actor_arrivedAtTarget(local(target), local(obj)); - if (local(nextTick) < s_curTick || arrivedAtTarget) - { - local(arrived) = JTRUE; - if (arrivedAtTarget) - { - local(nextTick2) = 0; - } - } - - if (local(arrived)) - { - local(arrived) = JFALSE; - vec2_fixed target; - if (s_curTick < local(nextTick2)) - { - target = local(physicsActor)->lastPlayerPos; - } - else - { - target = { s_eyePos.x, s_eyePos.z }; - } - - fixed16_16 absDx = TFE_Jedi::abs(s_playerObject->posWS.x - local(obj)->posWS.x); - fixed16_16 dxTarget = local(obj)->posWS.x - target.x; - fixed16_16 dzTarget = local(obj)->posWS.z - target.z; - angle14_32 angleToTarget = vec2ToAngle(dxTarget, dzTarget); - - local(target)->pos.x = target.x; - local(target)->pos.z = target.z; - actor_offsetTarget(&local(target)->pos.x, &local(target)->pos.z, absDx>>2, absDx>>3, angleToTarget, 0xfff); - local(target)->flags |= TARGET_MOVE_XZ; - - dxTarget = local(target)->pos.x - local(obj)->posWS.x; - dzTarget = local(target)->pos.z - local(obj)->posWS.z; - local(target)->pitch = 0; - local(target)->roll = 0; - local(target)->yaw = vec2ToAngle(dxTarget, dzTarget); - local(target)->flags |= TARGET_MOVE_ROT; - - local(nextTick) = s_curTick + local(delay); - } - - if (actor_handleSteps(&local(physicsActor)->moveMod, local(target))) - { - actor_changeDirFromCollision(&local(physicsActor)->moveMod, local(target), &local(prevColTick)); - - local(delay) += 72; - if (local(delay) > 1165) // ~8 seconds - { - local(delay) = 72; - } - local(nextTick) = s_curTick + local(delay); - } - } - task_end; - } - - void kellDragonTaskFunc(MessageType msg) - { - struct LocalContext - { - KellDragon* dragon; - PhysicsActor* physicsActor; - }; - task_begin_ctx; - - local(dragon) = (KellDragon*)task_getUserData(); - local(physicsActor) = &local(dragon)->actor; - while (local(physicsActor)->alive) - { - msg = MSG_RUN_TASK; - if (local(physicsActor)->state == 1) - { - s_curDragon = local(dragon); - task_callTaskFunc(kellDragon_handleState1); - } - else if (local(physicsActor)->state == 2) - { - s_curDragon = local(dragon); - task_callTaskFunc(kellDragon_handleRetreat); - } - else if (local(physicsActor)->state == 3) - { - s_curDragon = local(dragon); - task_callTaskFunc(kellDragon_handleJumping); - } - else if (local(physicsActor)->state == 4) - { - s_curDragon = local(dragon); - task_callTaskFunc(kellDragon_handleState4); - } - else if (local(physicsActor)->state == 5) - { - s_curDragon = local(dragon); - task_callTaskFunc(kellDragon_handleDyingState); - } - else if (local(physicsActor)->state == 6) - { - s_curDragon = local(dragon); - task_callTaskFunc(kellDragon_handleState6); - } - else - { - while (local(physicsActor)->state == 0) - { - do - { - entity_yield(145); - s_curDragon = local(dragon); - task_callTaskFunc(kellDragon_handleMsg); - - if (msg == MSG_DAMAGE || msg == MSG_EXPLOSION) - { - local(physicsActor)->state = 1; // Pain State - task_makeActive(local(physicsActor)->actorTask); - task_yield(TASK_NO_DELAY); - } - } while (msg != MSG_RUN_TASK); - if (local(physicsActor)->state == 0 && kellDragon_canSeePlayer(local(dragon))) - { - SecObject* obj = local(dragon)->logic.obj; - sound_playCued(s_shared.kellSound0, obj->posWS); - local(physicsActor)->state = 1; - } - } // while (state == 0) - } - } // while (alive) - - // Dead: - while (msg != MSG_RUN_TASK) - { - task_yield(TASK_NO_DELAY); - } - actor_removePhysicsActorFromWorld(local(physicsActor)); - deleteLogicAndObject((Logic*)local(dragon)); - level_free(local(dragon)); - - task_end; - } - - void kellDragonCleanupFunc(Logic* logic) - { - KellDragon* dragon = (KellDragon*)logic; - - actor_removePhysicsActorFromWorld(&dragon->actor); - deleteLogicAndObject(logic); - level_free(dragon); - task_free(dragon->actor.actorTask); - } - - void kellDragon_serialize(Logic*& logic, SecObject* obj, Stream* stream) - { - KellDragon* dragon = nullptr; - bool write = serialization_getMode() == SMODE_WRITE; - PhysicsActor* physicsActor = nullptr; - Task* dragonTask = nullptr; - if (write) - { - dragon = (KellDragon*)logic; - physicsActor = &dragon->actor; - } - else - { - dragon = (KellDragon*)level_alloc(sizeof(KellDragon)); - memset(dragon, 0, sizeof(KellDragon)); - physicsActor = &dragon->actor; - logic = (Logic*)dragon; - - // Task - char name[32]; - sprintf(name, "KellDragon%d", s_shared.dragonNum); - s_shared.dragonNum++; - - dragonTask = createSubTask(name, kellDragonTaskFunc); - task_setUserData(dragonTask, dragon); - - // Logic - logic->task = dragonTask; - logic->cleanupFunc = kellDragonCleanupFunc; - logic->type = LOGIC_DRAGON; - logic->obj = obj; - } - actor_serializeMovementModuleBase(stream, &physicsActor->moveMod); - actor_serializeLogicAnim(stream, &physicsActor->anim); - if (!write) - { - // Clear out functions, the mousebot handles all of this internally. - physicsActor->moveMod.header.obj = obj; - physicsActor->moveMod.header.func = nullptr; - physicsActor->moveMod.header.freeFunc = nullptr; - physicsActor->moveMod.header.attribFunc = nullptr; - physicsActor->moveMod.header.msgFunc = nullptr; - physicsActor->moveMod.header.type = ACTMOD_MOVE; - physicsActor->moveMod.updateTargetFunc = nullptr; - - actor_addPhysicsActorToWorld(physicsActor); - - physicsActor->moveMod.header.obj = obj; - physicsActor->moveMod.physics.obj = obj; - physicsActor->actorTask = dragonTask; - - dragon->painSndId = NULL_SOUND; - dragon->pad = 0; - } - SERIALIZE(SaveVersionInit, physicsActor->vel, { 0 }); - SERIALIZE(SaveVersionInit, physicsActor->lastPlayerPos, { 0 }); - SERIALIZE(SaveVersionInit, physicsActor->alive, JTRUE); - SERIALIZE(SaveVersionInit, physicsActor->hp, FIXED(180)); - SERIALIZE(SaveVersionInit, physicsActor->state, 0); - - SERIALIZE(SaveVersionInit, dragon->animIndex, 0); - SERIALIZE(SaveVersionInit, dragon->painLevel, 0); - SERIALIZE(SaveVersionInit, dragon->retreat, JFALSE); - SERIALIZE(SaveVersionInit, dragon->nextTick, 0); - } - - Logic* kellDragon_setup(SecObject* obj, LogicSetupFunc* setupFunc) - { - KellDragon* dragon = (KellDragon*)level_alloc(sizeof(KellDragon)); - memset(dragon, 0, sizeof(KellDragon)); - - // Give the name of the task a number so I can tell them apart when debugging. - char name[32]; - sprintf(name, "KellDragon%d", s_shared.dragonNum); - s_shared.dragonNum++; - Task* task = createSubTask(name, kellDragonTaskFunc); - task_setUserData(task, dragon); - - obj->entityFlags = ETFLAG_AI_ACTOR; - PhysicsActor* physicsActor = &dragon->actor; - physicsActor->alive = JTRUE; - physicsActor->hp = FIXED(180); - physicsActor->state = 0; - physicsActor->actorTask = task; - dragon->logic.obj = obj; - dragon->animIndex = 0; - dragon->painLevel = 0; - dragon->painSndId = 0; - dragon->retreat = JFALSE; - - actor_addPhysicsActorToWorld(physicsActor); - physicsActor->moveMod.header.obj = obj; - physicsActor->moveMod.physics.obj = obj; - actor_setupSmartObj(&physicsActor->moveMod); - - obj->flags |= OBJ_FLAG_MOVABLE; - - CollisionInfo* physics = &physicsActor->moveMod.physics; - physics->botOffset = 0x60000; - physics->yPos = 0x80000; - physics->width = obj->worldWidth; - physicsActor->moveMod.collisionFlags |= 7; - physics->height = obj->worldHeight + HALF_16; - - ActorTarget* target = &physicsActor->moveMod.target; - target->flags &= 0xfffffff0; - target->speedRotation = 43546; // 956.8 degrees per second. - target->speed = FIXED(10); - - LogicAnimation* anim = &physicsActor->anim; - anim->frameRate = 5; - anim->flags = (anim->flags | AFLAG_READY) & (~AFLAG_PLAYED); - anim->frameCount = ONE_16; - anim->prevTick = 0; - actor_setupBossAnimation(obj, 5, anim); - - obj_addLogic(obj, &dragon->logic, LOGIC_DRAGON, task, kellDragonCleanupFunc); - if (setupFunc) - { - *setupFunc = nullptr; - } - return (Logic*)dragon; - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/dragon.h b/components/darkforces/tfe/TFE_DarkForces/Actor/dragon.h deleted file mode 100644 index 97b7c33c..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/dragon.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Handles the Kell Dragon AI. -////////////////////////////////////////////////////////////////////// -#include -#include -#include "actor.h" - -namespace TFE_DarkForces -{ - void kellDragon_exit(); - void kellDragon_precache(); - Logic* kellDragon_setup(SecObject* obj, LogicSetupFunc* setupFunc); - void kellDragon_serialize(Logic*& logic, SecObject* obj, Stream* stream); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/enemies.cpp b/components/darkforces/tfe/TFE_DarkForces/Actor/enemies.cpp deleted file mode 100644 index e29df0dd..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/enemies.cpp +++ /dev/null @@ -1,186 +0,0 @@ -#include "enemies.h" -#include "actorModule.h" -#include "animTables.h" -#include "../logic.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace TFE_DarkForces -{ - static const s32 s_reeyeeMinDist = FIXED(30); - - Logic* reeyees_setup(SecObject* obj, LogicSetupFunc* setupFunc) - { - ActorDispatch* dispatch = actor_createDispatch(obj, setupFunc); - dispatch->alertSndSrc = s_alertSndSrc[ALERT_REEYEE]; - - DamageModule* module = actor_createDamageModule(dispatch); - module->hp = FIXED(36); - module->itemDropId = ITEM_DETONATORS; - module->hurtSndSrc = s_agentSndSrc[AGENTSND_REEYEE_2]; - module->dieSndSrc = s_agentSndSrc[AGENTSND_REEYEE_3]; - actor_addModule(dispatch, (ActorModule*)module); - - AttackModule* attackMod = actor_createAttackModule(dispatch); - attackMod->projType = PROJ_THERMAL_DET; - attackMod->attackPrimSndSrc = 0; - attackMod->attackSecSndSrc = 0; - attackMod->timing.rangedDelay = 436; - attackMod->maxDist = FIXED(100); - attackMod->meleeRange = FIXED(10); - attackMod->meleeDmg = FIXED(15); - FLAGS_CLEAR_SET(attackMod->attackFlags, ATTFLAG_LIT_RNG, ATTFLAG_MELEE | ATTFLAG_RANGED); - attackMod->minDist = s_reeyeeMinDist; - s_actorState.attackMod = attackMod; - actor_addModule(dispatch, (ActorModule*)attackMod); - - ThinkerModule* thinkerMod = actor_createThinkerModule(dispatch); - thinkerMod->target.speedRotation = 0x7fff; - thinkerMod->target.speed = FIXED(13); - thinkerMod->anim.flags &= 0xfffffffe; - thinkerMod->startDelay = TICKS(2); - actor_addModule(dispatch, (ActorModule*)thinkerMod); - - MovementModule* moveMod = actor_createMovementModule(dispatch); - dispatch->moveMod = moveMod; - dispatch->animTable = s_reeyeesAnimTable; - - moveMod->collisionFlags |= 1; - moveMod->physics.width = obj->worldWidth; - actor_setupInitAnimation(); - - return (Logic*)dispatch; - } - - Logic* reeyees2_setup(SecObject* obj, LogicSetupFunc* setupFunc) - { - ActorDispatch* dispatch = actor_createDispatch(obj, setupFunc); - dispatch->alertSndSrc = s_alertSndSrc[ALERT_REEYEE]; - - DamageModule* module = actor_createDamageModule(dispatch); - module->hp = FIXED(36); - module->hurtSndSrc = s_agentSndSrc[AGENTSND_REEYEE_2]; - module->dieSndSrc = s_agentSndSrc[AGENTSND_REEYEE_3]; - actor_addModule(dispatch, (ActorModule*)module); - - AttackModule* attackMod = actor_createAttackModule(dispatch); - attackMod->attackSecSndSrc = 0; - attackMod->maxDist = FIXED(100); - FLAGS_CLEAR_SET(attackMod->attackFlags, ATTFLAG_RANGED | ATTFLAG_LIT_RNG, ATTFLAG_MELEE); - attackMod->meleeDmg = FIXED(15); - attackMod->meleeRange = FIXED(10); - s_actorState.attackMod = attackMod; - actor_addModule(dispatch, (ActorModule*)attackMod); - - ThinkerModule* thinkerMod = actor_createThinkerModule(dispatch); - thinkerMod->target.speedRotation = 0x7fff; - thinkerMod->target.speed = FIXED(13); - thinkerMod->anim.flags &= 0xfffffffe; - thinkerMod->startDelay = TICKS(2); - actor_addModule(dispatch, (ActorModule*)thinkerMod); - - MovementModule* moveMod = actor_createMovementModule(dispatch); - dispatch->moveMod = moveMod; - dispatch->animTable = s_reeyeesAnimTable; - - moveMod->collisionFlags |= 1; - moveMod->physics.width = obj->worldWidth; - actor_setupInitAnimation(); - - return (Logic*)dispatch; - } - - Logic* gamor_setup(SecObject* obj, LogicSetupFunc* setupFunc) - { - ActorDispatch* dispatch = actor_createDispatch(obj, setupFunc); - dispatch->alertSndSrc = s_alertSndSrc[ALERT_GAMOR]; - - DamageModule* module = actor_createDamageModule(dispatch); - module->hp = FIXED(90); - module->stopOnHit = JFALSE; - module->dieSndSrc = s_agentSndSrc[AGENTSND_GAMOR_1]; - module->hurtSndSrc = s_agentSndSrc[AGENTSND_GAMOR_2]; - actor_addModule(dispatch, (ActorModule*)module); - - AttackModule* attackMod = actor_createAttackModule(dispatch); - s_actorState.attackMod = attackMod; - attackMod->timing.meleeDelay = 233; // 1.6 seconds - attackMod->meleeRange = FIXED(13); - attackMod->meleeDmg = FIXED(40); - attackMod->meleeRate = FIXED(360); - attackMod->attackSecSndSrc = s_agentSndSrc[AGENTSND_AXE_1]; - FLAGS_CLEAR_SET(attackMod->attackFlags, ATTFLAG_RANGED, ATTFLAG_MELEE); - actor_addModule(dispatch, (ActorModule*)attackMod); - - ThinkerModule* thinkerMod = actor_createThinkerModule(dispatch); - thinkerMod->approachVariation = 2730; - thinkerMod->delay = 0; - thinkerMod->target.speedRotation = 0x3fff; - thinkerMod->target.speed = FIXED(12); - thinkerMod->anim.flags &= 0xfffffffe; - thinkerMod->startDelay = TICKS(2); - actor_addModule(dispatch, (ActorModule*)thinkerMod); - - MovementModule* moveMod = actor_createMovementModule(dispatch); - dispatch->moveMod = moveMod; - dispatch->animTable = s_gamorAnimTable; - - moveMod->collisionFlags |= 1; - moveMod->physics.width = obj->worldWidth; - actor_setupInitAnimation(); - - return (Logic*)dispatch; - } - - Logic* bossk_setup(SecObject* obj, LogicSetupFunc* setupFunc) - { - ActorDispatch* dispatch = actor_createDispatch(obj, setupFunc); - dispatch->alertSndSrc = s_alertSndSrc[ALERT_BOSSK]; - - DamageModule* module = actor_createDamageModule(dispatch); - module->hp = FIXED(45); - module->dieSndSrc = s_agentSndSrc[AGENTSND_BOSSK_DIE]; - module->hurtSndSrc = s_agentSndSrc[AGENTSND_BOSSK_3]; - module->itemDropId = ITEM_CONCUSSION; - actor_addModule(dispatch, (ActorModule*)module); - - AttackModule* attackMod = actor_createAttackModule(dispatch); - s_actorState.attackMod = attackMod; - attackMod->projType = PROJ_CONCUSSION; - attackMod->maxDist = FIXED(100); - attackMod->minDist = FIXED(10); - attackMod->attackPrimSndSrc = s_concussion5SndSrc; - attackMod->fireSpread = 0; - FLAGS_CLEAR_SET(attackMod->attackFlags, ATTFLAG_MELEE, ATTFLAG_RANGED); - actor_addModule(dispatch, (ActorModule*)attackMod); - - ThinkerModule* thinkerMod = actor_createThinkerModule(dispatch); - thinkerMod->target.speedRotation = 0x7fff; - thinkerMod->target.speed = FIXED(9); - thinkerMod->delay = 0; - thinkerMod->anim.flags &= 0xfffffffe; - thinkerMod->startDelay = TICKS(2); - actor_addModule(dispatch, (ActorModule*)thinkerMod); - - MovementModule* moveMod = actor_createMovementModule(dispatch); - dispatch->moveMod = moveMod; - dispatch->animTable = s_bosskAnimTable; - - moveMod->collisionFlags |= 1; - moveMod->physics.width = obj->worldWidth; - actor_setupInitAnimation(); - - return (Logic*)dispatch; - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/enemies.h b/components/darkforces/tfe/TFE_DarkForces/Actor/enemies.h deleted file mode 100644 index 78b4066b..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/enemies.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Handles basic enemies that have no custom code beyond the setup. -////////////////////////////////////////////////////////////////////// -#include -#include -#include "actor.h" - -namespace TFE_DarkForces -{ - Logic* reeyees_setup(SecObject* obj, LogicSetupFunc* setupFunc); - Logic* reeyees2_setup(SecObject* obj, LogicSetupFunc* setupFunc); - Logic* bossk_setup(SecObject* obj, LogicSetupFunc* setupFunc); - Logic* gamor_setup(SecObject* obj, LogicSetupFunc* setupFunc); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/exploders.cpp b/components/darkforces/tfe/TFE_DarkForces/Actor/exploders.cpp deleted file mode 100644 index d0387cb1..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/exploders.cpp +++ /dev/null @@ -1,187 +0,0 @@ -#include "exploders.h" -#include "../logic.h" -#include "actorModule.h" -#include "animTables.h" -#include -#include -#include -#include - -namespace TFE_DarkForces -{ - // Actor function for exploders (i.e. landmines and exploding barrels). - JBool exploderFunc(ActorModule* module, MovementModule* moveMod) - { - DamageModule* damageMod = (DamageModule*)module; - LogicAnimation* anim = &damageMod->attackMod.anim; - if (!(anim->flags & AFLAG_READY)) - { - s_actorState.curAnimation = anim; - return JFALSE; - } - else if ((anim->flags & AFLAG_PLAYED) && damageMod->hp <= 0) - { - actor_kill(); - return JFALSE; - } - return JTRUE; - } - - // Actor message function for exploders, this is responsible for processing messages such as - // projectile damage and explosions. For other AI message functions, it would also process - // "wake up" messages, but those messages are ignored for exploders. - JBool exploderMsgFunc(s32 msg, ActorModule* module, MovementModule* moveMod) - { - DamageModule* damageMod = (DamageModule*)module; - JBool retValue = JFALSE; - SecObject* obj = damageMod->attackMod.header.obj; - LogicAnimation* anim = &damageMod->attackMod.anim; - - if (msg == MSG_DAMAGE) - { - if (damageMod->hp > 0) - { - ProjectileLogic* proj = (ProjectileLogic*)s_msgEntity; - damageMod->hp -= proj->dmg; - JBool retValue; - if (damageMod->hp > 0) - { - retValue = JTRUE; - } - else - { - ProjectileLogic* proj = (ProjectileLogic*)createProjectile(PROJ_EXP_BARREL, obj->sector, obj->posWS.x, obj->posWS.y, obj->posWS.z, obj); - proj->vel = { 0, 0, 0 }; - obj->flags |= OBJ_FLAG_FULLBRIGHT; - - // I have to remove the logics here in order to get this to work, but this doesn't actually happen here in the original code. - // TODO: Move to the correct location. - actor_removeLogics(obj); - - actor_setupAnimation(2/*animIndex*/, anim); - moveMod->updateTargetFunc(moveMod, &damageMod->attackMod.target); - retValue = JFALSE; - } - } - } - else if (msg == MSG_EXPLOSION) - { - if (damageMod->hp <= 0) - { - return JTRUE; - } - - fixed16_16 dmg = s_msgArg1; - fixed16_16 force = s_msgArg2; - damageMod->hp -= dmg; - - vec3_fixed pushDir; - vec3_fixed pos = { obj->posWS.x, obj->posWS.y - obj->worldHeight, obj->posWS.z }; - computeExplosionPushDir(&pos, &pushDir); - - fixed16_16 pushX = mul16(force, pushDir.x); - fixed16_16 pushZ = mul16(force, pushDir.z); - if (damageMod->hp > 0) - { - actor_addVelocity(pushX >> 1, 0, pushZ >> 1); - return JTRUE; - } - - obj->flags |= OBJ_FLAG_FULLBRIGHT; - actor_addVelocity(pushX, 0, pushZ); - - ProjectileLogic* proj = (ProjectileLogic*)createProjectile(PROJ_EXP_BARREL, obj->sector, obj->posWS.x, obj->posWS.y, obj->posWS.z, obj); - proj->vel = { 0, 0, 0 }; - - ProjectileLogic* proj2 = (ProjectileLogic*)createProjectile(PROJ_EXP_BARREL, obj->sector, obj->posWS.x, obj->posWS.y, obj->posWS.z, obj); - proj2->vel = { 0, 0, 0 }; - proj2->hitEffectId = HEFFECT_EXP_INVIS; - proj2->duration = s_curTick + 36; - - ActorDispatch* actorLogic = (ActorDispatch*)s_actorState.curLogic; - CollisionInfo colInfo = { 0 }; - colInfo.obj = proj2->logic.obj; - colInfo.offsetY = 0; - colInfo.offsetX = mul16(actorLogic->vel.x, 0x4000); - colInfo.offsetZ = mul16(actorLogic->vel.z, 0x4000); - colInfo.botOffset = ONE_16; - colInfo.yPos = COL_INFINITY; - colInfo.height = ONE_16; - colInfo.unused = 0; - colInfo.width = colInfo.obj->worldWidth; - handleCollision(&colInfo); - - // I have to remove the logics here in order to get this to work, but this doesn't actually happen here in the original code. - // TODO: Move to the correct location. - actor_removeLogics(obj); - actor_setupAnimation(2/*animIndex*/, anim); - retValue = JFALSE; - } - return retValue; - } - - Logic* barrel_setup(SecObject* obj, LogicSetupFunc* setupFunc) - { - ActorDispatch* dispatch = actor_createDispatch(obj, setupFunc); - - dispatch->flags &= ~(1 | 4); - dispatch->animTable = s_mineBarrelAnimTable; - - DamageModule* module = actor_createDamageModule(dispatch); - module->attackMod.header.func = exploderFunc; - module->attackMod.header.msgFunc = exploderMsgFunc; - module->hp = FIXED(11); - module->attackMod.anim.flags |= AFLAG_READY; - actor_addModule(dispatch, (ActorModule*)module); - - MovementModule* moveMod = actor_createMovementModule(dispatch); - dispatch->moveMod = moveMod; - moveMod->collisionFlags |= 1; - moveMod->physics.width = obj->worldWidth; - moveMod->target.flags = (moveMod->target.flags & ~TARGET_ALL_MOVE) | TARGET_FREEZE; - moveMod->target.speed = 0; - moveMod->target.speedRotation = 0; - - ActorTarget* target = &module->attackMod.target; - target->flags = (target->flags & ~TARGET_ALL_MOVE) | TARGET_FREEZE; - target->speed = 0; - target->speedRotation = 0; - - return (Logic*)dispatch; - } - - Logic* landmine_setup(SecObject* obj, LogicSetupFunc* setupFunc) - { - ActorDispatch* dispatch = actor_createDispatch(obj, setupFunc); - dispatch->flags &= ~4; - dispatch->flags &= ~1; - dispatch->animTable = s_mineBarrelAnimTable; - - DamageModule* module = actor_createDamageModule(dispatch); - module->attackMod.header.func = exploderFunc; - module->attackMod.header.msgFunc = exploderMsgFunc; - module->attackMod.anim.flags |= AFLAG_READY; - module->hp = FIXED(20); - actor_addModule(dispatch, (ActorModule*)module); - - MovementModule* moveMod = actor_createMovementModule(dispatch); - dispatch->moveMod = moveMod; - moveMod->collisionFlags |= 1; - // This was cleared to 0 in createProjectile() - moveMod->physics.width = obj->worldWidth; - - ActorTarget* target = &module->attackMod.target; - target->flags = (target->flags | 8) & 0xfffffff8; - target->speed = 0; - target->speedRotation = 0; - - moveMod->target.flags = TARGET_FREEZE; - moveMod->target.speed = 0; - moveMod->target.speedRotation = 0; - - dispatch->flags &= ~1; - dispatch->animTable = s_mineBarrelAnimTable; - - return (Logic*)dispatch; - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/exploders.h b/components/darkforces/tfe/TFE_DarkForces/Actor/exploders.h deleted file mode 100644 index f6b8cd13..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/exploders.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Handles exploding actors - Exploding Barrels, and pre-placed -// Landmines. -////////////////////////////////////////////////////////////////////// -#include -#include -#include "actor.h" - -namespace TFE_DarkForces -{ - Logic* barrel_setup(SecObject* obj, LogicSetupFunc* setupFunc); - Logic* landmine_setup(SecObject* obj, LogicSetupFunc* setupFunc); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/flyers.cpp b/components/darkforces/tfe/TFE_DarkForces/Actor/flyers.cpp deleted file mode 100644 index df102a73..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/flyers.cpp +++ /dev/null @@ -1,276 +0,0 @@ -#include "flyers.h" -#include "actorModule.h" -#include "animTables.h" -#include "../logic.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace TFE_DarkForces -{ - JBool flyingModuleFunc(ActorModule* module, MovementModule* moveMod) - { - ThinkerModule* flyingMod = (ThinkerModule*)module; - SecObject* obj = flyingMod->header.obj; - if (flyingMod->anim.state == 0) - { - flyingMod->anim.state = STATE_FIRE1; - return s_curTick + random(flyingMod->delay); - } - else if (flyingMod->anim.state == 1) - { - if (actor_handleSteps(moveMod, &flyingMod->target)) - { - flyingMod->anim.state = STATE_DELAY; - } - SecObject* actorObj = moveMod->header.obj; - if (actor_arrivedAtTarget(&flyingMod->target, actorObj)) - { - flyingMod->anim.state = STATE_DELAY; - } - } - else if (flyingMod->anim.state == STATE_FIRE1) - { - RSector* sector = obj->sector; - if (sector == s_playerObject->sector) - { - // Target a random height above or below the player y position: playerPosY - [-1.5, 6.5] - fixed16_16 heightChange = random(FIXED(5)) - 0x18000; // rand(5) - 1.5 - flyingMod->target.pos.y = s_eyePos.y - heightChange; - flyingMod->target.flags |= TARGET_MOVE_Y; - flyingMod->anim.state = STATE_ANIMATEATTACK; - } - else - { - flyingMod->anim.state = STATE_DELAY; - } - } - - moveMod->updateTargetFunc(moveMod, &flyingMod->target); - return JFALSE; - } - - JBool flyingModuleFunc_Remote(ActorModule* module, MovementModule* moveMod) - { - ThinkerModule* flyingMod = (ThinkerModule*)module; - ActorTarget* target = &flyingMod->target; - SecObject* obj = flyingMod->header.obj; - - if (flyingMod->anim.state == 0) - { - flyingMod->anim.state = STATE_FIRE1; - return s_curTick + random(flyingMod->delay); - } - else if (flyingMod->anim.state == 1) - { - if (actor_arrivedAtTarget(target, obj)) - { - flyingMod->anim.state = STATE_DELAY; - } - } - else if (flyingMod->anim.state == 2) - { - target->yaw = random_next() & ANGLE_MASK; - target->pitch = obj->pitch; - target->roll = obj->roll; - target->flags |= TARGET_MOVE_ROT; - flyingMod->anim.state = STATE_ANIMATEATTACK; - } - - moveMod->updateTargetFunc(moveMod, target); - return JFALSE; - } - - ThinkerModule* actor_createFlyingModule(Logic* logic) - { - ThinkerModule* flyingMod = (ThinkerModule*)level_alloc(sizeof(ThinkerModule)); - actor_thinkerModuleInit(flyingMod); - actor_initModule((ActorModule*)flyingMod, logic); - flyingMod->header.type = ACTMOD_FLYER; - - flyingMod->header.func = flyingModuleFunc; - flyingMod->delay = 145; - - return flyingMod; - } - - ThinkerModule* actor_createFlyingModule_Remote(Logic* logic) - { - ThinkerModule* flyingMod = (ThinkerModule*)level_alloc(sizeof(ThinkerModule)); - actor_thinkerModuleInit(flyingMod); - actor_initModule((ActorModule*)flyingMod, logic); - flyingMod->header.type = ACTMOD_FLYER_REMOTE; - - flyingMod->header.func = flyingModuleFunc_Remote; - flyingMod->delay = 145; // 1 second. - return flyingMod; - } - - Logic* intDroid_setup(SecObject* obj, LogicSetupFunc* setupFunc) - { - ActorDispatch* dispatch = actor_createDispatch(obj, setupFunc); - dispatch->fov = 0x4000; // 360 degrees - dispatch->alertSndSrc = s_alertSndSrc[ALERT_INTDROID]; - - DamageModule* module = actor_createDamageModule(dispatch); - module->hp = FIXED(45); - module->itemDropId = ITEM_POWER; - module->stopOnHit = JFALSE; - module->dieSndSrc = s_agentSndSrc[AGENTSND_SMALL_EXPLOSION]; - actor_addModule(dispatch, (ActorModule*)module); - - AttackModule* attackMod = actor_createAttackModule(dispatch); - attackMod->fireOffset.y = 9830; - attackMod->projType = PROJ_PROBE_PROJ; - attackMod->attackSecSndSrc = s_agentSndSrc[AGENTSND_INTSTUN]; - attackMod->attackPrimSndSrc = s_agentSndSrc[AGENTSND_PROBFIRE_11]; - attackMod->meleeRange = FIXED(30); - attackMod->meleeDmg = FIXED(5); - FLAGS_CLEAR_SET(attackMod->attackFlags, 0, ATTFLAG_MELEE | ATTFLAG_RANGED); - s_actorState.attackMod = attackMod; - actor_addModule(dispatch, (ActorModule*)attackMod); - - ThinkerModule* thinkerMod = actor_createThinkerModule(dispatch); - thinkerMod->target.speedRotation = 0; - thinkerMod->target.speed = FIXED(6); - thinkerMod->delay = 116; - thinkerMod->anim.flags &= ~FLAG_BIT(0); - thinkerMod->startDelay = TICKS(2); // (145.5)*2 - actor_addModule(dispatch, (ActorModule*)thinkerMod); - - ThinkerModule* flyingMod = actor_createFlyingModule((Logic*)dispatch); - flyingMod->target.speedRotation = 0x7fff; - flyingMod->target.speed = FIXED(13); - flyingMod->target.speedVert = FIXED(10); - flyingMod->delay = 436; // just shy of 3 seconds. - actor_addModule(dispatch, (ActorModule*)flyingMod); - - MovementModule* moveMod = actor_createMovementModule(dispatch); - dispatch->moveMod = moveMod; - moveMod->collisionFlags = (moveMod->collisionFlags & 0xfffffff8) | 4; - moveMod->physics.yPos = FIXED(200); - moveMod->physics.width = obj->worldWidth; - - // Setup the animation. - dispatch->animTable = s_intDroidAnimTable; - actor_setupInitAnimation(); - - return (Logic*)dispatch; - } - - Logic* probeDroid_setup(SecObject* obj, LogicSetupFunc* setupFunc) - { - ActorDispatch* dispatch = actor_createDispatch(obj, setupFunc); - dispatch->fov = 0x4000; // 360 degrees - dispatch->alertSndSrc = s_alertSndSrc[ALERT_PROBE]; - - DamageModule* module = actor_createDamageModule(dispatch); - module->hp = FIXED(45); - module->itemDropId = ITEM_POWER; - module->stopOnHit = JFALSE; - module->dieEffect = HEFFECT_EXP_35; - module->dieSndSrc = s_agentSndSrc[AGENTSND_PROBE_ALM]; - actor_addModule(dispatch, (ActorModule*)module); - - AttackModule* attackMod = actor_createAttackModule(dispatch); - attackMod->fireOffset.y = -557056; - attackMod->projType = PROJ_RIFLE_BOLT; - attackMod->attackPrimSndSrc = s_agentSndSrc[AGENTSND_PROBFIRE_12]; - FLAGS_CLEAR_SET(attackMod->attackFlags, ATTFLAG_MELEE, ATTFLAG_RANGED); - s_actorState.attackMod = attackMod; - actor_addModule(dispatch, (ActorModule*)attackMod); - - ThinkerModule* thinkerMod = actor_createThinkerModule(dispatch); - thinkerMod->target.speedRotation = 0; - thinkerMod->target.speed = FIXED(6); - thinkerMod->delay = 116; - thinkerMod->anim.flags &= ~FLAG_BIT(0); - thinkerMod->startDelay = TICKS(2); // (145.5)*2 - actor_addModule(dispatch, (ActorModule*)thinkerMod); - - ThinkerModule* flyingMod = actor_createFlyingModule((Logic*)dispatch); - flyingMod->target.speedRotation = 0x7fff; - flyingMod->target.speed = FIXED(4); - flyingMod->target.speedVert = FIXED(2); - flyingMod->delay = 436; // just shy of 3 seconds. - actor_addModule(dispatch, (ActorModule*)flyingMod); - - MovementModule* moveMod = actor_createMovementModule(dispatch); - dispatch->moveMod = moveMod; - moveMod->collisionFlags = (moveMod->collisionFlags & 0xfffffff8) | 4; - moveMod->physics.yPos = FIXED(200); - moveMod->physics.width = obj->worldWidth; - - // Setup the animation. - dispatch->animTable = s_probeDroidAnimTable; - actor_setupInitAnimation(); - - return (Logic*)dispatch; - } - - Logic* remote_setup(SecObject* obj, LogicSetupFunc* setupFunc) - { - obj->entityFlags = ETFLAG_AI_ACTOR | ETFLAG_FLYING | ETFLAG_REMOTE; - ActorDispatch* dispatch = actor_createDispatch(obj, setupFunc); - dispatch->fov = 0x4000; - - DamageModule* module = actor_createDamageModule(dispatch); - module->dieSndSrc = s_agentSndSrc[AGENTSND_TINY_EXPLOSION]; - module->hp = FIXED(9); - actor_addModule(dispatch, (ActorModule*)module); - - AttackModule* attackMod = actor_createAttackModule(dispatch); - attackMod->attackPrimSndSrc = s_agentSndSrc[AGENTSND_PROBFIRE_13]; - attackMod->projType = PROJ_REMOTE_BOLT; - FLAGS_CLEAR_SET(attackMod->attackFlags, ATTFLAG_MELEE, ATTFLAG_RANGED); - attackMod->fireOffset.y = 0x4000; // 0.25 units. - attackMod->maxDist = FIXED(50); - s_actorState.attackMod = attackMod; - actor_addModule(dispatch, (ActorModule*)attackMod); - - ThinkerModule* thinkerMod = actor_createThinkerModule(dispatch); - thinkerMod->target.speedRotation = 0x7fff; - thinkerMod->target.speed = FIXED(15); - thinkerMod->target.speedVert = FIXED(10); - thinkerMod->delay = 436; - thinkerMod->startDelay = 109; - thinkerMod->targetOffset = FIXED(9); - actor_addModule(dispatch, (ActorModule*)thinkerMod); - - ThinkerModule* flyingMod = actor_createFlyingModule_Remote((Logic*)dispatch); - flyingMod->target.speedRotation = 0x7fff; - flyingMod->delay = 291; - actor_addModule(dispatch, (ActorModule*)flyingMod); - - flyingMod = actor_createFlyingModule((Logic*)dispatch); - flyingMod->target.speedRotation = 0x7fff; - flyingMod->target.speed = FIXED(13); - flyingMod->target.speedVert = FIXED(10); - flyingMod->delay = 291; - actor_addModule(dispatch, (ActorModule*)flyingMod); - - MovementModule* moveMod = actor_createMovementModule(dispatch); - dispatch->moveMod = moveMod; - moveMod->collisionFlags &= 0xfffffff8; - moveMod->collisionFlags |= 4; - moveMod->physics.yPos = FIXED(200); - - // should be: 0xa7ec - moveMod->physics.width = obj->worldWidth; - obj->entityFlags &= 0xfffff7ff; - dispatch->animTable = s_remoteAnimTable; - actor_setupInitAnimation(); - - return (Logic*)dispatch; - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/flyers.h b/components/darkforces/tfe/TFE_DarkForces/Actor/flyers.h deleted file mode 100644 index 0df73646..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/flyers.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Handles the main flying enemies - Probe and Interrogation Droids. -////////////////////////////////////////////////////////////////////// -#include -#include -#include "actor.h" - -namespace TFE_DarkForces -{ - Logic* intDroid_setup(SecObject* obj, LogicSetupFunc* setupFunc); - Logic* probeDroid_setup(SecObject* obj, LogicSetupFunc* setupFunc); - Logic* remote_setup(SecObject* obj, LogicSetupFunc* setupFunc); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/mousebot.cpp b/components/darkforces/tfe/TFE_DarkForces/Actor/mousebot.cpp deleted file mode 100644 index ea2ef709..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/mousebot.cpp +++ /dev/null @@ -1,506 +0,0 @@ -#include - -#include "mousebot.h" -#include "actorModule.h" -#include "actorSerialization.h" -#include "../logic.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace TFE_DarkForces -{ - enum MouseBotState - { - MBSTATE_SLEEPING = 0, - MBSTATE_ACTIVE, - MBSTATE_DYING - }; - - struct MouseBotResources - { - WaxFrame* deadFrame = nullptr; - SoundSourceId sound0 = NULL_SOUND; - SoundSourceId sound1 = NULL_SOUND; - SoundSourceId sound2 = NULL_SOUND; - }; - struct MouseBot - { - Logic logic; - PhysicsActor actor; - }; - - static MouseBotResources s_mouseBotRes = { 0 }; - static MouseBot* s_curMouseBot; - static s32 s_mouseNum = 0; - - MessageType mousebot_handleDamage(MessageType msg, MouseBot* mouseBot) - { - SecObject* obj = mouseBot->logic.obj; - if (mouseBot->actor.alive) - { - ProjectileLogic* proj = (ProjectileLogic*)s_msgEntity; - mouseBot->actor.hp -= proj->dmg; - if (mouseBot->actor.hp <= 0) - { - mouseBot->actor.state = MBSTATE_DYING; - msg = MSG_RUN_TASK; - } - else - { - sound_playCued(s_mouseBotRes.sound1, obj->posWS); - msg = MSG_DAMAGE; - } - } - return msg; - } - - MessageType mousebot_handleExplosion(MessageType msg, MouseBot* mouseBot) - { - PhysicsActor* phyActor = &mouseBot->actor; - SecObject* obj = mouseBot->logic.obj; - if (mouseBot->actor.alive) - { - fixed16_16 dmg = s_msgArg1; - fixed16_16 force = s_msgArg2; - - mouseBot->actor.hp -= dmg; - vec3_fixed pushDir; - vec3_fixed pos = { obj->posWS.x, obj->posWS.y - obj->worldHeight, obj->posWS.z }; - - computeExplosionPushDir(&pos, &pushDir); - vec3_fixed vel = { mul16(force, pushDir.x), mul16(force, pushDir.y), mul16(force, pushDir.z) }; - - msg = MSG_RUN_TASK; - if (mouseBot->actor.hp <= 0) - { - mouseBot->actor.state = MBSTATE_DYING; - phyActor->vel = vel; - } - else - { - phyActor->vel = { vel.x >> 1, vel.y >> 1, vel.z >> 1 }; - sound_playCued(s_mouseBotRes.sound1, obj->posWS); - } - } - return msg; - } - - void mousebot_handleActiveState(MessageType msg) - { - struct LocalContext - { - MouseBot* mouseBot; - SecObject* obj; - PhysicsActor* phyActor; - MovementModule* moveMod; - CollisionInfo* colInfo; - Tick tick; - - JBool odd; - JBool flip; - }; - task_begin_ctx; - - local(mouseBot) = s_curMouseBot; - local(obj) = local(mouseBot)->logic.obj; - local(phyActor) = &local(mouseBot)->actor; - local(moveMod) = &local(phyActor)->moveMod; - local(colInfo) = &local(moveMod)->physics; - - local(moveMod)->target.pos = local(obj)->posWS; - local(moveMod)->target.yaw = local(obj)->yaw; - - local(tick) = s_curTick; - local(odd) = JFALSE; - local(flip) = JFALSE; - while (local(phyActor)->state == MBSTATE_ACTIVE) - { - do - { - entity_yield(TASK_NO_DELAY); - if (msg == MSG_DAMAGE) - { - msg = mousebot_handleExplosion(msg, local(mouseBot)); - } - else if (msg == MSG_EXPLOSION) - { - msg = mousebot_handleDamage(msg, local(mouseBot)); - } - } while (msg != MSG_RUN_TASK); - - if (local(phyActor)->state != MBSTATE_ACTIVE) { break; } - - // Go to sleep if the player hasn't been spotted in about 5 seconds. - if (actor_isObjectVisible(local(obj), s_playerObject, 0x4000/*360 degrees*/, FIXED(25)/*closeDist*/)) - { - local(tick) = s_curTick; - } - else - { - Tick dt = s_curTick - local(tick); - // If enough time has past since the player was last spotted, go back to sleep. - if (dt > 728) // ~5 seconds. - { - local(phyActor)->state = MBSTATE_SLEEPING; - break; - } - } - - angle14_32 yaw = local(obj)->yaw & ANGLE_MASK; - angle14_32 actorYaw = local(moveMod)->target.yaw & ANGLE_MASK; - if (actorYaw == yaw) - { - local(odd) = (s_curTick & 1) ? JTRUE : JFALSE; - angle14_32 deltaYaw = random(16338); - local(moveMod)->target.yaw = local(odd) ? (local(obj)->yaw + deltaYaw) : (local(obj)->yaw - deltaYaw); - - local(moveMod)->target.speedRotation = random(0x3555) + 0x555; - local(moveMod)->target.flags |= TARGET_MOVE_ROT; - local(flip) = JFALSE; - } - - if (local(colInfo)->wall) - { - s32 rnd = random(100); - if (rnd <= 10) // ~10% chance of playing a sound effect when hitting a wall. - { - sound_playCued(s_mouseBotRes.sound0, local(obj)->posWS); - } - if (local(odd)) - { - local(moveMod)->target.yaw += 4096; - } - else - { - local(moveMod)->target.yaw -= 4096; - } - local(moveMod)->target.speedRotation = random(0x3555); - local(flip) = ~local(flip); - } - - fixed16_16 speed = local(flip) ? -FIXED(22) : FIXED(22); - fixed16_16 cosYaw, sinYaw; - sinCosFixed(local(obj)->yaw, &sinYaw, &cosYaw); - local(moveMod)->target.pos.x = local(obj)->posWS.x + mul16(sinYaw, speed); - local(moveMod)->target.pos.z = local(obj)->posWS.z + mul16(cosYaw, speed); - - local(moveMod)->target.speed = FIXED(22); - local(moveMod)->target.flags |= TARGET_MOVE_XZ; - } - task_end; - } - - void mousebot_die(MessageType msg) - { - struct LocalContext - { - MouseBot* mouseBot; - MovementModule* moveMod; - SecObject* obj; - RSector* sector; - }; - task_begin_ctx; - local(mouseBot) = s_curMouseBot; - local(obj) = local(mouseBot)->logic.obj; - local(moveMod) = &local(mouseBot)->actor.moveMod; - local(sector) = local(obj)->sector; - - local(moveMod)->target.flags |= TARGET_FREEZE; - sound_playCued(s_mouseBotRes.sound2, local(obj)->posWS); - - while (1) - { - entity_yield(TASK_NO_DELAY); - if (msg == MSG_RUN_TASK && actor_canDie(&local(mouseBot)->actor)) - { - break; - } - } - - // Spawn a small explosion. - spawnHitEffect(HEFFECT_SMALL_EXP, local(sector), local(obj)->posWS, local(obj)); - - fixed16_16 secHeight = local(sector)->secHeight - 1; - if (secHeight < 0) // Not a water sector. - { - // Create the dead version of the mousebot. - SecObject* newObj = allocateObject(); - if (newObj) - { - if (!s_mouseBotRes.deadFrame) - { - TFE_System::logWrite(LOG_ERROR, "MouseBot", "Missing asset - dead frame."); - // Attempt to load it now. - s_mouseBotRes.deadFrame = TFE_Sprite_Jedi::getFrame("dedmouse.fme"); - } - - frame_setData(newObj, s_mouseBotRes.deadFrame); - newObj->frame = 0; - newObj->posWS = local(obj)->posWS; - newObj->entityFlags |= ETFLAG_CORPSE; - newObj->worldWidth = 0; - newObj->worldHeight = 0; - sector_addObject(local(sector), newObj); - } - - // Spawn a battery. - SecObject* item = item_create(ITEM_BATTERY); - item->posWS = local(obj)->posWS; - sector_addObject(local(sector), item); - } - - local(mouseBot)->actor.alive = JFALSE; - task_end; - } - - void mouseBotLocalMsgFunc(MessageType msg) - { - MouseBot* mouseBot = (MouseBot*)task_getUserData(); - if (msg == MSG_DAMAGE) - { - mousebot_handleDamage(msg, mouseBot); - } - else if (msg == MSG_EXPLOSION) - { - mousebot_handleExplosion(msg, mouseBot); - } - - // Wake up the mousebot if it has been hit. - if (mouseBot->actor.state == MBSTATE_SLEEPING && (msg == MSG_DAMAGE || msg == MSG_EXPLOSION)) - { - mouseBot->actor.state = MBSTATE_ACTIVE; - task_makeActive(mouseBot->actor.actorTask); - } - } - - void mouseBotTaskFunc(MessageType msg) - { - struct LocalContext - { - MouseBot* mouseBot; - PhysicsActor* actor; - SecObject* obj; - }; - task_begin_ctx; - local(mouseBot) = (MouseBot*)task_getUserData(); - local(actor) = &local(mouseBot)->actor; - - while (local(mouseBot)->actor.alive) - { - task_setMessage(MSG_RUN_TASK); - if (local(actor)->state == MBSTATE_DYING) - { - s_curMouseBot = local(mouseBot); - task_callTaskFunc(mousebot_die); - } - else if (local(actor)->state == MBSTATE_ACTIVE) - { - s_curMouseBot = local(mouseBot); - task_callTaskFunc(mousebot_handleActiveState); - } - else - { - local(obj) = local(mouseBot)->logic.obj; - while (local(actor)->state == MBSTATE_SLEEPING) - { - do - { - entity_yield(145); - if (msg == MSG_DAMAGE) - { - msg = mousebot_handleExplosion(msg, local(mouseBot)); - } - else if (msg == MSG_EXPLOSION) - { - msg = mousebot_handleDamage(msg, local(mouseBot)); - } - - if (msg == MSG_DAMAGE || msg == MSG_EXPLOSION) - { - local(actor)->state = MBSTATE_ACTIVE; - task_makeActive(local(actor)->actorTask); - task_yield(TASK_NO_DELAY); - } - } while (msg != MSG_RUN_TASK); - - // Wakeup if the player is visible. - if (local(actor)->state == MBSTATE_SLEEPING && actor_isObjectVisible(local(obj), s_playerObject, 0x4000/*full 360 degree fov*/, FIXED(25)/*25 units "close distance"*/)) - { - sound_playCued(s_mouseBotRes.sound0, local(obj)->posWS); - local(mouseBot)->actor.state = MBSTATE_ACTIVE; - } - } - } - } - - // The Mousebot is dead. - while (msg != MSG_RUN_TASK) - { - task_yield(TASK_NO_DELAY); - } - actor_removePhysicsActorFromWorld(&local(mouseBot)->actor); - deleteLogicAndObject(&local(mouseBot)->logic); - level_free(local(mouseBot)); - - task_end; - } - - void mouseBotLogicCleanupFunc(Logic* logic) - { - MouseBot* mouseBot = (MouseBot*)logic; - - Task* task = mouseBot->actor.actorTask; - actor_removePhysicsActorFromWorld(&mouseBot->actor); - deleteLogicAndObject(&mouseBot->logic); - level_free(mouseBot); - task_free(task); - } - - void mousebot_clear() - { - s_mouseBotRes.deadFrame = nullptr; - } - - void mousebot_exit() - { - s_mouseBotRes = {}; - } - - void mousebot_precache() - { - s_mouseBotRes.sound0 = sound_load("eeek-1.voc", SOUND_PRIORITY_MED5); - s_mouseBotRes.sound1 = sound_load("eeek-2.voc", SOUND_PRIORITY_LOW0); - s_mouseBotRes.sound2 = sound_load("eeek-3.voc", SOUND_PRIORITY_MED5); - } - - void mousebot_serialize(Logic*& logic, SecObject* obj, Stream* stream) - { - MouseBot* mouseBot = nullptr; - PhysicsActor* physActor = nullptr; - Task* mouseBotTask = nullptr; - bool write = serialization_getMode() == SMODE_WRITE; - if (write) - { - mouseBot = (MouseBot*)logic; - physActor = &mouseBot->actor; - } - else - { - mouseBot = (MouseBot*)level_alloc(sizeof(MouseBot)); - memset(mouseBot, 0, sizeof(MouseBot)); - logic = (Logic*)mouseBot; - - // Resources - if (!s_mouseBotRes.deadFrame) - { - s_mouseBotRes.deadFrame = TFE_Sprite_Jedi::getFrame("dedmouse.fme"); - } - - // Task - char name[32]; - sprintf(name, "mouseBot%d", s_mouseNum); - s_mouseNum++; - - mouseBotTask = createSubTask(name, mouseBotTaskFunc, mouseBotLocalMsgFunc); - task_setUserData(mouseBotTask, mouseBot); - - // Logic - logic->task = mouseBotTask; - logic->cleanupFunc = mouseBotLogicCleanupFunc; - logic->type = LOGIC_MOUSEBOT; - logic->obj = obj; - physActor = &mouseBot->actor; - } - actor_serializeMovementModuleBase(stream, &physActor->moveMod); - actor_serializeLogicAnim(stream, &physActor->anim); - if (!write) - { - // Clear out functions, the mousebot handles all of this internally. - physActor->moveMod.header.obj = obj; - physActor->moveMod.header.func = nullptr; - physActor->moveMod.header.freeFunc = nullptr; - physActor->moveMod.header.attribFunc = nullptr; - physActor->moveMod.header.msgFunc = nullptr; - physActor->moveMod.header.type = ACTMOD_MOVE; - physActor->moveMod.updateTargetFunc = nullptr; - - actor_addPhysicsActorToWorld(physActor); - - physActor->moveMod.header.obj = obj; - physActor->moveMod.physics.obj = obj; - physActor->actorTask = mouseBotTask; - } - SERIALIZE(SaveVersionInit, physActor->vel, { 0 }); - SERIALIZE(SaveVersionInit, physActor->lastPlayerPos, { 0 }); - SERIALIZE(SaveVersionInit, physActor->alive, JTRUE); - SERIALIZE(SaveVersionInit, physActor->hp, FIXED(10)); - SERIALIZE(SaveVersionInit, physActor->state, MBSTATE_SLEEPING); - } - - Logic* mousebot_setup(SecObject* obj, LogicSetupFunc* setupFunc) - { - if (!s_mouseBotRes.deadFrame) - { - s_mouseBotRes.deadFrame = TFE_Sprite_Jedi::getFrame("dedmouse.fme"); - } - - MouseBot* mouseBot = (MouseBot*)level_alloc(sizeof(MouseBot)); - memset(mouseBot, 0, sizeof(MouseBot)); - - // Give the name of the task a number so I can tell them apart when debugging. - char name[32]; - sprintf(name, "mouseBot%d", s_mouseNum); - s_mouseNum++; - Task* mouseBotTask = createSubTask(name, mouseBotTaskFunc, mouseBotLocalMsgFunc); - task_setUserData(mouseBotTask, mouseBot); - - obj->flags &= ~OBJ_FLAG_AIM; - obj->entityFlags = ETFLAG_AI_ACTOR; - mouseBot->logic.obj = obj; - - PhysicsActor* physActor = &mouseBot->actor; - physActor->alive = JTRUE; - physActor->hp = FIXED(10); - physActor->actorTask = mouseBotTask; - physActor->state = MBSTATE_SLEEPING; - physActor->moveMod.header.obj = obj; - physActor->moveMod.physics.obj = obj; - actor_addPhysicsActorToWorld(physActor); - actor_setupSmartObj(&physActor->moveMod); - - JediModel* model = obj->model; - fixed16_16 width = model->radius + ONE_16; - obj->worldWidth = width; - obj->worldHeight = width >> 1; - - physActor->moveMod.physics.botOffset = 0; - physActor->moveMod.physics.yPos = 0; - physActor->moveMod.collisionFlags = (physActor->moveMod.collisionFlags | 3) & 0xfffffffb; - physActor->moveMod.physics.height = obj->worldHeight + HALF_16; - physActor->moveMod.target.speed = FIXED(22); - physActor->moveMod.target.speedRotation = FIXED(3185); - physActor->moveMod.target.flags &= ~TARGET_ALL; - physActor->moveMod.target.pitch = obj->pitch; - physActor->moveMod.target.yaw = obj->yaw; - physActor->moveMod.target.roll = obj->roll; - - obj_addLogic(obj, (Logic*)mouseBot, LOGIC_MOUSEBOT, mouseBotTask, mouseBotLogicCleanupFunc); - if (setupFunc) - { - *setupFunc = nullptr; - } - return (Logic*)mouseBot; - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/mousebot.h b/components/darkforces/tfe/TFE_DarkForces/Actor/mousebot.h deleted file mode 100644 index 4b8a02b3..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/mousebot.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Handles the Mousebot AI. -////////////////////////////////////////////////////////////////////// -#include -#include -#include "actor.h" - -namespace TFE_DarkForces -{ - Logic* mousebot_setup(SecObject* obj, LogicSetupFunc* setupFunc); - - void mousebot_clear(); - void mousebot_exit(); - void mousebot_precache(); - - void mousebot_serialize(Logic*& logic, SecObject* obj, Stream* stream); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/phaseOne.cpp b/components/darkforces/tfe/TFE_DarkForces/Actor/phaseOne.cpp deleted file mode 100644 index 1f4e789c..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/phaseOne.cpp +++ /dev/null @@ -1,966 +0,0 @@ -#include - -#include "phaseOne.h" -#include "actorModule.h" -#include "actorSerialization.h" -#include "../logic.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace TFE_DarkForces -{ - struct PhaseOne - { - Logic logic; - PhysicsActor actor; - - SoundEffectId hitSndId; - SoundEffectId reflectSndId; - JBool canDamage; - }; - - struct PhaseOneShared - { - SoundSourceId phase1aSndID = NULL_SOUND; - SoundSourceId phase1bSndID = NULL_SOUND; - SoundSourceId phase1cSndID = NULL_SOUND; - SoundSourceId phase1SwordSndID = NULL_SOUND; - SoundSourceId phase1ReflectSndID = NULL_SOUND; - s32 trooperNum = 0; - }; - - static PhaseOne* s_curTrooper = nullptr; - static PhaseOneShared s_shared = {}; - - void phaseOne_exit() - { - s_curTrooper = nullptr; - s_shared = {}; - } - - void phaseOne_precache() - { - s_shared.phase1aSndID = sound_load("phase1a.voc", SOUND_PRIORITY_MED5); - s_shared.phase1bSndID = sound_load("phase1b.voc", SOUND_PRIORITY_LOW0); - s_shared.phase1SwordSndID = sound_load("sword-1.voc", SOUND_PRIORITY_LOW0); - s_shared.phase1ReflectSndID = sound_load("bigrefl1.voc", SOUND_PRIORITY_LOW0); - s_shared.phase1cSndID = sound_load("phase1c.voc", SOUND_PRIORITY_MED5); - } - - JBool phaseOne_canSeePlayer(PhaseOne* trooper) - { - if (actor_canSeeObject(trooper->logic.obj, s_playerObject)) - { - trooper->actor.lastPlayerPos.x = s_playerObject->posWS.x; - trooper->actor.lastPlayerPos.z = s_playerObject->posWS.z; - return JTRUE; - } - return JFALSE; - } - - void phaseOne_reflectShot(MessageType msg) - { - struct LocalContext - { - PhaseOne* trooper; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - LogicAnimation tmp; - JBool restoreAnim; - }; - task_begin_ctx; - - local(trooper) = s_curTrooper; - local(obj) = local(trooper)->logic.obj; - local(physicsActor) = &local(trooper)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - local(trooper)->canDamage = JTRUE; - local(restoreAnim) = JFALSE; - - if (local(physicsActor)->alive) - { - if (random(100) <= 70) - { - task_localBlockBegin; - ProjectileLogic* proj = (ProjectileLogic*)s_msgEntity; - SecObject* projObj = proj->logic.obj; - s_projReflectOverrideYaw = projObj->yaw + 0x1000; - local(target)->flags |= TARGET_FREEZE; - s_hitWallFlag = WH_BOUNCE; - - // Save Animation. - local(restoreAnim) = JTRUE; - memcpy(&local(tmp), local(anim), sizeof(LogicAnimation) - 4); - - // Handle reflection. - sound_stop(local(trooper)->reflectSndId); - local(trooper)->reflectSndId = sound_playCued(s_shared.phase1ReflectSndID, local(obj)->posWS); - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 13, local(anim)); - task_localBlockEnd; - - // Wait for animation to finish. - do - { - entity_yield(TASK_NO_DELAY); - if (msg == MSG_DAMAGE) - { - ProjectileLogic* proj = (ProjectileLogic*)s_msgEntity; - local(physicsActor)->hp -= proj->dmg; - } - else if (msg == MSG_EXPLOSION) - { - if (s_curEffectData->type == HEFFECT_THERMDET_EXP) - { - s_msgArg1 >>= 1; - } - local(physicsActor)->hp -= s_msgArg1; - } - } while (msg != MSG_RUN_TASK || !(local(anim)->flags & AFLAG_READY)); - } - else - { - task_localBlockBegin; - ProjectileLogic* proj = (ProjectileLogic*)s_msgEntity; - local(physicsActor)->hp -= proj->dmg; - task_localBlockEnd; - - if (local(physicsActor)->hp <= 0) - { - local(physicsActor)->state = 4; - msg = MSG_RUN_TASK; - task_setMessage(msg); - } - else - { - sound_stop(local(trooper)->hitSndId); - local(trooper)->hitSndId = sound_playCued(s_shared.phase1bSndID, local(obj)->posWS); - if (random(100) <= 20) - { - local(target)->flags |= TARGET_FREEZE; - // Save Animation. - local(restoreAnim) = JTRUE; - memcpy(&local(tmp), local(anim), sizeof(LogicAnimation) - 4); - - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 12, local(anim)); - - // Wait for animation to finish. - do - { - entity_yield(TASK_NO_DELAY); - if (msg == MSG_DAMAGE) - { - ProjectileLogic* proj = (ProjectileLogic*)s_msgEntity; - local(physicsActor)->hp -= proj->dmg; - } - else if (msg == MSG_EXPLOSION) - { - if (s_curEffectData->type == HEFFECT_THERMDET_EXP) - { - s_msgArg1 >>= 1; - } - local(physicsActor)->hp -= s_msgArg1; - } - } while (msg != MSG_RUN_TASK || !(local(anim)->flags & AFLAG_READY)); - } - } - } - // Restore Animation. - if (local(restoreAnim)) - { - memcpy(local(anim), &local(tmp), sizeof(LogicAnimation) - 4); - actor_setupBossAnimation(local(obj), local(anim)->animId, local(anim)); - local(target)->flags &= ~TARGET_FREEZE; - } - msg = MSG_RUN_TASK; - task_setMessage(msg); - } - local(trooper)->canDamage = JFALSE; - task_end; - } - - void phaseOne_handleExplosion(MessageType msg) - { - struct LocalContext - { - PhaseOne* trooper; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - LogicAnimation tmp; - vec3_fixed vel; - }; - task_begin_ctx; - - local(trooper) = s_curTrooper; - local(obj) = local(trooper)->logic.obj; - local(physicsActor) = &local(trooper)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - local(trooper)->canDamage = JTRUE; - - if (local(physicsActor)->alive) - { - task_localBlockBegin; - fixed16_16 dmg = s_msgArg1; - fixed16_16 force = s_msgArg2; - - local(physicsActor)->hp -= dmg; - vec3_fixed pos = { local(obj)->posWS.x, local(obj)->posWS.y - local(obj)->worldHeight, local(obj)->posWS.z }; - vec3_fixed pushDir; - - computeExplosionPushDir(&pos, &pushDir); - local(vel) = { mul16(pushDir.x, force), mul16(pushDir.y, force), mul16(pushDir.z, force) }; - task_localBlockEnd; - - if (local(physicsActor)->hp <= 0) - { - local(physicsActor)->state = 4; - local(physicsActor)->vel = local(vel); - msg = MSG_RUN_TASK; - task_setMessage(msg); - } - else - { - local(vel).x -= (local(vel).x < 0 ? 1 : 0); - local(vel).y -= (local(vel).y < 0 ? 1 : 0); - local(vel).z -= (local(vel).z < 0 ? 1 : 0); - local(physicsActor)->vel = { local(vel).x >> 1, local(vel).y >> 1, local(vel).z >> 1 }; - - sound_stop(local(trooper)->hitSndId); - local(trooper)->hitSndId = sound_playCued(s_shared.phase1bSndID, local(obj)->posWS); - - if (random(100) <= 20) - { - local(target)->flags |= TARGET_FREEZE; - - // Save Animation - memcpy(&local(tmp), local(anim), sizeof(LogicAnimation) - 4); - - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 12, local(anim)); - - // Wait for animation to finish. - do - { - entity_yield(TASK_NO_DELAY); - if (msg == MSG_DAMAGE) - { - ProjectileLogic* proj = (ProjectileLogic*)s_msgEntity; - local(physicsActor)->hp -= proj->dmg; - } - else if (msg == MSG_EXPLOSION) - { - if (s_curEffectData->type == HEFFECT_THERMDET_EXP) - { - s_msgArg1 >>= 1; - } - local(physicsActor)->hp -= s_msgArg1; - } - } while (msg != MSG_RUN_TASK || !(local(anim)->flags & AFLAG_READY)); - - memcpy(local(anim), &local(tmp), sizeof(LogicAnimation) - 4); - actor_setupBossAnimation(local(obj), local(anim)->animId, local(anim)); - local(target)->flags &= ~TARGET_FREEZE; - } - msg = MSG_EXPLOSION; - task_setMessage(msg); - } - } // if (alive) - local(trooper)->canDamage = JFALSE; - task_end; - } - - void phaseOne_handleMsg(MessageType msg) - { - struct LocalContext - { - PhaseOne* trooper; - }; - task_begin_ctx; - local(trooper) = s_curTrooper; - - if (msg == MSG_DAMAGE) - { - if (!local(trooper)->canDamage) - { - s_curTrooper = local(trooper); - task_callTaskFunc(phaseOne_reflectShot); - } - else - { - ProjectileLogic* proj = (ProjectileLogic*)s_msgEntity; - local(trooper)->actor.hp -= proj->dmg; - } - } - else if (msg == MSG_EXPLOSION) - { - if (s_curEffectData->type == HEFFECT_THERMDET_EXP) - { - s_msgArg1 >>= 1; - } - if (!local(trooper)->canDamage) - { - s_curTrooper = local(trooper); - task_callTaskFunc(phaseOne_handleExplosion); - } - else - { - local(trooper)->actor.hp -= s_msgArg1; - } - } - task_end; - } - - void phaseOne_handleCharge(MessageType msg) - { - struct LocalContext - { - PhaseOne* trooper; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - u32 prevColTick; - }; - task_begin_ctx; - - local(trooper) = s_curTrooper; - local(obj) = local(trooper)->logic.obj; - local(physicsActor) = &local(trooper)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - local(prevColTick) = 0; - - local(anim)->flags &= ~AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 0, local(anim)); - - while (local(physicsActor)->state == 1) - { - do - { - entity_yield(TASK_NO_DELAY); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseOne_handleMsg); - } while (msg != MSG_RUN_TASK); - if (local(physicsActor)->state != 1) { break; } - - if (!s_playerDying && phaseOne_canSeePlayer(local(trooper))) - { - fixed16_16 dy = TFE_Jedi::abs(local(obj)->posWS.y - s_playerObject->posWS.y); - fixed16_16 dist = dy + distApprox(s_playerObject->posWS.x, s_playerObject->posWS.z, local(obj)->posWS.x, local(obj)->posWS.z); - if (dist <= FIXED(15) && local(obj)->yaw == local(target)->yaw) - { - local(physicsActor)->state = 3; - } - } - else if (!s_playerDying) - { - local(physicsActor)->state = 5; - } - if (local(physicsActor)->state != 1) { break; } - - local(target)->flags &= ~TARGET_FREEZE; - if (actor_handleSteps(&local(physicsActor)->moveMod, local(target))) - { - // Change direction if the Trooper hits a wall or impassable ledge or drop. - actor_changeDirFromCollision(&local(physicsActor)->moveMod, local(target), &local(prevColTick)); - } - else - { - if (!s_playerDying) - { - fixed16_16 dx = s_playerObject->posWS.x - local(obj)->posWS.x; - fixed16_16 dz = s_playerObject->posWS.z - local(obj)->posWS.z; - local(target)->yaw = vec2ToAngle(dx, dz); - } - else - { - local(target)->yaw = random(16338); - } - - local(target)->speedRotation = 0x3000; - local(target)->flags |= TARGET_MOVE_ROT; - - fixed16_16 sinYaw, cosYaw; - sinCosFixed(local(obj)->yaw, &sinYaw, &cosYaw); - local(target)->pos.x = local(obj)->posWS.x + mul16(sinYaw, FIXED(30)); - local(target)->pos.z = local(obj)->posWS.z + mul16(cosYaw, FIXED(30)); - local(target)->flags |= TARGET_MOVE_XZ; - } - } - - local(anim)->flags |= AFLAG_READY; - task_end; - } - - void phaseOne_handleState2(MessageType msg) - { - struct LocalContext - { - PhaseOne* trooper; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - JBool odd; - }; - task_begin_ctx; - - local(trooper) = s_curTrooper; - local(obj) = local(trooper)->logic.obj; - local(physicsActor) = &local(trooper)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - local(odd) = (s_curTick & 1) ? JFALSE : JTRUE; - local(anim)->flags &= ~AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 0, local(anim)); - - task_localBlockBegin; - fixed16_16 dx = local(obj)->posWS.x - s_playerObject->posWS.x; - fixed16_16 dz = local(obj)->posWS.z - s_playerObject->posWS.z; - angle14_32 angle = vec2ToAngle(dx, dz) & ANGLE_MASK; - angle14_32 moveAngle = local(odd) ? angle - 2048 : angle + 2048; - - fixed16_16 sinYaw, cosYaw; - sinCosFixed(moveAngle, &sinYaw, &cosYaw); - - local(target)->flags &= ~TARGET_FREEZE; - local(target)->pos.x = s_playerObject->posWS.x + mul16(FIXED(15), sinYaw); - local(target)->pos.z = s_playerObject->posWS.z + mul16(FIXED(15), cosYaw); - local(target)->flags |= TARGET_MOVE_XZ; - - angle14_32 targetAngle = local(odd) ? angle - 4323 : angle + 4323; - local(target)->yaw = targetAngle; - local(target)->speedRotation = 0; - local(target)->flags |= TARGET_MOVE_ROT; - task_localBlockEnd; - - while (local(physicsActor)->state == 2) - { - do - { - entity_yield(TASK_NO_DELAY); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseOne_handleMsg); - } while (msg != MSG_RUN_TASK); - if (local(physicsActor)->state != 2) { break; } - - task_localBlockBegin; - CollisionInfo* collisionInfo = &local(physicsActor)->moveMod.physics; - if (collisionInfo->wall || collisionInfo->collidedObj) - { - local(physicsActor)->state = 1; - break; - } - - fixed16_16 dist = distApprox(s_playerObject->posWS.x, s_playerObject->posWS.z, local(obj)->posWS.x, local(obj)->posWS.z); - if (s_playerDying || !phaseOne_canSeePlayer(local(trooper)) || dist > FIXED(25)) - { - local(physicsActor)->state = 1; - break; - } - task_localBlockEnd; - - if (actor_arrivedAtTarget(local(target), local(obj))) - { - if (random(100) <= 70) - { - local(physicsActor)->state = 3; - fixed16_16 dx = s_playerObject->posWS.x - local(obj)->posWS.x; - fixed16_16 dz = s_playerObject->posWS.z - local(obj)->posWS.z; - local(target)->yaw = vec2ToAngle(dx, dz); - break; - } - else - { - if (random(100) <= 10) - { - local(odd) = ~local(odd); - } - fixed16_16 dx = local(obj)->posWS.x - s_playerObject->posWS.x; - fixed16_16 dz = local(obj)->posWS.z - s_playerObject->posWS.z; - angle14_32 angle = vec2ToAngle(dx, dz) & ANGLE_MASK; - angle14_32 angleMove = local(odd) ? (angle - 2048) : (angle + 2048); - - fixed16_16 sinYaw, cosYaw; - sinCosFixed(angleMove, &sinYaw, &cosYaw); - - local(target)->flags &= ~TARGET_FREEZE; - local(target)->pos.x = s_playerObject->posWS.x + mul16(FIXED(15), sinYaw); - local(target)->pos.z = s_playerObject->posWS.z + mul16(FIXED(15), cosYaw); - local(target)->flags |= TARGET_MOVE_XZ; - - angle14_32 angleTarget = local(odd) ? (angle - 4096) : (angle + 4096); - local(target)->yaw = angleTarget; - local(target)->speedRotation = 0; - local(target)->flags |= TARGET_MOVE_ROT; - } - } - } - - local(anim)->flags |= AFLAG_READY; - task_end; - } - - void phaseOne_handleAttack(MessageType msg) - { - struct LocalContext - { - PhaseOne* trooper; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - }; - task_begin_ctx; - - local(trooper) = s_curTrooper; - local(obj) = local(trooper)->logic.obj; - local(physicsActor) = &local(trooper)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - - local(target)->flags |= TARGET_FREEZE; - while (local(physicsActor)->state == 3) - { - do - { - entity_yield(TASK_NO_DELAY); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseOne_handleMsg); - } while (msg != MSG_RUN_TASK); - if (local(physicsActor)->state != 3) { break; } - - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 1, local(anim)); - - // Wait for the animation to finish. - do - { - entity_yield(TASK_NO_DELAY); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseOne_handleMsg); - } while (msg != MSG_RUN_TASK || !(local(anim)->flags&AFLAG_READY)); - - // Attempt to attack. - sound_playCued(s_shared.phase1SwordSndID, local(obj)->posWS); - fixed16_16 dy = TFE_Jedi::abs(local(obj)->posWS.y - s_playerObject->posWS.y); - fixed16_16 dist = dy + distApprox(s_playerObject->posWS.x, s_playerObject->posWS.z, local(obj)->posWS.x, local(obj)->posWS.z); - if (dist <= FIXED(15)) - { - player_applyDamage(FIXED(20), 0, JTRUE); - local(physicsActor)->state = 2; - } - else - { - local(physicsActor)->state = 1; - } - } - - task_end; - } - - void phaseOne_handleDyingState(MessageType msg) - { - struct LocalContext - { - PhaseOne* trooper; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - }; - task_begin_ctx; - - local(trooper) = s_curTrooper; - local(obj) = local(trooper)->logic.obj; - local(physicsActor) = &local(trooper)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - - local(target)->flags |= TARGET_FREEZE; - sound_playCued(s_shared.phase1cSndID, local(obj)->posWS); - - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 2, local(anim)); - - // Wait for the animation to finish. - do - { - entity_yield(TASK_NO_DELAY); - } while (msg != MSG_RUN_TASK || !(local(anim)->flags & AFLAG_READY)); - - // Wait until the actor can die. - do - { - entity_yield(TASK_NO_DELAY); - } while (msg != MSG_RUN_TASK || !actor_canDie(local(physicsActor))); - - task_localBlockBegin; - RSector* sector = local(obj)->sector; - if (sector->secHeight - 1 < 0) - { - SecObject* corpse = allocateObject(); - sprite_setData(corpse, local(obj)->wax); - corpse->frame = 0; - corpse->anim = 4; - corpse->posWS = local(obj)->posWS; - corpse->worldWidth = 0; - corpse->worldHeight = 0; - corpse->entityFlags |= (ETFLAG_CORPSE | ETFLAG_KEEP_CORPSE); - sector_addObject(sector, corpse); - } - local(physicsActor)->alive = JFALSE; - actor_handleBossDeath(local(physicsActor)); - task_localBlockEnd; - - task_end; - } - - void phaseOne_handleState5(MessageType msg) - { - struct LocalContext - { - PhaseOne* trooper; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - JBool updateTargetPos; - Tick prevColTick; - Tick nextTick; - Tick nextTick2; - Tick delay; - }; - task_begin_ctx; - - local(trooper) = s_curTrooper; - local(obj) = local(trooper)->logic.obj; - local(physicsActor) = &local(trooper)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - - local(updateTargetPos) = JTRUE; - local(prevColTick) = 0; - local(nextTick2) = 0; - local(nextTick) = s_curTick + 4369; - local(delay) = 72; - - local(anim)->flags &= ~AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 0, local(anim)); - local(target)->flags &= ~TARGET_FREEZE; - - while (local(physicsActor)->state == 5) - { - do - { - entity_yield(TASK_NO_DELAY); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseOne_handleMsg); - } while (msg != MSG_RUN_TASK); - if (local(physicsActor)->state != 5 || s_playerDying) { break; } - - JBool canSee = actor_canSeeObject(local(obj), s_playerObject); - if (canSee) - { - local(physicsActor)->lastPlayerPos.x = s_playerObject->posWS.x; - local(physicsActor)->lastPlayerPos.z = s_playerObject->posWS.z; - local(physicsActor)->state = 1; - break; - } - - JBool arrivedAtTarget = actor_arrivedAtTarget(local(target), local(obj)); - if (local(nextTick2) < s_curTick || arrivedAtTarget) - { - local(updateTargetPos) = JTRUE; - if (arrivedAtTarget) - { - local(nextTick) = 0; - } - } - - fixed16_16 targetX; - fixed16_16 targetZ; - if (local(updateTargetPos)) - { - local(updateTargetPos) = JFALSE; - if (s_curTick > local(nextTick)) - { - targetX = s_eyePos.x; - targetZ = s_eyePos.z; - } - else - { - targetX = local(physicsActor)->lastPlayerPos.x; - targetZ = local(physicsActor)->lastPlayerPos.z; - } - - fixed16_16 dx = TFE_Jedi::abs(s_playerObject->posWS.x - local(obj)->posWS.x); - fixed16_16 offset = dx >> 2; - angle14_32 angle = vec2ToAngle(local(obj)->posWS.x - targetX, local(obj)->posWS.z - targetZ); - - local(target)->pos.x = targetX; - local(target)->pos.z = targetZ; - actor_offsetTarget(&local(target)->pos.x, &local(target)->pos.z, offset, offset >> 1, angle, 0xfff); - local(target)->flags |= TARGET_MOVE_XZ; - - local(target)->yaw = vec2ToAngle(local(target)->pos.x - local(obj)->posWS.x, local(target)->pos.z - local(obj)->posWS.z); - local(target)->pitch = 0; - local(target)->roll = 0; - local(target)->flags |= TARGET_MOVE_ROT; - - local(nextTick2) = s_curTick + local(delay); - } - - if (actor_handleSteps(&local(physicsActor)->moveMod, local(target))) - { - actor_changeDirFromCollision(&local(physicsActor)->moveMod, local(target), &local(prevColTick)); - local(delay) += 72; - if (local(delay) > 1165) // ~8 seconds - { - local(delay) = 72; - } - local(nextTick2) = s_curTick + local(delay); - } - } // while (state == 5) - - local(anim)->flags |= AFLAG_READY; - task_end; - } - - void phaseOneTaskFunc(MessageType msg) - { - struct LocalContext - { - PhaseOne* trooper; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - }; - task_begin_ctx; - - local(trooper) = (PhaseOne*)task_getUserData(); - local(obj) = local(trooper)->logic.obj; - local(physicsActor) = &local(trooper)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - - while (local(physicsActor)->alive) - { - msg = MSG_RUN_TASK; - task_setMessage(msg); - - if (local(physicsActor)->state == 1) - { - s_curTrooper = local(trooper); - task_callTaskFunc(phaseOne_handleCharge); - } - else if (local(physicsActor)->state == 2) - { - s_curTrooper = local(trooper); - task_callTaskFunc(phaseOne_handleState2); - } - else if (local(physicsActor)->state == 3) - { - s_curTrooper = local(trooper); - task_callTaskFunc(phaseOne_handleAttack); - } - else if (local(physicsActor)->state == 4) - { - s_curTrooper = local(trooper); - task_callTaskFunc(phaseOne_handleDyingState); - } - else if (local(physicsActor)->state == 5) - { - s_curTrooper = local(trooper); - task_callTaskFunc(phaseOne_handleState5); - } - else - { - while (local(physicsActor)->state == 0) - { - do - { - entity_yield(145); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseOne_handleMsg); - - if (msg == MSG_DAMAGE || msg == MSG_EXPLOSION) - { - local(physicsActor)->state = 1; - task_makeActive(local(physicsActor)->actorTask); - task_yield(TASK_NO_DELAY); - } - } while (msg != MSG_RUN_TASK); - - if (local(physicsActor)->state == 0 && phaseOne_canSeePlayer(local(trooper))) - { - sound_playCued(s_shared.phase1aSndID, local(obj)->posWS); - local(physicsActor)->state = 1; - } - } // while (state == 0) - } - } // while (alive) - - // Dead - while (msg != MSG_RUN_TASK) - { - task_yield(TASK_NO_DELAY); - } - - actor_removePhysicsActorFromWorld(local(physicsActor)); - deleteLogicAndObject(&local(trooper)->logic); - level_free(local(trooper)); - - task_end; - } - - void phaseOneCleanupFunc(Logic* logic) - { - PhaseOne* trooper = (PhaseOne*)logic; - PhysicsActor* physicsActor = &trooper->actor; - - actor_removePhysicsActorFromWorld(physicsActor); - deleteLogicAndObject(&trooper->logic); - level_free(trooper); - task_free(physicsActor->actorTask); - } - - void phaseOne_serialize(Logic*& logic, SecObject* obj, Stream* stream) - { - PhaseOne* trooper = nullptr; - bool write = serialization_getMode() == SMODE_WRITE; - PhysicsActor* physicsActor = nullptr; - Task* trooperTask = nullptr; - if (write) - { - trooper = (PhaseOne*)logic; - physicsActor = &trooper->actor; - } - else - { - trooper = (PhaseOne*)level_alloc(sizeof(PhaseOne)); - memset(trooper, 0, sizeof(PhaseOne)); - physicsActor = &trooper->actor; - logic = (Logic*)trooper; - - // Task - char name[32]; - sprintf(name, "PhaseOne%d", s_shared.trooperNum); - s_shared.trooperNum++; - - trooperTask = createSubTask(name, phaseOneTaskFunc); - task_setUserData(trooperTask, trooper); - - // Logic - logic->task = trooperTask; - logic->cleanupFunc = phaseOneCleanupFunc; - logic->type = LOGIC_PHASE_ONE; - logic->obj = obj; - } - actor_serializeMovementModuleBase(stream, &physicsActor->moveMod); - actor_serializeLogicAnim(stream, &physicsActor->anim); - if (!write) - { - // Clear out functions, the mousebot handles all of this internally. - physicsActor->moveMod.header.obj = obj; - physicsActor->moveMod.header.func = nullptr; - physicsActor->moveMod.header.freeFunc = nullptr; - physicsActor->moveMod.header.attribFunc = nullptr; - physicsActor->moveMod.header.msgFunc = nullptr; - physicsActor->moveMod.header.type = ACTMOD_MOVE; - physicsActor->moveMod.updateTargetFunc = nullptr; - - actor_addPhysicsActorToWorld(physicsActor); - - physicsActor->moveMod.header.obj = obj; - physicsActor->moveMod.physics.obj = obj; - physicsActor->actorTask = trooperTask; - - trooper->hitSndId = NULL_SOUND; - trooper->reflectSndId = NULL_SOUND; - } - SERIALIZE(SaveVersionInit, physicsActor->vel, { 0 }); - SERIALIZE(SaveVersionInit, physicsActor->lastPlayerPos, { 0 }); - SERIALIZE(SaveVersionInit, physicsActor->alive, JTRUE); - SERIALIZE(SaveVersionInit, physicsActor->hp, FIXED(180)); - SERIALIZE(SaveVersionInit, physicsActor->state, 0); - - SERIALIZE(SaveVersionInit, trooper->canDamage, JFALSE); - } - - Logic* phaseOne_setup(SecObject* obj, LogicSetupFunc* setupFunc) - { - PhaseOne* trooper = (PhaseOne*)level_alloc(sizeof(PhaseOne)); - memset(trooper, 0, sizeof(PhaseOne)); - - PhysicsActor* physicsActor = &trooper->actor; - - // Give the name of the task a number so I can tell them apart when debugging. - char name[32]; - sprintf(name, "PhaseOne%d", s_shared.trooperNum); - s_shared.trooperNum++; - Task* task = createSubTask(name, phaseOneTaskFunc); - task_setUserData(task, trooper); - - obj->entityFlags = ETFLAG_AI_ACTOR; - - physicsActor->alive = JTRUE; - physicsActor->hp = FIXED(180); - physicsActor->state = 0; - physicsActor->actorTask = task; - trooper->hitSndId = 0; - trooper->reflectSndId = 0; - trooper->canDamage = JFALSE; - trooper->logic.obj = obj; - actor_addPhysicsActorToWorld(physicsActor); - - physicsActor->moveMod.header.obj = obj; - physicsActor->moveMod.physics.obj = obj; - actor_setupSmartObj(&physicsActor->moveMod); - - physicsActor->moveMod.collisionFlags |= 3; - physicsActor->moveMod.collisionFlags &= 0xfffffffb; - - ActorTarget* target = &physicsActor->moveMod.target; - target->flags &= 0xfffffff0; - target->speed = FIXED(30); - target->speedRotation = 0x3000; - - LogicAnimation* anim = &physicsActor->anim; - anim->frameRate = 5; - anim->frameCount = ONE_16; - anim->prevTick = 0; - anim->flags |= AFLAG_READY; - anim->flags &= (~AFLAG_PLAYED); - - actor_setupBossAnimation(obj, 5, anim); - obj_addLogic(obj, (Logic*)trooper, LOGIC_PHASE_ONE, task, phaseOneCleanupFunc); - - if (setupFunc) - { - *setupFunc = nullptr; - } - return (Logic*)trooper; - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/phaseOne.h b/components/darkforces/tfe/TFE_DarkForces/Actor/phaseOne.h deleted file mode 100644 index 0b0545bb..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/phaseOne.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Handles the Phase One Dark Trooper AI. -////////////////////////////////////////////////////////////////////// -#include -#include -#include "actor.h" - -namespace TFE_DarkForces -{ - void phaseOne_exit(); - void phaseOne_precache(); - Logic* phaseOne_setup(SecObject* obj, LogicSetupFunc* setupFunc); - void phaseOne_serialize(Logic*& logic, SecObject* obj, Stream* stream); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/phaseThree.cpp b/components/darkforces/tfe/TFE_DarkForces/Actor/phaseThree.cpp deleted file mode 100644 index 5bc9c93e..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/phaseThree.cpp +++ /dev/null @@ -1,1076 +0,0 @@ -#include - -#include "phaseThree.h" -#include "actorModule.h" -#include "actorSerialization.h" -#include "../logic.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace TFE_DarkForces -{ - enum PhaseThreeStates - { - P3STATE_DEFAULT = 0, - P3STATE_CHARGE, - P3STATE_WANDER, - P3STATE_FIRE_MISSILES, - P3STATE_FIRE_PLASMA, - P3STATE_DYING, - P3STATE_SEARCH, - P3STATE_COUNT - }; - - static const angle14_16 c_phaseThreeMissileOffsets[] = - { - -2275, -1365, -455, 455, 1365, 2275 - }; - - struct PhaseThree - { - Logic logic; - PhysicsActor actor; - - SoundEffectId rocketSndId; - SoundEffectId hitSndId; - JBool noDeath; - }; - - struct PhaseThreeShared - { - SoundSourceId phase3aSndID = NULL_SOUND; - SoundSourceId phase3bSndID = NULL_SOUND; - SoundSourceId phase3DieSndID = NULL_SOUND; - SoundSourceId phase3RocketSndID = NULL_SOUND; - s32 trooperNum = 0; - }; - - static PhaseThree* s_curTrooper = nullptr; - static PhaseThreeShared s_shared = {}; - - void phaseThree_exit() - { - s_curTrooper = nullptr; - s_shared = {}; - } - - void phaseThree_precache() - { - s_shared.phase3aSndID = sound_load("phase3a.voc", SOUND_PRIORITY_MED5); - s_shared.phase3bSndID = sound_load("phase3b.voc", SOUND_PRIORITY_LOW0); - s_shared.phase3RocketSndID = sound_load("rocket-1.voc", SOUND_PRIORITY_HIGH0); - s_shared.phase3DieSndID = sound_load("phase3c.voc", SOUND_PRIORITY_HIGH5); - sound_setBaseVolume(s_shared.phase3DieSndID, 120); - } - - JBool phaseThree_updatePlayerPos(PhaseThree* trooper) - { - if (actor_canSeeObject(trooper->logic.obj, s_playerObject)) - { - trooper->actor.lastPlayerPos.x = s_playerObject->posWS.x; - trooper->actor.lastPlayerPos.z = s_playerObject->posWS.z; - return JTRUE; - } - return JFALSE; - } - - void phaseThree_handleDamage(MessageType msg) - { - struct LocalContext - { - PhaseThree* trooper; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - LogicAnimation tmp; - vec3_fixed vel; - }; - task_begin_ctx; - - local(trooper) = s_curTrooper; - local(obj) = local(trooper)->logic.obj; - local(physicsActor) = &local(trooper)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - local(trooper)->noDeath = JTRUE; - - if (local(physicsActor)->alive) - { - task_localBlockBegin; - ProjectileLogic* proj = (ProjectileLogic*)s_msgEntity; - local(physicsActor)->hp -= proj->dmg; - task_localBlockEnd; - - if (local(physicsActor)->hp <= 0) - { - local(physicsActor)->state = P3STATE_DYING; - msg = MSG_RUN_TASK; - task_setMessage(msg); - } - else - { - sound_stop(local(trooper)->hitSndId); - local(trooper)->hitSndId = sound_playCued(s_shared.phase3bSndID, local(obj)->posWS); - - if (random(100) <= 10) - { - local(target)->flags |= TARGET_FREEZE; - - // Save Animation - memcpy(&local(tmp), local(anim), sizeof(LogicAnimation) - 4); - - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 10, local(anim)); - - // Wait for animation to finish. - do - { - entity_yield(TASK_NO_DELAY); - } while (msg != MSG_RUN_TASK || !(local(anim)->flags & AFLAG_READY)); - - memcpy(local(anim), &local(tmp), sizeof(LogicAnimation) - 4); - actor_setupBossAnimation(local(obj), local(anim)->animId, local(anim)); - local(target)->flags &= ~TARGET_FREEZE; - } - msg = MSG_DAMAGE; - task_setMessage(msg); - } - } // if (alive) - local(trooper)->noDeath = JFALSE; - task_end; - } - - void phaseThree_handleExplosion(MessageType msg) - { - struct LocalContext - { - PhaseThree* trooper; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - LogicAnimation tmp; - vec3_fixed vel; - }; - task_begin_ctx; - - local(trooper) = s_curTrooper; - local(obj) = local(trooper)->logic.obj; - local(physicsActor) = &local(trooper)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - local(trooper)->noDeath = JTRUE; - - if (local(physicsActor)->alive) - { - task_localBlockBegin; - fixed16_16 dmg = s_msgArg1; - fixed16_16 force = s_msgArg2; - - local(physicsActor)->hp -= dmg; - vec3_fixed pos = { local(obj)->posWS.x, local(obj)->posWS.y - local(obj)->worldHeight, local(obj)->posWS.z }; - vec3_fixed pushDir; - - computeExplosionPushDir(&pos, &pushDir); - local(vel) = { mul16(pushDir.x, force), mul16(pushDir.y, force), mul16(pushDir.z, force) }; - task_localBlockEnd; - - if (local(physicsActor)->hp <= 0) - { - local(physicsActor)->state = P3STATE_DYING; - local(physicsActor)->vel = local(vel); - msg = MSG_RUN_TASK; - task_setMessage(msg); - } - else - { - local(vel).x -= (local(vel).x < 0 ? 1 : 0); - local(vel).y -= (local(vel).y < 0 ? 1 : 0); - local(vel).z -= (local(vel).z < 0 ? 1 : 0); - local(physicsActor)->vel = { local(vel).x >> 1, local(vel).y >> 1, local(vel).z >> 1 }; - - sound_stop(local(trooper)->hitSndId); - local(trooper)->hitSndId = sound_playCued(s_shared.phase3bSndID, local(obj)->posWS); - - if (random(100) <= 10) - { - local(target)->flags |= TARGET_FREEZE; - - // Save Animation - memcpy(&local(tmp), local(anim), sizeof(LogicAnimation) - 4); - - local(anim)->flags |= 1; - actor_setupBossAnimation(local(obj), 10, local(anim)); - - // Wait for animation to finish. - do - { - entity_yield(TASK_NO_DELAY); - } while (msg != MSG_RUN_TASK || !(local(anim)->flags & AFLAG_READY)); - - memcpy(local(anim), &local(tmp), sizeof(LogicAnimation) - 4); - actor_setupBossAnimation(local(obj), local(anim)->animId, local(anim)); - local(target)->flags &= ~TARGET_FREEZE; - } - msg = MSG_EXPLOSION; - task_setMessage(msg); - } - } // if (alive) - local(trooper)->noDeath = JFALSE; - task_end; - } - - void phaseThree_handleMsg(MessageType msg) - { - struct LocalContext - { - PhaseThree* trooper; - }; - task_begin_ctx; - local(trooper) = s_curTrooper; - - if (msg == MSG_DAMAGE) - { - if (!local(trooper)->noDeath) - { - s_curTrooper = local(trooper); - task_callTaskFunc(phaseThree_handleDamage); - } - else - { - ProjectileLogic* proj = (ProjectileLogic*)s_msgEntity; - local(trooper)->actor.hp -= proj->dmg; - } - } - else if (msg == MSG_EXPLOSION) - { - if (!local(trooper)->noDeath) - { - s_curTrooper = local(trooper); - task_callTaskFunc(phaseThree_handleExplosion); - } - else - { - local(trooper)->actor.hp -= s_msgArg1; - } - } - task_end; - } - - void phaseThree_chargePlayer(MessageType msg) - { - struct LocalContext - { - PhaseThree* trooper; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - u32 prevColTick; - JBool flying; - }; - task_begin_ctx; - - local(trooper) = s_curTrooper; - local(obj) = local(trooper)->logic.obj; - local(physicsActor) = &local(trooper)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - local(prevColTick) = 0; - local(target)->flags &= ~TARGET_FREEZE; - - if (random(100) <= 40) - { - local(trooper)->rocketSndId = sound_playCued(s_shared.phase3RocketSndID, local(obj)->posWS); - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 13, local(anim)); - actor_setAnimFrameRange(local(anim), 0, 1); - - // Wait for the animation to finish. - do - { - entity_yield(TASK_NO_DELAY); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseThree_handleMsg); - } while (!(local(anim)->flags & AFLAG_READY) || msg != MSG_RUN_TASK); - - actor_setupBossAnimation(local(obj), 13, local(anim)); - actor_setAnimFrameRange(local(anim), 2, 2); - - local(target)->speed = FIXED(70); - local(flying) = JTRUE; - local(physicsActor)->moveMod.collisionFlags &= (~3); - local(physicsActor)->moveMod.physics.yPos = COL_INFINITY; - } - else - { - local(physicsActor)->moveMod.collisionFlags |= 3; - local(target)->speed = FIXED(25); - local(flying) = JFALSE; - local(anim)->flags &= ~AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 0, local(anim)); - } - - while (local(physicsActor)->state == P3STATE_CHARGE) - { - do - { - entity_yield(TASK_NO_DELAY); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseThree_handleMsg); - } while (msg != MSG_RUN_TASK); - if (local(physicsActor)->state != P3STATE_CHARGE) { break; } - - if (random(100) <= 10) - { - if (!s_playerDying && phaseThree_updatePlayerPos(local(trooper))) - { - if (playerDist(obj) <= FIXED(100) && local(obj)->yaw == local(target)->yaw) - { - local(physicsActor)->state = (random(100) > 40) ? P3STATE_FIRE_PLASMA : P3STATE_FIRE_MISSILES; - if (local(flying)) - { - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 13, local(anim)); - actor_setAnimFrameRange(local(anim), 3, 3); - do - { - entity_yield(TASK_NO_DELAY); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseThree_handleMsg); - } while (msg != MSG_RUN_TASK || !(local(anim)->flags & AFLAG_READY)); - - local(physicsActor)->moveMod.collisionFlags |= 3; - local(physicsActor)->moveMod.physics.yPos = COL_INFINITY; - local(target)->speed = FIXED(25); - local(target)->flags &= ~TARGET_MOVE_Y; - sound_stop(local(trooper)->rocketSndId); - } - } - } - else if (!s_playerDying) - { - sound_stop(local(trooper)->rocketSndId); - local(physicsActor)->state = P3STATE_SEARCH; - } - } - if (local(physicsActor)->state != P3STATE_CHARGE) { break; } - - local(target)->flags &= ~TARGET_FREEZE; - if (actor_handleSteps(&local(physicsActor)->moveMod, local(target))) - { - // Change direction if the Trooper hits a wall or impassable ledge or drop. - actor_changeDirFromCollision(&local(physicsActor)->moveMod, local(target), &local(prevColTick)); - } - else - { - if (!s_playerDying) - { - fixed16_16 dx = s_playerObject->posWS.x - local(obj)->posWS.x; - fixed16_16 dz = s_playerObject->posWS.z - local(obj)->posWS.z; - local(target)->yaw = vec2ToAngle(dx, dz); - } - else - { - local(target)->yaw = random(16338); - } - - local(target)->speedRotation = 0x3000; - local(target)->flags |= TARGET_MOVE_ROT; - - fixed16_16 sinYaw, cosYaw; - sinCosFixed(local(obj)->yaw, &sinYaw, &cosYaw); - local(target)->pos.x = local(obj)->posWS.x + mul16(sinYaw, FIXED(25)); - local(target)->pos.z = local(obj)->posWS.z + mul16(cosYaw, FIXED(25)); - local(target)->flags |= TARGET_MOVE_XZ; - - if (local(flying)) - { - local(target)->pos.y = s_playerObject->posWS.y - FIXED(2); - local(target)->flags |= TARGET_MOVE_Y; - } - } - } - - local(anim)->flags |= AFLAG_READY; - task_end; - } - - void phaseThree_wander(MessageType msg) - { - struct LocalContext - { - PhaseThree* trooper; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - JBool odd; - }; - task_begin_ctx; - - local(trooper) = s_curTrooper; - local(obj) = local(trooper)->logic.obj; - local(physicsActor) = &local(trooper)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - local(odd) = (s_curTick & 1) ? JFALSE : JTRUE; - local(anim)->flags &= ~AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 0, local(anim)); - - task_localBlockBegin; - fixed16_16 dx = local(obj)->posWS.x - s_playerObject->posWS.x; - fixed16_16 dz = local(obj)->posWS.z - s_playerObject->posWS.z; - angle14_32 angle = vec2ToAngle(dx, dz) & ANGLE_MASK; - angle14_32 moveAngle = local(odd) ? angle - 2048 : angle + 2048; - - fixed16_16 sinYaw, cosYaw; - sinCosFixed(moveAngle, &sinYaw, &cosYaw); - - local(target)->flags &= ~TARGET_FREEZE; - local(target)->pos.x = s_playerObject->posWS.x + mul16(FIXED(100), sinYaw); - local(target)->pos.z = s_playerObject->posWS.z + mul16(FIXED(100), cosYaw); - local(target)->flags |= TARGET_MOVE_XZ; - - angle14_32 targetAngle = local(odd) ? angle - 4323 : angle + 4323; - local(target)->yaw = targetAngle; - local(target)->speedRotation = 0; - local(target)->flags |= TARGET_MOVE_ROT; - task_localBlockEnd; - - while (local(physicsActor)->state == P3STATE_WANDER) - { - do - { - entity_yield(TASK_NO_DELAY); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseThree_handleMsg); - } while (msg != MSG_RUN_TASK); - if (local(physicsActor)->state != P3STATE_WANDER) { break; } - - task_localBlockBegin; - CollisionInfo* collisionInfo = &local(physicsActor)->moveMod.physics; - if (collisionInfo->wall || collisionInfo->collidedObj) - { - local(physicsActor)->state = P3STATE_CHARGE; - break; - } - - fixed16_16 dist = distApprox(s_playerObject->posWS.x, s_playerObject->posWS.z, local(obj)->posWS.x, local(obj)->posWS.z); - if (s_playerDying || !phaseThree_updatePlayerPos(local(trooper)) || dist > FIXED(20)) - { - local(physicsActor)->state = P3STATE_CHARGE; - break; - } - task_localBlockEnd; - - if (actor_arrivedAtTarget(local(target), local(obj))) - { - if (random(100) <= 10) - { - local(physicsActor)->state = (random(100) > 40) ? P3STATE_FIRE_PLASMA : P3STATE_FIRE_MISSILES; - fixed16_16 dx = s_playerObject->posWS.x - local(obj)->posWS.x; - fixed16_16 dz = s_playerObject->posWS.z - local(obj)->posWS.z; - local(target)->yaw = vec2ToAngle(dx, dz); - } - else - { - if (random(100) <= 10) - { - local(odd) = ~local(odd); - } - fixed16_16 dx = local(obj)->posWS.x - s_playerObject->posWS.x; - fixed16_16 dz = local(obj)->posWS.z - s_playerObject->posWS.z; - angle14_32 angle = vec2ToAngle(dx, dz) & ANGLE_MASK; - angle14_32 angleMove = local(odd) ? (angle - 2048) : (angle + 2048); - - fixed16_16 sinYaw, cosYaw; - sinCosFixed(angleMove, &sinYaw, &cosYaw); - - local(target)->flags &= ~TARGET_FREEZE; - local(target)->pos.x = s_playerObject->posWS.x + mul16(FIXED(100), sinYaw); - local(target)->pos.z = s_playerObject->posWS.z + mul16(FIXED(100), cosYaw); - local(target)->flags |= TARGET_MOVE_XZ; - - local(target)->yaw = local(odd) ? (angle - 4096) : (angle + 4096); - local(target)->speedRotation = 0; // was commented out? - local(target)->flags |= TARGET_MOVE_ROT; - } - } - } - - local(anim)->flags |= AFLAG_READY; - task_end; - } - - void phaseThree_fireMissiles(MessageType msg) - { - struct LocalContext - { - PhaseThree* trooper; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - }; - task_begin_ctx; - - local(trooper) = s_curTrooper; - local(obj) = local(trooper)->logic.obj; - local(physicsActor) = &local(trooper)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - - local(target)->flags &= ~TARGET_MOVE_XZ; - local(physicsActor)->moveMod.collisionFlags |= 3; - while (local(physicsActor)->state == P3STATE_FIRE_MISSILES) - { - do - { - entity_yield(TASK_NO_DELAY); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseThree_handleMsg); - } while (msg != MSG_RUN_TASK); - if (local(physicsActor)->state != P3STATE_FIRE_MISSILES) { break; } - - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 11, local(anim)); - - // Wait for the animation to finish. - do - { - entity_yield(TASK_NO_DELAY); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseThree_handleMsg); - } while (msg != MSG_RUN_TASK || !(local(anim)->flags&AFLAG_READY)); - - // Attempt to attack. - task_localBlockBegin; - local(obj)->flags |= OBJ_FLAG_FULLBRIGHT; - sound_playCued(s_missile1SndSrc, local(obj)->posWS); - - // Fire 6 missiles with different yaw offsets. - for (s32 i = 0; i < 6; i++) - { - ProjectileLogic* proj = (ProjectileLogic*)createProjectile(PROJ_HOMING_MISSILE, local(obj)->sector, local(obj)->posWS.x, local(obj)->posWS.y - FIXED(11), local(obj)->posWS.z, local(obj)); - proj->prevColObj = local(obj); - proj->excludeObj = local(obj); - proj->prevObj = local(obj); - - SecObject* projObj = proj->logic.obj; - projObj->yaw = local(target)->yaw + c_phaseThreeMissileOffsets[i]; - proj_setTransform(proj, 0, projObj->yaw); - } - - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 12, local(anim)); - task_localBlockEnd; - - // Wait for the animation to finish. - do - { - entity_yield(TASK_NO_DELAY); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseThree_handleMsg); - } while (msg != MSG_RUN_TASK || !(local(anim)->flags & AFLAG_READY)); - - local(obj)->flags &= ~OBJ_FLAG_FULLBRIGHT; - local(physicsActor)->state = P3STATE_WANDER; - } - - task_end; - } - - void phaseThree_firePlasma(MessageType msg) - { - struct LocalContext - { - PhaseThree* trooper; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - s32 shotCount; - }; - task_begin_ctx; - - local(trooper) = s_curTrooper; - local(obj) = local(trooper)->logic.obj; - local(physicsActor) = &local(trooper)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - - local(target)->flags &= ~TARGET_MOVE_XZ; - local(physicsActor)->moveMod.collisionFlags |= 3; - - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 1, local(anim)); - - // Wait for the animation to finish. - do - { - entity_yield(TASK_NO_DELAY); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseThree_handleMsg); - } while (msg != MSG_RUN_TASK || !(local(anim)->flags & AFLAG_READY)); - - local(shotCount) = random(20) + 1; - local(obj)->flags |= OBJ_FLAG_FULLBRIGHT; - local(target)->flags |= TARGET_FREEZE; - - while (local(physicsActor)->state == P3STATE_FIRE_PLASMA) - { - do - { - entity_yield(29); // 0.2 seconds - s_curTrooper = local(trooper); - task_callTaskFunc(phaseThree_handleMsg); - } while (msg != MSG_RUN_TASK); - if (local(physicsActor)->state != P3STATE_FIRE_PLASMA) { break; } - - sound_playCued(s_plasma4SndSrc, local(obj)->posWS); - - ProjectileLogic* proj = (ProjectileLogic*)createProjectile(PROJ_CANNON, local(obj)->sector, local(obj)->posWS.x, local(obj)->posWS.y - FIXED(9), local(obj)->posWS.z, local(obj)); - proj->prevColObj = local(obj); - proj->excludeObj = local(obj); - - SecObject* projObj = proj->logic.obj; - projObj->yaw = local(target)->yaw; - actor_leadTarget(proj); - local(shotCount)--; - if (local(shotCount) == 0) - { - local(physicsActor)->state = P3STATE_WANDER; - } - } - - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 6, local(anim)); - - // Wait for the animation to finish. - do - { - entity_yield(TASK_NO_DELAY); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseThree_handleMsg); - } while (msg != MSG_RUN_TASK || !(local(anim)->flags & AFLAG_READY)); - - local(obj)->flags &= ~OBJ_FLAG_FULLBRIGHT; - task_end; - } - - void phaseThree_handleDying(MessageType msg) - { - struct LocalContext - { - PhaseThree* trooper; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - }; - task_begin_ctx; - - local(trooper) = s_curTrooper; - local(obj) = local(trooper)->logic.obj; - local(physicsActor) = &local(trooper)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - - local(target)->flags |= TARGET_FREEZE; - sound_stop(local(trooper)->rocketSndId); - sound_playCued(s_shared.phase3DieSndID, local(obj)->posWS); - - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 2, local(anim)); - local(physicsActor)->moveMod.collisionFlags |= 3; // ground, gravity - - // Wait for the animation to finish. - do - { - entity_yield(TASK_NO_DELAY); - } while (msg != MSG_RUN_TASK || !(local(anim)->flags & AFLAG_READY)); - - // Wait until the actor can die. - do - { - entity_yield(TASK_NO_DELAY); - } while (msg != MSG_RUN_TASK || !actor_canDie(local(physicsActor))); - - task_localBlockBegin; - RSector* sector = local(obj)->sector; - if (sector->secHeight - 1 < 0) - { - SecObject* corpse = allocateObject(); - sprite_setData(corpse, local(obj)->wax); - corpse->frame = 0; - corpse->anim = 4; - corpse->posWS = local(obj)->posWS; - corpse->worldWidth = 0; - corpse->worldHeight = 0; - corpse->entityFlags |= (ETFLAG_CORPSE | ETFLAG_KEEP_CORPSE); - sector_addObject(sector, corpse); - } - local(physicsActor)->alive = JFALSE; - actor_handleBossDeath(local(physicsActor)); - task_localBlockEnd; - - task_end; - } - - void phaseThree_lookForPlayer(MessageType msg) - { - struct LocalContext - { - PhaseThree* trooper; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - JBool updateTargetPos; - JBool forceContinue; - Tick prevColTick; - Tick nextTick; - Tick retargetTick; - Tick delay; - }; - task_begin_ctx; - - local(trooper) = s_curTrooper; - local(obj) = local(trooper)->logic.obj; - local(physicsActor) = &local(trooper)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - - local(updateTargetPos) = JTRUE; - local(prevColTick) = 0; - local(retargetTick) = 0; - local(nextTick) = s_curTick + 4369; - local(delay) = 72; - - local(anim)->flags &= ~AFLAG_PLAYED; - local(forceContinue) = JFALSE; - actor_setupBossAnimation(local(obj), 13, local(anim)); - - local(target)->flags &= ~TARGET_FREEZE; - local(target)->speed = FIXED(30); - local(physicsActor)->moveMod.collisionFlags &= (~3); - - while (local(physicsActor)->state == P3STATE_SEARCH || local(forceContinue)) - { - do - { - entity_yield(TASK_NO_DELAY); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseThree_handleMsg); - } while (msg != MSG_RUN_TASK); - if (s_playerDying) { continue; } - - JBool canSee = actor_canSeeObject(local(obj), s_playerObject); - if (canSee) - { - local(physicsActor)->lastPlayerPos.x = s_playerObject->posWS.x; - local(physicsActor)->lastPlayerPos.z = s_playerObject->posWS.z; - local(physicsActor)->state = P3STATE_CHARGE; - } - - if (local(retargetTick) < s_curTick || actor_arrivedAtTarget(local(target), local(obj))) - { - local(updateTargetPos) = JTRUE; - if (actor_arrivedAtTarget(local(target), local(obj))) - { - local(nextTick) = 0; - } - } - - fixed16_16 targetX; - fixed16_16 targetZ; - if (local(updateTargetPos)) - { - local(updateTargetPos) = JFALSE; - if (local(nextTick) > s_curTick) - { - targetX = local(physicsActor)->lastPlayerPos.x; - targetZ = local(physicsActor)->lastPlayerPos.z; - } - else - { - targetX = s_eyePos.x; - targetZ = s_eyePos.z; - } - // This is a copy-paste bug in the original code, it really should be the min of dx and dz. - fixed16_16 dx = TFE_Jedi::abs(s_playerObject->posWS.x - local(obj)->posWS.x); - fixed16_16 offset = dx >> 2; - angle14_32 angle = vec2ToAngle(local(obj)->posWS.x - targetX, local(obj)->posWS.z - targetZ); - - local(target)->pos.x = targetX; - local(target)->pos.z = targetZ; - actor_offsetTarget(&local(target)->pos.x, &local(target)->pos.z, offset, offset >> 1, angle, 0xfff); - local(target)->flags |= TARGET_MOVE_XZ; - - local(target)->yaw = vec2ToAngle(local(target)->pos.x - local(obj)->posWS.x, local(target)->pos.z - local(obj)->posWS.z); - local(target)->pitch = 0; - local(target)->roll = 0; - local(target)->flags |= TARGET_MOVE_ROT; - - local(retargetTick) = s_curTick + local(delay); - } - - if (actor_handleSteps(&local(physicsActor)->moveMod, local(target))) - { - actor_changeDirFromCollision(&local(physicsActor)->moveMod, local(target), &local(prevColTick)); - local(delay) += 36; - local(forceContinue) = JTRUE; - if (local(delay) > 582) - { - local(delay) = 72; - } - local(retargetTick) = s_curTick + local(delay); - } - else - { - local(forceContinue) = JFALSE; - } - } // while (state == 6 || forceContinue) - - local(anim)->flags |= AFLAG_READY; - task_end; - } - - void phaseThreeTaskFunc(MessageType msg) - { - struct LocalContext - { - PhaseThree* trooper; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - }; - task_begin_ctx; - - local(trooper) = (PhaseThree*)task_getUserData(); - local(obj) = local(trooper)->logic.obj; - local(physicsActor) = &local(trooper)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - - while (local(physicsActor)->alive) - { - msg = MSG_RUN_TASK; - task_setMessage(msg); - - if (local(physicsActor)->state == P3STATE_CHARGE) - { - s_curTrooper = local(trooper); - task_callTaskFunc(phaseThree_chargePlayer); - } - else if (local(physicsActor)->state == P3STATE_WANDER) - { - s_curTrooper = local(trooper); - task_callTaskFunc(phaseThree_wander); - } - else if (local(physicsActor)->state == P3STATE_FIRE_MISSILES) - { - s_curTrooper = local(trooper); - task_callTaskFunc(phaseThree_fireMissiles); - } - else if (local(physicsActor)->state == P3STATE_FIRE_PLASMA) - { - s_curTrooper = local(trooper); - task_callTaskFunc(phaseThree_firePlasma); - } - else if (local(physicsActor)->state == P3STATE_DYING) - { - s_curTrooper = local(trooper); - task_callTaskFunc(phaseThree_handleDying); - } - else if (local(physicsActor)->state == P3STATE_SEARCH) - { - s_curTrooper = local(trooper); - task_callTaskFunc(phaseThree_lookForPlayer); - } - else - { - while (local(physicsActor)->state == P3STATE_DEFAULT) - { - do - { - entity_yield(145); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseThree_handleMsg); - - if (msg == MSG_DAMAGE || msg == MSG_EXPLOSION) - { - local(physicsActor)->state = P3STATE_CHARGE; - task_makeActive(local(physicsActor)->actorTask); - task_yield(TASK_NO_DELAY); - } - } while (msg != MSG_RUN_TASK); - - if (local(physicsActor)->state == P3STATE_DEFAULT && phaseThree_updatePlayerPos(local(trooper))) - { - sound_playCued(s_shared.phase3aSndID, local(obj)->posWS); - local(physicsActor)->state = P3STATE_CHARGE; - } - } // while (state == P3STATE_DEFAULT) - } - } // while (alive) - - // Dead - while (msg != MSG_RUN_TASK) - { - task_yield(TASK_NO_DELAY); - } - - actor_removePhysicsActorFromWorld(local(physicsActor)); - deleteLogicAndObject(&local(trooper)->logic); - level_free(local(trooper)); - - task_end; - } - - void phaseThreeCleanupFunc(Logic* logic) - { - PhaseThree* trooper = (PhaseThree*)logic; - PhysicsActor* physicsActor = &trooper->actor; - - actor_removePhysicsActorFromWorld(physicsActor); - deleteLogicAndObject(&trooper->logic); - level_free(trooper); - task_free(physicsActor->actorTask); - } - - void phaseThree_serialize(Logic*& logic, SecObject* obj, Stream* stream) - { - PhaseThree* trooper = nullptr; - bool write = serialization_getMode() == SMODE_WRITE; - PhysicsActor* physicsActor = nullptr; - Task* trooperTask = nullptr; - if (write) - { - trooper = (PhaseThree*)logic; - physicsActor = &trooper->actor; - } - else - { - trooper = (PhaseThree*)level_alloc(sizeof(PhaseThree)); - memset(trooper, 0, sizeof(PhaseThree)); - physicsActor = &trooper->actor; - logic = (Logic*)trooper; - - // Task - char name[32]; - sprintf(name, "PhaseThree%d", s_shared.trooperNum); - s_shared.trooperNum++; - - trooperTask = createSubTask(name, phaseThreeTaskFunc); - task_setUserData(trooperTask, trooper); - - // Logic - logic->task = trooperTask; - logic->cleanupFunc = phaseThreeCleanupFunc; - logic->type = LOGIC_PHASE_THREE; - logic->obj = obj; - } - actor_serializeMovementModuleBase(stream, &physicsActor->moveMod); - actor_serializeLogicAnim(stream, &physicsActor->anim); - if (!write) - { - // Clear out functions, the mousebot handles all of this internally. - physicsActor->moveMod.header.obj = obj; - physicsActor->moveMod.header.func = nullptr; - physicsActor->moveMod.header.freeFunc = nullptr; - physicsActor->moveMod.header.attribFunc = nullptr; - physicsActor->moveMod.header.msgFunc = nullptr; - physicsActor->moveMod.header.type = ACTMOD_MOVE; - physicsActor->moveMod.updateTargetFunc = nullptr; - - actor_addPhysicsActorToWorld(physicsActor); - - physicsActor->moveMod.header.obj = obj; - physicsActor->moveMod.physics.obj = obj; - physicsActor->actorTask = trooperTask; - - trooper->hitSndId = NULL_SOUND; - trooper->rocketSndId = NULL_SOUND; - } - SERIALIZE(SaveVersionInit, physicsActor->vel, { 0 }); - SERIALIZE(SaveVersionInit, physicsActor->lastPlayerPos, { 0 }); - SERIALIZE(SaveVersionInit, physicsActor->alive, JTRUE); - SERIALIZE(SaveVersionInit, physicsActor->hp, FIXED(750)); - SERIALIZE(SaveVersionInit, physicsActor->state, 0); - - SERIALIZE(SaveVersionInit, trooper->noDeath, JFALSE); - } - - Logic* phaseThree_setup(SecObject* obj, LogicSetupFunc* setupFunc) - { - PhaseThree* trooper = (PhaseThree*)level_alloc(sizeof(PhaseThree)); - memset(trooper, 0, sizeof(PhaseThree)); - - PhysicsActor* physicsActor = &trooper->actor; - - // Give the name of the task a number so I can tell them apart when debugging. - char name[32]; - sprintf(name, "PhaseThree%d", s_shared.trooperNum); - s_shared.trooperNum++; - Task* task = createSubTask(name, phaseThreeTaskFunc); - task_setUserData(task, trooper); - - obj->entityFlags = ETFLAG_AI_ACTOR | ETFLAG_GENERAL_MOHC; - - physicsActor->alive = JTRUE; - physicsActor->hp = FIXED(750); - physicsActor->state = 0; - physicsActor->actorTask = task; - trooper->hitSndId = 0; - trooper->rocketSndId = 0; - trooper->noDeath = JFALSE; - trooper->logic.obj = obj; - actor_addPhysicsActorToWorld(physicsActor); - - physicsActor->moveMod.header.obj = obj; - physicsActor->moveMod.physics.obj = obj; - actor_setupSmartObj(&physicsActor->moveMod); - - physicsActor->moveMod.collisionFlags |= 7; - physicsActor->moveMod.physics.yPos = COL_INFINITY; - - ActorTarget* target = &physicsActor->moveMod.target; - target->flags &= ~TARGET_ALL; - target->speed = FIXED(25); - target->speedVert = FIXED(10); - target->speedRotation = 0x3000; - - LogicAnimation* anim = &physicsActor->anim; - anim->frameRate = 5; - anim->frameCount = ONE_16; - anim->prevTick = 0; - anim->flags |= AFLAG_READY; - anim->flags &= ~AFLAG_PLAYED; - - actor_setupBossAnimation(obj, 3, anim); - obj_addLogic(obj, (Logic*)trooper, LOGIC_PHASE_THREE, task, phaseThreeCleanupFunc); - - if (setupFunc) - { - *setupFunc = nullptr; - } - return (Logic*)trooper; - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/phaseThree.h b/components/darkforces/tfe/TFE_DarkForces/Actor/phaseThree.h deleted file mode 100644 index 5c68a881..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/phaseThree.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Handles the Phase Two Dark Trooper AI. -////////////////////////////////////////////////////////////////////// -#include -#include -#include "actor.h" - -namespace TFE_DarkForces -{ - void phaseThree_exit(); - void phaseThree_precache(); - Logic* phaseThree_setup(SecObject* obj, LogicSetupFunc* setupFunc); - void phaseThree_serialize(Logic*& logic, SecObject* obj, Stream* stream); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/phaseTwo.cpp b/components/darkforces/tfe/TFE_DarkForces/Actor/phaseTwo.cpp deleted file mode 100644 index 43b64ffa..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/phaseTwo.cpp +++ /dev/null @@ -1,1116 +0,0 @@ -#include - -#include "phaseTwo.h" -#include "actorModule.h" -#include "actorSerialization.h" -#include "../logic.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace TFE_DarkForces -{ - enum PhaseTwoStates - { - P2STATE_DEFAULT = 0, - P2STATE_CHARGE, - P2STATE_WANDER, - P2STATE_FIRE_MISSILES, - P2STATE_FIRE_PLASMA, - P2STATE_DYING, - P2STATE_SEARCH, - P2STATE_COUNT - }; - - struct PhaseTwo - { - Logic logic; - PhysicsActor actor; - - SoundEffectId rocketSndId; - SoundEffectId hitSndId; - JBool noDeath; - }; - - struct PhaseThreeShared - { - SoundSourceId phase2aSndID = NULL_SOUND; - SoundSourceId phase2bSndID = NULL_SOUND; - SoundSourceId phase2cSndID = NULL_SOUND; - SoundSourceId phase2RocketSndID = NULL_SOUND; - s32 trooperNum = 0; - }; - static PhaseThreeShared s_shared = {}; - static PhaseTwo* s_curTrooper = nullptr; - - void phaseTwo_exit() - { - s_curTrooper = nullptr; - s_shared = {}; - } - - void phaseTwo_precache() - { - s_shared.phase2aSndID = sound_load("phase2a.voc", SOUND_PRIORITY_MED5); - s_shared.phase2bSndID = sound_load("phase2b.voc", SOUND_PRIORITY_LOW0); - s_shared.phase2RocketSndID = sound_load("rocket-1.voc", SOUND_PRIORITY_HIGH0); - s_shared.phase2cSndID = sound_load("phase2c.voc", SOUND_PRIORITY_HIGH1); - } - - JBool phaseTwo_updatePlayerPos(PhaseTwo* trooper) - { - if (actor_canSeeObject(trooper->logic.obj, s_playerObject)) - { - trooper->actor.lastPlayerPos.x = s_playerObject->posWS.x; - trooper->actor.lastPlayerPos.z = s_playerObject->posWS.z; - return JTRUE; - } - return JFALSE; - } - - void phaseTwo_handleDamage(MessageType msg) - { - struct LocalContext - { - PhaseTwo* trooper; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - LogicAnimation tmp; - vec3_fixed vel; - }; - task_begin_ctx; - - local(trooper) = s_curTrooper; - local(obj) = local(trooper)->logic.obj; - local(physicsActor) = &local(trooper)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - local(trooper)->noDeath = JTRUE; - - if (local(physicsActor)->alive) - { - task_localBlockBegin; - ProjectileLogic* proj = (ProjectileLogic*)s_msgEntity; - local(physicsActor)->hp -= proj->dmg; - task_localBlockEnd; - - if (local(physicsActor)->hp <= 0) - { - local(physicsActor)->state = P2STATE_DYING; - msg = MSG_RUN_TASK; - task_setMessage(msg); - } - else - { - sound_stop(local(trooper)->hitSndId); - local(trooper)->hitSndId = sound_playCued(s_shared.phase2bSndID, local(obj)->posWS); - - if (random(100) <= 10) - { - local(target)->flags |= TARGET_FREEZE; - - // Save Animation - memcpy(&local(tmp), local(anim), sizeof(LogicAnimation) - 4); - - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 12, local(anim)); - - // Wait for animation to finish. - do - { - entity_yield(TASK_NO_DELAY); - } while (msg != MSG_RUN_TASK || !(local(anim)->flags & AFLAG_READY)); - - memcpy(local(anim), &local(tmp), sizeof(LogicAnimation) - 4); - actor_setupBossAnimation(local(obj), local(anim)->animId, local(anim)); - local(target)->flags &= ~TARGET_FREEZE; - } - msg = MSG_DAMAGE; - task_setMessage(msg); - } - } // if (alive) - local(trooper)->noDeath = JFALSE; - task_end; - } - - void phaseTwo_handleExplosion(MessageType msg) - { - struct LocalContext - { - PhaseTwo* trooper; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - LogicAnimation tmp; - vec3_fixed vel; - }; - task_begin_ctx; - - local(trooper) = s_curTrooper; - local(obj) = local(trooper)->logic.obj; - local(physicsActor) = &local(trooper)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - local(trooper)->noDeath = JTRUE; - - if (local(physicsActor)->alive) - { - task_localBlockBegin; - fixed16_16 dmg = s_msgArg1; - fixed16_16 force = s_msgArg2; - - local(physicsActor)->hp -= dmg; - vec3_fixed pos = { local(obj)->posWS.x, local(obj)->posWS.y - local(obj)->worldHeight, local(obj)->posWS.z }; - vec3_fixed pushDir; - - computeExplosionPushDir(&pos, &pushDir); - local(vel) = { mul16(pushDir.x, force), mul16(pushDir.y, force), mul16(pushDir.z, force) }; - task_localBlockEnd; - - if (local(physicsActor)->hp <= 0) - { - local(physicsActor)->state = P2STATE_DYING; - local(physicsActor)->vel = local(vel); - msg = MSG_RUN_TASK; - task_setMessage(msg); - } - else - { - local(vel).x -= (local(vel).x < 0 ? 1 : 0); - local(vel).y -= (local(vel).y < 0 ? 1 : 0); - local(vel).z -= (local(vel).z < 0 ? 1 : 0); - local(physicsActor)->vel = { local(vel).x >> 1, local(vel).y >> 1, local(vel).z >> 1 }; - - sound_stop(local(trooper)->hitSndId); - local(trooper)->hitSndId = sound_playCued(s_shared.phase2bSndID, local(obj)->posWS); - - if (random(100) <= 10) - { - local(target)->flags |= TARGET_FREEZE; - - // Save Animation - memcpy(&local(tmp), local(anim), sizeof(LogicAnimation) - 4); - - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 12, local(anim)); - - // Wait for animation to finish. - do - { - entity_yield(TASK_NO_DELAY); - } while (msg != MSG_RUN_TASK || !(local(anim)->flags & AFLAG_READY)); - - memcpy(local(anim), &local(tmp), sizeof(LogicAnimation) - 4); - actor_setupBossAnimation(local(obj), local(anim)->animId, local(anim)); - local(target)->flags &= ~TARGET_FREEZE; - } - msg = MSG_EXPLOSION; - task_setMessage(msg); - } - } // if (alive) - local(trooper)->noDeath = JFALSE; - task_end; - } - - void phaseTwo_handleMsg(MessageType msg) - { - struct LocalContext - { - PhaseTwo* trooper; - }; - task_begin_ctx; - local(trooper) = s_curTrooper; - - if (msg == MSG_DAMAGE) - { - if (!local(trooper)->noDeath) - { - s_curTrooper = local(trooper); - task_callTaskFunc(phaseTwo_handleDamage); - } - else - { - ProjectileLogic* proj = (ProjectileLogic*)s_msgEntity; - local(trooper)->actor.hp -= proj->dmg; - } - } - else if (msg == MSG_EXPLOSION) - { - if (!local(trooper)->noDeath) - { - s_curTrooper = local(trooper); - task_callTaskFunc(phaseTwo_handleExplosion); - } - else - { - local(trooper)->actor.hp -= s_msgArg1; - } - } - task_end; - } - - void phaseTwo_chargePlayer(MessageType msg) - { - struct LocalContext - { - PhaseTwo* trooper; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - u32 prevColTick; - JBool flying; - }; - task_begin_ctx; - - local(trooper) = s_curTrooper; - local(obj) = local(trooper)->logic.obj; - local(physicsActor) = &local(trooper)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - local(prevColTick) = 0; - local(target)->flags &= ~TARGET_FREEZE; - - if (random(100) <= 40) - { - local(trooper)->rocketSndId = sound_playCued(s_shared.phase2RocketSndID, local(obj)->posWS); - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 13, local(anim)); - actor_setAnimFrameRange(local(anim), 0, 2); - - // Wait for the animation to finish. - do - { - entity_yield(0); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseTwo_handleMsg); - } while (!(local(anim)->flags & AFLAG_READY) || msg != MSG_RUN_TASK); - - actor_setupBossAnimation(local(obj), 13, local(anim)); - actor_setAnimFrameRange(local(anim), 3, 3); - - local(target)->speed = FIXED(60); - local(flying) = JTRUE; - local(physicsActor)->moveMod.collisionFlags &= 0xfffffffc; - local(physicsActor)->moveMod.physics.yPos = COL_INFINITY; - } - else - { - local(physicsActor)->moveMod.collisionFlags |= 3; - local(target)->speed = FIXED(15); - local(flying) = JFALSE; - local(anim)->flags &= ~AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 0, local(anim)); - } - - while (local(physicsActor)->state == P2STATE_CHARGE) - { - do - { - entity_yield(TASK_NO_DELAY); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseTwo_handleMsg); - } while (msg != MSG_RUN_TASK); - - if (random(100) <= 10) - { - if (!s_playerDying && phaseTwo_updatePlayerPos(local(trooper))) - { - if (playerDist(obj) <= FIXED(100) && local(obj)->yaw == local(target)->yaw) - { - local(physicsActor)->state = (random(100) > 40) ? P2STATE_FIRE_PLASMA : P2STATE_FIRE_MISSILES; - if (local(flying)) - { - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 13, local(anim)); - actor_setAnimFrameRange(local(anim), 4, 4); - do - { - entity_yield(0); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseTwo_handleMsg); - } while (msg != MSG_RUN_TASK || !(local(anim)->flags & AFLAG_READY)); - - local(physicsActor)->moveMod.collisionFlags |= 3; - local(physicsActor)->moveMod.physics.yPos = COL_INFINITY; - local(target)->speed = FIXED(15); - local(target)->flags &= ~TARGET_MOVE_Y; - sound_stop(local(trooper)->rocketSndId); - } - } - } - else if (!s_playerDying) - { - sound_stop(local(trooper)->rocketSndId); - local(physicsActor)->state = P2STATE_SEARCH; - } - } - if (local(physicsActor)->state != P2STATE_CHARGE) { break; } - - local(target)->flags &= ~TARGET_FREEZE; - if (actor_handleSteps(&local(physicsActor)->moveMod, local(target))) - { - // Change direction if the Trooper hits a wall or impassable ledge or drop. - actor_changeDirFromCollision(&local(physicsActor)->moveMod, local(target), &local(prevColTick)); - } - else - { - if (!s_playerDying) - { - fixed16_16 dx = s_playerObject->posWS.x - local(obj)->posWS.x; - fixed16_16 dz = s_playerObject->posWS.z - local(obj)->posWS.z; - local(target)->yaw = vec2ToAngle(dx, dz); - } - else - { - local(target)->yaw = random(16338); - } - - local(target)->speedRotation = 0x3000; - local(target)->flags |= TARGET_MOVE_ROT; - - fixed16_16 sinYaw, cosYaw; - sinCosFixed(local(obj)->yaw, &sinYaw, &cosYaw); - local(target)->pos.x = local(obj)->posWS.x + mul16(sinYaw, FIXED(30)); - local(target)->pos.z = local(obj)->posWS.z + mul16(cosYaw, FIXED(30)); - local(target)->flags |= TARGET_MOVE_XZ; - - if (local(flying)) - { - local(target)->pos.y = s_playerObject->posWS.y - FIXED(2); - local(target)->flags |= TARGET_MOVE_Y; - } - } - } - - local(anim)->flags |= AFLAG_READY; - task_end; - } - - void phaseTwo_wander(MessageType msg) - { - struct LocalContext - { - PhaseTwo* trooper; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - JBool odd; - }; - task_begin_ctx; - - local(trooper) = s_curTrooper; - local(obj) = local(trooper)->logic.obj; - local(physicsActor) = &local(trooper)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - local(odd) = (s_curTick & 1) ? JFALSE : JTRUE; - local(anim)->flags &= ~AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 0, local(anim)); - - task_localBlockBegin; - fixed16_16 dx = local(obj)->posWS.x - s_playerObject->posWS.x; - fixed16_16 dz = local(obj)->posWS.z - s_playerObject->posWS.z; - angle14_32 angle = vec2ToAngle(dx, dz) & ANGLE_MASK; - angle14_32 moveAngle = local(odd) ? angle - 2048 : angle + 2048; - - fixed16_16 sinYaw, cosYaw; - sinCosFixed(moveAngle, &sinYaw, &cosYaw); - - local(target)->flags &= ~TARGET_FREEZE; - local(target)->pos.x = s_playerObject->posWS.x + mul16(FIXED(100), sinYaw); - local(target)->pos.z = s_playerObject->posWS.z + mul16(FIXED(100), cosYaw); - local(target)->flags |= TARGET_MOVE_XZ; - - angle14_32 targetAngle = local(odd) ? angle - 4323 : angle + 4323; - local(target)->yaw = targetAngle; - local(target)->speedRotation = 0; - local(target)->flags |= TARGET_MOVE_ROT; - task_localBlockEnd; - - while (local(physicsActor)->state == P2STATE_WANDER) - { - do - { - entity_yield(TASK_NO_DELAY); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseTwo_handleMsg); - } while (msg != MSG_RUN_TASK); - if (local(physicsActor)->state != P2STATE_WANDER) { break; } - - task_localBlockBegin; - CollisionInfo* collisionInfo = &local(physicsActor)->moveMod.physics; - if (collisionInfo->wall || collisionInfo->collidedObj) - { - local(physicsActor)->state = P2STATE_CHARGE; - break; - } - - fixed16_16 dist = distApprox(s_playerObject->posWS.x, s_playerObject->posWS.z, local(obj)->posWS.x, local(obj)->posWS.z); - if (s_playerDying || !phaseTwo_updatePlayerPos(local(trooper)) || dist > FIXED(20)) - { - local(physicsActor)->state = P2STATE_CHARGE; - break; - } - task_localBlockEnd; - - if (actor_arrivedAtTarget(local(target), local(obj))) - { - if (random(100) <= 10) - { - local(physicsActor)->state = (random(100) > 40) ? P2STATE_FIRE_PLASMA : P2STATE_FIRE_MISSILES; - fixed16_16 dx = s_playerObject->posWS.x - local(obj)->posWS.x; - fixed16_16 dz = s_playerObject->posWS.z - local(obj)->posWS.z; - local(target)->yaw = vec2ToAngle(dx, dz); - } - else - { - if (random(100) <= 10) - { - local(odd) = ~local(odd); - } - fixed16_16 dx = local(obj)->posWS.x - s_playerObject->posWS.x; - fixed16_16 dz = local(obj)->posWS.z - s_playerObject->posWS.z; - angle14_32 angle = vec2ToAngle(dx, dz) & ANGLE_MASK; - angle14_32 angleMove = local(odd) ? (angle - 2048) : (angle + 2048); - - fixed16_16 sinYaw, cosYaw; - sinCosFixed(angleMove, &sinYaw, &cosYaw); - - local(target)->flags &= ~TARGET_FREEZE; - local(target)->pos.x = s_playerObject->posWS.x + mul16(FIXED(100), sinYaw); - local(target)->pos.z = s_playerObject->posWS.z + mul16(FIXED(100), cosYaw); - local(target)->flags |= TARGET_MOVE_XZ; - - angle14_32 angleTarget = local(odd) ? (angle - 4096) : (angle + 4096); - local(target)->yaw = angleTarget; - local(target)->speedRotation = 0; - local(target)->flags |= TARGET_MOVE_ROT; - } - } - } - - local(anim)->flags |= AFLAG_READY; - task_end; - } - - void phaseTwo_fireMissiles(MessageType msg) - { - struct LocalContext - { - PhaseTwo* trooper; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - }; - task_begin_ctx; - - local(trooper) = s_curTrooper; - local(obj) = local(trooper)->logic.obj; - local(physicsActor) = &local(trooper)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - - local(target)->flags &= ~TARGET_MOVE_XZ; - local(physicsActor)->moveMod.collisionFlags |= 3; - while (local(physicsActor)->state == P2STATE_FIRE_MISSILES) - { - do - { - entity_yield(TASK_NO_DELAY); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseTwo_handleMsg); - } while (msg != MSG_RUN_TASK); - if (local(physicsActor)->state != P2STATE_FIRE_MISSILES) { break; } - - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 1, local(anim)); - - // Wait for the animation to finish. - do - { - entity_yield(TASK_NO_DELAY); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseTwo_handleMsg); - } while (msg != MSG_RUN_TASK || !(local(anim)->flags&AFLAG_READY)); - - // Attempt to attack. - task_localBlockBegin; - local(obj)->flags |= OBJ_FLAG_FULLBRIGHT; - sound_playCued(s_missile1SndSrc, local(obj)->posWS); - - ProjectileLogic* proj = (ProjectileLogic*)createProjectile(PROJ_MISSILE, local(obj)->sector, local(obj)->posWS.x, local(obj)->posWS.y - FIXED(9), local(obj)->posWS.z, local(obj)); - proj->prevColObj = local(obj); - proj->excludeObj = local(obj); - - fixed16_16 dx = s_playerObject->posWS.x - local(obj)->posWS.x; - fixed16_16 dz = s_playerObject->posWS.z - local(obj)->posWS.z; - SecObject* projObj = proj->logic.obj; - projObj->yaw = vec2ToAngle(dx, dz); - - vec3_fixed target = { s_eyePos.x, s_eyePos.y + ONE_16, s_eyePos.z }; - proj_aimAtTarget(proj, target); - - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 6, local(anim)); - task_localBlockEnd; - - // Wait for the animation to finish. - do - { - entity_yield(TASK_NO_DELAY); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseTwo_handleMsg); - } while (msg != MSG_RUN_TASK || !(local(anim)->flags & AFLAG_READY)); - - local(obj)->flags &= ~OBJ_FLAG_FULLBRIGHT; - local(physicsActor)->state = P2STATE_WANDER; - } - - task_end; - } - - void phaseTwo_firePlasma(MessageType msg) - { - struct LocalContext - { - PhaseTwo* trooper; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - s32 shotCount; - }; - task_begin_ctx; - - local(trooper) = s_curTrooper; - local(obj) = local(trooper)->logic.obj; - local(physicsActor) = &local(trooper)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - - local(target)->flags &= ~TARGET_MOVE_XZ; - local(physicsActor)->moveMod.collisionFlags |= 3; - - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 1, local(anim)); - - // Wait for the animation to finish. - do - { - entity_yield(TASK_NO_DELAY); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseTwo_handleMsg); - } while (msg != MSG_RUN_TASK || !(local(anim)->flags & AFLAG_READY)); - - local(shotCount) = random(20) + 1; - local(obj)->flags |= OBJ_FLAG_FULLBRIGHT; - local(target)->flags |= TARGET_FREEZE; - - while (local(physicsActor)->state == P2STATE_FIRE_PLASMA) - { - do - { - entity_yield(29); // 0.2 seconds - s_curTrooper = local(trooper); - task_callTaskFunc(phaseTwo_handleMsg); - } while (msg != MSG_RUN_TASK); - if (local(physicsActor)->state != P2STATE_FIRE_PLASMA) { break; } - - sound_playCued(s_plasma4SndSrc, local(obj)->posWS); - - ProjectileLogic* proj = (ProjectileLogic*)createProjectile(PROJ_CANNON, local(obj)->sector, local(obj)->posWS.x, local(obj)->posWS.y - FIXED(9), local(obj)->posWS.z, local(obj)); - proj->prevColObj = local(obj); - proj->excludeObj = local(obj); - - SecObject* projObj = proj->logic.obj; - projObj->yaw = local(target)->yaw; - actor_leadTarget(proj); - local(shotCount)--; - if (local(shotCount) == 0) - { - local(physicsActor)->state = P2STATE_WANDER; - } - } - - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 6, local(anim)); - - // Wait for the animation to finish. - do - { - entity_yield(TASK_NO_DELAY); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseTwo_handleMsg); - } while (msg != MSG_RUN_TASK || !(local(anim)->flags & AFLAG_READY)); - - local(obj)->flags &= ~OBJ_FLAG_FULLBRIGHT; - task_end; - } - - void phaseTwo_handleDying(MessageType msg) - { - struct LocalContext - { - PhaseTwo* trooper; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - }; - task_begin_ctx; - - local(trooper) = s_curTrooper; - local(obj) = local(trooper)->logic.obj; - local(physicsActor) = &local(trooper)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - - local(target)->flags |= TARGET_FREEZE; - sound_stop(local(trooper)->rocketSndId); - sound_playCued(s_shared.phase2cSndID, local(obj)->posWS); - - local(anim)->flags |= AFLAG_PLAYED; - actor_setupBossAnimation(local(obj), 2, local(anim)); - local(physicsActor)->moveMod.collisionFlags |= 3; - - // Wait for the animation to finish. - do - { - entity_yield(TASK_NO_DELAY); - } while (msg != MSG_RUN_TASK || !(local(anim)->flags & AFLAG_READY)); - - // Wait until the actor can die. - do - { - entity_yield(TASK_NO_DELAY); - } while (msg != MSG_RUN_TASK || !actor_canDie(local(physicsActor))); - - task_localBlockBegin; - RSector* sector = local(obj)->sector; - if (sector->secHeight - 1 < 0) - { - SecObject* corpse = allocateObject(); - sprite_setData(corpse, local(obj)->wax); - corpse->frame = 0; - corpse->anim = 4; - corpse->posWS = local(obj)->posWS; - corpse->worldWidth = 0; - corpse->worldHeight = 0; - corpse->entityFlags |= (ETFLAG_CORPSE | ETFLAG_KEEP_CORPSE); - sector_addObject(sector, corpse); - - // Create Plasma pickup - SecObject* item = item_create(ITEM_PLASMA); - item->posWS = local(obj)->posWS; - sector_addObject(sector, item); - - // Try to move the object 3 units away in X and Z to help sorting. - CollisionInfo collisionInfo = - { - item, - FIXED(3), 0, FIXED(3), // offset - ONE_16, COL_INFINITY, ONE_16, 0, // botOffset, yPos, height, 0x1c - nullptr, 0, nullptr, // wall, u24, collidedObj - item->worldWidth, 0, 0, // width, u30, responseStep - {0,0}, {0,0}, 0 // responseDir, responsePos, responseAngle. - }; - handleCollision(&collisionInfo); - - RSector* itemSector = item->sector; - item->posWS.y = itemSector->floorHeight; - // If the item is dropped into a liquid, then delete the item. - if (itemSector->secHeight - 1 >= 0) // eax - { - freeObject(item); - } - - // Create Missile pickup - item = item_create(ITEM_MISSILES); - item->posWS = local(obj)->posWS; - sector_addObject(sector, item); - - collisionInfo = - { - item, - 0, FIXED(3), FIXED(3), // offset - ONE_16, COL_INFINITY, ONE_16, 0, // botOffset, yPos, height, 0x1c - nullptr, 0, nullptr, // wall, u24, collidedObj - item->worldWidth, 0, 0, // width, u30, responseStep - {0,0}, {0,0}, 0 // responseDir, responsePos, responseAngle. - }; - handleCollision(&collisionInfo); - - itemSector = item->sector; - item->posWS.y = itemSector->floorHeight; - // If the item is dropped into a liquid, then delete the item. - if (itemSector->secHeight - 1 >= 0) // eax - { - freeObject(item); - } - } - local(physicsActor)->alive = JFALSE; - actor_handleBossDeath(local(physicsActor)); - task_localBlockEnd; - - task_end; - } - - void phaseTwo_lookForPlayer(MessageType msg) - { - struct LocalContext - { - PhaseTwo* trooper; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - JBool updateTargetPos; - JBool forceContinue; - Tick prevColTick; - Tick nextTick; - Tick retargetTick; - Tick delay; - }; - task_begin_ctx; - - local(trooper) = s_curTrooper; - local(obj) = local(trooper)->logic.obj; - local(physicsActor) = &local(trooper)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - - local(updateTargetPos) = JTRUE; - local(prevColTick) = 0; - local(retargetTick) = 0; - local(nextTick) = s_curTick + 4369; - local(delay) = 72; - - local(anim)->flags &= ~AFLAG_PLAYED; - local(forceContinue) = JFALSE; - actor_setupBossAnimation(local(obj), 13, local(anim)); - - local(target)->flags &= ~TARGET_FREEZE; - local(target)->speed = FIXED(30); - local(physicsActor)->moveMod.collisionFlags &= 0xfffffffc; - - while (local(physicsActor)->state == P2STATE_SEARCH || local(forceContinue)) - { - do - { - entity_yield(TASK_NO_DELAY); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseTwo_handleMsg); - } while (msg != MSG_RUN_TASK); - if (s_playerDying) { continue; } - - JBool canSee = actor_canSeeObject(local(obj), s_playerObject); - if (canSee) - { - local(physicsActor)->lastPlayerPos.x = s_playerObject->posWS.x; - local(physicsActor)->lastPlayerPos.z = s_playerObject->posWS.z; - local(physicsActor)->state = P2STATE_CHARGE; - } - - if (local(retargetTick) < s_curTick || actor_arrivedAtTarget(local(target), local(obj))) - { - local(updateTargetPos) = JTRUE; - if (actor_arrivedAtTarget(local(target), local(obj))) - { - local(nextTick) = 0; - } - } - - fixed16_16 targetX; - fixed16_16 targetZ; - if (local(updateTargetPos)) - { - local(updateTargetPos) = JFALSE; - if (local(nextTick) > s_curTick) - { - targetX = local(physicsActor)->lastPlayerPos.x; - targetZ = local(physicsActor)->lastPlayerPos.z; - } - else - { - targetX = s_eyePos.x; - targetZ = s_eyePos.z; - } - fixed16_16 dx = TFE_Jedi::abs(s_playerObject->posWS.x - local(obj)->posWS.x); - fixed16_16 offset = dx >> 2; - angle14_32 angle = vec2ToAngle(local(obj)->posWS.x - targetX, local(obj)->posWS.z - targetZ); - - local(target)->pos.x = targetX; - local(target)->pos.z = targetZ; - actor_offsetTarget(&local(target)->pos.x, &local(target)->pos.z, offset, offset >> 1, angle, 0xfff); - local(target)->flags |= TARGET_MOVE_XZ; - - local(target)->yaw = vec2ToAngle(local(target)->pos.x - local(obj)->posWS.x, local(target)->pos.z - local(obj)->posWS.z); - local(target)->pitch = 0; - local(target)->roll = 0; - local(target)->flags |= TARGET_MOVE_ROT; - - local(retargetTick) = s_curTick + local(delay); - } - - if (actor_handleSteps(&local(physicsActor)->moveMod, local(target))) - { - actor_changeDirFromCollision(&local(physicsActor)->moveMod, local(target), &local(prevColTick)); - local(delay) += 36; - local(forceContinue) = JTRUE; - if (local(delay) > 582) - { - local(delay) = 72; - } - local(retargetTick) = s_curTick + local(delay); - } - else - { - local(forceContinue) = JFALSE; - } - } // while (state == 6 || forceContinue) - - local(anim)->flags |= AFLAG_READY; - task_end; - } - - void phaseTwoTaskFunc(MessageType msg) - { - struct LocalContext - { - PhaseTwo* trooper; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - LogicAnimation* anim; - }; - task_begin_ctx; - - local(trooper) = (PhaseTwo*)task_getUserData(); - local(obj) = local(trooper)->logic.obj; - local(physicsActor) = &local(trooper)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(anim) = &local(physicsActor)->anim; - - while (local(physicsActor)->alive) - { - msg = MSG_RUN_TASK; - task_setMessage(msg); - - if (local(physicsActor)->state == P2STATE_CHARGE) - { - s_curTrooper = local(trooper); - task_callTaskFunc(phaseTwo_chargePlayer); - } - else if (local(physicsActor)->state == P2STATE_WANDER) - { - s_curTrooper = local(trooper); - task_callTaskFunc(phaseTwo_wander); - } - else if (local(physicsActor)->state == P2STATE_FIRE_MISSILES) - { - s_curTrooper = local(trooper); - task_callTaskFunc(phaseTwo_fireMissiles); - } - else if (local(physicsActor)->state == P2STATE_FIRE_PLASMA) - { - s_curTrooper = local(trooper); - task_callTaskFunc(phaseTwo_firePlasma); - } - else if (local(physicsActor)->state == P2STATE_DYING) - { - s_curTrooper = local(trooper); - task_callTaskFunc(phaseTwo_handleDying); - } - else if (local(physicsActor)->state == P2STATE_SEARCH) - { - s_curTrooper = local(trooper); - task_callTaskFunc(phaseTwo_lookForPlayer); - } - else - { - while (local(physicsActor)->state == P2STATE_DEFAULT) - { - do - { - entity_yield(145); - s_curTrooper = local(trooper); - task_callTaskFunc(phaseTwo_handleMsg); - - if (msg == MSG_DAMAGE || msg == MSG_EXPLOSION) - { - local(physicsActor)->state = P2STATE_CHARGE; - task_makeActive(local(physicsActor)->actorTask); - task_yield(TASK_NO_DELAY); - } - } while (msg != MSG_RUN_TASK); - - if (local(physicsActor)->state == 0 && phaseTwo_updatePlayerPos(local(trooper))) - { - sound_playCued(s_shared.phase2aSndID, local(obj)->posWS); - local(physicsActor)->state = P2STATE_CHARGE; - } - } // while (state == P2STATE_DEFAULT) - } - } // while (alive) - - // Dead - while (msg != MSG_RUN_TASK) - { - task_yield(TASK_NO_DELAY); - } - - actor_removePhysicsActorFromWorld(local(physicsActor)); - deleteLogicAndObject(&local(trooper)->logic); - level_free(local(trooper)); - - task_end; - } - - void phaseTwoCleanupFunc(Logic* logic) - { - PhaseTwo* trooper = (PhaseTwo*)logic; - PhysicsActor* physicsActor = &trooper->actor; - - actor_removePhysicsActorFromWorld(physicsActor); - deleteLogicAndObject(&trooper->logic); - level_free(trooper); - task_free(physicsActor->actorTask); - } - - void phaseTwo_serialize(Logic*& logic, SecObject* obj, Stream* stream) - { - PhaseTwo* trooper = nullptr; - bool write = serialization_getMode() == SMODE_WRITE; - PhysicsActor* physicsActor = nullptr; - Task* trooperTask = nullptr; - if (write) - { - trooper = (PhaseTwo*)logic; - physicsActor = &trooper->actor; - } - else - { - trooper = (PhaseTwo*)level_alloc(sizeof(PhaseTwo)); - memset(trooper, 0, sizeof(PhaseTwo)); - physicsActor = &trooper->actor; - logic = (Logic*)trooper; - - // Task - char name[32]; - sprintf(name, "PhaseTwo%d", s_shared.trooperNum); - s_shared.trooperNum++; - - trooperTask = createSubTask(name, phaseTwoTaskFunc); - task_setUserData(trooperTask, trooper); - - // Logic - logic->task = trooperTask; - logic->cleanupFunc = phaseTwoCleanupFunc; - logic->type = LOGIC_PHASE_TWO; - logic->obj = obj; - } - actor_serializeMovementModuleBase(stream, &physicsActor->moveMod); - actor_serializeLogicAnim(stream, &physicsActor->anim); - if (!write) - { - // Clear out functions, the mousebot handles all of this internally. - physicsActor->moveMod.header.obj = obj; - physicsActor->moveMod.header.func = nullptr; - physicsActor->moveMod.header.freeFunc = nullptr; - physicsActor->moveMod.header.attribFunc = nullptr; - physicsActor->moveMod.header.msgFunc = nullptr; - physicsActor->moveMod.header.type = ACTMOD_MOVE; - physicsActor->moveMod.updateTargetFunc = nullptr; - - actor_addPhysicsActorToWorld(physicsActor); - - physicsActor->moveMod.header.obj = obj; - physicsActor->moveMod.physics.obj = obj; - physicsActor->actorTask = trooperTask; - - trooper->hitSndId = NULL_SOUND; - trooper->rocketSndId = NULL_SOUND; - } - SERIALIZE(SaveVersionInit, physicsActor->vel, { 0 }); - SERIALIZE(SaveVersionInit, physicsActor->lastPlayerPos, { 0 }); - SERIALIZE(SaveVersionInit, physicsActor->alive, JTRUE); - SERIALIZE(SaveVersionInit, physicsActor->hp, FIXED(350)); - SERIALIZE(SaveVersionInit, physicsActor->state, 0); - - SERIALIZE(SaveVersionInit, trooper->noDeath, JFALSE); - } - - Logic* phaseTwo_setup(SecObject* obj, LogicSetupFunc* setupFunc) - { - PhaseTwo* trooper = (PhaseTwo*)level_alloc(sizeof(PhaseTwo)); - memset(trooper, 0, sizeof(PhaseTwo)); - - PhysicsActor* physicsActor = &trooper->actor; - - // Give the name of the task a number so I can tell them apart when debugging. - char name[32]; - sprintf(name, "PhaseTwo%d", s_shared.trooperNum); - s_shared.trooperNum++; - Task* task = createSubTask(name, phaseTwoTaskFunc); - task_setUserData(task, trooper); - - obj->entityFlags = ETFLAG_AI_ACTOR; - - physicsActor->alive = JTRUE; - physicsActor->hp = FIXED(350); - physicsActor->state = 0; - physicsActor->actorTask = task; - trooper->hitSndId = 0; - trooper->rocketSndId = 0; - trooper->noDeath = JFALSE; - trooper->logic.obj = obj; - actor_addPhysicsActorToWorld(physicsActor); - - physicsActor->moveMod.header.obj = obj; - physicsActor->moveMod.physics.obj = obj; - actor_setupSmartObj(&physicsActor->moveMod); - - physicsActor->moveMod.collisionFlags |= 7; - physicsActor->moveMod.physics.yPos = COL_INFINITY; - - ActorTarget* target = &physicsActor->moveMod.target; - target->flags &= 0xfffffff0; - target->speed = FIXED(15); - target->speedVert = FIXED(10); - target->speedRotation = 0x3000; - - LogicAnimation* anim = &physicsActor->anim; - anim->frameRate = 5; - anim->frameCount = ONE_16; - anim->prevTick = 0; - anim->flags |= AFLAG_READY; - anim->flags &= (~AFLAG_PLAYED); - - actor_setupBossAnimation(obj, 5, anim); - obj_addLogic(obj, (Logic*)trooper, LOGIC_PHASE_TWO, task, phaseTwoCleanupFunc); - - if (setupFunc) - { - *setupFunc = nullptr; - } - return (Logic*)trooper; - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/phaseTwo.h b/components/darkforces/tfe/TFE_DarkForces/Actor/phaseTwo.h deleted file mode 100644 index 2f77b083..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/phaseTwo.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Handles the Phase Two Dark Trooper AI. -////////////////////////////////////////////////////////////////////// -#include -#include -#include "actor.h" - -namespace TFE_DarkForces -{ - void phaseTwo_exit(); - void phaseTwo_precache(); - Logic* phaseTwo_setup(SecObject* obj, LogicSetupFunc* setupFunc); - void phaseTwo_serialize(Logic*& logic, SecObject* obj, Stream* stream); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/scenery.cpp b/components/darkforces/tfe/TFE_DarkForces/Actor/scenery.cpp deleted file mode 100644 index 73791220..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/scenery.cpp +++ /dev/null @@ -1,109 +0,0 @@ -#include "scenery.h" -#include "../logic.h" -#include "actorModule.h" -#include "animTables.h" -#include -#include -#include -#include -#include -#include - -namespace TFE_DarkForces -{ - // Actor function for exploders (i.e. landmines and exploding barrels). - JBool sceneryLogicFunc(ActorModule* module, MovementModule* moveMod) - { - DamageModule* damageMod = (DamageModule*)module; - LogicAnimation* anim = &damageMod->attackMod.anim; - SecObject* obj = damageMod->attackMod.header.obj; - - if (!(anim->flags & AFLAG_READY)) - { - s_actorState.curAnimation = anim; - return JFALSE; - } - else if (damageMod->hp <= 0 && actor_getAnimationIndex(4) != -1) - { - SecObject* newObj = allocateObject(); - sprite_setData(newObj, obj->wax); - newObj->frame = 0; - newObj->anim = actor_getAnimationIndex(4); - newObj->posWS = obj->posWS; - newObj->worldWidth = obj->worldWidth; - - sector_addObject(obj->sector, newObj); - actor_kill(); - return JFALSE; - } - return JTRUE; - } - - // Actor message function for exploders, this is responsible for processing messages such as - // projectile damage and explosions. For other AI message functions, it would also process - // "wake up" messages, but those messages are ignored for exploders. - JBool sceneryMsgFunc(s32 msg, ActorModule* module, MovementModule* moveMod) - { - JBool retValue = JFALSE; - DamageModule* damageMod = (DamageModule*)module; - LogicAnimation* anim = &damageMod->attackMod.anim; - SecObject* obj = damageMod->attackMod.header.obj; - - if (msg == MSG_DAMAGE) - { - if (damageMod->hp > 0) - { - ProjectileLogic* proj = (ProjectileLogic*)s_msgEntity; - damageMod->hp -= proj->dmg; - JBool retValue; - if (damageMod->hp > 0) - { - retValue = JTRUE; - } - else - { - actor_setupAnimation(4, anim); - actor_removeLogics(obj); - retValue = JFALSE; - } - } - } - else if (msg == MSG_EXPLOSION) - { - if (damageMod->hp <= 0) - { - return JTRUE; - } - - fixed16_16 dmg = s_msgArg1; - damageMod->hp -= dmg; - if (damageMod->hp > 0) - { - retValue = JTRUE; - } - else - { - actor_setupAnimation(4, anim); - actor_removeLogics(obj); - retValue = JFALSE; - } - } - return retValue; - } - - Logic* scenery_setup(SecObject* obj, LogicSetupFunc* setupFunc) - { - ActorDispatch* dispatch = actor_createDispatch(obj, setupFunc); - dispatch->flags &= ~(FLAG_BIT(0) | FLAG_BIT(2)); - dispatch->animTable = s_sceneryAnimTable; - - DamageModule* module = actor_createDamageModule(dispatch); - module->attackMod.header.func = sceneryLogicFunc; - module->attackMod.header.msgFunc = sceneryMsgFunc; - module->attackMod.anim.flags |= AFLAG_READY; - module->hp = FIXED(1); - actor_addModule(dispatch, (ActorModule*)module); - - return (Logic*)dispatch; - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/scenery.h b/components/darkforces/tfe/TFE_DarkForces/Actor/scenery.h deleted file mode 100644 index 0097920a..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/scenery.h +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Handles destroyable scenery. -////////////////////////////////////////////////////////////////////// -#include -#include -#include "actor.h" - -namespace TFE_DarkForces -{ - Logic* scenery_setup(SecObject* obj, LogicSetupFunc* setupFunc); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/sewer.cpp b/components/darkforces/tfe/TFE_DarkForces/Actor/sewer.cpp deleted file mode 100644 index 37a4af6a..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/sewer.cpp +++ /dev/null @@ -1,313 +0,0 @@ -#include "sewer.h" -#include "actorModule.h" -#include "animTables.h" -#include "../logic.h" -#include "../gameMusic.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace TFE_DarkForces -{ - u32 sewerCreatureDie(DamageModule* module, MovementModule* moveMod); - - JBool sewerCreatureAiFunc(ActorModule* module, MovementModule* moveMod) - { - DamageModule* damageMod = (DamageModule*)module; - AttackModule* attackMod = &damageMod->attackMod; - SecObject* obj = attackMod->header.obj; - RSector* sector = obj->sector; - LogicAnimation* anim = &attackMod->anim; - - if (!(anim->flags & AFLAG_READY)) - { - if (obj->type == OBJ_TYPE_SPRITE) - { - actor_setCurAnimation(&attackMod->anim); - } - moveMod->updateTargetFunc(moveMod, &attackMod->target); - return 0; - } - else if (damageMod->hp > 0) - { - return 0xffffffff; - } - - // Creature die. - s32 animIndex = actor_getAnimationIndex(4); - if (animIndex != -1) - { - SecObject* corpse = allocateObject(); - sprite_setData(corpse, obj->wax); - corpse->frame = 0; - corpse->anim = animIndex; - corpse->posWS.x = obj->posWS.x; - corpse->posWS.z = obj->posWS.z; - corpse->posWS.y = sector->floorHeight; - corpse->entityFlags |= ETFLAG_CORPSE; - corpse->worldWidth = 0; - sector_addObject(sector, corpse); - } - actor_kill(); - return 0; - } - - JBool sewerCreatureAiMsgFunc(s32 msg, ActorModule* module, MovementModule* moveMod) - { - DamageModule* damageMod = (DamageModule*)module; - AttackModule* attackMod = &damageMod->attackMod; - SecObject* obj = attackMod->header.obj; - RSector* sector = obj->sector; - LogicAnimation* anim = &attackMod->anim; - - if (msg == MSG_DAMAGE) - { - if (damageMod->hp <= 0) - { - if (obj->type == OBJ_TYPE_SPRITE) - { - actor_setCurAnimation(&attackMod->anim); - } - moveMod->updateTargetFunc(moveMod, &attackMod->target); - return 0; - } - - ProjectileLogic* proj = (ProjectileLogic*)s_msgEntity; - damageMod->hp -= proj->dmg; - if (damageMod->hp <= 0) - { - return sewerCreatureDie(damageMod, moveMod); - } - - sound_stop(damageMod->hurtSndID); - damageMod->hurtSndID = sound_playCued(damageMod->hurtSndSrc, obj->posWS); - return 0xffffffff; - } - else if (msg == MSG_EXPLOSION) - { - if (damageMod->hp <= 0) - { - if (obj->type == OBJ_TYPE_SPRITE) - { - actor_setCurAnimation(&attackMod->anim); - } - moveMod->updateTargetFunc(moveMod, &attackMod->target); - return 0; - } - - fixed16_16 dmg = s_msgArg1; - damageMod->hp -= dmg; - if (damageMod->hp > 0) - { - sound_stop(damageMod->hurtSndID); - damageMod->hurtSndID = sound_playCued(damageMod->hurtSndSrc, obj->posWS); - return 0xffffffff; - } - return sewerCreatureDie(damageMod, moveMod); - } - return attackMod->header.nextTick; - } - - JBool sewerCreatureEnemyFunc(ActorModule* module, MovementModule* moveMod) - { - DamageModule* damageMod = (DamageModule*)module; - AttackModule* attackMod = &damageMod->attackMod; - SecObject* obj = attackMod->header.obj; - RSector* sector = obj->sector; - - switch (attackMod->anim.state) - { - case STATE_DELAY: - { - if (attackMod->anim.flags & 2) - { - obj->flags &= ~OBJ_FLAG_NEEDS_TRANSFORM; - obj->worldWidth = 0; - obj->posWS.y = sector->floorHeight + sector->secHeight; - - moveMod->collisionFlags |= 1; - attackMod->target.flags &= ~TARGET_ALL; - attackMod->anim.state = STATE_ANIMATEATTACK; - return s_curTick + random(attackMod->timing.delay); - } - } break; - case STATE_ANIMATEATTACK: - { - gameMusic_sustainFight(); - if (!actor_canSeeObjFromDist(obj, s_playerObject)) - { - actor_updatePlayerVisiblity(JFALSE, 0, 0); - attackMod->anim.flags |= 2; - attackMod->anim.state = STATE_DELAY; - if (s_curTick > attackMod->timing.nextTick) - { - attackMod->timing.delay = attackMod->timing.searchDelay; - actor_setupInitAnimation(); - } - return attackMod->timing.delay; - } - - actor_updatePlayerVisiblity(JTRUE, s_eyePos.x, s_eyePos.z); - moveMod->collisionFlags &= ~1; - - obj->posWS.y = sector->floorHeight; - fixed16_16 dy = TFE_Jedi::abs(obj->posWS.y - s_playerObject->posWS.y); - fixed16_16 dist = dy + distApprox(s_playerObject->posWS.x, s_playerObject->posWS.z, obj->posWS.x, obj->posWS.z); - if (dist <= attackMod->meleeRange) - { - attackMod->anim.state = STATE_FIRE1; - attackMod->timing.delay = attackMod->timing.meleeDelay; - attackMod->target.pos.x = obj->posWS.x; - attackMod->target.pos.z = obj->posWS.z; - attackMod->target.flags |= TARGET_MOVE_XZ; - - fixed16_16 dx = s_eyePos.x - obj->posWS.x; - fixed16_16 dz = s_eyePos.z - obj->posWS.z; - attackMod->target.yaw = vec2ToAngle(dx, dz); - attackMod->target.pitch = obj->pitch; - attackMod->target.roll = obj->roll; - attackMod->target.flags |= TARGET_MOVE_ROT; - } - else - { - attackMod->anim.state = STATE_DELAY; - attackMod->timing.delay = attackMod->timing.searchDelay; - } - - attackMod->timing.nextTick = s_curTick + attackMod->timing.losDelay; - attackMod->target.flags |= TARGET_FREEZE; - obj->worldWidth = FIXED(3); - obj->flags |= OBJ_FLAG_NEEDS_TRANSFORM; - if (obj->type == OBJ_TYPE_SPRITE) - { - if (attackMod->anim.state == 2) // Attack animation - { - actor_setupAnimation(1, &attackMod->anim); - } - else // Look around animation - { - actor_setupAnimation(14, &attackMod->anim); - } - } - } break; - case STATE_FIRE1: - { - if (attackMod->anim.flags & 2) - { - attackMod->anim.state = STATE_ANIMATE1; - sound_playCued(attackMod->attackSecSndSrc, obj->posWS); - - fixed16_16 dy = TFE_Jedi::abs(obj->posWS.y - s_playerObject->posWS.y); - fixed16_16 dist = dy + distApprox(s_playerObject->posWS.x, s_playerObject->posWS.z, obj->posWS.x, obj->posWS.z); - if (dist <= attackMod->meleeRange) - { - player_applyDamage(attackMod->meleeDmg, 0, JTRUE); - } - } - } break; - case STATE_ANIMATE1: - { - actor_setupAnimation(6, &attackMod->anim); - attackMod->anim.state = STATE_DELAY; - } break; - } - - actor_setCurAnimation(&attackMod->anim); - moveMod->updateTargetFunc(moveMod, &attackMod->target); - return attackMod->timing.delay; - } - - Logic* sewerCreature_setup(SecObject* obj, LogicSetupFunc* setupFunc) - { - obj->flags &= ~OBJ_FLAG_NEEDS_TRANSFORM; - obj->entityFlags = ETFLAG_AI_ACTOR; - - ActorDispatch* dispatch = actor_createDispatch(obj, setupFunc); - dispatch->alertSndSrc = s_alertSndSrc[ALERT_CREATURE]; - dispatch->fov = ANGLE_MAX; - - DamageModule* module = actor_createDamageModule(dispatch); - module->attackMod.header.func = sewerCreatureAiFunc; - module->attackMod.header.msgFunc = sewerCreatureAiMsgFunc; - module->hp = FIXED(36); - module->hurtSndSrc = s_agentSndSrc[AGENTSND_CREATURE_HURT]; - module->dieSndSrc = s_agentSndSrc[AGENTSND_CREATURE_DIE]; - actor_addModule(dispatch, (ActorModule*)module); - - AttackModule* attackMod = actor_createAttackModule(dispatch); - s_actorState.attackMod = attackMod; - attackMod->header.func = sewerCreatureEnemyFunc; - attackMod->timing.searchDelay = 1165; - attackMod->timing.meleeDelay = 1165; - attackMod->meleeRange = FIXED(13); - attackMod->meleeDmg = FIXED(20); - attackMod->meleeRate = FIXED(360); - attackMod->attackSecSndSrc = s_agentSndSrc[AGENTSND_CREATURE2]; - FLAGS_CLEAR_SET(attackMod->attackFlags, ATTFLAG_RANGED, ATTFLAG_MELEE); - actor_addModule(dispatch, (ActorModule*)attackMod); - - ThinkerModule* thinkerMod = actor_createThinkerModule(dispatch); - thinkerMod->target.speedRotation = 0x7fff; - thinkerMod->target.speed = FIXED(18); - thinkerMod->delay = 58; - thinkerMod->startDelay = 72; - thinkerMod->anim.flags &= 0xfffffffe; - actor_addModule(dispatch, (ActorModule*)thinkerMod); - - MovementModule* moveMod = actor_createMovementModule(dispatch); - dispatch->moveMod = moveMod; - dispatch->animTable = s_sewerCreatureAnimTable; - obj->entityFlags &= ~ETFLAG_SMART_OBJ; - - moveMod->collisionFlags = (moveMod->collisionFlags | 1) & 0xfffffffd; - moveMod->physics.yPos = 0; - moveMod->physics.botOffset = 0; - moveMod->physics.width = obj->worldWidth; - actor_setupInitAnimation(); - - return (Logic*)dispatch; - } - - u32 sewerCreatureDie(DamageModule* module, MovementModule* moveMod) - { - AttackModule* attackMod = &module->attackMod; - SecObject* obj = attackMod->header.obj; - RSector* sector = obj->sector; - - actor_setDeathCollisionFlags(); - ActorDispatch* logic = (ActorDispatch*)s_actorState.curLogic; - sound_stop(logic->alertSndID); - sound_playCued(module->dieSndSrc, obj->posWS); - attackMod->target.flags |= TARGET_FREEZE; - - if ((obj->anim == 1 || obj->anim == 6) && obj->type == OBJ_TYPE_SPRITE) - { - actor_setupAnimation(2, &attackMod->anim); - } - else if (obj->type == OBJ_TYPE_SPRITE) - { - actor_setupAnimation(3, &attackMod->anim); - } - - obj->posWS.y = sector->floorHeight; - moveMod->collisionFlags &= 0xfffffffd; - - if (obj->type == OBJ_TYPE_SPRITE) - { - actor_setCurAnimation(&attackMod->anim); - } - moveMod->updateTargetFunc(moveMod, &attackMod->target); - return 0; - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/sewer.h b/components/darkforces/tfe/TFE_DarkForces/Actor/sewer.h deleted file mode 100644 index aa005b64..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/sewer.h +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Handles the Sewer Creature AI (Dianoga) -////////////////////////////////////////////////////////////////////// -#include -#include -#include "actor.h" - -namespace TFE_DarkForces -{ - Logic* sewerCreature_setup(SecObject* obj, LogicSetupFunc* setupFunc); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/troopers.cpp b/components/darkforces/tfe/TFE_DarkForces/Actor/troopers.cpp deleted file mode 100644 index dfb399b9..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/troopers.cpp +++ /dev/null @@ -1,162 +0,0 @@ -#include "troopers.h" -#include "actorModule.h" -#include "animTables.h" -#include "../logic.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace TFE_DarkForces -{ - ItemId officer_getItemDropId(KEYWORD logicId) - { - switch (logicId) - { - case KW_I_OFFICER: { return ITEM_ENERGY; } break; - case KW_I_OFFICER1: { return ITEM_CODE1; } break; - case KW_I_OFFICER2: { return ITEM_CODE2; } break; - case KW_I_OFFICER3: { return ITEM_CODE3; } break; - case KW_I_OFFICER4: { return ITEM_CODE4; } break; - case KW_I_OFFICER5: { return ITEM_CODE5; } break; - case KW_I_OFFICER6: { return ITEM_CODE6; } break; - case KW_I_OFFICER7: { return ITEM_CODE7; } break; - case KW_I_OFFICER8: { return ITEM_CODE8; } break; - case KW_I_OFFICER9: { return ITEM_CODE9; } break; - case KW_I_OFFICERR: { return ITEM_RED_KEY; } break; - case KW_I_OFFICERY: { return ITEM_YELLOW_KEY; } break; - case KW_I_OFFICERB: { return ITEM_BLUE_KEY; } break; - } - return ITEM_ENERGY; - } - - Logic* officer_setup(SecObject* obj, LogicSetupFunc* setupFunc, KEYWORD logicId) - { - ActorDispatch* dispatch = actor_createDispatch(obj, setupFunc); - dispatch->flags |= FLAG_BIT(4); // Use Officer alert table. - dispatch->alertSndSrc = 0; - - DamageModule* module = actor_createDamageModule(dispatch); - module->hp = FIXED(9); - module->hurtSndSrc = s_agentSndSrc[AGENTSND_STORM_HURT]; - module->dieSndSrc = s_agentSndSrc[AGENTSND_STORM_DIE]; - module->itemDropId = officer_getItemDropId(logicId); - actor_addModule(dispatch, (ActorModule*)module); - - AttackModule* attackMod = actor_createAttackModule(dispatch); - FLAGS_CLEAR_SET(attackMod->attackFlags, ATTFLAG_MELEE, ATTFLAG_RANGED); - attackMod->projType = PROJ_PISTOL_BOLT; - attackMod->attackPrimSndSrc = s_pistolSndSrc; - - s_actorState.attackMod = attackMod; - actor_addModule(dispatch, (ActorModule*)attackMod); - - ThinkerModule* thinkerMod = actor_createThinkerModule(dispatch); - thinkerMod->target.speedRotation = HALF_16 - 1; - thinkerMod->target.speed = FIXED(7); - thinkerMod->delay = 0; - thinkerMod->anim.flags &= 0xfffffffe; - thinkerMod->startDelay = TICKS(2); - actor_addModule(dispatch, (ActorModule*)thinkerMod); - - MovementModule* moveMod = actor_createMovementModule(dispatch); - dispatch->moveMod = moveMod; - dispatch->animTable = s_officerAnimTable; - s_actorState.curLogic = (Logic*)dispatch; - - moveMod->collisionFlags |= 1; - moveMod->physics.width = obj->worldWidth; - actor_setupInitAnimation(); - - return (Logic*)dispatch; - } - - Logic* trooper_setup(SecObject* obj, LogicSetupFunc* setupFunc) - { - ActorDispatch* dispatch = actor_createDispatch(obj, setupFunc); - dispatch->flags |= FLAG_BIT(5); // Use Stormtrooper alert table. - dispatch->alertSndSrc = 0; - - DamageModule* module = actor_createDamageModule(dispatch); - module->hp = FIXED(18); - module->hurtSndSrc = s_agentSndSrc[AGENTSND_STORM_HURT]; - module->dieSndSrc = s_agentSndSrc[AGENTSND_STORM_DIE]; - module->itemDropId = ITEM_RIFLE; - actor_addModule(dispatch, (ActorModule*)module); - - AttackModule* attackMod = actor_createAttackModule(dispatch); - s_actorState.attackMod = attackMod; - FLAGS_CLEAR_SET(attackMod->attackFlags, ATTFLAG_MELEE, ATTFLAG_RANGED); - attackMod->projType = PROJ_RIFLE_BOLT; - attackMod->attackPrimSndSrc = s_rifleSndSrc; - actor_addModule(dispatch, (ActorModule*)attackMod); - - ThinkerModule* thinkerMod = actor_createThinkerModule(dispatch); - thinkerMod->target.speedRotation = HALF_16 - 1; - thinkerMod->target.speed = FIXED(8); - thinkerMod->delay = 116; - thinkerMod->anim.flags &= 0xfffffffe; - thinkerMod->startDelay = TICKS(2); - actor_addModule(dispatch, (ActorModule*)thinkerMod); - - MovementModule* moveMod = actor_createMovementModule(dispatch); - dispatch->moveMod = moveMod; - dispatch->animTable = s_troopAnimTable; - s_actorState.curLogic = (Logic*)dispatch; - - moveMod->collisionFlags |= 1; - moveMod->physics.width = obj->worldWidth; - actor_setupInitAnimation(); - - return (Logic*)dispatch; - } - - Logic* commando_setup(SecObject* obj, LogicSetupFunc* setupFunc) - { - ActorDispatch* dispatch = actor_createDispatch(obj, setupFunc); - dispatch->flags |= FLAG_BIT(5); // Use Stormtrooper alert table. - dispatch->alertSndSrc = 0; - - DamageModule* module = actor_createDamageModule(dispatch); - module->hp = FIXED(27); - module->hurtSndSrc = s_agentSndSrc[AGENTSND_STORM_HURT]; - module->dieSndSrc = s_agentSndSrc[AGENTSND_STORM_DIE]; - module->itemDropId = ITEM_RIFLE; - actor_addModule(dispatch, (ActorModule*)module); - - AttackModule* attackMod = actor_createAttackModule(dispatch); - s_actorState.attackMod = attackMod; - FLAGS_CLEAR_SET(attackMod->attackFlags, ATTFLAG_MELEE, ATTFLAG_RANGED); - attackMod->projType = PROJ_RIFLE_BOLT; - attackMod->attackPrimSndSrc = s_rifleSndSrc; - actor_addModule(dispatch, (ActorModule*)attackMod); - - ThinkerModule* thinkerMod = actor_createThinkerModule(dispatch); - thinkerMod->target.speedRotation = HALF_16 - 1; - thinkerMod->target.speed = FIXED(9); - thinkerMod->delay = 116; - thinkerMod->anim.flags &= 0xfffffffe; - thinkerMod->startDelay = TICKS(1); - actor_addModule(dispatch, (ActorModule*)thinkerMod); - - MovementModule* moveMod = actor_createMovementModule(dispatch); - dispatch->moveMod = moveMod; - dispatch->animTable = s_commandoAnimTable; - s_actorState.curLogic = (Logic*)dispatch; - - moveMod->collisionFlags |= 1; - moveMod->physics.width = obj->worldWidth; - actor_setupInitAnimation(); - - return (Logic*)dispatch; - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/troopers.h b/components/darkforces/tfe/TFE_DarkForces/Actor/troopers.h deleted file mode 100644 index 6ce0703b..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/troopers.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Handles "trooper" enemies - Officers, Commandos, and Storm Troopers -////////////////////////////////////////////////////////////////////// -#include -#include -#include "actor.h" - -namespace TFE_DarkForces -{ - Logic* officer_setup(SecObject* obj, LogicSetupFunc* setupFunc, KEYWORD logicId); - Logic* trooper_setup(SecObject* obj, LogicSetupFunc* setupFunc); - Logic* commando_setup(SecObject* obj, LogicSetupFunc* setupFunc); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/turret.cpp b/components/darkforces/tfe/TFE_DarkForces/Actor/turret.cpp deleted file mode 100644 index 3a43919c..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/turret.cpp +++ /dev/null @@ -1,622 +0,0 @@ -#include - -#include "turret.h" -#include "actorModule.h" -#include "actorSerialization.h" -#include "../logic.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace TFE_DarkForces -{ - enum TurretState - { - TURRETSTATE_DEFAULT = 0, - TURRETSTATE_FIRING = 1, - TURRETSTATE_ATTACKING = 2, - TURRETSTATE_AIMING = 3, - TURRETSTATE_OUT_OF_CONTROL = 4, - TURRETSTATE_DYING = 5, - TURRETSTATE_COUNT - }; - - enum TurretConstants - { - TURRET_HP = FIXED(60), // Starting HP. - TURRET_WIDTH = FIXED(3), - TURRET_HEIGHT =-FIXED(2), - //TURRET_FIRE_Z_OFFSET = 19660, // ~0.3 - TURRET_FIRE_Z_OFFSET = 98300, // ~1.5 -- TODO: This seems to be required for mods like Dark Tide 4, but I'm not sure why. - TURRET_FIRE_ZMAX_OFFSET = 294900, // ~1.5 * 3 - TURRET_YAW_TOLERANCE = 3185, // How close the turret aim has to be in order to fire. - TURRET_PITCH_RANGE = 1820, // How much pitch can deviate from the current value when aiming (+/- 40 degrees) - TURRET_MAX_DIST = FIXED(140), // Maximum distance that the turret will shoot the player. - TURRET_MIN_DIST = FIXED(70), // Minimum distance where the turret no longer cares about the relative angle when spotting the player. - TURRET_ATTACK_DELAY = 72, // 0.5 seconds - the minimum delay from entering the attacking state and transitioning to the firing state. - TURRET_ATTACK_TRANS = 436, // ~3 seconds - the delay from the attacking state to the aiming state, since the last sight of the player. - TURRET_ACCURACY_RAND = FIXED(10), // These determine how accurate the turret is. The higher the value, the more the bolt velocities are randomized. - TURRET_ACCURACY_OFFSET = FIXED(5), // These is generally TURRET_ACCURACY_RAND/2 - TURRET_ROTATION_SPD = 7736, // ~170 degrees per second. - TURRET_OUT_OF_CONTROL_ROTATE_SPD = 12288, // ~270 degrees per second - the rotation speed when the turret is out of control. - - TURRET_OVERLAP_MIN = FIXED(5), - }; - - struct TurretResources - { - SoundSourceId sound1 = NULL_SOUND; - }; - struct Turret - { - Logic logic; - PhysicsActor actor; - - angle14_16 pitch; - angle14_16 yaw; - Tick nextTick; - }; - - static TurretResources s_turretRes = {}; - static Turret* s_curTurret; - static s32 s_turretNum = 0; - - void turret_exit() - { - s_turretRes = {}; - } - - void turret_precache() - { - s_turretRes.sound1 = sound_load("TURRET-1.VOC", SOUND_PRIORITY_MED2); - } - - MessageType turret_handleDamage(MessageType msg, Turret* turret) - { - PhysicsActor* physicsActor = &turret->actor; - if (physicsActor->alive) - { - ProjectileLogic* proj = (ProjectileLogic*)s_msgEntity; - physicsActor->hp -= proj->dmg; - if (physicsActor->hp <= 0) - { - physicsActor->state = TURRETSTATE_DYING; - msg = MSG_RUN_TASK; - } - else if (physicsActor->hp < FIXED(8)) - { - physicsActor->state = TURRETSTATE_OUT_OF_CONTROL; - msg = MSG_RUN_TASK; - } - else - { - msg = MSG_DAMAGE; - } - } - return msg; - } - - MessageType turret_handleExplosion(MessageType msg, Turret* turret) - { - PhysicsActor* physicsActor = &turret->actor; - if (physicsActor->alive) - { - fixed16_16 dmg = s_msgArg1; - physicsActor->hp -= dmg; - if (physicsActor->hp <= 0) - { - physicsActor->state = TURRETSTATE_DYING; - msg = MSG_RUN_TASK; - } - else if (physicsActor->hp < FIXED(8)) - { - physicsActor->state = TURRETSTATE_OUT_OF_CONTROL; - msg = MSG_RUN_TASK; - } - else - { - msg = MSG_EXPLOSION; - } - } - return msg; - } - - void turret_handleAttackingState(MessageType msg) - { - struct LocalContext - { - Turret* turret; - PhysicsActor* physicsActor; - ActorTarget* target; - SecObject* obj; - }; - task_begin_ctx; - task_localBlockBegin; - - local(turret) = s_curTurret; - local(physicsActor) = &local(turret)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(obj) = local(physicsActor)->moveMod.header.obj; - fixed16_16 dz = s_playerObject->posWS.z - local(obj)->posWS.z; - fixed16_16 dx = s_playerObject->posWS.x - local(obj)->posWS.x; - local(target)->yaw = vec2ToAngle(dx, dz) & ANGLE_MASK; - - fixed16_16 dist = distApprox(local(obj)->posWS.x, local(obj)->posWS.z, s_playerObject->posWS.x, s_playerObject->posWS.z); - angle14_32 aimPitch = vec2ToAngle(local(obj)->posWS.y - (s_eyePos.y + ONE_16), dist); - angle14_32 pitchDiff = TFE_Jedi::clamp(getAngleDifference(local(turret)->pitch, aimPitch), -TURRET_PITCH_RANGE, TURRET_PITCH_RANGE); - local(target)->pitch = (local(turret)->pitch + pitchDiff) & ANGLE_MASK; - local(target)->flags = (local(target)->flags | TARGET_MOVE_ROT) & (~TARGET_MOVE_XZ); - - task_localBlockEnd; - local(turret)->nextTick = s_curTick + TURRET_ATTACK_TRANS; - while (local(physicsActor)->state == TURRETSTATE_ATTACKING) - { - do - { - entity_yield(TURRET_ATTACK_DELAY); - if (msg == MSG_DAMAGE) - { - msg = turret_handleDamage(msg, local(turret)); - } - else if (msg == MSG_EXPLOSION) - { - msg = turret_handleExplosion(msg, local(turret)); - } - } while (msg != MSG_RUN_TASK); - - if (local(physicsActor)->state == TURRETSTATE_ATTACKING && local(target)->yaw == local(obj)->yaw && local(target)->pitch == local(obj)->pitch) - { - if (!s_playerDying && actor_isObjectVisible(local(obj), s_playerObject, ANGLE_MAX, TURRET_MIN_DIST)) - { - fixed16_16 dy = TFE_Jedi::abs(local(obj)->posWS.y - s_playerObject->posWS.y); - fixed16_16 dist = dy + distApprox(s_playerObject->posWS.x, s_playerObject->posWS.z, local(obj)->posWS.x, local(obj)->posWS.z); - if (dist > TURRET_MAX_DIST) - { - continue; - } - - fixed16_16 dz = s_playerObject->posWS.z - local(obj)->posWS.z; - fixed16_16 dx = s_playerObject->posWS.x - local(obj)->posWS.x; - angle14_32 yaw = vec2ToAngle(dx, dz); - angle14_32 yawDiff = getAngleDifference(local(obj)->yaw, yaw) & ANGLE_MASK; - if (yawDiff < TURRET_YAW_TOLERANCE) - { - local(turret)->actor.state = TURRETSTATE_FIRING; - continue; - } - - local(target)->yaw = yaw & ANGLE_MASK; - dist = distApprox(local(obj)->posWS.x, local(obj)->posWS.z, s_playerObject->posWS.x, s_playerObject->posWS.z); - angle14_32 pitch = vec2ToAngle(local(obj)->posWS.y - (s_eyePos.y + ONE_16), dist); - angle14_32 pitchDiff = clamp(getAngleDifference(local(turret)->pitch, pitch), -TURRET_PITCH_RANGE, TURRET_PITCH_RANGE); - local(target)->pitch = (local(turret)->pitch + pitchDiff) & ANGLE_MASK; - local(target)->flags = (local(target)->flags | TARGET_MOVE_ROT) & (~TARGET_MOVE_XZ); - local(turret)->nextTick = s_curTick + TURRET_ATTACK_TRANS; - } - else if (s_curTick >= local(turret)->nextTick) - { - local(turret)->actor.state = TURRETSTATE_AIMING; - } - } - } - task_end; - } - - fixed16_16 turret_getZOffset(SecObject* srcObj) - { - RSector* sector = srcObj->sector; - for (s32 i = 0, objIdx = 0; i < sector->objectCapacity && objIdx < sector->objectCount; i++) - { - SecObject* obj = sector->objectList[i]; - if (obj) - { - const JBool isOverlapping3D = obj->type == OBJ_TYPE_3D && obj->worldWidth > TURRET_OVERLAP_MIN && !obj->projectileLogic; - if (obj != srcObj && isOverlapping3D) - { - // Hack to make AT-ST turrets work in the Dark Tide mods. - // TODO: DOS shouldn't work in this case, figure out why it does (probably related to low framerate and cycles setting). - const fixed16_16 dx = obj->posWS.x - srcObj->posWS.x; - const fixed16_16 dz = obj->posWS.z - srcObj->posWS.z; - if (dx < ONE_16 && dz < ONE_16) - { - return TURRET_FIRE_ZMAX_OFFSET; - } - } - objIdx++; - } - } - return TURRET_FIRE_Z_OFFSET; - } - - void turrent_handleFiringState(MessageType msg) - { - Turret* turret = s_curTurret; - PhysicsActor* physicsActor = &turret->actor; - SecObject* obj = physicsActor->moveMod.header.obj; - - fixed16_16 mtx[9]; - weapon_computeMatrix(mtx, -obj->pitch, -obj->yaw); - - RSector* sector = obj->sector; - vec3_fixed inVec = { 0, 0, turret_getZOffset(obj) }; - vec3_fixed outVec; - rotateVectorM3x3(&inVec, &outVec, mtx); - - vec3_fixed pos = { obj->posWS.x + outVec.x, obj->posWS.y + outVec.y, obj->posWS.z + outVec.z }; - ProjectileLogic* proj = (ProjectileLogic*)createProjectile(PROJ_TURRET_BOLT, sector, pos.x, pos.y, pos.z, obj); - sound_playCued(s_turretRes.sound1, pos); - - proj->prevColObj = obj; - proj->prevObj = obj; - proj->excludeObj = obj; - - SecObject* projObj = proj->logic.obj; - projObj->pitch = obj->pitch; - projObj->yaw = obj->yaw; - - vec3_fixed targetPos = { s_eyePos.x, s_eyePos.y + ONE_16, s_eyePos.z }; - proj_aimAtTarget(proj, targetPos); - - proj->vel.x += random(TURRET_ACCURACY_RAND) - TURRET_ACCURACY_OFFSET; - proj->vel.y += random(TURRET_ACCURACY_RAND) - TURRET_ACCURACY_OFFSET; - proj->vel.z += random(TURRET_ACCURACY_RAND) - TURRET_ACCURACY_OFFSET; - - physicsActor->state = TURRETSTATE_ATTACKING; - } - - void turret_handleHighlyDamagedState(MessageType msg) - { - struct LocalContext - { - Turret* turret; - PhysicsActor* physicsActor; - ActorTarget* target; - SecObject* obj; - }; - task_begin_ctx; - - local(turret) = s_curTurret; - local(physicsActor) = &local(turret)->actor; - local(obj) = local(turret)->logic.obj; - while (local(physicsActor)->state == TURRETSTATE_OUT_OF_CONTROL) - { - do - { - entity_yield(TASK_NO_DELAY); - if (msg == MSG_DAMAGE) - { - msg = turret_handleDamage(msg, local(turret)); - } - else if (msg == MSG_EXPLOSION) - { - msg = turret_handleExplosion(msg, local(turret)); - } - } while (msg != MSG_RUN_TASK); - - ActorTarget* target = &local(physicsActor)->moveMod.target; - if (local(physicsActor)->state == TURRETSTATE_OUT_OF_CONTROL && target->yaw == local(obj)->yaw && target->pitch == local(obj)->pitch) - { - fixed16_16 mtx[9]; - weapon_computeMatrix(mtx, -local(obj)->pitch, -local(obj)->yaw); - - vec3_fixed inVec = { 0, 0, TURRET_FIRE_Z_OFFSET }; - vec3_fixed outVec; - rotateVectorM3x3(&inVec, &outVec, mtx); - - vec3_fixed pos = { local(obj)->posWS.x + outVec.x, local(obj)->posWS.y + outVec.y, local(obj)->posWS.z + outVec.z }; - ProjectileLogic* proj = (ProjectileLogic*)createProjectile(PROJ_TURRET_BOLT, local(obj)->sector, pos.x, pos.y, pos.z, local(obj)); - sound_playCued(s_turretRes.sound1, pos); - - proj->prevColObj = local(obj); - proj->excludeObj = local(obj); - proj_setTransform(proj, local(obj)->pitch, local(obj)->yaw); - - // Set a new random target. - target->yaw = random(ANGLE_MAX); - target->pitch = (-random(TURRET_PITCH_RANGE)) & ANGLE_MASK; - target->flags = (target->flags | 4) & 0xfffffffe; - target->speedRotation = TURRET_OUT_OF_CONTROL_ROTATE_SPD; - } - } - task_end; - } - - MessageType turret_handleMessages(MessageType msg, Turret* turret) - { - if (msg == MSG_DAMAGE) - { - msg = turret_handleDamage(msg, turret); - } - else if (msg == MSG_EXPLOSION) - { - msg = turret_handleExplosion(msg, turret); - } - return msg; - } - - void turret_handleDefaultState(MessageType msg) - { - struct LocalContext - { - Turret* turret; - PhysicsActor* physicsActor; - ActorTarget* target; - SecObject* obj; - }; - task_begin_ctx; - - local(turret) = s_curTurret; - local(physicsActor) = &local(turret)->actor; - local(obj) = local(turret)->logic.obj; - - while (local(physicsActor)->state == TURRETSTATE_DEFAULT) - { - do - { - entity_yield(145); - if (msg == MSG_DAMAGE) - { - msg = turret_handleDamage(msg, local(turret)); - } - else if (msg == MSG_EXPLOSION) - { - msg = turret_handleDamage(msg, local(turret)); - } - - if (msg == MSG_DAMAGE || msg == MSG_EXPLOSION) - { - local(physicsActor)->state = TURRETSTATE_ATTACKING; - task_makeActive(local(physicsActor)->actorTask); - task_yield(TASK_NO_DELAY); - } - } while (msg != MSG_RUN_TASK); - - // Check to see if the player is visible and in range to be shot. - // If so, switch to the shooting state. - if (local(physicsActor)->state == TURRETSTATE_DEFAULT && !s_playerDying && actor_isObjectVisible(local(obj), s_playerObject, ANGLE_MAX, TURRET_MIN_DIST)) - { - fixed16_16 dy = TFE_Jedi::abs(local(obj)->posWS.y - s_playerObject->posWS.y); - fixed16_16 dist = dy + distApprox(s_playerObject->posWS.x, s_playerObject->posWS.z, local(obj)->posWS.x, local(obj)->posWS.z); - if (dist <= TURRET_MAX_DIST) - { - local(physicsActor)->state = TURRETSTATE_ATTACKING; - } - } - } - task_end; - } - - void turretLocalMsgFunc(MessageType msg) - { - Turret* turret = (Turret*)task_getUserData(); - - if (msg == MSG_DAMAGE) - { - turret_handleDamage(msg, turret); - } - else if (msg == MSG_EXPLOSION) - { - turret_handleExplosion(msg, turret); - } - } - - void turretTaskFunc(MessageType msg) - { - struct LocalContext - { - Turret* turret; - PhysicsActor* physicsActor; - SecObject* obj; - ActorTarget* target; - }; - task_begin_ctx; - local(turret) = (Turret*)task_getUserData(); - local(physicsActor) = &local(turret)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(obj) = local(turret)->logic.obj; - - while (local(physicsActor)->alive) - { - if (local(physicsActor)->state == TURRETSTATE_FIRING) - { - s_curTurret = local(turret); - turrent_handleFiringState(msg); - } - else if (local(physicsActor)->state == TURRETSTATE_ATTACKING) - { - s_curTurret = local(turret); - task_callTaskFunc(turret_handleAttackingState); - } - else if (local(physicsActor)->state == TURRETSTATE_AIMING) - { - local(target)->yaw = local(turret)->yaw; - local(target)->pitch = local(turret)->pitch; - local(target)->flags = (local(target)->flags | TARGET_MOVE_ROT) & (~TARGET_MOVE_XZ); - - while (local(physicsActor)->state == TURRETSTATE_AIMING) - { - do - { - entity_yield(TASK_NO_DELAY); - msg = turret_handleMessages(msg, local(turret)); - } while (msg != MSG_RUN_TASK); - - // Set to state 0 if the turret has reached its target alignment. - if (local(physicsActor)->state == TURRETSTATE_AIMING && local(target)->yaw == local(obj)->yaw && local(target)->pitch == local(obj)->pitch) - { - local(physicsActor)->state = TURRETSTATE_DEFAULT; - } - } - } - else if (local(physicsActor)->state == TURRETSTATE_OUT_OF_CONTROL) - { - s_curTurret = local(turret); - task_callTaskFunc(turret_handleHighlyDamagedState); - } - else if (local(physicsActor)->state == TURRETSTATE_DYING) - { - spawnHitEffect(HEFFECT_EXP_NO_DMG, local(obj)->sector, local(obj)->posWS, local(obj)); - entity_yield(TASK_NO_DELAY); - local(physicsActor)->alive = JFALSE; - } - else - { - s_curTurret = local(turret); - task_callTaskFunc(turret_handleDefaultState); - } - } - - // The Turret is dead. - while (msg != MSG_RUN_TASK) - { - task_yield(TASK_NO_DELAY); - } - actor_removePhysicsActorFromWorld(local(physicsActor)); - deleteLogicAndObject(&local(turret)->logic); - level_free(local(turret)); - - task_end; - } - - void turretCleanupFunc(Logic* logic) - { - Turret* turret = (Turret*)logic; - - Task* task = turret->actor.actorTask; - actor_removePhysicsActorFromWorld(&turret->actor); - deleteLogicAndObject(&turret->logic); - level_free(turret); - task_free(task); - } - - void turret_serialize(Logic*& logic, SecObject* obj, Stream* stream) - { - Turret* turret = nullptr; - bool write = serialization_getMode() == SMODE_WRITE; - PhysicsActor* physicsActor = nullptr; - Task* turretTask = nullptr; - if (write) - { - turret = (Turret*)logic; - physicsActor = &turret->actor; - } - else - { - turret = (Turret*)level_alloc(sizeof(Turret)); - memset(turret, 0, sizeof(Turret)); - physicsActor = &turret->actor; - logic = (Logic*)turret; - - // Task - char name[32]; - sprintf(name, "turret%d", s_turretNum); - s_turretNum++; - - turretTask = createSubTask(name, turretTaskFunc, turretLocalMsgFunc); - task_setUserData(turretTask, turret); - - // Logic - logic->task = turretTask; - logic->cleanupFunc = turretCleanupFunc; - logic->type = LOGIC_TURRET; - logic->obj = obj; - } - actor_serializeMovementModuleBase(stream, &physicsActor->moveMod); - actor_serializeLogicAnim(stream, &physicsActor->anim); - if (!write) - { - // Clear out functions, the mousebot handles all of this internally. - physicsActor->moveMod.header.obj = obj; - physicsActor->moveMod.header.func = nullptr; - physicsActor->moveMod.header.freeFunc = nullptr; - physicsActor->moveMod.header.attribFunc = nullptr; - physicsActor->moveMod.header.msgFunc = nullptr; - physicsActor->moveMod.header.type = ACTMOD_MOVE; - physicsActor->moveMod.updateTargetFunc = nullptr; - - actor_addPhysicsActorToWorld(physicsActor); - - physicsActor->moveMod.header.obj = obj; - physicsActor->moveMod.physics.obj = obj; - physicsActor->actorTask = turretTask; - } - SERIALIZE(SaveVersionInit, physicsActor->vel, { 0 }); - SERIALIZE(SaveVersionInit, physicsActor->lastPlayerPos, { 0 }); - SERIALIZE(SaveVersionInit, physicsActor->alive, JTRUE); - SERIALIZE(SaveVersionInit, physicsActor->hp, TURRET_HP); - SERIALIZE(SaveVersionInit, physicsActor->state, TURRETSTATE_DEFAULT); - - SERIALIZE(SaveVersionInit, turret->pitch, 0); - SERIALIZE(SaveVersionInit, turret->yaw, 0); - SERIALIZE(SaveVersionInit, turret->nextTick, 0); - } - - Logic* turret_setup(SecObject* obj, LogicSetupFunc* setupFunc) - { - Turret* turret = (Turret*)level_alloc(sizeof(Turret)); - memset(turret, 0, sizeof(Turret)); - - // Give the name of the task a number so I can tell them apart when debugging. - char name[32]; - sprintf(name, "turret%d", s_turretNum); - s_turretNum++; - Task* turretTask = createSubTask(name, turretTaskFunc, turretLocalMsgFunc); - task_setUserData(turretTask, turret); - - obj->entityFlags = ETFLAG_AI_ACTOR; - obj->worldWidth = TURRET_WIDTH; - obj->worldHeight = TURRET_HEIGHT; - - turret->actor.alive = JTRUE; - turret->actor.hp = TURRET_HP; - turret->logic.obj = obj; - turret->actor.state = TURRETSTATE_DEFAULT; - turret->actor.actorTask = turretTask; - turret->yaw = obj->yaw; - turret->pitch = obj->pitch; - - PhysicsActor* physicsActor = &turret->actor; - actor_addPhysicsActorToWorld(physicsActor); - - CollisionInfo* physics = &physicsActor->moveMod.physics; - physics->obj = obj; - physics->width = obj->worldWidth; - physics->height = obj->worldHeight + HALF_16; - physics->wall = nullptr; - physics->u24 = 0; - physics->botOffset = 0; - physics->yPos = 0; - - MovementModule* moveMod = &physicsActor->moveMod; - moveMod->header.obj = obj; - moveMod->delta = { 0, 0, 0 }; - moveMod->collisionFlags &= 0xfffffff8; - - ActorTarget* target = &physicsActor->moveMod.target; - target->speed = 0; - target->flags &= 0xfffffff0; - target->speedRotation = TURRET_ROTATION_SPD; - target->pitch = obj->pitch; - target->yaw = obj->yaw; - target->roll = obj->roll; - obj_addLogic(obj, (Logic*)turret, LOGIC_TURRET, turretTask, turretCleanupFunc); - - if (setupFunc) - { - *setupFunc = nullptr; - } - return (Logic*)turret; - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/turret.h b/components/darkforces/tfe/TFE_DarkForces/Actor/turret.h deleted file mode 100644 index 39b5a251..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/turret.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Handles the Ceiling Turret AI. -////////////////////////////////////////////////////////////////////// -#include -#include -#include "actor.h" - -namespace TFE_DarkForces -{ - void turret_exit(); - void turret_precache(); - Logic* turret_setup(SecObject* obj, LogicSetupFunc* setupFunc); - void turret_serialize(Logic*& logic, SecObject* obj, Stream* stream); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/welder.cpp b/components/darkforces/tfe/TFE_DarkForces/Actor/welder.cpp deleted file mode 100644 index 3c64031a..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/welder.cpp +++ /dev/null @@ -1,556 +0,0 @@ -#include - -#include "welder.h" -#include "actorModule.h" -#include "actorSerialization.h" -#include "../logic.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace TFE_DarkForces -{ - enum WelderState - { - WSTATE_DEFAULT = 0, - WSTATE_ACTIVE = 1, - WSTATE_RESET = 2, - WSTATE_DYING = 3, - WSTATE_COUNT - }; - - struct Welder - { - Logic logic; - PhysicsActor actor; - - SoundEffectId sound2Id; - SoundEffectId hurtSndId; - angle14_16 yaw; - angle14_16 pitch; - }; - - struct WelderShared - { - SoundSourceId weld2SoundSrcId = NULL_SOUND; - SoundSourceId weld1SoundSrcId = NULL_SOUND; - SoundSourceId weldSparkSoundSrcId = NULL_SOUND; - SoundSourceId weldHurtSoundSrcId = NULL_SOUND; - SoundSourceId weldDieSoundSrcId = NULL_SOUND; - s32 welderNum = 0; - }; - - static Wax* s_welderSpark = nullptr; - static Welder* s_curWelder = nullptr; - static WelderShared s_shared = {}; - - void welder_exit() - { - s_shared = {}; - } - - void welder_precache() - { - s_shared.weld2SoundSrcId = sound_load("weld-2.voc", SOUND_PRIORITY_MED5); - s_shared.weld1SoundSrcId = sound_load("weld-1.voc", SOUND_PRIORITY_MED5); - s_shared.weldSparkSoundSrcId = sound_load("weldsht1.voc", SOUND_PRIORITY_LOW0); - s_shared.weldHurtSoundSrcId = sound_load("weldhrt.voc", SOUND_PRIORITY_LOW0); - s_shared.weldDieSoundSrcId = sound_load("weld-die.voc", SOUND_PRIORITY_MED5); - } - - MessageType welder_handleDamage(MessageType msg, Welder* welder) - { - PhysicsActor* physicsActor = &welder->actor; - SecObject* obj = welder->logic.obj; - if (physicsActor->alive) - { - ProjectileLogic* proj = (ProjectileLogic*)s_msgEntity; - physicsActor->hp -= proj->dmg; - if (physicsActor->hp <= 0) - { - physicsActor->state = WSTATE_DYING; - msg = MSG_RUN_TASK; - } - else - { - if (welder->hurtSndId) - { - sound_stop(welder->hurtSndId); - } - welder->hurtSndId = sound_playCued(s_shared.weldHurtSoundSrcId, obj->posWS); - msg = MSG_DAMAGE; - } - } - return msg; - } - - MessageType welder_handleExplosion(MessageType msg, Welder* welder) - { - PhysicsActor* physicsActor = &welder->actor; - SecObject* obj = welder->logic.obj; - if (physicsActor->alive) - { - fixed16_16 dmg = s_msgArg1; - physicsActor->hp -= dmg; - if (physicsActor->hp <= 0) - { - physicsActor->state = WSTATE_DYING; - msg = MSG_RUN_TASK; - } - else - { - if (welder->hurtSndId) - { - sound_stop(welder->hurtSndId); - } - welder->hurtSndId = sound_playCued(s_shared.weldHurtSoundSrcId, obj->posWS); - msg = MSG_EXPLOSION; - } - } - return msg; - } - - void welder_handleDefaultState(MessageType msg) - { - struct LocalContext - { - Welder* welder; - SecObject* obj; - PhysicsActor* physicsActor; - }; - task_begin_ctx; - - local(welder) = s_curWelder; - local(obj) = local(welder)->logic.obj; - local(physicsActor) = &local(welder)->actor; - while (local(physicsActor)->state == WSTATE_DEFAULT) - { - do - { - entity_yield(145); - if (msg == MSG_DAMAGE) - { - msg = welder_handleDamage(msg, local(welder)); - } - else if (msg == MSG_EXPLOSION) - { - msg = welder_handleExplosion(msg, local(welder)); - } - if (msg == MSG_DAMAGE || msg == MSG_EXPLOSION) - { - local(physicsActor)->state = WSTATE_ACTIVE; - task_makeActive(local(physicsActor)->actorTask); - task_yield(TASK_NO_DELAY); - } - } while (msg != MSG_RUN_TASK); - if (local(physicsActor)->state != WSTATE_DEFAULT || s_playerDying) { break; } - - if (actor_isObjectVisible(local(obj), s_playerObject, ANGLE_MAX, FIXED(25))) - { - fixed16_16 dy = TFE_Jedi::abs(local(obj)->posWS.y - s_playerObject->posWS.y); - fixed16_16 dist = dy + distApprox(s_playerObject->posWS.x, s_playerObject->posWS.z, local(obj)->posWS.x, local(obj)->posWS.z); - // Switch to the attack state if the player is close enough. - if (dist <= FIXED(40)) - { - local(physicsActor)->state = WSTATE_ACTIVE; - } - } - } // while (state == WSTATE_DEFAULT) - - task_end; - } - - void welder_handleActiveState(MessageType msg) - { - struct LocalContext - { - Welder* welder; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - RSector* sector; - JBool attack; - fixed16_16 dist; - fixed16_16 dy; - }; - task_begin_ctx; - - local(welder) = s_curWelder; - local(obj) = local(welder)->logic.obj; - local(physicsActor) = &local(welder)->actor; - local(target) = &local(physicsActor)->moveMod.target; - local(sector) = local(obj)->sector; - local(attack) = JFALSE; - - while (local(physicsActor)->state == WSTATE_ACTIVE) - { - do - { - entity_yield(TASK_NO_DELAY); - if (msg == MSG_DAMAGE) - { - msg = welder_handleDamage(msg, local(welder)); - } - else if (msg == MSG_EXPLOSION) - { - msg = welder_handleExplosion(msg, local(welder)); - } - } while (msg != MSG_RUN_TASK); - if (local(physicsActor)->state != WSTATE_ACTIVE) { break; } - - // Is the yaw aligned to the target? - if ((local(obj)->yaw & ANGLE_MASK) == (local(target)->yaw & ANGLE_MASK)) - { - sound_stop(local(welder)->sound2Id); - if (local(attack)) - { - sound_playCued(s_shared.weld1SoundSrcId, local(obj)->posWS); - } - local(dy) = TFE_Jedi::abs(local(obj)->posWS.y - s_playerObject->posWS.y); - local(dist) = local(dy) + distApprox(s_playerObject->posWS.x, s_playerObject->posWS.z, local(obj)->posWS.x, local(obj)->posWS.z); - if (local(dist) <= FIXED(40) && actor_isObjectVisible(local(obj), s_playerObject, ANGLE_MAX, FIXED(25))) - { - if (local(attack)) - { - fixed16_16 sinYaw, cosYaw; - fixed16_16 sinPitch, cosPitch; - sinCosFixed(local(obj)->yaw, &sinYaw, &cosYaw); - sinCosFixed(local(obj)->pitch, &sinPitch, &cosPitch); - - fixed16_16 armTipX = local(obj)->posWS.x + mul16(FIXED(19), sinYaw); - fixed16_16 armTipZ = local(obj)->posWS.z + mul16(FIXED(19), cosYaw); - fixed16_16 armTipY = FIXED(3) + local(obj)->posWS.y + mul16(FIXED(19), sinPitch); - - SecObject* spark = allocateObject(); - setObjPos_AddToSector(spark, armTipX, armTipY, armTipZ, local(sector)); - spark->flags |= OBJ_FLAG_FULLBRIGHT; - sprite_setData(spark, s_welderSpark); - - SpriteAnimLogic* animLogic = (SpriteAnimLogic*)obj_setSpriteAnim(spark); - setupAnimationFromLogic(animLogic, 0, 0, 0xffffffff, 1); - sound_playCued(s_shared.weldSparkSoundSrcId, spark->posWS); - - spark->worldWidth = 0; - local(dy) = TFE_Jedi::abs(armTipY - s_playerObject->posWS.y); - local(dist) = local(dy) + distApprox(s_playerObject->posWS.x, s_playerObject->posWS.z, armTipX, armTipZ); - if (local(dist) <= FIXED(35)) - { - player_applyDamage(FIXED(20), 0, JTRUE); - } - } - - do - { - entity_yield(72); - if (msg == MSG_DAMAGE) - { - msg = welder_handleDamage(msg, local(welder)); - } - else if (msg == MSG_EXPLOSION) - { - msg = welder_handleExplosion(msg, local(welder)); - } - } while (msg != MSG_RUN_TASK); - - fixed16_16 dz = s_playerObject->posWS.z - local(obj)->posWS.z; - fixed16_16 dx = s_playerObject->posWS.x - local(obj)->posWS.x; - local(dy) = local(obj)->posWS.y - s_eyePos.y + ONE_16; - - local(target)->yaw = vec2ToAngle(dx, dz); - local(target)->pitch = vec2ToAngle(local(dy), FIXED(19)); - - if (local(target)->yaw != local(obj)->yaw || local(target)->pitch != local(obj)->pitch) - { - local(target)->flags |= TARGET_MOVE_ROT; - local(attack) = JTRUE; - local(welder)->sound2Id = sound_playCued(s_shared.weld2SoundSrcId, local(obj)->posWS); - } - else - { - local(target)->flags &= ~TARGET_MOVE_ROT; - local(attack) = JFALSE; - } - } - else - { - local(physicsActor)->state = WSTATE_RESET; - } - } - } // while (state == WSTATE_ACTIVE) - - task_end; - } - - void welder_handleReset(MessageType msg) - { - struct LocalContext - { - Welder* welder; - SecObject* obj; - PhysicsActor* physicsActor; - ActorTarget* target; - }; - task_begin_ctx; - - local(welder) = s_curWelder; - local(obj) = local(welder)->logic.obj; - local(physicsActor) = &local(welder)->actor; - local(target) = &local(physicsActor)->moveMod.target; - - local(target)->yaw = local(welder)->yaw; - local(target)->pitch = local(welder)->pitch; - local(target)->flags = (local(target)->flags | TARGET_MOVE_ROT) & (~TARGET_MOVE_XZ); - local(welder)->sound2Id = sound_playCued(s_shared.weld2SoundSrcId, local(obj)->posWS); - - while (local(physicsActor)->state == WSTATE_RESET) - { - do - { - entity_yield(TASK_NO_DELAY); - if (msg == MSG_DAMAGE) - { - msg = welder_handleDamage(msg, local(welder)); - } - else if (msg == MSG_EXPLOSION) - { - msg = welder_handleExplosion(msg, local(welder)); - } - } while (msg != MSG_RUN_TASK); - if (local(physicsActor)->state != WSTATE_RESET) { break; } - - if (local(target)->yaw == local(obj)->yaw) - { - sound_stop(local(welder)->sound2Id); - sound_playCued(s_shared.weld1SoundSrcId, local(obj)->posWS); - local(physicsActor)->state = WSTATE_DEFAULT; - } - } // while (state == WSTATE_RESET) - - task_end; - } - - void welderTaskFunc(MessageType msg) - { - struct LocalContext - { - Welder* welder; - PhysicsActor* physicsActor; - SecObject* obj; - ActorTarget* target; - }; - task_begin_ctx; - - local(welder) = (Welder*)task_getUserData(); - local(physicsActor) = &local(welder)->actor; - local(obj) = local(welder)->logic.obj; - local(target) = &local(physicsActor)->moveMod.target; - while (local(physicsActor)->alive) - { - msg = MSG_RUN_TASK; - task_setMessage(MSG_RUN_TASK); - - if (local(physicsActor)->state == WSTATE_ACTIVE) - { - s_curWelder = local(welder); - task_callTaskFunc(welder_handleActiveState); - } - else if (local(physicsActor)->state == WSTATE_RESET) - { - s_curWelder = local(welder); - task_callTaskFunc(welder_handleReset); - } - else if (local(physicsActor)->state == WSTATE_DYING) - { - local(target)->flags |= TARGET_FREEZE; - sound_stop(local(welder)->sound2Id); - sound_playCued(s_shared.weldDieSoundSrcId, local(obj)->posWS); - - local(target)->pitch = 64171 & ANGLE_MASK; - local(target)->yaw = local(obj)->yaw; - local(target)->flags |= TARGET_MOVE_ROT; - - do - { - entity_yield(TASK_NO_DELAY); - } while ((local(obj)->yaw & ANGLE_MASK) != (local(target)->yaw & ANGLE_MASK) || msg != MSG_RUN_TASK); - - spawnHitEffect(HEFFECT_EXP_NO_DMG, local(obj)->sector, local(obj)->posWS, local(obj)); - local(physicsActor)->alive = JFALSE; - } - else - { - s_curWelder = local(welder); - task_callTaskFunc(welder_handleDefaultState); - } - } // while (alive) - - // Dead: - while (msg != MSG_RUN_TASK) - { - task_yield(TASK_NO_DELAY); - } - actor_removePhysicsActorFromWorld(local(physicsActor)); - deleteLogicAndObject((Logic*)local(welder)); - level_free(local(welder)); - - task_end; - } - - void welderCleanupFunc(Logic* logic) - { - Welder* welder = (Welder*)logic; - - actor_removePhysicsActorFromWorld(&welder->actor); - deleteLogicAndObject(logic); - level_free(welder); - task_free(welder->actor.actorTask); - } - - void welder_clear() - { - s_welderSpark = nullptr; - } - - void welder_serialize(Logic*& logic, SecObject* obj, Stream* stream) - { - Welder* welder = nullptr; - bool write = serialization_getMode() == SMODE_WRITE; - PhysicsActor* physicsActor = nullptr; - Task* welderTask = nullptr; - if (write) - { - welder = (Welder*)logic; - physicsActor = &welder->actor; - } - else - { - welder = (Welder*)level_alloc(sizeof(Welder)); - memset(welder, 0, sizeof(Welder)); - physicsActor = &welder->actor; - logic = (Logic*)welder; - - // Resources - if (!s_welderSpark) - { - s_welderSpark = TFE_Sprite_Jedi::getWax("spark.wax"); - } - - // Task - char name[32]; - sprintf(name, "Welder%d", s_shared.welderNum); - s_shared.welderNum++; - - welderTask = createSubTask(name, welderTaskFunc); - task_setUserData(welderTask, welder); - - // Logic - logic->task = welderTask; - logic->cleanupFunc = welderCleanupFunc; - logic->type = LOGIC_WELDER; - logic->obj = obj; - } - actor_serializeMovementModuleBase(stream, &physicsActor->moveMod); - actor_serializeLogicAnim(stream, &physicsActor->anim); - if (!write) - { - // Clear out functions, the mousebot handles all of this internally. - physicsActor->moveMod.header.obj = obj; - physicsActor->moveMod.header.func = nullptr; - physicsActor->moveMod.header.freeFunc = nullptr; - physicsActor->moveMod.header.attribFunc = nullptr; - physicsActor->moveMod.header.msgFunc = nullptr; - physicsActor->moveMod.header.type = ACTMOD_MOVE; - physicsActor->moveMod.updateTargetFunc = nullptr; - - actor_addPhysicsActorToWorld(physicsActor); - - physicsActor->moveMod.header.obj = obj; - physicsActor->moveMod.physics.obj = obj; - physicsActor->actorTask = welderTask; - - welder->hurtSndId = NULL_SOUND; - welder->sound2Id = NULL_SOUND; - } - SERIALIZE(SaveVersionInit, physicsActor->vel, { 0 }); - SERIALIZE(SaveVersionInit, physicsActor->lastPlayerPos, { 0 }); - SERIALIZE(SaveVersionInit, physicsActor->alive, JTRUE); - SERIALIZE(SaveVersionInit, physicsActor->hp, FIXED(130)); - SERIALIZE(SaveVersionInit, physicsActor->state, WSTATE_DEFAULT); - SERIALIZE(SaveVersionInit, welder->pitch, 0); - SERIALIZE(SaveVersionInit, welder->yaw, 0); - } - - Logic* welder_setup(SecObject* obj, LogicSetupFunc* setupFunc) - { - if (!s_welderSpark) - { - s_welderSpark = TFE_Sprite_Jedi::getWax("spark.wax"); - } - - Welder* welder = (Welder*)level_alloc(sizeof(Welder)); - memset(welder, 0, sizeof(Welder)); - - // Give the name of the task a number so I can tell them apart when debugging. - char name[32]; - sprintf(name, "Welder%d", s_shared.welderNum); - s_shared.welderNum++; - Task* task = createSubTask(name, welderTaskFunc); - task_setUserData(task, welder); - - obj->entityFlags = ETFLAG_AI_ACTOR; - PhysicsActor* physicsActor = &welder->actor; - physicsActor->alive = JTRUE; - physicsActor->hp = FIXED(130); - physicsActor->state = WSTATE_DEFAULT; - physicsActor->actorTask = task; - welder->logic.obj = obj; - welder->yaw = obj->yaw; - welder->pitch = obj->pitch; - welder->hurtSndId = NULL_SOUND; - welder->sound2Id = NULL_SOUND; - actor_addPhysicsActorToWorld(physicsActor); - CollisionInfo* physics = &physicsActor->moveMod.physics; - - ActorTarget* target = &physicsActor->moveMod.target; - obj->worldWidth = FIXED(10); - obj->worldHeight = FIXED(4); - physicsActor->moveMod.header.obj = obj; - physics->obj = obj; - physics->width = obj->worldWidth; - physics->wall = nullptr; - physics->u24 = 0; - physics->botOffset = 0; - physics->yPos = 0; - physics->height = obj->worldHeight + HALF_16; - - physicsActor->moveMod.delta = { 0, 0, 0 }; - physicsActor->moveMod.collisionFlags &= 0xfffffff8; - - target->speed = 0; - target->speedRotation = 4551; // ~100 degrees/second. - target->flags &= 0xfffffff0; - target->pitch = obj->pitch; - target->yaw = obj->yaw; - target->roll = obj->roll; - obj_addLogic(obj, &welder->logic, LOGIC_WELDER, task, welderCleanupFunc); - - if (setupFunc) - { - *setupFunc = nullptr; - } - return (Logic*)welder; - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Actor/welder.h b/components/darkforces/tfe/TFE_DarkForces/Actor/welder.h deleted file mode 100644 index a6045f02..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Actor/welder.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Handles the Welder AI. -////////////////////////////////////////////////////////////////////// -#include -#include -#include "actor.h" - -namespace TFE_DarkForces -{ - Logic* welder_setup(SecObject* obj, LogicSetupFunc* setupFunc); - void welder_serialize(Logic*& logic, SecObject* obj, Stream* stream); - void welder_clear(); - void welder_exit(); - void welder_precache(); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/GameUI/agentMenu.cpp b/components/darkforces/tfe/TFE_DarkForces/GameUI/agentMenu.cpp deleted file mode 100644 index 3b035484..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/GameUI/agentMenu.cpp +++ /dev/null @@ -1,774 +0,0 @@ -#include - -#include "agentMenu.h" -#include -#include "editBox.h" -#include "delt.h" -#include "menu.h" -#include "uiDraw.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - /////////////////////////////////////////// - // Constants - /////////////////////////////////////////// - enum AgentMenuButtons - { - AGENT_NEW, - AGENT_REMOVE, - AGENT_EXIT, - AGENT_BEGIN, - AGENT_COUNT - }; - static const Vec2i c_agentButtons[AGENT_COUNT] = - { - {21, 165}, // AGENT_NEW - {90, 165}, // AGENT_REMOVE - {164, 165}, // AGENT_EXIT - {239, 165}, // AGENT_BEGIN - }; - static const Vec2i c_agentButtonDim = { 60, 25 }; - - enum NewAgentDlg - { - NEW_AGENT_NO, - NEW_AGENT_YES, - NEW_AGENT_COUNT - }; - static const Vec2i c_newAgentButtons[NEW_AGENT_COUNT] = - { - {167, 107}, // NEW_AGENT_NO - {206, 107}, // NEW_AGENT_YES - }; - static const Vec2i c_newAgentButtonDim = { 28, 15 }; - - /////////////////////////////////////////// - // Internal State - /////////////////////////////////////////// - static JBool s_loaded = JFALSE; - static JBool s_displayInit = JFALSE; - static u8* s_framebuffer = nullptr; - - static s32 s_selectedMission = 0; - static s32 s_editCursorFlicker = 0; - static s32 s_agentCount = 0; - static JBool s_lastSelectedAgent = JTRUE; - static JBool s_newAgentDlg = JFALSE; - static JBool s_removeAgentDlg = JFALSE; - static JBool s_quitConfirmDlg = JFALSE; - static JBool s_missionBegin = JFALSE; - static EditBox s_editBox = {}; - - static u8 s_menuPalette[768]; - static DeltFrame* s_agentMenuFrames; - static DeltFrame* s_agentDlgFrames; - static u32 s_agentMenuCount; - static u32 s_agentDlgCount; - - static char s_newAgentName[32]; - static LangHotkeys* s_langKeys; - - /////////////////////////////////////////// - // Forward Declarations - /////////////////////////////////////////// - void agentMenu_startup(); - void agentMenu_startupDisplay(); - void agentMenu_blit(); - void agentMenu_update(); - void agentMenu_draw(); - - void drawYesNoDlg(s32 baseFrame); - void drawNewAgentDlg(); - - void updateNewAgentDlg(); - void updateRemoveAgentDlg(); - JBool updateQuitConfirmDlg(); - - /////////////////////////////////////////// - // API Implementation - /////////////////////////////////////////// - void agentMenu_resetState() - { - s_loaded = JFALSE; - s_displayInit = JFALSE; - s_agentMenuFrames = nullptr; - s_agentDlgFrames = nullptr; - s_framebuffer = nullptr; - delt_resetState(); - } - - JBool agentMenu_update(s32* levelIndex) - { - if (!s_loaded) - { - menu_init(); - agentMenu_startup(); - s_loaded = JTRUE; - } - if (!s_displayInit) - { - agentMenu_startupDisplay(); - s_missionBegin = JFALSE; - s_displayInit = JTRUE; - } - - // Update the mouse position. - menu_handleMousePosition(); - agentMenu_update(); - agentMenu_draw(); - - agentMenu_blit(); - - // Reset for next time. - if (s_missionBegin) - { - s_displayInit = JFALSE; - vfb_forceToBlack(); - lcanvas_clear(); - - assert(s_selectedMission >= 0 && s_selectedMission <= MAX_LEVEL_COUNT - 1); - s_selectedMission = clamp(s_selectedMission, 0, MAX_LEVEL_COUNT - 1); - } - - *levelIndex = s_selectedMission + 1; - return ~s_missionBegin; - } - - /////////////////////////////////////////// - // Internal Implementation - /////////////////////////////////////////// - void agentMenu_update() - { - if (s_newAgentDlg) - { - updateNewAgentDlg(); - return; - } - else if (s_removeAgentDlg) - { - updateRemoveAgentDlg(); - return; - } - else if (s_quitConfirmDlg) - { - if (updateQuitConfirmDlg()) - { - if (TFE_Settings::getSystemSettings()->gameQuitExitsToMenu) - { - TFE_FrontEndUI::exitToMenu(); - } - else - { - TFE_System::postQuitMessage(); - } - } - return; - } - - if (s_selectedMission < 0) - { - assert(0); // This shouldn't happen. - s_selectedMission = 0; - } - else if (s_selectedMission >= s_maxLevelIndex) - { - s_selectedMission = max(0, s_maxLevelIndex - 1); - } - - const s32 x = s_cursorPos.x; - const s32 z = s_cursorPos.z; - if (TFE_Input::mousePressed(MBUTTON_LEFT)) - { - s_buttonPressed = -1; - for (u32 i = 0; i < AGENT_COUNT; i++) - { - if (x >= c_agentButtons[i].x && x < c_agentButtons[i].x + c_agentButtonDim.x && - z >= c_agentButtons[i].z && z < c_agentButtons[i].z + c_agentButtonDim.z) - { - s_buttonPressed = s32(i); - s_buttonHover = JTRUE; - break; - } - } - - if (s_buttonPressed < 0) - { - if (x >= 25 && x < 122 && z >= 35 && z < 147 && s_agentCount > 0) - { - s_agentId = clamp((z - 35) / 8, 0, (s32)s_agentCount - 1); - s_selectedMission = max(0, s_agentData[s_agentId].selectedMission - 1); - s_lastSelectedAgent = true; - } - else if (x >= 171 && x < 290 && z >= 35 && z < 147 && s_agentCount > 0) - { - s_selectedMission = clamp((z - 35) / 8, 0, (s32)s_agentData[s_agentId].nextMission - 1); - s_agentData[s_agentId].selectedMission = s_selectedMission + 1; - s_lastSelectedAgent = false; - } - } - } - else if (TFE_Input::mouseDown(MBUTTON_LEFT) && s_buttonPressed >= 0) - { - // Verify that the mouse is still over the button. - if (x >= c_agentButtons[s_buttonPressed].x && x < c_agentButtons[s_buttonPressed].x + c_agentButtonDim.x && - z >= c_agentButtons[s_buttonPressed].z && z < c_agentButtons[s_buttonPressed].z + c_agentButtonDim.z) - { - s_buttonHover = true; - } - else - { - s_buttonHover = false; - } - } - else - { - if (TFE_Input::keyPressed(KEY_N)) - { - s_buttonPressed = AGENT_NEW; - s_buttonHover = JTRUE; - } - else if (TFE_Input::keyPressed(s_langKeys->k_agdel)) - { - s_buttonPressed = AGENT_REMOVE; - s_buttonHover = JTRUE; - } - else if (TFE_Input::keyPressed(KEY_D)) // DOS - { - s_buttonPressed = AGENT_EXIT; - s_buttonHover = JTRUE; - } - else if (TFE_Input::keyPressed(s_langKeys->k_begin) || TFE_Input::keyPressed(KEY_RETURN) || TFE_Input::keyPressed(KEY_KP_ENTER)) - { - s_buttonPressed = AGENT_BEGIN; - s_buttonHover = JTRUE; - } - - // Arrow keys to change the selected agent or mission. - if (TFE_Input::bufferedKeyDown(KEY_DOWN)) - { - if (s_lastSelectedAgent && s_agentCount > 0) - { - s_agentId++; - if (s_agentId >= (s32)s_agentCount) { s_agentId = 0; } - if (s_agentId >= 0) { s_selectedMission = s_agentData[s_agentId].selectedMission - 1; } - } - else if (!s_lastSelectedAgent && s_agentId >= 0 && s_agentData[s_agentId].nextMission > 1) - { - s_selectedMission++; - if (s_selectedMission > s_agentData[s_agentId].nextMission - 1 || s_selectedMission == 14) { s_selectedMission = 0; } - } - } - else if (TFE_Input::bufferedKeyDown(KEY_UP)) - { - if (s_lastSelectedAgent && s_agentCount > 0) - { - s_agentId--; - if (s_agentId < 0) { s_agentId = s_agentCount - 1; } - if (s_agentId >= 0) { s_selectedMission = s_agentData[s_agentId].selectedMission - 1; } - } - else if (!s_lastSelectedAgent && s_agentId >= 0 && s_agentData[s_agentId].nextMission > 1) - { - s_selectedMission--; - if (s_selectedMission < 0) { s_selectedMission = s_agentData[s_agentId].nextMission - 1; } - } - } - else if (TFE_Input::bufferedKeyDown(KEY_LEFT) || TFE_Input::bufferedKeyDown(KEY_RIGHT)) - { - s_lastSelectedAgent = !s_lastSelectedAgent; - } - - if (s_buttonPressed >= AGENT_NEW && s_buttonHover) - { - switch (s_buttonPressed) - { - case AGENT_NEW: - { - s_newAgentDlg = JTRUE; - memset(s_newAgentName, 0, 32); - s_editBox.cursor = 0; - s_editBox.inputField = s_newAgentName; - s_editBox.maxLen = 16; - } break; - case AGENT_REMOVE: - s_removeAgentDlg = JTRUE; - break; - case AGENT_EXIT: - s_quitConfirmDlg = JTRUE; - break; - case AGENT_BEGIN: - if (s_agentCount > 0 && s_selectedMission >= 0) - { - s_missionBegin = JTRUE; - } - break; - }; - } - - // Reset. - s_buttonPressed = -1; - s_buttonHover = JFALSE; - } - } - - void agentMenu_draw() - { - memset(s_framebuffer, 0, 320 * 200); - blitDeltaFrame(&s_agentMenuFrames[0], 0, 0, s_framebuffer); - - // Draw the buttons - for (s32 i = 0; i < 4; i++) - { - s32 index; - if (s_newAgentDlg) - { - if (i == 0) { index = i * 2 + 1; } - else { index = i * 2 + 2; } - } - else if (s_removeAgentDlg) - { - if (i == 1) { index = i * 2 + 1; } - else { index = i * 2 + 2; } - } - else if (s_quitConfirmDlg) - { - if (i == 2) { index = i * 2 + 1; } - else { index = i * 2 + 2; } - } - else - { - if (s_buttonPressed == i && s_buttonHover) { index = i * 2 + 1; } - else { index = i * 2 + 2; } - } - blitDeltaFrame(&s_agentMenuFrames[index], 0, 0, s_framebuffer); - } - - // 11 = easy, 12 = medium, 13 = hard - s32 yOffset = -20; - s32 textX = 174; - s32 textY = 36; - u8 color = 47; - if (s_agentId >= 0 && s_agentCount > 0) - { - s32 nextMission = min(s_agentData[s_agentId].nextMission, s_maxLevelIndex); - - for (s32 i = 0; i < nextMission - 1 && i < s_maxLevelIndex; i++) - { - color = 47; - if (s_selectedMission == i) - { - color = 32; - drawColoredQuad(textX - 3, textY - 1, 118, 9, s_lastSelectedAgent ? 13 : 12, s_framebuffer); - } - - print(s_levelDisplayNames[i], textX, textY, color, s_framebuffer); - s32 diff = s_agentData[s_agentId].completed[i] + 11; - blitDeltaFrame(&s_agentMenuFrames[diff], 0, yOffset, s_framebuffer); - yOffset += 8; - textY += 8; - } - color = 47; - if (s_selectedMission == nextMission - 1) - { - color = 32; - drawColoredQuad(textX - 3, textY - 1, 118, 9, s_lastSelectedAgent ? 13 : 12, s_framebuffer); - } - print(s_levelDisplayNames[nextMission - 1], textX, textY, color, s_framebuffer); - - // Show final level complete. - if (s_agentData[s_agentId].nextMission > s_maxLevelIndex) - { - yOffset = -20 + 8 * (s_maxLevelIndex - 1); - s32 diff = s_agentData[s_agentId].completed[s_maxLevelIndex-1] + 11; - blitDeltaFrame(&s_agentMenuFrames[diff], 0, yOffset, s_framebuffer); - } - } - - // Draw agents. - textX = 28; - textY = 36; - for (s32 i = 0; i < s_agentCount; i++) - { - color = 47; - if (s_agentId == i) - { - color = 32; - drawColoredQuad(textX - 3, textY - 1, 118, 9, s_lastSelectedAgent ? 12 : 13, s_framebuffer); - } - print(s_agentData[i].name, textX, textY, color, s_framebuffer); - textY += 8; - } - - if (s_newAgentDlg) - { - drawNewAgentDlg(); - } - else if (s_removeAgentDlg) - { - drawYesNoDlg(0); - } - else if (s_quitConfirmDlg) - { - drawYesNoDlg(1); - } - } - - void setPalette() - { - // Update the palette. - u32 palette[256]; - u32* outColor = palette; - u8* srcColor = s_menuPalette; - for (s32 i = 0; i < 256; i++, outColor++, srcColor += 3) - { - *outColor = u32(srcColor[0]) | (u32(srcColor[1]) << 8u) | (u32(srcColor[2]) << 16u) | (0xffu << 24u); - } - vfb_setPalette(palette); - } - - // TFE Specific. - void agentMenu_startupDisplay() - { - s_framebuffer = menu_startupDisplay(); - menu_resetCursor(); - - setPalette(); - } - -#ifdef TFE_ESPBOX - // Release the menu frames (they are only needed in the agent menu); agentMenu_load() - // reloads them on demand. - void agentMenu_freeFrames() - { - DeltFrame* lists[2] = { s_agentMenuFrames, s_agentDlgFrames }; - s32 counts[2] = { s_agentMenuCount, s_agentDlgCount }; - for (s32 l = 0; l < 2; l++) - { - if (!lists[l]) { continue; } - for (s32 i = 0; i < counts[l]; i++) { game_free(lists[l][i].texture.image); } - game_free(lists[l]); - } - s_agentMenuFrames = nullptr; - s_agentDlgFrames = nullptr; - s_agentMenuCount = 0; - s_agentDlgCount = 0; - // s_cursor (uiDraw.h) is shared with the in-mission escape menu and the PDA: - // it stays loaded (it is a few hundred bytes). - } -#endif - - void agentMenu_load(LangHotkeys* langKeys) - { -#ifdef TFE_ESPBOX - if (s_agentMenuFrames) { s_langKeys = langKeys; return; } -#endif - FilePath filePath; - if (!TFE_Paths::getFilePath("AGENTMNU.LFD", &filePath)) { return; } - Archive* archive = Archive::getArchive(ARCHIVE_LFD, "AGENTMNU", filePath.path); - TFE_Paths::addLocalArchive(archive); - - loadPaletteFromPltt("agentmnu.pltt", s_menuPalette); - s_agentMenuCount = getFramesFromAnim("agentmnu.anim", &s_agentMenuFrames); - s_agentDlgCount = getFramesFromAnim("agentdlg.anim", &s_agentDlgFrames); - getFrameFromDelt("cursor.delt", &s_cursor); - TFE_Paths::removeLastArchive(); - - s_langKeys = langKeys; - } - - void agentMenu_startup() - { - s_agentCount = 0; - for (s32 i = 0; i < MAX_AGENT_COUNT; i++) - { - if (!s_agentData[i].name[0]) - { - break; - } - s_agentCount++; - } - // Clear out extra data. - for (s32 i = s_agentCount; i < MAX_AGENT_COUNT; i++) - { - memset(&s_agentData[i], 0, sizeof(AgentData)); - } - - if (s_agentCount > 0) - { - s_agentId = 0; - s_selectedMission = max(0, s_agentData[s_agentId].selectedMission - 1); - } - else - { - s_agentId = -1; - s_selectedMission = 0; - } - - s_missionBegin = JFALSE; - } - - void agentMenu_blit() - { - setPalette(); - menu_blitCursor(s_cursorPos.x, s_cursorPos.z, s_framebuffer); - menu_blitToScreen(s_framebuffer); - } - - void agentMenu_createNewAgent() - { - if (s_agentCount < MAX_AGENT_COUNT) - { - s_agentId = s_agentCount; - s_agentCount++; - agent_createNewAgent(s_agentId, &s_agentData[s_agentId], s_newAgentName); - - s_selectedMission = 0; - } - } - - void agentMenu_removeAgent(s32 index) - { - if (s_agentCount < 1) - { - return; - } - - for (s32 i = index; i < (s32)s_agentCount; i++) - { - s_agentData[i] = s_agentData[i + 1]; - } - s_agentCount--; - memset(&s_agentData[s_agentCount], 0, sizeof(AgentData)); - - s_agentId = s_agentCount > 0 ? 0 : -1; - s_selectedMission = s_agentCount > 0 ? s_agentData[0].selectedMission : 0; - } - - // UI routines. - void drawYesNoButtons(u32 indexNo, u32 indexYes) - { - if (s_buttonPressed == 0 && s_buttonHover) - { - blitDeltaFrame(&s_agentDlgFrames[indexNo], 0, 0, s_framebuffer); - } - else if (s_buttonPressed == 1 && s_buttonHover) - { - blitDeltaFrame(&s_agentDlgFrames[indexYes], 0, 0, s_framebuffer); - } - } - - void drawYesNoDlg(s32 baseFrame) - { - blitDeltaFrame(&s_agentDlgFrames[baseFrame], 0, 0, s_framebuffer); - drawYesNoButtons(4, 6); - } - - void drawNewAgentDlg() - { - blitDeltaFrame(&s_agentDlgFrames[2], 0, 0, s_framebuffer); - drawEditBox(&s_editBox, 106, 87, 216, 100, s_framebuffer); - drawYesNoButtons(8, 10); - } - - void updateNewAgentDlg() - { - updateEditBox(&s_editBox); - - if (TFE_Input::keyPressed(KEY_RETURN) || TFE_Input::keyPressed(KEY_KP_ENTER)) - { - agentMenu_createNewAgent(); - s_newAgentDlg = JFALSE; - return; - } - else if (TFE_Input::keyPressed(KEY_ESCAPE)) - { - s_newAgentDlg = JFALSE; - return; - } - - if (TFE_Input::mousePressed(MBUTTON_LEFT)) - { - s_buttonPressed = -1; - for (u32 i = 0; i < NEW_AGENT_COUNT; i++) - { - if (s_cursorPos.x >= c_newAgentButtons[i].x && s_cursorPos.x < c_newAgentButtons[i].x + c_newAgentButtonDim.x && - s_cursorPos.z >= c_newAgentButtons[i].z && s_cursorPos.z < c_newAgentButtons[i].z + c_newAgentButtonDim.z) - { - s_buttonPressed = s32(i); - s_buttonHover = true; - break; - } - } - } - else if (TFE_Input::mouseDown(MBUTTON_LEFT) && s_buttonPressed >= 0) - { - // Verify that the mouse is still over the button. - if (s_cursorPos.x >= c_newAgentButtons[s_buttonPressed].x && s_cursorPos.x < c_newAgentButtons[s_buttonPressed].x + c_newAgentButtonDim.x && - s_cursorPos.z >= c_newAgentButtons[s_buttonPressed].z && s_cursorPos.z < c_newAgentButtons[s_buttonPressed].z + c_newAgentButtonDim.z) - { - s_buttonHover = true; - } - else - { - s_buttonHover = false; - } - } - else - { - // Activate button 's_escButtonPressed' - if (s_buttonPressed >= NEW_AGENT_NO && s_buttonHover) - { - if (s_buttonPressed == NEW_AGENT_YES) - { - agentMenu_createNewAgent(); - } - s_newAgentDlg = JFALSE; - } - // Reset. - s_buttonPressed = -1; - s_buttonHover = false; - } - } - - void updateRemoveAgentDlg() - { - if (TFE_Input::keyPressed(KEY_RETURN) || TFE_Input::keyPressed(KEY_KP_ENTER) || TFE_Input::keyPressed(KEY_ESCAPE)) - { - s_removeAgentDlg = false; - return; - } - - if (TFE_Input::mousePressed(MBUTTON_LEFT)) - { - s_buttonPressed = -1; - for (u32 i = 0; i < NEW_AGENT_COUNT; i++) - { - if (s_cursorPos.x >= c_newAgentButtons[i].x && s_cursorPos.x < c_newAgentButtons[i].x + c_newAgentButtonDim.x && - s_cursorPos.z >= c_newAgentButtons[i].z && s_cursorPos.z < c_newAgentButtons[i].z + c_newAgentButtonDim.z) - { - s_buttonPressed = s32(i); - s_buttonHover = true; - break; - } - } - } - else if (TFE_Input::mouseDown(MBUTTON_LEFT) && s_buttonPressed >= 0) - { - // Verify that the mouse is still over the button. - if (s_cursorPos.x >= c_newAgentButtons[s_buttonPressed].x && s_cursorPos.x < c_newAgentButtons[s_buttonPressed].x + c_newAgentButtonDim.x && - s_cursorPos.z >= c_newAgentButtons[s_buttonPressed].z && s_cursorPos.z < c_newAgentButtons[s_buttonPressed].z + c_newAgentButtonDim.z) - { - s_buttonHover = true; - } - else - { - s_buttonHover = false; - } - } - else - { - if (TFE_Input::keyPressed(s_langKeys->k_yes)) - { - agentMenu_removeAgent(s_agentId); - s_removeAgentDlg = false; - } - else if (TFE_Input::keyPressed(KEY_N)) - { - s_removeAgentDlg = false; - } - else if (s_buttonPressed >= NEW_AGENT_NO && s_buttonHover) - { - if (s_buttonPressed == NEW_AGENT_YES) - { - agentMenu_removeAgent(s_agentId); - } - s_removeAgentDlg = false; - } - // Reset. - s_buttonPressed = -1; - s_buttonHover = false; - } - } - - JBool updateQuitConfirmDlg() - { - JBool quit = JFALSE; - if (TFE_Input::keyPressed(KEY_ESCAPE)) - { - s_quitConfirmDlg = JFALSE; - return JFALSE; - } - else if (TFE_Input::keyPressed(KEY_RETURN) || TFE_Input::keyPressed(KEY_KP_ENTER)) - { - s_quitConfirmDlg = JFALSE; - return JTRUE; - } - - if (TFE_Input::mousePressed(MBUTTON_LEFT)) - { - s_buttonPressed = -1; - for (u32 i = 0; i < NEW_AGENT_COUNT; i++) - { - if (s_cursorPos.x >= c_newAgentButtons[i].x && s_cursorPos.x < c_newAgentButtons[i].x + c_newAgentButtonDim.x && - s_cursorPos.z >= c_newAgentButtons[i].z && s_cursorPos.z < c_newAgentButtons[i].z + c_newAgentButtonDim.z) - { - s_buttonPressed = s32(i); - s_buttonHover = JTRUE; - break; - } - } - } - else if (TFE_Input::mouseDown(MBUTTON_LEFT) && s_buttonPressed >= 0) - { - // Verify that the mouse is still over the button. - if (s_cursorPos.x >= c_newAgentButtons[s_buttonPressed].x && s_cursorPos.x < c_newAgentButtons[s_buttonPressed].x + c_newAgentButtonDim.x && - s_cursorPos.z >= c_newAgentButtons[s_buttonPressed].z && s_cursorPos.z < c_newAgentButtons[s_buttonPressed].z + c_newAgentButtonDim.z) - { - s_buttonHover = JTRUE; - } - else - { - s_buttonHover = JFALSE; - } - } - else - { - // Activate button 's_escButtonPressed' - if (TFE_Input::keyPressed(s_langKeys->k_yes)) - { - quit = JTRUE; - s_quitConfirmDlg = JFALSE; - } - else if (TFE_Input::keyPressed(KEY_N)) - { - s_quitConfirmDlg = JFALSE; - } - else if (s_buttonPressed >= NEW_AGENT_NO && s_buttonHover) - { - if (s_buttonPressed == NEW_AGENT_YES) - { - quit = JTRUE; - } - s_quitConfirmDlg = JFALSE; - } - // Reset. - s_buttonPressed = -1; - s_buttonHover = false; - } - - return quit; - } -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/GameUI/agentMenu.h b/components/darkforces/tfe/TFE_DarkForces/GameUI/agentMenu.h deleted file mode 100644 index c1280548..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/GameUI/agentMenu.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Note this is still the original TFE code, reverse-engineered game -// UI code will not be available until future releases. -////////////////////////////////////////////////////////////////////// - -#include -#include - -namespace TFE_DarkForces -{ - // Return True if the menu is still running. - // levelIndex will hold the selected level index (1 - 14). - JBool agentMenu_update(s32* levelIndex); - - void agentMenu_load(LangHotkeys* hotkeys); -#ifdef TFE_ESPBOX - void agentMenu_freeFrames(); -#endif - - // Reset Presistent State. - void agentMenu_resetState(); -} diff --git a/components/darkforces/tfe/TFE_DarkForces/GameUI/delt.cpp b/components/darkforces/tfe/TFE_DarkForces/GameUI/delt.cpp deleted file mode 100644 index 09b479b0..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/GameUI/delt.cpp +++ /dev/null @@ -1,328 +0,0 @@ -#include -#include - -#include "delt.h" -#include -#include -#include -#include -#include -#include - -namespace TFE_DarkForces -{ -#pragma pack(push) -#pragma pack(1) - struct DeltHeader - { - s16 offsetX; - s16 offsetY; - s16 sizeX; - s16 sizeY; - }; - - struct DeltLine - { - s16 sizeAndType; - s16 xStart; - s16 yStart; - }; -#pragma pack(pop) - - static u8* s_buffer = nullptr; - static size_t s_bufferSize = 0; - - void delt_resetState() - { - s_buffer = nullptr; - s_bufferSize = 0; - } - - u8* getTempBuffer(size_t size) - { - if (size > s_bufferSize) - { - s_bufferSize = size + 256; - s_buffer = (u8*)game_realloc(s_buffer, s_bufferSize); - } - return s_buffer; - } - - // This is here for now, until the proper LFD code is handled. - JBool loadPaletteFromPltt(const char* name, u8* palette) - { - FilePath filePath; - if (!TFE_Paths::getFilePath(name, &filePath)) - { - return JFALSE; - } - FileStream file; - file.open(&filePath, Stream::MODE_READ); - size_t size = file.getSize(); - u8* buffer = getTempBuffer(size); - file.readBuffer(buffer, (u32)size); - file.close(); - - s32 first = (s32)buffer[0]; - s32 last = (s32)buffer[1]; - s32 count = last - first + 1; - memset(palette, 0, 768); - - const u8* color = buffer + 2; - u8* outColor = palette; - for (s32 i = first; i <= last; i++, color += 3, outColor += 3) - { - outColor[0] = color[0]; - outColor[1] = color[1]; - outColor[2] = color[2]; - } - - return JTRUE; - } - - u32 getFramesFromAnim(const char* name, DeltFrame** outFrames) - { - FilePath filePath; - if (!TFE_Paths::getFilePath(name, &filePath)) - { - return JFALSE; - } - FileStream file; - file.open(&filePath, Stream::MODE_READ); - size_t size = file.getSize(); - u8* buffer = getTempBuffer(size); - file.readBuffer(buffer, (u32)size); - file.close(); - - s16 frameCount = *((s16*)buffer); - frameCount = TFE_Endian::le16_to_cpu(frameCount); - - const u8* frames = buffer + 2; - - *outFrames = (DeltFrame*)game_alloc(sizeof(DeltFrame) * frameCount); - DeltFrame* outFramePtr = *outFrames; - if (!outFramePtr) { return 0; } - - for (s32 i = 0; i < frameCount; i++) - { - u32 size = *((u32*)frames); - size = TFE_Endian::le32_to_cpu(size); - frames += 4; - - loadDeltIntoFrame(&outFramePtr[i], frames, size); - frames += size; - } -#ifdef TFE_ESPBOX - // Out of memory part way through: release what was loaded and report failure - // rather than handing back frames with null images. - for (s32 i = 0; i < frameCount; i++) - { - if (outFramePtr[i].texture.image) { continue; } - for (s32 j = 0; j < frameCount; j++) { if (outFramePtr[j].texture.image) { game_free(outFramePtr[j].texture.image); } } - game_free(outFramePtr); - *outFrames = nullptr; - return 0; - } -#endif - - return frameCount; - } - - JBool getFrameFromDelt(const char* name, DeltFrame* outFrame) - { - FilePath filePath; - if (!TFE_Paths::getFilePath(name, &filePath)) - { - return JFALSE; - } - FileStream file; - file.open(&filePath, Stream::MODE_READ); - size_t size = file.getSize(); - u8* buffer = getTempBuffer(size); - file.readBuffer(buffer, (u32)size); - file.close(); - - // Then read out the data. - loadDeltIntoFrame(outFrame, buffer, (u32)size); - return JTRUE; - } - - void getDeltaFrameRect(DeltFrame* frame, ScreenRect* rect) - { - rect->left = INT_MAX; - rect->top = INT_MAX; - rect->right = -INT_MAX; - rect->bot = -INT_MAX; - - u8* srcTexels = frame->texture.image; - s32 w = frame->texture.width; - s32 h = frame->texture.height; - - for (s32 y = 0; y < h; y++) - { - for (s32 x = 0; x < w; x++) - { - if (srcTexels[x]) - { - rect->left = min(x, rect->left); - rect->top = min(y, rect->top); - rect->right = max(x, rect->right); - rect->bot = max(y, rect->bot); - } - } - srcTexels += w; - } - } - - void blitDeltaFrame(DeltFrame* frame, s32 x0, s32 y0, u8* framebuffer) - { - u8* output = &framebuffer[y0 * 320]; - u8* srcTexels = frame->texture.image; - s32 w = frame->texture.width; - s32 h = frame->texture.height; - s32 x1 = x0 + w - 1; - s32 y1 = y0 + h - 1; - - // Skip if out of bounds. - if (x0 >= 320 || x1 < 0 || y0 >= 200 || y1 < 0) - { - return; - } - // Clip - if (x0 < 0) - { - x0 = 0; - } - if (x1 >= 320) - { - x1 = 319; - } - if (y0 < 0) - { - srcTexels -= y0 * w; - output -= y0 * 320; - y0 = 0; - } - if (y1 >= 200) - { - y1 = 199; - } - - for (s32 y = y0; y <= y1; y++) - { - for (s32 x = x0; x <= x1; x++) - { - if (srcTexels[x - x0]) - { - output[x] = srcTexels[x - x0]; - } - } - srcTexels += w; - output += 320; - } - } - - void blitDeltaFrameScaled(DeltFrame* frame, s32 x0, s32 y0, fixed16_16 xScale, fixed16_16 yScale, u8* framebuffer) - { - s32 x1 = x0 + floor16(mul16(intToFixed16(frame->texture.width - 1), xScale)); - s32 y1 = y0 + floor16(mul16(intToFixed16(frame->texture.height- 1), yScale)); - - ScreenImage scrImage= - { - frame->texture.width, - frame->texture.height, - frame->texture.image, - JTRUE, - JFALSE - }; - - ScreenRect* rect = vfb_getScreenRect(VFB_RECT_UI); - blitTextureToScreenScaled(&scrImage, (DrawRect*)rect, x0, y0, xScale, yScale, framebuffer); - } - - void loadDeltIntoFrame(DeltFrame* frame, const u8* buffer, u32 size) - { - DeltHeader header = *((DeltHeader*)buffer); - header.offsetX = TFE_Endian::le16_to_cpu(header.offsetX); - header.offsetY = TFE_Endian::le16_to_cpu(header.offsetY); - header.sizeX = TFE_Endian::le16_to_cpu(header.sizeX); - header.sizeY = TFE_Endian::le16_to_cpu(header.sizeY); - header.sizeX++; - header.sizeY++; - - frame->texture.width = header.sizeX; - frame->texture.height = header.sizeY; - frame->texture.uvWidth = header.sizeX; - frame->texture.uvHeight = header.sizeY; - frame->texture.dataSize = frame->texture.width * frame->texture.height; - frame->texture.logSizeY = 0; - frame->texture.flags = OPACITY_TRANS; - frame->texture.textureId = 0; - - frame->offsetX = header.offsetX; - frame->offsetY = header.offsetY; - frame->texture.image = (u8*)game_alloc(frame->texture.dataSize); - if (!frame->texture.image) - { - // Out of memory: leave an empty frame (callers check for a null image). - frame->texture.dataSize = 0; - return; - } - memset(frame->texture.image, 0, frame->texture.dataSize); - - const u8* data = buffer + sizeof(DeltHeader); - const u8* end = size ? buffer + size : nullptr; - while ((data && data < end) || !data) - { - const DeltLine* line = (DeltLine*)data; - if (line->sizeAndType == 0) - { - break; - } - - data += sizeof(DeltLine); - - const s32 startX = TFE_Endian::le16_to_cpu(line->xStart); - const s32 startY = TFE_Endian::le16_to_cpu(line->yStart); - const bool rle = (TFE_Endian::le16_to_cpu(line->sizeAndType) & 1) ? true : false; - s32 pixelCount = (TFE_Endian::le16_to_cpu(line->sizeAndType) >> 1) & 0x3FFF; - - u8* image = frame->texture.image + startX + startY * header.sizeX; - while (pixelCount > 0) - { - if (rle) - { - //read count byte... - u8 count = *data; data++; - if (!(count & 1)) // direct - { - count >>= 1; - for (s32 p = 0; p < count; p++, image++, data++) - { - *image = *data; - } - pixelCount -= count; - } - else //rle - { - count >>= 1; - const u8 pixel = *data; data++; - - memset(image, pixel, count); - image += count; - - pixelCount -= count; - } - } - else - { - for (s32 p = 0; p < pixelCount; p++, image++, data++) - { - *image = *data; - } - pixelCount = 0; - } - } - } - } -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/GameUI/delt.h b/components/darkforces/tfe/TFE_DarkForces/GameUI/delt.h deleted file mode 100644 index bfbb74bb..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/GameUI/delt.h +++ /dev/null @@ -1,33 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Note this is still the original TFE code, reverse-engineered game -// UI code will not be available until future releases. -////////////////////////////////////////////////////////////////////// -#include -#include - -struct ScreenRect; - -namespace TFE_DarkForces -{ - struct DeltFrame - { - TextureData texture; - s16 offsetX; - s16 offsetY; - }; - - void delt_resetState(); - - u8* getTempBuffer(size_t size); - JBool loadPaletteFromPltt(const char* name, u8* palette); - u32 getFramesFromAnim(const char* name, DeltFrame** outFrames); - JBool getFrameFromDelt(const char* name, DeltFrame* outFrame); - - void loadDeltIntoFrame(DeltFrame* frame, const u8* buffer, u32 size); - - void blitDeltaFrame(DeltFrame* frame, s32 x, s32 y, u8* framebuffer); - void blitDeltaFrameScaled(DeltFrame* frame, s32 x0, s32 y0, fixed16_16 xScale, fixed16_16 yScale, u8* framebuffer); - - void getDeltaFrameRect(DeltFrame* frame, ScreenRect* rect); -} diff --git a/components/darkforces/tfe/TFE_DarkForces/GameUI/editBox.cpp b/components/darkforces/tfe/TFE_DarkForces/GameUI/editBox.cpp deleted file mode 100644 index 208d0297..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/GameUI/editBox.cpp +++ /dev/null @@ -1,116 +0,0 @@ -#include - -#include "editBox.h" -#include "uiDraw.h" -#include -#include - -namespace -{ - void insertChar(char* output, s32* cursor, char input, s32 maxLen) - { - if ((*cursor) >= maxLen) - { - return; - } - - const size_t len = strlen(output); - if (*cursor == len) - { - output[len] = input; - output[len + 1] = 0; - } - else - { - for (s32 i = (s32)len - 1; i > *cursor; i--) - { - output[i + 1] = output[i]; - } - output[*cursor] = input; - output[len + 1] = 0; - } - (*cursor)++; - } -} - -namespace TFE_DarkForces -{ - const u8 c_editBoxBackground = 0u; - const u8 c_editBoxColor = 47u; - const u8 c_editBoxHighlight = 32u; - const u8 c_editBoxText = 32u; - const u8 c_cursorColor = 36u; - - static u32 s_editCursorFlicker = 0; - - void updateEditBox(EditBox* editBox) - { - const char* input = TFE_Input::getBufferedText(); - const s32 len = (s32)strlen(input); - for (s32 c = 0; c < len; c++) - { - insertChar(editBox->inputField, &editBox->cursor, input[c], editBox->maxLen); - } - - const s32 nameLen = (s32)strlen(editBox->inputField); - if (TFE_Input::bufferedKeyDown(KEY_BACKSPACE)) - { - if (editBox->cursor > 0) - { - for (s32 c = editBox->cursor - 1; c < nameLen - 1; c++) - { - editBox->inputField[c] = editBox->inputField[c + 1]; - } - editBox->inputField[nameLen - 1] = 0; - editBox->cursor--; - } - } - else if (TFE_Input::bufferedKeyDown(KEY_DELETE)) - { - if (editBox->cursor < nameLen) - { - for (s32 c = editBox->cursor; c < nameLen - 1; c++) - { - editBox->inputField[c] = editBox->inputField[c + 1]; - } - editBox->inputField[nameLen - 1] = 0; - } - } - - if (TFE_Input::bufferedKeyDown(KEY_LEFT) && editBox->cursor > 0) - { - editBox->cursor--; - } - else if (TFE_Input::bufferedKeyDown(KEY_RIGHT) && editBox->cursor < nameLen) - { - editBox->cursor++; - } - if (TFE_Input::bufferedKeyDown(KEY_HOME)) - { - editBox->cursor = 0; - } - else if (TFE_Input::bufferedKeyDown(KEY_END)) - { - editBox->cursor = nameLen; - } - } - - void drawEditBox(EditBox* editBox, s32 x0, s32 y0, s32 x1, s32 y1, u8* framebuffer) - { - drawHorizontalLine(x0, x1, y0, c_editBoxColor, framebuffer); - drawHorizontalLine(x0, x1, y1, c_editBoxHighlight, framebuffer); - drawVerticalLine(y0 + 1, y1 - 1, x0, c_editBoxColor, framebuffer); - drawVerticalLine(y0 + 1, y1 - 1, x1, c_editBoxColor, framebuffer); - drawColoredQuad(x0 + 1, y0 + 1, x1 - x0 - 1, y1 - y0 - 1, c_editBoxBackground, framebuffer); - print(editBox->inputField, x0 + 4, y0 + 4, c_editBoxText, framebuffer); - if ((s_editCursorFlicker >> 4) & 1) - { - char textToCursor[64]; - strcpy(textToCursor, editBox->inputField); - textToCursor[editBox->cursor] = 0; - s32 drawPos = getStringPixelLength(textToCursor); - drawHorizontalLine(x0 + 4 + drawPos, x0 + 8 + drawPos, y1 - 2, c_cursorColor, framebuffer); - } - s_editCursorFlicker++; - } -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/GameUI/editBox.h b/components/darkforces/tfe/TFE_DarkForces/GameUI/editBox.h deleted file mode 100644 index 05aab74b..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/GameUI/editBox.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// A simple edit box. -////////////////////////////////////////////////////////////////////// -#include -#include - -struct EditBox -{ - char* inputField = nullptr; - s32 cursor = 0; - s32 maxLen = 0; -}; - -namespace TFE_DarkForces -{ - void updateEditBox(EditBox* editBox); - void drawEditBox(EditBox* editBox, s32 x0, s32 y0, s32 x1, s32 y1, u8* framebuffer); -} diff --git a/components/darkforces/tfe/TFE_DarkForces/GameUI/escapeMenu.cpp b/components/darkforces/tfe/TFE_DarkForces/GameUI/escapeMenu.cpp deleted file mode 100644 index fb73d662..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/GameUI/escapeMenu.cpp +++ /dev/null @@ -1,903 +0,0 @@ -#include - -#include "escapeMenu.h" -#include -#include -#include "delt.h" -#include "uiDraw.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; -using namespace TFE_Input; - -namespace TFE_DarkForces -{ - enum ConfirmDlg - { - CONFIRM_NEXT_BG = 0, - CONFIRM_ABORT_BG, - CONFIRM_QUIT_BG, - // Next / Abort - CONFIRM_NEXT_NOBTN_DOWN, - CONFIRM_NEXT_NOBTN_UP, - CONFIRM_NEXT_YESBTN_DOWN, - CONFIRM_NEXT_YESBTN_UP, - // Quit - CONFIRM_QUIT_NOBTN_DOWN, - CONFIRM_QUIT_NOBTN_UP, - CONFIRM_QUIT_YESBTN_DOWN, - CONFIRM_QUIT_YESBTN_UP, - CONFIRM_COUNT - }; - - enum ConfirmState - { - CONFIRM_STATE_NONE = 0, - CONFIRM_STATE_ABORT, - CONFIRM_STATE_NEXT, - CONFIRM_STATE_QUIT, - CONFIRM_STATE_CONT - }; - - enum EscapeButtons - { - ESC_BTN_ABORT, - ESC_BTN_CONFIG, - ESC_BTN_QUIT, - ESC_BTN_RETURN, - ESC_BTN_COUNT - }; - enum ConfirmButtons - { - CONFIRM_NO = 0, - CONFIRM_YES, - CONFIRM_BTN_COUNT - }; - static Vec2i c_escButtons[ESC_BTN_COUNT] = - { - {64, 35}, // ESC_ABORT - {64, 55}, // ESC_CONFIG - {64, 75}, // ESC_QUIT - {64, 99}, // ESC_RETURN - }; - static const Vec2i c_escButtonDim = { 96, 16 }; - static Vec4i s_confirmButtonRange[4]; -#ifdef TFE_ESPBOX - static u32* s_escMenuPalette = nullptr; // 256 entries (shared memory) -#else - static u32 s_escMenuPalette[256]; -#endif - - struct EscapeMenuState - { - JBool escMenuOpen = JFALSE; - - u32 escMenuFrameCount = 0; - DeltFrame* escMenuFrames = nullptr; - - u32 confirmMenuFrameCount = 0; - DeltFrame* confirmMenuFrames = nullptr; - - OffScreenBuffer* framebufferCopy = nullptr; - u8* framebuffer = nullptr; - - Vec2i cursorPosAccum = { 0 }; - Vec2i cursorPos = { 0 }; - s32 buttonPressed = -1; - bool buttonHover = false; - ConfirmState confirmState = CONFIRM_STATE_NONE; - - RenderTargetHandle renderTarget = nullptr; - LangHotkeys* langKeys; - }; - static EscapeMenuState s_emState = {}; - - void escMenu_resetCursor(); - void escMenu_handleMousePosition(); - bool escapeMenu_getTextures(TextureInfoList& texList, AssetPool pool); - void escapeMenu_draw(JBool drawMouse, JBool drawBackground); - EscapeMenuAction escapeMenu_updateUI(); - - extern void pauseLevelSound(); - extern void resumeLevelSound(); - extern void clearBufferedSound(); - - void escapeMenu_resetState() - { - // TFE: GPU Support. - if (s_emState.renderTarget) - { - TFE_RenderBackend::freeRenderTarget(s_emState.renderTarget); - } - - // Free memory - freeOffScreenBuffer(s_emState.framebufferCopy); - - // Clear State. - s_emState = {}; - } - - Vec4i getButtonRange(DeltFrame* frames, s32 index) - { - Vec4i range; - ScreenRect rect; - getDeltaFrameRect(&frames[index], &rect); - range.x = rect.left; - range.y = rect.top; - range.z = rect.right; - range.w = rect.bot; - return range; - } - -#ifdef TFE_ESPBOX - // The escape and confirmation menu frames take ~530KB: load them when the menu - // opens and release them when it closes instead of keeping them for the whole game. - static void escapeMenu_loadFrames(); - static void escapeMenu_freeFrames() - { - DeltFrame* lists[2] = { s_emState.escMenuFrames, s_emState.confirmMenuFrames }; - u32 counts[2] = { s_emState.escMenuFrameCount, s_emState.confirmMenuFrameCount }; - for (s32 l = 0; l < 2; l++) - { - if (!lists[l]) { continue; } - for (u32 i = 0; i < counts[l]; i++) { game_free(lists[l][i].texture.image); } - game_free(lists[l]); - } - s_emState.escMenuFrames = nullptr; - s_emState.confirmMenuFrames = nullptr; - s_emState.escMenuFrameCount = 0; - s_emState.confirmMenuFrameCount = 0; - } - - void escapeMenu_load(LangHotkeys* langKeys) - { - s_emState.langKeys = langKeys; - } - - // The confirmation dialog frames are only needed once the player picks abort, - // next mission or quit; load them then (and release them with the menu). - static bool escapeMenu_loadConfirmFrames() - { - if (s_emState.confirmMenuFrames) { return true; } - FilePath filePath; - if (!TFE_Paths::getFilePath("MENU.LFD", &filePath)) { return false; } - Archive* archive = Archive::getArchive(ARCHIVE_LFD, "MENU", filePath.path); - TFE_Paths::addLocalArchive(archive); - s_emState.confirmMenuFrameCount = getFramesFromAnim("yesno.anim", &s_emState.confirmMenuFrames); - TFE_Paths::removeLastArchive(); - if (!s_emState.confirmMenuFrames) - { - TFE_System::logWrite(LOG_ERROR, "EscapeMenu", "Failed to load the confirmation frames from MENU.LFD."); - s_emState.confirmMenuFrameCount = 0; - return false; - } - s_confirmButtonRange[0] = getButtonRange(s_emState.confirmMenuFrames, CONFIRM_NEXT_NOBTN_DOWN); - s_confirmButtonRange[1] = getButtonRange(s_emState.confirmMenuFrames, CONFIRM_NEXT_YESBTN_DOWN); - s_confirmButtonRange[2] = getButtonRange(s_emState.confirmMenuFrames, CONFIRM_QUIT_NOBTN_DOWN); - s_confirmButtonRange[3] = getButtonRange(s_emState.confirmMenuFrames, CONFIRM_QUIT_YESBTN_DOWN); - return true; - } - - static void escapeMenu_loadFrames() - { - static bool s_layoutAdjusted = false; - if (!s_emState.escMenuFrames) - { -#else - void escapeMenu_load(LangHotkeys* langKeys) - { - s_emState.langKeys = langKeys; - if (!s_emState.escMenuFrames) - { -#endif - u8 paletteBuffer[768] = { 0 }; - - FilePath filePath; - if (!TFE_Paths::getFilePath("MENU.LFD", &filePath)) { return; } - Archive* archive = Archive::getArchive(ARCHIVE_LFD, "MENU", filePath.path); - TFE_Paths::addLocalArchive(archive); - s_emState.escMenuFrameCount = getFramesFromAnim("escmenu.anim", &s_emState.escMenuFrames); -#ifndef TFE_ESPBOX - s_emState.confirmMenuFrameCount = getFramesFromAnim("yesno.anim", &s_emState.confirmMenuFrames); -#endif - loadPaletteFromPltt("menu.pltt", paletteBuffer); - TFE_Paths::removeLastArchive(); -#ifdef TFE_ESPBOX - // The confirmation frames (yesno.anim, 400KB) are loaded when a confirmation - // dialog opens: see escapeMenu_loadConfirmFrames(). - if (!s_emState.escMenuFrames) -#else - if (!s_emState.escMenuFrames || !s_emState.confirmMenuFrames) -#endif - { - TFE_System::logWrite(LOG_ERROR, "EscapeMenu", "Failed to load the escape menu frames from MENU.LFD."); -#ifdef TFE_ESPBOX - escapeMenu_freeFrames(); -#endif - return; - } - - // Adjust button ranges since different languages seem to move the menu around for some reason... -#ifdef TFE_ESPBOX - // The frames are reloaded every time the menu opens: only move the buttons once. - if (!s_layoutAdjusted) -#endif - { - Vec4i range = getButtonRange(s_emState.escMenuFrames, 0); - s32 dx = range.x - 36; - s32 dy = range.y - 25; - for (s32 i = 0; i < ESC_BTN_COUNT; i++) - { - c_escButtons[i].x += dx; - c_escButtons[i].z += dy; - } -#ifdef TFE_ESPBOX - s_layoutAdjusted = true; -#endif - } - - // Get confirmation button positions. -#ifndef TFE_ESPBOX - s_confirmButtonRange[0] = getButtonRange(s_emState.confirmMenuFrames, CONFIRM_NEXT_NOBTN_DOWN); - s_confirmButtonRange[1] = getButtonRange(s_emState.confirmMenuFrames, CONFIRM_NEXT_YESBTN_DOWN); - - s_confirmButtonRange[2] = getButtonRange(s_emState.confirmMenuFrames, CONFIRM_QUIT_NOBTN_DOWN); - s_confirmButtonRange[3] = getButtonRange(s_emState.confirmMenuFrames, CONFIRM_QUIT_YESBTN_DOWN); -#endif - - // TFE -#ifndef TFE_ESPBOX // GPU renderer only, and the frames come and go on this platform. - TFE_Jedi::renderer_addHudTextureCallback(escapeMenu_getTextures); -#endif - - // convert palette to argb entries now since we don't need the raw format anywhere. - u8* pal = paletteBuffer; - for (u32 i = 0; i < 256; i++, pal += 3) - { - s_escMenuPalette[i] = 0xffu << 24 | ((u32)pal[0]) | ((u32)(pal[1]) << 8) | ((u32)pal[2] << 16); - } - } - } - - void escapeMenu_copyBackground(u8* framebuffer, u8* palette) - { - u32 dispWidth, dispHeight; - vfb_getResolution(&dispWidth, &dispHeight); - - if (TFE_Jedi::getSubRenderer() == TSR_CLASSIC_GPU) - { - // 1. Create a render target to hold the frame. - u32 prevWidth = 0, prevHeight = 0; - if (s_emState.renderTarget) - { - TFE_RenderBackend::getRenderTargetDim(s_emState.renderTarget, &prevWidth, &prevHeight); - } - - if (!s_emState.renderTarget || prevWidth != dispWidth || prevHeight != dispHeight) - { - TFE_RenderBackend::freeRenderTarget(s_emState.renderTarget); - s_emState.renderTarget = TFE_RenderBackend::createRenderTarget(dispWidth, dispHeight); - } - - // 2. Blit current frame to the new render target. - TFE_Jedi::endRender(); - TFE_RenderBackend::swap(true); - - TFE_RenderBackend::copyBackbufferToRenderTarget(s_emState.renderTarget); - TFE_RenderBackend::unbindRenderTarget(); - } - else // Software renderer code. - { - if (s_emState.framebufferCopy && (s_emState.framebufferCopy->width != dispWidth || s_emState.framebufferCopy->height != dispHeight)) - { - freeOffScreenBuffer(s_emState.framebufferCopy); - s_emState.framebufferCopy = nullptr; - } - - if (!s_emState.framebufferCopy) - { - s_emState.framebufferCopy = createOffScreenBuffer(dispWidth, dispHeight, OBF_NONE); - } - memcpy(s_emState.framebufferCopy->image, framebuffer, s_emState.framebufferCopy->size); - s_emState.framebuffer = framebuffer; - - // Post process to convert sceen capture to grayscale. - for (s32 i = 0; i < s_emState.framebufferCopy->size; i++) - { - u8 color = s_emState.framebufferCopy->image[i]; - u8* rgb = &palette[color * 3]; - u8 luminance = ((rgb[1] >> 1) + (rgb[0] >> 2) + (rgb[2] >> 2)) >> 1; - s_emState.framebufferCopy->image[i] = 63 - luminance; - } - } - } - - void escapeMenu_open(u8* framebuffer, u8* palette) - { - // TFE - reticle_enable(false); - TFE_RenderBackend::bloomPostEnable(false); - - pauseLevelSound(); -#ifdef TFE_ESPBOX - escapeMenu_loadFrames(); -#endif - s_emState.escMenuOpen = JTRUE; - - escapeMenu_copyBackground(framebuffer, palette); - - escMenu_resetCursor(); - s_emState.buttonPressed = -1; - s_emState.buttonHover = false; - s_emState.confirmState = CONFIRM_STATE_NONE; - } - - void escapeMenu_resetLevel() - { - s_emState.escMenuOpen = JFALSE; -#ifdef TFE_ESPBOX - // A mission that ends from the escape menu (abort / next mission) never closes - // it: release the frames here too, or 533KB stays allocated into the next level. - escapeMenu_freeFrames(); -#endif - } - - void escapeMenu_close() - { - s_emState.escMenuOpen = JFALSE; -#ifdef TFE_ESPBOX - escapeMenu_freeFrames(); -#endif - resumeLevelSound(); - - // TFE - reticle_enable(true); - TFE_RenderBackend::bloomPostEnable(true); - } - - JBool escapeMenu_isOpen() - { - return s_emState.escMenuOpen; - } - - void escapeMenu_addDeltFrame(TextureInfoList& texList, DeltFrame* frame) - { - TextureInfo texInfo = {}; - texInfo.type = TEXINFO_DF_DELT_TEX; - texInfo.texData = &frame->texture; - texList.push_back(texInfo); - } - - bool escapeMenu_getTextures(TextureInfoList& texList, AssetPool pool) - { - for (u32 i = 0; i < s_emState.escMenuFrameCount; i++) - { - escapeMenu_addDeltFrame(texList, &s_emState.escMenuFrames[i]); - } - for (u32 i = 0; i < s_emState.confirmMenuFrameCount; i++) - { - escapeMenu_addDeltFrame(texList, &s_emState.confirmMenuFrames[i]); - } - escapeMenu_addDeltFrame(texList, &s_cursor); - return true; - } - - void escapeMenu_drawGpu(JBool drawMouse, JBool drawBackground) - { - u32 dispWidth, dispHeight; - vfb_getResolution(&dispWidth, &dispHeight); - - const fixed16_16 xScale = vfb_getXScale(); - const fixed16_16 yScale = vfb_getYScale(); - const s32 xOffset = vfb_getWidescreenOffset(); - - // Draw the background. - if (drawBackground) - { - if (xOffset) - { - screenGPU_addImageQuad(0, 0, dispWidth, dispHeight, (TextureGpu*)TFE_RenderBackend::getRenderTargetTexture(s_emState.renderTarget)); - } - else - { - // Adjust the UV coordinates to stretch 4:3 to the full size. - DisplayInfo displayInfo; - TFE_RenderBackend::getDisplayInfo(&displayInfo); - - s32 offsetWidth = displayInfo.height * 4 / 3; - s32 imgOffset = (displayInfo.width - offsetWidth) / 2; - - f32 offset = f32(imgOffset) / f32(displayInfo.width); - f32 u0 = offset; - f32 u1 = 1.0f - offset; - screenGPU_addImageQuad(0, 0, dispWidth, dispHeight, u0, u1, (TextureGpu*)TFE_RenderBackend::getRenderTargetTexture(s_emState.renderTarget)); - } - } - - // Draw the menu. - if (s_emState.confirmState == CONFIRM_STATE_NONE) - { - screenGPU_blitTextureScaled(&s_emState.escMenuFrames[0].texture, nullptr, intToFixed16(xOffset), 0, xScale, yScale, 31); - - if (s_levelComplete) - { - // Attempt to clean up the button positions, note this is only a problem at non-vanilla resolutions. - fixed16_16 yOffset = (dispHeight == 200 || dispHeight == 400) ? 0 : round16(yScale / 2); - - if (s_emState.buttonPressed == ESC_BTN_ABORT && s_emState.buttonHover) - { - screenGPU_blitTextureScaled(&s_emState.escMenuFrames[3].texture, nullptr, intToFixed16(xOffset), yOffset, xScale, yScale, 31); - } - else - { - screenGPU_blitTextureScaled(&s_emState.escMenuFrames[4].texture, nullptr, intToFixed16(xOffset), yOffset, xScale, yScale, 31); - } - } - if ((s_emState.buttonPressed > ESC_BTN_ABORT || (s_emState.buttonPressed == ESC_BTN_ABORT && !s_levelComplete)) && s_emState.buttonHover) - { - // Attempt to clean up the button positions, note this is only a problem at non-vanilla resolutions. - fixed16_16 yOffset = (dispHeight == 200 || dispHeight == 400) ? 0 : round16(yScale / 2); - yOffset = min(yOffset, 3 - s_emState.buttonPressed); - - // Draw the highlight button - const s32 highlightIndices[] = { 1, 7, 9, 5 }; - screenGPU_blitTextureScaled(&s_emState.escMenuFrames[highlightIndices[s_emState.buttonPressed]].texture, nullptr, intToFixed16(xOffset), yOffset, xScale, yScale, 31); - } - } - // Confirmation. - else if (s_emState.confirmState == CONFIRM_STATE_ABORT) - { - screenGPU_blitTextureScaled(&s_emState.confirmMenuFrames[CONFIRM_ABORT_BG].texture, nullptr, intToFixed16(xOffset), 0, xScale, yScale, 31); - screenGPU_blitTextureScaled(&s_emState.confirmMenuFrames[s_emState.buttonPressed == CONFIRM_YES ? CONFIRM_NEXT_YESBTN_DOWN : CONFIRM_NEXT_YESBTN_UP].texture, nullptr, intToFixed16(xOffset), 0, xScale, yScale, 31); - screenGPU_blitTextureScaled(&s_emState.confirmMenuFrames[s_emState.buttonPressed == CONFIRM_NO ? CONFIRM_NEXT_NOBTN_DOWN : CONFIRM_NEXT_NOBTN_UP].texture, nullptr, intToFixed16(xOffset), 0, xScale, yScale, 31); - } - else if (s_emState.confirmState == CONFIRM_STATE_NEXT) - { - screenGPU_blitTextureScaled(&s_emState.confirmMenuFrames[CONFIRM_NEXT_BG].texture, nullptr, intToFixed16(xOffset), 0, xScale, yScale, 31); - screenGPU_blitTextureScaled(&s_emState.confirmMenuFrames[s_emState.buttonPressed == CONFIRM_YES ? CONFIRM_NEXT_YESBTN_DOWN : CONFIRM_NEXT_YESBTN_UP].texture, nullptr, intToFixed16(xOffset), 0, xScale, yScale, 31); - screenGPU_blitTextureScaled(&s_emState.confirmMenuFrames[s_emState.buttonPressed == CONFIRM_NO ? CONFIRM_NEXT_NOBTN_DOWN : CONFIRM_NEXT_NOBTN_UP].texture, nullptr, intToFixed16(xOffset), 0, xScale, yScale, 31); - } - else if (s_emState.confirmState == CONFIRM_STATE_QUIT) - { - screenGPU_blitTextureScaled(&s_emState.confirmMenuFrames[CONFIRM_QUIT_BG].texture, nullptr, intToFixed16(xOffset), 0, xScale, yScale, 31); - screenGPU_blitTextureScaled(&s_emState.confirmMenuFrames[s_emState.buttonPressed == CONFIRM_YES ? CONFIRM_QUIT_YESBTN_DOWN : CONFIRM_QUIT_YESBTN_UP].texture, nullptr, intToFixed16(xOffset), 0, xScale, yScale, 31); - screenGPU_blitTextureScaled(&s_emState.confirmMenuFrames[s_emState.buttonPressed == CONFIRM_NO ? CONFIRM_QUIT_NOBTN_DOWN : CONFIRM_QUIT_NOBTN_UP].texture, nullptr, intToFixed16(xOffset), 0, xScale, yScale, 31); - } - - // Draw the mouse. - if (drawMouse) - { - screenGPU_blitTextureScaled(&s_cursor.texture, nullptr, intToFixed16(s_emState.cursorPos.x), intToFixed16(s_emState.cursorPos.z), xScale, yScale, 31); - } - } - - void escapeMenu_draw(JBool drawMouse, JBool drawBackground) - { -#ifdef TFE_ESPBOX - // The frames are loaded when the menu opens; that can fail when memory is short. - if (!s_emState.escMenuFrames) { return; } - if (s_emState.confirmState != CONFIRM_STATE_NONE && !s_emState.confirmMenuFrames) { return; } -#endif - // TFE Note: handle GPU drawing differently, though the UI update is exactly the same. - if (TFE_Jedi::getSubRenderer() == TSR_CLASSIC_GPU) - { - escapeMenu_drawGpu(drawMouse, drawBackground); - return; - } - - // Draw the screen capture. - ScreenRect* drawRect = vfb_getScreenRect(VFB_RECT_UI); - u32 dispWidth, dispHeight; - vfb_getResolution(&dispWidth, &dispHeight); - - if (dispWidth == 320 && dispHeight == 200) - { - if (drawBackground) - { - hud_drawElementToScreen(s_emState.framebufferCopy, drawRect, 0, 0, s_emState.framebuffer); - } - - if (s_emState.confirmState == CONFIRM_STATE_NONE) - { - // Draw the menu background. - blitDeltaFrame(&s_emState.escMenuFrames[0], 0, 0, s_emState.framebuffer); - - if (s_levelComplete) - { - if (s_emState.buttonPressed == ESC_BTN_ABORT && s_emState.buttonHover) - { - blitDeltaFrame(&s_emState.escMenuFrames[3], 0, 0, s_emState.framebuffer); - } - else - { - blitDeltaFrame(&s_emState.escMenuFrames[4], 0, 0, s_emState.framebuffer); - } - } - if ((s_emState.buttonPressed > ESC_BTN_ABORT || (s_emState.buttonPressed == ESC_BTN_ABORT && !s_levelComplete)) && s_emState.buttonHover) - { - // Draw the highlight button - const s32 highlightIndices[] = { 1, 7, 9, 5 }; - blitDeltaFrame(&s_emState.escMenuFrames[highlightIndices[s_emState.buttonPressed]], 0, 0, s_emState.framebuffer); - } - } - // Confirmation. - else if (s_emState.confirmState == CONFIRM_STATE_ABORT) - { - blitDeltaFrame(&s_emState.confirmMenuFrames[CONFIRM_ABORT_BG], 0, 0, s_emState.framebuffer); - blitDeltaFrame(&s_emState.confirmMenuFrames[s_emState.buttonPressed == CONFIRM_YES ? CONFIRM_NEXT_YESBTN_DOWN : CONFIRM_NEXT_YESBTN_UP], 0, 0, s_emState.framebuffer); - blitDeltaFrame(&s_emState.confirmMenuFrames[s_emState.buttonPressed == CONFIRM_NO ? CONFIRM_NEXT_NOBTN_DOWN : CONFIRM_NEXT_NOBTN_UP], 0, 0, s_emState.framebuffer); - } - else if (s_emState.confirmState == CONFIRM_STATE_NEXT) - { - blitDeltaFrame(&s_emState.confirmMenuFrames[CONFIRM_NEXT_BG], 0, 0, s_emState.framebuffer); - blitDeltaFrame(&s_emState.confirmMenuFrames[s_emState.buttonPressed == CONFIRM_YES ? CONFIRM_NEXT_YESBTN_DOWN : CONFIRM_NEXT_YESBTN_UP], 0, 0, s_emState.framebuffer); - blitDeltaFrame(&s_emState.confirmMenuFrames[s_emState.buttonPressed == CONFIRM_NO ? CONFIRM_NEXT_NOBTN_DOWN : CONFIRM_NEXT_NOBTN_UP], 0, 0, s_emState.framebuffer); - } - else if (s_emState.confirmState == CONFIRM_STATE_QUIT) - { - blitDeltaFrame(&s_emState.confirmMenuFrames[CONFIRM_QUIT_BG], 0, 0, s_emState.framebuffer); - blitDeltaFrame(&s_emState.confirmMenuFrames[s_emState.buttonPressed == CONFIRM_YES ? CONFIRM_QUIT_YESBTN_DOWN : CONFIRM_QUIT_YESBTN_UP], 0, 0, s_emState.framebuffer); - blitDeltaFrame(&s_emState.confirmMenuFrames[s_emState.buttonPressed == CONFIRM_NO ? CONFIRM_QUIT_NOBTN_DOWN : CONFIRM_QUIT_NOBTN_UP], 0, 0, s_emState.framebuffer); - } - - // Draw the mouse. - blitDeltaFrame(&s_cursor, s_emState.cursorPos.x, s_emState.cursorPos.z, s_emState.framebuffer); - } - else - { - const fixed16_16 xScale = vfb_getXScale(); - const fixed16_16 yScale = vfb_getYScale(); - const s32 xOffset = vfb_getWidescreenOffset(); - - if (drawBackground) - { - hud_drawElementToScreen(s_emState.framebufferCopy, drawRect, 0, 0, s_emState.framebuffer); - } - - if (s_emState.confirmState == CONFIRM_STATE_NONE) - { - // Draw the menu background. - blitDeltaFrameScaled(&s_emState.escMenuFrames[0], xOffset, 0, xScale, yScale, s_emState.framebuffer); - - if (s_levelComplete) - { - // Attempt to clean up the button positions, note this is only a problem at non-vanilla resolutions. - fixed16_16 yOffset = (dispHeight == 200 || dispHeight == 400) ? 0 : round16(yScale / 2); - - if (s_emState.buttonPressed == ESC_BTN_ABORT && s_emState.buttonHover) - { - blitDeltaFrameScaled(&s_emState.escMenuFrames[3], xOffset, yOffset, xScale, yScale, s_emState.framebuffer); - } - else - { - blitDeltaFrameScaled(&s_emState.escMenuFrames[4], xOffset, yOffset, xScale, yScale, s_emState.framebuffer); - } - } - if ((s_emState.buttonPressed > ESC_BTN_ABORT || (s_emState.buttonPressed == ESC_BTN_ABORT && !s_levelComplete)) && s_emState.buttonHover) - { - // Attempt to clean up the button positions, note this is only a problem at non-vanilla resolutions. - fixed16_16 yOffset = (dispHeight == 200 || dispHeight == 400) ? 0 : round16(yScale / 2); - yOffset = min(yOffset, 3 - s_emState.buttonPressed); - - // Draw the highlight button - const s32 highlightIndices[] = { 1, 7, 9, 5 }; - blitDeltaFrameScaled(&s_emState.escMenuFrames[highlightIndices[s_emState.buttonPressed]], xOffset, yOffset, xScale, yScale, s_emState.framebuffer); - } - } - // Confirmation. - else if (s_emState.confirmState == CONFIRM_STATE_ABORT) - { - blitDeltaFrameScaled(&s_emState.confirmMenuFrames[CONFIRM_ABORT_BG], xOffset, 0, xScale, yScale, s_emState.framebuffer); - blitDeltaFrameScaled(&s_emState.confirmMenuFrames[s_emState.buttonPressed == CONFIRM_YES ? CONFIRM_NEXT_YESBTN_DOWN : CONFIRM_NEXT_YESBTN_UP], xOffset, 0, xScale, yScale, s_emState.framebuffer); - blitDeltaFrameScaled(&s_emState.confirmMenuFrames[s_emState.buttonPressed == CONFIRM_NO ? CONFIRM_NEXT_NOBTN_DOWN : CONFIRM_NEXT_NOBTN_UP], xOffset, 0, xScale, yScale, s_emState.framebuffer); - } - else if (s_emState.confirmState == CONFIRM_STATE_NEXT) - { - blitDeltaFrameScaled(&s_emState.confirmMenuFrames[CONFIRM_NEXT_BG], xOffset, 0, xScale, yScale, s_emState.framebuffer); - blitDeltaFrameScaled(&s_emState.confirmMenuFrames[s_emState.buttonPressed == CONFIRM_YES ? CONFIRM_NEXT_YESBTN_DOWN : CONFIRM_NEXT_YESBTN_UP], xOffset, 0, xScale, yScale, s_emState.framebuffer); - blitDeltaFrameScaled(&s_emState.confirmMenuFrames[s_emState.buttonPressed == CONFIRM_NO ? CONFIRM_NEXT_NOBTN_DOWN : CONFIRM_NEXT_NOBTN_UP], xOffset, 0, xScale, yScale, s_emState.framebuffer); - } - else if (s_emState.confirmState == CONFIRM_STATE_QUIT) - { - blitDeltaFrameScaled(&s_emState.confirmMenuFrames[CONFIRM_QUIT_BG], xOffset, 0, xScale, yScale, s_emState.framebuffer); - blitDeltaFrameScaled(&s_emState.confirmMenuFrames[s_emState.buttonPressed == CONFIRM_YES ? CONFIRM_QUIT_YESBTN_DOWN : CONFIRM_QUIT_YESBTN_UP], xOffset, 0, xScale, yScale, s_emState.framebuffer); - blitDeltaFrameScaled(&s_emState.confirmMenuFrames[s_emState.buttonPressed == CONFIRM_NO ? CONFIRM_QUIT_NOBTN_DOWN : CONFIRM_QUIT_NOBTN_UP], xOffset, 0, xScale, yScale, s_emState.framebuffer); - } - - // Draw the mouse. - if (drawMouse) - { - blitDeltaFrameScaled(&s_cursor, s_emState.cursorPos.x, s_emState.cursorPos.z, xScale, yScale, s_emState.framebuffer); - } - } - } - - EscapeMenuAction escapeMenu_update() - { - vfb_setPalette(s_escMenuPalette); - - EscapeMenuAction action = escapeMenu_updateUI(); - if (action != ESC_CONTINUE) - { - s_emState.escMenuOpen = JFALSE; - // Avoid sound pops due to buffered sound when returning to the Agent or Main menu. - if (!s_levelComplete || action != ESC_ABORT_OR_NEXT) - { - clearBufferedSound(); - } - resumeLevelSound(); - - // TFE - reticle_enable(true); - TFE_RenderBackend::bloomPostEnable(true); - } - - escapeMenu_draw(JTRUE, JTRUE); -#ifdef TFE_ESPBOX - // Closing through an action (abort / next mission / quit) does not go through - // escapeMenu_close(): release the frames here as well. - if (action != ESC_CONTINUE) { escapeMenu_freeFrames(); } -#endif - return action; - } - - /////////////////////////////////////// - // Internal - /////////////////////////////////////// - EscapeMenuAction escapeMenu_handleAction(EscapeMenuAction action, s32 actionPressed) - { - if (s_emState.confirmState == CONFIRM_STATE_NONE) - { - if (actionPressed < 0) - { - // Handle keyboard shortcuts. - if ((TFE_Input::keyPressed(KEY_A) && !s_levelComplete) || (TFE_Input::keyPressed(KEY_N) && s_levelComplete)) - { - actionPressed = ESC_BTN_ABORT; - } - if (TFE_Input::keyPressed(s_emState.langKeys->k_conf)) - { - actionPressed = ESC_BTN_CONFIG; - } - if (TFE_Input::keyPressed(s_emState.langKeys->k_quit)) - { - actionPressed = ESC_BTN_QUIT; - } - if (TFE_Input::keyPressed(s_emState.langKeys->k_cont)) - { - actionPressed = ESC_BTN_RETURN; - } - } - - switch (actionPressed) - { - case ESC_BTN_ABORT: - s_emState.confirmState = s_levelComplete ? CONFIRM_STATE_NEXT : CONFIRM_STATE_ABORT; -#ifdef TFE_ESPBOX - if (!escapeMenu_loadConfirmFrames()) { s_emState.confirmState = CONFIRM_STATE_NONE; } -#endif - break; - case ESC_BTN_CONFIG: - action = ESC_CONFIG; - break; - case ESC_BTN_QUIT: - s_emState.confirmState = CONFIRM_STATE_QUIT; -#ifdef TFE_ESPBOX - if (!escapeMenu_loadConfirmFrames()) { s_emState.confirmState = CONFIRM_STATE_NONE; } -#endif - break; - case ESC_BTN_RETURN: - action = ESC_RETURN; - break; - }; - } - else - { - if (actionPressed < 0) - { - if (TFE_Input::keyPressed(s_emState.langKeys->k_yes)) - { - actionPressed = CONFIRM_YES; - } - else if (TFE_Input::keyPressed(KEY_N)) - { - actionPressed = CONFIRM_NO; - } - else if (TFE_Input::keyPressed(KEY_RETURN)) - { - actionPressed = s_emState.confirmState == CONFIRM_STATE_NEXT ? CONFIRM_YES : CONFIRM_NO; - } - else if (TFE_Input::keyPressed(KEY_ESCAPE)) - { - actionPressed = CONFIRM_NO; - } - } - switch (actionPressed) - { - case CONFIRM_YES: - if (s_emState.confirmState == CONFIRM_STATE_ABORT || s_emState.confirmState == CONFIRM_STATE_NEXT) - { - action = ESC_ABORT_OR_NEXT; - } - else - { - action = ESC_QUIT; - } - break; - case CONFIRM_NO: - s_emState.confirmState = CONFIRM_STATE_NONE; - break; - }; - s_emState.buttonHover = false; - s_emState.buttonPressed = -1; - } - return action; - } - - EscapeMenuAction escapeMenu_updateUI() - { - EscapeMenuAction action = ESC_CONTINUE; - escMenu_handleMousePosition(); - if (inputMapping_getActionState(IADF_MENU_TOGGLE) == STATE_PRESSED || TFE_Input::keyPressed(KEY_ESCAPE)) - { - action = ESC_RETURN; - s_emState.escMenuOpen = JFALSE; - } - - s32 x = s_emState.cursorPos.x; - s32 z = s_emState.cursorPos.z; - - // Move into "UI space" - fixed16_16 xScale = vfb_getXScale(); - fixed16_16 yScale = vfb_getYScale(); - x = floor16(div16(intToFixed16(x - vfb_getWidescreenOffset()), xScale)); - z = floor16(div16(intToFixed16(z), yScale)); - - if (TFE_Input::mousePressed(MBUTTON_LEFT)) - { - s_emState.buttonPressed = -1; - if (s_emState.confirmState == CONFIRM_STATE_NONE) - { - for (u32 i = 0; i < ESC_BTN_COUNT; i++) - { - if (x >= c_escButtons[i].x && x < c_escButtons[i].x + c_escButtonDim.x && - z >= c_escButtons[i].z && z < c_escButtons[i].z + c_escButtonDim.z) - { - s_emState.buttonPressed = s32(i); - s_emState.buttonHover = true; - break; - } - } - } - else if (s_emState.confirmState == CONFIRM_STATE_ABORT || s_emState.confirmState == CONFIRM_STATE_NEXT) - { - for (u32 i = 0; i < 2; i++) - { - if (x >= s_confirmButtonRange[i].x && x < s_confirmButtonRange[i].z && - z >= s_confirmButtonRange[i].y && z < s_confirmButtonRange[i].w) - { - s_emState.buttonPressed = s32(i); - s_emState.buttonHover = true; - break; - } - } - } - else - { - for (u32 i = 0; i < 2; i++) - { - if (x >= s_confirmButtonRange[i+2].x && x < s_confirmButtonRange[i+2].z && - z >= s_confirmButtonRange[i+2].y && z < s_confirmButtonRange[i+2].w) - { - s_emState.buttonPressed = s32(i); - s_emState.buttonHover = true; - break; - } - } - } - } - else if (TFE_Input::mouseDown(MBUTTON_LEFT) && s_emState.confirmState == CONFIRM_STATE_NONE && s_emState.buttonPressed >= 0) - { - s_emState.buttonHover = false; - // Verify that the mouse is still over the button. - if (x >= c_escButtons[s_emState.buttonPressed].x && x < c_escButtons[s_emState.buttonPressed].x + c_escButtonDim.x && - z >= c_escButtons[s_emState.buttonPressed].z && z < c_escButtons[s_emState.buttonPressed].z + c_escButtonDim.z) - { - s_emState.buttonHover = true; - } - } - else if (TFE_Input::mouseDown(MBUTTON_LEFT) && (s_emState.confirmState == CONFIRM_STATE_ABORT || s_emState.confirmState == CONFIRM_STATE_NEXT) && s_emState.buttonPressed >= 0) - { - s_emState.buttonHover = false; - if (x >= s_confirmButtonRange[s_emState.buttonPressed].x && x < s_confirmButtonRange[s_emState.buttonPressed].z && - z >= s_confirmButtonRange[s_emState.buttonPressed].y && z < s_confirmButtonRange[s_emState.buttonPressed].w) - { - s_emState.buttonHover = true; - } - } - else if (TFE_Input::mouseDown(MBUTTON_LEFT) && s_emState.confirmState == CONFIRM_STATE_QUIT && s_emState.buttonPressed >= 0) - { - s_emState.buttonHover = false; - if (x >= s_confirmButtonRange[s_emState.buttonPressed+2].x && x < s_confirmButtonRange[s_emState.buttonPressed+2].z && - z >= s_confirmButtonRange[s_emState.buttonPressed+2].y && z < s_confirmButtonRange[s_emState.buttonPressed+2].w) - { - s_emState.buttonHover = true; - } - } - else - { - action = escapeMenu_handleAction(action, (s_emState.buttonPressed >= 0 && s_emState.buttonHover) ? s_emState.buttonPressed : -1); - // Reset. - s_emState.buttonPressed = -1; - s_emState.buttonHover = false; - } - - return action; - } - - // The cursor is handled independently for the Escape Menu for now so it can later handle - // widescreen. However, it may be better to merge these functions anyway. - void escMenu_resetCursor() - { - // Reset the cursor. - u32 width, height; - vfb_getResolution(&width, &height); - - DisplayInfo displayInfo; - TFE_RenderBackend::getDisplayInfo(&displayInfo); - - s_emState.cursorPosAccum = { (s32)displayInfo.width >> 1, (s32)displayInfo.height >> 1 }; - s_emState.cursorPos.x = clamp(s_emState.cursorPosAccum.x * (s32)height / (s32)displayInfo.height, 0, (s32)width - 3); - s_emState.cursorPos.z = clamp(s_emState.cursorPosAccum.z * (s32)height / (s32)displayInfo.height, 0, (s32)height - 3); - } - - void escMenu_handleMousePosition() - { - DisplayInfo displayInfo; - TFE_RenderBackend::getDisplayInfo(&displayInfo); - - u32 width, height; - vfb_getResolution(&width, &height); - - s32 dx, dy; - TFE_Input::getAccumulatedMouseMove(&dx, &dy); - - MonitorInfo monitorInfo; - TFE_RenderBackend::getCurrentMonitorInfo(&monitorInfo); - - s32 mx, my; - TFE_Input::getMousePos(&mx, &my); - s_emState.cursorPosAccum = { mx, my }; - - if (displayInfo.width >= displayInfo.height) - { - s_emState.cursorPos.x = clamp(s_emState.cursorPosAccum.x * (s32)height / (s32)displayInfo.height, 0, (s32)width - 3); - s_emState.cursorPos.z = clamp(s_emState.cursorPosAccum.z * (s32)height / (s32)displayInfo.height, 0, (s32)height - 3); - } - else - { - s_emState.cursorPos.x = clamp(s_emState.cursorPosAccum.x * (s32)width / (s32)displayInfo.width, 0, (s32)width - 3); - s_emState.cursorPos.z = clamp(s_emState.cursorPosAccum.z * (s32)width / (s32)displayInfo.width, 0, (s32)height - 3); - } - } -} -#ifdef TFE_ESPBOX -void espbox_shared_escapeMenu(bool alloc) -{ - ESPBOX_SHARED_ALLOC(TFE_DarkForces::s_escMenuPalette, 256); -} -#endif diff --git a/components/darkforces/tfe/TFE_DarkForces/GameUI/escapeMenu.h b/components/darkforces/tfe/TFE_DarkForces/GameUI/escapeMenu.h deleted file mode 100644 index c004d0be..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/GameUI/escapeMenu.h +++ /dev/null @@ -1,39 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Note this is still the original TFE code, reverse-engineered game -// UI code will not be available until future releases. -////////////////////////////////////////////////////////////////////// - -#include -#include - -enum EscapeMenuAction -{ - ESC_CONTINUE = 0, // the menu is still open. - ESC_RETURN, // return to the game. - ESC_ABORT_OR_NEXT, // abort the current mission or move on to the next. - ESC_QUIT, // quit the game. - ESC_CONFIG, // configuration menu. - ESC_COUNT -}; - -namespace TFE_DarkForces -{ - // Preload. - void escapeMenu_load(LangHotkeys* hotkeys); - - // Opens the escape menu, which sets up the background. - void escapeMenu_open(u8* framebuffer, u8* palette); - void escapeMenu_close(); - void escapeMenu_resetLevel(); - - // Returns JTRUE if the escape menu is open. - JBool escapeMenu_isOpen(); - - // Returns ESC_CONTINUE if the menu is still running, - // otherwise the menu has been closed. - EscapeMenuAction escapeMenu_update(); - - // Reset Persistent state - void escapeMenu_resetState(); -} diff --git a/components/darkforces/tfe/TFE_DarkForces/GameUI/menu.cpp b/components/darkforces/tfe/TFE_DarkForces/GameUI/menu.cpp deleted file mode 100644 index e38eda6f..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/GameUI/menu.cpp +++ /dev/null @@ -1,203 +0,0 @@ -#include - -#include "menu.h" -#include "delt.h" -#include "uiDraw.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - /////////////////////////////////////////// - // Internal State - /////////////////////////////////////////// - static LfdArchive s_archive; - - Vec2i s_cursorPosAccum; - Vec2i s_cursorPos; - s32 s_buttonPressed = -1; - JBool s_buttonHover = JFALSE; - - /////////////////////////////////////////// - // API Implementation - /////////////////////////////////////////// - void menu_init() - { - } - - void menu_destroy() - { - menu_resetState(); - } - - void menu_resetState() - { - delt_resetState(); - } - - void menu_handleMousePosition() - { - DisplayInfo displayInfo; - TFE_RenderBackend::getDisplayInfo(&displayInfo); - - LRect bounds; - lcanvas_getBounds(&bounds); - s32 width = bounds.right - bounds.left; - s32 height = bounds.bottom - bounds.top; - - s32 mx, my; - TFE_Input::getMousePos(&mx, &my); -#ifdef TFE_ESPBOX - s_cursorPosAccum = { mx, my }; -#else - s_cursorPosAccum = { 12*mx/10, my }; // Account for 320x200 in 4:3 scaling. -#endif - - if (displayInfo.width >= displayInfo.height) - { - s_cursorPos.x = clamp(s_cursorPosAccum.x * (s32)height / (s32)displayInfo.height, 0, (s32)width - 3); - s_cursorPos.z = clamp(s_cursorPosAccum.z * (s32)height / (s32)displayInfo.height, 0, (s32)height - 3); - } - else - { - s_cursorPos.x = clamp(s_cursorPosAccum.x * (s32)width / (s32)displayInfo.width, 0, (s32)width - 3); - s_cursorPos.z = clamp(s_cursorPosAccum.z * (s32)width / (s32)displayInfo.width, 0, (s32)height - 3); - } - } - - void menu_resetCursor() - { - // Reset the cursor. - u32 width, height; - vfb_getResolution(&width, &height); - - DisplayInfo displayInfo; - TFE_RenderBackend::getDisplayInfo(&displayInfo); - - s_cursorPosAccum = { (s32)displayInfo.width >> 1, (s32)displayInfo.height >> 1 }; - s_cursorPos.x = clamp(s_cursorPosAccum.x * (s32)height / (s32)displayInfo.height, 0, (s32)width - 3); - s_cursorPos.z = clamp(s_cursorPosAccum.z * (s32)height / (s32)displayInfo.height, 0, (s32)height - 3); - } - - u8* menu_startupDisplay() - { - vfb_setResolution(320, 200); - return vfb_getCpuBuffer(); - } - - void menu_blitCursor(s32 x, s32 y, u8* framebuffer) - { - blitDeltaFrame(&s_cursor, x, y, framebuffer); - } - - JBool menu_openResourceArchive(const char* name) - { - FilePath lfdPath; - if (!TFE_Paths::getFilePath(name, &lfdPath)) - { - return JFALSE; - } - // Load the mission briefing text. - if (!s_archive.open(lfdPath.path)) - { - return JFALSE; - } - TFE_Paths::addLocalArchive(&s_archive); - return JTRUE; - } - - void menu_closeResourceArchive() - { - s_archive.close(); - TFE_Paths::removeLastArchive(); - } - - void menu_blitToScreen(u8* framebuffer/*=nullptr*/, JBool transparent/*=JFALSE*/, JBool swap/*=JTRUE*/) - { - u32 outWidth, outHeight; - vfb_getResolution(&outWidth, &outHeight); - - // If there is no override, the default behavior is to use the Landru bitmap. - if (!framebuffer) - { - framebuffer = ldraw_getBitmap(); - } - - if (outWidth == 320 && outHeight == 200) - { - if (transparent) - { - TFE_Jedi::ScreenImage canvas = - { - 320, - 200, - framebuffer, - transparent, - JFALSE, - }; - ScreenRect* uiRect = vfb_getScreenRect(VFB_RECT_UI); - blitTextureToScreen(&canvas, (DrawRect*)uiRect, 0, 0, vfb_getCpuBuffer()); - } - else - { - // This is a straight copy - best for performance since the GPU can do the upscale. - memcpy(vfb_getCpuBuffer(), framebuffer, 320 * 200); - } - } - else - { - // This version requires a software upscale, this is handy when some parts need to be higher resolution or - // to avoid switching virtual framebuffers during play. - TFE_Jedi::ScreenImage canvas = - { - 320, - 200, - framebuffer, - transparent, - JFALSE, - }; - ScreenRect* uiRect = vfb_getScreenRect(VFB_RECT_UI); - fixed16_16 xScale = vfb_getXScale(); - fixed16_16 yScale = vfb_getYScale(); - - s32 virtualWidth = floor16(mul16(intToFixed16(320), xScale)); - s32 offset = max(0, ((uiRect->right - uiRect->left + 1) - virtualWidth) / 2); - - if (!transparent) - { - memset(vfb_getCpuBuffer(), 0, outWidth * outHeight); - } - blitTextureToScreenScaled(&canvas, (DrawRect*)uiRect, offset, 0, xScale, yScale, vfb_getCpuBuffer()); - } - if (swap) { vfb_swap(); } - } - - void menu_blitCursorScaled(s16 x, s16 y, u8* buffer) - { - ScreenRect* uiRect = vfb_getScreenRect(VFB_RECT_UI); - fixed16_16 xScale = vfb_getXScale(); - fixed16_16 yScale = vfb_getYScale(); - - s32 virtualWidth = floor16(mul16(intToFixed16(320), xScale)); - s32 offset = max(0, ((uiRect->right - uiRect->left + 1) - virtualWidth) / 2); - - x = floor16(mul16(intToFixed16(x), xScale)) + offset; - y = floor16(mul16(intToFixed16(y), yScale)); - - blitDeltaFrameScaled(&s_cursor, x, y, xScale, yScale, buffer); - } -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/GameUI/menu.h b/components/darkforces/tfe/TFE_DarkForces/GameUI/menu.h deleted file mode 100644 index 9675689a..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/GameUI/menu.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// General Dark Forces shared menu code. -////////////////////////////////////////////////////////////////////// - -#include -#include - -namespace TFE_DarkForces -{ - void menu_init(); - void menu_destroy(); - void menu_resetState(); - - void menu_handleMousePosition(); - void menu_blitCursor(s32 x, s32 y, u8* framebuffer); - void menu_resetCursor(); - u8* menu_startupDisplay(); - - JBool menu_openResourceArchive(const char* name); - void menu_closeResourceArchive(); - - // 'framebuffer' can be passed in to override the default source bitmap. - // If null, the Landru bitmap will be used. - void menu_blitToScreen(u8* framebuffer = nullptr, JBool transparent = JFALSE, JBool swap = JTRUE); - void menu_blitCursorScaled(s16 x, s16 y, u8* buffer); - - // Variables. - extern Vec2i s_cursorPos; - extern s32 s_buttonPressed; - extern JBool s_buttonHover; -} diff --git a/components/darkforces/tfe/TFE_DarkForces/GameUI/missionBriefing.cpp b/components/darkforces/tfe/TFE_DarkForces/GameUI/missionBriefing.cpp deleted file mode 100644 index 82ecdb8c..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/GameUI/missionBriefing.cpp +++ /dev/null @@ -1,438 +0,0 @@ -#include - -#include "missionBriefing.h" -#include "menu.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - /////////////////////////////////////////// - // Constants - /////////////////////////////////////////// - enum BriefingButton - { - BRIEF_BTN_OK = 0, - BRIEF_BTN_UP, - BRIEF_BTN_DOWN, - BRIEF_BTN_CANCEL, - BRIEF_BTN_EASY, - BRIEF_BTN_MEDIUM, - BRIEF_BTN_HARD, - BRIEF_BTN_COUNT, - }; - static s32 s_keyPressed = -1; - static JBool s_briefingOpen = JFALSE; - static s32 s_skill = 0; - static LRect s_briefRect = { 25, 15, 155, 305 }; - static LRect s_missionTextRect; - static LRect s_viewBounds; - static LActor* s_briefActor = nullptr; - static LActor* s_menuActor = nullptr; - static LPalette* s_palette = nullptr; - static u8* s_framebuffer = nullptr; - static LangHotkeys* s_langKeys; - - s16 s_briefY; - s32 s_briefingMaxY; - LRect s_overlayRect; - - enum - { - MENU_TYPE_BACK = 200, - MENU_TYPE_OVERLAY = 201, - }; - - static const s16 c_frameTypes[] = - { - MENU_TYPE_BACK, - MENU_TYPE_OVERLAY, - -1, // MENU_TYPE_BUTTON, - -1, // MENU_TYPE_BUTTON_UP, - -1, // MENU_TYPE_REPEAT_BUTTON, - -1, // MENU_TYPE_BUTTON_UP, - -1, // MENU_TYPE_REPEAT_BUTTON, - -1, // MENU_TYPE_BUTTON_UP, - -1, // MENU_TYPE_BUTTON, - -1, // MENU_TYPE_BUTTON_UP, - -1, // MENU_TYPE_BUTTON, - -1, // MENU_TYPE_BUTTON_UP, - -1, // MENU_TYPE_BUTTON, - -1, // MENU_TYPE_BUTTON_UP, - -1, // MENU_TYPE_BUTTON, - -1, // MENU_TYPE_BUTTON_UP, - }; - - /////////////////////////////////////////// - // API Implementation - /////////////////////////////////////////// - void missionBriefing_start(const char* archive, const char* bgAnim, const char* mission, const char* palette, s32 skill, LangHotkeys* langKeys) - { - s_langKeys = langKeys; - - menu_init(); - menu_startupDisplay(); - - s_briefingOpen = JFALSE; - s_skill = skill; - - if (!menu_openResourceArchive(archive)) - { - // Try the dfbrief.lfd file. - if (!menu_openResourceArchive("dfbrief.lfd")) - { - return; - } - } - - // Mission specific text and images. - s_briefActor = lactorDelt_load(mission, &s_briefRect, 0, 0, 0); - if (!s_briefActor) - { - menu_closeResourceArchive(); - return; - } - - // Menu Items - LRect bounds; - lcanvas_getBounds(&bounds); - s_menuActor = lactorAnim_load(bgAnim, &bounds, 0, 0, 0); - lactor_setTime(s_menuActor, -1, -1); - s_palette = lpalette_load(palette); - lpalette_setScreenPal(s_palette); - - if (!s_menuActor) - { - menu_closeResourceArchive(); - s_briefingOpen = JFALSE; - s_skill = 1; - vfb_forceToBlack(); - lcanvas_clear(); - return; - } - - s16 state_btn_index = 600; - s16 button_index = 0; - s16 slider_index = 0; - s16 back_state = -1; - s16 overlay_state = -1; - - // Buttons - const s32 count = s_menuActor ? s_menuActor->arraySize : 0; - for (s32 i = 0; i < count; i++) - { - LRect rect; - lactor_setState(s_menuActor, i, 0); - lactor_getFrame(s_menuActor, &rect); - - if (c_frameTypes[i] == MENU_TYPE_BACK) - { - back_state = i; - } - else if (c_frameTypes[i] == MENU_TYPE_OVERLAY) - { - overlay_state = i; - lactorAnim_getFrame(s_menuActor, &s_missionTextRect); - } - } - menu_closeResourceArchive(); - - LRect rect; - lactor_setTime(s_briefActor, -1, -1); - lactorDelt_getFrame(s_briefActor, &rect); - - s_briefingMaxY = (rect.bottom - rect.top) - (s_briefRect.bottom - s_briefRect.top) + BRIEF_VERT_MARGIN; - // Round to a factor of the line scrolling value. - s_briefingMaxY = s_briefingMaxY + BRIEF_LINE_SCROLL - (s_briefingMaxY % BRIEF_LINE_SCROLL); - - if (s_briefingMaxY < -BRIEF_VERT_MARGIN) - { - s_briefingMaxY = -BRIEF_VERT_MARGIN; - } - s_overlayRect = s_briefRect; - s_briefY = -BRIEF_VERT_MARGIN; - - s_briefingOpen = JTRUE; - - s_framebuffer = ldraw_getBitmap(); - lcanvas_getBounds(&s_viewBounds); - - ltime_setFrameDelay(20); - } - - void missionBriefing_cleanup() - { - lactor_removeActor(s_briefActor); - lactor_removeActor(s_menuActor); - - lactor_free(s_briefActor); - lactor_free(s_menuActor); - lpalette_free(s_palette); - - s_briefActor = nullptr; - s_menuActor = nullptr; - s_palette = nullptr; - } - - void drawButton(BriefingButton id) - { - s32 pressed = 0; - if ((s_buttonHover && id == s_buttonPressed) || (id == s_keyPressed)) - { - pressed = 1; - } - else if (id >= BRIEF_BTN_EASY && s_skill == id - BRIEF_BTN_EASY) - { - pressed = 1; - } - - lactor_setState(s_menuActor, 2*(1+id) + (pressed ? 0 : 1), 0); - lactorAnim_draw(s_menuActor, &s_viewBounds, &s_viewBounds, 0, 0, JTRUE); - } - - void missionBriefing_scroll(s32 amt) - { - if (amt < 0 && s_briefY > -BRIEF_VERT_MARGIN) - { - s_briefY += amt; - if (s_briefY < -BRIEF_VERT_MARGIN) { s_briefY = -BRIEF_VERT_MARGIN; } - } - else if (amt > 0 && s_briefY != s_briefingMaxY) - { - s_briefY += amt; - if (s_briefY > s_briefingMaxY) { s_briefY = s_briefingMaxY; } - } - } - - JBool missionBriefing_handleInput(JBool* abort) - { - JBool exitBriefing = JFALSE; - - // Add support for mouse wheel scrolling. - s32 wdx, wdy; - TFE_Input::getMouseWheel(&wdx, &wdy); - - // Mouse interactions. - menu_handleMousePosition(); - if (TFE_Input::mousePressed(MBUTTON_LEFT)) - { - s_buttonPressed = -1; - for (s32 i = 0; i < BRIEF_BTN_COUNT; i++) - { - lactor_setState(s_menuActor, 2 * (1 + i), 0); - LRect buttonRect; - lactorAnim_getFrame(s_menuActor, &buttonRect); - - if (s_cursorPos.x >= buttonRect.left && s_cursorPos.x < buttonRect.right && - s_cursorPos.z >= buttonRect.top && s_cursorPos.z < buttonRect.bottom) - { - s_buttonPressed = s32(i); - s_buttonHover = JTRUE; - break; - } - } - } - else if (TFE_Input::mouseDown(MBUTTON_LEFT) && s_buttonPressed >= 0) - { - lactor_setState(s_menuActor, 2 * (1 + s_buttonPressed), 0); - LRect buttonRect; - lactorAnim_getFrame(s_menuActor, &buttonRect); - - // Verify that the mouse is still over the button. - if (s_cursorPos.x >= buttonRect.left && s_cursorPos.x < buttonRect.right && - s_cursorPos.z >= buttonRect.top && s_cursorPos.z < buttonRect.bottom) - { - s_buttonHover = JTRUE; - if (ltime_isFrameReady()) - { - if (s_buttonPressed == BRIEF_BTN_UP) - { - missionBriefing_scroll(-BRIEF_LINE_SCROLL); - } - else if (s_buttonPressed == BRIEF_BTN_DOWN) - { - missionBriefing_scroll(BRIEF_LINE_SCROLL); - } - } - } - else - { - s_buttonHover = JFALSE; - } - } - else - { - // Mouse wheel support. - if (wdy > 0) // up - { - missionBriefing_scroll(-BRIEF_LINE_SCROLL * wdy); - } - else if (wdy < 0) // down - { - missionBriefing_scroll(-BRIEF_LINE_SCROLL * wdy); - } - - if (s_buttonPressed >= 0 && s_buttonHover) - { - switch (s_buttonPressed) - { - case BRIEF_BTN_OK: - { - *abort = JFALSE; - exitBriefing = JTRUE; - } break; - case BRIEF_BTN_UP: - { - missionBriefing_scroll(-BRIEF_LINE_SCROLL); - } break; - case BRIEF_BTN_DOWN: - { - missionBriefing_scroll(BRIEF_LINE_SCROLL); - } break; - case BRIEF_BTN_CANCEL: - { - *abort = JTRUE; - exitBriefing = JTRUE; - } break; - case BRIEF_BTN_EASY: - { - s_skill = 0; - } break; - case BRIEF_BTN_MEDIUM: - { - s_skill = 1; - } break; - case BRIEF_BTN_HARD: - { - s_skill = 2; - } break; - } - } - // Reset. - s_buttonPressed = -1; - s_buttonHover = JFALSE; - } - - // Keyboard shortcuts. - - // These need to be timer limited so that the scrolling works correctly. - if (ltime_isFrameReady()) - { - s_keyPressed = -1; - if (TFE_Input::keyDown(KEY_UP)) - { - s_keyPressed = BRIEF_BTN_UP; - missionBriefing_scroll(-BRIEF_LINE_SCROLL); - } - else if (TFE_Input::keyDown(KEY_DOWN)) - { - s_keyPressed = BRIEF_BTN_DOWN; - missionBriefing_scroll(BRIEF_LINE_SCROLL); - } - - if (TFE_Input::keyDown(KEY_PAGEUP)) - { - missionBriefing_scroll(-BRIEF_PAGE_SCROLL); - } - else if (TFE_Input::keyDown(KEY_PAGEDOWN)) - { - missionBriefing_scroll(BRIEF_PAGE_SCROLL); - } - } - - if (TFE_Input::keyPressed(s_langKeys->k_easy)) - { - s_keyPressed = BRIEF_BTN_EASY; - s_skill = 0; - } - else if (TFE_Input::keyPressed(s_langKeys->k_med)) - { - s_keyPressed = BRIEF_BTN_MEDIUM; - s_skill = 1; - } - else if (TFE_Input::keyPressed(s_langKeys->k_hard)) - { - s_keyPressed = BRIEF_BTN_HARD; - s_skill = 2; - } - - if (TFE_Input::keyPressed(s_langKeys->k_canc) || TFE_Input::keyPressed(KEY_ESCAPE)) - { - *abort = JTRUE; - exitBriefing = JTRUE; - } - else if (TFE_Input::keyPressed(KEY_O) || TFE_Input::keyPressed(KEY_RETURN)) - { - *abort = JFALSE; - exitBriefing = JTRUE; - } - - return exitBriefing; - } - - JBool missionBriefing_update(s32* skill, JBool* abort) - { - if (!s_briefingOpen) - { - *skill = s_skill; - *abort = JFALSE; - return JFALSE; - } - tfe_updateLTime(); - - // Input - if (missionBriefing_handleInput(abort)) - { - s_briefingOpen = JFALSE; - *skill = s_skill; - vfb_forceToBlack(); - lcanvas_clear(); - return JFALSE; - } - - // Background - lcanvas_eraseRect(&s_viewBounds); - lactor_setState(s_menuActor, 0, 0); - lactorAnim_draw(s_menuActor, &s_viewBounds, &s_viewBounds, 0, 0, JTRUE); - - // Buttons - for (s32 i = 0; i < BRIEF_BTN_COUNT; i++) - { - drawButton(BriefingButton(i)); - } - - // Briefing Text. - LRect rect = s_missionTextRect; - s16 diff = ((rect.right - rect.left) - s_briefActor->w) >> 1; - s16 x = diff + rect.left - s_briefActor->x; - s16 y = (rect.top - s_briefActor->y) - s_briefY; - - lcanvas_setClip(&s_missionTextRect); - lactorDelt_draw(s_briefActor, &rect, &s_missionTextRect, x, y, JTRUE); - lcanvas_clearClipRect(); - - menu_blitCursor(s_cursorPos.x, s_cursorPos.z, s_framebuffer); - menu_blitToScreen(); - return JTRUE; - } - - /////////////////////////////////////////// - // Internal Implementation - /////////////////////////////////////////// -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/GameUI/missionBriefing.h b/components/darkforces/tfe/TFE_DarkForces/GameUI/missionBriefing.h deleted file mode 100644 index b5244db1..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/GameUI/missionBriefing.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Mission Briefing -////////////////////////////////////////////////////////////////////// - -#include -#include -#include - -namespace TFE_DarkForces -{ - enum MissionBriefingConstants - { - BRIEF_VERT_MARGIN = 0, - BRIEF_LINE_SCROLL = 12, - BRIEF_PAGE_SCROLL = BRIEF_LINE_SCROLL * 10, - }; - - void missionBriefing_start(const char* archive, const char* bgAnim, const char* mission, const char* palette, s32 skill, LangHotkeys* langKeys); - void missionBriefing_cleanup(); - JBool missionBriefing_update(s32* skill, JBool* abort); -} diff --git a/components/darkforces/tfe/TFE_DarkForces/GameUI/pda.cpp b/components/darkforces/tfe/TFE_DarkForces/GameUI/pda.cpp deleted file mode 100644 index 31be3881..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/GameUI/pda.cpp +++ /dev/null @@ -1,879 +0,0 @@ -#include - -#include "pda.h" -#include "menu.h" -#include "missionBriefing.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; -using namespace TFE_Input; - -namespace TFE_DarkForces -{ - /////////////////////////////////////////// - // Constants - /////////////////////////////////////////// - enum PdaMode - { - PDA_MODE_MAP = 0, - PDA_MODE_WEAPONS, - PDA_MODE_INV, - PDA_MODE_GOALS, - PDA_MODE_BRIEF, - PDA_MODE_COUNT - }; - - enum PdaButton - { - PDA_BTN_MAP = 0, - PDA_BTN_WEAPONS, - PDA_BTN_INV, - PDA_BTN_GOALS, - PDA_BTN_BRIEF, - PDA_BTN_EXIT, - - PDA_BTN_PANUP, - PDA_BTN_PANRIGHT, - PDA_BTN_PANDOWN, - PDA_BTN_PANLEFT, - PDA_BTN_ZOOMOUT, - PDA_BTN_ZOOMIN, - PDA_BTN_LAYERUP, - PDA_BTN_LAYERDOWN, - - PDA_BTN_COUNT, - PDA_RADIO_BTN_COUNT = PDA_BTN_BRIEF - PDA_BTN_MAP + 1 - }; - - enum PdaFrames - { - PFRAME_BACK = 0, - PFRAME_SECRET_LABEL = 30, - PFRAME_SECRET_BOX = 31, - }; - - /////////////////////////////////////////// - // State - /////////////////////////////////////////// - static JBool s_pdaOpen = JFALSE; - static JBool s_pdaLoaded = JFALSE; - static LActor* s_briefing = nullptr; - static LActor* s_pdaArt = nullptr; - static LActor* s_goalsActor = nullptr; - static LActor* s_weapons = nullptr; - static LActor* s_items = nullptr; - static LPalette* s_palette = nullptr; - static LRect s_pdaRect = { 12, 15, 168, 305 }; - static LRect s_viewBounds; - static LRect s_overlayRect; - static u8* s_framebuffer; - - static JBool s_frameReady = true; - static Vec2i s_mouseAccum = { 0 }; - - static PdaMode s_pdaMode = PDA_MODE_MAP; - static s32 s_simulatePressed = -1; - - static s32 s_briefingMaxY; - static s16 s_briefY; - - void pda_handleInput(); - void pda_drawCommonButtons(); - void pda_drawMapButtons(); - void pdaDrawBriefingButtons(); - void pda_drawOverlay(); - void pda_clearToBlack(); - void pda_displayFontString(Font* font, s32 x, s32 y, char* msg); - - extern void pauseLevelSound(); - // From DarkForcesMain - // TODO: Refactor. - extern Font* getMapNumFont(); - - /////////////////////////////////////////// - // API Implementation - /////////////////////////////////////////// - void pda_start(const char* levelName) - { - // TFE - reticle_enable(false); - s_mouseAccum = { 0 }; - - pauseLevelSound(); - if (!s_pdaLoaded) - { - if (!menu_openResourceArchive("dfbrief.lfd")) - { - return; - } - LRect rect; - - s_briefing = lactorDelt_load(levelName, &s_pdaRect, 0, 0, 0); - s_goalsActor = lactorAnim_load(levelName, &rect, 0, 0, 0); - s_weapons = lactorAnim_load("guns", &rect, 0, 0, 0); - s_items = lactorAnim_load("items", &rect, 0, 0, 0); - menu_closeResourceArchive(); - - lactor_setTime(s_goalsActor, -1, -1); - lactor_setTime(s_weapons, -1, -1); - lactor_setTime(s_items, -1, -1); - - if (s_briefing) - { - lactor_setTime(s_briefing, -1, -1); - lactorDelt_getFrame(s_briefing, &rect); - - s_briefingMaxY = (rect.bottom - rect.top) - (s_pdaRect.bottom - s_pdaRect.top) + BRIEF_VERT_MARGIN; - // Round to a factor of the line scrolling value. - s_briefingMaxY = s_briefingMaxY + BRIEF_LINE_SCROLL - (s_briefingMaxY % BRIEF_LINE_SCROLL); - - if (s_briefingMaxY < -BRIEF_VERT_MARGIN) - { - s_briefingMaxY = -BRIEF_VERT_MARGIN; - } - s_briefY = -BRIEF_VERT_MARGIN; - } - s_overlayRect = s_pdaRect; - - if (!menu_openResourceArchive("menu.lfd")) - { - return; - } - s_framebuffer = ldraw_getBitmap(); - lcanvas_getBounds(&s_viewBounds); - - s_pdaArt = lactorAnim_load("pda", &s_viewBounds, 0, 0, 0); - s_palette = lpalette_load("menu"); - lactor_setTime(s_pdaArt, -1, -1); - - menu_closeResourceArchive(); - - s_pdaLoaded = JTRUE; - } - lpalette_setScreenPal(s_palette); - - s_pdaOpen = JTRUE; - s_buttonPressed = -1; - s_simulatePressed = -1; - s_buttonHover = JFALSE; - automap_updateMapData(MAP_CENTER_PLAYER); - automap_updateMapData(MAP_ENABLE_AUTOCENTER); - automap_resetScale(); - ltime_setFrameDelay(10); - - TFE_Input::endFrame(); - } - - void pda_cleanup() - { - lactor_removeActor(s_briefing); - lactor_removeActor(s_pdaArt); - lactor_removeActor(s_goalsActor); - lactor_removeActor(s_weapons); - lactor_removeActor(s_items); - - lactor_free(s_briefing); - lactor_free(s_pdaArt); - lactor_free(s_goalsActor); - lactor_free(s_weapons); - lactor_free(s_items); - lpalette_free(s_palette); - - pda_resetState(); - } - - void pda_resetState() - { - s_pdaOpen = JFALSE; - s_pdaLoaded = JFALSE; - s_briefing = nullptr; - s_pdaArt = nullptr; - s_goalsActor = nullptr; - s_weapons = nullptr; - s_items = nullptr; - s_palette = nullptr; - } - - JBool pda_isOpen() - { - return s_pdaOpen; - } - - void pda_close() - { - // Clear the screen to black during the palette transition. - pda_clearToBlack(); - - // Reset automap - automap_updateMapData(MAP_ENABLE_AUTOCENTER); - s_pdaOpen = JFALSE; - - // TFE - reticle_enable(true); - - // Convert back to level rendering. - TFE_Settings_Graphics* graphics = TFE_Settings::getGraphicsSettings(); - if (graphics->rendererIndex != RENDERER_SOFTWARE) - { - TFE_Jedi::renderer_setType(RendererType(graphics->rendererIndex)); - TFE_Jedi::renderer_setLimits(); - } - } - - void pda_update() - { - if (!s_pdaOpen) - { - return; - } - - if (inputMapping_getActionState(IADF_PDA_TOGGLE) == STATE_PRESSED || TFE_Input::keyPressed(KEY_ESCAPE)) - { - pda_close(); - return; - } - else if (TFE_Jedi::renderer_getType() != RENDERER_SOFTWARE) - { - // Convert back to CPU rendering. - TFE_Jedi::renderer_setType(RENDERER_SOFTWARE); - TFE_Jedi::renderer_setLimits(); - } - - tfe_updateLTime(); - s_frameReady = ltime_isFrameReady(); - - // Input - pda_handleInput(); - - // Main view - u32 outWidth, outHeight; - vfb_getResolution(&outWidth, &outHeight); - memset(vfb_getCpuBuffer(), 0, outWidth * outHeight); - - // Draw the overlay *behind* the main view - which means we must blit it to the view. - pda_drawOverlay(); - - // Finally draw the PDA background and UI controls. - lcanvas_eraseRect(&s_viewBounds); - lactor_setState(s_pdaArt, 0, 0); - lactorAnim_draw(s_pdaArt, &s_viewBounds, &s_viewBounds, 0, 0, JTRUE); - - // Common buttons - pda_drawCommonButtons(); - if (s_pdaMode == PDA_MODE_MAP) - { - pda_drawMapButtons(); - - // Draw the floor number - Font* mapNumFont = getMapNumFont(); - if (mapNumFont) - { - char str[10]; - memset(str, 0, 10); // just to be safe - snprintf(str, 10, "%d", automap_getLayer()); - // This shows up as an 'S' in the font. - if (str[0] == '-') { str[0] = ':'; } - // In TFE the map covers the whole screen, so no additional offset is needed. - s32 leftAdj = font_getStringLength(mapNumFont, str) / 2; - pda_displayFontString(mapNumFont, 275 - leftAdj, 127, str); - } - } - else if (s_pdaMode == PDA_MODE_BRIEF) - { - pdaDrawBriefingButtons(); - } - - // Blit the canvas to the screen as a transparent image, using 79 as the transparent color. - // This allows the PDA border to overlay the map, briefing, and other "overlay" elements. - screenDraw_setTransColor(79); - menu_blitToScreen(nullptr, JTRUE/*transparent*/, JFALSE/*swap*/); - - // Doing that we need to restore the transparent color before blitting the mouse cursor, otherwise its black edges will - // show up incorrectly. - screenDraw_setTransColor(0); - menu_blitCursorScaled(s_cursorPos.x, s_cursorPos.z, vfb_getCpuBuffer()); - vfb_swap(); - } - - /////////////////////////////////////////// - // Internal Implementation - /////////////////////////////////////////// - void pda_handleMouseAccum(s32* wdx, s32* wdy) - { - if (!s_frameReady) - { - s_mouseAccum.x += *wdx; - s_mouseAccum.z += *wdy; - *wdx += s_mouseAccum.x; - *wdy += s_mouseAccum.z; - } - else - { - *wdx += s_mouseAccum.x; - *wdy += s_mouseAccum.z; - s_mouseAccum = { 0 }; - } - } - - void pda_handleButtons() - { - // Add support for mouse wheel scrolling. - s32 wdx, wdy; - TFE_Input::getMouseWheel(&wdx, &wdy); - // Ensure that mouse movements are not lost between updates. - pda_handleMouseAccum(&wdx, &wdy); - - if (TFE_Input::mousePressed(MBUTTON_LEFT) || s_simulatePressed >= 0 || wdy) - { - s_buttonPressed = -1; - s32 count = (s_pdaMode == PDA_MODE_MAP || s_pdaMode == PDA_MODE_BRIEF) ? PDA_BTN_COUNT : PDA_BTN_EXIT + 1; - for (s32 i = PDA_BTN_MAP; i < count; i++) - { - lactor_setState(s_pdaArt, 2 * (1 + i), 0); - LRect buttonRect; - lactorAnim_getFrame(s_pdaArt, &buttonRect); - - if (!TFE_Input::mousePressed(MBUTTON_LEFT)) - { - if (i == s_simulatePressed) - { - s_buttonPressed = s32(i); - s_buttonHover = JTRUE; - s_simulatePressed = 0; - break; - } - } - else if ((s_cursorPos.x >= buttonRect.left && s_cursorPos.x < buttonRect.right && - s_cursorPos.z >= buttonRect.top && s_cursorPos.z < buttonRect.bottom) || - i == s_simulatePressed) - { - s_buttonPressed = s32(i); - s_buttonHover = JTRUE; - if (i == s_simulatePressed) { s_simulatePressed = 0; } - break; - } - } - - if (s_pdaMode == PDA_MODE_MAP && (s_buttonPressed || wdy) && s_frameReady) - { - // Add support for mouse wheel scrolling. - if (wdy < 0) - { - automap_updateMapData(MAP_ZOOM_IN); - } - else if (wdy > 0) - { - automap_updateMapData(MAP_ZOOM_OUT); - } - - switch (s_buttonPressed) - { - case PDA_BTN_PANUP: - { - automap_updateMapData(MAP_MOVE1_UP); - } break; - case PDA_BTN_PANRIGHT: - { - automap_updateMapData(MAP_MOVE1_RIGHT); - } break; - case PDA_BTN_PANDOWN: - { - automap_updateMapData(MAP_MOVE1_DN); - } break; - case PDA_BTN_PANLEFT: - { - automap_updateMapData(MAP_MOVE1_LEFT); - } break; - case PDA_BTN_ZOOMOUT: - { - automap_updateMapData(MAP_ZOOM_IN); - } break; - case PDA_BTN_ZOOMIN: - { - automap_updateMapData(MAP_ZOOM_OUT); - } break; - case PDA_BTN_LAYERUP: - { - if (s_buttonPressed == s_simulatePressed) - { - automap_updateMapData(MAP_LAYER_UP); - s_simulatePressed = 0; - } - } break; - case PDA_BTN_LAYERDOWN: - { - if (s_buttonPressed == s_simulatePressed) - { - automap_updateMapData(MAP_LAYER_DOWN); - s_simulatePressed = 0; - } - } break; - } - } - else if (s_pdaMode == PDA_MODE_BRIEF && (s_buttonPressed || wdy) && s_frameReady) - { - // Add support for mouse wheel scrolling. - if (wdy > 0) // up - { - if (s_briefY > -BRIEF_VERT_MARGIN) - { - s_briefY -= BRIEF_LINE_SCROLL * wdy; - if (s_briefY < -BRIEF_VERT_MARGIN) s_briefY = -BRIEF_VERT_MARGIN; - } - } - else if (wdy < 0) // down - { - if (s_briefY != s_briefingMaxY) - { - s_briefY -= BRIEF_LINE_SCROLL * wdy; - if (s_briefY > s_briefingMaxY) s_briefY = s_briefingMaxY; - } - } - - switch (s_buttonPressed) - { - case PDA_BTN_PANUP: - { - if (s_briefY > -BRIEF_VERT_MARGIN) - { - s_briefY -= BRIEF_LINE_SCROLL; - if (s_briefY < -BRIEF_VERT_MARGIN) s_briefY = -BRIEF_VERT_MARGIN; - } - } break; - case PDA_BTN_PANDOWN: - { - if (s_briefY != s_briefingMaxY) - { - s_briefY += BRIEF_LINE_SCROLL; - - if (s_briefY > s_briefingMaxY) s_briefY = s_briefingMaxY; - } - } break; - } - } - } - else if (TFE_Input::mouseDown(MBUTTON_LEFT) && s_buttonPressed >= 0) - { - lactor_setState(s_pdaArt, 2 * (1 + s_buttonPressed), 0); - LRect buttonRect; - lactorAnim_getFrame(s_pdaArt, &buttonRect); - - // Verify that the mouse is still over the button. - if (s_cursorPos.x >= buttonRect.left && s_cursorPos.x < buttonRect.right && - s_cursorPos.z >= buttonRect.top && s_cursorPos.z < buttonRect.bottom) - { - s_buttonHover = JTRUE; - } - else - { - s_buttonHover = JFALSE; - } - - if (s_buttonHover && s_pdaMode == PDA_MODE_MAP && s_frameReady) - { - switch (s_buttonPressed) - { - case PDA_BTN_PANUP: - { - automap_updateMapData(MAP_MOVE1_UP); - } break; - case PDA_BTN_PANRIGHT: - { - automap_updateMapData(MAP_MOVE1_RIGHT); - } break; - case PDA_BTN_PANDOWN: - { - automap_updateMapData(MAP_MOVE1_DN); - } break; - case PDA_BTN_PANLEFT: - { - automap_updateMapData(MAP_MOVE1_LEFT); - } break; - case PDA_BTN_ZOOMOUT: - { - automap_updateMapData(MAP_ZOOM_IN); - } break; - case PDA_BTN_ZOOMIN: - { - automap_updateMapData(MAP_ZOOM_OUT); - } break; - } - } - else if (s_buttonHover && s_pdaMode == PDA_MODE_BRIEF && s_frameReady) - { - switch (s_buttonPressed) - { - case PDA_BTN_PANUP: - { - if (s_briefY > -BRIEF_VERT_MARGIN) - { - s_briefY -= BRIEF_LINE_SCROLL; - if (s_briefY < -BRIEF_VERT_MARGIN) s_briefY = -BRIEF_VERT_MARGIN; - } - } break; - case PDA_BTN_PANDOWN: - { - if (s_briefY != s_briefingMaxY) - { - s_briefY += BRIEF_LINE_SCROLL; - - if (s_briefY > s_briefingMaxY) s_briefY = s_briefingMaxY; - } - } break; - } - } - } - else - { - if (s_buttonPressed >= 0 && s_buttonHover && s_simulatePressed < 0) - { - switch (s_buttonPressed) - { - case PDA_BTN_MAP: - { - s_pdaMode = PDA_MODE_MAP; - } break; - case PDA_BTN_WEAPONS: - { - s_pdaMode = PDA_MODE_WEAPONS; - } break; - case PDA_BTN_INV: - { - s_pdaMode = PDA_MODE_INV; - } break; - case PDA_BTN_GOALS: - { - s_pdaMode = PDA_MODE_GOALS; - } break; - case PDA_BTN_BRIEF: - { - s_pdaMode = PDA_MODE_BRIEF; - } break; - case PDA_BTN_EXIT: - { - pda_close(); - } break; - case PDA_BTN_LAYERUP: - { - automap_updateMapData(MAP_LAYER_UP); - } break; - case PDA_BTN_LAYERDOWN: - { - automap_updateMapData(MAP_LAYER_DOWN); - } break; - } - } - // Reset. - s_buttonPressed = -1; - s_buttonHover = JFALSE; - } - s_simulatePressed = -1; - } - - void pda_handleInput() - { - menu_handleMousePosition(); - automap_setPdaActive(JTRUE); - - if (TFE_Input::keyPressed(KEY_SPACE)) - { - if (TFE_Input::keyDown(KEY_LSHIFT) || TFE_Input::keyDown(KEY_RSHIFT)) - { - s_pdaMode = (s_pdaMode == PDA_MODE_MAP) ? PDA_MODE_BRIEF : PdaMode(s_pdaMode - 1); - } - else - { - s_pdaMode = (s_pdaMode == PDA_MODE_BRIEF) ? PDA_MODE_MAP : PdaMode(s_pdaMode + 1); - } - } - - if (s_pdaMode == PDA_MODE_MAP) - { - if (TFE_Input::keyDown(KEY_UP)) - { - s_simulatePressed = PDA_BTN_PANUP; - } - else if (TFE_Input::keyDown(KEY_DOWN)) - { - s_simulatePressed = PDA_BTN_PANDOWN; - } - if (TFE_Input::keyDown(KEY_LEFT)) - { - s_simulatePressed = PDA_BTN_PANLEFT; - } - else if (TFE_Input::keyDown(KEY_RIGHT)) - { - s_simulatePressed = PDA_BTN_PANRIGHT; - } - - if (TFE_Input::keyDown(KEY_EQUALS)) - { - s_simulatePressed = PDA_BTN_ZOOMIN; - } - else if (TFE_Input::keyDown(KEY_MINUS)) - { - s_simulatePressed = PDA_BTN_ZOOMOUT; - } - - if (TFE_Input::keyPressed(KEY_LEFTBRACKET)) - { - s_simulatePressed = PDA_BTN_LAYERDOWN; - } - else if (TFE_Input::keyPressed(KEY_RIGHTBRACKET)) - { - s_simulatePressed = PDA_BTN_LAYERUP; - } - } - else if (s_pdaMode == PDA_MODE_BRIEF) - { - if (TFE_Input::keyDown(KEY_UP)) - { - s_simulatePressed = PDA_BTN_PANUP; - } - else if (TFE_Input::keyDown(KEY_DOWN)) - { - s_simulatePressed = PDA_BTN_PANDOWN; - } - } - - pda_handleButtons(); - } - - void pda_drawButton(PdaButton id) - { - s32 pressed = 0; - if ((s_buttonHover && id == s_buttonPressed) || (id == (PdaButton)s_pdaMode)) - { - pressed = 1; - } - - lactor_setState(s_pdaArt, 2 * (1 + id) + (pressed ? 0 : 1), 0); - lactorAnim_draw(s_pdaArt, &s_viewBounds, &s_viewBounds, 0, 0, JTRUE); - } - - void pda_drawCommonButtons() - { - for (s32 i = PDA_BTN_MAP; i <= PDA_BTN_EXIT; i++) - { - pda_drawButton(PdaButton(i)); - } - } - - void pda_drawMapButtons() - { - for (s32 i = PDA_BTN_PANUP; i <= PDA_BTN_LAYERDOWN; i++) - { - pda_drawButton(PdaButton(i)); - } - } - - void pdaDrawBriefingButtons() - { - pda_drawButton(PDA_BTN_PANUP); - pda_drawButton(PDA_BTN_PANDOWN); - } - - void pda_drawOverlay() - { - if (s_pdaMode == PDA_MODE_MAP) - { - ScreenRect* uiRect = vfb_getScreenRect(VFB_RECT_UI); - fixed16_16 xScale = vfb_getXScale(); - fixed16_16 yScale = vfb_getYScale(); - - s32 virtualWidth = floor16(mul16(intToFixed16(320), xScale)); - s32 offset = max(0, ((uiRect->right - uiRect->left + 1) - virtualWidth) / 2); - - ScreenRect clipRect; - clipRect.left = offset + floor16(mul16(intToFixed16(s_pdaRect.left), xScale) + xScale); - clipRect.right = offset + floor16(mul16(intToFixed16(s_pdaRect.right), xScale) - xScale); - clipRect.top = floor16(mul16(intToFixed16(s_pdaRect.top), yScale) + yScale); - clipRect.bot = floor16(mul16(intToFixed16(s_pdaRect.bottom), yScale) - yScale); - - vfb_setScreenRect(VFB_RECT_RENDER, &clipRect); - automap_draw(vfb_getCpuBuffer()); - vfb_restoreScreenRect(VFB_RECT_RENDER); - } - else if (s_pdaMode == PDA_MODE_WEAPONS && s_weapons) - { - lcanvas_eraseRect(&s_overlayRect); - lcanvas_setClip(&s_overlayRect); - - for (s32 i = 0; i < s_weapons->arraySize; i++) - { - if (player_hasWeapon(i + 2)) - { - lactor_setState(s_weapons, i, 0); - lactorAnim_draw(s_weapons, &s_overlayRect, &s_viewBounds, 0, 0, JTRUE); - } - } - - lcanvas_clearClipRect(); - menu_blitToScreen(nullptr, JFALSE); - } - else if (s_pdaMode == PDA_MODE_INV && s_items) - { - lcanvas_eraseRect(&s_overlayRect); - lcanvas_setClip(&s_overlayRect); - - for (s32 i = 0; i < s_items->arraySize; i++) - { - if (player_hasItem(i)) - { - lactor_setState(s_items, i, 0); - lactorAnim_draw(s_items, &s_overlayRect, &s_viewBounds, 0, 0, JTRUE); - } - } - - lcanvas_clearClipRect(); - menu_blitToScreen(nullptr, JFALSE); - } - else if (s_pdaMode == PDA_MODE_BRIEF && s_briefing) - { - s32 diff = (s_overlayRect.right - s_overlayRect.left - s_briefing->w) >> 1; - s32 x = diff + s_overlayRect.left - s_briefing->x; - s32 y = s_overlayRect.top - s_briefing->y - s_briefY; - - lcanvas_eraseRect(&s_overlayRect); - lcanvas_setClip(&s_overlayRect); - lactorDelt_draw(s_briefing, &s_overlayRect, &s_overlayRect, x, y, JTRUE); - lcanvas_clearClipRect(); - menu_blitToScreen(nullptr, JFALSE); - } - else if (s_pdaMode == PDA_MODE_GOALS && s_goalsActor) - { - lcanvas_eraseRect(&s_overlayRect); - lcanvas_setClip(&s_overlayRect); - - lactor_setState(s_goalsActor, 0, 0); - lactorAnim_draw(s_goalsActor, &s_overlayRect, &s_overlayRect, 0, 0, JTRUE); - - s32 goalCount = s_goalsActor->arraySize - 1; - for (s32 i = 0; i < goalCount; i++) - { - if (level_isGoalComplete(i)) - { - lactor_setState(s_goalsActor, i + 1, 0); - lactorAnim_draw(s_goalsActor, &s_overlayRect, &s_overlayRect, 0, 0, JTRUE); - } - } - - s32 secretPercentage = s_levelState.secretCount ? floor16(mul16(FIXED(100), div16(intToFixed16(s_secretsFound), intToFixed16(s_levelState.secretCount)))) : 0; - lactor_setState(s_pdaArt, 30, 0); - lactorAnim_draw(s_pdaArt, &s_overlayRect, &s_overlayRect, 0, 0, JTRUE); - - char secretStr[32]; - LRect rect; - - sprintf(secretStr, "%2d%%", secretPercentage); - lactor_setState(s_pdaArt, 31, 0); - lactorAnim_getFrame(s_pdaArt, &rect); - - // Shadow - rect.top++; - lfont_setColor(91); - lfont_setFrame(&rect); - lfont_drawTextClipped(secretStr); - - rect.top--; - rect.left++; - lfont_setFrame(&rect); - lfont_drawTextClipped(secretStr); - - // Text - rect.left--; - lfont_setColor(19); - lfont_setFrame(&rect); - lfont_drawTextClipped(secretStr); - - lcanvas_clearClipRect(); - menu_blitToScreen(nullptr, JFALSE); - } - } - - void pda_clearToBlack() - { - u32 outWidth, outHeight; - vfb_getResolution(&outWidth, &outHeight); - memset(vfb_getCpuBuffer(), 0, outWidth * outHeight); - - u32 palette[256] = { 0 }; - vfb_setPalette(palette); - } - - // Simplified font drawing which assumes 320x200. - // Does not handle clipping to avoid code duplication. - void pda_drawFontGlyph(TextureData* glyph, s32 x0, s32 y0, u8* framebuffer) - { - u8* col = glyph->image; - for (s32 x = x0; x < x0 + glyph->width; x++, col += glyph->height) - { - u8* output = framebuffer + x + y0 * 320; - - // columns - for (s32 y = y0; y < y0 + glyph->height; y++, output += 320) - { - u8 color = col[glyph->height - y + y0 - 1]; - if (color) { *output = color; } - } - } - } - - void pda_displayFontString(Font* font, s32 x, s32 y, char* msg) - { - if (!font) { return; } - - u8* framebuffer = ldraw_getBitmap(); - - s32 xi = x; - s32 x0 = x; - for (char c = *msg; c != 0;) - { - if (c == '\n') - { - xi = x0; - y += font->height + font->vertSpacing; - } - else if (c == ' ') - { - xi += font->width; - } - else if (c >= font->minChar && c <= font->maxChar) - { - s32 charIndex = c - font->minChar; - TextureData* glyph = &font->glyphs[charIndex]; - pda_drawFontGlyph(glyph, xi, y, framebuffer); - xi += font->horzSpacing + glyph->width; - } - msg++; - c = *msg; - } - } -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/GameUI/pda.h b/components/darkforces/tfe/TFE_DarkForces/GameUI/pda.h deleted file mode 100644 index e75502aa..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/GameUI/pda.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Mission Briefing -////////////////////////////////////////////////////////////////////// - -#include - -namespace TFE_DarkForces -{ - void pda_start(const char* levelName); - void pda_cleanup(); - void pda_resetState(); - - JBool pda_isOpen(); - void pda_update(); -} diff --git a/components/darkforces/tfe/TFE_DarkForces/GameUI/uiDraw.cpp b/components/darkforces/tfe/TFE_DarkForces/GameUI/uiDraw.cpp deleted file mode 100644 index 10d89681..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/GameUI/uiDraw.cpp +++ /dev/null @@ -1,100 +0,0 @@ -#include - -#include "uiDraw.h" -#include - -namespace TFE_DarkForces -{ - // TODO: Factor out to the Landru system. - DeltFrame s_cursor; - - void print(const char* text, s32 x0, s32 y0, u8 color, u8* framebuffer) - { - LRect frame; - frame.left = x0; - frame.top = y0; - frame.right = 320; - frame.bottom = 200; - - lfont_setFrame(&frame); - lfont_setColor(color); - lfont_drawText(text, framebuffer); - } - - s32 getStringPixelLength(const char* str) - { - if (!str) { return 0; } - return lfont_getTextWidth(str); - } - - void drawColoredQuad(s32 x0, s32 y0, s32 w, s32 h, u8 color, u8* framebuffer) - { - u8* output = &framebuffer[y0 * 320]; - s32 x1 = x0 + w - 1; - s32 y1 = y0 + h - 1; - - // Skip if out of bounds. - if (x0 >= 320 || x1 < 0 || y0 >= 200 || y1 < 0) - { - return; - } - // Clip - if (x0 < 0) - { - x0 = 0; - } - if (x1 >= 320) - { - x1 = 319; - } - if (y0 < 0) - { - output -= y0 * 320; - y0 = 0; - } - if (y1 >= 200) - { - y1 = 199; - } - - s32 width = x1 - x0 + 1; - for (s32 y = y0; y <= y1; y++) - { - memset(&output[x0], color, width); - output += 320; - } - } - - void drawHorizontalLine(s32 x0, s32 x1, s32 y0, u8 color, u8* framebuffer) - { - // Skip if out of bounds. - if (x0 >= 320 || x1 < 0 || y0 < 0 || y0 >= 200) - { - return; - } - - if (x0 < 0) { x0 = 0; } - if (x1 >= 320) { x1 = 319; } - - s32 width = x1 - x0 + 1; - memset(&framebuffer[y0*320 + x0], color, width); - } - - void drawVerticalLine(s32 y0, s32 y1, s32 x0, u8 color, u8* framebuffer) - { - // Skip if out of bounds. - if (x0 >= 320 || x0 < 0 || y1 < 0 || y0 >= 200) - { - return; - } - - if (y0 < 0) { y0 = 0; } - if (y1 >= 320) { y1 = 319; } - - u8* output = &framebuffer[y0 * 320 + x0]; - for (s32 y = y0; y <= y1; y++, output += 320) - { - *output = color; - } - } -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/GameUI/uiDraw.h b/components/darkforces/tfe/TFE_DarkForces/GameUI/uiDraw.h deleted file mode 100644 index b9960c02..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/GameUI/uiDraw.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Note this is still the original TFE code, reverse-engineered game -// UI code will not be available until future releases. -////////////////////////////////////////////////////////////////////// -#include -#include -#include "delt.h" - -namespace TFE_DarkForces -{ - void createFont(); - - void drawColoredQuad(s32 x0, s32 y0, s32 w, s32 h, u8 color, u8* framebuffer); - void drawHorizontalLine(s32 x0, s32 x1, s32 y0, u8 color, u8* framebuffer); - void drawVerticalLine(s32 y0, s32 y1, s32 x0, u8 color, u8* framebuffer); - - void print(const char* text, s32 x0, s32 y0, u8 color, u8* framebuffer); - s32 getStringPixelLength(const char* str); - - extern DeltFrame s_cursor; -} diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/cutscene.cpp b/components/darkforces/tfe/TFE_DarkForces/Landru/cutscene.cpp deleted file mode 100644 index 44fdeeb3..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/cutscene.cpp +++ /dev/null @@ -1,107 +0,0 @@ -#include "cutscene.h" -#include "cutscene_player.h" -#include "lsystem.h" -#include "lcanvas.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - static JBool s_playing = JFALSE; - - CutsceneState* s_playSeq = nullptr; - s32 s_soundVolume = 0; - s32 s_musicVolume = 0; - s32 s_enabled = 1; - - void cutscene_init(CutsceneState* cutsceneList) - { - s_playSeq = cutsceneList; - s_playing = JFALSE; - } - - JBool cutscene_play(s32 sceneId) - { - if (!s_enabled || !s_playSeq) { return JFALSE; } - TFE_Settings_Sound* soundSettings = TFE_Settings::getSoundSettings(); - TFE_Audio::setVolume(soundSettings->cutsceneSoundFxVolume * soundSettings->masterVolume); - TFE_MidiPlayer::setVolume(soundSettings->cutsceneMusicVolume * soundSettings->masterVolume); - - // Search for the requested scene. - s32 found = 0; - for (s32 i = 0; !found && s_playSeq[i].id != SCENE_EXIT; i++) - { - if (s_playSeq[i].id == sceneId) - { - found = 1; - break; - } - } - if (!found) return JFALSE; - // Re-initialize the canvas, so cutscenes run at the correct resolution even if it was changed for gameplay - // (i.e. high resolution support). - lcanvas_init(320, 200); - - // The original code then starts the cutscene loop here, and then returns when done. - // Instead we set a bool and then the calling code will call 'update' until it returns false. - s_playing = JTRUE; - cutscenePlayer_start(sceneId); - return JTRUE; - } - -#ifdef TFE_ESPBOX - void cutscene_abort() - { - if (!s_playing) { return; } - cutscenePlayer_abort(); - s_playing = JFALSE; - } -#endif - - JBool cutscene_update() - { - if (!s_playing) { return JFALSE; } - - s_playing = cutscenePlayer_update(); - return s_playing; - } - - void cutscene_enable(s32 enable) - { - s_enabled = enable; - } - - s32 cutscene_isEnabled() - { - return s_enabled; - } - - void cutscene_setSoundVolume(s32 volume) - { - s_soundVolume = clamp(volume, 0, 127); - } - - void cutscene_setMusicVolume(s32 volume) - { - s_musicVolume = clamp(volume, 0, 127); - } - - s32 cutscene_getSoundVolume() - { - return s_soundVolume; - } - - s32 cutscene_getMusicVolume() - { - return s_musicVolume; - } -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/cutscene.h b/components/darkforces/tfe/TFE_DarkForces/Landru/cutscene.h deleted file mode 100644 index 9b231454..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/cutscene.h +++ /dev/null @@ -1,34 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces Cutscene -// This manages loading assets and playback. -////////////////////////////////////////////////////////////////////// -#include -#include "cutsceneList.h" - -namespace TFE_DarkForces -{ - enum CutsceneConstants - { - SCENE_ENTER = -10, - SCENE_EXIT = 0, - }; - - void cutscene_init(CutsceneState* cutsceneList); - - JBool cutscene_play(s32 sceneId); - JBool cutscene_update(); -#ifdef TFE_ESPBOX - // Stop the cutscene that is playing, if any (used when a game is loaded while - // a cutscene runs, e.g. the startup logo). - void cutscene_abort(); -#endif - void cutscene_enable(s32 enable); - s32 cutscene_isEnabled(); - - void cutscene_setSoundVolume(s32 volume); - void cutscene_setMusicVolume(s32 volume); - - s32 cutscene_getSoundVolume(); - s32 cutscene_getMusicVolume(); -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/cutsceneList.cpp b/components/darkforces/tfe/TFE_DarkForces/Landru/cutsceneList.cpp deleted file mode 100644 index 0ec492eb..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/cutsceneList.cpp +++ /dev/null @@ -1,109 +0,0 @@ -#include - -#include "cutsceneList.h" -#include -#include -#include -#include -#include - -namespace TFE_DarkForces -{ - static char* s_buffer = nullptr; - - void cutsceneList_freeBuffer() - { - s_buffer = nullptr; - } - - char* copyStringAndNullTerminate(char* dstString, const char* srcString, s32 bufferSize) - { - strCopyAndZero(dstString, srcString, bufferSize - 1); - dstString[bufferSize - 1] = 0; - return dstString; - } - - CutsceneState* cutsceneList_load(const char* filename) - { - FilePath filePath; - if (!TFE_Paths::getFilePath(filename, &filePath)) - { - return nullptr; - } - - FileStream file; - if (!file.open(&filePath, Stream::MODE_READ)) { return nullptr; } - - size_t size = file.getSize(); - s_buffer = (char*)game_realloc(s_buffer, size); - if (!s_buffer) { return nullptr; } - - file.readBuffer(s_buffer, (u32)size); - file.close(); - - TFE_Parser parser; - parser.init(s_buffer, size); - parser.addCommentString("#"); - - size_t bufferPos = 0; - const char* fileData = parser.readLine(bufferPos); - s32 v0, v1; - if (sscanf(fileData, "CUT %d.%d", &v0, &v1) != 2) - { - TFE_System::logWrite(LOG_ERROR, "LoadList", "Cannot read version."); - return nullptr; - } - - if (v0 != 1 || v1 != 0) - { - TFE_System::logWrite(LOG_ERROR, "LoadList", "Invalid version: %d.%d; should be 1.0", v0, v1); - return nullptr; - } - - s32 count = 0; - fileData = parser.readLine(bufferPos); - if (sscanf(fileData, "CUTS %d", &count) != 1) - { - TFE_System::logWrite(LOG_ERROR, "LoadList", "Cannot read count."); - return nullptr; - } - - CutsceneState* items = (CutsceneState*)game_alloc((count + 1) * sizeof(CutsceneState)); - memset(items, 0, (count + 1) * sizeof(CutsceneState)); - if (!items) - { - TFE_System::logWrite(LOG_ERROR, "LoadList", "Cannot allocate %d list items.", count + 1); - return nullptr; - } - - for (s32 i = 0; i < count; i++) - { - fileData = parser.readLine(bufferPos); - if (!fileData) - { - break; - } - - s32 id; - char archive[32], scene[32]; - s32 speed, nextId, skip, music = 0, volume; - s32 r = sscanf(fileData, " %d: %s %s %d %d %d %d %d", &id, archive, scene, &speed, &nextId, &skip, &music, &volume); - if (r != 8) - { - TFE_System::logWrite(LOG_ERROR, "LoadList", "Invalid cutscene data."); - break; - } - - copyStringAndNullTerminate(items[i].archive, archive, 14); - copyStringAndNullTerminate(items[i].scene, scene, 10); - items[i].id = id; - items[i].nextId = nextId; - items[i].skip = skip; - items[i].speed = speed; - items[i].music = music; - items[i].volume = volume; - } - - return items; - } -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/cutsceneList.h b/components/darkforces/tfe/TFE_DarkForces/Landru/cutsceneList.h deleted file mode 100644 index 9433dbbf..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/cutsceneList.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces Cutscene List -////////////////////////////////////////////////////////////////////// -#include -#include - -namespace TFE_DarkForces -{ - struct CutsceneState - { - char archive[14]; - char scene[10]; - s16 id; - s16 nextId; - s16 skip; - s16 speed; - s16 music; - s16 volume; - }; - - void cutsceneList_freeBuffer(); - CutsceneState* cutsceneList_load(const char* filename); -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/cutscene_film.cpp b/components/darkforces/tfe/TFE_DarkForces/Landru/cutscene_film.cpp deleted file mode 100644 index 04856b42..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/cutscene_film.cpp +++ /dev/null @@ -1,1126 +0,0 @@ -#include "cutscene_film.h" -#include "lsystem.h" -#include "lactorDelt.h" -#include "lactorAnim.h" -#include "lactorCust.h" -#include "lcanvas.h" -#include "lfade.h" -#include "lsound.h" -#include "time.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - struct FilmState - { - Film* firstFilm = nullptr; - FadeType filmFade = ftype_noFade; - FadeColorType filmColorFade = fcolorType_noColorFade; - }; - static FilmState s_filmState = {}; - - LActor* cutsceneFilm_cloneActor(u32 type, const char* name); - LSound* cutsceneFilm_cloneSound(u32 type, const char* name); - void cutsceneFilm_initFilm(Film* film, u8** array, LRect* frame, s16 x, s16 y, s16 zPlane); - void cutsceneFilm_setName(Film* film, u32 resType, const char* name); - JBool cutsceneFilm_isTimeStamp(Film* film, FilmObject* filmObj, u8* data); - void cutsceneFilm_setActorToFilm(FilmObject* filmObj, u8* data); - void cutsceneFilm_setViewToFilm(Film* film, FilmObject* filmObj, u8* data); - void cutsceneFilm_setFade(s16 fade, s16 colorFade); - void cutsceneFilm_stepView(Film* film, FilmObject* filmObj, u8* data); - void cutsceneFilm_stepPalette(Film* film, FilmObject* filmObj, u8* data); - void cutsceneFilm_stepSound(Film* film, FilmObject* filmObj, u8* data); - void cutsceneFilm_rewind(Film* film); - void cutsceneFilm_update(Film* film); - void cutsceneFilm_freeData(Film* film); - void cutsceneFilm_freeDataObject(Film* film, s16 index); - - void cutsceneFilm_setFade(s16 fade, s16 colorFade); - void cutsceneFilm_clearFade(); - void cutsceneFilm_startFade(JBool paletteChange); - JBool cutsceneFilm_isFading(); - - void cutsceneFilm_reset() - { - s_filmState = {}; - } - - Film* cutsceneFilm_allocate() - { - Film* film = (Film*)landru_alloc(sizeof(Film)); - if (!film) { return nullptr; } - - memset(film, 0, sizeof(Film)); - film->stop = -1; - film->flags = CF_STATE_REFRESH; - - return film; - } - - void cutsceneFilm_free(Film* film) - { - if (!film) { return; } - - if (film->varPtr) - { - landru_free(film->varPtr); - } - if (film->varPtr2) - { - landru_free(film->varPtr2); - } - if (film->flags & CF_STATE_DISCARD) - { - cutsceneFilm_freeData(film); - } - landru_free(film); - } - - void cutsceneFilm_freeData(Film* film) - { - if (!film->array) { return; } - - for (s32 i = 0; i < film->arraySize; i++) - { - cutsceneFilm_freeDataObject(film, i); - } - - landru_free(film->array); - film->array = nullptr; - } - - void cutsceneFilm_freeDataObject(Film* film, s16 index) - { - FilmObject* filmObj = (FilmObject*)film->array[index]; - if (filmObj) - { - switch (filmObj->id) - { - case CF_FILE_ACTOR: - { - LActor* actor = (LActor*)filmObj->data; - lactor_removeActor(actor); - lactor_free(actor); - } break; - case CF_FILE_PALETTE: - { - LPalette* pal = (LPalette*)filmObj->data; - lpalette_remove(pal); - lpalette_free(pal); - } break; - case CF_FILE_SOUND: - { - LSound* sound = (LSound*)filmObj->data; - stopSound(sound); - } break; - } - landru_free(filmObj); - film->array[index] = nullptr; - } - } - - JBool cutsceneFilm_loadResources(FileStream* file, u8** array, s16 arraySize) - { - for (s32 i = 0; i < arraySize; i++) - { - s32 type; - file->read(&type); - type = TFE_Endian::be32_to_cpu(type); - - char name[32]; - file->readBuffer(name, 8); - name[8] = 0; - - u32 size; - s16 id, chunks, used; - file->read(&size); - file->read(&id); - file->read(&chunks); - file->read(&used); - size = TFE_Endian::le32_to_cpu(size); - id = TFE_Endian::le16_to_cpu(id); - chunks = TFE_Endian::le16_to_cpu(chunks); - used = TFE_Endian::le16_to_cpu(used); - - // Allocate space for the object. - FilmObject* obj = (FilmObject*)landru_alloc(sizeof(FilmObject) + used); - if (!obj) - { - return JFALSE; - } - - obj->resType = type; - strcpy(obj->name, name); - obj->id = id; - obj->offset = 0; - obj->data = nullptr; - - u8* objData = (u8*)obj + sizeof(FilmObject); - file->readBuffer(objData, used); - - array[i] = (u8*)obj; - } - return JTRUE; - } - - LActor* cutsceneFilm_cloneActor(u32 type, const char* name) - { - LActor* curActor = lactor_getList(); - LActor* actor = nullptr; - s32 equal = 0; - while (curActor && !actor) - { - if (type == curActor->resType && strcmp(name, curActor->name) == 0) - { - actor = curActor; - } - curActor = curActor->next; - } - - curActor = nullptr; - if (actor) - { - LRect rect; - lcanvas_getClip(&rect); - - if (actor->resType == CF_TYPE_DELTA_ACTOR) - { - curActor = lactorDelt_alloc(nullptr, &rect, 0, 0, 0); - } - else - { - curActor = lactorAnim_alloc(nullptr, &rect, 0, 0, 0); - } - - if (curActor) - { - lactor_copyData(curActor, actor); - lactor_setName(curActor, type, name); - } - } - return curActor; - } - - LSound* cutsceneFilm_cloneSound(u32 type, const char* name) - { - LSound* curSound = lSoundGetList(); - LSound* sound = nullptr; - - while (curSound && !sound) - { - s32 equal = 0; - if (type == curSound->resType) - { - equal = 1; - - s32 i = 0; - for (; i < 8 && name[i]; i++) - { - if (name[i] != curSound->name[i]) { equal = 0; } - } - if (i < 8 && curSound->name[i] && equal) - { - equal = 0; - } - } - if (equal) - { - sound = curSound; - } - - curSound = curSound->next; - } - - LSound* clonedSound = nullptr; - if (sound) - { - clonedSound = lSoundAlloc(nullptr); - if (clonedSound) - { - copySoundData(clonedSound, sound); - setSoundName(clonedSound, type, name); - } - } - return clonedSound; - } - - JBool cutsceneFilm_readObject(u32 type, const char* name, u8** obj) - { - LRect rect; - lcanvas_getBounds(&rect); - - LActor* actor = nullptr; - LPalette* pal = nullptr; - LSound* sound = nullptr; - JBool retValue = JTRUE; - if (type != CF_TYPE_VIEW && type != CF_TYPE_CUSTOM_ACTOR) - { - if (type == CF_TYPE_DELTA_ACTOR) - { - actor = cutsceneFilm_cloneActor(type, name); - if (!actor) - { - actor = lactorDelt_load(name, &rect, 0, 0, 0); - } - if (!actor) { retValue = JFALSE; } - } - else if (type == CF_TYPE_ANIM_ACTOR) - { - actor = cutsceneFilm_cloneActor(type, name); - if (!actor) - { - actor = lactorAnim_load(name, &rect, 0, 0, 0); - } - if (!actor) { retValue = JFALSE; } - } - else if (type == CF_TYPE_PALETTE) - { - pal = lpalette_load(name); - if (!pal) { retValue = JFALSE; } - } - else if (type == CF_TYPE_GMIDI) - { - sound = nullptr; - assert(0); - if (!sound) { retValue = JFALSE; } - } - else if (type == CF_TYPE_VOC_SOUND) - { - sound = cutsceneFilm_cloneSound(digitalSound, name); - if (!sound) - { - sound = lSoundLoad(name, digitalSound); - } - if (!sound) { retValue = JFALSE; } - } - } - else if (type == CF_TYPE_CUSTOM_ACTOR) - { - actor = lactorCust_alloc(nullptr, &rect, 0, 0, 0); - if (actor) - { - lactor_setDrawFunc(actor, nullptr); - } - if (!actor) { retValue = JFALSE; } - } - - if (actor) - { - lactor_setTime(actor, -1, -1); - *obj = (u8*)actor; - } - else if (pal) - { - *obj = (u8*)pal; - } - else - { - *obj = (u8*)sound; - } - return retValue; - } - - JBool cutsceneFilm_readObjects(Film* film, FilmLoadCallback filmCallback) - { - for (s32 i = 0; i < film->arraySize; i++) - { - FilmObject* obj = (FilmObject*)film->array[i]; - - // Read the object. - if (cutsceneFilm_readObject(obj->resType, obj->name, &obj->data)) - { - if (filmCallback && filmCallback(film, obj)) - { - landru_free(obj->data); - landru_free(obj); - film->array[i] = nullptr; - } - } - else - { - return JFALSE; - } - } - - return JTRUE; - } - - Film* cutsceneFilm_load(const char* name, LRect* frameRect, s16 x, s16 y, s16 z, FilmLoadCallback callback) - { - Film* film = cutsceneFilm_allocate(); - if (!film) { return nullptr; } - - u8** array = nullptr; - FilePath resPath; - char filmName[32]; - sprintf(filmName, "%s.FILM", name); - - if (TFE_Paths::getFilePath(filmName, &resPath)) - { - FileStream file; - file.open(&resPath, Stream::MODE_READ); - - s16 version; - s16 cellCount; - s16 arraySize; - file.read(&version); - file.read(&cellCount); - file.read(&arraySize); - version = TFE_Endian::le16_to_cpu(version); - cellCount = TFE_Endian::le16_to_cpu(cellCount); - arraySize = TFE_Endian::le16_to_cpu(arraySize); - - if (version != CF_VERSION) - { - file.close(); - landru_free(film); - return nullptr; - } - - array = (u8**)landru_alloc(sizeof(u8*) * arraySize); - memset(array, 0, sizeof(u8*) * arraySize); - if (array) - { - film->array = array; - film->arraySize = arraySize; - film->curCell = 0; - film->cellCount = cellCount; - - if (!cutsceneFilm_loadResources(&file, film->array, film->arraySize)) - { - landru_free(film); - landru_free(array); - film = nullptr; - } - } - file.close(); - - if (!cutsceneFilm_readObjects(film, callback)) - { - landru_free(film); - landru_free(array); - film = nullptr; - array = nullptr; - } - } - - if (array) - { - cutsceneFilm_initFilm(film, array, frameRect, x, y, z); - cutsceneFilm_setName(film, CF_TYPE_FILM, name); - } - else - { - landru_free(film); - film = nullptr; - } - - return film; - } - - void cutsceneFilm_setName(Film* film, u32 resType, const char* name) - { - film->resType = resType; - strcpy(film->name, name); - } - - void cutsceneFilm_initFilm(Film* film, u8** array, LRect* frame, s16 x, s16 y, s16 zPlane) - { - film->frameRect = *frame; - film->x = x; - film->y = y; - film->zplane = zPlane; - cutsceneFilm_discardData(film); - - film->drawFunc = nullptr; - film->updateFunc = cutsceneFilm_update; - film->array = array; - - cutsceneFilm_add(film); - } - - void cutsceneFilm_discardData(Film* film) - { - film->flags |= CF_STATE_DISCARD; - } - - void cutsceneFilm_keepData(Film* film) - { - film->flags &= ~CF_STATE_DISCARD; - } - - JBool cutsceneFilm_isTimeStamp(Film* film, FilmObject* filmObj, u8* data) - { - s16* chunk = (s16*)(data + filmObj->offset); - if (TFE_Endian::le16_to_cpu(chunk[1]) == CF_CMD_TIMESTAMP && TFE_Endian::le16_to_cpu(chunk[2]) == (s16)film->curCell) - { - return JTRUE; - } - return JFALSE; - } - - void cutsceneFilm_rewindView(Film* film, FilmObject* filmObj, u8* data) - { - filmObj->offset = 0; - if (cutsceneFilm_isTimeStamp(film, filmObj, data)) - { - cutsceneFilm_stepView(film, filmObj, data); - } - } - - void cutsceneFilm_rewindPalette(Film* film, FilmObject* filmObj, u8* data) - { - filmObj->offset = 0; - if (cutsceneFilm_isTimeStamp(film, filmObj, data)) - { - cutsceneFilm_stepPalette(film, filmObj, data); - } - } - - void cutsceneFilm_rewindActor(Film* film, FilmObject* filmObj, u8* data) - { - LActor* actor = (LActor*)filmObj->data; - lcanvas_getClip(&actor->frame); - - lactor_setPos(actor, 0, 0, 0, 0); - lactor_setSpeed(actor, 0, 0, 0, 0); - lactor_setState(actor, 0, 0); - lactor_setZPlane(actor, 0); - lactor_setFlip(actor, JFALSE, JFALSE); - - if (lactor_isVisible(actor)) - { - lactor_hide(actor); - } - - actor->var1 = 0; - actor->var2 = 0; - filmObj->offset = 0; - - if (cutsceneFilm_isTimeStamp(film, filmObj, data)) - { - cutsceneFilm_stepActor(film, filmObj, data); - } - } - - void cutsceneFilm_rewindSound(Film* film, FilmObject* filmObj, u8* data) - { - LSound* sound = (LSound*)filmObj->data; - filmObj->offset = 0; - - stopSound(sound); - sound->var1 = 0; - sound->var2 = 0; - - if (cutsceneFilm_isTimeStamp(film, filmObj, data)) - { - cutsceneFilm_stepSound(film, filmObj, data); - } - } - - void cutsceneFilm_rewindObjects(Film* film) - { - film->curCell = 0; - - // Store the screen palette. - lpalette_copyScreenToDest(0, 0, 255); - lpalette_copyScreenToSrc(0, 0, 255); - // Clear the palette - lpalette_setDstColor(0, 255, 0, 0, 0); - - if (film->def_palette) - { - lpalette_setDstPal(film->def_palette); - } - - for (s32 i = 0; i < film->arraySize; i++) - { - FilmObject* filmObj = (FilmObject*)film->array[i]; - if (filmObj) - { - switch (filmObj->id) - { - case CF_FILE_VIEW: - { - cutsceneFilm_rewindView(film, filmObj, (u8*)(filmObj + 1)); - } break; - case CF_FILE_PALETTE: - { - cutsceneFilm_rewindPalette(film, filmObj, (u8*)(filmObj + 1)); - } break; - case CF_FILE_ACTOR: - { - cutsceneFilm_rewindActor(film, filmObj, (u8*)(filmObj + 1)); - } break; - case CF_FILE_SOUND: - { - cutsceneFilm_rewindSound(film, filmObj, (u8*)(filmObj + 1)); - } break; - } - } - } - - if (!lpalette_compareSrcDst()) - { - if (cutsceneFilm_isFading()) - { - cutsceneFilm_startFade(JTRUE); - } - else if (!lfade_isActive()) - { - lfade_startColorFade(fcolorType_snapColorFade, JTRUE, 1, 0, 1); - } - else - { - lpalette_copyDstToScreen(0, 0, 255); - lpalette_putScreenPal(); - } - } - else if (cutsceneFilm_isFading()) - { - cutsceneFilm_startFade(JFALSE); - } - - // Advance to the next frame. - film->curCell++; - } - - void cutsceneFilm_stepFilmFrame(FilmObject* filmObj, u8* data) - { - s16* chunk = (s16*)(data + filmObj->offset); - filmObj->offset += TFE_Endian::le16_to_cpu(chunk[0]); - } - - JBool cutsceneFilm_isNextFrame(FilmObject* filmObj, u8* data) - { - s16* chunk = (s16*)(data + filmObj->offset); - if (TFE_Endian::le16_to_cpu(chunk[1]) == CF_CMD_TIMESTAMP || TFE_Endian::le16_to_cpu(chunk[1]) == CF_CMD_END) - { - return JTRUE; - } - return JFALSE; - } - - void cutsceneFilm_setActorToFilm(FilmObject* filmObj, u8* data) - { - s16* chunk = (s16*)(data + filmObj->offset); - u32 type = TFE_Endian::le16_to_cpu(chunk[1]); - LActor* actor = (LActor*)filmObj->data; - chunk += 2; - - switch (type) - { - case CF_CMD_ACTOR_POS: - lactor_setPos(actor, TFE_Endian::le16_to_cpu(chunk[0]), TFE_Endian::le16_to_cpu(chunk[1]), TFE_Endian::le16_to_cpu(chunk[2]), TFE_Endian::le16_to_cpu(chunk[3])); - break; - - case CF_CMD_ACTOR_VEL: - lactor_setSpeed(actor, TFE_Endian::le16_to_cpu(chunk[0]), TFE_Endian::le16_to_cpu(chunk[1]), TFE_Endian::le16_to_cpu(chunk[2]), TFE_Endian::le16_to_cpu(chunk[3])); - break; - - case CF_CMD_ACTOR_Z: - lactor_setZPlane(actor, TFE_Endian::le16_to_cpu(chunk[0])); - break; - - case CF_CMD_ACTOR_STATE: - lactor_setState(actor, TFE_Endian::le16_to_cpu(chunk[0]), TFE_Endian::le16_to_cpu(chunk[1])); - break; - - case CF_CMD_ACTOR_STATEV: - lactor_setStateSpeed(actor, TFE_Endian::le16_to_cpu(chunk[0]), TFE_Endian::le16_to_cpu(chunk[1])); - break; - - case CF_CMD_ACTOR_VAR1: - actor->var1 = TFE_Endian::le16_to_cpu(chunk[0]); - break; - - case CF_CMD_ACTOR_VAR2: - actor->var2 = TFE_Endian::le16_to_cpu(chunk[0]); - break; - - case CF_CMD_ACTOR_CLIP: - lrect_set(&actor->frame, TFE_Endian::le16_to_cpu(chunk[0]), TFE_Endian::le16_to_cpu(chunk[1]), TFE_Endian::le16_to_cpu(chunk[2]), TFE_Endian::le16_to_cpu(chunk[3])); - break; - - case CF_CMD_ACTOR_CLIPV: - lrect_set(&actor->frameVelocity, TFE_Endian::le16_to_cpu(chunk[0]), TFE_Endian::le16_to_cpu(chunk[1]), TFE_Endian::le16_to_cpu(chunk[2]), TFE_Endian::le16_to_cpu(chunk[3])); - break; - - case CF_CMD_ACTOR_SHOW: - if (TFE_Endian::le16_to_cpu(chunk[0])) { lactor_show(actor); } - else { lactor_hide(actor); } - break; - - case CF_CMD_ACTOR_FLIP: - lactor_setFlip(actor, TFE_Endian::le16_to_cpu(chunk[0]), TFE_Endian::le16_to_cpu(chunk[1])); - break; - } - } - - void cutsceneFilm_setViewToFilm(Film* film, FilmObject* filmObj, u8* data) - { - s16* chunk = (s16*)(data + filmObj->offset); - u8* byteChunk = (u8*)chunk; - u16 type = TFE_Endian::le16_to_cpu(chunk[1]); - - switch (type) - { - case CF_CMD_VIEW_SETRGB: - { - u16 start = (u16)byteChunk[4]; - u16 stop = (u16)byteChunk[5]; - u16 r = (u16)byteChunk[6]; - u16 g = (u16)byteChunk[7]; - u16 b = (u16)byteChunk[8]; - - lpalette_setDstColor(start, stop, r, g, b); - } break; - case CF_CMD_VIEW_DEFPAL: - { - lpalette_setDstColor(0, 255, 0, 0, 0); - if (film->def_palette) - { - lpalette_setDstPal(film->def_palette); - } - } break; - case CF_CMD_VIEW_FADE: - { - s16 fade = TFE_Endian::le16_to_cpu(chunk[2]); - s16 colorFade = TFE_Endian::le16_to_cpu(chunk[3]); - cutsceneFilm_setFade(fade, colorFade); - } break; - } - } - - void cutsceneFilm_setPaletteToFilm(Film* film, FilmObject* filmObj, u8* data) - { - s16* chunk = (s16*)(data + filmObj->offset); - if (TFE_Endian::le16_to_cpu(chunk[1]) == CF_CMD_PALETTE_SET) - { - lpalette_setDstPal((LPalette*)filmObj->data); - } - } - - void cutsceneFilm_setSoundToFilm(Film* film, FilmObject* filmObj, u8* data) - { - LSound* sound = (LSound*)filmObj->data; - s16* chunk = (s16*)(data + filmObj->offset); - u16 type = TFE_Endian::le16_to_cpu(chunk[1]); - chunk += 2; - - switch (type) - { - case CF_CMD_SOUND_START: - { - if (sound->var2 == 1) - { - startSpeech(sound); - } - else - { - startSfx(sound); - } - } break; - case CF_CMD_SOUND_STOP: - { - stopSound(sound); - } break; - case CF_CMD_SOUND_VOLUME: - { - setSoundVolume(sound, TFE_Endian::le16_to_cpu(chunk[0])); - } break; - case CF_CMD_SOUND_FADE: - { - setSoundFade(sound, TFE_Endian::le16_to_cpu(chunk[0]), TFE_Endian::le16_to_cpu(chunk[1])); - } break; - case CF_CMD_SOUND_VAR1: - { - sound->var1 = TFE_Endian::le16_to_cpu(chunk[0]); - if (sound->var1 == 1) - { - setSoundKeep(sound); - } - } break; - case CF_CMD_SOUND_VAR2: - { - sound->var2 = TFE_Endian::le16_to_cpu(chunk[0]); - } break; - case CF_CMD_SOUND_CMD: - { - if (TFE_Endian::le16_to_cpu(chunk[0])) - { - if (sound->var2 == 1) - { - startSpeech(sound); - } - else - { - startSfx(sound); - } - } - - if (TFE_Endian::le16_to_cpu(chunk[1])) { setSoundVolume(sound, TFE_Endian::le16_to_cpu(chunk[1])); } - if (TFE_Endian::le16_to_cpu(chunk[2]) || TFE_Endian::le16_to_cpu(chunk[3])) - { - setSoundFade(sound, TFE_Endian::le16_to_cpu(chunk[2]), TFE_Endian::le16_to_cpu(chunk[3])); - } - } break; - case CF_CMD_SOUND_CMD2: - { - if (TFE_Endian::le16_to_cpu(chunk[0])) - { - if (sound->var2 == 1) - { - startSpeech(sound); - } - else - { - startSfx(sound); - } - } - - if (TFE_Endian::le16_to_cpu(chunk[1])) { setSoundVolume(sound, TFE_Endian::le16_to_cpu(chunk[1])); } - if (TFE_Endian::le16_to_cpu(chunk[2]) || TFE_Endian::le16_to_cpu(chunk[3])) - { - setSoundFade(sound, TFE_Endian::le16_to_cpu(chunk[2]), TFE_Endian::le16_to_cpu(chunk[3])); - } - - if (TFE_Endian::le16_to_cpu(chunk[4])) { setSoundPan(sound, TFE_Endian::le16_to_cpu(chunk[4])); } - if (TFE_Endian::le16_to_cpu(chunk[5]) || TFE_Endian::le16_to_cpu(chunk[6])) { setSoundPanFade(sound, TFE_Endian::le16_to_cpu(chunk[5]), TFE_Endian::le16_to_cpu(chunk[6])); } - } break; - } - } - - void cutsceneFilm_setFade(s16 fade, s16 colorFade) - { - s_filmState.filmFade = (FadeType)fade; - s_filmState.filmColorFade = (FadeColorType)colorFade; - } - - void cutsceneFilm_clearFade() - { - s_filmState.filmFade = ftype_noFade; - s_filmState.filmColorFade = fcolorType_noColorFade; - } - - void cutsceneFilm_startFade(JBool paletteChange) - { - s16 lock = 1; - if (s_filmState.filmColorFade == fcolorType_paletteColorFade && s_filmState.filmFade <= ftype_longSnapFade) - { - lock = 0; - } - - lfade_startFull(s_filmState.filmFade, s_filmState.filmColorFade, paletteChange, 0, lock); - cutsceneFilm_clearFade(); - } - - JBool cutsceneFilm_isFading() - { - return (s_filmState.filmFade == ftype_noFade && s_filmState.filmColorFade == fcolorType_noColorFade) ? JFALSE : JTRUE; - } - - void cutsceneFilm_stepActor(Film* film, FilmObject* filmObj, u8* data) - { - LActor* actor = (LActor*)filmObj->data; - if (actor && actor->updateFunc) - { - actor->updateFunc(actor); - } - - if (cutsceneFilm_isTimeStamp(film, filmObj, data)) - { - cutsceneFilm_stepFilmFrame(filmObj, data); - while (!cutsceneFilm_isNextFrame(filmObj, data)) - { - cutsceneFilm_setActorToFilm(filmObj, data); - cutsceneFilm_stepFilmFrame(filmObj, data); - } - } - } - - void cutsceneFilm_stepView(Film* film, FilmObject* filmObj, u8* data) - { - if (cutsceneFilm_isTimeStamp(film, filmObj, data)) - { - cutsceneFilm_stepFilmFrame(filmObj, data); - while (!cutsceneFilm_isNextFrame(filmObj, data)) - { - cutsceneFilm_setViewToFilm(film, filmObj, data); - cutsceneFilm_stepFilmFrame(filmObj, data); - } - } - } - - void cutsceneFilm_stepPalette(Film* film, FilmObject* filmObj, u8* data) - { - if (cutsceneFilm_isTimeStamp(film, filmObj, data)) - { - cutsceneFilm_stepFilmFrame(filmObj, data); - while (!cutsceneFilm_isNextFrame(filmObj, data)) - { - cutsceneFilm_setPaletteToFilm(film, filmObj, data); - cutsceneFilm_stepFilmFrame(filmObj, data); - } - } - } - - void cutsceneFilm_stepSound(Film* film, FilmObject* filmObj, u8* data) - { - if (cutsceneFilm_isTimeStamp(film, filmObj, data)) - { - cutsceneFilm_stepFilmFrame(filmObj, data); - while (!cutsceneFilm_isNextFrame(filmObj, data)) - { - cutsceneFilm_setSoundToFilm(film, filmObj, data); - cutsceneFilm_stepFilmFrame(filmObj, data); - } - } - } - - void cutsceneFilm_stepObjects(Film* film) - { - if (!lfade_isActive()) - { - lpalette_copyScreenToDest(0, 0, 255); - lpalette_copyScreenToSrc(0, 0, 255); - } - - u8** array = film->array; - for (s32 i = 0; i < film->arraySize; i++) - { - FilmObject* filmObj = (FilmObject*)array[i]; - if (filmObj) - { - switch (filmObj->id) - { - case CF_FILE_VIEW: - cutsceneFilm_stepView(film, filmObj, (u8*)(filmObj + 1)); - break; - case CF_FILE_PALETTE: - cutsceneFilm_stepPalette(film, filmObj, (u8*)(filmObj + 1)); - break; - case CF_FILE_ACTOR: - cutsceneFilm_stepActor(film, filmObj, (u8*)(filmObj + 1)); - break; - case CF_FILE_SOUND: - cutsceneFilm_stepSound(film, filmObj, (u8*)(filmObj + 1)); - break; - } - } - } - - if (!lfade_isActive()) - { - if (!lpalette_compareSrcDst()) - { - if (cutsceneFilm_isFading()) - { - cutsceneFilm_startFade(JTRUE); - } - else if (!lfade_isActive()) - { - lfade_startColorFade(fcolorType_snapColorFade, JTRUE, 1, 0, 1); - } - else - { - lpalette_copyDstToScreen(0, 0, 255); - lpalette_putScreenPal(); - } - } - else if (cutsceneFilm_isFading()) - { - cutsceneFilm_startFade(JFALSE); - } - } - - film->curCell++; - } - - void cutsceneFilm_update(Film* film) - { - cutsceneFilm_stepObjects(film); - } - - void cutsceneFilm_updateCallbacks(s32 time) - { - Film* film = s_filmState.firstFilm; - while (film) - { - if (film->callback) - { - film->callback(film, time); - } - film = film->next; - } - } - - void cutsceneFilm_start(Film* film) - { - cutsceneFilm_rewind(film); - film->flags |= (CF_STATE_VISIBLE | CF_STATE_ACTIVE); - } - - void cutsceneFilm_stop(Film* film) - { - film->flags &= ~(CF_STATE_VISIBLE | CF_STATE_ACTIVE); - } - - void cutsceneFilm_rewind(Film* film) - { - cutsceneFilm_rewindObjects(film); - } - - JBool cutsceneFilm_isActive(Film* film) - { - return (film->flags & CF_STATE_ACTIVE) ? JTRUE : JFALSE; - } - - JBool cutsceneFilm_isLooping(Film* film) - { - return (film->flags & CF_STATE_REPEAT) ? JTRUE : JFALSE; - } - - void cutsceneFilm_updateFilms(s32 time) - { - Film* film = s_filmState.firstFilm; - while (film) - { - if (film->start == time) - { - cutsceneFilm_start(film); - if (film->stop == time) - { - cutsceneFilm_stop(film); - } - } - else if (film->stop == time) - { - cutsceneFilm_stop(film); - } - else if (!film->cellCount) - { - if (cutsceneFilm_isActive(film)) - { - cutsceneFilm_stop(film); - } - } - else if (film->curCell >= film->cellCount) - { - if (cutsceneFilm_isLooping(film)) - { - cutsceneFilm_rewind(film); - } - else - { - cutsceneFilm_stop(film); - } - } - else - { - if (film->updateFunc && cutsceneFilm_isActive(film)) - { - film->updateFunc(film); - } - } - - film = film->next; - } - } - - void cutsceneFilm_getRelativePos(Film* film, LRect* rect, s16* x, s16* y) - { - *x = film->x - film->frameRect.left + rect->left; - *y = film->y - film->frameRect.top + rect->top; - } - - void cutsceneFilm_drawFilms(JBool refresh) - { - Film* film = s_filmState.firstFilm; - for (s32 i = 0; i < LVIEW_COUNT; i++) - { - LRect rect; - lview_getFrame(i, &rect); - if (lrect_isEmpty(&rect)) { continue; } - - Film* curFilm = film; - while (curFilm) - { - LRect clipRect; - if (curFilm->drawFunc && (curFilm->flags & CF_STATE_VISIBLE) && lview_clipObjToView(i, curFilm->zplane, &curFilm->frameRect, &rect, &clipRect)) - { - JBool curRefresh = (curFilm->flags & CF_STATE_REFRESH) | (curFilm->flags & CF_STATE_REFRESHABLE) | refresh; - lcanvas_setClip(&clipRect); - - s16 x, y; - cutsceneFilm_getRelativePos(curFilm, &rect, &x, &y); - curFilm->drawFunc(curFilm, &rect, &clipRect, x, y, curRefresh); - } - - curFilm = curFilm->next; - } - } - - for (Film* curFilm = film; curFilm; curFilm = curFilm->next) - { - curFilm->flags &= ~CF_STATE_REFRESH; - } - } - - void cutsceneFilm_add(Film* film) - { - Film* curFilm = s_filmState.firstFilm; - Film* lastFilm = nullptr; - while (curFilm && curFilm->zplane > film->zplane) - { - lastFilm = curFilm; - curFilm = curFilm->next; - } - - film->next = curFilm; - if (!lastFilm) - { - s_filmState.firstFilm = film; - } - else - { - lastFilm->next = film; - } - } - - void cutsceneFilm_remove(Film* film) - { - if (!film) { return; } - - Film* curFilm = s_filmState.firstFilm; - Film* lastFilm = nullptr; - while (curFilm && curFilm != film) - { - lastFilm = curFilm; - curFilm = curFilm->next; - } - - if (curFilm == film) - { - if (!lastFilm) - { - s_filmState.firstFilm = curFilm->next; - } - else - { - lastFilm->next = curFilm->next; - } - film->next = nullptr; - } - } -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/cutscene_film.h b/components/darkforces/tfe/TFE_DarkForces/Landru/cutscene_film.h deleted file mode 100644 index 7e5861fa..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/cutscene_film.h +++ /dev/null @@ -1,144 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces "Film" format -// This handles loading and processing the cutscene "film" format, -// though it doesn't handle playback. -////////////////////////////////////////////////////////////////////// -#include -#include -#include "cutscene.h" -#include "lpalette.h" - -namespace TFE_DarkForces -{ - enum CutsceneFilmConstants : u32 - { - // Header - CF_VERSION = 4, - // Types - CF_TYPE_FILM = 0x46494c4d, // 'FILM' - CF_TYPE_VIEW = 0x56494557, // 'VIEW' - CF_TYPE_CUSTOM_ACTOR = 0x43555354, // 'CUST' - CF_TYPE_DELTA_ACTOR = 0x44454c54, // 'DELT' - CF_TYPE_ANIM_ACTOR = 0x414e494d, // 'ANIM' - CF_TYPE_PALETTE = 0x504c5454, // 'PLTT' - CF_TYPE_GMIDI = 0x474d4944, // 'GMID' - CF_TYPE_VOC_SOUND = 0x564f4943, // 'BLAS' - - // Files - CF_FILE_NULL = 0, - CF_FILE_END, - CF_FILE_VIEW, - CF_FILE_ACTOR, - CF_FILE_PALETTE, - CF_FILE_SOUND, - - // Commands - CF_CMD_NONE = 0, - CF_CMD_DELETE, - CF_CMD_END, - CF_CMD_TIMESTAMP, - CF_CMD_ACTOR_POS, - CF_CMD_ACTOR_VEL, - CF_CMD_ACTOR_Z, - CF_CMD_ACTOR_STATE, - CF_CMD_ACTOR_STATEV, - CF_CMD_ACTOR_VAR1, - CF_CMD_ACTOR_VAR2, - CF_CMD_ACTOR_CLIP, - CF_CMD_ACTOR_CLIPV, - CF_CMD_ACTOR_SHOW, - CF_CMD_ACTOR_FLIP, - CF_CMD_PALETTE_SET, - CF_CMD_VIEW_SETRGB, - CF_CMD_VIEW_DEFPAL, - CF_CMD_VIEW_FADE, - CF_CMD_SOUND_START, - CF_CMD_SOUND_STOP, - CF_CMD_SOUND_VOLUME, - CF_CMD_SOUND_FADE, - CF_CMD_SOUND_VAR1, - CF_CMD_SOUND_VAR2, - CF_CMD_SOUND_CMD, - CF_CMD_SOUND_PAN, - CF_CMD_SOUND_PAN_FADE, - CF_CMD_SOUND_CMD2, - - // State - CF_STATE_VISIBLE = FLAG_BIT(0), - CF_STATE_ACTIVE = FLAG_BIT(1), - CF_STATE_DISCARD = FLAG_BIT(2), - CF_STATE_REFRESHABLE = FLAG_BIT(3), - CF_STATE_REFRESH = FLAG_BIT(4), - CF_STATE_REPEAT = FLAG_BIT(5), - CF_STATE_USER_FLAG1 = FLAG_BIT(14), - CF_STATE_USER_FLAG2 = FLAG_BIT(15), - }; - - struct FilmObject - { - u32 resType; - char name[16]; - u32 id; - u32 offset; - u8* data; - }; - - struct Film; - - typedef JBool(*FilmDrawFunc)(Film*, LRect*, LRect*, s16, s16, JBool); - typedef void(*FilmUpdateFunc)(Film*); - typedef JBool(*FilmCallback)(Film*, s32); - typedef JBool(*FilmLoadCallback)(Film*, FilmObject*); - - struct Film - { - u32 resType; - char name[16]; - Film* next; - LPalette* def_palette; - - s32 start; - s32 stop; - - LRect frameRect; - u32 flags; - - s16 zplane; - s16 x; - s16 y; - - u16 cellCount; - u16 curCell; - - s16 var1; - s16 var2; - u8* varPtr; - u8* varPtr2; // varhdl - - u8** array; - s16 arraySize; - - FilmDrawFunc drawFunc; - FilmUpdateFunc updateFunc; - FilmCallback callback; - }; - - void cutsceneFilm_reset(); - - Film* cutsceneFilm_allocate(); - void cutsceneFilm_free(Film* film); - - Film* cutsceneFilm_load(const char* name, LRect* frameRect, s16 x, s16 y, s16 z, FilmLoadCallback callback); - void cutsceneFilm_discardData(Film* film); - void cutsceneFilm_keepData(Film* film); - void cutsceneFilm_rewindActor(Film* film, FilmObject* filmObj, u8* data); - void cutsceneFilm_stepActor(Film* film, FilmObject* filmObj, u8* data); - - void cutsceneFilm_add(Film* film); - void cutsceneFilm_remove(Film* film); - - void cutsceneFilm_updateFilms(s32 time); - void cutsceneFilm_updateCallbacks(s32 time); - void cutsceneFilm_drawFilms(JBool refresh); -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/cutscene_player.cpp b/components/darkforces/tfe/TFE_DarkForces/Landru/cutscene_player.cpp deleted file mode 100644 index fb053218..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/cutscene_player.cpp +++ /dev/null @@ -1,349 +0,0 @@ -#include "cutscene_player.h" -#include "cutscene_film.h" -#include "lcanvas.h" -#include "lmusic.h" -#include "lsound.h" -#include "lsystem.h" -#include "time.h" -#include "textCrawl.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - enum CutsceneInternalConstants - { - TEXTCRAWL_SCENE = 30, - MIN_FPS = 4, - MAX_FPS = 20, - CUT_TICKS_PER_SECOND = 240, - }; - - // Note that the cutscene player seems to operate at a rate of 240 ticks / second. - // Also note that some values don't match, for example 5 fps is 48 ticks delay and htere it is marked as 49. - // 42 ticks delay is obviously wrong for 4 fps (it should be 60). It looks like this table was adjusted for the desired - // look instead of the source data. - static const s32 c_frameRateDelay[] = - { - 42, - 49, - 40, - 35, - 31, - 28, - 25, - 23, - 20, - 19, - 17, - 16, - 15, - 14, - 13, - 12, - 12, - }; - - static s32 s_scene = SCENE_EXIT; - static s32 s_playId = 0; - static LTick s_frameDelay; - static LActor* s_textCrawl = nullptr; - static Film* s_film = nullptr; - - extern CutsceneState* s_playSeq; - extern s32 s_soundVolume; - extern s32 s_musicVolume; - extern s32 s_enabled; - - static JBool s_skipSceneInput = JFALSE; - static JBool s_nextSceneInput = JFALSE; - static JBool s_cutscenePause = JFALSE; - static JBool s_cutsceneStepFrame = JFALSE; - - void cutscene_customSoundCallback(LActor* actor, s32 time); - s32 lcutscenePlayer_endView(s32 time); - - void cutscenePlayer_setFramerate(s32 fps) - { - fps = clamp(fps, MIN_FPS, MAX_FPS); - s_frameDelay = c_frameRateDelay[fps - MIN_FPS]; - ltime_setFrameDelay(s_frameDelay); - } - - JBool cutscene_loadCallback(Film* film, FilmObject* obj) - { - if (obj->id == CF_FILE_ACTOR) - { - LActor* actor = (LActor*)obj->data; - if (actor->resType == CF_TYPE_CUSTOM_ACTOR) - { - // custom actors send midi cue points. - lactor_setCallback(actor, cutscene_customSoundCallback); - } - } - else if (obj->id == CF_FILE_SOUND) - { - LSound* sound = (LSound*)obj->data; - if (sound->var2 > 0) - { - setSoundKeep(sound); - } - } - return JFALSE; - } - - void cutscenePlayer_start(s32 sceneId) - { - s_scene = sceneId; - s_textCrawl = nullptr; - - // Find current scene. - s_playId = 0; - while (sceneId != s_playSeq[s_playId].id && s_playSeq[s_playId].id != SCENE_EXIT) - { - s_playId++; - } - - // Start the next sequence of MIDI music. - if (s_playSeq[s_playId].music > 0) - { - lmusic_setSequence(s_playSeq[s_playId].music); - } - - Archive* lfd = nullptr; - if (s_playSeq[s_playId].id != SCENE_EXIT) - { - FilePath path; - if (!TFE_Paths::getFilePath(s_playSeq[s_playId].archive, &path)) - { - s_scene = SCENE_EXIT; - return; - } - lfd = new LfdArchive(); - if (!lfd->open(path.path)) - { - delete lfd; - s_scene = SCENE_EXIT; - return; - } - TFE_Paths::addLocalArchiveToFront(lfd); - - char name[16]; - CutsceneState* scene = &s_playSeq[s_playId]; - strcpy(name, scene->scene); -#ifdef TFE_ESPBOX - printf("[DarkForces] cutscene scene %d: '%s' from '%s' (next %d, skip %d, music %d, speed %d)\n", - (int)scene->id, scene->scene, scene->archive, (int)scene->nextId, (int)scene->skip, (int)scene->music, (int)scene->speed); -#endif - cutscenePlayer_setFramerate(scene->speed); - - // Set the sound and music volume. - s32 baseMusicVol = cutscene_getMusicVolume(); - if (baseMusicVol > 0) // Set music volume as percentage of the base volume. - { - s32 v = clamp(baseMusicVol * scene->volume / 100, 0, 127); - // ImSetMusicVol(v); - } - // ImSetSfxVol(cutscene_getSoundVolume()); - - // Load & Setup - LRect rect; - lcanvas_getBounds(&rect); - - lsystem_setAllocator(LALLOC_CUTSCENE); - s_film = cutsceneFilm_load(name, &rect, 0, 0, 0, cutscene_loadCallback); - if (!s_film) - { - TFE_Paths::removeFirstArchive(); - delete lfd; - - s_scene = SCENE_EXIT; - TFE_System::logWrite(LOG_ERROR, "CutscenePlayer", "Unable to load all items in cutscene '%s'.", name); - return; - } - lview_setUpdateFunc(lcutscenePlayer_endView); - - // Close the archive. - TFE_Paths::removeFirstArchive(); - delete lfd; - - // Text Crawl handling - if (sceneId == TEXTCRAWL_SCENE) - { - s_textCrawl = lactor_find(CF_TYPE_DELTA_ACTOR, "textcraw"); - if (s_textCrawl) - { - openTextCrawl(s_textCrawl, s_film); - } - } - - // In the original code, the playback loop starts here, and then the cleanup afterward. - // For TFE, the function will return and then cutscenePlayer_update() will handle each frame. - lview_startLoop(); - } - else - { - s_scene = SCENE_EXIT; - } - } - - void cutscenePlayer_stop() - { - if (s_textCrawl) - { - closeTextCrawl(s_textCrawl); - s_textCrawl = nullptr; - } - lview_clearUpdateFunc(); - } - -#ifdef TFE_ESPBOX - void cutscenePlayer_abort() - { - if (s_scene == SCENE_EXIT) { return; } - lview_endLoop(); - cutscenePlayer_stop(); - cutsceneFilm_remove(s_film); - cutsceneFilm_free(s_film); - s_film = nullptr; - freeSoundList(lSoundGetList()); - lmusic_stop(); - vfb_forceToBlack(); - lcanvas_clear(); - lsystem_clearAllocator(LALLOC_CUTSCENE); - lsystem_setAllocator(LALLOC_PERSISTENT); - s_scene = SCENE_EXIT; - } -#endif - - JBool cutscenePlayer_update() - { - if (s_scene == SCENE_EXIT) { return JFALSE; } - - // TFE: Added since inputs can be skipped at low framerates. - // Ignore Enter key if player is pressing Alt-Enter (to switch between windowed and fullscreen) - if (TFE_Input::keyPressed(KEY_ESCAPE) || (TFE_Input::keyPressed(KEY_RETURN) && !TFE_Input::keyDown(KEY_LALT) - && !TFE_Input::keyDown(KEY_RALT))) - { - s_skipSceneInput = JTRUE; - } - else if (TFE_Input::keyPressed(KEY_SPACE)) - { - s_nextSceneInput = JTRUE; - if (TFE_A11Y::cutsceneCaptionsEnabled()) TFE_A11Y::clearCaptions(); - } - - ///////////////////////////////// - // DEBUG: Single step cutscenes. - if (TFE_Input::keyPressed(KEY_PAUSE)) - { - s_cutscenePause = ~s_cutscenePause; - } - - s_cutsceneStepFrame = JFALSE; - if (s_cutscenePause && TFE_Input::keyPressed(KEY_BACKSPACE)) - { - s_cutsceneStepFrame = JTRUE; - } - ///////////////////////////////// - - JBool stepView = JFALSE; - if (s_cutscenePause) - { - stepView = s_cutsceneStepFrame; - } - else - { - tfe_updateLTime(); - stepView = ltime_isFrameReady(); - } - - if (stepView) - { - s32 exitValue = lview_loop(); - if (exitValue != VIEW_LOOP_RUNNING) - { - lview_endLoop(); - cutscenePlayer_stop(); - cutsceneFilm_remove(s_film); - cutsceneFilm_free(s_film); - s_film = nullptr; - - if (exitValue != SCENE_EXIT) - { - cutscenePlayer_start(exitValue); - } - else - { - s_scene = SCENE_EXIT; - } - } - } - - if (s_scene == SCENE_EXIT) - { - lmusic_stop(); - lsystem_clearAllocator(LALLOC_CUTSCENE); - lsystem_setAllocator(LALLOC_PERSISTENT); - } - - return s_scene != SCENE_EXIT ? JTRUE : JFALSE; - } - - s32 lcutscenePlayer_endView(s32 time) - { - s16 nextScene = s_playSeq[s_playId].nextId; - s16 skipScene = s_playSeq[s_playId].skip; - - if (s_skipSceneInput) - { - s_skipSceneInput = JFALSE; - freeSoundList(lSoundGetList()); - lmusic_stop(); - vfb_forceToBlack(); - lcanvas_clear(); - return skipScene; - } - else if (s_nextSceneInput) - { - s_nextSceneInput = JFALSE; - freeSoundList(lSoundGetList()); - vfb_forceToBlack(); - lcanvas_clear(); - return nextScene; - } - else if (s_film->curCell >= s_film->cellCount) - { -#ifdef TFE_ESPBOX - // Release this scene's sounds, as the skip path above does. They live in the - // game region, which is never cleared during a sequence: across the twelve - // post-mission scenes they added up to over 1MB, which the 8MB box does not - // have. The next scene reloads whatever it needs (sounds marked "keep" survive). - freeSoundList(lSoundGetList()); -#endif - return nextScene; - } - - return VIEW_LOOP_RUNNING; - } - - void cutscene_customSoundCallback(LActor* actor, s32 time) - { - const s32 var1 = actor->var1; - if (var1) - { - lmusic_setCuePoint(max(0, var1)); - } - } -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/cutscene_player.h b/components/darkforces/tfe/TFE_DarkForces/Landru/cutscene_player.h deleted file mode 100644 index 5a48a189..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/cutscene_player.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces Cutscene Player -// This gets initialized by the cutscene system and handles the actual -// playback. -////////////////////////////////////////////////////////////////////// -#include -#include "cutscene.h" - -namespace TFE_DarkForces -{ - void cutscenePlayer_start(s32 scene); - void cutscenePlayer_stop(); -#ifdef TFE_ESPBOX - // Stop a running cutscene sequence right away (as if it had reached SCENE_EXIT): - // frees the current film and its actors and clears the cutscene memory. - void cutscenePlayer_abort(); -#endif - - // Returns JTRUE if we want to continue playing. - // Note: this is a little different than the original code, which ran in a while loop until finished. - JBool cutscenePlayer_update(); -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/lactor.cpp b/components/darkforces/tfe/TFE_DarkForces/Landru/lactor.cpp deleted file mode 100644 index 3df3e671..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/lactor.cpp +++ /dev/null @@ -1,830 +0,0 @@ -#include "lactor.h" -#include "lsystem.h" -#include "lcanvas.h" -#include "lview.h" -#include "ltimer.h" -#include -#include -#include - -namespace TFE_DarkForces -{ - static JBool s_lactorInit = JFALSE; - static JBool s_zPlaneBuild = JFALSE; - static JBool s_refreshActors; - static LActorType* s_actorType = nullptr; - static LActor* s_actorList = nullptr; - - void lactor_freeData(LActor* actor); - - void lactor_init() - { - s_lactorInit = JTRUE; - s_actorType = nullptr; - s_actorList = nullptr; - } - - void lactor_destroy() - { - s_lactorInit = JFALSE; - s_actorType = nullptr; - s_actorList = nullptr; - } - - JBool lactor_createType(u32 type, LActorFrameFunc frameFunc, LActorStateFunc stateFunc) - { - assert(s_lactorInit); - LActorType* newType = (LActorType*)landru_alloc(sizeof(LActorType)); - if (newType) - { - newType->type = type; - newType->frameFunc = frameFunc; - newType->stateFunc = stateFunc; - - newType->next = s_actorType; - s_actorType = newType; - } - return (newType) ? JTRUE : JFALSE; - } - - void lactor_destroyType(u32 type) - { - LActorType* newType = s_actorType; - LActorType* lastType = nullptr; - while (newType && newType->type != type) - { - lastType = newType; - newType = newType->next; - } - - if (newType) - { - if (lastType) { lastType->next = newType->next; } - else { s_actorType = s_actorType->next; } - - landru_free(newType); - } - } - - LActorType* lactor_findType(u32 type) - { - LActorType* curType = s_actorType; - while (curType && curType->type != type) - { - curType = curType->next; - } - return curType; - } - - LActor* lactor_getList() - { - return s_actorList; - } - - void lactor_addActor(LActor* actor) - { - LActor* curActor = s_actorList; - LActor* lastActor = nullptr; - - while (curActor && curActor->zplane > actor->zplane) - { - lastActor = curActor; - curActor = curActor->next; - } - - if (!lastActor) - { - actor->next = curActor; - s_actorList = actor; - } - else - { - actor->next = curActor; - lastActor->next = actor; - } - - actor->id = 0; - } - - void lactor_removeActor(LActor* actor) - { - if (!actor) { return; } - - LActor* curActor = s_actorList; - LActor* lastActor = nullptr; - - while (curActor && curActor != actor) - { - lastActor = curActor; - curActor = curActor->next; - } - - if (curActor && curActor == actor) - { - if (!lastActor) - { - s_actorList = curActor->next; - } - else - { - lastActor->next = curActor->next; - } - actor->next = nullptr; - } - } - - LActor* lactor_alloc(s16 extend) - { - LActor* actor = (LActor*)landru_alloc(sizeof(LActor) + extend); - memset(actor, 0, sizeof(LActor) + extend); - - if (actor) - { - actor->next = nullptr; - actor->start = 0; - actor->stop = -1; - - actor->flags = LAFLAG_REFRESHABLE | LAFLAG_REFRESH | LAFLAG_DIRTY; - - actor->fgColor = 0x0f; - actor->bgColor = 0x00; - actor->xScale = LA_SCALE_FACTOR; - actor->yScale = LA_SCALE_FACTOR; - } - return actor; - } - - void lactor_free(LActor* actor) - { - if (!actor) { return; } - lactor_freeData(actor); - - if (actor->varPtr) - { - landru_free(actor->varPtr); - } - if (actor->varPtr2) - { - landru_free(actor->varPtr2); - } - landru_free(actor); - } - - void lactor_freeList(LActor* actor) - { - while (actor) - { - LActor* next = actor->next; - lactor_removeActor(actor); - lactor_free(actor); - - actor = next; - } - } - - void lactor_refresh() - { - s_refreshActors = JTRUE; - } - - void lactor_draw(JBool refresh) - { - refresh |= s_refreshActors; - s_refreshActors = JFALSE; - - LActor* actorList = lactor_getList(); - for (s32 i = 0; i < LVIEW_COUNT; i++) - { - LRect rect, clipRect; - lview_getFrame(i, &rect); - - LActor* curActor = actorList; - if (!lrect_isEmpty(&rect)) - { - while (curActor) - { - // This might not be needed in TFE. - ltime_checkTimeElapsed(); - - if (curActor->drawFunc && lactor_isVisible(curActor)) - { - if (lview_clipObjToView(i, curActor->zplane, &curActor->frame, &rect, &clipRect)) - { - s32 curRefresh = (curActor->flags&LAFLAG_REFRESH) | (curActor->flags&LAFLAG_REFRESHABLE) | refresh; - lcanvas_setClip(&clipRect); - - s16 x, y; - lactor_getRelativePos(curActor, &rect, &x, &y); - curActor->drawFunc(curActor, &rect, &clipRect, x, y, curRefresh ? JTRUE : JFALSE); - } - } - - curActor = curActor->next; - } // while (curActor) - } // if (!empty) - } // view loop - - // Clear actor refresh - for (LActor* curActor = actorList; curActor; curActor = curActor->next) - { - curActor->flags &= ~LAFLAG_REFRESH; - } - } - - void lactor_update(LTick time) - { - LActor* actor = lactor_getList(); - while (actor) - { - if (actor->start == time) - { - lactor_start(actor); - if (actor->stop == time) - { - lactor_stop(actor); - } - } - else - { - if (actor->stop == time) - { - lactor_stop(actor); - } - else if (actor->updateFunc && (actor->flags & LAFLAG_ACTIVE)) - { - actor->updateFunc(actor); - } - } - - actor = actor->next; - } - } - - void lactor_updateCallbacks(LTick time) - { - LActor* actor = lactor_getList(); - while (actor) - { - if (actor->callbackFunc) - { - actor->callbackFunc(actor, time); - } - actor = actor->next; - } - } - - LActor* lactor_find(u32 type, const char* name) - { - LActor* actor = lactor_getList(); - while (actor) - { - if (actor->resType == type && strcasecmp(actor->name, name) == 0) - { - return actor; - } - actor = actor->next; - } - return nullptr; - } - - void lactor_show(LActor* actor) - { - actor->flags |= LAFLAG_VISIBLE; - } - - void lactor_hide(LActor* actor) - { - actor->flags &= ~LAFLAG_VISIBLE; - } - - JBool lactor_isVisible(LActor* actor) - { - return (actor->flags&LAFLAG_VISIBLE) ? JTRUE : JFALSE; - } - - void lactor_start(LActor* actor) - { - actor->flags |= (LAFLAG_VISIBLE | LAFLAG_ACTIVE); - } - - void lactor_stop(LActor* actor) - { - actor->flags &= ~(LAFLAG_VISIBLE | LAFLAG_ACTIVE); - } - - void lactor_setDirty(LActor* actor) - { - actor->flags |= LAFLAG_DIRTY; - } - - JBool lactor_isDirty(LActor* actor) - { - return (actor->flags&LAFLAG_DIRTY) ? JTRUE : JFALSE; - } - - void lactor_enableRefresh(LActor* actor) - { - actor->flags |= LAFLAG_REFRESH; - } - - void lactor_disableRefresh(LActor* actor) - { - actor->flags &= ~LAFLAG_REFRESH; - } - - JBool lactor_isActive(LActor* actor) - { - return (actor->flags & LAFLAG_REFRESH) ? JTRUE : JFALSE; - } - - void lactor_enableRefreshable(LActor* actor) - { - actor->flags |= LAFLAG_REFRESHABLE; - } - - void lactor_disableRefreshable(LActor* actor) - { - actor->flags &= ~LAFLAG_REFRESHABLE; - } - - JBool lactor_isRefreshable(LActor* actor) - { - return (actor->flags & LAFLAG_REFRESHABLE) ? JTRUE : JFALSE; - } - - void lactor_discardData(LActor* actor) - { - actor->flags |= LAFLAG_DISCARD; - } - - void lactor_keepData(LActor* actor) - { - actor->flags &= ~LAFLAG_DISCARD; - } - - JBool lactor_willDiscardData(LActor* actor) - { - return (actor->flags & LAFLAG_DISCARD) ? JTRUE : JFALSE; - } - - void lactor_setFlag1(LActor* actor) - { - actor->flags |= LAFLAG_USER_FLAG1; - } - - void lactor_clearFlag1(LActor* actor) - { - actor->flags &= ~LAFLAG_USER_FLAG1; - } - - JBool lactor_isFlag1Set(LActor* actor) - { - return (actor->flags & LAFLAG_USER_FLAG1) ? JTRUE : JFALSE; - } - - void lactor_setFlag2(LActor* actor) - { - actor->flags |= LAFLAG_USER_FLAG2; - } - - void lactor_clearFlag2(LActor* actor) - { - actor->flags &= ~LAFLAG_USER_FLAG2; - } - - JBool lactor_isFlag2Set(LActor* actor) - { - return (actor->flags & LAFLAG_USER_FLAG2) ? JTRUE : JFALSE; - } - - void lactor_getRelativePos(LActor* actor, LRect* rect, s16* x, s16* y) - { - *x = (actor->x - actor->frame.left) + rect->left; - *y = (actor->y - actor->frame.top) + rect->top; - } - - void lactor_setPos(LActor* actor, s16 x, s16 y, s16 xFract, s16 yFract) - { - actor->x = x; - actor->y = y; - actor->xFract = xFract; - actor->yFract = yFract; - } - - void lactor_getOffset(LActor* actor, s16* x, s16* y) - { - LActorType* type = lactor_findType(actor->resType); - if (type && type->frameFunc) - { - LRect rect; - type->frameFunc(actor, &rect); - *x = rect.left; - *y = rect.top; - } - else - { - *x = 0; - *y = 0; - } - } - - void lactor_getPos(LActor* actor, s16* x, s16* y, s16* xFract, s16* yFract) - { - *x = actor->x; - *y = actor->y; - *xFract = actor->xFract; - *yFract = actor->yFract; - } - - void lactor_setSize(LActor* actor, s16 w, s16 h) - { - actor->w = w; - actor->h = h; - } - - void lactor_getSize(LActor* actor, s16* w, s16* h) - { - *w = actor->w; - *h = actor->h; - } - - void lactor_getBaseRect(LActor* actor, LRect* rect) - { - LActorType* type = lactor_findType(actor->resType); - if (type && type->frameFunc) - { - type->frameFunc(actor, rect); - } - else - { - lrect_set(rect, 0, 0, actor->w, actor->h); - } - } - - void lactor_getRect(LActor* actor, LRect* rect) - { - lactor_getBaseRect(actor, rect); - lrect_offset(rect, actor->x, actor->y); - } - - void lactor_getCenter(LActor* actor, s16* x, s16* y) - { - *x = actor->x + (actor->w >> 1); - *y = actor->y + (actor->h >> 1); - } - - void lactor_setName(LActor* actor, u32 resType, const char* name) - { - actor->resType = resType; - strcpy(actor->name, name); - } - - void lactor_setFrame(LActor* actor, LRect* rect) - { - actor->frame = *rect; - } - - void lactor_getFrame(LActor* actor, LRect* rect) - { - *rect = actor->frame; - } - - void lactor_setBounds(LActor* actor, LRect* rect) - { - actor->bounds = *rect; - } - - void lactor_getBounds(LActor* actor, LRect* rect) - { - *rect = actor->bounds; - } - - void lactor_setZPlane(LActor* actor, s16 zplane) - { - actor->zplane = zplane; - s_zPlaneBuild = JTRUE; - } - - void lactor_getZPlane(LActor* actor, s16* zplane) - { - *zplane = actor->zplane; - } - - void lactor_setTime(LActor* actor, s32 start, s32 stop) - { - if (!actor) { return; } - actor->start = start; - actor->stop = stop; - } - - void lactor_getTime(LActor* actor, s32* start, s32* stop) - { - *start = actor->start; - *stop = actor->stop; - } - - void lactor_setState(LActor* actor, s16 state, s16 stateFract) - { - if (!actor) { return; } - - LActorType* type = lactor_findType(actor->resType); - if (type && type->stateFunc) - { - type->stateFunc(actor, state, stateFract); - } - else - { - actor->state = state; - actor->stateFract = stateFract; - } - } - - void lactor_getState(LActor* actor, s16* state, s16* stateFract) - { - *state = actor->state; - *stateFract = actor->stateFract; - } - - void lactor_setStateSpeed(LActor* actor, s16 stateVel, s16 stateVelFract) - { - actor->stateVel = stateVel; - actor->stateVelFract = stateVelFract; - } - - void lactor_getStateSpeed(LActor* actor, s16* stateVel, s16* stateVelFract) - { - *stateVel = actor->stateVel; - *stateVelFract = actor->stateVelFract; - } - - void lactor_setColor(LActor* actor, s16 fgColor, s16 bgColor) - { - actor->fgColor = fgColor; - actor->bgColor = bgColor; - } - - void lactor_getColor(LActor* actor, s16* fgColor, s16* bgColor) - { - *fgColor = actor->fgColor; - *bgColor = actor->bgColor; - } - - void lactor_setRemapColor(LActor* actor, s16 fgColor) - { - actor->fgColor = fgColor; - actor->flags |= LAFLAG_COLOR; - } - - s16 lactor_getRemapColor(LActor* actor) - { - return actor->fgColor; - } - - void lactor_clearRemapColor(LActor* actor) - { - actor->flags &= ~LAFLAG_COLOR; - } - - void lactor_setScale(LActor* actor, s16 xScale, s16 yScale) - { - actor->xScale = xScale; - actor->yScale = yScale; - } - - void lactor_getScale(LActor* actor, s16* xScale, s16* yScale) - { - *xScale = actor->xScale; - *yScale = actor->yScale; - } - - void lactor_setFlip(LActor* actor, JBool hFlip, JBool vFlip) - { - if (hFlip) { actor->flags |= LAFLAG_HFLIP; } - else { actor->flags &= ~LAFLAG_HFLIP; } - - if (vFlip) { actor->flags |= LAFLAG_VFLIP; } - else { actor->flags &= ~LAFLAG_VFLIP; } - } - - void lactor_getFlip(LActor* actor, JBool* hFlip, JBool* vFlip) - { - *hFlip = (actor->flags & LAFLAG_HFLIP) ? JTRUE : JFALSE; - *vFlip = (actor->flags & LAFLAG_VFLIP) ? JTRUE : JFALSE; - } - - void lactor_setSpeed(LActor* actor, s16 xVel, s16 yVel, s16 xVelFract, s16 yVelFract) - { - actor->xVel = xVel; - actor->yVel = yVel; - actor->xVelFract = xVelFract; - actor->yVelFract = yVelFract; - } - - void lactor_getSpeed(LActor* actor, s16* xVel, s16* yVel, s16* xVelFract, s16* yVelFract) - { - *xVel = actor->xVel; - *yVel = actor->yVel; - *xVelFract = actor->xVelFract; - *yVelFract = actor->yVelFract; - } - - void lactor_setFrameSpeed(LActor* actor, s16 leftVel, s16 topVel, s16 rightVel, s16 bottomVel) - { - lrect_set(&actor->frameVelocity, leftVel, topVel, rightVel, bottomVel); - } - - void lactor_getFrameSpeed(LActor* actor, s16* leftVel, s16* topVel, s16* rightVel, s16* bottomVel) - { - *leftVel = actor->frameVelocity.left; - *topVel = actor->frameVelocity.top; - *rightVel = actor->frameVelocity.right; - *bottomVel = actor->frameVelocity.bottom; - } - - void lactor_setData(LActor* actor, u8* data) - { - actor->data = data; - } - - void lactor_getData(LActor* actor, u8** data) - { - *data = actor->data; - } - - void lactor_setArray(LActor* actor, u8** array) - { - actor->array = array; - } - - void lactor_getArray(LActor* actor, u8*** array) - { - *array = actor->array; - } - - u8* lactor_getArrayData(LActor* actor, s16 index) - { - if (!actor->array) { return nullptr; } - return actor->array[index]; - } - - void lactor_setDrawFunc(LActor* actor, LActorDrawFunc drawFunc) - { - actor->drawFunc = drawFunc; - } - - void lactor_getDrawFunc(LActor* actor, LActorDrawFunc* drawFunc) - { - *drawFunc = actor->drawFunc; - } - - void lactor_setUpdateFunc(LActor* actor, LActorUpdateFunc updateFunc) - { - actor->updateFunc = updateFunc; - } - - void lactor_getUpdateFunc(LActor* actor, LActorUpdateFunc* updateFunc) - { - *updateFunc = actor->updateFunc; - } - - void lactor_setCallback(LActor* actor, LActorCallback callback) - { - actor->callbackFunc = callback; - } - - void lactor_getUpdateFunc(LActor* actor, LActorCallback* callback) - { - *callback = actor->callbackFunc; - } - - void lactor_move(LActor* actor) - { - actor->xFract += actor->xVelFract; - actor->yFract += actor->yVelFract; - actor->x += actor->xVel + (actor->xFract / 256); - actor->y += actor->yVel + (actor->yFract / 256); - - while (actor->xFract >= 256) { actor->xFract -= 256; } - while (actor->yFract >= 256) { actor->yFract -= 256; } - while (actor->xFract <= -256) { actor->xFract += 256; } - while (actor->yFract <= -256) { actor->yFract += 256; } - } - - void lactor_moveFrame(LActor* actor) - { - actor->frame.left += actor->frameVelocity.left; - actor->frame.top += actor->frameVelocity.top; - actor->frame.right += actor->frameVelocity.right; - actor->frame.bottom += actor->frameVelocity.bottom; - } - - void lactor_moveState(LActor* actor) - { - actor->stateFract += actor->stateVelFract; - actor->state += actor->stateVel + (actor->stateVelFract / 256); - - while (actor->stateFract >= 256) { actor->stateFract -= 256; } - while (actor->stateFract <= -256) { actor->stateFract += 256; } - } - - void lactor_copyData(LActor* dst, const LActor* src) - { - lactor_freeData(dst); - lactor_keepData(dst); - strcpy(dst->name, src->name); - - dst->data = src->data; - dst->array = src->array; - dst->arraySize = src->arraySize; - dst->bounds = src->bounds; - dst->w = src->w; - dst->h = src->h; - } - - void lactor_clipToActor(LActor* dst, LActor* src) - { - lrect_clip(&dst->frame, &src->frame); - } - - void lactor_updateZPlanes() - { - if (s_zPlaneBuild) - { - s_zPlaneBuild = JFALSE; - lactor_sortZPlanes(); - } - } - - void lactor_sortZPlanes() - { - LActor* actorSort = nullptr; - LActor* actorBase = lactor_getList(); - while (actorBase) - { - LActor* curActorSort = actorSort; - LActor* curActorBase = actorBase; - actorBase = actorBase->next; - - LActor* lastActorSort = nullptr; - curActorBase->next = nullptr; - - while (curActorSort && curActorSort->zplane >= curActorBase->zplane) - { - lastActorSort = curActorSort; - curActorSort = curActorSort->next; - } - - if (!curActorSort) - { - if (!lastActorSort) - { - actorSort = curActorBase; - } - else - { - lastActorSort->next = curActorBase; - } - } - else if (!lastActorSort) - { - actorSort = curActorBase; - curActorBase->next = curActorSort; - } - else - { - lastActorSort->next = curActorBase; - curActorBase->next = curActorSort; - } - } - - s_actorList = actorSort; - } - - void lactor_freeData(LActor* actor) - { - if (!actor) { return; } - - if (actor->flags & LAFLAG_DISCARD) - { - if (actor->data) - { - landru_free(actor->data); - } - if (actor->array) - { - for (s32 i = 0; i < actor->arraySize; i++) - { - if (actor->array[i]) - { - landru_free(actor->array[i]); - } - } - landru_free(actor->array); - } - } - - actor->data = nullptr; - actor->array = nullptr; - actor->arraySize = 0; - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/lactor.h b/components/darkforces/tfe/TFE_DarkForces/Landru/lactor.h deleted file mode 100644 index 7454c9c7..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/lactor.h +++ /dev/null @@ -1,204 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Landru Actor -// Landru was the cutscene system developed for XWing and Tie Fighter -// and is also used in Dark Forces. -////////////////////////////////////////////////////////////////////// -#include -#include "lview.h" -#include "ltimer.h" - -/////////////////////////////////////////// -// Constants -/////////////////////////////////////////// -enum LActorConstants -{ - LA_SCALE_FACTOR = 256, - // Flags - LAFLAG_VISIBLE = FLAG_BIT(0), - LAFLAG_ACTIVE = FLAG_BIT(1), - LAFLAG_DISCARD = FLAG_BIT(2), - LAFLAG_DIRTY = FLAG_BIT(3), - LAFLAG_REFRESHABLE = FLAG_BIT(4), - LAFLAG_REFRESH = FLAG_BIT(5), - LAFLAG_KEEPABLE = FLAG_BIT(6), - LAFLAG_KEEP = FLAG_BIT(7), - LAFLAG_HFLIP = FLAG_BIT(8), - LAFLAG_VFLIP = FLAG_BIT(9), - LAFLAG_COLOR = FLAG_BIT(10), - LAFLAG_PACKET = FLAG_BIT(11), - LAFLAG_USER_FLAG1 = FLAG_BIT(14), - LAFLAG_USER_FLAG2 = FLAG_BIT(15), -}; - -namespace TFE_DarkForces -{ - struct LActor; - - typedef JBool(*LActorDrawFunc)(LActor*, LRect*, LRect*, s16, s16, JBool); - typedef void(*LActorUpdateFunc)(LActor*); - typedef void(*LActorCallback)(LActor*, s32); - typedef void(*LActorFrameFunc)(LActor*, LRect*); - typedef void(*LActorStateFunc)(LActor*, s16, s16); - - struct LActor - { - u32 resType; - char name[16]; - - LActor* next; - s32 start; - s32 stop; - - LRect frame; - LRect frameVelocity; - LRect bounds; - - s16 x, y; - s16 xFract, yFract; - s16 xVel, yVel; - s16 xVelFract, yVelFract; - - s16 w, h; - s16 zplane; - - s16 flags; - s16 id; - - s16 state; - s16 stateFract; - s16 stateVel; - s16 stateVelFract; - - s16 fgColor; - s16 bgColor; - s16 xScale; - s16 yScale; - - s16 var1; - s16 var2; - u8* varPtr; - u8* varPtr2; - - u8* data; - u8** array; - u16 arraySize; - - LActorDrawFunc drawFunc; - LActorUpdateFunc updateFunc; - LActorCallback callbackFunc; - }; - - struct LActorType - { - u32 type; - LActorType* next; - LActorFrameFunc frameFunc; - LActorStateFunc stateFunc; - }; - - void lactor_init(); - void lactor_destroy(); - - JBool lactor_createType(u32 type, LActorFrameFunc frameFunc, LActorStateFunc stateFunc); - void lactor_destroyType(u32 type); - LActorType* lactor_findType(u32 type); - - void lactor_addActor(LActor* actor); - void lactor_removeActor(LActor* actor); - - LActor* lactor_alloc(s16 extend); - void lactor_free(LActor* actor); - void lactor_freeList(LActor* actor); - - LActor* lactor_getList(); - LActor* lactor_find(u32 type, const char* name); - - void lactor_refresh(); - void lactor_draw(JBool refresh); - void lactor_update(LTick time); - void lactor_updateCallbacks(LTick time); - void lactor_updateZPlanes(); - void lactor_sortZPlanes(); - - void lactor_copyData(LActor* dst, const LActor* src); - void lactor_clipToActor(LActor* dst, LActor* src); - - void lactor_setName(LActor* actor, u32 resType, const char* name); - void lactor_getRelativePos(LActor* actor, LRect* rect, s16* x, s16* y); - void lactor_getOffset(LActor* actor, s16* x, s16* y); - void lactor_setPos(LActor* actor, s16 x, s16 y, s16 xFract, s16 yFract); - void lactor_getPos(LActor* actor, s16* x, s16* y, s16* xFract, s16* yFract); - void lactor_setSize(LActor* actor, s16 w, s16 h); - void lactor_getSize(LActor* actor, s16* w, s16* h); - void lactor_getCenter(LActor* actor, s16* x, s16* y); - void lactor_setFrame(LActor* actor, LRect* rect); - void lactor_getFrame(LActor* actor, LRect* rect); - void lactor_setBounds(LActor* actor, LRect* rect); - void lactor_getBounds(LActor* actor, LRect* rect); - void lactor_getBaseRect(LActor* actor, LRect* rect); - void lactor_getRect(LActor* actor, LRect* rect); - void lactor_show(LActor* actor); - void lactor_hide(LActor* actor); - void lactor_setDirty(LActor* actor); - void lactor_start(LActor* actor); - void lactor_stop(LActor* actor); - - void lactor_enableRefresh(LActor* actor); - void lactor_disableRefresh(LActor* actor); - void lactor_enableRefreshable(LActor* actor); - void lactor_disableRefreshable(LActor* actor); - void lactor_discardData(LActor* actor); - void lactor_keepData(LActor* actor); - void lactor_setFlag1(LActor* actor); - void lactor_clearFlag1(LActor* actor); - void lactor_setFlag2(LActor* actor); - void lactor_clearFlag2(LActor* actor); - - void lactor_move(LActor* actor); - void lactor_moveFrame(LActor* actor); - void lactor_moveState(LActor* actor); - - void lactor_setZPlane(LActor* actor, s16 zplane); - void lactor_getZPlane(LActor* actor, s16* zplane); - void lactor_setTime(LActor* actor, s32 start, s32 stop); - void lactor_getTime(LActor* actor, s32* start, s32* stop); - void lactor_setState(LActor* actor, s16 state, s16 stateFract); - void lactor_getState(LActor* actor, s16* state, s16* stateFract); - void lactor_setStateSpeed(LActor* actor, s16 stateVel, s16 stateVelFract); - void lactor_getStateSpeed(LActor* actor, s16* stateVel, s16* stateVelFract); - void lactor_setColor(LActor* actor, s16 fgColor, s16 bgColor); - void lactor_getColor(LActor* actor, s16* fgColor, s16* bgColor); - void lactor_setRemapColor(LActor* actor, s16 fgColor); - s16 lactor_getRemapColor(LActor* actor); - void lactor_clearRemapColor(LActor* actor); - void lactor_setScale(LActor* actor, s16 xScale, s16 yScale); - void lactor_getScale(LActor* actor, s16* xScale, s16* yScale); - void lactor_setFlip(LActor* actor, JBool hFlip, JBool vFlip); - void lactor_getFlip(LActor* actor, JBool* hFlip, JBool* vFlip); - void lactor_setSpeed(LActor* actor, s16 xVel, s16 yVel, s16 xVelFract, s16 yVelFract); - void lactor_getSpeed(LActor* actor, s16* xVel, s16* yVel, s16* xVelFract, s16* yVelFract); - void lactor_setFrameSpeed(LActor* actor, s16 leftVel, s16 topVel, s16 rightVel, s16 bottomVel); - void lactor_getFrameSpeed(LActor* actor, s16* leftVel, s16* topVel, s16* rightVel, s16* bottomVel); - void lactor_setData(LActor* actor, u8* data); - void lactor_getData(LActor* actor, u8** data); - void lactor_setArray(LActor* actor, u8** array); - void lactor_getArray(LActor* actor, u8*** array); - u8* lactor_getArrayData(LActor* actor, s16 index); - - void lactor_setDrawFunc(LActor* actor, LActorDrawFunc drawFunc); - void lactor_getDrawFunc(LActor* actor, LActorDrawFunc* drawFunc); - void lactor_setUpdateFunc(LActor* actor, LActorUpdateFunc updateFunc); - void lactor_getUpdateFunc(LActor* actor, LActorUpdateFunc* updateFunc); - void lactor_setCallback(LActor* actor, LActorCallback callback); - void lactor_getUpdateFunc(LActor* actor, LActorCallback* callback); - - JBool lactor_isVisible(LActor* actor); - JBool lactor_isDirty(LActor* actor); - JBool lactor_isActive(LActor* actor); - JBool lactor_isRefreshable(LActor* actor); - JBool lactor_willDiscardData(LActor* actor); - JBool lactor_isFlag1Set(LActor* actor); - JBool lactor_isFlag2Set(LActor* actor); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/lactorAnim.cpp b/components/darkforces/tfe/TFE_DarkForces/Landru/lactorAnim.cpp deleted file mode 100644 index 2c4a3309..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/lactorAnim.cpp +++ /dev/null @@ -1,214 +0,0 @@ -#include "lactorAnim.h" -#include "lactorDelt.h" -#include "lsystem.h" -#include "cutscene_film.h" -#include "lview.h" -#include "ltimer.h" -#include -#include -#include - -#include "ldraw.h" - -namespace TFE_DarkForces -{ - static JBool s_animActorInit = JFALSE; - - void lactorAnim_getFrame(LActor* actor, LRect* rect); - void lactorAnim_setState(LActor* actor, s16 state, s16 stateFract); - void lactorAnim_initActor(LActor* actor, u8** array, LRect* frame, s16 x, s16 y, s16 zPlane); - JBool lactorAnim_draw(LActor* actor, LRect* rect, LRect* clipRect, s16 x, s16 y, JBool refresh); - void lactorAnim_update(LActor* actor); - void lactorAnim_getBounds(LActor* actor, LRect* rect); - - void lactorAnim_init() - { - lactor_createType(CF_TYPE_ANIM_ACTOR, lactorAnim_getFrame, lactorAnim_setState); - s_animActorInit = JTRUE; - } - - void lactorAnim_destroy() - { - if (s_animActorInit) - { - lactor_destroyType(CF_TYPE_ANIM_ACTOR); - } - s_animActorInit = JFALSE; - } - - void lactorAnim_getFrame(LActor* actor, LRect* rect) - { - lrect_set(rect, 0, 0, 0, 0); - s16* data = (s16*)lactor_getArrayData(actor, actor->state); - if (data && data[0] != -1 && data[1] != -1) - { - lrect_set(rect, TFE_Endian::le16_to_cpu(data[0]), TFE_Endian::le16_to_cpu(data[1]), TFE_Endian::le16_to_cpu(data[2]) + 1, TFE_Endian::le16_to_cpu(data[3]) + 1); - JBool xFlip, yFlip; - lactor_getFlip(actor, &xFlip, &yFlip); - lrect_flip(rect, &actor->bounds, xFlip, yFlip); - } - } - - void lactorAnim_setState(LActor* actor, s16 state, s16 stateFract) - { - actor->state = state; - actor->stateFract = stateFract; - - LRect rect; - lactorAnim_getFrame(actor, &rect); - actor->w = rect.right - rect.left; - actor->h = rect.bottom - rect.top; - } - - LActor* lactorAnim_alloc(u8** array, LRect* frame, s16 xOffset, s16 yOffset, s16 zPlane) - { - LActor* actor = lactor_alloc(0); - if (!actor) { return nullptr; } - - lactorAnim_initActor(actor, array, frame, xOffset, yOffset, zPlane); - lactor_setName(actor, CF_TYPE_ANIM_ACTOR, ""); - lactor_keepData(actor); - - return actor; - } - - LActor* lactorAnim_load(const char* name, LRect* rect, s16 x, s16 y, s16 zPlane) - { - LActor* actor = lactor_alloc(0); - if (!actor) - { - return nullptr; - } - - char animName[32]; - sprintf(animName, "%s.ANIM", name); - FilePath path; - if (TFE_Paths::getFilePath(animName, &path)) - { - FileStream file; - file.open(&path, Stream::MODE_READ); - - s16 animCount; - file.read(&animCount); - animCount = TFE_Endian::le16_to_cpu(animCount); - u8** array = (u8**)landru_alloc(sizeof(u8*) * animCount); - if (array) - { - for (s32 i = 0; i < animCount; i++) - { - s32 deltaSize; - file.read(&deltaSize); - deltaSize = TFE_Endian::le32_to_cpu(deltaSize); - if (deltaSize <= 0) { array[i] = nullptr; continue; } - - array[i] = (u8*)landru_alloc(deltaSize); - file.readBuffer(array[i], deltaSize); - } - } - else - { - lactor_free(actor); - file.close(); - return nullptr; - } - file.close(); - - actor->arraySize = animCount; - lactorAnim_initActor(actor, array, rect, x, y, zPlane); - lactor_setName(actor, CF_TYPE_ANIM_ACTOR, name); - lactorAnim_getBounds(actor, &actor->bounds); - } - else - { - lactor_free(actor); - actor = nullptr; - } - - return actor; - } - - void lactorAnim_initActor(LActor* actor, u8** array, LRect* frame, s16 x, s16 y, s16 zPlane) - { - lrect_set(&actor->frame, frame->left, frame->top, frame->right, frame->bottom); - actor->x = x; - actor->y = y; - actor->zplane = zPlane; - lactor_discardData(actor); - - actor->drawFunc = lactorAnim_draw; - actor->updateFunc = lactorAnim_update; - actor->array = array; - lactor_addActor(actor); - - LRect rect; - lactor_getFrame(actor, &rect); - actor->w = rect.right - rect.left; - actor->h = rect.bottom - rect.top; - } - - void lactorAnim_getBounds(LActor* actor, LRect* rect) - { - lrect_clear(rect); - s16 state = actor->state; - for (s32 i = 0; i < actor->arraySize; i++) - { - LRect cellRect; - actor->state = i; - lactorAnim_getFrame(actor, &cellRect); - lrect_enclose(rect, &cellRect); - } - - actor->state = state; - } - - JBool lactorAnim_draw(LActor* actor, LRect* rect, LRect* clipRect, s16 x, s16 y, JBool refresh) - { - if (!refresh) - { - return JFALSE; - } - u8* data = lactor_getArrayData(actor, actor->state); - - JBool retValue = JFALSE; - if (data) - { - if (actor->flags & LAFLAG_HFLIP) - { - retValue = lactorDelt_drawFlippedClipped(actor, data, x, y, lactor_isDirty(actor)); - } - else - { - retValue = lactorDelt_drawClipped(data, x, y, lactor_isDirty(actor)); - } - } - - return retValue; - } - - void lactorAnim_update(LActor* actor) - { - s16 prevState = actor->state; - lactor_move(actor); - lactor_moveFrame(actor); - lactor_moveState(actor); - - if (actor->arraySize) - { - while (actor->state < 0) { actor->state += actor->arraySize; } - while (actor->state >= actor->arraySize) { actor->state -= actor->arraySize; } - } - else - { - actor->state = 0; - } - - if (prevState != actor->state) - { - LRect rect; - lactorAnim_getFrame(actor, &rect); - actor->w = rect.right - rect.left; - actor->h = rect.bottom - rect.top; - } - } - -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/lactorAnim.h b/components/darkforces/tfe/TFE_DarkForces/Landru/lactorAnim.h deleted file mode 100644 index 1c2e4ea7..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/lactorAnim.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Landru Actor -// Landru was the cutscene system developed for XWing and Tie Fighter -// and is also used in Dark Forces. -////////////////////////////////////////////////////////////////////// -#include -#include "lactor.h" - -namespace TFE_DarkForces -{ - void lactorAnim_init(); - void lactorAnim_destroy(); - - LActor* lactorAnim_alloc(u8** array, LRect* frame, s16 xOffset, s16 yOffset, s16 zPlane); - LActor* lactorAnim_load(const char* name, LRect* rect, s16 x, s16 y, s16 zPlane); - JBool lactorAnim_draw(LActor* actor, LRect* rect, LRect* clipRect, s16 x, s16 y, JBool refresh); - void lactorAnim_getFrame(LActor* actor, LRect* rect); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/lactorCust.cpp b/components/darkforces/tfe/TFE_DarkForces/Landru/lactorCust.cpp deleted file mode 100644 index 0c8a6c82..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/lactorCust.cpp +++ /dev/null @@ -1,81 +0,0 @@ -#include "lactorCust.h" -#include "lsystem.h" -#include "cutscene_film.h" -#include "ldraw.h" -#include "lview.h" -#include "ltimer.h" -#include -#include - -namespace TFE_DarkForces -{ - static JBool s_lactorCustInit = JFALSE; - - void lactorCust_initActor(LActor* actor, LRect* frame, s16 xOffset, s16 yOffset, s16 zPlane); - JBool lactorCust_draw(LActor* actor, LRect* rect, LRect* clipRect, s16 x, s16 y, JBool refresh); - void lactorCust_update(LActor* actor); - - void lactorCust_init() - { - lactor_createType(CF_TYPE_CUSTOM_ACTOR, nullptr, nullptr); - s_lactorCustInit = JTRUE; - } - - void lactorCust_destroy() - { - if (s_lactorCustInit) - { - lactor_destroyType(CF_TYPE_CUSTOM_ACTOR); - } - s_lactorCustInit = JFALSE; - } - - LActor* lactorCust_alloc(u8* custom, LRect* frame, s16 xOffset, s16 yOffset, s16 zPlane) - { - LActor* actor = lactor_alloc(0); - if (!actor) { return nullptr; } - - lactorCust_initActor(actor, frame, xOffset, yOffset, zPlane); - actor->data = custom; - lactor_setName(actor, CF_TYPE_CUSTOM_ACTOR, "CUSTOM"); - lactor_keepData(actor); - - return actor; - } - - void lactorCust_initActor(LActor* actor, LRect* frame, s16 xOffset, s16 yOffset, s16 zPlane) - { - lrect_set(&actor->frame, frame->left, frame->top, frame->right, frame->bottom); - actor->x = xOffset; - actor->y = yOffset; - actor->zplane = zPlane; - - lactor_discardData(actor); - actor->drawFunc = lactorCust_draw; - actor->updateFunc = lactorCust_update; - - lactor_addActor(actor); - } - - JBool lactorCust_draw(LActor* actor, LRect* rect, LRect* clipRect, s16 x, s16 y, JBool refresh) - { - if (!refresh) { return JFALSE; } - - LRect ra; - lrect_set(&ra, x, y, x + actor->w, y + actor->h); - JBool retValue = drawClippedColorRect(&ra, (u8)actor->fgColor); - - if (lactor_isDirty(actor)) - { - // DirtyRect(&ra); - } - - return retValue; - } - - void lactorCust_update(LActor* actor) - { - lactor_move(actor); - lactor_moveFrame(actor); - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/lactorCust.h b/components/darkforces/tfe/TFE_DarkForces/Landru/lactorCust.h deleted file mode 100644 index 3e44ff59..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/lactorCust.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Landru Actor -// Landru was the cutscene system developed for XWing and Tie Fighter -// and is also used in Dark Forces. -////////////////////////////////////////////////////////////////////// -#include -#include "lactor.h" - -namespace TFE_DarkForces -{ - void lactorCust_init(); - void lactorCust_destroy(); - - LActor* lactorCust_alloc(u8* custom, LRect* frame, s16 xOffset, s16 yOffset, s16 zPlane); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/lactorDelt.cpp b/components/darkforces/tfe/TFE_DarkForces/Landru/lactorDelt.cpp deleted file mode 100644 index b50262a6..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/lactorDelt.cpp +++ /dev/null @@ -1,240 +0,0 @@ -#include "lactorDelt.h" -#include "lsystem.h" -#include "cutscene_film.h" -#include "lcanvas.h" -#include "lview.h" -#include "ldraw.h" -#include "ltimer.h" -#include -#include -#include - -namespace TFE_DarkForces -{ - static JBool s_lactorDeltInit = JFALSE; - - /////////////////////////////////////////// - // TODO: Draw API. - void dirtyRect(LRect* rect) - { - } - ////////////////////////////////////////////// - - void lactorDelt_initActor(LActor* actor, u8* data, LRect* frame, s16 xOffset, s16 yOffset, s16 zPlane); - void lactorDelt_update(LActor* actor); - - void lactorDelt_init() - { - lactor_createType(CF_TYPE_DELTA_ACTOR, lactorDelt_getFrame, nullptr); - s_lactorDeltInit = JTRUE; - } - - void lactorDelt_destroy() - { - if (s_lactorDeltInit) - { - lactor_destroyType(CF_TYPE_DELTA_ACTOR); - } - s_lactorDeltInit = JFALSE; - } - - void lactorDelt_getFrame(LActor* actor, LRect* rect) - { - s16* data = (s16*)actor->data; - if (data) - { - lrect_set(rect, TFE_Endian::le16_to_cpu(data[0]), TFE_Endian::le16_to_cpu(data[1]), TFE_Endian::le16_to_cpu(data[2]), TFE_Endian::le16_to_cpu(data[3])); - JBool hFlip, vFlip; - lactor_getFlip(actor, &hFlip, &vFlip); - lrect_flip(rect, &actor->bounds, hFlip, JFALSE); - } - else - { - lrect_set(rect, 0, 0, 0, 0); - } - } - - LActor* lactorDelt_alloc(u8* delta, LRect* frame, s16 xOffset, s16 yOffset, s16 zPlane) - { - LActor* actor = lactor_alloc(0); - if (!actor) { return nullptr; } - - lactorDelt_initActor(actor, delta, frame, xOffset, yOffset, zPlane); - lactor_setName(actor, CF_TYPE_DELTA_ACTOR, ""); - lactor_keepData(actor); - - return actor; - } - - LActor* lactorDelt_load(const char* name, LRect* rect, s16 x, s16 y, s16 zPlane) - { - char deltName[32]; - sprintf(deltName, "%s.DELT", name); - - FilePath path; - if (!TFE_Paths::getFilePath(deltName, &path)) - { - return nullptr; - } - - FileStream file; - if (!file.open(&path, Stream::MODE_READ)) - { - return nullptr; - } - u32 deltSize = (u32)file.getSize(); - - u8* data = (u8*)landru_alloc(deltSize); - file.readBuffer(data, deltSize); - file.close(); - - LActor* actor = lactor_alloc(0); - if (!actor) - { - landru_free(data); - return nullptr; - } - - lactorDelt_initActor(actor, data, rect, x, y, zPlane); - lactor_setName(actor, CF_TYPE_DELTA_ACTOR, name); - - return actor; - } - - void lactorDelt_initActor(LActor* actor, u8* data, LRect* frame, s16 xOffset, s16 yOffset, s16 zPlane) - { - lrect_set(&actor->frame, frame->left, frame->top, frame->right, frame->bottom); - actor->x = xOffset; - actor->y = yOffset; - actor->zplane = zPlane; - - lactor_discardData(actor); - actor->drawFunc = lactorDelt_draw; - actor->updateFunc = lactorDelt_update; - actor->data = data; - - LRect rect; - lactor_addActor(actor); - lactorDelt_getFrame(actor, &rect); - actor->w = rect.right - rect.left; - actor->h = rect.bottom - rect.top; - actor->bounds = rect; - } - - void lactorDelt_update(LActor* actor) - { - lactor_move(actor); - lactor_moveFrame(actor); - } - - JBool lactorDelt_draw(LActor* actor, LRect* rect, LRect* clipRect, s16 x, s16 y, JBool refresh) - { - if (!refresh) - { - return JFALSE; - } - u8* data = actor->data; - - JBool retValue = JFALSE; - if (data) - { - if (actor->flags & LAFLAG_HFLIP) - { - retValue = lactorDelt_drawFlippedClipped(actor, data, x, y, lactor_isDirty(actor)); - } - else - { - retValue = lactorDelt_drawClipped(data, x, y, lactor_isDirty(actor)); - } - } - - return retValue; - } - - JBool lactorDelt_drawClipped(u8* data, s16 x, s16 y, JBool dirty) - { - s16* data16 = (s16*)data; - s16 sx = TFE_Endian::le16_to_cpu(data16[0]) + x; - s16 sy = TFE_Endian::le16_to_cpu(data16[1]) + y; - - s16 ex = TFE_Endian::le16_to_cpu(data16[2]) + x; - s16 ey = TFE_Endian::le16_to_cpu(data16[3]) + y; - data16 += 4; - - LRect drect; - lrect_set(&drect, sx, sy, ex + 1, ey + 1); - LRect clipRect = drect; - - JBool retValue = JFALSE; - if (lcanvas_clipRectToCanvas(&clipRect)) - { - if (lrect_equal(&clipRect, &drect)) - { - deltaImage(data16, x, y); - } - else - { - deltaClip(data16, x, y); - } - - if (dirty) - { - dirtyRect(&clipRect); - } - retValue = JTRUE; - } - - return retValue; - } - - JBool lactorDelt_drawFlippedClipped(LActor* actor, u8* data, s16 x, s16 y, JBool dirty) - { - s16* data16 = (s16*)data; - JBool hFlip = (actor->flags & LAFLAG_HFLIP) ? JTRUE : JFALSE; - s16 w = actor->bounds.right + actor->bounds.left - 1; - s16 h = actor->bounds.bottom + actor->bounds.top - 1; - - s16 sx, sy; - s16 ex, ey; - if (hFlip) - { - ex = w - TFE_Endian::le16_to_cpu(data16[0]) + x; - sy = TFE_Endian::le16_to_cpu(data16[1]) + y; - sx = w - TFE_Endian::le16_to_cpu(data16[2]) + x; - ey = TFE_Endian::le16_to_cpu(data16[3]) + y; - } - else - { - sx = TFE_Endian::le16_to_cpu(data16[0]) + x; - sy = TFE_Endian::le16_to_cpu(data16[1]) + y; - ex = TFE_Endian::le16_to_cpu(data16[2]) + x; - ey = TFE_Endian::le16_to_cpu(data16[3]) + y; - } - data16 += 4; - - LRect drect; - lrect_set(&drect, sx, sy, ex + 1, ey + 1); - LRect clipRect = drect; - - JBool retValue = JFALSE; - if (lcanvas_clipRectToCanvas(&clipRect)) - { - if (lrect_equal(&clipRect, &drect)) - { - deltaFlip(data16, x, y, w); - } - else - { - deltaFlipClip(data16, x, y, w); - } - - if (dirty) - { - dirtyRect(&clipRect); - } - retValue = JTRUE; - } - - return retValue; - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/lactorDelt.h b/components/darkforces/tfe/TFE_DarkForces/Landru/lactorDelt.h deleted file mode 100644 index d378dc7d..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/lactorDelt.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Landru Actor -// Landru was the cutscene system developed for XWing and Tie Fighter -// and is also used in Dark Forces. -////////////////////////////////////////////////////////////////////// -#include -#include "lactor.h" - -namespace TFE_DarkForces -{ - void lactorDelt_init(); - void lactorDelt_destroy(); - - void lactorDelt_getFrame(LActor* actor, LRect* rect); - - LActor* lactorDelt_alloc(u8* delta,LRect* frame, s16 xOffset, s16 yOffset, s16 zPlane); - LActor* lactorDelt_load(const char* name, LRect* rect, s16 x, s16 y, s16 zPlane); - - // Draw - JBool lactorDelt_draw(LActor* actor, LRect* rect, LRect* clipRect, s16 x, s16 y, JBool refresh); - JBool lactorDelt_drawClipped(u8* data, s16 x, s16 y, JBool dirty); - JBool lactorDelt_drawFlippedClipped(LActor* actor, u8* data, s16 x, s16 y, JBool dirty); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/lcanvas.cpp b/components/darkforces/tfe/TFE_DarkForces/Landru/lcanvas.cpp deleted file mode 100644 index 5b45a657..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/lcanvas.cpp +++ /dev/null @@ -1,151 +0,0 @@ -#include "lcanvas.h" -#include "lfade.h" -#include "ldraw.h" -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - static s16 s_lcanvasSize[2]; - static LRect s_lcanvasRect; - static LRect s_lcanvasClipRect; - - void lcanvas_copyToFramebuffer(LRect* rect, s16 x, s16 y); - - void lcanvas_init(s16 w, s16 h) - { - s_lcanvasSize[0] = w; - s_lcanvasSize[1] = h; - lrect_set(&s_lcanvasRect, 0, 0, w, h); - s_lcanvasClipRect = s_lcanvasRect; - - vfb_setResolution(w, h); - ldraw_init(w, h); - } - - void lcanvas_destroy() - { - ldraw_destroy(); - } - - void lcanvas_getBounds(LRect* rect) - { - *rect = s_lcanvasRect; - } - - void lcanvas_setClip(LRect* rect) - { - s_lcanvasClipRect = *rect; - } - - void lcanvas_getClip(LRect* rect) - { - *rect = s_lcanvasClipRect; - } - - JBool lcanvas_clipRectToCanvas(LRect* rect) - { - return lrect_clip(rect, &s_lcanvasClipRect); - } - - void lcanvas_clearClipRect() - { - s_lcanvasClipRect = s_lcanvasRect; - } - - void lcanvas_clear() - { - LRect bounds; - lcanvas_getBounds(&bounds); - s32 width = bounds.right - bounds.left; - s32 height = bounds.bottom - bounds.top; - memset(ldraw_getBitmap(), 0, width * height); - } - - void lcanvas_eraseRect(LRect* rect) - { - LRect clipRect; - lcanvas_getClip(&clipRect); - lcanvas_clearClipRect(); - - drawClippedColorRect(rect, 0); - - lcanvas_setClip(&clipRect); - } - - JBool lcanvas_applyFade(JBool dialog) - { - LRect rect; - lcanvas_getBounds(&rect); - - /* - if (cursor is visible) - { - TODO: Cursor is visible. - } - else - { - ... - } - */ - return lfade_applyFadeLoop(&rect, dialog); - } - - void lcanvas_showNextFrame() - { - LRect bounds; - lcanvas_getBounds(&bounds); - s32 width = bounds.right - bounds.left; - s32 height = bounds.bottom - bounds.top; - - memcpy(vfb_getCpuBuffer(), ldraw_getBitmap(), width * height); - vfb_swap(); - } - - void lcanvas_copyScreenToVideo(LRect* rect) - { - lcanvas_copyPortionToVideo(rect, rect->left, rect->top); - } - - void lcanvas_copyPortionToVideo(LRect* rect, s16 x, s16 y) - { - LRect bounds; - lcanvas_getBounds(&bounds); - - LRect srcRect = *rect; - if (!lrect_clip(&srcRect, &bounds)) { return; } - - LRect clipRect = srcRect; - lrect_offset(&clipRect, x - rect->left, y - rect->top); - LRect dstRect = clipRect; - if (!lrect_clip(&dstRect, &bounds)) { return; } - - srcRect.left += dstRect.left - clipRect.left; - srcRect.top += dstRect.top - clipRect.top; - srcRect.right += dstRect.right - clipRect.right; - srcRect.bottom += dstRect.bottom - clipRect.bottom; - - lcanvas_copyToFramebuffer(&srcRect, rect->left, rect->top); - } - - void lcanvas_copyToFramebuffer(LRect* srcRect, s16 x, s16 y) - { - const u8* srcData = ldraw_getBitmap(); - u8* dstData = vfb_getCpuBuffer(); - if (!srcData || !dstData) { return; } - - LRect bounds; - lcanvas_getBounds(&bounds); - s32 width = bounds.right - bounds.left; - - for (s32 fy = srcRect->top; fy < srcRect->bottom; fy++) - { - memcpy(&dstData[(y+fy-srcRect->top)*width + x], &srcData[fy*width + srcRect->left], srcRect->right - srcRect->left); - } - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/lcanvas.h b/components/darkforces/tfe/TFE_DarkForces/Landru/lcanvas.h deleted file mode 100644 index 7bf8343e..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/lcanvas.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Landru Canvas - this is drawn to by the system. -////////////////////////////////////////////////////////////////////// -#include -#include "lrect.h" - -namespace TFE_DarkForces -{ - void lcanvas_init(s16 w, s16 h); - void lcanvas_destroy(); - - void lcanvas_getBounds(LRect* rect); - void lcanvas_setClip(LRect* rect); - void lcanvas_getClip(LRect* rect); - JBool lcanvas_clipRectToCanvas(LRect* rect); - void lcanvas_clearClipRect(); - - void lcanvas_eraseRect(LRect* rect); - JBool lcanvas_applyFade(JBool dialog); - - void lcanvas_clear(); - void lcanvas_showNextFrame(); - void lcanvas_copyScreenToVideo(LRect* rect); - void lcanvas_copyPortionToVideo(LRect* rect, s16 x, s16 y); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/ldraw.cpp b/components/darkforces/tfe/TFE_DarkForces/Landru/ldraw.cpp deleted file mode 100644 index 62f65856..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/ldraw.cpp +++ /dev/null @@ -1,370 +0,0 @@ -#include "ldraw.h" -#include "lcanvas.h" -#include "lsystem.h" -#include -#include -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - struct LDrawState - { - u8* bitmap = nullptr; - s32 bitmapWidth = 0; - s32 bitmapHeight = 0; - }; - static LDrawState s_state = {}; - - void ldraw_init(s16 w, s16 h) - { - if (w != s_state.bitmapWidth || h != s_state.bitmapHeight || !s_state.bitmap) - { - landru_free(s_state.bitmap); - s_state.bitmap = (u8*)landru_alloc(w * h); - memset(s_state.bitmap, 0, w * h); - - s_state.bitmapWidth = w; - s_state.bitmapHeight = h; - } - } - - void ldraw_destroy() - { - landru_free(s_state.bitmap); - s_state = {}; - } - - u8* ldraw_getBitmap() - { - return s_state.bitmap; - } - - JBool drawClippedColorRect(LRect* rect, u8 color) - { - u8* framebuffer = s_state.bitmap; - const u32 stride = s_state.bitmapWidth; - - LRect clipRect; - lcanvas_getClip(&clipRect); - - LRect drawRect = *rect; - if (!lrect_clip(&drawRect, &clipRect)) - { - return JFALSE; - } - - for (s32 y = drawRect.top; y < drawRect.bottom; y++) - { - u8* output = &framebuffer[y * stride]; - for (s32 x = drawRect.left; x < drawRect.right; x++) - { - output[x] = color; - } - } - return JTRUE; - } - - void drawDeltaIntoBitmap(s16* data, s16 x, s16 y, u8* framebuffer, s32 stride) - { - const u8* srcImage = (u8*)data; - while (1) - { - const s16* deltaLine = (s16*)srcImage; - s16 sizeAndType = TFE_Endian::le16_to_cpu(deltaLine[0]); - if (sizeAndType == 0) - { - break; - } - - s16 xStart = TFE_Endian::le16_to_cpu(deltaLine[1]) + x; - s16 yStart = TFE_Endian::le16_to_cpu(deltaLine[2]) + y; - // Size of the Delta Line structure. - srcImage += sizeof(s16) * 3; - - const JBool rle = (sizeAndType & 1) ? JTRUE : JFALSE; - const JBool skipCol = (xStart < 0 || xStart >= stride) ? JTRUE : JFALSE; - s32 pixelCount = (sizeAndType >> 1) & 0x3fff; - u8* dstImage = &framebuffer[yStart*stride + xStart]; - - while (pixelCount > 0) - { - if (rle) - { - //read count byte... - u8 count = *srcImage; srcImage++; - if (!(count & 1)) // direct - { - count >>= 1; - if (skipCol) - { - dstImage += count; - srcImage += count; - } - else - { - for (s32 p = 0; p < count; p++, dstImage++, srcImage++) - { - *dstImage = *srcImage; - } - } - pixelCount -= count; - } - else //rle - { - count >>= 1; - const u8 pixel = *srcImage; srcImage++; - if (skipCol) - { - dstImage += count; - } - else - { - for (s32 p = 0; p < count; p++, dstImage++) - { - *dstImage = pixel; - } - } - pixelCount -= count; - } - } - else - { - if (skipCol) - { - dstImage += pixelCount; - srcImage += pixelCount; - } - else - { - for (s32 p = 0; p < pixelCount; p++, dstImage++, srcImage++) - { - *dstImage = *srcImage; - } - } - pixelCount = 0; - } - } - } - } - - void deltaImage(s16* data, s16 x, s16 y) - { - drawDeltaIntoBitmap(data, x, y, s_state.bitmap, s_state.bitmapWidth); - } - - void deltaClip(s16* data, s16 x, s16 y) - { - u8* framebuffer = s_state.bitmap; - const u32 stride = s_state.bitmapWidth; - - LRect clipRect; - lcanvas_getClip(&clipRect); - - u8* srcImage = (u8*)data; - while (1) - { - const s16* deltaLine = (s16*)srcImage; - s16 sizeAndType = TFE_Endian::le16_to_cpu(deltaLine[0]); - s16 xStart = TFE_Endian::le16_to_cpu(deltaLine[1]) + x; - s16 yStart = TFE_Endian::le16_to_cpu(deltaLine[2]) + y; - srcImage += 3 * sizeof(s16); - - if (sizeAndType == 0) { break; } - - const JBool rle = (sizeAndType & 1) ? JTRUE : JFALSE; - s32 pixelCount = (sizeAndType >> 1) & 0x3fff; - u8* dstImage = &framebuffer[yStart*stride]; - - s16 xCur = xStart; - s16 yCur = yStart; - JBool writeRow = (yCur >= clipRect.top && yCur < clipRect.bottom) ? JTRUE : JFALSE; - - while (pixelCount > 0) - { - if (rle) - { - //read count byte... - u8 count = *srcImage; srcImage++; - if (!(count & 1)) // direct - { - count >>= 1; - for (s32 p = 0; p < count; p++, srcImage++, xCur++) - { - if (writeRow && xCur >= clipRect.left && xCur < clipRect.right) - { - dstImage[xCur] = *srcImage; - } - } - pixelCount -= count; - } - else //rle - { - count >>= 1; - const u8 pixel = *srcImage; srcImage++; - for (s32 p = 0; p < count; p++, xCur++) - { - if (writeRow && xCur >= clipRect.left && xCur < clipRect.right) - { - dstImage[xCur] = pixel; - } - } - pixelCount -= count; - } - } - else - { - for (s32 p = 0; p < pixelCount; p++, srcImage++, xCur++) - { - if (writeRow && xCur >= clipRect.left && xCur < clipRect.right) - { - dstImage[xCur] = *srcImage; - } - } - pixelCount = 0; - } - } - } - } - - void deltaFlip(s16* data, s16 x, s16 y, s16 w) - { - u8* framebuffer = s_state.bitmap; - const u32 stride = s_state.bitmapWidth; - - const u8* srcImage = (u8*)data; - while (1) - { - const s16* deltaLine = (s16*)srcImage; - s16 sizeAndType = TFE_Endian::le16_to_cpu(deltaLine[0]); - if (sizeAndType == 0) - { - break; - } - - s16 xCur = w - TFE_Endian::le16_to_cpu(deltaLine[1]) + x; - s16 yStart = TFE_Endian::le16_to_cpu(deltaLine[2]) + y; - // Size of the Delta Line structure. - srcImage += sizeof(s16) * 3; - - const JBool rle = (sizeAndType & 1) ? JTRUE : JFALSE; - s32 pixelCount = (sizeAndType >> 1) & 0x3fff; - u8* dstImage = &framebuffer[yStart*stride]; - - while (pixelCount > 0) - { - if (rle) - { - //read count byte... - u8 count = *srcImage; srcImage++; - if (!(count & 1)) // direct - { - count >>= 1; - for (s32 p = 0; p < count; p++, xCur--, srcImage++) - { - dstImage[xCur] = *srcImage; - } - pixelCount -= count; - } - else //rle - { - count >>= 1; - const u8 pixel = *srcImage; srcImage++; - for (s32 p = 0; p < count; p++, xCur--) - { - dstImage[xCur] = pixel; - } - pixelCount -= count; - } - } - else - { - for (s32 p = 0; p < pixelCount; p++, xCur--, srcImage++) - { - dstImage[xCur] = *srcImage; - } - pixelCount = 0; - } - } - } - } - - void deltaFlipClip(s16* data, s16 x, s16 y, s16 w) - { - u8* framebuffer = s_state.bitmap; - const u32 stride = s_state.bitmapWidth; - - LRect clipRect; - lcanvas_getClip(&clipRect); - - u8* srcImage = (u8*)data; - while (1) - { - const s16* deltaLine = (s16*)srcImage; - s16 sizeAndType = TFE_Endian::le16_to_cpu(deltaLine[0]); - s16 xStart = TFE_Endian::le16_to_cpu(deltaLine[1]) + x; - s16 yStart = TFE_Endian::le16_to_cpu(deltaLine[2]) + y; - srcImage += 3 * sizeof(s16); - - if (sizeAndType == 0) { break; } - - const JBool rle = (sizeAndType & 1) ? JTRUE : JFALSE; - s32 pixelCount = (sizeAndType >> 1) & 0x3fff; - u8* dstImage = &framebuffer[yStart*stride]; - - s16 xCur = w - TFE_Endian::le16_to_cpu(deltaLine[1]) + x; - s16 yCur = yStart; - JBool writeRow = (yCur >= clipRect.top && yCur < clipRect.bottom) ? JTRUE : JFALSE; - - while (pixelCount > 0) - { - if (rle) - { - //read count byte... - u8 count = *srcImage; srcImage++; - if (!(count & 1)) // direct - { - count >>= 1; - for (s32 p = 0; p < count; p++, srcImage++, xCur--) - { - if (writeRow && xCur >= clipRect.left && xCur < clipRect.right) - { - dstImage[xCur] = *srcImage; - } - } - pixelCount -= count; - } - else //rle - { - count >>= 1; - const u8 pixel = *srcImage; srcImage++; - for (s32 p = 0; p < count; p++, xCur--) - { - if (writeRow && xCur >= clipRect.left && xCur < clipRect.right) - { - dstImage[xCur] = pixel; - } - } - pixelCount -= count; - } - } - else - { - for (s32 p = 0; p < pixelCount; p++, srcImage++, xCur--) - { - if (writeRow && xCur >= clipRect.left && xCur < clipRect.right) - { - dstImage[xCur] = *srcImage; - } - } - pixelCount = 0; - } - } - } - } -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/ldraw.h b/components/darkforces/tfe/TFE_DarkForces/Landru/ldraw.h deleted file mode 100644 index 65083279..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/ldraw.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Landru Palette -////////////////////////////////////////////////////////////////////// -#include -#include "lrect.h" - -namespace TFE_DarkForces -{ - void ldraw_init(s16 w, s16 h); - void ldraw_destroy(); - u8* ldraw_getBitmap(); - - void deltaImage(s16* data, s16 x, s16 y); - void deltaClip(s16* data, s16 x, s16 y); - void deltaFlip(s16* data, s16 x, s16 y, s16 w); - void deltaFlipClip(s16* data, s16 x, s16 y, s16 w); - JBool drawClippedColorRect(LRect* rect, u8 color); - - void drawDeltaIntoBitmap(s16* data, s16 x, s16 y, u8* framebuffer, s32 stride); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/lfade.cpp b/components/darkforces/tfe/TFE_DarkForces/Landru/lfade.cpp deleted file mode 100644 index 3c521250..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/lfade.cpp +++ /dev/null @@ -1,567 +0,0 @@ -#include "lfade.h" -#include "lcanvas.h" -#include "lpalette.h" -#include "lsystem.h" -#include "ltimer.h" -#include "ldraw.h" -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - JBool s_fadeInit = JFALSE; - LFade* s_fade = nullptr; - - LFade* lfade_alloc(); - void lfade_free(LFade* fade); - s16 lfade_calculateFadeLength(FadeType type); - void lfade_startColorFade(FadeColorType colorType, JBool paletteChange, s16 len, s16 delay, s16 lock); - - void lfade_init() - { - s_fade = lfade_alloc(); - - if (s_fade) - { - for (s32 i = 0; i < LVIEW_COUNT; i++) - { - s_fade->type[i] = ftype_noFade; - } - s_fade->fullType = ftype_noFade; - s_fade->colorType = fcolorType_noColorFade; - s_fade->r = 0; - s_fade->g = 0; - s_fade->b = 0; - - s_fadeInit = JTRUE; - } - } - - void lfade_destroy() - { - if (s_fadeInit && s_fade) - { - lfade_free(s_fade); - s_fade = nullptr; - } - s_fadeInit = JFALSE; - } - - LFade* lfade_alloc() - { - return (LFade*)landru_alloc(sizeof(LFade)); - } - - void lfade_free(LFade* fade) - { - landru_free(fade); - } - - void lfade_start(s16 viewId, FadeType type, FadeColorType colorType, JBool paletteChange, s16 delay, s16 lock) - { - s_fade->type[viewId] = type; - s_fade->delay[viewId] = delay; - s_fade->lock[viewId] = lock; - s_fade->len[viewId] = lfade_calculateFadeLength(type); - s_fade->step[viewId] = 0; - - lfade_startColorFade(colorType, paletteChange, s_fade->len[viewId], delay, lock); - } - - void lfade_startFull(FadeType type, FadeColorType colorType, JBool paletteChange, s16 delay, s16 lock) - { - s_fade->fullType = type; - s_fade->fullDelay = delay; - s_fade->fullLock = lock; - s_fade->fullLen = lfade_calculateFadeLength(type); - s_fade->fullStep = 0; - - lfade_startColorFade(colorType, paletteChange, s_fade->fullLen, delay, lock); - } - - void lfade_startColorFade(FadeColorType colorType, JBool paletteChange, s16 len, s16 delay, s16 lock) - { - if (colorType != fcolorType_noColorFade) - { - s_fade->colorType = colorType; - lpalette_copyScreenToSrc(0, 0, 255); - if (!paletteChange) - { - lpalette_copyScreenToDest(0, 0, 255); - } - - s_fade->colorDelay = delay; - s_fade->colorLock = lock; - s_fade->colorLen = len; - s_fade->colorStep = 0; - } - } - - void lfade_setColor(s16 r, s16 g, s16 b) - { - s_fade->r = u8(r); - s_fade->g = u8(g); - s_fade->b = u8(b); - } - - s16 lfade_calculateFadeLength(FadeType type) - { - s16 time; - - switch (type) - { - case ftype_snapFade: - time = 1; - break; - case ftype_shortSnapFade: - time = 16; - break; - default: - time = 32; - break; - } - - return time; - } - - JBool lfade_isStep(FadeType type, s16 lock, s16 delay, s32 time, s32 lockTime) - { - if (type == ftype_noFade) { return 0; } - if (time == lockTime) { return !delay; } - return (!delay) && lock; - } - - JBool lfade_isDelayStep(FadeType type, s16 delay, s32 time, s32 lockTime) - { - if (delay && type != ftype_noFade && time == lockTime) - { - return JTRUE; - } - return JFALSE; - } - - void lfade_calculateFadeLockTime(s32* time, s32* end) - { - s32 lockTime = lview_getTime(); - s32 lockEnd = lockTime; - - if (lfade_isStep(s_fade->fullType, s_fade->fullLock, s_fade->fullDelay, lockTime, lockTime)) - { - if (s_fade->fullLock) - { - lockEnd = lockTime + s_fade->fullLen; - } - - for (s32 i = 0; i < LVIEW_COUNT; i++) - { - s_fade->type[i] = ftype_noFade; - } - } - else - { - for (s32 i = 0; i < LVIEW_COUNT; i++) - { - if (lfade_isStep(s_fade->type[i], s_fade->lock[i], s_fade->delay[i], lockTime, lockTime) && s_fade->lock[i]) - { - if (lockTime + s_fade->len[i] > lockEnd) - { - lockEnd = lockTime + s_fade->fullLen; - } - } - } - } - - *time = lockTime; - *end = lockEnd; - } - - JBool lfade_isActive() - { - s32 time = lview_getTime(); - if (s_fade->fullType != ftype_noFade && !s_fade->fullDelay) - { - return JTRUE; - } - for (s32 i = 0; i < LVIEW_COUNT; i++) - { - if (s_fade->type[i] != ftype_noFade && !s_fade->delay[i]) - { - return JTRUE; - } - } - return JFALSE; - } - - void lfade_fadeToVideoPalette(s32 time, s32 lockTime) - { - s16 applyFadeStep = 0; - if (s_fade->colorType != fcolorType_noColorFade) - { - if (s_fade->colorLock) - { - if (time == lockTime) - { - if (s_fade->colorDelay) - { - s_fade->colorDelay--; - } - else - { - applyFadeStep = 1; - } - } - else if (!s_fade->colorDelay) - { - applyFadeStep = 1; - } - } - else if (time == lockTime) - { - if (s_fade->colorDelay) - { - s_fade->colorDelay--; - } - else - { - applyFadeStep = 1; - } - } - } - - if (applyFadeStep) - { - s16 step = s_fade->colorStep; - s16 len = s_fade->colorLen; - s16 mid = len >> 1; - - switch (s_fade->colorType) - { - case fcolorType_snapColorFade: - { - if (step == mid) - { - // Make sure we are show the next frame *before* changing the palette. - lcanvas_showNextFrame(); - - lpalette_copyDstToScreen(0, 0, 255); - lpalette_putScreenPal(); - } - } break; - case fcolorType_monoColorFade: - { - if (step < mid) - { - s16 fraction = step * 256 / mid; - lpalette_buildFadePalette(LPAL_BUILD_MONODEST, 0, 255, fraction, (s16)s_fade->r, (s16)s_fade->g, (s16)s_fade->b); - } - else - { - s16 fraction = (step - mid) * 256 / (len - mid); - lpalette_buildFadePalette(LPAL_BUILD_MONOSRC, 0, 255, fraction, (s16)s_fade->r, (s16)s_fade->g, (s16)s_fade->b); - } - lpalette_putScreenPal(); - } break; - case fcolorType_toMonoColorFade: - { - s16 fraction = step * 256 / len; - lpalette_buildFadePalette(LPAL_BUILD_MONODEST, 0, 255, fraction, (s16)s_fade->r, (s16)s_fade->g, (s16)s_fade->b); - lpalette_putScreenPal(); - } break; - case fcolorType_fromMonoColorFade: - { - s16 fraction = step * 256 / len; - lpalette_buildFadePalette(LPAL_BUILD_MONOSRC, 0, 255, fraction, (s16)s_fade->r, (s16)s_fade->g, (s16)s_fade->b); - lpalette_putScreenPal(); - } break; - case fcolorType_paletteColorFade: - { - s16 fraction = step * 256 / len; - lpalette_buildFadePalette(LPAL_BUILD_PALETTE, 0, 255, fraction, 0, 0, 0); - lpalette_putScreenPal(); - } break; - } - - s_fade->colorStep++; - if (s_fade->colorStep > s_fade->colorLen) - { - s_fade->colorType = fcolorType_noColorFade; - } - } - } - - void lfade_copyToVideo(LRect* frame, FadeType type, s16 step, s16 length, s16 lock) - { - if (lrect_isEmpty(frame)) { return; } - - s16 revStep = length - step; - LRect fadeRect = *frame; - s16 slice = 0; - s16 xOffset = frame->left; - s16 yOffset = frame->top; - s16 cut = 0; - s16 wOffset = 0; - - switch (type) - { - case ftype_shortSnapFade: - case ftype_longSnapFade: - { - if ((step != length >> 1) && lock) - { - lrect_set(&fadeRect, 0, 0, 0, 0); - } - } break; - case ftype_slideLeftFade: - { - fadeRect.left = frame->right - ((frame->right - frame->left) * step) / length; - } break; - case ftype_slideRightFade: - { - fadeRect.right = frame->left + ((frame->right - frame->left) * step) / length; - xOffset = frame->right - (fadeRect.right - fadeRect.left); - } break; - case ftype_slideUpFade: - { - fadeRect.bottom = frame->top + ((frame->bottom - frame->top) * step) / length; - yOffset = frame->bottom - (fadeRect.bottom - fadeRect.top); - } break; - case ftype_slideDownFade: - { - fadeRect.top = frame->bottom - ((frame->bottom - frame->top) * step) / length; - } break; - case ftype_slideTLeftFade: - { - fadeRect.top = frame->bottom - ((frame->bottom - frame->top) * step) / length; - fadeRect.right = frame->left + ((frame->right - frame->left) * step) / length; - xOffset = frame->right - (fadeRect.right - fadeRect.left); - } break; - case ftype_slideTRightFade: - { - fadeRect.top = frame->bottom - ((frame->bottom - frame->top) * step) / length; - fadeRect.left = frame->right - ((frame->right - frame->left) * step) / length; - } break; - case ftype_slideBLeftFade: - { - fadeRect.bottom = frame->top + ((frame->bottom - frame->top) * step) / length; - fadeRect.right = frame->left + ((frame->right - frame->left) * step) / length; - xOffset = frame->right - (fadeRect.right - fadeRect.left); - yOffset = frame->bottom - (fadeRect.bottom - fadeRect.top); - } break; - case ftype_slideBRightFade: - { - fadeRect.bottom = frame->top + ((frame->bottom - frame->top) * step) / length; - fadeRect.left = frame->right - ((frame->right - frame->left) * step) / length; - yOffset = frame->bottom - (fadeRect.bottom - fadeRect.top); - } break; - case ftype_wipeLeftFade: - { - fadeRect.right = frame->left + ((frame->right - frame->left) * step) / length; - } break; - case ftype_wipeRightFade: - { - fadeRect.left = frame->right - ((frame->right - frame->left) * step) / length; - xOffset = fadeRect.left; - } break; - case ftype_wipeUpFade: - { - fadeRect.top = frame->bottom - ((frame->bottom - frame->top) * step) / length; - yOffset = fadeRect.top; - } break; - case ftype_wipeDownFade: - { - fadeRect.bottom = frame->top + ((frame->bottom - frame->top) * step) / length; - } break; - case ftype_wipeTLeftFade: - { - fadeRect.top = frame->bottom - ((frame->bottom - frame->top) * step) / length; - fadeRect.right = frame->left + ((frame->right - frame->left) * step) / length; - yOffset = fadeRect.top; - } break; - case ftype_wipeTRightFade: - { - fadeRect.top = frame->bottom - ((frame->bottom - frame->top) * step) / length; - fadeRect.left = frame->right - ((frame->right - frame->left) * step) / length; - xOffset = fadeRect.left; - yOffset = fadeRect.top; - } break; - case ftype_wipeBLeftFade: - { - fadeRect.bottom = frame->top + ((frame->bottom - frame->top) * step) / length; - fadeRect.right = frame->left + ((frame->right - frame->left) * step) / length; - } break; - case ftype_wipeBRightFade: - { - fadeRect.bottom = frame->top + ((frame->bottom - frame->top) * step) / length; - fadeRect.left = frame->right - ((frame->right - frame->left) * step) / length; - xOffset = fadeRect.left; - } break; - case ftype_vertCenterFade: - { - s16 val = (((frame->bottom - frame->top) >> 1) * revStep) / length; - fadeRect.top = frame->top + val; - fadeRect.bottom = frame->bottom - val; - yOffset = fadeRect.top; - } break; - case ftype_horizCenterFade: - { - s16 val = (((frame->right - frame->left) >> 1) * revStep) / length; - fadeRect.left = frame->left + val; - fadeRect.right = frame->right - val; - xOffset = fadeRect.left; - } break; - case ftype_centerFade: - { - s16 val = (((frame->bottom - frame->top) >> 1) * revStep) / length; - fadeRect.top = frame->top + val; - fadeRect.bottom = frame->bottom - val; - yOffset = fadeRect.top; - - val = (((frame->right - frame->left) >> 1) * revStep) / length; - fadeRect.left = frame->left + val; - fadeRect.right = frame->right - val; - xOffset = fadeRect.left; - } break; - case ftype_thinSliceFade: - { - wOffset = ((fadeRect.right - fadeRect.left) * step) / length; - slice++; - cut = 1; - } break; - case ftype_sliceFade: - { - wOffset = ((fadeRect.right - fadeRect.left) * step) / length; - slice++; - cut = 4; - } break; - case ftype_thickSliceFade: - { - wOffset = ((fadeRect.right - fadeRect.left) * step) / length; - slice++; - cut = 8; - } break; - } - - if (!lrect_isEmpty(&fadeRect)) - { - if (type == ftype_noFade || type == ftype_snapFade || type == ftype_shortSnapFade || type == ftype_longSnapFade) - { - lcanvas_copyScreenToVideo(&fadeRect); - } - else if (slice) - { - // Code empty here... - } - else - { - lcanvas_copyPortionToVideo(&fadeRect, xOffset, yOffset); - } - } - } - - static LRect s_fadeRect; - static JBool s_fadeDialog; - static s32 s_fadeTime; - static s32 s_fadeLockTime = -1; - static s32 s_fadeLockEnd = -1; - static u16 s_baseRate; - - void lfade_loop(s32 time) - { - lfade_fadeToVideoPalette(time, s_fadeLockTime); - - if (lfade_isStep(s_fade->fullType, s_fade->fullLock, s_fade->fullDelay, time, s_fadeLockTime)) - { - lfade_copyToVideo(&s_fadeRect, s_fade->fullType, s_fade->fullStep, s_fade->fullLen, time != s_fadeLockEnd); - s_fade->fullStep++; - if (s_fade->fullStep > s_fade->fullLen) - { - s_fade->fullType = ftype_noFade; - } - } - else - { - if (lfade_isDelayStep(s_fade->fullType, s_fade->fullDelay, time, s_fadeLockTime)) - { - s_fade->fullDelay--; - } - - if (s_fadeDialog) - { - lfade_copyToVideo(&s_fadeRect, ftype_snapFade, 0, 0, JFALSE); - } - else - { - for (s32 i = 0; i < LVIEW_COUNT; i++) - { - if (lview_copyEnabled(i)) - { - LRect frame; - lview_getViewClipFrame(i, &frame); - lrect_clip(&frame, &s_fadeRect); - - if (lfade_isStep(s_fade->type[i], s_fade->lock[i], s_fade->delay[i], time, s_fadeLockTime)) - { - lfade_copyToVideo(&frame, s_fade->type[i], s_fade->step[i], s_fade->len[i], time != s_fadeLockEnd); - s_fade->step[i]++; - if (s_fade->step[i] > s_fade->len[i]) - { - s_fade->type[i] = ftype_noFade; - } - } - else - { - if (lfade_isDelayStep(s_fade->type[i], s_fade->delay[i], time, s_fadeLockTime)) - { - s_fade->delay[i]--; - } - if (s_fade->type[i] == ftype_noFade) - { - lfade_copyToVideo(&frame, ftype_snapFade, 0, 0, time != s_fadeLockEnd); - } - } - } - } - } - } - } - - JBool lfade_applyFadeLoop(LRect* rect, JBool dialog) - { - if (s_fadeLockTime < 0) - { - s_fadeRect = *rect; - s_fadeDialog = dialog; - lfade_calculateFadeLockTime(&s_fadeLockTime, &s_fadeLockEnd); - s_fadeTime = s_fadeLockTime; - s_baseRate = ltime_getDelay(); - } - // We are not fading at all. - if (s_fadeTime > s_fadeLockEnd) - { - return JTRUE; - } - // Fading is applied - if (s_fadeTime <= s_fadeLockEnd) - { - lfade_loop(s_fadeTime); - s_fadeTime++; - - if (s_fadeTime > s_fadeLockEnd) - { - s_fadeLockTime = -1; - s_fadeLockEnd = -1; - s_fadeTime = 0; - ltime_setFrameDelay(s_baseRate); - return JTRUE; - } - // Fading occurs at a higher framerate. - ltime_setFrameDelay(4); - } - return JFALSE; - } -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/lfade.h b/components/darkforces/tfe/TFE_DarkForces/Landru/lfade.h deleted file mode 100644 index aa04127f..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/lfade.h +++ /dev/null @@ -1,94 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Landru Fade System -////////////////////////////////////////////////////////////////////// -#include -#include "lrect.h" -#include "lview.h" - -namespace TFE_DarkForces -{ - enum LFadeConstants - { - LFADE_PALETTE = 1, - LFADE_LOCK = 1, - }; - - enum FadeType - { - ftype_noFade = 0, - ftype_snapFade, - ftype_shortSnapFade, - ftype_longSnapFade, - ftype_slideLeftFade, - ftype_slideRightFade, - ftype_slideUpFade, - ftype_slideDownFade, - ftype_slideTLeftFade, - ftype_slideTRightFade, - ftype_slideBLeftFade, - ftype_slideBRightFade, - ftype_wipeLeftFade, - ftype_wipeRightFade, - ftype_wipeUpFade, - ftype_wipeDownFade, - ftype_wipeTLeftFade, - ftype_wipeTRightFade, - ftype_wipeBLeftFade, - ftype_wipeBRightFade, - ftype_horizCenterFade, - ftype_vertCenterFade, - ftype_centerFade, - ftype_thinSliceFade, - ftype_sliceFade, - ftype_thickSliceFade, - ftype_count - }; - - enum FadeColorType - { - fcolorType_noColorFade, - fcolorType_snapColorFade, - fcolorType_monoColorFade, - fcolorType_toMonoColorFade, - fcolorType_fromMonoColorFade, - fcolorType_paletteColorFade, - fcolorType_count - }; - - struct LFade - { - FadeType type[LVIEW_COUNT]; - s16 delay[LVIEW_COUNT]; - s16 lock[LVIEW_COUNT]; - s16 step[LVIEW_COUNT]; - s16 len[LVIEW_COUNT]; - - FadeType fullType; - s16 fullDelay; - s16 fullLock; - s16 fullStep; - s16 fullLen; - - FadeColorType colorType; - s16 colorDelay; - s16 colorLock; - s16 colorStep; - s16 colorLen; - u8 r; - u8 g; - u8 b; - u8 pad8; - }; - - void lfade_init(); - void lfade_destroy(); - void lfade_start(s16 viewId, FadeType type, FadeColorType colorType, JBool paletteChange, s16 delay, s16 lock); - void lfade_startFull(FadeType type, FadeColorType colorType, JBool paletteChange, s16 delay, s16 lock); - void lfade_startColorFade(FadeColorType colorType, JBool paletteChange, s16 len, s16 delay, s16 lock); - void lfade_setColor(s16 r, s16 g, s16 b); - - JBool lfade_isActive(); - JBool lfade_applyFadeLoop(LRect* rect, JBool dialog); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/lfont.cpp b/components/darkforces/tfe/TFE_DarkForces/Landru/lfont.cpp deleted file mode 100644 index cbe5508a..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/lfont.cpp +++ /dev/null @@ -1,374 +0,0 @@ -#include "lfont.h" -#include "lcanvas.h" -#include "ldraw.h" -#include "lpalette.h" -#include "lsystem.h" -#include "ltimer.h" -#include -#include -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - enum - { - MAX_FONT_HEIGHT = 22, - FONT_SPACE_BETWEEN = 1, - FONT_LINES_BETWEEN = 1, - FONT_INDENT = 16, - NUM_FONTS = 6, - }; - - struct LFont - { - u16 firstChar; - u16 numChars; - - u16 spaceBetween; - u16 linesBetween; - u16 indent; - - u16 width; - u16 height; - u16 baseline; - - u16 isColor; - - u16 charSize; - - u8* widthArray; - u8* data; - - s16 unused[2]; - }; - - static LFont* s_fonts[NUM_FONTS]; - static LFont* s_curFont; - static LRect s_fontFrame = { 0 }; - static s16 s_curFontId; - static s16 s_fontX, s_fontY; - static u8 s_fontColor; - - void lfont_initFont(LFont* font); - JBool lfont_add(s16 id, LFont* font); - void lfont_remove(s16 id); - - void lfont_init() - { - for (s32 i = 0; i < NUM_FONTS; i++) - { - s_fonts[i] = nullptr; - } - - s_curFont = nullptr; - s_curFontId = -1; - s_fontX = 0; - s_fontY = 0; - - s_fontColor = 15; - } - - void lfont_destroy() - { - for (s32 i = 0; i < NUM_FONTS; i++) - { - if (s_fonts[i]) - { - lfont_remove(i); - } - } - } - - LFont* lfont_alloc(s16 id) - { - LFont* font = (LFont*)landru_alloc(sizeof(LFont)); - if (font) - { - lfont_initFont(font); - lfont_add(id, font); - } - return font; - } - - void lfont_free(LFont* font) - { - if (!font) { return; } - - if (font->widthArray) - { - landru_free(font->widthArray); - } - if (font->data) - { - landru_free(font->data); - } - landru_free(font); - } - - void lfont_initFont(LFont* font) - { - font->firstChar = ' '; - font->numChars = 0; - font->spaceBetween = FONT_SPACE_BETWEEN; - font->linesBetween = FONT_LINES_BETWEEN; - font->indent = FONT_INDENT; - - font->width = 0; - font->height = 0; - font->baseline = 0; - font->charSize = 0; - font->widthArray = nullptr; - font->data = nullptr; - } - - JBool lfont_add(s16 id, LFont* font) - { - if (id < 0 || id >= NUM_FONTS) { return JFALSE; } - if (s_fonts[id]) - { - lfont_remove(id); - } - s_fonts[id] = font; - return JTRUE; - } - - void lfont_remove(s16 id) - { - if (s_fonts[id]) - { - lfont_free(s_fonts[id]); - s_fonts[id] = nullptr; - } - } - - JBool lfont_load(const char* name, s32 id) - { - char fontFile[32]; - sprintf(fontFile, "%s.FONT", name); - FilePath fontPath; - FileStream file; - if (!TFE_Paths::getFilePath(fontFile, &fontPath)) { return JFALSE; } - if (!file.open(&fontPath, Stream::MODE_READ)) { return JFALSE; } - - LFont* font = lfont_alloc(id); - file.read(&font->firstChar); - file.read(&font->numChars); - file.read(&font->width); - file.read(&font->height); - font->firstChar = TFE_Endian::le16_to_cpu(font->firstChar); - font->numChars = TFE_Endian::le16_to_cpu(font->numChars); - font->width = TFE_Endian::le16_to_cpu(font->width); - font->height = TFE_Endian::le16_to_cpu(font->height); - font->charSize = (font->width >> 3) * font->height; - - if (font->height > MAX_FONT_HEIGHT) - { - file.close(); - lfont_remove(id); - return JFALSE; - } - - file.read(&font->baseline); - file.read(&font->isColor); - font->baseline = TFE_Endian::le16_to_cpu(font->baseline); - font->isColor = TFE_Endian::le16_to_cpu(font->isColor); - - font->widthArray = (u8*)landru_alloc(256); - memset(font->widthArray, 0, 256); - if (font->widthArray) - { - file.readBuffer(font->widthArray + font->firstChar, font->numChars); - } - - u32 fontSize = font->charSize * font->numChars; - font->data = (u8*)landru_alloc(fontSize); - file.readBuffer(font->data, fontSize); - - file.close(); - return JTRUE; - } - - s16 lfont_set(s16 id) - { - s16 lastFont = s_curFontId; - if (id >= 0 && id < NUM_FONTS) - { - s_curFont = s_fonts[id]; - s_curFontId = id; - } - else - { - s_curFont = nullptr; - s_curFontId = -1; - } - return lastFont; - } - - s16 lfont_getCurrent() - { - return s_curFontId; - } - - u8 lfont_setColor(u8 color) - { - u8 lastColor = s_fontColor; - s_fontColor = color; - return lastColor; - } - - u8 lfont_getColor() - { - return s_fontColor; - } - - void lfont_setFrame(LRect* frame) - { - s_fontFrame = *frame; - lfont_homePosition(); - } - - void lfont_getFrame(LRect* frame) - { - *frame = s_fontFrame; - } - - void lfont_setPosition(s16 x, s16 y) - { - s_fontX = x; - s_fontY = y; - s_fontFrame.left = x; - s_fontFrame.top = y; - } - - void lfont_getPosition(s16* x, s16* y) - { - *x = s_fontX; - *y = s_fontY; - } - - void lfont_movePosition(s16 dx, s16 dy) - { - s_fontX += dx; - s_fontY += dy; - } - - void lfont_returnPosition(s16 dy) - { - s_fontX = s_fontFrame.left; - s_fontY += dy; - } - - void lfont_homePosition() - { - s_fontX = s_fontFrame.left; - s_fontY = s_fontFrame.top; - } - - s16 lfont_getTextWidth(const char* text) - { - if (!s_curFont) { return 0; } - - u8* widthArray = s_curFont->widthArray; - s16 len = 0; - for (; *text; text++) - { - u8 value = u8(text[0]); - len += widthArray[value]; - if (text[1]) - { - len += s_curFont->spaceBetween; - } - } - - return len; - } - - void lfont_getRect(const char* text, LRect* rect) - { - if (s_curFont) - { - s16 w = lfont_getTextWidth(text); - lrect_set(rect, 0, 0, w, s_curFont->height); - } - else - { - lrect_clear(rect); - } - } - - void lfont_drawText(const char* text, u8* bitmap/* = nullptr*/) - { - if (!s_curFont || !text) { return; } - - u8* widthArray = s_curFont->widthArray; - u8* data = s_curFont->data; - if (!bitmap) { bitmap = ldraw_getBitmap(); } - - const s16 stepY = (s_curFont->width >> 3); - const s16 step = s_curFont->charSize; - s16 xGlyph = s_fontX; - for (; *text; text++) - { - u8 value = u8(text[0]); - u8* curGlyph = &data[(value - s_curFont->firstChar) * step]; - for (s32 y = 0; y < s_curFont->height; y++, curGlyph += stepY) - { - u8* output = &bitmap[(y + s_fontY) * 320 + xGlyph]; - for (s32 x = 0; x < s_curFont->width; x++) - { - u32 mask = 1 << ((7-x) & 7); - if (curGlyph[x >> 3] & mask) - { - output[x] = s_fontColor; - } - } - } - - xGlyph += widthArray[value]; - if (text[1]) - { - xGlyph += s_curFont->spaceBetween; - } - } - } - - JBool lfont_drawTextClipped(const char* text) - { - LRect textRect; - lfont_getRect(text, &textRect); - lrect_offset(&textRect, s_fontX, s_fontY); - - JBool adjust = JFALSE; - JBool retValue = JFALSE; - LRect clipRect = textRect; - if (lcanvas_clipRectToCanvas(&clipRect)) - { - if (!lrect_equal(&textRect, &clipRect)) - { - // TODO - } - else - { - lfont_drawText(text); - retValue = JTRUE; - } - } - else - { - adjust = JTRUE; - } - - if (adjust) - { - s_fontX += textRect.right - textRect.left; - } - - return retValue; - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/lfont.h b/components/darkforces/tfe/TFE_DarkForces/Landru/lfont.h deleted file mode 100644 index ff8c64e4..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/lfont.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Landru Font -////////////////////////////////////////////////////////////////////// -#include -#include "lrect.h" - -namespace TFE_DarkForces -{ - void lfont_init(); - void lfont_destroy(); - - JBool lfont_load(const char* name, s32 id); - - s16 lfont_set(s16 id); - s16 lfont_getCurrent(); - u8 lfont_setColor(u8 color); - u8 lfont_getColor(); - - void lfont_setFrame(LRect* frame); - void lfont_getFrame(LRect* frame); - void lfont_setPosition(s16 x, s16 y); - void lfont_getPosition(s16* x, s16* y); - void lfont_movePosition(s16 dx, s16 dy); - void lfont_returnPosition(s16 dy); - void lfont_homePosition(); - s16 lfont_getTextWidth(const char* text); - - void lfont_drawText(const char* text, u8* bitmap = nullptr); - JBool lfont_drawTextClipped(const char* text); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/lmusic.cpp b/components/darkforces/tfe/TFE_DarkForces/Landru/lmusic.cpp deleted file mode 100644 index e110d4e8..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/lmusic.cpp +++ /dev/null @@ -1,288 +0,0 @@ -#include "lmusic.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; -#define SHOW_MUSIC_MSG 0 - -#if SHOW_MUSIC_MSG -#define LMUSIC_MSG(fmt, ...) TFE_System::logWrite(LOG_MSG, "Landru Music", fmt, __VA_ARGS__) -#else -#define LMUSIC_MSG(fmt, ...) -#endif - -namespace TFE_DarkForces -{ - enum MusicConstants - { - LEVEL_COUNT = 14, - SEQUENCE_COUNT = 20, - MAX_CUE_POINTS = 20, - }; - - struct Sequence - { - char name[10]; - s8 xChunk; - s32 xMeasure; - s8 yChunk; - s32 yMeasure; - }; -#ifdef TFE_ESPBOX - static Sequence (*s_sequences)[MAX_CUE_POINTS] = nullptr; // [SEQUENCE_COUNT][MAX_CUE_POINTS] (shared memory) -#else - static Sequence s_sequences[SEQUENCE_COUNT][MAX_CUE_POINTS]; -#endif - - static ImSoundId s_saveSound = IM_NULL_SOUNDID; - static s32 s_curSeq = 0; - static s32 s_curCuePoint = 0; - static f32 s_volume = 1.0f; - static f32 s_baseVolume = 1.0f; - - void lmusic_init() - { - s_curSeq = 0; - s_curCuePoint = 0; - memset(s_sequences, 0, sizeof(Sequence) * SEQUENCE_COUNT * MAX_CUE_POINTS); - - FilePath filePath; - FileStream file; - if (!TFE_Paths::getFilePath("cutmuse.txt", &filePath)) { return; } - if (!file.open(&filePath, Stream::MODE_READ)) { return; } - - size_t size = file.getSize(); - char* buffer = (char*)landru_alloc(size); - if (!buffer) { return; } - - file.readBuffer(buffer, (u32)size); - file.close(); - - TFE_Parser parser; - parser.addCommentString("//"); - parser.addCommentString("#"); - parser.init(buffer, size); - - size_t bufferPos = 0; - const char* fileData = parser.readLine(bufferPos); - - s32 index = 0; - char name[80]; - while (fileData) - { - s32 sequence; - if (sscanf(fileData, "SEQUENCE: %d", &sequence) == 1) - { - index = 0; - } - else if (sscanf(fileData, "CUE: %s", name) == 1) - { - fileData = parser.readLine(bufferPos); - - char xChunk, yChunk; - s32 xMeasure, yMeasure; - if (sscanf(fileData, "%c %d %c %d", &xChunk, &xMeasure, &yChunk, &yMeasure) == 4) - { - if (sequence && sequence <= SEQUENCE_COUNT && index < MAX_CUE_POINTS) - { - strncpy(s_sequences[sequence - 1][index].name, name, 9); - s_sequences[sequence - 1][index].name[9] = 0; - - s_sequences[sequence-1][index].xChunk = xChunk; - s_sequences[sequence-1][index].xMeasure = xMeasure; - s_sequences[sequence-1][index].yChunk = yChunk; - s_sequences[sequence-1][index].yMeasure = yMeasure; - index++; - } - } - } - fileData = parser.readLine(bufferPos); - } - - landru_free(buffer); - } - - void lmusic_destroy() - { - s_saveSound = IM_NULL_SOUNDID; - s_curSeq = 0; - s_curCuePoint = 0; - s_volume = s_baseVolume; - memset(s_sequences, 0, sizeof(Sequence) * SEQUENCE_COUNT * MAX_CUE_POINTS); - } - - void lmusic_reset() - { - s_saveSound = IM_NULL_SOUNDID; - s_curSeq = 0; - s_curCuePoint = 0; - s_volume = s_baseVolume; - } - - void lmusic_stop() - { - ImStopAllSounds(); - ImUnloadAll(); - } - - s32 lmusic_setSequence(s32 newSeq) - { - if (newSeq > SEQUENCE_COUNT || s_curSeq == newSeq) { return s_curSeq; } - s32 oldSeq = s_curSeq; - s_curSeq = newSeq; - - if (s_curSeq != oldSeq) - { - LMUSIC_MSG("Set Seq %lu...", newSeq); - ImStopAllSounds(); - ImUnloadAll(); - s_curCuePoint = 0; // Reset cue point on sequence change. - if (s_curSeq) - { - for (s32 i = 0; i < MAX_CUE_POINTS; i++) - { - if (s_sequences[s_curSeq - 1][i].name[0]) - { - ImLoadMidi(s_sequences[s_curSeq - 1][i].name); - } - } - } - } - return s_curSeq; - } - - s32 lmusic_setCuePoint(s32 newCuePoint) - { - ImPause(); - - if (s_curSeq && (u32)newCuePoint < MAX_CUE_POINTS && newCuePoint != s_curCuePoint) - { - if (!newCuePoint) - { - ImStopAllSounds(); - s_saveSound = IM_NULL_SOUNDID; - } - else - { - if (s_curCuePoint) - { - ImClearTrigger(-1, -1, -1); // Clear pending midi transitions. - - const char* oldTitle = s_sequences[s_curSeq - 1][s_curCuePoint - 1].name; - ImSoundId oldSound = ImFindMidi(oldTitle); - if (!oldSound) { oldSound = s_saveSound; } - else { s_saveSound = oldSound; } - - char* newTitle = s_sequences[s_curSeq - 1][newCuePoint - 1].name; - char oldChunk = s_sequences[s_curSeq - 1][newCuePoint - 1].xChunk; - char newChunk = s_sequences[s_curSeq - 1][newCuePoint - 1].yChunk; - s32 oldMeasure = s_sequences[s_curSeq - 1][newCuePoint - 1].xMeasure; - s32 newMeasure = s_sequences[s_curSeq - 1][newCuePoint - 1].yMeasure; - - // A = 1, B = 2, ... - if (oldChunk > '@') { oldChunk -= '@'; } - if (newChunk > '@') { newChunk -= '@'; } - - if (oldChunk == 26) - { - // End of sequence marker. - ImStopSound(oldSound); - s_saveSound = IM_NULL_SOUNDID; - } - else if (oldChunk == '?') - { - // Fade randomly over 1 - 3 seconds. - ImFadeParam(oldSound, soundVol, 0, 60 * ((rand() % 3) + 1)); - } - else if (oldChunk == '.') - { - // Fade slowly over 2 seconds. - ImFadeParam(oldSound, soundVol, 0, 120); - } - else if (oldChunk == '!') - { - // Fade over 1 second. - ImFadeParam(oldSound, soundVol, 0, 60); - } - else if (oldChunk == '0') - { - // Do nothing. - } - else if (oldChunk == '1' || (oldMeasure == 0 && newMeasure == 0)) - { - // This is in the original code as a printf - LMUSIC_MSG("oc: %d om: %d ", ImGetParam(oldSound, midiChunk), ImGetParam(oldSound, midiMeasure)); - ImSoundId newSound = ImFindMidi(newTitle); - if (oldSound != newSound) - { - ImStopSound(oldSound); - ImStartSound(newSound, 64); - ImSetHook(oldSound, 0); - LMUSIC_MSG("jhk foulup: old: %d new: %d", oldSound, newSound); - } - else - { - // This will take the next '1' value jump (this is used to break out of loops, etc.). - ImSetHook(oldSound, 1); - LMUSIC_MSG("jump hook 1 set... %d", newCuePoint); - } - } - else // If current pos < X or in a different chunk, jump to Y. - { - ImSoundId newSound = ImFindMidi(newTitle); - if (oldSound != newSound) - { - ImStopSound(oldSound); - ImStartSound(newSound, 64); - ImSetHook(oldSound, 0); - LMUSIC_MSG("Switch files old: 0x%x new: 0x%x", oldSound, newSound); - } - else - { - if (ImGetParam(oldSound, midiChunk) < oldChunk || - (ImGetParam(oldSound, midiChunk) == oldChunk && ImGetParam(oldSound, midiMeasure) < oldMeasure)) - { - LMUSIC_MSG("oc: %d om: %d ", oldChunk, oldMeasure); - LMUSIC_MSG("cc: %d cm: %d ", ImGetParam(oldSound, midiChunk), ImGetParam(oldSound, midiMeasure)); - LMUSIC_MSG("nc: %d nm: %d ", newChunk, newMeasure); - ImJumpMidi(newSound, newChunk, newMeasure, 1, 0, 0); - ImSetHook(oldSound, 0); - } - else - { - TFE_System::logWrite(LOG_WARNING, "Landru Music", "nogo"); - } - } - } - } - else - { - ImSoundId newSound = ImFindMidi(s_sequences[s_curSeq - 1][newCuePoint - 1].name); - ImStartSound(newSound, 64); - s_saveSound = newSound; - } - } - - // Update the cue point. - s_curCuePoint = newCuePoint; - } - ImResume(); - - return s_curCuePoint; - } -} // namespace TFE_DarkForces -#ifdef TFE_ESPBOX -void espbox_shared_lmusic(bool alloc) -{ - ESPBOX_SHARED_ALLOC(TFE_DarkForces::s_sequences, TFE_DarkForces::SEQUENCE_COUNT); -} -#endif diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/lmusic.h b/components/darkforces/tfe/TFE_DarkForces/Landru/lmusic.h deleted file mode 100644 index 25f0664b..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/lmusic.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Landru Sound - the Landru system manages sounds differently than -// the main game. -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include "lsystem.h" - -namespace TFE_DarkForces -{ - void lmusic_init(); - void lmusic_destroy(); - - s32 lmusic_setSequence(s32 newSeq); - s32 lmusic_setCuePoint(s32 newCuePoint); - void lmusic_stop(); - void lmusic_reset(); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/lpalette.cpp b/components/darkforces/tfe/TFE_DarkForces/Landru/lpalette.cpp deleted file mode 100644 index 0c48b6ff..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/lpalette.cpp +++ /dev/null @@ -1,649 +0,0 @@ -#include "lpalette.h" -#include "lsystem.h" -#include "lview.h" -#include -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - // System palettes - static LPalette* s_firstPal = nullptr; - static LPalette* s_workPal = nullptr; - static LPalette* s_screenPal = nullptr; - static LPalette* s_srcPal = nullptr; - static LPalette* s_dstPal = nullptr; - static LPalette* s_videoPal = nullptr; - static JBool s_lpaletteInit = JFALSE; - - void lpalette_setName(LPalette* pal, u32 resType, const char* name); - void lpalette_restoreScreenPal(s16 low, s16 high); - void lpalette_setVideoPal(LPalette* pal, s16 start, s16 length, s16 offset); - void lpalette_setVgaPalette(); - void lpalette_setCycleRange(s16 start, s16 stop, s16 offset); - - void lpalette_init() - { - s_lpaletteInit = JTRUE; - s_firstPal = nullptr; - s_screenPal = lpalette_alloc(0, MAX_COLORS); - s_srcPal = lpalette_alloc(0, MAX_COLORS); - s_dstPal = lpalette_alloc(0, MAX_COLORS); - s_workPal = lpalette_alloc(0, MAX_COLORS); - s_videoPal = lpalette_alloc(0, MAX_COLORS); - lpalette_setRGB(s_videoPal, 0x3f, 0x3f, 0x3f, 0, MAX_COLORS); - } - - void lpalette_destroy() - { - s_lpaletteInit = JFALSE; - lpalette_free(s_screenPal); - lpalette_free(s_srcPal); - lpalette_free(s_dstPal); - lpalette_free(s_workPal); - lpalette_free(s_videoPal); - - s_firstPal = nullptr; - s_workPal = nullptr; - s_screenPal = nullptr; - s_srcPal = nullptr; - s_dstPal = nullptr; - s_videoPal = nullptr; - } - - LPalette* lpalette_getList() - { - return s_firstPal; - } - - void lpalette_add(LPalette* pal) - { - LPalette* curPal = s_firstPal; - LPalette* lastPal = nullptr; - while (curPal) - { - lastPal = curPal; - curPal = curPal->next; - } - - pal->next = curPal; - if (!lastPal) - { - s_firstPal = pal; - } - else - { - lastPal->next = pal; - } - } - - void lpalette_remove(LPalette* pal) - { - if (!pal) { return; } - - LPalette* curPal = s_firstPal; - LPalette* lastPal = nullptr; - - while (curPal && curPal != pal) - { - lastPal = curPal; - curPal = curPal->next; - } - - if (curPal == pal) - { - if (!lastPal) - { - s_firstPal = curPal->next; - } - else - { - lastPal->next = curPal->next; - } - pal->next = nullptr; - } - } - - void lpalette_setRGB(LPalette* pal, s16 r, s16 g, s16 b, s16 start, s16 length) - { - LRGB* rgbList = pal->colors; - for (s32 slot = start; slot < start + length; slot++) - { - if (slot >= pal->start && slot <= pal->end) - { - rgbList[slot - pal->start].r = u8(r); - rgbList[slot - pal->start].g = u8(g); - rgbList[slot - pal->start].b = u8(b); - } - } - } - - LPalette* lpalette_alloc(s16 start, s16 length) - { - if (!length) { return nullptr; } - - LPalette* pal = (LPalette*)landru_alloc(sizeof(LPalette)); - if (!pal) { return nullptr; } - - LRGB* rgb = (LRGB*)landru_alloc(sizeof(LRGB) * length); - if (!rgb) - { - landru_free(pal); - return nullptr; - } - memset(rgb, 0, sizeof(LRGB) * length); - - pal->next = nullptr; - pal->colors = rgb; - pal->start = start; - pal->end = start + length - 1; - pal->len = length; - pal->cycle_count = 0; - pal->cycle_active = 0; - pal->varptr = nullptr; - - return pal; - } - - void lpalette_free(LPalette* pal) - { - if (!pal) { return; } - - lpalette_remove(pal); - if (pal->colors) - { - landru_free(pal->colors); - } - if (pal->varptr) - { - landru_free(pal->varptr); - } - landru_free(pal); - } - - void lpalette_freeList(LPalette* pal) - { - while (pal) - { - LPalette* nextPal = pal->next; - lpalette_remove(pal); - lpalette_free(pal); - pal = nextPal; - } - } - - LPalette* lpalette_load(const char* name) - { - char palName[32]; - sprintf(palName, "%s.PLTT", name); - - FilePath path; - if (!TFE_Paths::getFilePath(palName, &path)) - { - return nullptr; - } - - FileStream file; - if (!file.open(&path, Stream::MODE_READ)) - { - return nullptr; - } - - u32 palSize = (u32)file.getSize(); - u8* data = (u8*)landru_alloc(palSize); - file.readBuffer(data, palSize); - file.close(); - - s32 index = 0; - JBool failed = JFALSE; - - s16 start = data[index]; index++; - s16 stop = data[index]; index++; - s16 count = stop - start + 1; - LPalette* pal = lpalette_alloc(start, count); - if (!pal) - { - landru_free(data); - return nullptr; - } - - LRGB* rgbList = pal->colors; - for (s32 i = 0; i < count; i++) - { - rgbList[i].r = u8(data[index] >> 2); index++; - rgbList[i].g = u8(data[index] >> 2); index++; - rgbList[i].b = u8(data[index] >> 2); index++; - } - - pal->cycle_count = data[index]; index++; - if (pal->cycle_count > MAX_PALETTE_CYCLES) { pal->cycle_count = MAX_PALETTE_CYCLES; } - - if (pal->cycle_count) - { - for (s32 i = 0; i < (s32)pal->cycle_count; i++) - { - pal->cycles[i].rate = data[index]; index++; - pal->cycles[i].rate += data[index] * MAX_COLORS; index++; - pal->cycles[i].rate = (s16)MAX_CYCLE_RATE / pal->cycles[i].rate; - - s16 low = data[index]; index++; - s16 high = data[index]; index++; - - if (low < high) - { - pal->cycles[i].low = u8(low); - pal->cycles[i].high = u8(high); - pal->cycles[i].dir = 1; - } - else - { - pal->cycles[i].low = u8(high); - pal->cycles[i].high = u8(low); - pal->cycles[i].dir = -1; - } - pal->cycles[i].active = 0; - } - } - - lpalette_setName(pal, PALETTE_TYPE, name); - lpalette_add(pal); - - return pal; - } - - void lpalette_startCycle(LPalette* pal) - { - if (!pal->cycle_active) - { - pal->cycle_active = 1; - for (s32 i = 0; i < (s32)pal->cycle_count; i++) - { - pal->cycles[i].active = 1; - pal->cycles[i].current = pal->cycles[i].low; - } - } - } - - void lpalette_stopCycle(LPalette* pal) - { - if (pal->cycle_active) - { - pal->cycle_active = 0; - for (s32 i = 0; i < (s32)pal->cycle_count; i++) - { - pal->cycles[i].active = 0; - pal->cycles[i].current = pal->cycles[i].low; - - s16 low = (s16)pal->cycles[i].low; - s16 high = (s16)pal->cycles[i].high; - lpalette_restoreScreenPal(low, high); - } - } - } - - void lpalette_cycleScreen() - { - u8 active = 0; - LPalette* curPal = s_firstPal; - while (curPal) - { - active |= curPal->cycle_active; - curPal = curPal->next; - } - - s16 min = 256; - s16 max = -1; - - s32 time = lview_getTime(); - if (active) - { - curPal = s_firstPal; - lpalette_copy(s_workPal, s_screenPal, 0, MAX_COLORS, 0); - - while (curPal) - { - if (curPal->cycle_active) - { - for (s32 i = 0; i < (s32)curPal->cycle_count; i++) - { - s16 low = curPal->cycles[i].low; - s16 high = curPal->cycles[i].high; - s16 current = curPal->cycles[i].current; - - if (curPal->cycles[i].rate) - { - if ((time % curPal->cycles[i].rate) == 0) - { - if (curPal->cycles[i].dir < 0) - { - current--; - if (current < low) { current = high; } - } - else // dir > 0 - { - current++; - if (current > high) { current = low; } - } - } - - if (min > low) min = low; - if (max < high) max = high; - lpalette_setCycleRange(low, high, current); - } - } - } - - curPal = curPal->next; - } - - if (min < max) - { - lpalette_setVideoPal(s_workPal, min, max - min + 1, min); - } - } - } - - void lpalette_cyclesToStart() - { - LPalette* curPal = s_firstPal; - while (curPal) - { - if (curPal->cycle_active) - { - for (s32 i = 0; i < (s32)curPal->cycle_count; i++) - { - s16 low = curPal->cycles[i].low; - s16 high = curPal->cycles[i].high; - curPal->cycles[i].current = u8(low); - lpalette_restoreScreenPal(low, high); - } - } - - curPal = curPal->next; - } - } - - void lpalette_stopAllCycles() - { - LPalette* curPal = s_firstPal; - while (curPal) - { - curPal->cycle_active = 0; - for (s32 i = 0; i < (s32)curPal->cycle_count; i++) - { - curPal->cycles[i].active = 0; - } - curPal = curPal->next; - } - - lpalette_restoreScreenPal(0, 255); - } - - JBool lpalette_compare(LPalette* dstPal, LPalette* srcPal, s16 start, s16 length, s16 offset) - { - const LRGB* src = srcPal->colors; - const LRGB* dst = dstPal->colors; - for (s32 srcSlot = start, dstSlot = offset; srcSlot < start + length; srcSlot++, dstSlot++) - { - if (srcSlot >= srcPal->start && srcSlot <= srcPal->end && dstSlot >= dstPal->start && dstSlot <= dstPal->end) - { - if (dst[dstSlot - dstPal->start].r != src[srcSlot - srcPal->start].r || - dst[dstSlot - dstPal->start].g != src[srcSlot - srcPal->start].g || - dst[dstSlot - dstPal->start].b != src[srcSlot - srcPal->start].b) - { - return JFALSE; - } - } - } - return JTRUE; - } - - JBool lpalette_compareSrcDst() - { - return lpalette_compare(s_srcPal, s_dstPal, s_srcPal->start, s_srcPal->len, s_srcPal->start); - } - - void lpalette_copyDstToScreen(s16 offset, s16 start, s16 stop) - { - lpalette_copy(s_screenPal, s_dstPal, start, stop - start + 1, offset); - } - - void lpalette_putScreenPalRange(s16 start, s16 length) - { - lpalette_setVideoPal(s_screenPal, start, length, start); - } - - void lpalette_putScreenPal() - { - lpalette_putScreenPalRange(0, MAX_COLORS); - } - - void lpalette_setScreenPal(LPalette* pal) - { - if (!pal) { return; } - lpalette_setVideoPal(pal, pal->start, pal->len, pal->start); - lpalette_copy(s_screenPal, pal, pal->start, pal->len, pal->start); - } - - void lpalette_setScreenRGB(s16 start, s16 stop, s16 r, s16 g, s16 b) - { - lpalette_setRGB(s_screenPal, r, g, b, start, stop - start + 1); - lpalette_setVideoPal(s_screenPal, start, stop - start + 1, start); - } - - void lpalette_setDstPal(LPalette* pal) - { - lpalette_copy(s_dstPal, pal, pal->start, pal->len, pal->start); - } - - void lpalette_setSrcPal(LPalette* pal) - { - lpalette_copy(s_srcPal, pal, pal->start, pal->len, pal->start); - } - - void lpalette_setDstColor(s16 start, s16 stop, s16 r, s16 g, s16 b) - { - lpalette_setRGB(s_dstPal, r, g, b, start, stop - start + 1); - } - - void lpalette_setCycleRange(s16 start, s16 stop, s16 offset) - { - s16 vstart = start; - s16 vlen = stop - offset + 1; - s16 voff = offset; - lpalette_copy(s_workPal, s_screenPal, vstart, vlen, voff); - - vstart += vlen; - vlen = offset - start; - voff = start; - if (vlen) - { - lpalette_copy(s_workPal, s_screenPal, vstart, vlen, voff); - } - } - - void lpalette_copyScreenToDest(s16 offset, s16 start, s16 stop) - { - lpalette_copy(s_dstPal, s_screenPal, start, stop - start + 1, offset); - } - - void lpalette_copyScreenToSrc(s16 offset, s16 start, s16 stop) - { - lpalette_copy(s_srcPal, s_screenPal, start, stop - start + 1, offset); - } - - void lpalette_copy(LPalette* dstPal, LPalette* srcPal, s16 start, s16 length, s16 offset) - { - LRGB* src = srcPal->colors; - LRGB* dst = dstPal->colors; - - s16 srcSlot, dstSlot, dir; - if (start < offset) - { - srcSlot = start + length - 1; - dstSlot = offset + length - 1; - dir = -1; - } - else - { - srcSlot = start; - dstSlot = offset; - dir = 1; - } - - while (srcSlot >= start && srcSlot < srcSlot + length) - { - if (srcSlot >= srcPal->start && srcSlot <= srcPal->end && - dstSlot >= dstPal->start && dstSlot <= dstPal->end) - { - dst[dstSlot - dstPal->start] = src[srcSlot - srcPal->start]; - } - - srcSlot += dir; - dstSlot += dir; - } - } - - void lpalette_restoreScreenPal(s16 start, s16 stop) - { - lpalette_setVideoPal(s_screenPal, start, stop - start + 1, start); - } - - void lpalette_setVideoPal(LPalette* pal, s16 start, s16 length, s16 offset) - { - LRGB* videoList = s_videoPal->colors; - LRGB* rgbList = pal->colors; - - s16 palStart = pal->start; - s16 palEnd = pal->end; - LRGB* setList = nullptr; - s16 setFirst = 0; - s16 count = 0; - - for (s32 slot = start, vidSlot = offset; slot < start + length; slot++, vidSlot++) - { - if (slot >= palStart && slot <= palEnd) - { - // Always set it - videoList[vidSlot].r = rgbList[slot - palStart].r; - videoList[vidSlot].g = rgbList[slot - palStart].g; - videoList[vidSlot].b = rgbList[slot - palStart].b; - count++; - } - } - - if (count) - { - lpalette_setVgaPalette(); - } - } - - void lpalette_buildPaletteToPalette(s16 start, s16 stop, s16 step) - { - LRGB* src1 = s_srcPal->colors; - LRGB* src2 = s_dstPal->colors; - LRGB* dst = s_screenPal->colors; - - for (s32 slot = start; slot <= stop; slot++) - { - s32 r = s32(src2[slot].r) - s32(src1[slot].r); - s32 g = s32(src2[slot].g) - s32(src1[slot].g); - s32 b = s32(src2[slot].b) - s32(src1[slot].b); - - r = (r * step) / 256; - g = (g * step) / 256; - b = (b * step) / 256; - - dst[slot].r = u8(src1[slot].r + r); - dst[slot].g = u8(src1[slot].g + g); - dst[slot].b = u8(src1[slot].b + b); - } - } - - void lpalette_buildPaletteToMono(s16 start, s16 stop, s16 step, s16 fr, s16 fg, s16 fb) - { - LRGB* src = s_srcPal->colors; - LRGB* dst = s_screenPal->colors; - - for (s32 slot = start; slot <= stop; slot++) - { - s32 r = s32(fr) - s32(src[slot].r); - s32 g = s32(fg) - s32(src[slot].g); - s32 b = s32(fb) - s32(src[slot].b); - - r = (r * step) / 256; - g = (g * step) / 256; - b = (b * step) / 256; - - dst[slot].r = u8(s32(src[slot].r) + r); - dst[slot].g = u8(s32(src[slot].g) + g); - dst[slot].b = u8(s32(src[slot].b) + b); - } - } - - void lpalette_buildMonoToPalette(s16 start, s16 stop, s16 step, s16 fr, s16 fg, s16 fb) - { - LRGB* src = s_dstPal->colors; - LRGB* dst = s_screenPal->colors; - - for (s32 slot = start; slot <= stop; slot++) - { - s32 r = s32(src[slot].r) - s32(fr); - s32 g = s32(src[slot].g) - s32(fg); - s32 b = s32(src[slot].b) - s32(fb); - - r = (r * step) / 256; - g = (g * step) / 256; - b = (b * step) / 256; - - dst[slot].r = u8(s32(fr) + r); - dst[slot].g = u8(s32(fg) + g); - dst[slot].b = u8(s32(fb) + b); - } - } - - void lpalette_buildFadePalette(s16 type, s16 start, s16 stop, s16 step, s16 fr, s16 fg, s16 fb) - { - switch (type) - { - case LPAL_BUILD_PALETTE: - lpalette_buildPaletteToPalette(start, stop, step); - break; - case LPAL_BUILD_MONOSRC: - lpalette_buildMonoToPalette(start, stop, step, fr, fg, fb); - break; - case LPAL_BUILD_MONODEST: - lpalette_buildPaletteToMono(start, stop, step, fr, fg, fb); - break; - } - } - -#define _CONV_6bitTo8bit(x) (((x)<<2) | ((x)>>4)) - - void lpalette_setVgaPalette() - { - u32 palette[256]; - u32* outColor = palette; - LRGB* srcColor = s_videoPal->colors; - for (s32 i = 0; i < 256; i++, outColor++, srcColor++) - { - *outColor = _CONV_6bitTo8bit(srcColor->r) | (_CONV_6bitTo8bit(srcColor->g) << 8u) | (_CONV_6bitTo8bit(srcColor->b) << 16u) | (0xffu << 24u); - } - vfb_setPalette(palette); -#ifndef TFE_ESPBOX - vfb_setPalette(palette); -#endif - } - - void lpalette_setName(LPalette* pal, u32 resType, const char* name) - { - pal->resType = resType; - strcpy(pal->name, name); - __strlwr(pal->name); - } -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/lpalette.h b/components/darkforces/tfe/TFE_DarkForces/Landru/lpalette.h deleted file mode 100644 index 6d3fcce5..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/lpalette.h +++ /dev/null @@ -1,93 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Landru Palette -////////////////////////////////////////////////////////////////////// -#include -#include "lrect.h" - -namespace TFE_DarkForces -{ - struct LRGB - { - u8 r, g, b; - }; - - struct Cycle - { - s16 dir; - s16 rate; - u8 active; - u8 current; - u8 low; - u8 high; - }; - - enum LPaletteConstants : u32 - { - PALETTE_TYPE = 0x504c5454, // 'PLTT' - MAX_PALETTE_CYCLES = 4, - MAX_CYCLE_RATE = 4915, - MAX_COLORS = 256, - PALETTE_KEEPABLE = 0x0040, - PALETTE_KEEP = 0x0080, - - LPAL_BUILD_PALETTE = 0, - LPAL_BUILD_MONOSRC = 1, - LPAL_BUILD_MONODEST = 2, - }; - - struct LPalette - { - u32 resType; - char name[16]; - LPalette* next; - - LRGB* colors; - - Cycle cycles[MAX_PALETTE_CYCLES]; - u8 cycle_count; - u8 cycle_active; - - s16 start; - s16 end; - s16 len; - - u16 flags; - u8* varptr; - }; - - void lpalette_init(); - void lpalette_destroy(); - - LPalette* lpalette_load(const char* name); - LPalette* lpalette_alloc(s16 start, s16 length); - void lpalette_free(LPalette* pal); - void lpalette_freeList(LPalette* pal); - - LPalette* lpalette_getList(); - void lpalette_add(LPalette* pal); - void lpalette_remove(LPalette* pal); - void lpalette_copy(LPalette* dst, LPalette* src, s16 start, s16 length, s16 offset); - void lpalette_copyScreenToDest(s16 offset, s16 start, s16 stop); - void lpalette_copyScreenToSrc(s16 offset, s16 start, s16 stop); - void lpalette_copyDstToScreen(s16 offset, s16 start, s16 stop); - - JBool lpalette_compare(LPalette* dstPal, LPalette* srcPal, s16 start, s16 length, s16 offset); - JBool lpalette_compareSrcDst(); - - void lpalette_setRGB(LPalette* pal, s16 r, s16 g, s16 b, s16 start, s16 length); - void lpalette_putScreenPalRange(s16 start, s16 length); - void lpalette_putScreenPal(); - - void lpalette_cycleScreen(); - void lpalette_cyclesToStart(); - void lpalette_stopAllCycles(); - void lpalette_setScreenPal(LPalette* pal); - void lpalette_setScreenRGB(s16 start, s16 stop, s16 r, s16 g, s16 b); - void lpalette_setDstPal(LPalette* pal); - void lpalette_setSrcPal(LPalette* pal); - void lpalette_setDstColor(s16 start, s16 stop, s16 r, s16 g, s16 b); - - void lpalette_buildFadePalette(s16 type, s16 start, s16 stop, s16 step, s16 fr, s16 fg, s16 fb); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/lrect.cpp b/components/darkforces/tfe/TFE_DarkForces/Landru/lrect.cpp deleted file mode 100644 index 0c23ee51..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/lrect.cpp +++ /dev/null @@ -1,201 +0,0 @@ -#include "lrect.h" -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - void lrect_clear(LRect* rect) - { - rect->left = 0; - rect->top = 0; - rect->right = 0; - rect->bottom = 0; - } - - void lrect_set(LRect* rect, s16 left, s16 top, s16 right, s16 bottom) - { - rect->left = left; - rect->top = top; - rect->right = right; - rect->bottom = bottom; - } - - void lrect_setMax(LRect* rect) - { - rect->left = -32767; - rect->top = -32767; - rect->right = 32767; - rect->bottom = 32767; - } - - JBool lrect_equal(LRect* r1, LRect* r2) - { - s16 notEqual = 0; - notEqual |= (r1->left != r2->left); - notEqual |= (r1->top != r2->top); - notEqual |= (r1->right != r2->right); - notEqual |= (r1->bottom != r2->bottom); - - return notEqual ? JFALSE : JTRUE; - } - - void lrect_offset(LRect* rect, s16 dx, s16 dy) - { - rect->left += dx; - rect->right += dx; - rect->top += dy; - rect->bottom += dy; - } - - void lrect_origin(LRect* rect) - { - lrect_offset(rect, -rect->left, -rect->top); - } - - // Align rect relative to its 'parent'. - void lrect_align(LRect* rect, LRect* parent, LAlignType xAlign, LAlignType yAlign) - { - switch (xAlign) - { - case LORIGIN: - { - rect->left += parent->left; - rect->right += parent->left; - } break; - case LCENTER: - { - s16 temp = (parent->right - parent->left) - (rect->right - rect->left); - temp = (temp >> 1) + parent->left; - - rect->left += temp; - rect->right += temp; - } break; - case LEXTENT: - { - s16 temp = rect->left; - rect->left = parent->right - rect->right; - rect->right = parent->right - temp; - } break; - default: - { - assert(0); - } - } - - switch (yAlign) - { - case LORIGIN: - { - rect->top += parent->top; - rect->bottom += parent->top; - } break; - case LCENTER: - { - s16 temp = (parent->bottom - parent->top) - (rect->bottom - rect->top); - temp = (temp >> 1) + parent->top; - - rect->top += temp; - rect->bottom += temp; - } break; - case LEXTENT: - { - s16 temp = rect->top; - rect->top = parent->bottom - rect->bottom; - rect->bottom = parent->bottom - temp; - } break; - default: - { - assert(0); - } - } - } - - // Flips within the parent. - void lrect_flip(LRect* rect, LRect* parent, JBool xFlip, JBool yFlip) - { - if (xFlip) - { - s16 x0 = (parent->right - rect->right) + parent->left; - s16 x1 = x0 + (rect->right - rect->left); - rect->left = x0; - rect->right = x1; - } - if (yFlip) - { - s16 y0 = (parent->bottom - rect->bottom) + parent->top; - s16 y1 = y0 + (rect->bottom - rect->top); - rect->top = y0; - rect->bottom = y1; - } - } - - void lrect_inset(LRect* rect, s16 dx, s16 dy) - { - rect->left += dx; - rect->right -= dx; - rect->top += dy; - rect->bottom -= dy; - } - - JBool lrect_isEmpty(LRect* rect) - { - if (rect->left >= rect->right) { return JTRUE; } - if (rect->top >= rect->bottom) { return JTRUE; } - return JFALSE; - } - - JBool lrect_intersect(LRect* r1, LRect* r2) - { - if (lrect_isEmpty(r1) || lrect_isEmpty(r2)) { return JFALSE; } - - if (r1->right <= r2->left) { return JFALSE; } - if (r1->left >= r2->right) { return JFALSE; } - if (r1->bottom <= r2->top) { return JFALSE; } - if (r1->top >= r2->bottom) { return JFALSE; } - - return JTRUE; - } - - void lrect_enclose(LRect* r1, LRect* r2) - { - if (lrect_isEmpty(r1)) - { - *r1 = *r2; - } - else if (!lrect_isEmpty(r2)) - { - if (r1->left > r2->left) { r1->left = r2->left; } - if (r1->right < r2->right) { r1->right = r2->right; } - if (r1->top > r2->top) { r1->top = r2->top; } - if (r1->bottom < r2->bottom) { r1->bottom = r2->bottom; } - } - } - - JBool lrect_clip(LRect* r1, LRect* r2) - { - if (r1->left < r2->left) { r1->left = r2->left; } - if (r1->right > r2->right) { r1->right = r2->right; } - if (r1->top < r2->top) { r1->top = r2->top; } - if (r1->bottom > r2->bottom) { r1->bottom = r2->bottom; } - - if (r1->left > r1->right) { r1->right = r1->left; } - if (r1->top > r1->bottom) { r1->bottom = r1->top; } - - return (r1->left < r1->right && r1->top < r1->bottom) ? JTRUE : JFALSE; - } - - void lrect_clipPoint(LRect* rect, s16* x, s16* y) - { - *x = s16(clamp(s32(*x), s32(rect->left), s32(rect->right))); - *y = s16(clamp(s32(*y), s32(rect->top), s32(rect->bottom))); - } - - JBool lrect_isPointInside(LRect* rect, s16 x, s16 y) - { - if (x < rect->left || x >= rect->right) { return JFALSE; } - if (y < rect->top || y >= rect->bottom) { return JFALSE; } - return JTRUE; - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/lrect.h b/components/darkforces/tfe/TFE_DarkForces/Landru/lrect.h deleted file mode 100644 index b557065d..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/lrect.h +++ /dev/null @@ -1,43 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Landru Actor -// Landru was the cutscene system developed for XWing and Tie Fighter -// and is also used in Dark Forces. -////////////////////////////////////////////////////////////////////// -#include - -namespace TFE_DarkForces -{ - enum LAlignType - { - LORIGIN = 0, - LCENTER, - LEXTENT - }; - - struct LRect - { - s16 top; - s16 left; - s16 bottom; - s16 right; - }; - - void lrect_clear(LRect* rect); - void lrect_set(LRect* rect, s16 left, s16 top, s16 right, s16 bottom); - void lrect_setMax(LRect* rect); - void lrect_offset(LRect* rect, s16 dx, s16 dy); - void lrect_origin(LRect* rect); - void lrect_align(LRect* rect, LRect* parent, LAlignType xAlign, LAlignType yAlign); - void lrect_flip(LRect* rect, LRect* parent, JBool xFlip, JBool yFlip); - void lrect_inset(LRect* rect, s16 dx, s16 dy); - void lrect_enclose(LRect* r1, LRect* r2); - void lrect_clipPoint(LRect* rect, s16* x, s16* y); - - JBool lrect_equal(LRect* r1, LRect* r2); - JBool lrect_isEmpty(LRect* rect); - JBool lrect_intersect(LRect* r1, LRect* r2); - JBool lrect_clip(LRect* r1, LRect* r2); - JBool lrect_isPointInside(LRect* rect, s16 x, s16 y); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/lsound.cpp b/components/darkforces/tfe/TFE_DarkForces/Landru/lsound.cpp deleted file mode 100644 index 62974599..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/lsound.cpp +++ /dev/null @@ -1,367 +0,0 @@ -#include - -#include "lsound.h" -#include -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - #define DEFAULT_PRIORITY 64 - static LSound* s_soundList = nullptr; - - void purgeAllSounds(); - void freeSoundList(LSound* sound); - void initSound(LSound* sound); - - ///////////////////////////////////////////////////////// - // System - ///////////////////////////////////////////////////////// - void lSoundInit() - { - s_soundList = nullptr; - } - - void lSoundDestroy() - { - purgeAllSounds(); - } - - LSound* lSoundGetList() - { - return s_soundList; - } - - LSound* lSoundAlloc(u8* data) - { - LSound* sound = (LSound*)game_alloc(sizeof(LSound)); - if (sound) - { - initSound(sound); - sound->data = data; - - // Add the sound to the head of the list. - if (s_soundList) - { - sound->next = s_soundList; - } - s_soundList = sound; - } - return sound; - } - - LSound* lSoundLoad(const char* name, LSoundType soundType) - { - // Read the data from the file. - u8* data = readVocFileData(name); - - // Then allocate the sound itself. - LSound* sound = lSoundAlloc(data); - setSoundName(sound, soundType, name); - discardSoundData(sound); - sound->type = soundType; - - return sound; - } - - void lSoundFree(LSound* sound) - { - if (!sound) { return; } - lSoundFreePlaying(sound, JTRUE); - } - - void lSoundFreePlaying(LSound* sound, JBool stop) - { - if (isSoundKeep(sound) || isSoundKeepable(sound)) - { - clearSoundKeep(sound); - } - else - { - LSound* curSound = s_soundList; - LSound* lastSound = nullptr; - - while (curSound && curSound != sound) - { - lastSound = curSound; - curSound = curSound->next; - } - - if (curSound == sound) - { - if (lastSound) - { - lastSound->next = sound->next; - } - else - { - s_soundList = sound->next; - } - } - - if (stop) - { - stopSound(sound); - } - - if (isDiscardSoundData(sound) && sound->data) - { - game_free(sound->data); - sound->data = nullptr; - } - if (sound->varptr) - { - game_free(sound->varptr); - sound->varptr = nullptr; - } - if (sound->varhdl) - { - game_free(sound->varhdl); - sound->varhdl = nullptr; - } - game_free(sound); - } - } - - ///////////////////////////////////////////////////////// - // Game Sound <-> iMuse interface. - ///////////////////////////////////////////////////////// - void startSfx(LSound* sound) - { - TFE_A11Y::onSoundPlay(sound->name, TFE_A11Y::CaptionEnv::CC_Cutscene); - ImStartSfx((ImSoundId)sound, DEFAULT_PRIORITY); - } - - void startSpeech(LSound* sound) - { - TFE_A11Y::onSoundPlay(sound->name, TFE_A11Y::CaptionEnv::CC_Cutscene); - ImStartVoice((ImSoundId)sound, DEFAULT_PRIORITY); - } - - void stopSound(LSound* sound) - { - ImStopSound((ImSoundId)sound); - } - - void setSoundVolume(LSound* sound, s32 volume) - { - ImSetParam((ImSoundId)sound, soundVol, volume); - } - - void setSoundFade(LSound* sound, s32 volume, s32 time) - { - ImFadeParam((ImSoundId)sound, soundVol, volume, time); - } - - void setSoundPan(LSound* sound, s32 pan) - { - ImSetParam((ImSoundId)sound, soundPan, pan); - } - - void setSoundPanFade(LSound* sound, s32 pan, s32 time) - { - ImFadeParam((ImSoundId)sound, soundPan, pan, time); - } - - ///////////////////////////////////////////////////////// - // Game Sound General Interface - ///////////////////////////////////////////////////////// - void copySoundData(LSound* dstSound, LSound* srcSound) - { - if (isDiscardSoundData(dstSound) && dstSound->data) - { - game_free(dstSound->data); - } - nonDiscardSoundData(dstSound); - setSoundName(dstSound, srcSound->resType, srcSound->name); - dstSound->data = srcSound->data; - dstSound->id = srcSound->id; - dstSound->type = srcSound->type; - } - - LSound* findSoundType(const char* name, u32 type) - { - LSound* sound = s_soundList; - s32 found = 0; - while (sound && !found) - { - if (type == sound->resType) - { - found = 1; - s32 i = 0; - for (; i < LS_NAME_LEN && found && name[i]; i++) - { - found = (sound->name[i] == tolower(name[i])); - } - if (found && i < LS_NAME_LEN && sound->name[i]) { found = 0; } - } - - if (!found) - { - sound = sound->next; - } - } - return sound; - } - - void discardSoundData(LSound* sound) - { - sound->flags |= LS_SOUND_DISCARD; - } - - void nonDiscardSoundData(LSound* sound) - { - sound->flags &= ~LS_SOUND_DISCARD; - } - - JBool isDiscardSoundData(LSound* sound) - { - return sound->flags & LS_SOUND_DISCARD; - } - - void setSoundKeep(LSound* sound) - { - sound->flags |= LS_SOUND_KEEP; - } - - void clearSoundKeep(LSound* sound) - { - sound->flags &= ~LS_SOUND_KEEP; - } - - JBool isSoundKeep(LSound* sound) - { - return sound->flags & LS_SOUND_KEEP; - } - - void setSoundKeepable(LSound* sound) - { - sound->flags |= LS_SOUND_KEEPABLE; - } - - void clearSoundKeepable(LSound* sound) - { - sound->flags &= ~LS_SOUND_KEEPABLE; - } - - JBool isSoundKeepable(LSound* sound) - { - return sound->flags & LS_SOUND_KEEPABLE; - } - - void setSoundName(LSound* sound, u32 type, const char* name) - { - sound->resType = type; - - s32 i = 0; - for (; i < LS_NAME_LEN && name[i]; i++) - { - sound->name[i] = tolower(name[i]); - } - while (i < LS_NAME_LEN) - { - sound->name[i] = 0; - i++; - } - } - - void freeSoundList(LSound* sound) - { - while (sound) - { - LSound* next = sound->next; - lSoundFree(sound); - sound = next; - } - } - -#ifdef TFE_ESPBOX - JBool vocFileExists(const char* name) - { - FilePath path; - if (strstr(name, ".voc") || strstr(name, ".VOC")) - { - return TFE_Paths::getFilePath(name, &path) ? JTRUE : JFALSE; - } - char fileName[TFE_MAX_PATH]; - sprintf(fileName, "%s.VOIC", name); - if (TFE_Paths::getFilePath(fileName, &path)) { return JTRUE; } - sprintf(fileName, "%s.VOC", name); - return TFE_Paths::getFilePath(fileName, &path) ? JTRUE : JFALSE; - } -#endif - - u8* readVocFileData(const char* name, u32* sizeOut) - { - FilePath path; - if (strstr(name, ".voc") || strstr(name, ".VOC")) - { - if (!TFE_Paths::getFilePath(name, &path)) - { - return nullptr; - } - } - else - { - char fileName[TFE_MAX_PATH]; - sprintf(fileName, "%s.VOIC", name); // Prefer the version of a sound from the LFD. - if (!TFE_Paths::getFilePath(fileName, &path)) - { - sprintf(fileName, "%s.VOC", name); - if (!TFE_Paths::getFilePath(fileName, &path)) - { - return nullptr; - } - } - } - FileStream file; - if (!file.open(&path, Stream::MODE_READ)) - { - return nullptr; - } - u32 size = (u32)file.getSize(); - u8* data = (u8*)game_alloc(size); - if (!data) - { - return nullptr; - } - file.readBuffer(data, size); - file.close(); - - if (sizeOut) - { - *sizeOut = size; - } - - return data; - } - - ///////////////////////////////////////////////////////// - // System Internal - ///////////////////////////////////////////////////////// - void purgeAllSounds() - { - LSound* sound = s_soundList; - - while (sound) - { - clearSoundKeep(sound); - clearSoundKeepable(sound); - sound = sound->next; - } - - freeSoundList(s_soundList); - s_soundList = nullptr; - } - - void initSound(LSound* sound) - { - memset(sound, 0, sizeof(LSound)); - sound->volume = 128; - } -} // TFE_JediSound \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/lsound.h b/components/darkforces/tfe/TFE_DarkForces/Landru/lsound.h deleted file mode 100644 index d2d6f4a7..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/lsound.h +++ /dev/null @@ -1,99 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Jedi Sound System -// Derived from the DOS Dark Forces code. -// This system uses the TFE Framework low level sound system to -// actually manage sounds, but this system is used as a front end to -// ensure the behavior matches the original game. -////////////////////////////////////////////////////////////////////// -#include -#include - -enum LSoundConst -{ - LS_NAME_LEN = 8, // Sound name length - LS_MAX_SOUNDS = 48, // Maximum number of sounds -}; - -enum LSoundFlags -{ - LS_SOUND_FREE = 0x0001, // Free the sound after user function - LS_SOUND_DISCARD = 0x0002, // Sound data is discardable - LS_SOUND_KEEP_USER = 0x0004, // Don't NULL user function - LS_SOUND_KEEP = 0x1000, // Keep the sound for one free - LS_SOUND_KEEPABLE = 0x2000, // Keep the sound - LS_SOUND_USER_FLAG1 = 0x4000, // User flag 1 - LS_SOUND_USER_FLAG2 = 0x8000, // User flag 2 -}; - -// In practice, only digitalSound is used but I'm keeping the code the same for now. -enum LSoundType -{ - noSound = 0, - gmidiSound, - digitalSound -}; - -// Structure padding matters due to the hacky way iMuse gets at the sound data, -// so I promoted 16-bit members to 32-bit to simplify. -struct LSound -{ - u32 resType; - char name[LS_NAME_LEN]; - - LSound* next; - LSoundType type; - s32 id; - - s32 flags; - s32 volume; - - s32 var1; - s32 var2; - u8* varptr; - u8* varhdl; - - u8* data; -}; - -namespace TFE_DarkForces -{ - // System - void lSoundInit(); - void lSoundDestroy(); - LSound* lSoundGetList(); - LSound* lSoundAlloc(u8* data); - LSound* lSoundLoad(const char* name, LSoundType soundType); - void lSoundFree(LSound* sound); - void lSoundFreePlaying(LSound* sound, JBool stop); - void freeSoundList(LSound* sound); - - // Landru Sound <-> iMuse interface. - void startSfx(LSound* sound); - void startSpeech(LSound* sound); - void stopSound(LSound* sound); - void setSoundVolume(LSound* sound, s32 volume); - void setSoundFade(LSound* sound, s32 volume, s32 time); - void setSoundPan(LSound* sound, s32 pan); - void setSoundPanFade(LSound* sound, s32 pan, s32 time); - - // Landru Sound only. - void copySoundData(LSound* dstSound, LSound* srcSound); - LSound* findSoundType(const char* name, u32 type); - void discardSoundData(LSound* sound); - void nonDiscardSoundData(LSound* sound); - JBool isDiscardSoundData(LSound* sound); - void setSoundKeep(LSound* sound); - void clearSoundKeep(LSound* sound); - JBool isSoundKeep(LSound* sound); - void setSoundKeepable(LSound* sound); - void clearSoundKeepable(LSound* sound); - JBool isSoundKeepable(LSound* sound); - void setSoundName(LSound* sound, u32 type, const char* name); - - u8* readVocFileData(const char* name, u32* size = nullptr); -#ifdef TFE_ESPBOX - // True if readVocFileData() would find the sound (without reading it). - JBool vocFileExists(const char* name); -#endif -} // namespace TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/lsystem.cpp b/components/darkforces/tfe/TFE_DarkForces/Landru/lsystem.cpp deleted file mode 100644 index dcfc2b09..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/lsystem.cpp +++ /dev/null @@ -1,144 +0,0 @@ -#include "lsystem.h" -#include "lactor.h" -#include "lactorAnim.h" -#include "lactorCust.h" -#include "lactorDelt.h" -#include "lcanvas.h" -#include "lfade.h" -#include "lfont.h" -#include "lmusic.h" -#include "ltimer.h" -#include "lpalette.h" -#include "lsound.h" -#include "lview.h" -#include "ldraw.h" -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - static JBool s_lsystemInit = JFALSE; - static LfdArchive s_archive = {}; - static LfdArchive s_soundFx = {}; - static MemoryRegion* s_lmem = nullptr; - static MemoryRegion* s_lscene = nullptr; - MemoryRegion* s_alloc = nullptr; - - enum LandruConstants - { - LANDRU_MEMORY_BASE = 4 * 1024 * 1024, // 4 MB - CUTSCENE_MEMORY_BASE = 8 * 1024 * 1024, // 8 MB - }; - - void lsystem_init() - { - if (s_lsystemInit) { return; } - s_lmem = TFE_Memory::region_create("Landru", LANDRU_MEMORY_BASE); - s_lscene = TFE_Memory::region_create("Cutscene", CUTSCENE_MEMORY_BASE); - lsystem_setAllocator(LALLOC_PERSISTENT); - - s_lsystemInit = JTRUE; - lcanvas_init(320, 200); - ltime_init(); - lview_init(); - lpalette_init(); - lfade_init(); - lfont_init(); - lmusic_init(); - lSoundInit(); - - lactor_init(); - lactorDelt_init(); - lactorAnim_init(); - lactorCust_init(); - - FilePath lfdPath; - if (TFE_Paths::getFilePath("menu.lfd", &lfdPath)) - { - s_archive.open(lfdPath.path); - TFE_Paths::addLocalArchive(&s_archive); - - // Default font used by in-game UI. - lfont_load("font8", 0); - lfont_set(0); - - s_archive.close(); - TFE_Paths::removeLastArchive(); - } - - FilePath sfxPath; - if (TFE_Paths::getFilePath("jedisfx.lfd", &sfxPath)) - { - s_soundFx.open(sfxPath.path); - TFE_Paths::addLocalArchive(&s_soundFx); - } - } - - void lsystem_destroy() - { - if (!s_lsystemInit) { return; } - vfb_forceToBlack(); - - s_lsystemInit = JFALSE; -#ifdef TFE_ESPBOX - // The sound effects archive is a static that is never destructed; close it - // so its file handle and stdio buffer are released on shutdown. (The local - // archive list that references it is cleared by exitGame() afterwards.) - s_soundFx.close(); -#endif - lcanvas_destroy(); - lview_destroy(); - lpalette_destroy(); - lfade_destroy(); - lfont_destroy(); - lmusic_destroy(); - lSoundDestroy(); - - lactorCust_destroy(); - lactorAnim_destroy(); - lactorDelt_destroy(); - lactor_destroy(); - - TFE_Memory::region_destroy(s_lmem); - TFE_Memory::region_destroy(s_lscene); - } - - void lsystem_setAllocator(LAllocator alloc) - { - s_alloc = (alloc == LALLOC_PERSISTENT) ? s_lmem : s_lscene; - } - - void lsystem_clearAllocator(LAllocator alloc) - { - MemoryRegion* region = (alloc == LALLOC_PERSISTENT) ? s_lmem : s_lscene; -#ifdef TFE_ESPBOX - // Debug: actors still linked in the actor list whose memory is about to be - // released with this region (they would then be drawn from freed memory). - { - s32 stale = 0; - for (LActor* actor = lactor_getList(); actor; actor = actor->next) - { - if (TFE_Memory::region_contains(region, actor)) - { - if (stale < 8) - { - printf("[DarkForces] actor '%s' (id %d) still listed while its region '%s' is cleared\n", - actor->name, (int)actor->id, alloc == LALLOC_PERSISTENT ? "Landru" : "Cutscene"); - } - stale++; - } - } - if (stale) { printf("[DarkForces] %d stale actors at region clear\n", (int)stale); } - } -#endif - TFE_Memory::region_clear(region); - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/lsystem.h b/components/darkforces/tfe/TFE_DarkForces/Landru/lsystem.h deleted file mode 100644 index 5aab9e1f..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/lsystem.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Landru system, setup and teardown. -////////////////////////////////////////////////////////////////////// -#include -#include "lrect.h" - -#define landru_alloc(size) TFE_Memory::region_alloc(s_alloc, size) -#define landru_realloc(ptr, size) TFE_Memory::region_realloc(s_alloc, ptr, size) -#define landru_free(ptr) TFE_Memory::region_free(s_alloc, ptr) -struct MemoryRegion; - -enum LAllocator -{ - LALLOC_PERSISTENT = 0, - LALLOC_CUTSCENE, -}; - -namespace TFE_DarkForces -{ - void lsystem_init(); - void lsystem_destroy(); - - void lsystem_setAllocator(LAllocator alloc); - void lsystem_clearAllocator(LAllocator alloc); - - extern MemoryRegion* s_alloc; -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/ltimer.cpp b/components/darkforces/tfe/TFE_DarkForces/Landru/ltimer.cpp deleted file mode 100644 index 736b2733..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/ltimer.cpp +++ /dev/null @@ -1,90 +0,0 @@ -#include "ltimer.h" -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - static f64 s_timeInSec = 0.0; - static LTick s_curTick = 0; - static LTick s_lastTick = 0; - static s32 s_frameDelay = 20; // 12 frames per second - - static LTick s_prevAccum = 0; - static LTick s_lastAccum = 0; - - static f64 s_prevTime = 0.0f; - - // This takes the place of the timer interrupt and should be called every frame. - void tfe_updateLTime() - { - f64 curTime = TFE_System::getTime(); - s_timeInSec += s_prevTime ? (curTime - s_prevTime) : 0.0; - s_prevTime = curTime; - - // Convert from seconds to ticks. - f64 curTick = f64(LTICKS_PER_SECOND) * s_timeInSec * TFE_System::c_gameTimeScale; - s_curTick = LTick(curTick); - } - - void ltime_init() - { - s_prevTime = 0.0; - s_timeInSec = 0.0; - s_curTick = 0; - s_lastTick = 0; - s_frameDelay = 20; - - s_prevAccum = 0; - s_lastAccum = 0; - } - - void ltime_setFrameDelay(u16 delay) - { - s_frameDelay = delay; - } - - u16 ltime_getDelay() - { - return s_frameDelay; - } - - LTick ltime_curTick() - { - return s_curTick; - } - - LTick ltime_elapsed() - { - if (s_lastTick == 0) { s_lastTick = s_curTick; } - LTick dt = s_curTick - s_lastTick; - s_lastTick = s_curTick; - - return dt; - } - - JBool ltime_checkTimeElapsed() - { - s_lastAccum += ltime_elapsed(); - if (s_lastAccum >= (LTick)s_frameDelay) - { - return JFALSE; - } - return JTRUE; - } - - // returns JTRUE if the frame is ready. - // This is implemented instead of the DOS while loop. - JBool ltime_isFrameReady() - { - if (!ltime_checkTimeElapsed()) - { - s_prevAccum = s_lastAccum; - s_lastAccum = 0; - return JTRUE; - } - return JFALSE; - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/ltimer.h b/components/darkforces/tfe/TFE_DarkForces/Landru/ltimer.h deleted file mode 100644 index f5852c70..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/ltimer.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Landru Timer -// Timer used for updating Landru loops. -////////////////////////////////////////////////////////////////////// -#include - -namespace TFE_DarkForces -{ - #define LTICKS_PER_SECOND (1193182.0/4096.0) - typedef u32 LTick; // Landru tick = 291.3 / second. - - // TFE Specific - this replaces the timer interrupt. - void tfe_updateLTime(); - - // Landru timer API. - void ltime_init(); - void ltime_setFrameDelay(u16 delay); - u16 ltime_getDelay(); - LTick ltime_elapsed(); - JBool ltime_checkTimeElapsed(); - LTick ltime_curTick(); - - // This is also altered from DOS to return JTRUE when the frame is ready instead of - // looping. - JBool ltime_isFrameReady(); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/lview.cpp b/components/darkforces/tfe/TFE_DarkForces/Landru/lview.cpp deleted file mode 100644 index 92ec61ee..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/lview.cpp +++ /dev/null @@ -1,519 +0,0 @@ -#include "lview.h" -#include "lactor.h" -#include "lcanvas.h" -#include "lpalette.h" -#include "lsystem.h" -#include "lfade.h" -#include "cutscene_film.h" -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - LView* s_view = nullptr; - JBool s_lviewInit = JFALSE; - JBool s_updateView = JTRUE; - static LView* s_defaultView = nullptr; - static JBool s_running = JFALSE; - static s32 s_exitValue = VIEW_LOOP_RUNNING; - - void lview_freeData(LView* view); - void lview_initView(LView* view); - void lview_trackView(s16 viewIndex, s16 snap); - void lview_update(s32 time); - void lview_updateCallback(s32 time); - - void lview_init() - { - s_defaultView = lview_alloc(); - if (s_defaultView) - { - s_lviewInit = JTRUE; - lview_initView(s_defaultView); - - s_defaultView->coords = 0; - s_defaultView->frameCount = 0; - lview_setCurrent(s_defaultView); - } - s_updateView = JTRUE; - } - - void lview_destroy() - { - if (s_defaultView) - { - lview_free(s_defaultView); - s_defaultView = nullptr; - } - s_lviewInit = JFALSE; - } - - void lview_initView(LView* view) - { - for (s32 i = 0; i < LVIEW_COUNT; i++) - { - if (i == 0) - { - lcanvas_getBounds(&view->frame[i]); - view->zStart[i] = -32000; - view->zStop[i] = 32000; - } - else - { - lrect_clear(&view->frame[i]); - view->zStart[i] = -32767; - view->zStop[i] = 32767; - } - - view->xRel[i] = 0; - view->yRel[i] = 0; - view->xVel[i] = 0; - view->yVel[i] = 0; - view->trackActor[i] = nullptr; - view->trackActive[i] = 0; - view->clearView[i] = LVIEW_FLAG_CLEAR | LVIEW_FLAG_COPY; - } - lcanvas_getBounds(&view->clipFrame); - - view->time = 0; - view->refreshWorld = 0; - view->clear = 1; - - view->step = 0; - view->stepCount = 0; - view->updateFunc = nullptr; - } - - void lview_clear() - { - if (s_view->clear) - { - lcanvas_eraseRect(&s_view->clipFrame); - } - else - { - for (s32 i = 0; i < LVIEW_COUNT; i++) - { - if (s_view->clearView[i] & LVIEW_FLAG_CLEAR) - { - LRect rect; - lview_getViewClipFrame(i, &rect); - lcanvas_eraseRect(&rect); - } - } - } - } - - void lview_draw(JBool refresh) - { - cutsceneFilm_drawFilms(refresh); - lactor_draw(refresh); - // TODO: System dialogs. - } - - void lview_blit() - { - // Note: in Dark Forces, the fade is a while loop, pausing the view code. - // For TFE, we run once loop iteration at a time, meaning that we have to - // pause the view code using internal state. - s_updateView = lcanvas_applyFade(JFALSE); - vfb_swap(); - } - - void lview_startLoop() - { - s_view->time = 0; - s_view->step = 0; - s_view->stepCount = 0; - s_exitValue = VIEW_LOOP_RUNNING; - } - - void lview_endLoop() - { - // lview_freeAll(s_view); - lview_initView(s_view); - lpalette_stopAllCycles(); - } - - // A single iteration of the view loop. - s32 lview_loop() - { - if (s_exitValue != VIEW_LOOP_RUNNING) - { - return s_exitValue; - } - - if (s_updateView) - { - if (!s_view->step) - { - lview_update(s_view->time); - lview_updateCallback(s_view->time); - } - - lview_clear(); - lview_draw(s_view->refreshWorld); - s_view->refreshWorld = JFALSE; - } - - lview_blit(); - - if (s_updateView) - { - if (!s_view->step) - { - lpalette_cycleScreen(); - if (s_view->updateFunc) { s_exitValue = s_view->updateFunc(s_view->time); } - s_view->time++; - } - } - - return s_exitValue; - } - - void lview_update(s32 time) - { - ltime_checkTimeElapsed(); - lview_move(); - cutsceneFilm_updateFilms(time); - lactor_update(time); - } - - void lview_updateCallback(s32 time) - { - ltime_checkTimeElapsed(); - cutsceneFilm_updateCallbacks(time); - lactor_updateCallbacks(time); - lactor_updateZPlanes(); - } - - LView* lview_alloc() - { - LView* view = (LView*)landru_alloc(sizeof(LView)); - memset(view, 0, sizeof(LView)); - return view; - } - - void lview_free(LView* view) - { - lview_freeData(view); - landru_free(view); - } - - void lview_setCurrent(LView* view) - { - s_view = view; - } - - LView* lview_getCurrent() - { - return s_view; - } - - void lview_move() - { - for (s32 i = 0; i < LVIEW_COUNT; i++) - { - if (s_view->trackActive[i]) - { - lview_trackView(i, 0); - } - else - { - s_view->xRel[i] += s_view->xVel[i]; - s_view->yRel[i] += s_view->yVel[i]; - } - } - } - - void lview_originToView(s16 viewIndex, s16* x, s16* y) - { - *x -= s_view->xRel[viewIndex]; - *y -= s_view->yRel[viewIndex]; - } - - void lview_viewToOrigin(s16 viewIndex, s16* x, s16* y) - { - *x += s_view->xRel[viewIndex]; - *y += s_view->yRel[viewIndex]; - } - - // View tracks an actor and tries to keep it centered. - void lview_trackView(s16 viewIndex, s16 snap) - { - if (!s_view->trackActor[viewIndex]) { return; } - - s16 x, y, xFract, yFract; - lactor_getPos(s_view->trackActor[viewIndex], &x, &y, &xFract, &yFract); - - LRect frame; - lview_getFrame(viewIndex, &frame); - - // Move the view so that the actor is in the center. - x -= (frame.right - frame.left) >> 1; - y -= (frame.bottom - frame.top) >> 1; - // Handle the offset. - x += s_view->trackXOffset[viewIndex]; - y += s_view->trackYOffset[viewIndex]; - // Then clip to the rect. - lrect_clipPoint(&s_view->trackFrame[viewIndex], &x, &y); - - // Determine how much to move so it can be clamped. - s16 xVel = x - s_view->xRel[viewIndex]; - s16 yVel = y - s_view->yRel[viewIndex]; - if (!snap) - { - xVel = clamp(xVel, -s_view->maxTrackXVel[viewIndex], s_view->maxTrackXVel[viewIndex]); - yVel = clamp(yVel, -s_view->maxTrackYVel[viewIndex], s_view->maxTrackYVel[viewIndex]); - } - - // Finally update the position. - s_view->xRel[viewIndex] += xVel; - s_view->yRel[viewIndex] += yVel; - } - - void lview_enableTracking(s16 viewIndex) - { - s_view->trackActive[viewIndex] = 1; - } - - void lview_disableTracking(s16 viewIndex) - { - s_view->trackActive[viewIndex] = 0; - } - - void lview_setTrackingFrame(s16 viewIndex, LRect* rect) - { - s_view->trackFrame[viewIndex] = *rect; - } - - void lview_getTrackingFrame(s16 viewIndex, LRect* rect) - { - *rect = s_view->trackFrame[viewIndex]; - } - - void lview_setTrackingMaxVelocity(s16 viewIndex, s16 xVel, s16 yVel) - { - s_view->maxTrackXVel[viewIndex] = xVel; - s_view->maxTrackYVel[viewIndex] = yVel; - } - - void lview_getTrackingMaxVelocity(s16 viewIndex, s16* xVel, s16* yVel) - { - *xVel = s_view->maxTrackXVel[viewIndex]; - *yVel = s_view->maxTrackYVel[viewIndex]; - } - - void lview_setTrackingOffset(s16 viewIndex, s16 xOffset, s16 yOffset) - { - s_view->trackXOffset[viewIndex] = xOffset; - s_view->trackYOffset[viewIndex] = yOffset; - } - - void lview_getTrackingOffset(s16 viewIndex, s16* xOffset, s16* yOffset) - { - *xOffset = s_view->trackXOffset[viewIndex]; - *yOffset = s_view->trackYOffset[viewIndex]; - } - - void lview_trackActor(s16 viewIndex, LActor* actor, LRect* rect, s16 maxXVel, s16 maxYVel) - { - s_view->trackActor[viewIndex] = actor; - lview_setTrackingFrame(viewIndex, rect); - lview_setTrackingMaxVelocity(viewIndex, maxXVel, maxYVel); - - s16 w, h; - lactor_getSize(actor, &w, &h); - lview_setTrackingOffset(viewIndex, w>>1, h>>1); - lview_enableTracking(viewIndex); - } - - void lview_setFrame(s16 viewIndex, LRect* rect) - { - s_view->frame[viewIndex] = *rect; - } - - void lview_getFrame(s16 viewIndex, LRect* rect) - { - *rect = s_view->frame[viewIndex]; - } - - void lview_getViewClipFrame(s16 viewIndex, LRect* rect) - { - *rect = s_view->frame[viewIndex]; - lrect_clip(rect, &s_view->clipFrame); - } - - void lview_setClipFrame(LRect* rect) - { - s_view->clipFrame = *rect; - } - - void lview_getClipFrame(LRect* rect) - { - *rect = s_view->clipFrame; - } - - void lview_restoreClipFrame() - { - lcanvas_getBounds(&s_view->clipFrame); - } - - void lview_setZPlane(s16 viewIndex, s16 zStart, s16 zStop) - { - s_view->zStart[viewIndex] = zStart; - s_view->zStop[viewIndex] = zStop; - } - - void lview_getZPlane(s16 viewIndex, s16* zStart, s16* zStop) - { - *zStart = s_view->zStart[viewIndex]; - *zStop = s_view->zStop[viewIndex]; - } - - void lview_setPos(s16 viewIndex, s16 x, s16 y) - { - s_view->xRel[viewIndex] = x; - s_view->yRel[viewIndex] = y; - } - - void lview_getPos(s16 viewIndex, s16* x, s16* y) - { - *x = s_view->xRel[viewIndex]; - *y = s_view->yRel[viewIndex]; - } - - void lview_setSpeed(s16 viewIndex, s16 xVel, s16 yVel) - { - s_view->xVel[viewIndex] = xVel; - s_view->yVel[viewIndex] = yVel; - } - - void lview_getSpeed(s16 viewIndex, s16* xVel, s16* yVel) - { - *xVel = s_view->xVel[viewIndex]; - *yVel = s_view->yVel[viewIndex]; - } - - void lview_setUpdateFunc(LViewUpdateFunc updateFunc) - { - s_view->updateFunc = updateFunc; - } - - void lview_getUpdateFunc(LViewUpdateFunc* updateFunc) - { - *updateFunc = s_view->updateFunc; - } - - void lview_clearUpdateFunc() - { - s_view->updateFunc = nullptr; - } - - void lview_refreshWorld() - { - s_view->refreshWorld = 1; - } - - JBool lview_clearEnabled(s16 viewIndex) - { - return (s_view->clearView[viewIndex] & LVIEW_FLAG_CLEAR) ? JTRUE : JFALSE; - } - - void lview_enableClear(s16 viewIndex) - { - s_view->clearView[viewIndex] |= LVIEW_FLAG_CLEAR; - } - - void lview_disableClear(s16 viewIndex) - { - s_view->clearView[viewIndex] &= ~LVIEW_FLAG_CLEAR; - } - - void lview_enableGlobalClear() - { - s_view->clear = 1; - } - - void lview_disableGlobalClear() - { - s_view->clear = 0; - } - - void lview_enableClearAll() - { - for (s32 i = 0; i < LVIEW_COUNT; i++) - { - lview_enableClear(i); - } - } - - void lview_disableClearAll() - { - for (s32 i = 0; i < LVIEW_COUNT; i++) - { - lview_disableClear(i); - } - } - - JBool lview_copyEnabled(s16 viewIndex) - { - return (s_view->clearView[viewIndex] & LVIEW_FLAG_COPY) ? JTRUE : JFALSE; - } - - void lview_enableCopy(s16 viewIndex) - { - s_view->clearView[viewIndex] |= LVIEW_FLAG_COPY; - } - - void lview_disableCopy(s16 viewIndex) - { - s_view->clearView[viewIndex] &= ~LVIEW_FLAG_COPY; - } - - s32 lview_getTime() - { - return s_view->time; - } - - // Clip the current rect to the view. - JBool lview_clipObjToView(s16 viewIndex, s16 zPlane, LRect* frame, LRect* rect, LRect* clip_rect) - { - LRect clipFrame; - - // Check the z range. - if (zPlane >= s_view->zStart[viewIndex] && zPlane <= s_view->zStop[viewIndex]) - { - // view relative - s16 xOffset = s_view->frame[viewIndex].left - s_view->xRel[viewIndex]; - s16 yOffset = s_view->frame[viewIndex].top - s_view->yRel[viewIndex]; - - *rect = *frame; - lrect_offset(rect, xOffset, yOffset); - *clip_rect = *rect; - - lview_getViewClipFrame(viewIndex, &clipFrame); - lrect_clip(clip_rect, &clipFrame); - - // Is there anything left? - return !lrect_isEmpty(clip_rect); - } - return JFALSE; - } - - // For some reason a view is passed in but isn't actully used by any of this... - void lview_freeData(LView* view) - { - // TODO: - - // free cutscenes. - lactor_freeList(lactor_getList()); - // free palettes - // free sounds. - } -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/lview.h b/components/darkforces/tfe/TFE_DarkForces/Landru/lview.h deleted file mode 100644 index 3b419be7..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/lview.h +++ /dev/null @@ -1,115 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Landru View -// Used by the cutscene/UI system to setup different clipping/render -// regions. -////////////////////////////////////////////////////////////////////// -#include -#include -#include "lrect.h" - -namespace TFE_DarkForces -{ - struct LActor; - - enum LViewConstants - { - LVIEW_COUNT = 4, - VIEW_LOOP_RUNNING = INT_MAX, - // Flags - LVIEW_FLAG_CLEAR = FLAG_BIT(0), - LVIEW_FLAG_COPY = FLAG_BIT(1), - }; - - typedef s32(*LViewUpdateFunc)(s32); - - struct LView - { - LRect frame[LVIEW_COUNT]; - s16 zStart[LVIEW_COUNT]; - s16 zStop[LVIEW_COUNT]; - s16 xRel[LVIEW_COUNT]; - s16 yRel[LVIEW_COUNT]; - s16 xVel[LVIEW_COUNT]; - s16 yVel[LVIEW_COUNT]; - - LRect trackFrame[LVIEW_COUNT]; - LActor* trackActor[LVIEW_COUNT]; - s16 maxTrackXVel[LVIEW_COUNT]; - s16 maxTrackYVel[LVIEW_COUNT]; - s16 trackActive[LVIEW_COUNT]; - s16 trackXOffset[LVIEW_COUNT]; - s16 trackYOffset[LVIEW_COUNT]; - s16 clearView[LVIEW_COUNT]; - - LRect clipFrame; - s32 time; - - s16 refreshWorld; - s16 clear; - s16 step; - s16 stepCount; - s16 coords; - s16 frameCount; - - LViewUpdateFunc updateFunc; - }; - - void lview_init(); - void lview_destroy(); - - LView* lview_alloc(); - void lview_free(LView* view); - void lview_initView(LView* view); - - void lview_startLoop(); - void lview_endLoop(); - s32 lview_loop(); - - void lview_setCurrent(LView* view); - LView* lview_getCurrent(); - - void lview_move(); - void lview_originToView(s16 viewIndex, s16* x, s16* y); - void lview_viewToOrigin(s16 viewIndex, s16* x, s16* y); - void lview_trackView(s16 viewIndex, s16 snap); - void lview_enableTracking(s16 viewIndex); - void lview_disableTracking(s16 viewIndex); - void lview_setTrackingFrame(s16 viewIndex, LRect* rect); - void lview_getTrackingFrame(s16 viewIndex, LRect* rect); - void lview_setTrackingMaxVelocity(s16 viewIndex, s16 xVel, s16 yVel); - void lview_getTrackingMaxVelocity(s16 viewIndex, s16* xVel, s16* yVel); - void lview_setTrackingOffset(s16 viewIndex, s16 xOffset, s16 yOffset); - void lview_getTrackingOffset(s16 viewIndex, s16* xOffset, s16* yOffset); - void lview_trackActor(s16 viewIndex, LActor* actor, LRect* rect, s16 maxXVel, s16 maxYVel); - void lview_setFrame(s16 viewIndex, LRect* rect); - void lview_getFrame(s16 viewIndex, LRect* rect); - void lview_getViewClipFrame(s16 viewIndex, LRect* rect); - void lview_setClipFrame(LRect* rect); - void lview_getClipFrame(LRect* rect); - void lview_restoreClipFrame(); - void lview_setZPlane(s16 viewIndex, s16 zStart, s16 zStop); - void lview_getZPlane(s16 viewIndex, s16* zStart, s16* zStop); - void lview_setPos(s16 viewIndex, s16 x, s16 y); - void lview_getPos(s16 viewIndex, s16* x, s16* y); - void lview_setSpeed(s16 viewIndex, s16 xVel, s16 yVel); - void lview_getSpeed(s16 viewIndex, s16* xVel, s16* yVel); - void lview_setUpdateFunc(LViewUpdateFunc updateFunc); - void lview_getUpdateFunc(LViewUpdateFunc* updateFunc); - void lview_clearUpdateFunc(); - void lview_refreshWorld(); - void lview_enableClear(s16 viewIndex); - void lview_disableClear(s16 viewIndex); - void lview_enableGlobalClear(); - void lview_disableGlobalClear(); - void lview_enableClearAll(); - void lview_disableClearAll(); - void lview_enableCopy(s16 viewIndex); - void lview_disableCopy(s16 viewIndex); - - JBool lview_clearEnabled(s16 viewIndex); - JBool lview_copyEnabled(s16 viewIndex); - JBool lview_clipObjToView(s16 viewIndex, s16 zPlane, LRect* frame, LRect* rect, LRect* clip_rect); - s32 lview_getTime(); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/textCrawl.cpp b/components/darkforces/tfe/TFE_DarkForces/Landru/textCrawl.cpp deleted file mode 100644 index b327e358..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/textCrawl.cpp +++ /dev/null @@ -1,156 +0,0 @@ -#include "textCrawl.h" -#include "lcanvas.h" -#include "ldraw.h" -#include "lsystem.h" -#include "lview.h" -#include "ltimer.h" -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - enum TextCrawlConst - { - TCRAWL_EYEALT = FIXED(60), - TCRAWL_VIEWDIST = FIXED(210), - TCRAWL_WIDTH = FIXED(2020), - TCRAWL_STARTFADEDIST = FIXED(100), - TCRAWL_YSTART = 30, - TCRAWL_YEND = 199, - TCRAWL_HEIGHT = (TCRAWL_YEND - TCRAWL_YSTART + 1), - TCRAWL_XORIGIN = 160, - TCRAWL_YORIGIN = (TCRAWL_YSTART - 1), - TCRAWL_DARKEST = 224, - }; - static const fixed16_16 TCRAWL_PIXELSIZE = floatToFixed16(0.9f); - static const fixed16_16 TCRAWL_FADEPERUNIT = floatToFixed16(0.1f); - - static Film* s_crawlFilm = nullptr; - static u8* s_bitmap = nullptr; - static s32 s_bitmapWidth = 0; - static s32 s_bitmapHeight = 0; - - static fixed16_16 s_aRowOffset[TCRAWL_HEIGHT]; - static fixed16_16 s_aRowScale[TCRAWL_HEIGHT]; - static fixed16_16 s_aRowXStart[TCRAWL_HEIGHT]; - static s32 s_aRowStart[TCRAWL_HEIGHT]; - static s32 s_aRowWidth[TCRAWL_HEIGHT]; - static s32 s_aRowFade[TCRAWL_HEIGHT]; - - JBool drawTextCrawl(LActor* actor, LRect* rect, LRect* clipRect, s16 xOffset, s16 yOffset, JBool refresh); - void textCrawlBuildTables(); - - void openTextCrawl(LActor* actor, Film* film) - { - lactor_setDrawFunc(actor, drawTextCrawl); - s_crawlFilm = film; - s_bitmapWidth = actor->w + 1; - s_bitmapHeight = actor->h + 1; - - // In some mods, the with and height aren't exactly correct... - // This can cause crashes on Windows. - size_t bufferSize = s_bitmapWidth * s_bitmapHeight * 3 / 2; // 1.5x memory allocation. - s_bitmap = (u8*)landru_alloc(bufferSize); - memset(s_bitmap, 0, bufferSize); - // Decompress the image into its own bitmap. - drawDeltaIntoBitmap((s16*)actor->data + 4, 0, 0, s_bitmap, s_bitmapWidth); - - textCrawlBuildTables(); - } - - void closeTextCrawl(LActor* actor) - { - if (!s_bitmap) { return; } - landru_free(s_bitmap); - - s_crawlFilm = nullptr; - s_bitmap = nullptr; - } - - JBool drawTextCrawl(LActor* actor, LRect* rect, LRect* clipRect, s16 xOffset, s16 yOffset, JBool refresh) - { - fixed16_16 offset = floatToFixed16(0.25f) * (200 - actor->y) - intToFixed16(430); - - u8* outBitmap = ldraw_getBitmap(); - s32 stride = 320; - - u8* displayBase = &outBitmap[TCRAWL_YSTART * stride]; - for (s32 y = TCRAWL_YSTART, index = 0; y < TCRAWL_YEND; y++, index++, displayBase += stride) - { - s32 yOffset = round16(s_aRowOffset[index] + offset); - if (yOffset >= 0 && yOffset < s_bitmapHeight) - { - const u8* tex = s_bitmap + (yOffset * s_bitmapWidth); - fixed16_16 offset = s_aRowXStart[index]; - - s32 xStart = s_aRowStart[index]; - s32 xEnd = xStart + s_aRowWidth[index] - 1; - // Clip - if (xStart < 0) - { - offset += mul16(s_aRowScale[index], intToFixed16(-xStart)); - xStart = 0; - } - if (xEnd >= stride) - { - xEnd = stride - 1; - } - - // Draw the current scanline. - u8* display = displayBase + xStart; - for (s32 x = xStart; x <= xEnd; x++, display++) - { - const u8 color = tex[round16(offset)]; - if (color) - { - *display = max(TCRAWL_DARKEST, s32(color) - s_aRowFade[index]); - } - offset += s_aRowScale[index]; - } - } - } - - return JTRUE; - } - - void textCrawlBuildTables() - { - const fixed16_16 numerator = mul16(TCRAWL_EYEALT, TCRAWL_VIEWDIST); - - // Precompute tables. - s32 index = 0; - for (s32 sy = TCRAWL_YSTART; sy <= TCRAWL_YEND; sy++, index++) - { - fixed16_16 z = div16(div16(numerator, intToFixed16(sy - TCRAWL_YORIGIN)), TCRAWL_PIXELSIZE); - s_aRowOffset[index] = intToFixed16(s_bitmapHeight) - z; - -#ifdef TFE_ESPBOX - fixed16_16 xl = div16(FIXED(-floor16(TCRAWL_WIDTH) / 2 * floor16(TCRAWL_VIEWDIST)), z); - fixed16_16 xr = div16(FIXED( floor16(TCRAWL_WIDTH) / 2 * floor16(TCRAWL_VIEWDIST)), z); -#else - fixed16_16 xl = div16(mul16(-TCRAWL_WIDTH >> 1, TCRAWL_VIEWDIST), z); - fixed16_16 xr = div16(mul16( TCRAWL_WIDTH >> 1, TCRAWL_VIEWDIST), z); -#endif - s_aRowWidth[index] = round16(xr - xl); - s_aRowStart[index] = round16(xl) + TCRAWL_XORIGIN; - - s_aRowScale[index] = div16(intToFixed16(s_bitmapWidth - 1), xr - xl + ONE_16); - fixed16_16 xlRounded = intToFixed16(round16(xl)); - s_aRowXStart[index] = mul16(xlRounded - xl, s_aRowScale[index]); - - if (z > TCRAWL_STARTFADEDIST) - { - s_aRowFade[index] = round16(mul16(TCRAWL_FADEPERUNIT, z - TCRAWL_STARTFADEDIST)); - } - else - { - s_aRowFade[index] = 0; - } - } - } -} // namespace TFE_DarkForces diff --git a/components/darkforces/tfe/TFE_DarkForces/Landru/textCrawl.h b/components/darkforces/tfe/TFE_DarkForces/Landru/textCrawl.h deleted file mode 100644 index 2e5c6422..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/Landru/textCrawl.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Handles "Crawl" rendering. -////////////////////////////////////////////////////////////////////// -#include -#include "lactor.h" -#include "cutscene_film.h" - -namespace TFE_DarkForces -{ - void openTextCrawl(LActor* actor, Film* film); - void closeTextCrawl(LActor* actor); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/agent.cpp b/components/darkforces/tfe/TFE_DarkForces/agent.cpp deleted file mode 100644 index d9ffed3a..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/agent.cpp +++ /dev/null @@ -1,578 +0,0 @@ -#include - -#include "agent.h" -#include "util.h" -#include "player.h" -#include "hud.h" -#include "weapon.h" -#include -#include -#include -#include -#include -#include -#include -#include - -namespace TFE_DarkForces -{ - /////////////////////////////////////////// - // Shared State - /////////////////////////////////////////// - AgentData s_agentData[MAX_AGENT_COUNT]; - JBool s_levelComplete = JFALSE; - JBool s_invalidLevelIndex; - s32 s_maxLevelIndex = 0; - s32 s_levelIndex = -1; // This is actually s_levelIndex2 in the RE code. - s32 s_agentId = 0; - s32 s_headerSize = (s32)sizeof(PilotConfigHeader); - char** s_levelDisplayNames; - char** s_levelGamePaths; - char** s_levelSrcPaths; - - static Task* s_levelEndTask = nullptr; - - void agent_writeSavedData(s32 agentId, LevelSaveData* saveData); - void agent_readSavedData(s32 agentId, LevelSaveData* levelData); - - /////////////////////////////////////////// - // API Implementation - /////////////////////////////////////////// - void agent_checkNameLen(u8& nameLen) - { - if (nameLen >= 32) - { - TFE_System::logWrite(LOG_ERROR, "Agent", "Agent load - name is too long: %d / 32", nameLen); - assert(0); - nameLen = 31; - } - } - - void agent_restartEndLevelTask() - { - // Add the level complete task. - if (s_levelComplete) - { - agent_createLevelEndTask(); - } - } - - void agent_serialize(Stream* stream) - { - bool write = serialization_getMode() == SMODE_WRITE; - - SERIALIZE(SaveVersionInit, s_levelComplete, JFALSE); - SERIALIZE(SaveVersionInit, s_invalidLevelIndex, JFALSE); - SERIALIZE(SaveVersionInit, s_maxLevelIndex, JFALSE); - SERIALIZE(SaveVersionInit, s_levelIndex, JFALSE); - - // Agent. - char name[64] = { 0 }; - u8 agentNameLen = 0; - if (write) - { - strcpy(name, s_agentData[s_agentId].name); - name[32] = 0; // Just in case. - - agentNameLen = (u8)strlen(name); - agent_checkNameLen(agentNameLen); - } - SERIALIZE(SaveVersionInit, agentNameLen, 0); - if (!write) - { - agent_checkNameLen(agentNameLen); - } - SERIALIZE_BUF(SaveVersionInit, name, agentNameLen); - name[agentNameLen] = 0; - - // Agent data. - LevelSaveData data; - if (write) - { - agent_readSavedData(s_agentId, &data); - } - SERIALIZE(SaveVersionInit, data, { 0 }); - - // Find the agent. - if (!write) - { - s_agentId = -1; - // First get the count. - s32 agentCount = 0; - for (s32 i = 0; i < 14; i++) - { - if (!s_agentData[i].name[0]) { break; } - agentCount++; - } - // Next find the agent, if it exists. - for (s32 i = 0; i < agentCount; i++) - { - if (strcmp(s_agentData[i].name, name) == 0) - { - s_agentId = i; - break; - } - } - // If the agent doesn't exist, create it. - if (s_agentId < 0) - { - if (agentCount < 14) - { - // Create a new agent. - s_agentData[agentCount] = data.agentData; - s_agentId = agentCount; - agent_writeSavedData(s_agentId, &data); - } - else - { - TFE_System::logWrite(LOG_ERROR, "Agent", "Too many agents - cannot create a new agent from save."); - assert(0); - s_agentId = 0; - } - } - else - { - // Check the agent and make sure it will work... - if (s_agentData[s_agentId].nextMission < data.agentData.nextMission) - { - TFE_System::logWrite(LOG_WARNING, "Agent", "The agent in the save file has completed more levels than the local agent, updating."); - s_agentData[s_agentId] = data.agentData; - agent_writeSavedData(s_agentId, &data); - } - } - } - } - - s32 agent_loadData() - { - FileStream file; - if (!openDarkPilotConfig(&file)) - { - TFE_System::logWrite(LOG_ERROR, "Agent", "Cannot open DarkPilo.cfg"); - return 0; - } - - s32 agentReadCount = 0; - for (s32 i = 0; i < MAX_AGENT_COUNT; i++) - { - LevelSaveData saveData; - if (agent_readConfigData(&file, i, &saveData)) - { - memcpy(&s_agentData[i], &saveData.agentData, sizeof(AgentData)); - agentReadCount++; - } - } - - file.close(); - return agentReadCount; - } - - void agent_levelComplete() - { - s_levelComplete = JTRUE; - - s32 curLevel = s_agentData[s_agentId].selectedMission + 1; - if (curLevel > s_agentData[s_agentId].nextMission) - { - s_agentData[s_agentId].nextMission = curLevel; - } - } - - void levelEndTaskFunc(MessageType msg) - { - task_begin; - while (1) - { - hud_sendTextMessage(461); - task_yield(582); // ~4 seconds - hud_sendTextMessage(462); - task_yield(4369); // ~30 seconds - } - task_end; - } - - void agent_levelEndTask() - { - s_levelEndTask = nullptr; - } - - void agent_createLevelEndTask() - { - if (!s_levelEndTask) - { - s_levelEndTask = createSubTask("LevelEnd", levelEndTaskFunc); - } - } - - void agent_saveLevelCompletion(u8 diff, s32 levelIndex) - { - s_agentData[s_agentId].completed[levelIndex - 1] = diff; - } - - s32 agent_getLevelIndex() - { - return s_levelIndex; - } - - s32 agent_getLevelIndexFromName(const char* name) - { - for (s32 i = 0; i < s_maxLevelIndex; i++) - { - if (!strcasecmp(s_levelGamePaths[i], name)) - { - return i + 1; - } - } - return 0; - } - - const char* agent_getLevelName() - { - if (!s_maxLevelIndex) { return nullptr; } - const s32 index = clamp(s_levelIndex, 1, s_maxLevelIndex); - return s_levelGamePaths[index - 1]; - } - - const char* agent_getLevelDisplayName() - { - if (!s_maxLevelIndex) { return nullptr; } - const s32 index = clamp(s_levelIndex, 1, s_maxLevelIndex); - return s_levelDisplayNames[index - 1]; - } - - void agent_setLevelComplete(JBool complete) - { - s_levelComplete = complete; - } - - JBool agent_getLevelComplete() - { - return s_levelComplete; - } - - void agent_setNextLevelByIndex(s32 index) - { - if (index <= s_maxLevelIndex) - { - s_levelIndex = index; - s_agentData[s_agentId].selectedMission = index; - } - } - - void agent_createNewAgent(s32 agentId, AgentData* data, const char* name) - { - FileStream file; - if (!openDarkPilotConfig(&file)) - { - TFE_System::logWrite(LOG_ERROR, "Agent", "Cannot open DarkPilo.cfg"); - return; - } - - LevelSaveData saveData; - memset(&saveData, 0, sizeof(LevelSaveData)); - memset(data, 0, sizeof(AgentData)); - - saveData.inv[0] = 0xff; - saveData.inv[2] = 0xff; - saveData.inv[6] = 0xff; - saveData.inv[30] = WPN_PISTOL; - saveData.inv[31] = 3; - - saveData.ammo[0] = 100; - saveData.ammo[7] = 100; - saveData.ammo[8] = 100; - saveData.ammo[9] = FIXED(2); - - strCopyAndZero(data->name, name, 32); - data->difficulty = 1; - data->nextMission = 1; - data->selectedMission = 1; - memcpy(&saveData.agentData, data, sizeof(AgentData)); - - agent_writeAgentConfigData(&file, agentId, &saveData); - file.close(); - } - - void agent_writeSavedData(s32 agentId, LevelSaveData* saveData) - { - FileStream file; - if (!openDarkPilotConfig(&file)) - { - TFE_System::logWrite(LOG_ERROR, "Agent", "Cannot open DarkPilo.cfg"); - return; - } - agent_writeAgentConfigData(&file, agentId, saveData); - file.close(); - } - - void agent_updateAgentSavedData() - { - FileStream file; - if (!openDarkPilotConfig(&file)) - { - TFE_System::logWrite(LOG_ERROR, "Agent", "Cannot open DarkPilo.cfg"); - return; - } - - for (s32 i = 0; i < MAX_AGENT_COUNT; i++) - { - LevelSaveData saveData; - agent_readConfigData(&file, i, &saveData); - - // Copy Agent data into saved data. - memcpy(&saveData, &s_agentData[i], sizeof(AgentData)); - agent_writeAgentConfigData(&file, i, &saveData); - } - - file.close(); - } - - s32 agent_saveInventory(s32 agentId, s32 nextLevel) - { - if (nextLevel > 14) { return 0; } - - FileStream file; - if (!openDarkPilotConfig(&file)) { return 0; } - - LevelSaveData saveData; - if (!agent_readConfigData(&file, agentId, &saveData)) - { - file.close(); - return 0; - } - - s32 levelIndex = nextLevel - 1; - s32* ammo = &saveData.ammo[levelIndex * 10]; - u8* inv = &saveData.inv[levelIndex * 32]; - player_writeInfo(inv, ammo); - s32 written = agent_writeAgentConfigData(&file, agentId, &saveData); - file.close(); - - return written; - } - - JBool agent_loadLevelList(const char* fileName) - { - FilePath filePath; - if (!TFE_Paths::getFilePath(fileName, &filePath)) - { - return JFALSE; - } - char* buffer = nullptr; - FileStream file; - if (!file.open(&filePath, Stream::MODE_READ)) - { - return JFALSE; - } - u32 len = (u32)file.getSize(); - buffer = (char*)game_alloc(len+1); - file.readBuffer(buffer, len); - file.close(); - buffer[len] = 0; - - TFE_Parser parser; - parser.init(buffer, len); - parser.addCommentString("#"); - - size_t bufferPos = 0; - const char* line = parser.readLine(bufferPos); - s32 count; - if (sscanf(line, "LEVELS %d", &count) < 1) - { - game_free(buffer); - s_maxLevelIndex = 0; - return JFALSE; - } - else - { - s_maxLevelIndex = min(count, MAX_LEVEL_COUNT); - if (count) - { - s_levelDisplayNames = (char**)game_alloc(count * sizeof(char*)); - s_levelGamePaths = (char**)game_alloc(count * sizeof(char*)); - s_levelSrcPaths = (char**)game_alloc(count * sizeof(char*)); - } - } - - for (s32 i = 0; i < count; i++) - { - line = parser.readLine(bufferPos); - char* displayName = strtok((char*)line, ","); - char* gamePath = strtok(nullptr, ", \t\n\r"); - char* srcPath = strtok(nullptr, ", \t\n\r"); - - s_levelDisplayNames[i] = nullptr; - s_levelGamePaths[i] = nullptr; - s_levelSrcPaths[i] = nullptr; - - if (displayName && gamePath) - { - if (displayName[0]) - { - s_levelDisplayNames[i] = copyAndAllocateString(displayName); - } - if (gamePath[0]) - { - s_levelGamePaths[i] = copyAndAllocateString(gamePath); - } - } - } - - game_free(buffer); - return JTRUE; - } - - JBool agent_readConfigData(FileStream* file, s32 agentId, LevelSaveData* saveData) - { - const s32 dataSize = (s32)sizeof(LevelSaveData); - - s32 offset = s_headerSize + agentId * dataSize; - if (!file->seek(offset)) - { - return JFALSE; - } - if (file->readBuffer(saveData, dataSize) != dataSize) - { - return JFALSE; - } - saveData->agentData.selectedMission = TFE_Endian::le32_to_cpu(saveData->agentData.selectedMission); - saveData->agentData.nextMission = TFE_Endian::le32_to_cpu(saveData->agentData.nextMission); - for (s32 i = 0; i < 140; i++) - { - saveData->ammo[i] = TFE_Endian::le32_to_cpu(saveData->ammo[i]); - } - return JTRUE; - } - - JBool agent_writeAgentConfigData(FileStream* file, s32 agentId, LevelSaveData* saveData) - { - s32 fileOffset = agentId*sizeof(LevelSaveData) + s_headerSize; - if (!file->seek(fileOffset)) - { - return JFALSE; - } - saveData->agentData.selectedMission = TFE_Endian::cpu_to_le32(saveData->agentData.selectedMission); - saveData->agentData.nextMission = TFE_Endian::cpu_to_le32(saveData->agentData.nextMission); - for (s32 i = 0; i < 140; i++) - { - saveData->ammo[i] = TFE_Endian::cpu_to_le32(saveData->ammo[i]); - } - file->writeBuffer(saveData, sizeof(LevelSaveData)); - return JTRUE; - } - - void agent_readSavedData(s32 agentId, LevelSaveData* levelData) - { - FileStream file; - if (!openDarkPilotConfig(&file)) - { - TFE_System::logWrite(LOG_ERROR, "Agent", "Cannot open DarkPilo.cfg"); - return; - } - agent_readConfigData(&file, agentId, levelData); - file.close(); - } - - void agent_readSavedDataForLevel(s32 agentId, s32 levelIndex) - { - FileStream file; - if (!openDarkPilotConfig(&file)) - { - TFE_System::logWrite(LOG_ERROR, "Agent", "Cannot open DarkPilo.cfg"); - return; - } - LevelSaveData levelData; - agent_readConfigData(&file, agentId, &levelData); - file.close(); - - s32* ammo = &levelData.ammo[(levelIndex - 1) * 10]; - u8* inv = &levelData.inv[(levelIndex - 1) * 32]; - player_readInfo(inv, ammo); - } - - // Creates a new Dark Pilot config file, which is used for saving. - JBool createDarkPilotConfig(const char* path) - { - FileStream darkPilot; - if (!darkPilot.open(path, Stream::MODE_WRITE)) - { - return JFALSE; - } - - PilotConfigHeader header = - { - {'P', 'C', 'F'}, // signature. - 0x12, // version used by Dark Forces. - 14, // maximum number of agents. - }; - darkPilot.writeBuffer(&header, s_headerSize); - LevelSaveData clearData = { 0 }; - for (s32 i = 0; i < MAX_AGENT_COUNT; i++) - { - darkPilot.writeBuffer(&clearData, sizeof(LevelSaveData)); - } - darkPilot.close(); - return JTRUE; - } - - // This function differs slightly from Dark Forces in the following ways: - // 1. First it tries to open the CFG file from PATH_PROGRAM_DATA/DarkPilot.cfg - // 2. If (1) fails, it will then attempt to copy the file from PATH_SOURCE/DarkPilot.cfg to PATH_PROGRAM_DATA/DarkPilot.cfg - // 3. Instead of returning a handle, the caller passes in a FileStream pointer to be filled in. - // This is done so that the original data cannot be corrupted by a potentially buggy Alpha build. - // Also, later, the TFE based save format will likely change - so importing will be necessary anyway. - JBool openDarkPilotConfig(FileStream* file) - { - assert(file); - - // TFE uses its own local copy of the save game data to avoid corrupting existing data. - // If this copy does not exist, then copy it. - char documentsPath[TFE_MAX_PATH]; - char programDataPath[TFE_MAX_PATH]; - char sourcePath[TFE_MAX_PATH]; - TFE_Paths::appendPath(PATH_USER_DOCUMENTS, "DARKPILO.CFG", documentsPath); - if (!FileUtil::exists(documentsPath)) - { - // First check in /ProgramData since that is where the previous version stored it. - TFE_Paths::appendPath(PATH_PROGRAM_DATA, "DARKPILO.CFG", programDataPath); - if (FileUtil::exists(programDataPath)) - { - TFE_System::logWrite(LOG_WARNING, "DarkForcesMain", "'DARKPILO.CFG' copied from '%s' to '%s', ProgramData/ will no longer be used and can be deleted.", - programDataPath, documentsPath); - FileUtil::copyFile(programDataPath, documentsPath); - // Cleanup after TFE. - FileUtil::deleteFile(programDataPath); - } - else - { - // Then try the source data path. - TFE_Paths::appendPath(PATH_SOURCE_DATA, "DARKPILO.CFG", sourcePath); - if (FileUtil::exists(sourcePath)) - { - FileUtil::copyFile(sourcePath, documentsPath); - } - else - { - // Finally generate a new one. - TFE_System::logWrite(LOG_WARNING, "DarkForcesMain", "Cannot find 'DARKPILO.CFG' at '%s'. Creating a new file for save data.", sourcePath); - createDarkPilotConfig(documentsPath); - } - } - } - // Then try opening the file. - if (!file->open(documentsPath, Stream::MODE_READWRITE)) - { - return JFALSE; - } - // Then verify the file. - PilotConfigHeader header; - file->readBuffer(&header, sizeof(PilotConfigHeader)); - if (header.version == 0x12 && header.count == 14 && strncasecmp(header.signature, "PCF", 3) == 0) - { - return JTRUE; - } - // If it is not correct, then close the file and return false. - file->close(); - return JFALSE; - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/agent.h b/components/darkforces/tfe/TFE_DarkForces/agent.h deleted file mode 100644 index 128eee15..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/agent.h +++ /dev/null @@ -1,84 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Agent - handles save game data, level lists, etc. -////////////////////////////////////////////////////////////////////// -#include -#include - -namespace TFE_DarkForces -{ - enum AgentConstants - { - MAX_LEVEL_COUNT = 14, - MAX_AGENT_COUNT = 14, - }; - -#pragma pack(push) -#pragma pack(1) - struct PilotConfigHeader - { - char signature[3]; // "PCF" - u8 version; // 18 - s8 count; // Number of agents. - }; - struct AgentData - { - char name[32]; - s32 selectedMission; - s32 nextMission; - u8 difficulty; - u8 completed[MAX_LEVEL_COUNT]; - }; - struct LevelSaveData - { - AgentData agentData; - - // Inventory - // 32 items * 14 levels = 448 values - u8 inv[448]; - - // Ammo (includes health, shields, energy) - // 10 items * 14 levels = 140 values (each 4 bytes). - s32 ammo[140]; - - s32 pad; // unused, but the struct size must stay the same. - }; -#pragma pack(pop) - - void agent_serialize(Stream* stream); - void agent_restartEndLevelTask(); - s32 agent_loadData(); - JBool agent_loadLevelList(const char* fileName); - void agent_updateAgentSavedData(); - void agent_levelEndTask(); - - JBool agent_readConfigData(FileStream* file, s32 agentId, LevelSaveData* saveData); - JBool agent_writeAgentConfigData(FileStream* file, s32 agentId, LevelSaveData* saveData); - void agent_readSavedDataForLevel(s32 agentId, s32 levelIndex); - void agent_saveLevelCompletion(u8 diff, s32 levelIndex); - s32 agent_saveInventory(s32 agentId, s32 nextLevel); - void agent_createNewAgent(s32 agentId, AgentData* data, const char* name); - - JBool openDarkPilotConfig(FileStream* file); - void agent_setNextLevelByIndex(s32 index); - s32 agent_getLevelIndex(); - s32 agent_getLevelIndexFromName(const char* name); - const char* agent_getLevelName(); - const char* agent_getLevelDisplayName(); - - void agent_setLevelComplete(JBool complete); - JBool agent_getLevelComplete(); - - void agent_levelComplete(); - void agent_createLevelEndTask(); - - extern AgentData s_agentData[MAX_AGENT_COUNT]; - extern s32 s_maxLevelIndex; - extern s32 s_agentId; - extern JBool s_invalidLevelIndex; - extern JBool s_levelComplete; - extern char** s_levelDisplayNames; - extern char** s_levelGamePaths; - extern char** s_levelSrcPaths; -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/animLogic.cpp b/components/darkforces/tfe/TFE_DarkForces/animLogic.cpp deleted file mode 100644 index 2c301fed..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/animLogic.cpp +++ /dev/null @@ -1,218 +0,0 @@ -#include "animLogic.h" -#include "time.h" -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - Allocator* s_spriteAnimList = nullptr; - Task* s_spriteAnimTask = nullptr; - - void setSpriteAnimation(Task* spriteAnimTask, Allocator* spriteAnimAlloc) - { - s_spriteAnimTask = spriteAnimTask; - s_spriteAnimList = spriteAnimAlloc; - } - - void spriteAnimLogicCleanupFunc(Logic* logic) - { - SpriteAnimLogic* animLogic = (SpriteAnimLogic*)logic; - Task* completeTask = animLogic->completeTask; - // The original code would loop and yield while not in the main task. - // For TFE, that should be unnecessary. - deleteLogicAndObject(logic); - allocator_deleteItem(s_spriteAnimList, logic); - if (completeTask) - { - task_runAndReturn(completeTask, MSG_SEQ_COMPLETE); - } - } - - // Logic update function, handles the update of all sprite animations. - void spriteAnimLogicFunc(MessageType msg) - { - struct LocalContext - { - SpriteAnimLogic* anim; - SecObject* obj; - s32 count; - }; - task_begin_ctx; - while (msg != MSG_FREE_TASK) - { - if (msg == MSG_FREE) - { - deleteLogicAndObject((Logic*)s_msgTarget); - allocator_deleteItem(s_spriteAnimList, s_msgTarget); - } - else // otherwise update all of the animations in the list. - { - taskCtx->anim = (SpriteAnimLogic*)allocator_getHead(s_spriteAnimList); - taskCtx->count = 0; - while (taskCtx->anim) - { - taskCtx->count++; - if (taskCtx->anim->nextTick < s_curTick) - { - taskCtx->obj = taskCtx->anim->logic.obj; - taskCtx->obj->frame++; - taskCtx->anim->nextTick += taskCtx->anim->delay; - - if (taskCtx->obj->frame > taskCtx->anim->lastFrame) - { - taskCtx->anim->loopCount--; - if (taskCtx->anim->loopCount == 0) - { - // Only delete from the main task. - task_waitWhileIdNotZero(TASK_NO_DELAY); - - // Finally delete the logic and call the complete function. - Task* completeTask = taskCtx->anim->completeTask; - - deleteLogicAndObject((Logic*)taskCtx->anim); // This just deletes the Logic from the list - if (completeTask) - { - task_runAndReturn(completeTask, MSG_SEQ_COMPLETE); - } - allocator_deleteItem(s_spriteAnimList, taskCtx->anim); // This deletes the logic itself. - } - else - { - taskCtx->obj->frame = taskCtx->anim->firstFrame; - } - } - } - taskCtx->anim = (SpriteAnimLogic*)allocator_getNext(s_spriteAnimList); - } - } - // There must be a yield in an endless while() loop. - // If there are no more animated logics, then make the task go to sleep. - task_yield(taskCtx->count ? TASK_NO_DELAY : TASK_SLEEP); - } - // Once we break out of the while loop, the task gets removed. - task_end; - } - - Logic* obj_setSpriteAnim(SecObject* obj) - { - if (!(obj->type & OBJ_TYPE_SPRITE)) - { - return nullptr; - } - - // Create an allocator if one is not already setup. - if (!s_spriteAnimTask) - { - s_spriteAnimTask = createTask("sprite animation", spriteAnimLogicFunc); - } - if (!s_spriteAnimList) - { - s_spriteAnimList = allocator_create(sizeof(SpriteAnimLogic)); - } - - SpriteAnimLogic* anim = (SpriteAnimLogic*)allocator_newItem(s_spriteAnimList); - const WaxAnim* waxAnim = WAX_AnimPtr(obj->wax, 0); - - obj_addLogic(obj, (Logic*)anim, LOGIC_ANIM, s_spriteAnimTask, spriteAnimLogicCleanupFunc); - - anim->firstFrame = 0; - anim->lastFrame = waxAnim->frameCount - 1; - anim->loopCount = 0; - anim->completeTask = nullptr; - anim->delay = time_frameRateToDelay(u32(waxAnim->frameRate)); - anim->nextTick = s_curTick + anim->delay; - - obj->frame = 0; - obj->anim = 0; - task_makeActive(s_spriteAnimTask); - - return (Logic*)anim; - } - - // TODO: Find a better way of handling the complete task. - extern Task* s_hitEffectTask; - - void animLogic_serialize(Logic*& logic, SecObject* obj, Stream* stream) - { - SpriteAnimLogic* anim = nullptr; - if (serialization_getMode() == SMODE_WRITE) - { - anim = (SpriteAnimLogic*)logic; - } - else - { - - // Create an allocator if one is not already setup. - if (!s_spriteAnimTask) - { - s_spriteAnimTask = createTask("sprite animation", spriteAnimLogicFunc); - } - if (!s_spriteAnimList) - { - s_spriteAnimList = allocator_create(sizeof(SpriteAnimLogic)); - } - task_makeActive(s_spriteAnimTask); - - anim = (SpriteAnimLogic*)allocator_newItem(s_spriteAnimList); - logic = (Logic*)anim; - } - SERIALIZE(ObjState_InitVersion, anim->firstFrame, 0); - SERIALIZE(ObjState_InitVersion, anim->lastFrame, 0); - SERIALIZE(ObjState_InitVersion, anim->loopCount, 0); - SERIALIZE(ObjState_InitVersion, anim->delay, 0); - SERIALIZE(ObjState_InitVersion, anim->nextTick, 0); - - // For now, we know the only complete task is s_hitEffectTask. - s32 completeTaskId = 0; - if (serialization_getMode() == SMODE_WRITE) - { - if (anim->completeTask == s_hitEffectTask) - { - completeTaskId = 1; - } - assert(!anim->completeTask || anim->completeTask == s_hitEffectTask); - } - SERIALIZE(ObjState_InitVersion, completeTaskId, 0); - - if (serialization_getMode() == SMODE_READ) - { - anim->logic.task = s_spriteAnimTask; - anim->logic.cleanupFunc = spriteAnimLogicCleanupFunc; - - assert(completeTaskId == 0 || completeTaskId == 1); - anim->completeTask = nullptr; - if (completeTaskId == 1) - { - anim->completeTask = s_hitEffectTask; - } - } - } - - void setAnimCompleteTask(SpriteAnimLogic* logic, Task* completeTask) - { - logic->completeTask = completeTask; - } - - void setupAnimationFromLogic(SpriteAnimLogic* animLogic, s32 animIndex, u32 firstFrame, u32 lastFrame, u32 loopCount) - { - SecObject* obj = animLogic->logic.obj; - obj->anim = animIndex; - obj->frame = firstFrame; - - const WaxAnim* anim = WAX_AnimPtr(obj->wax, animIndex); - const s32 animLastFrame = anim->frameCount - 1; - if (lastFrame >= (u32)animLastFrame) - { - lastFrame = animLastFrame; - } - - animLogic->firstFrame = firstFrame; - animLogic->lastFrame = lastFrame; - animLogic->delay = time_frameRateToDelay(u32(anim->frameRate)); - animLogic->loopCount = loopCount; - } - -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/animLogic.h b/components/darkforces/tfe/TFE_DarkForces/animLogic.h deleted file mode 100644 index eff756c3..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/animLogic.h +++ /dev/null @@ -1,40 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces Animation Logic- -// Handles cyclic "fire and forget" sprite animations. -// This includes animated sprite objects, explosions, and hit effects. -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include "logic.h" -#include "time.h" - -namespace TFE_DarkForces -{ - // This is a type of "Logic" and can be safety cast to Logic {}. - struct SpriteAnimLogic - { - Logic logic; // Logic header. - s32 firstFrame; // First frame (inclusive). - s32 lastFrame; // Last frame (inclusive). - s32 loopCount; // Number of loops before the animation ends. Set to <= 0 to loop forever. - Tick delay; // Delay between frames, computed from the frame rate. - Tick nextTick; // Next game tick to advance the animation to the next frame. - Task* completeTask; // Function to call once the animation has completed (can be null). - }; - - // Given an object, create and setup the animation logic. Note - this will return null if the object is not a sprite. - Logic* obj_setSpriteAnim(SecObject* obj); - // Set the completeFunc for a instance of the logic. The complete function is called when the animation completes. - void setAnimCompleteTask(SpriteAnimLogic* logic, Task* completeTask); - // Setup the animation logic instance given the WAX animation index, first and last frames (inclusive) and loop count. - // Note that loopCount = 0 means that the animation loops forever. - void setupAnimationFromLogic(SpriteAnimLogic* logic, s32 animIndex, u32 firstFrame, u32 lastFrame, u32 loopCount); - - void setSpriteAnimation(Task* spriteAnimTask, Allocator* spriteAnimAlloc); - - // Serialization - void animLogic_serialize(Logic*& logic, SecObject* obj, Stream* stream); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/automap.cpp b/components/darkforces/tfe/TFE_DarkForces/automap.cpp deleted file mode 100644 index 1dbe294f..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/automap.cpp +++ /dev/null @@ -1,669 +0,0 @@ -#include "automap.h" -#include "player.h" -#include "hud.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - enum MapWallColor - { - WCOLOR_INVISIBLE = 0, - WCOLOR_NORMAL = 10, - WCOLOR_LEDGE = 12, - WCOLOR_GRAYED_OUT = 13, - WCOLOR_DOOR = 19, - }; - - enum MapObjectColor - { - MOBJCOLOR_DEFAULT = 19, - MOBJCOLOR_PROJ = 6, - MOBJCOLOR_CORPSE = 48, - MOBJCOLOR_LANDMINE = 1, - MOBJCOLOR_PICKUP = 152, - MOBJCOLOR_SCENERY = 21, - }; - - enum MapConstants - { - MOBJSPRITE_DRAW_LEN = FIXED(2) - }; - - static fixed16_16 s_screenScale = 0xc000; // 0.75 - static fixed16_16 s_scrLeftScaled; - static fixed16_16 s_scrRightScaled; - static fixed16_16 s_scrTopScaled; - static fixed16_16 s_scrBotScaled; - - static JBool s_automapAutoCenter = JTRUE; - static fixed16_16 s_mapXCenterInPixels = 159; - static fixed16_16 s_mapZCenterInPixels = 99; - - static s32 s_mapTop; - static s32 s_mapLeft; - static s32 s_mapRight; - static s32 s_mapBot; - static s32 s_mapShowSectorMode = 0; - static JBool s_mapShowAllLayers = JFALSE; - - static s32 s_mapPrevPlayerX; - static s32 s_mapPrevPlayerZ; - static u8* s_mapFramebuffer; - - JBool s_pdaActive = JFALSE; - JBool s_drawAutomap = JFALSE; - JBool s_automapLocked = JTRUE; - fixed16_16 s_mapX0; - fixed16_16 s_mapX1; - fixed16_16 s_mapZ0; - fixed16_16 s_mapZ1; - s32 s_mapLayer; - - void automap_projectPosition(fixed16_16* x, fixed16_16* z); -#ifdef TFE_ESPBOX - static inline -#endif - void automap_drawPointWithRadius(fixed16_16 x, fixed16_16 z, fixed16_16 r, u8 color); -#ifdef TFE_ESPBOX - static inline -#endif - void automap_drawPointWithDirection(fixed16_16 x, fixed16_16 z, angle14_32 angle, fixed16_16 len, u8 color); -#ifdef TFE_ESPBOX - static inline -#endif - void automap_drawPoint(fixed16_16 x, fixed16_16 z, u8 color); -#ifdef TFE_ESPBOX - static inline -#endif - void automap_drawLine(fixed16_16 px1, fixed16_16 pz1, fixed16_16 px2, fixed16_16 pz2, u8 color); - void automap_drawWall(RWall* wall, u8 color); - void automap_drawObject(SecObject* obj); - void automap_drawSector(RSector* sector); - void automap_drawPlayer(s32 layer); - void automap_drawSectors(); - - void automap_serialize(Stream* stream) - { - SERIALIZE(SaveVersionInit, s_screenScale, 0xc000); - SERIALIZE(SaveVersionInit, s_scrLeftScaled, 0); - SERIALIZE(SaveVersionInit, s_scrRightScaled, 0); - SERIALIZE(SaveVersionInit, s_scrTopScaled, 0); - SERIALIZE(SaveVersionInit, s_scrBotScaled, 0); - - SERIALIZE(SaveVersionInit, s_automapAutoCenter, JTRUE); - SERIALIZE(SaveVersionInit, s_mapXCenterInPixels, 159); - SERIALIZE(SaveVersionInit, s_mapZCenterInPixels, 99); - - SERIALIZE(SaveVersionInit, s_mapTop, 0); - SERIALIZE(SaveVersionInit, s_mapLeft, 0); - SERIALIZE(SaveVersionInit, s_mapRight, 0); - SERIALIZE(SaveVersionInit, s_mapBot, 0); - SERIALIZE(SaveVersionInit, s_mapShowSectorMode, 0); - SERIALIZE(SaveVersionInit, s_mapShowAllLayers, JFALSE); - - SERIALIZE(SaveVersionInit, s_mapPrevPlayerX, 0); - SERIALIZE(SaveVersionInit, s_mapPrevPlayerZ, 0); - - SERIALIZE(SaveVersionInit, s_pdaActive, JFALSE); - SERIALIZE(SaveVersionInit, s_drawAutomap, JFALSE); - SERIALIZE(SaveVersionInit, s_automapLocked, JTRUE); - SERIALIZE(SaveVersionInit, s_mapX0, 0); - SERIALIZE(SaveVersionInit, s_mapX1, 0); - SERIALIZE(SaveVersionInit, s_mapZ0, 0); - SERIALIZE(SaveVersionInit, s_mapZ1, 0); - SERIALIZE(SaveVersionInit, s_mapLayer, 0); - } - - // _computeScreenBounds() and computeScaledScreenBounds() in the original source: - // computeScaledScreenBounds() calls _computeScreenBounds() - so merged here. - void automap_computeScreenBounds() - { - ScreenRect* screenRect = vfb_getScreenRect(VFB_RECT_RENDER); - - { - u32 dispWidth, dispHeight; - vfb_getResolution(&dispWidth, &dispHeight); - - fixed16_16 leftEdge = intToFixed16(screenRect->left - s32(dispWidth) + 1); - s_scrLeftScaled = div16(leftEdge, s_screenScale); - - fixed16_16 rightEdge = intToFixed16(screenRect->right - s32(dispWidth) + 1); - s_scrRightScaled = div16(rightEdge, s_screenScale); - - fixed16_16 topEdge = intToFixed16(screenRect->top - s32(dispHeight) + 1); - s_scrTopScaled = -div16(topEdge, s_screenScale); - - fixed16_16 botEdge = intToFixed16(screenRect->bot - s32(dispHeight) + 1); - s_scrBotScaled = -div16(botEdge, s_screenScale); - } - } - - void automap_resetScale() - { - // default scale. - s_screenScale = 0xc000; // 0.75 - - // Adjust for resolution. - u32 width, height; - vfb_getResolution(&width, &height); - - if (height != 200) - { - fixed16_16 scaleFactor = div16(intToFixed16(height), FIXED(200)); - s_screenScale = mul16(s_screenScale, scaleFactor); - } - } - - void automap_updateMapData(MapUpdateID id) - { - switch (id) - { - case MAP_CENTER_PLAYER: - { - RSector* sector = s_playerEye ? s_playerEye->sector : nullptr; - if (sector) { s_mapLayer = sector->layer; } - s_mapX1 = s_mapX0 = s_eyePos.x; - s_mapZ1 = s_mapZ0 = s_eyePos.z; - } break; - case MAP_MOVE1_UP: - { - if (s_pdaActive) - { - s_mapZ1 += div16(FIXED(20), s_screenScale); - } - else if (!s_automapAutoCenter) - { - s32 speed = FIXED(60) << (s_playerRun * 2); - speed >>= s_playerSlow; - s_mapZ1 += mul16(speed, s_deltaTime); - } - } break; - case MAP_MOVE1_DN: - { - if (s_pdaActive) - { - s_mapZ1 -= div16(FIXED(20), s_screenScale); - } - else if (!s_automapAutoCenter) - { - s32 speed = FIXED(60) << (s_playerRun * 2); - speed >>= s_playerSlow; - s_mapZ1 -= mul16(speed, s_deltaTime); - } - } break; - case MAP_MOVE1_LEFT: - { - if (s_pdaActive) - { - s_mapX1 -= div16(FIXED(20), s_screenScale); - } - else if (!s_automapAutoCenter) - { - s32 speed = FIXED(60) << (s_playerRun * 2); - speed >>= s_playerSlow; - s_mapX1 -= mul16(speed, s_deltaTime); - } - } break; - case MAP_MOVE1_RIGHT: - { - if (s_pdaActive) - { - s_mapX1 += div16(FIXED(20), s_screenScale); - } - else if (!s_automapAutoCenter) - { - s32 speed = FIXED(60) << (s_playerRun * 2); - speed >>= s_playerSlow; - s_mapX1 += mul16(speed, s_deltaTime); - } - } break; - case MAP_ZOOM_IN: - { - if (s_pdaActive) - { - // screenScale *= 0.8 - s_screenScale = mul16(0xcccc, s_screenScale); - s_screenScale = max(0x666, s_screenScale); - } - else - { - s32 speed = s_screenScale << s_playerRun; - speed >>= s_playerSlow; - s_screenScale += mul16(speed, s_deltaTime); - } - s_screenScale = min(FIXED(32), s_screenScale); - automap_computeScreenBounds(); - } break; - case MAP_ZOOM_OUT: - { - if (s_pdaActive) - { - // screenScale /= 0.8 - s_screenScale = div16(s_screenScale, 0xcccc); - s_screenScale = min(FIXED(32), s_screenScale); - } - else - { - s32 speed = s_screenScale << s_playerRun; - speed >>= s_playerSlow; - s_screenScale -= mul16(speed, s_deltaTime); - } - s_screenScale = max(0x666, s_screenScale); - automap_computeScreenBounds(); - } break; - case MAP_LAYER_UP: - { - s_mapLayer = min(s_levelState.maxLayer, s_mapLayer + 1); - } break; - case MAP_LAYER_DOWN: - { - s_mapLayer = max(s_levelState.minLayer, s_mapLayer - 1); - } break; - case MAP_ENABLE_AUTOCENTER: - { - s_automapAutoCenter = JTRUE; - } break; - case MAP_DISABLE_AUTOCENTER: - { - s_automapAutoCenter = JFALSE; - } break; - case MAP_TOGGLE_ALL_LAYERS: - { - s_mapShowAllLayers = !s_mapShowAllLayers; - if (!s_pdaActive) - { - if (s_mapShowAllLayers) - { - hud_sendTextMessage(17); - } - else - { - hud_sendTextMessage(18); - } - } - } break; - case MAP_INCR_SECTOR_MODE: - { - s_mapShowSectorMode++; - if (s_mapShowSectorMode >= 3) - { - s_mapShowSectorMode = 0; - } - } break; - case MAP_TELEPORT: - { - // TODO - } break; - } - } - - void automap_disableLock() - { - s_automapLocked = JFALSE; - automap_updateMapData(MAP_DISABLE_AUTOCENTER); // This splits out map position 0 and 1. - } - - void automap_enableLock() - { - s_automapLocked = JTRUE; - } - - void automap_setPdaActive(JBool enable) - { - s_pdaActive = enable; - } - - void automap_draw(u8* framebuffer) - { - u32 dispWidth, dispHeight; - vfb_getResolution(&dispWidth, &dispHeight); - screenDraw_beginLines(dispWidth, dispHeight); - - s_mapXCenterInPixels = dispWidth/2 - 1; - s_mapZCenterInPixels = dispHeight/2 - 1; - s_mapFramebuffer = framebuffer; - automap_drawSectors(); - s_pdaActive = JFALSE; - } - - s32 automap_getLayer() - { - return s_mapLayer; - } - - void automap_setLayer(s32 layer) - { - s_mapLayer = layer; - } - - void automap_drawSectors() - { - if (s_automapAutoCenter && !s_pdaActive) - { - s_mapX0 = s_eyePos.x; - s_mapX1 = s_mapX0; - s_mapZ0 = s_eyePos.z; - s_mapZ1 = s_mapZ0; - } - else - { - s_mapX0 = s_mapX1; - s_mapZ0 = s_mapZ1; - } - - // Compute the screen bounds and map corners. - automap_computeScreenBounds(); - s_mapLeft = s_scrLeftScaled + s_mapX0; - s_mapRight = s_scrRightScaled + s_mapX0; - s_mapBot = s_scrBotScaled + s_mapZ0; - s_mapTop = s_scrTopScaled + s_mapZ0; - - // Draw the sectors. - RSector* sector = s_levelState.sectors; - for (u32 i = 0; i < s_levelState.sectorCount; i++, sector++) - { - if (!s_mapShowAllLayers) - { - s32 layer = sector->layer; - if (layer != s_mapLayer) - { - continue; - } - } - automap_drawSector(sector); - } - - SecObject* player = s_playerObject; - sector = player->sector; - if (!s_automapAutoCenter || s_mapLayer != sector->layer) - { - automap_drawPoint(s_mapX1, s_mapZ1, 6); - } - automap_drawPlayer(s_mapLayer); - if (!s_automapAutoCenter) - { - // Re-center the automap if the player moves. - if (player->posWS.x != s_mapPrevPlayerX || player->posWS.z != s_mapPrevPlayerZ) - { - s_automapAutoCenter = JTRUE; - } - s_mapPrevPlayerX = player->posWS.x; - s_mapPrevPlayerZ = player->posWS.z; - } - } - - void automap_projectPosition(fixed16_16* x, fixed16_16* z) - { - *x -= s_mapX0; - *z -= s_mapZ0; - *x = mul16(*x, s_screenScale); - *z = -mul16(*z, s_screenScale); - - *x = floor16(*x) + s_mapXCenterInPixels; - *z = floor16(*z) + s_mapZCenterInPixels; - } - -#ifdef TFE_ESPBOX - static inline -#endif - void automap_drawPointWithRadius(fixed16_16 x, fixed16_16 z, fixed16_16 r, u8 color) - { - ScreenRect* screenRect = vfb_getScreenRect(VFB_RECT_RENDER); - automap_projectPosition(&x, &z); - fixed16_16 rScreen = mul16(r, s_screenScale); - screen_drawCircle(screenRect, x, z, rScreen, 0x1c7, color, s_mapFramebuffer); - } - -#ifdef TFE_ESPBOX - static inline -#endif - void automap_drawPointWithDirection(fixed16_16 x, fixed16_16 z, angle14_32 angle, fixed16_16 len, u8 color) - { - fixed16_16 x0 = x; - fixed16_16 z0 = z; - - fixed16_16 sinAngle, cosAngle; - sinCosFixed(angle, &sinAngle, &cosAngle); - x0 -= mul16(sinAngle, len) >> 2; - z0 -= mul16(cosAngle, len) >> 2; - fixed16_16 x1 = x0 + mul16(sinAngle, len); - fixed16_16 z1 = z0 + mul16(cosAngle, len); - - // Add 90 degrees to the angle. - sinCosFixed(angle + 0xfff, &sinAngle, &cosAngle); - fixed16_16 x2 = x0 + mul16(sinAngle, len); - fixed16_16 z2 = z0 + mul16(cosAngle, len); - fixed16_16 x3 = x0 - mul16(sinAngle, len); - fixed16_16 z3 = z0 - mul16(cosAngle, len); - - fixed16_16 px1 = x1; - fixed16_16 px2 = x2; - fixed16_16 pz1 = z1; - fixed16_16 pz2 = z2; - automap_projectPosition(&px1, &pz1); - automap_projectPosition(&px2, &pz2); - automap_drawLine(px1, pz1, px2, pz2, color); - - px1 = x1; - px2 = x3; - pz1 = z1; - pz2 = z3; - automap_projectPosition(&px1, &pz1); - automap_projectPosition(&px2, &pz2); - automap_drawLine(px1, pz1, px2, pz2, color); - - px1 = x2; - px2 = x3; - pz1 = z2; - pz2 = z3; - automap_projectPosition(&px1, &pz1); - automap_projectPosition(&px2, &pz2); - automap_drawLine(px1, pz1, px2, pz2, color); - } - -#ifdef TFE_ESPBOX - static inline -#endif - void automap_drawPoint(fixed16_16 x, fixed16_16 z, u8 color) - { - ScreenRect* screenRect = vfb_getScreenRect(VFB_RECT_RENDER); - automap_projectPosition(&x, &z); - screen_drawPoint(screenRect, x, z, color, s_mapFramebuffer); - } - -#ifdef TFE_ESPBOX - static inline -#endif - void automap_drawLine(fixed16_16 x0, fixed16_16 z0, fixed16_16 x1, fixed16_16 z1, u8 color) - { - ScreenRect* screenRect = vfb_getScreenRect(VFB_RECT_RENDER); - screen_drawLine(screenRect, x0, z0, x1, z1, color, s_mapFramebuffer); - } - - void automap_drawWall(RWall* wall, u8 color) - { - vec2_fixed* w0 = wall->w0; - vec2_fixed* w1 = wall->w1; - fixed16_16 x0 = w0->x; - fixed16_16 x1 = w1->x; - fixed16_16 z0 = w0->z; - fixed16_16 z1 = w1->z; - - // The DOS code clips the line here, but it also gets clipped again in the underlying code - no point clipping twice. - automap_projectPosition(&x0, &z0); - automap_projectPosition(&x1, &z1); - automap_drawLine(x0, z0, x1, z1, color); - } - - u8 automap_getWallColor(RWall* wall) - { - u8 color; - if (wall->flags1 & WF1_HIDE_ON_MAP) - { - color = WCOLOR_INVISIBLE; - } - else if (wall->flags1 & WF1_SHOW_AS_LEDGE_ON_MAP) - { - color = WCOLOR_LEDGE; - } - else if (wall->flags1 & WF1_SHOW_AS_DOOR_ON_MAP) - { - color = WCOLOR_DOOR; - } - else if ((wall->flags1 & WF1_SHOW_NORMAL_ON_MAP) || !wall->nextSector) - { - color = WCOLOR_NORMAL; - } - else if (sector_isDoor(wall->sector) || sector_isDoor(wall->nextSector)) - { - color = WCOLOR_DOOR; - } - else if (s_mapShowSectorMode == 2) - { - color = WCOLOR_GRAYED_OUT; - } - else - { - RSector* curSector = wall->sector; - RSector* nextSector = wall->nextSector; - fixed16_16 curFloorHeight = curSector->floorHeight; - fixed16_16 nextFloorHeight = nextSector->floorHeight; - fixed16_16 floorDelta = TFE_Jedi::abs(curFloorHeight - nextFloorHeight); - if (floorDelta >= 0x4000) // 0.25 units - { - color = WCOLOR_LEDGE; - } - else - { - color = WCOLOR_INVISIBLE; - } - } - - return color; - } - - void automap_drawSector(RSector* sector) - { - if (!s_mapShowSectorMode && !(sector->flags1 & SEC_FLAGS1_RENDERED)) - { - return; - } - - RWall* wall = sector->walls; - for (s32 i = 0; i < sector->wallCount; i++, wall++) - { - if (!s_mapShowSectorMode && !wall->seen) - { - continue; - } - - u8 color = automap_getWallColor(wall); - if (color != WCOLOR_INVISIBLE) - { - automap_drawWall(wall, color); - } - } - if (s_mapShowSectorMode) - { - SecObject** objIter = sector->objectList; - for (s32 i = 0; i < sector->objectCount; objIter++) - { - SecObject* obj = *objIter; - while (!obj) - { - objIter++; - obj = *objIter; - } - if (obj) - { - automap_drawObject(obj); - i++; - } - } - } - } - - void automap_drawObject(SecObject* obj) - { - u8 color = MOBJCOLOR_DEFAULT; - if (obj->flags & OBJ_FLAG_NEEDS_TRANSFORM) - { - if (obj->entityFlags & ETFLAG_PROJECTILE) - { - color = MOBJCOLOR_PROJ; - } - else if (obj->entityFlags & ETFLAG_CORPSE) - { - color = MOBJCOLOR_CORPSE; - } - else if (obj->entityFlags & ETFLAG_LANDMINE) - { - color = MOBJCOLOR_LANDMINE; - } - else if (obj->entityFlags & ETFLAG_PICKUP) - { - color = MOBJCOLOR_PICKUP; - } - else if (obj->entityFlags & ETFLAG_SCENERY) - { - color = MOBJCOLOR_SCENERY; - } - - ObjectType type = obj->type; - if (type == OBJ_TYPE_3D || type == OBJ_TYPE_FRAME) - { - if (obj->worldWidth) - { - automap_drawPointWithRadius(obj->posWS.x, obj->posWS.z, obj->worldWidth, color); - } - else - { - automap_drawPoint(obj->posWS.x, obj->posWS.z, color); - } - } - else if (type == OBJ_TYPE_SPRITE) - { - automap_drawPointWithDirection(obj->posWS.x, obj->posWS.z, obj->yaw, MOBJSPRITE_DRAW_LEN, color); - } - } - } - - void automap_drawPlayer(s32 layer) - { - SecObject* player = s_playerObject; - fixed16_16 x0 = player->posWS.x; - fixed16_16 z0 = player->posWS.z; - RSector* sector = player->sector; - - if (sector->layer == layer) - { - fixed16_16 sinYaw, cosYaw; - sinCosFixed(player->yaw, &sinYaw, &cosYaw); - - fixed16_16 x1 = x0 + mul16(sinYaw, FIXED(4)); - fixed16_16 z1 = z0 + mul16(cosYaw, FIXED(4)); - - automap_projectPosition(&x0, &z0); - automap_projectPosition(&x1, &z1); - automap_drawLine(x0, z0, x1, z1, 8); - - fixed16_16 r = mul16(player->worldWidth, s_screenScale); - if (r >= 0x18000) // 1.5 - { - automap_drawPointWithRadius(player->posWS.x, player->posWS.z, player->worldWidth, 7); - } - automap_drawPoint(player->posWS.x, player->posWS.z, 6); - } - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/automap.h b/components/darkforces/tfe/TFE_DarkForces/automap.h deleted file mode 100644 index 8ba6f614..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/automap.h +++ /dev/null @@ -1,52 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces -// Automap functionality -////////////////////////////////////////////////////////////////////// -#include -#include -#include - -namespace TFE_DarkForces -{ - enum MapUpdateID - { - MAP_CENTER_PLAYER = 1, - MAP_MOVE1_UP = 2, - MAP_MOVE1_DN = 3, - MAP_MOVE1_LEFT = 4, - MAP_MOVE1_RIGHT = 5, - MAP_ZOOM_IN = 6, - MAP_ZOOM_OUT = 7, - MAP_LAYER_UP = 8, - MAP_LAYER_DOWN = 9, - MAP_ENABLE_AUTOCENTER = 10, - MAP_DISABLE_AUTOCENTER = 11, - MAP_TOGGLE_ALL_LAYERS = 12, - MAP_INCR_SECTOR_MODE = 13, - MAP_TELEPORT = 14, - MAP_MAX = 14, - }; - - void automap_serialize(Stream* stream); - - void automap_computeScreenBounds(); - void automap_updateMapData(MapUpdateID id); - void automap_resetScale(); - void automap_draw(u8* framebuffer); - void automap_setPdaActive(JBool enable); - - s32 automap_getLayer(); - void automap_setLayer(s32 layer); - void automap_disableLock(); - void automap_enableLock(); - - extern JBool s_pdaActive; - extern JBool s_drawAutomap; - extern JBool s_automapLocked; - extern TFE_Jedi::fixed16_16 s_mapX0; - extern TFE_Jedi::fixed16_16 s_mapX1; - extern TFE_Jedi::fixed16_16 s_mapZ0; - extern TFE_Jedi::fixed16_16 s_mapZ1; - extern s32 s_mapLayer; -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/briefingList.cpp b/components/darkforces/tfe/TFE_DarkForces/briefingList.cpp deleted file mode 100644 index 354a95af..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/briefingList.cpp +++ /dev/null @@ -1,95 +0,0 @@ -#include "briefingList.h" -#include "util.h" -#include -#include -#include -#include -#include - -namespace TFE_DarkForces -{ - static char* s_buffer = nullptr; - - void briefingList_freeBuffer() - { - s_buffer = nullptr; - } - - // FileStream and TFE_Parser are used to read the file and parse out lines. - // However all other processing matches the original DOS version. - s32 parseBriefingList(BriefingList* briefingList, const char* filename) - { - FilePath path; - if (!TFE_Paths::getFilePath(filename, &path)) { return 0; } - - FileStream file; - if (!file.open(&path, Stream::MODE_READ)) { return 0; } - - size_t size = file.getSize(); - s_buffer = (char*)game_realloc(s_buffer, size); - if (!s_buffer) { return 0; } - - file.readBuffer(s_buffer, (u32)size); - file.close(); - - TFE_Parser parser; - parser.addCommentString("#"); - parser.init(s_buffer, size); - - size_t bufferPos = 0; - const char* fileData = parser.readLine(bufferPos); - - s32 v0 = 0, v1 = 0; - s32 count = sscanf(fileData, "BRF %d.%d", &v0, &v1); - if (count != 2 || v0 != 1 || v1 != 0) - { - TFE_System::logWrite(LOG_ERROR, "Briefing List", "Invalid version: %d.%d. Only version 1.0 is supported.", v0, v1); - return 0; - } - - fileData = parser.readLine(bufferPos); - s32 msgCount; - count = sscanf(fileData, "BRIEFS %d", &msgCount); - if (count != 1) - { - TFE_System::logWrite(LOG_ERROR, "Briefing List", "Cannot parse briefing count."); - return 0; - } - - briefingList->count = msgCount; - briefingList->briefing = (BriefingInfo*)game_alloc(msgCount * sizeof(BriefingInfo)); - BriefingInfo* info = briefingList->briefing; - for (s32 i = 0; i < msgCount; i++, info++) - { - fileData = parser.readLine(bufferPos); - if (!fileData) - { - TFE_System::logWrite(LOG_ERROR, "Game Message", "The message count is incorrect!"); - return 0; - } - - char mission[32]; - char archive[32]; - char bgAnim[32]; - char palette[32]; - if (sscanf(fileData, "LEV: %s LFD: %s ANI: %s PAL: %s", mission, archive, bgAnim, palette) != 4) - { - TFE_System::logWrite(LOG_ERROR, "Briefing List", "Error reading briefing file %s on line: >>> %s", filename, fileData); - return 0; - } - else - { - __strlwr(mission); - __strlwr(archive); - __strlwr(bgAnim); - __strlwr(palette); - - strcpy(info->mission, mission); - strcpy(info->archive, archive); - strcpy(info->bgAnim, bgAnim); - strcpy(info->palette, palette); - } - } // for (s32 i = 0; i < msgCount; i++, info++) - return 1; - } -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/briefingList.h b/components/darkforces/tfe/TFE_DarkForces/briefingList.h deleted file mode 100644 index e51867fb..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/briefingList.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces Game Message -// This handles HUD messages, local messages, etc. -////////////////////////////////////////////////////////////////////// -#include -#include - -namespace TFE_DarkForces -{ - enum { BRIEF_STR_LEN = 13 }; - - struct BriefingInfo - { - char mission[BRIEF_STR_LEN]; - char archive[BRIEF_STR_LEN]; - char bgAnim[BRIEF_STR_LEN]; - char palette[BRIEF_STR_LEN]; - }; - struct BriefingList - { - s32 count; - BriefingInfo* briefing; - }; - - void briefingList_freeBuffer(); - s32 parseBriefingList(BriefingList* briefingList, const char* filename); -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/cheats.cpp b/components/darkforces/tfe/TFE_DarkForces/cheats.cpp deleted file mode 100644 index 92f5be8c..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/cheats.cpp +++ /dev/null @@ -1,126 +0,0 @@ -#include - -#include "cheats.h" -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - // In the DOS code, the cheats were encoded by taking the character and subtracting 0x3c (60) before storing in the executable. - // For TFE, I don't see the point - there is no hiding the cheats now with the source code freely available. :)- - static const char* c_cheatStrings[] = - { - "CDS", - "NTFH", - "POGO", - "RANDY", - "IMLAME", - "POSTAL", - "DATA", - "BUG", - "REDLITE", - "SECBASE", - "TALAY", - "SEWERS", - "TESTBASE", - "GROMAS", - "DTENTION", - "RAMSHED", - "ROBOTICS", - "NARSHADA", - "JABSHIP", - "IMPCITY", - "FUELSTAT", - "EXECUTOR", - "ARC", - "SKIP", - "BRADY", - "UNLOCK", - "MAXOUT", - // New Cheats for TFE. - "FLY", - "NOCLIP", - "TESTER", - }; - - char s_cheatString[32] = { 0 }; - s32 s_cheatCharIndex = 0; - s32 s_cheatInputCount = 0; - - CheatID cheat_getIDFromString(const char* cheatStr) - { - if (!cheatStr || strlen(cheatStr) <= 2) - { - return CHEAT_NONE; - } - - s32 maxMatchIndex = 0; - const size_t cheatCount = TFE_ARRAYSIZE(c_cheatStrings); - for (size_t cheatIndex = 0; cheatIndex < cheatCount; cheatIndex++) - { - if (strcasecmp(cheatStr + 2, c_cheatStrings[cheatIndex]) == 0) - { - return CheatID(cheatIndex + 1); - } - } - return CHEAT_NONE; - } - - CheatID cheat_getID() - { - if (!s_cheatCharIndex) - { - return CHEAT_NONE; - } - - s32 maxMatchIndex = 0; - const size_t cheatCount = TFE_ARRAYSIZE(c_cheatStrings); - for (size_t cheatIndex = 0; cheatIndex < cheatCount; cheatIndex++) - { - const char* srcCheatStr = c_cheatStrings[cheatIndex]; - for (s32 c = 0; c <= s_cheatCharIndex; c++) - { - if (srcCheatStr[c]) - { - if (srcCheatStr[c] != s_cheatString[c]) - { - break; - } - } - else if (s_cheatString[c]) - { - break; - } - - // If the strings match to the end, clear out the data and return the cheat ID. - maxMatchIndex = max(maxMatchIndex, c + 1); - if (!srcCheatStr[c + 1]) - { - cheat_clearData(); - return CheatID(cheatIndex + 1); - } - } - } - - // If we match don't match up to this point, then clear out the data. - if (maxMatchIndex != s_cheatCharIndex) - { - cheat_clearData(); - } - return CHEAT_NONE; - } - - const char* cheat_getStringFromID(CheatID id) - { - if (id <= CHEAT_NONE || id >= CHEAT_COUNT) { return nullptr; } - return c_cheatStrings[id - 1]; - } - - void cheat_clearData() - { - s_cheatInputCount = 0; - s_cheatString[0] = 0; - s_cheatCharIndex = 0; - } -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/cheats.h b/components/darkforces/tfe/TFE_DarkForces/cheats.h deleted file mode 100644 index d69413b6..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/cheats.h +++ /dev/null @@ -1,54 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces Cheats -////////////////////////////////////////////////////////////////////// -#include - -namespace TFE_DarkForces -{ - enum CheatID - { - CHEAT_NONE = 0, - CHEAT_LACDS, - CHEAT_LANTFH, - CHEAT_LAPOGO, - CHEAT_LARANDY, - CHEAT_LAIMLAME, - CHEAT_LAPOSTAL, - CHEAT_LADATA, - CHEAT_LABUG, - CHEAT_LAREDLITE, - CHEAT_LASECBASE, - CHEAT_LATALAY, - CHEAT_LASEWERS, - CHEAT_LATESTBASE, - CHEAT_LAGROMAS, - CHEAT_LADTENTION, - CHEAT_LARAMSHED, - CHEAT_LAROBOTICS, - CHEAT_LANARSHADA, - CHEAT_LAJABSHIP, - CHEAT_LAIMPCITY, - CHEAT_LAFUELSTAT, - CHEAT_LAEXECUTOR, - CHEAT_LAARC, - CHEAT_LASKIP, - CHEAT_LABRADY, - CHEAT_LAUNLOCK, - CHEAT_LAMAXOUT, - // New Cheats for TFE. - CHEAT_LAFLY, - CHEAT_LANOCLIP, - CHEAT_LATESTER, - CHEAT_COUNT - }; - - CheatID cheat_getID(); - CheatID cheat_getIDFromString(const char* cheatStr); - const char* cheat_getStringFromID(CheatID id); - void cheat_clearData(); - - extern char s_cheatString[32]; - extern s32 s_cheatCharIndex; - extern s32 s_cheatInputCount; -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/config.cpp b/components/darkforces/tfe/TFE_DarkForces/config.cpp deleted file mode 100644 index 7c9f2abd..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/config.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include "config.h" -#include -#include - -namespace TFE_DarkForces -{ - GameConfig s_config = - { - JTRUE, // headwave - JTRUE, // wpnAutoMount - JFALSE, // mouseTurnEnabled - JTRUE, // mouseLookEnabled - JFALSE, // superShield - JTRUE, // showUI - }; - - void config_startup() - { - // Read Config - } - - void config_shutdown() - { - // Write Config - } -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/config.h b/components/darkforces/tfe/TFE_DarkForces/config.h deleted file mode 100644 index 007635b6..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/config.h +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces Config -// Replacement for the Jedi Config for TFE. -////////////////////////////////////////////////////////////////////// -#include -#include -#include - -namespace TFE_DarkForces -{ - struct GameConfig - { - JBool headwave; - JBool wpnAutoMount; - JBool mouseTurnEnabled; - JBool mouseLookEnabled; - JBool superShield; - JBool showUI; - }; - - void config_startup(); - void config_shutdown(); - - extern GameConfig s_config; -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/darkForcesMain.cpp b/components/darkforces/tfe/TFE_DarkForces/darkForcesMain.cpp deleted file mode 100644 index d95fc9fb..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/darkForcesMain.cpp +++ /dev/null @@ -1,1384 +0,0 @@ -#include - -#include "darkForcesMain.h" -#include "agent.h" -#include "automap.h" -#include "config.h" -#include "briefingList.h" -#include "gameMessage.h" -#include "gameMusic.h" -#include "hud.h" -#include "item.h" -#include "mission.h" -#include "player.h" -#include "pickup.h" -#include "projectile.h" -#include "random.h" -#include "time.h" -#include "weapon.h" -#include "vueLogic.h" -#include "GameUI/menu.h" -#include "GameUI/agentMenu.h" -#include "GameUI/escapeMenu.h" -#include "GameUI/missionBriefing.h" -#include "GameUI/pda.h" -#include "Landru/lsystem.h" -#include "Landru/lsound.h" -#include "Landru/lmusic.h" -#include "Landru/cutscene_film.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// Add texture callbacks. -#include - -using namespace TFE_Memory; -using namespace TFE_Input; - -namespace TFE_DarkForces -{ - ///////////////////////////////////////////// - // Constants - ///////////////////////////////////////////// - static const char* c_gobFileNames[] = - { - "DARK.GOB", - "SOUNDS.GOB", - "TEXTURES.GOB", - "SPRITES.GOB", - }; - - enum GameConstants - { - MAX_MOD_LFD = 16, - }; - - enum GameState - { - GSTATE_STARTUP_CUTSCENES = 0, - GSTATE_AGENT_MENU, - GSTATE_CUTSCENE, - GSTATE_BRIEFING, - GSTATE_MISSION, - GSTATE_COUNT - }; - - enum GameMode - { - GMODE_END = -1, - GMODE_CUTSCENE = 0, - GMODE_BRIEFING = 1, - GMODE_MISSION = 2, - }; - - struct CutsceneData - { - s32 levelIndex; - GameMode nextGameMode; - s32 cutscene; - }; - - static CutsceneData s_cutsceneData[] = - { - { 1, GMODE_CUTSCENE, 100 }, - { 1, GMODE_BRIEFING, 0 }, - { 1, GMODE_MISSION, 0 }, - { 1, GMODE_CUTSCENE, 150 }, - - { 2, GMODE_CUTSCENE, 200 }, - { 2, GMODE_BRIEFING, 0 }, - { 2, GMODE_MISSION, 0 }, - { 2, GMODE_CUTSCENE, 250 }, - - { 3, GMODE_CUTSCENE, 300 }, - { 3, GMODE_BRIEFING, 0 }, - { 3, GMODE_MISSION, 0 }, - { 3, GMODE_CUTSCENE, 350 }, - - { 4, GMODE_CUTSCENE, 400 }, - { 4, GMODE_BRIEFING, 0 }, - { 4, GMODE_MISSION, 0 }, - { 4, GMODE_CUTSCENE, 450 }, - - { 5, GMODE_CUTSCENE, 500 }, - { 5, GMODE_BRIEFING, 0 }, - { 5, GMODE_MISSION, 0 }, - { 5, GMODE_CUTSCENE, 550 }, - - { 6, GMODE_CUTSCENE, 600 }, - { 6, GMODE_BRIEFING, 0 }, - { 6, GMODE_MISSION, 0 }, - { 6, GMODE_CUTSCENE, 650 }, - - { 7, GMODE_CUTSCENE, 700 }, - { 7, GMODE_BRIEFING, 0 }, - { 7, GMODE_MISSION, 0 }, - { 7, GMODE_CUTSCENE, 750 }, - - { 8, GMODE_CUTSCENE, 800 }, - { 8, GMODE_BRIEFING, 0 }, - { 8, GMODE_MISSION, 0 }, - { 8, GMODE_CUTSCENE, 850 }, - - { 9, GMODE_CUTSCENE, 900 }, - { 9, GMODE_BRIEFING, 0 }, - { 9, GMODE_MISSION, 0 }, - { 9, GMODE_CUTSCENE, 950 }, - - { 10, GMODE_CUTSCENE,1000 }, - { 10, GMODE_BRIEFING, 0 }, - { 10, GMODE_MISSION, 0 }, - { 10, GMODE_CUTSCENE,1050 }, - - { 11, GMODE_CUTSCENE,1100 }, - { 11, GMODE_BRIEFING, 0 }, - { 11, GMODE_MISSION, 0 }, - { 11, GMODE_CUTSCENE,1150 }, - - { 12, GMODE_CUTSCENE,1200 }, - { 12, GMODE_BRIEFING, 0 }, - { 12, GMODE_MISSION, 0 }, - { 12, GMODE_CUTSCENE,1250 }, - - { 13, GMODE_CUTSCENE,1300 }, - { 13, GMODE_BRIEFING, 0 }, - { 13, GMODE_MISSION, 0 }, - { 13, GMODE_CUTSCENE,1350 }, - - { 14, GMODE_CUTSCENE,1400 }, - { 14, GMODE_BRIEFING, 0 }, - { 14, GMODE_MISSION, 0 }, - { 14, GMODE_CUTSCENE,1450 }, - { 14, GMODE_CUTSCENE,1500 }, // game ending. - // Game flow end (restart). - { -1, GMODE_END, -1 } - }; - - ///////////////////////////////////////////// - // Internal State - ///////////////////////////////////////////// - struct RunGameState - { - s32 argCount = 0; - char* args[64] = { 0 }; - - JBool cutscenesEnabled = JTRUE; - JBool localMsgLoaded = JFALSE; - s32 startLevel = 0; - GameState state = GSTATE_STARTUP_CUTSCENES; - s32 levelIndex = 0; - s32 cutsceneIndex = 0; - JBool abortLevel = JFALSE; - }; - struct SharedGameState - { - GameMessages localMessages = {}; - GameMessages hotKeyMessages = {}; - TextureData* diskErrorImg = nullptr; - Font* swFont1 = nullptr; - Font* mapNumFont = nullptr; - SoundSourceId screenShotSndSrc = NULL_SOUND; - BriefingList briefingList = { 0 }; - JBool gameStarted = JFALSE; - - Task* loadMissionTask = nullptr; - CutsceneState* cutsceneList = nullptr; - char customGobName[256] = ""; - LangHotkeys langKeys; - }; - static RunGameState s_runGameState = {}; - static SharedGameState s_sharedState = {}; - - ///////////////////////////////////////////// - // Forward Declarations - ///////////////////////////////////////////// - void printGameInfo(); - void processCommandLineArgs(s32 argCount, const char* argv[], char* startLevel); - void enableCutscenes(JBool enable); - void loadCustomGob(const char* gobName); - void setInitialLevel(const char* levelName); - s32 loadLocalMessages(); - void buildSearchPaths(); - void openGobFiles(); - void gameStartup(); - void loadAgentAndLevelData(); - void startNextMode(); - void freeAllMidi(); - void pauseLevelSound(); - void resumeLevelSound(); - - ///////////////////////////////////////////// - // API - ///////////////////////////////////////////// - - // This is the equivalent of the initial part of main() in Dark Forces DOS. - // This part loads and sets up the game. - bool DarkForces::runGame(s32 argCount, const char* argv[], Stream* stream) - { - // TFE: Initially disable the reticle. - reticle_enable(false); - - if (!stream) - { - // Normal start. - s_runGameState.argCount = min(64, argCount); - for (s32 i = 0; i < s_runGameState.argCount; i++) - { - if (i == 0) - { - // No need to store the executable path, just put in a dummy value so everything else works as-is. - s_runGameState.args[i] = (char*)game_alloc(strlen("ExeName") + 1); - strcpy(s_runGameState.args[i], "ExeName"); - } - else - { - s_runGameState.args[i] = (char*)game_alloc(strlen(argv[i]) + 1); - strcpy(s_runGameState.args[i], argv[i]); - } - } - } - else - { - // Start from save game. - SERIALIZE(SaveVersionInit, s_runGameState.argCount, 0); - for (s32 i = 0; i < s_runGameState.argCount; i++) - { - u32 length; - SERIALIZE(SaveVersionInit, length, 0); - - s_runGameState.args[i] = (char*)game_alloc(length + 1); - SERIALIZE_BUF(SaveVersionInit, s_runGameState.args[i], length); - s_runGameState.args[i][length] = 0; - } - - argCount = s_runGameState.argCount; - argv = (const char**)s_runGameState.args; - } - - char startLevel[TFE_MAX_PATH] = ""; - bitmap_setAllocator(s_gameRegion); - - printGameInfo(); - buildSearchPaths(); - processCommandLineArgs(argCount, argv, startLevel); - loadLocalMessages(); - openGobFiles(); - - // Sound is initialized before the task system. - sound_open(s_gameRegion); - - TFE_Jedi::task_setDefaults(); - TFE_Jedi::task_setMinStepInterval(1.0f / f32(TICKS_PER_SECOND)); - TFE_Jedi::setupInitCameraAndLights(); - config_startup(); - gameStartup(); - loadAgentAndLevelData(); - lsystem_init(); - - renderer_init(); - - // Handle start level - setInitialLevel(startLevel); - - // TFE Specific - agentMenu_load(&s_sharedState.langKeys); - escapeMenu_load(&s_sharedState.langKeys); - // Add texture callbacks. - renderer_addHudTextureCallback(TFE_Jedi::level_getLevelTextures); - renderer_addHudTextureCallback(TFE_Jedi::level_getObjectTextures); - - // Deserialize. - if (stream) - { - SERIALIZE(SaveVersionInit, s_runGameState.cutscenesEnabled, JTRUE); - SERIALIZE(SaveVersionInit, s_runGameState.localMsgLoaded, JFALSE); - SERIALIZE(SaveVersionInit, s_runGameState.startLevel, 0); - SERIALIZE(SaveVersionInit, s_runGameState.state, GSTATE_STARTUP_CUTSCENES); - SERIALIZE(SaveVersionInit, s_runGameState.levelIndex, 0); - SERIALIZE(SaveVersionInit, s_runGameState.cutsceneIndex, 0); - SERIALIZE(SaveVersionInit, s_runGameState.abortLevel, 0); - } - - s_sharedState.gameStarted = JTRUE; - sound_setLevelStart(); - return true; - } - - void DarkForces::exitGame() - { - if (s_sharedState.gameStarted) - { - saveLevelStatus(); - } - freeAllMidi(); - - gameMessage_freeBuffer(); - briefingList_freeBuffer(); - cutsceneList_freeBuffer(); - cutsceneFilm_reset(); - lsystem_destroy(); - bitmap_clearAll(); - - // Clear paths and archives. - TFE_Paths::clearSearchPaths(); - TFE_Paths::clearLocalArchives(); - task_shutdown(); - - // Sound is destroyed after the task system. - sound_close(); - config_shutdown(); - - // TFE Specific - // Reset state - actor_exitState(); - weapon_resetState(); - renderer_resetState(); - agentMenu_resetState(); - menu_resetState(); - pda_resetState(); - escapeMenu_resetState(); - vue_resetState(); - lsystem_destroy(); - hud_reset(); - - // TFE - TFE_Sprite_Jedi::freeAll(); - TFE_Model_Jedi::freeAll(); - reticle_enable(false); - texturepacker_reset(); - - TFE_MidiPlayer::resume(); - TFE_Audio::resume(); - - // Reset state. - s_sharedState = {}; - s_runGameState = {}; - } - - void DarkForces::pauseGame(bool pause) - { - mission_pause(pause ? JTRUE : JFALSE); - } - - bool DarkForces::isPaused() - { - return s_gamePaused; - } - - void DarkForces::pauseSound(bool pause) - { - if (pause) { pauseLevelSound(); } - else { resumeLevelSound(); } - } - - void DarkForces::restartMusic() - { - gameMusic_setState(MUS_STATE_NULLSTATE); - ImReintializeMidi(); - gameMusic_setState(MUS_STATE_STALK); - } - - void handleLevelComplete() - { - s32 completedLevelIndex = agent_getLevelIndex(); - u8 diff = s_agentData[s_agentId].difficulty; - - // Save the level completion, inventory and other stats into the agent data and then save to disk. - agent_saveLevelCompletion(diff, completedLevelIndex); - agent_updateAgentSavedData(); - agent_saveInventory(s_agentId, completedLevelIndex + 1); - agent_setNextLevelByIndex(completedLevelIndex + 1); - } - - void saveLevelStatus() - { - if (s_levelComplete) - { - handleLevelComplete(); - } - else - { - agent_updateAgentSavedData(); - } - } - - bool DarkForces::canSave() - { - return s_runGameState.state == GSTATE_MISSION; - } - - void DarkForces::getLevelName(char* name) - { - const char* levelName = agent_getLevelDisplayName(); - if (levelName) - { - strcpy(name, levelName); - } - else - { - name[0] = 0; - } - } - - void skipToLevelNextScene(s32 index) - { - if (!index) { return; } - - s_invalidLevelIndex = JTRUE; - for (s32 i = 0; i < TFE_ARRAYSIZE(s_cutsceneData); i++) - { - if (s_cutsceneData[i].levelIndex >= 0 && s_cutsceneData[i].levelIndex == index && s_cutsceneData[i].nextGameMode == GMODE_BRIEFING) - { - s_runGameState.cutsceneIndex = i - 1; - s_invalidLevelIndex = JFALSE; - break; - } - } - } - - void DarkForces::getModList(char* modList) - { - strcpy(modList, s_sharedState.customGobName); - } - - /**********The basic structure of the Dark Forces main loop is as follows:*************** - while (1) // <- This will be replaced by the function call from the main TFE loop. - { - // TFE: This becomes a game state in TFE - where runAgentMenu() gets an update function - it can't loop forever. - s32 levelIndex = runAgentMenu(); <- this loops internally until complete and returns the level to load. - updateAgentSavedData(); // handle any agent changes. - - // Invalid level index just maps back to the runAgentMenu(). - if (levelIndex <= 0) { continue; } // <- This becomes a return in TFE, back off and try again. - - // Then we go through the list of cutscenes, looking for the first instance that matches our desired level. - s32 levelDataIndex; // <- this is the index into the cutscene list. - for (s32 i = 0; ; i++) - { - if (cutsceneData[i].levelIndex >= 0 && s_agentLevelData[n].levelIndex == levelIndex) - { - levelDataIndex = i; - break; - } - } - // Then do some init setup for the next level ahead of time; the actual loading will happen after the cutscenes and mission briefing. - setLevelByIndex(levelIndex); - - // The inner most loop - this cycles through the cutscene entries, each of which lists the game mode. - // TFE: Again this becomes a game state, where each iteration through this loop is from a single function call into loopGame(). - while (!s_invalidLevelIndex && !s_abortLevel) - { - GameMode mode = s_agentLevelData[levelDataIndex].nextGameMode; - switch (mode) - { - case GMODE_ERROR: - // Error out. - break; - case GMODE_CUTSCENE: - // TFE: Cutscene playback becomes a state. - // Play the cutscene - levelDataIndex++; // <- next loop, this goes to the next cutscene or instruction. - break; - case GMODE_BRIEFING: - // TFE: Briefing becomes a state. - // Handle the mission briefing. - levelDataIndex++; // <- next loop, this goes to the next cutscene or instruction. - break; - case GMODE_MISSION: - // TFE: In Mission becomes a state, but here the Task System will take up the slack (which will act very similarly to the original game). - // Create the loadMission task, which will then create the main task, etc. - // Start the level music. - // Read saved game data for this agent and this level. - // Launch the level load task. - // After returning from the level load task, stop the music. - // If not complete set abortLevel to true (which breaks out of this inner loop) otherwise - - // Save the game state and level completion info to disk. - levelDataIndex++; // <- next loop, this goes to the next cutscene or instruction. - levelIndex++; - setNextLevelByIndex(levelIndex); // <- prepares the next level for when we get to it after the cutscenes and briefing. - break; - } - } // Inner Loop - } // Outer Loop - ****************************************************/ - void DarkForces::loopGame() - { - updateTime(); - - switch (s_runGameState.state) - { - case GSTATE_STARTUP_CUTSCENES: - { - s_runGameState.state = GSTATE_CUTSCENE; - s_invalidLevelIndex = JTRUE; - if (s_runGameState.cutscenesEnabled && !s_runGameState.startLevel) - { - cutscene_play(10); - } - else - { - startNextMode(); - } - } break; - case GSTATE_AGENT_MENU: - { - bool levelSelected = false; -#ifdef TFE_ESPBOX - agentMenu_load(&s_sharedState.langKeys); // no-op if the frames are already loaded. -#endif - if (s_runGameState.startLevel) - { - s_runGameState.abortLevel = JFALSE; - s_runGameState.levelIndex = s_runGameState.startLevel; - s_runGameState.startLevel = 0; - levelSelected = true; - } - else if (!agentMenu_update(&s_runGameState.levelIndex)) - { - agent_updateAgentSavedData(); - levelSelected = true; - } - - if (levelSelected) - { - s_invalidLevelIndex = JTRUE; - for (s32 i = 0; i < TFE_ARRAYSIZE(s_cutsceneData); i++) - { - if (s_cutsceneData[i].levelIndex >= 0 && s_cutsceneData[i].levelIndex == s_runGameState.levelIndex) - { - s_runGameState.cutsceneIndex = i; - s_invalidLevelIndex = JFALSE; - break; - } - } - - lmusic_reset(); - s_runGameState.abortLevel = JFALSE; - agent_setNextLevelByIndex(s_runGameState.levelIndex); - startNextMode(); - } - } break; - case GSTATE_CUTSCENE: - { - if (cutscene_update()) - { - if (TFE_A11Y::cutsceneCaptionsEnabled()) { TFE_A11Y::drawCaptions(); } - } - else - { - s_runGameState.cutsceneIndex++; - if (s_cutsceneData[s_runGameState.cutsceneIndex].nextGameMode == GMODE_END) - { - s_runGameState.state = GSTATE_AGENT_MENU; - s_invalidLevelIndex = JTRUE; - } - else - { - startNextMode(); - } - TFE_A11Y::clearCaptions(); - } - } break; - case GSTATE_BRIEFING: - { - s32 skill; - JBool abort; - lmusic_reset(); // Fix a Dark Forces bug where music won't play when entering a cutscene again without restarting. - if (!missionBriefing_update(&skill, &abort)) - { - missionBriefing_cleanup(); - TFE_Input::clearAccumulatedMouseMove(); - - if (abort) - { - s_invalidLevelIndex = JTRUE; - s_runGameState.cutsceneIndex--; - } - else - { - s_agentData[s_agentId].difficulty = skill; - s_runGameState.cutsceneIndex++; - } - startNextMode(); - } - } break; - case GSTATE_MISSION: - { - // At this point the mission has already been launched. - // The task system will take over. Basically every frame we just check to see if there are any tasks running. - if (task_getCount()) - { - if (!s_gamePaused && TFE_A11Y::gameplayCaptionsEnabled()) { TFE_A11Y::drawCaptions(); } - } - else - { - // We have returned from the mission tasks. - renderer_reset(); - gameMusic_stop(); - sound_levelStop(); - agent_levelEndTask(); - lmusic_reset(); // Fix a Dark Forces bug where music won't play when entering a cutscene again without restarting. - pda_cleanup(); - - // Reset - TFE_Jedi::renderer_setType(RENDERER_SOFTWARE); - TFE_Jedi::render_setResolution(); - TFE_Jedi::renderer_setLimits(); - - // TFE - reticle_enable(false); - - if (!s_levelComplete) - { - s_runGameState.abortLevel = JTRUE; - s_runGameState.cutsceneIndex--; - } - else - { - s_runGameState.cutsceneIndex++; - handleLevelComplete(); - } - - startNextMode(); - - region_clear(s_levelRegion); - bitmap_clearLevelData(); - bitmap_setAllocator(s_gameRegion); - level_freeAllAssets(); - TFE_A11Y::clearCaptions(); - } - } break; - } - } - - void loadCutsceneList() - { - s_sharedState.cutsceneList = cutsceneList_load("cutscene.lst"); - cutscene_init(s_sharedState.cutsceneList); - } - - void freeAllMidi() - { - gameMusic_stop(); - } - - void pauseLevelSound() - { - TFE_MidiPlayer::pause(); - TFE_Audio::pause(); - } - - void resumeLevelSound() - { - TFE_MidiPlayer::resume(); - TFE_Audio::resume(); - } - - void clearBufferedSound() - { - TFE_Audio::bufferedAudioClear(); - } - - void startNextMode() - { - if (s_invalidLevelIndex || s_runGameState.abortLevel) - { - s_runGameState.state = GSTATE_AGENT_MENU; - return; - } - - GameMode mode = s_cutsceneData[s_runGameState.cutsceneIndex].nextGameMode; - switch (mode) - { - case GMODE_END: - { - s_runGameState.cutsceneIndex = 0; - s_invalidLevelIndex = JTRUE; - startNextMode(); - } break; - case GMODE_CUTSCENE: - { - if (s_runGameState.cutscenesEnabled && cutscene_play(s_cutsceneData[s_runGameState.cutsceneIndex].cutscene)) - { - s_runGameState.state = GSTATE_CUTSCENE; - } - else - { - s_runGameState.cutsceneIndex++; - startNextMode(); - } - } break; - case GMODE_BRIEFING: - { - BriefingInfo* brief = nullptr; - if (s_runGameState.cutscenesEnabled) - { - const char* levelName = agent_getLevelName(); - s32 briefingIndex = 0; - for (s32 i = 0; i < s_sharedState.briefingList.count; i++) - { - if (strcasecmp(levelName, s_sharedState.briefingList.briefing[i].mission) == 0) - { - briefingIndex = i; - break; - } - } - - s32 skill = (s32)s_agentData[s_agentId].difficulty; - brief = &s_sharedState.briefingList.briefing[briefingIndex]; - if (brief) - { - missionBriefing_start(brief->archive, brief->bgAnim, levelName, brief->palette, skill, &s_sharedState.langKeys); - s_runGameState.state = GSTATE_BRIEFING; - } - } - - if (!brief) - { - s_runGameState.cutsceneIndex++; - startNextMode(); - } - } break; - case GMODE_MISSION: - { -#ifdef TFE_ESPBOX - // Cutscene/menu sounds and the agent menu images are not needed during a - // mission; free them so the level fits in memory (reloaded on demand). - lSoundDestroy(); - lSoundInit(); - agentMenu_freeFrames(); -#endif - sound_levelStart(); - - bitmap_setAllocator(s_levelRegion); - actor_clearState(); - - task_reset(); - inf_clearState(); - s_sharedState.loadMissionTask = createTask("start mission", mission_startTaskFunc, JTRUE); - mission_setLoadMissionTask(s_sharedState.loadMissionTask); - - s32 levelIndex = agent_getLevelIndex(); - gameMusic_start(levelIndex); - - agent_setLevelComplete(JFALSE); - agent_readSavedDataForLevel(s_agentId, levelIndex); - - // The load mission task should begin immediately once the Task System updates, - // so launchCurrentTask() is not required here. - // In the original, the task system would simply loop here. - s_runGameState.state = GSTATE_MISSION; - } - } - } - - ///////////////////////////////////////////// - // Internal Implementation - ///////////////////////////////////////////// - void printGameInfo() - { - TFE_System::logWrite(LOG_MSG, "Game", "Dark Forces Version: %d.%d (Build %d)", 1, 0, 1); - } - - // Note: not all command line arguments have been brought over from the DOS version. - // Many no longer make sense and in some cases will always be available (such as screenshots). - void processCommandLineArgs(s32 argCount, const char* argv[], char* startLevel) - { - s_sharedState.customGobName[0] = 0; - - for (s32 i = 0; i < argCount; i++) - { - const char* arg = argv[i]; - char c = arg[0]; - - if (c == '-' || c == '/' || c == '+') - { - c = arg[1]; - if (c == 'c' || c == 'C') - { - enableCutscenes(arg[2] == '1' ? JTRUE : JFALSE); - } - else if ((c == 'l' || c == 'L') && arg[2]) - { - strcpy(startLevel, arg + 2); - } - else if (c == 'u' || c == 'U') - { - loadCustomGob(arg + 2); - } - } - } - - // TFE: Support drag and drop. - if (argCount == 2) - { - const char* arg = argv[1]; - if (arg && arg[0] && arg[0] != '-') - { - const size_t len = strlen(arg); - const char* ext = len > 3 ? &arg[len - 3] : nullptr; - if (ext && strcasecmp(ext, "zip") == 0) - { - // Next check to see if the path is already in the local paths. - char path[TFE_MAX_PATH]; - char fileName[TFE_MAX_PATH]; - size_t len = strlen(arg); - size_t lastSlash = 0; - for (size_t i = 0; i < len; i++) - { - if (arg[i] == '\\' || arg[i] == '/') - { - lastSlash = i; - } - } - memcpy(path, arg, lastSlash + 1); - memcpy(fileName, &arg[lastSlash + 1], len - lastSlash - 1); - - TFE_Paths::fixupPathAsDirectory(path); - TFE_Paths::addAbsoluteSearchPath(path); - TFE_System::logWrite(LOG_MSG, "DarkForces", "Drag and Drop Mod File: '%s'; Path: '%s'", fileName, path); - - loadCustomGob(fileName); - } - } - } - } - - void enableCutscenes(JBool enable) - { - s_runGameState.cutscenesEnabled = enable; - } - - void setInitialLevel(const char* levelName) - { - s_runGameState.startLevel = 0; - - if (!levelName || levelName[0] == 0) { return; } - s_runGameState.startLevel = agent_getLevelIndexFromName(levelName); - } - - void loadCustomGob(const char* gobName) - { - FilePath archivePath; - s32 lfdIndex[MAX_MOD_LFD]; - char lfdName[MAX_MOD_LFD][TFE_MAX_PATH]; - char briefingName[TFE_MAX_PATH]; - s32 lfdCount = 0; - s32 briefingIndex = -1; - - strcpy(s_sharedState.customGobName, gobName); - - if (TFE_Paths::getFilePath(gobName, &archivePath)) - { - // Is this really a gob? - const size_t len = strlen(gobName); - const char* ext = &gobName[len - 3]; - if (strcasecmp(ext, "zip") == 0 || strcasecmp(ext, "pk3") == 0) - { - // In the case of a zip file, we want to extract the GOB into an in-memory format and use that directly. - ZipArchive zipArchive; - if (zipArchive.open(archivePath.path)) - { - s32 gobIndex = -1; - const u32 count = zipArchive.getFileCount(); - for (u32 i = 0; i < count; i++) - { - const char* name = zipArchive.getFileName(i); - const size_t nameLen = strlen(name); - const char* zext = &name[nameLen - 3]; - if (strcasecmp(zext, "gob") == 0) - { - // Avoid MacOS references, they aren't real files. - char gobFileName[TFE_MAX_PATH]; - FileUtil::getFileNameFromPath(name, gobFileName, true); - if (gobFileName[0] != '.' || gobFileName[1] != '_') - { - gobIndex = i; - } - } - else if (strcasecmp(zext, "lfd") == 0 && lfdCount < MAX_MOD_LFD) - { - if (strstr(name, "brief") || strstr(name, "BRIEF")) - { - briefingIndex = i; - } - else - { - lfdIndex[lfdCount++] = i; - } - } - } - - // If there is only 1 LFD, assume it is mission briefings. - if (lfdCount == 1 && briefingIndex < 0) - { - briefingIndex = lfdIndex[0]; - lfdCount = 0; - } - - if (gobIndex >= 0) - { - u32 bufferLen = (u32)zipArchive.getFileLength(gobIndex); - u8* buffer = (u8*)malloc(bufferLen); - zipArchive.openFile(gobIndex); - zipArchive.readFile(buffer, bufferLen); - zipArchive.closeFile(); - - GobMemoryArchive* gobArchive = new GobMemoryArchive(); - gobArchive->open(buffer, bufferLen); - TFE_Paths::addLocalArchive(gobArchive); - } - - char tempPath[TFE_MAX_PATH]; - sprintf(tempPath, "%sTemp/", TFE_Paths::getPath(PATH_PROGRAM_DATA)); - // Extract and copy the briefing. - if (briefingIndex >= 0) - { - u32 bufferLen = (u32)zipArchive.getFileLength(briefingIndex); - u8* buffer = (u8*)malloc(bufferLen); - zipArchive.openFile(briefingIndex); - zipArchive.readFile(buffer, bufferLen); - zipArchive.closeFile(); - - char lfdPath[TFE_MAX_PATH]; - sprintf(lfdPath, "%sdfbrief.lfd", tempPath); - FileStream file; - if (file.open(lfdPath, Stream::MODE_WRITE)) - { - file.writeBuffer(buffer, bufferLen); - file.close(); - } - free(buffer); - - TFE_Paths::addSingleFilePath("dfbrief.lfd", lfdPath); - } - // Extract and copy the LFD. - for (s32 i = 0; i < lfdCount; i++) - { - u32 bufferLen = (u32)zipArchive.getFileLength(lfdIndex[i]); - u8* buffer = (u8*)malloc(bufferLen); - zipArchive.openFile(lfdIndex[i]); - zipArchive.readFile(buffer, bufferLen); - zipArchive.closeFile(); - - char lfdPath[TFE_MAX_PATH]; - sprintf(lfdPath, "%scutscenes%d.lfd", tempPath, i); - FileStream file; - if (file.open(lfdPath, Stream::MODE_WRITE)) - { - file.writeBuffer(buffer, bufferLen); - file.close(); - } - free(buffer); - - TFE_Paths::addSingleFilePath(zipArchive.getFileName(lfdIndex[i]), lfdPath); - } - - zipArchive.close(); - } - } - else - { - Archive* archive = Archive::getArchive(ARCHIVE_GOB, gobName, archivePath.path); - if (archive) - { - TFE_Paths::addLocalArchive(archive); - - // Handle LFD files. - char modPath[TFE_MAX_PATH]; - FileUtil::getFilePath(archivePath.path, modPath); - - // Look for LFD files. - lfdCount = 0; - briefingIndex = -1; - - FileList fileList; - FileUtil::readDirectory(modPath, "lfd", fileList); - const size_t count = fileList.size(); - const std::string* file = fileList.data(); - - for (size_t i = 0; i < count; i++, file++) - { - const size_t len = file->length(); - const char* name = file->c_str(); - - if (lfdCount < 16) - { - if (strstr(name, "brief") || strstr(name, "BRIEF")) - { - briefingIndex = s32(i); - strcpy(briefingName, name); - } - else if (lfdCount < MAX_MOD_LFD) - { - strcpy(lfdName[lfdCount], name); - lfdCount++; - } - } - } - - // If there is only 1 LFD, assume it is mission briefings. - if (lfdCount == 1 && briefingIndex < 0) - { - strcpy(briefingName, lfdName[0]); - briefingIndex = 0; - lfdCount = 0; - } - - // Extract and copy the briefing. - char lfdPath[TFE_MAX_PATH]; - if (briefingIndex >= 0) - { - sprintf(lfdPath, "%s%s", modPath, briefingName); - TFE_Paths::addSingleFilePath("dfbrief.lfd", lfdPath); - } - - // Extract and copy the LFD. - for (s32 i = 0; i < lfdCount; i++) - { - sprintf(lfdPath, "%s%s", modPath, lfdName[i]); - TFE_Paths::addSingleFilePath(lfdName[i], lfdPath); - } - } - } - } - } - - s32 loadLocalMessages() - { - if (s_runGameState.localMsgLoaded) - { - return 1; - } - - FilePath path; - TFE_Paths::getFilePath("local.msg", &path); - return parseMessageFile(&s_sharedState.localMessages, &path, 0); - } - - void buildSearchPaths() - { - TFE_Paths::addLocalSearchPath(""); - TFE_Paths::addLocalSearchPath("LFD/"); - // Dark Forces also adds C:/ and C:/LFD but TFE won't be doing that for obvious reasons... - -#ifndef TFE_ESPBOX - // Add some extra directories, if they exist. - // Obviously these were not in the original code. - TFE_Paths::addLocalSearchPath("Mods/"); - - // Add Mods/ paths to the program data directory and local executable directory. - // Note only directories that exist are actually added. - const char* programData = TFE_Paths::getPath(PATH_PROGRAM_DATA); - const char* programDir = TFE_Paths::getPath(PATH_PROGRAM); - char path[TFE_MAX_PATH]; - - sprintf(path, "%sMods/", programData); - TFE_Paths::addAbsoluteSearchPath(path); - - sprintf(path, "%sMods/", programDir); - TFE_Paths::addAbsoluteSearchPath(path); - - // Add the adjustable HUD. - sprintf(path, "%sMods/TFE/AdjustableHud", programDir); - TFE_Paths::addAbsoluteSearchPath(path); -#endif - } - - void openGobFiles() - { - for (s32 i = 0; i < TFE_ARRAYSIZE(c_gobFileNames); i++) - { - FilePath archivePath; - if (TFE_Paths::getFilePath(c_gobFileNames[i], &archivePath)) - { - assert(archivePath.path[0] != 0); - Archive* archive = Archive::getArchive(ARCHIVE_GOB, c_gobFileNames[i], archivePath.path); - if (archive) - { - TFE_Paths::addLocalArchive(archive); - } - } - else - { - TFE_System::logWrite(LOG_ERROR, "Dark Forces Main", "Cannot find required game data - '%s'.", c_gobFileNames[i]); - } - } - } - - void loadMapNumFont() - { - FilePath filePath; - s_sharedState.mapNumFont = nullptr; - if (TFE_Paths::getFilePath("map-nums.fnt", &filePath)) - { - s_sharedState.mapNumFont = font_load(&filePath); - } - } - - Font* getMapNumFont() - { - return s_sharedState.mapNumFont; - } - - static void parseKey(GameMessages* msgs, u32 keyId, KeyboardCode* dest, KeyboardCode dflt) - { - GameMessage* m = getGameMessage(msgs, keyId); - unsigned char c; - - *dest = dflt; - if (m) - { - c = toupper(m->text[0]); - if ((c >= 'A') && (c <= 'Z')) - { - *dest = (KeyboardCode)((u32)(KEY_A) + (c - 'A')); - } - } - } - - static void loadLangHotkeys(void) - { - GameMessages msgs; - FilePath fp; - - TFE_Paths::getFilePath("HOTKEYS.MSG", &fp); - parseMessageFile(&msgs, &fp, 1); - parseKey(&msgs, 160, &s_sharedState.langKeys.k_yes, KEY_Y); - parseKey(&msgs, 350, &s_sharedState.langKeys.k_quit, KEY_Q); - parseKey(&msgs, 330, &s_sharedState.langKeys.k_cont, KEY_R); - parseKey(&msgs, 340, &s_sharedState.langKeys.k_conf, KEY_C); - parseKey(&msgs, 110, &s_sharedState.langKeys.k_agdel, KEY_R); - parseKey(&msgs, 130, &s_sharedState.langKeys.k_begin, KEY_B); - parseKey(&msgs, 240, &s_sharedState.langKeys.k_easy, KEY_E); - parseKey(&msgs, 250, &s_sharedState.langKeys.k_med, KEY_M); - parseKey(&msgs, 260, &s_sharedState.langKeys.k_hard, KEY_H); - parseKey(&msgs, 230, &s_sharedState.langKeys.k_canc, KEY_C); - } - - void gameStartup() - { - hud_loadGraphics(); - hud_loadGameMessages(); - loadMapNumFont(); - inf_loadSounds(); - actor_loadSounds(); - item_loadData(); - player_init(); - actor_allocatePhysicsActorList(); - loadCutsceneList(); - projectile_startup(); - hitEffect_startup(); - weapon_startup(); - loadLangHotkeys(); - - FilePath filePath; - TFE_Paths::getFilePath("swfont1.fnt", &filePath); - s_sharedState.swFont1 = font_load(&filePath); - - renderer_setVisionEffect(0); - renderer_setupCameraLight(JFALSE, JFALSE); - - s_loadScreen = bitmap_load("wait.bm", 1, POOL_GAME); - if (TFE_Paths::getFilePath("wait.pal", &filePath)) - { - FileStream::readContents(&filePath, s_loadingScreenPal, 768); - } - - weapon_enableAutomount(s_config.wpnAutoMount); - s_sharedState.screenShotSndSrc = sound_load("scrshot.voc", SOUND_PRIORITY_HIGH0); - sound_setBaseVolume(s_sharedState.screenShotSndSrc, 127); - } - - void loadAgentAndLevelData() - { - agent_loadData(); - if (!agent_loadLevelList("jedi.lvl")) - { - TFE_System::logWrite(LOG_ERROR, "DarkForcesMain", "Failed to load level list."); - } - if (!parseBriefingList(&s_sharedState.briefingList, "briefing.lst")) - { - TFE_System::logWrite(LOG_ERROR, "DarkForcesMain", "Failed to load briefing list."); - } - - FilePath filePath; - if (TFE_Paths::getFilePath("hotkeys.msg", &filePath)) - { - parseMessageFile(&s_sharedState.hotKeyMessages, &filePath, 1); - } - s_sharedState.diskErrorImg = bitmap_load("diskerr.bm", 0, POOL_GAME); - if (!s_sharedState.diskErrorImg) - { - TFE_System::logWrite(LOG_ERROR, "DarkForcesMain", "Failed to load diskerr image."); - } - } - - void startMissionFromSave(s32 levelIndex) - { -#ifdef TFE_ESPBOX - // The emulator can load a save at any time, including while the startup logo - // cutscene is still playing: stop it first, or its film and actors stay in the - // Landru lists and are drawn (from freed memory) over the next cutscenes. - cutscene_abort(); -#endif - // We have returned from the mission tasks. - renderer_reset(); - gameMusic_stop(); - sound_levelStop(); - agent_levelEndTask(); - lmusic_reset(); // Fix a Dark Forces bug where music won't play when entering a cutscene again without restarting. - pda_cleanup(); - reticle_enable(true); - - region_clear(s_levelRegion); - bitmap_clearLevelData(); - level_freeAllAssets(); -#ifdef TFE_ESPBOX - // Same as the normal mission start: drop cutscene/menu sounds and the agent menu images. - lSoundDestroy(); - lSoundInit(); - agentMenu_freeFrames(); -#endif - - // Next - sound_levelStart(); - bitmap_setAllocator(s_levelRegion); - actor_clearState(); - - task_reset(); - inf_clearState(); - mission_setLoadingFromSave(); // This tells the mission system that this is loading from a save. - s_sharedState.loadMissionTask = createTask("start mission", mission_startTaskFunc, JTRUE); - mission_setLoadMissionTask(s_sharedState.loadMissionTask); - gameMusic_start(levelIndex); - - s_runGameState.state = GSTATE_MISSION; - mission_setupTasks(); - } - - void serializeLoopState(Stream* stream, DarkForces* game) - { - if (s_sharedState.gameStarted) - { - SERIALIZE(SaveVersionInit, s_runGameState.argCount, 0); - for (s32 i = 0; i < s_runGameState.argCount; i++) - { - u32 length = 0; - if (serialization_getMode() == SMODE_WRITE) - { - length = (u32)strlen(s_runGameState.args[i]); - } - SERIALIZE(SaveVersionInit, length, 0); - if (serialization_getMode() == SMODE_READ) - { - s_runGameState.args[i] = (char*)game_alloc(length + 1); - } - SERIALIZE_BUF(SaveVersionInit, s_runGameState.args[i], length); - s_runGameState.args[i][length] = 0; - } - - SERIALIZE(SaveVersionInit, s_runGameState.cutscenesEnabled, JTRUE); - SERIALIZE(SaveVersionInit, s_runGameState.localMsgLoaded, JFALSE); - SERIALIZE(SaveVersionInit, s_runGameState.startLevel, 0); - SERIALIZE(SaveVersionInit, s_runGameState.state, GSTATE_STARTUP_CUTSCENES); - SERIALIZE(SaveVersionInit, s_runGameState.levelIndex, 0); - SERIALIZE(SaveVersionInit, s_runGameState.cutsceneIndex, 0); - SERIALIZE(SaveVersionInit, s_runGameState.abortLevel, 0); - } - else if (serialization_getMode() == SMODE_READ) // We need to start the game. - { - game->runGame(0, nullptr, stream); - } - } - - void serializeVersion(Stream* stream) - { - SERIALIZE_VERSION(SaveVersionInit); - } - - bool DarkForces::serializeGameState(Stream* stream, const char* filename, bool writeState) - { - if (!stream) { return false; } - if (writeState && filename) - { - // Write the save message. - const char* msg = TFE_System::getMessage(TFE_MSG_SAVE); - if (msg) - { - char fullMsg[TFE_MAX_PATH]; - sprintf(fullMsg, "%s [%s]", msg, filename); - hud_sendTextMessage(fullMsg, 0); - } - } - - time_pause(JTRUE); - if (writeState) - { - serialization_setMode(SMODE_WRITE); - } - else - { - serialization_setMode(SMODE_READ); - } - - serializeVersion(stream); - serializeLoopState(stream, this); - agent_serialize(stream); - time_serialize(stream); - if (!writeState) - { - startMissionFromSave(agent_getLevelIndex()); - } - sound_serializeLevelSounds(stream); - random_serialize(stream); - automap_serialize(stream); - hitEffect_serializeTasks(stream); - weapon_serialize(stream); - mission_serializeColorMap(stream); - level_serialize(stream); - inf_serialize(stream); - pickupLogic_serializeTasks(stream); - mission_serialize(stream); - - if (!writeState) - { - agent_restartEndLevelTask(); - } - - time_pause(JFALSE); - if (!writeState) - { - task_updateTime(); - mission_pause(JFALSE); - } - return true; - } -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/darkForcesMain.h b/components/darkforces/tfe/TFE_DarkForces/darkForcesMain.h deleted file mode 100644 index 5315fdf7..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/darkForcesMain.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Game Level -// Manages the game while playing levels in first person. -// This holds one or more players, handles input updates, etc. -////////////////////////////////////////////////////////////////////// -#include -#include - -namespace TFE_DarkForces -{ - struct DarkForces : IGame - { - bool runGame(s32 argCount, const char* argv[], Stream* stream) override; - void pauseGame(bool pause) override; - void pauseSound(bool pause) override; - void restartMusic() override; - void exitGame() override; - void loopGame() override; - bool serializeGameState(Stream* stream, const char* filename, bool writeState) override; - bool canSave() override; - bool isPaused() override; - void getLevelName(char* name) override; - void getModList(char* modList) override; - }; - - extern void saveLevelStatus(); -} diff --git a/components/darkforces/tfe/TFE_DarkForces/gameMessage.cpp b/components/darkforces/tfe/TFE_DarkForces/gameMessage.cpp deleted file mode 100644 index 5baa2d7c..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/gameMessage.cpp +++ /dev/null @@ -1,136 +0,0 @@ -#include "gameMessage.h" -#include "util.h" -#include -#include -#include -#include - -namespace TFE_DarkForces -{ - static char* s_buffer = nullptr; - - void gameMessage_freeBuffer() - { - s_buffer = nullptr; - } - - // FileStream and TFE_Parser are used to read the file and parse out lines. - // However all other processing matches the original DOS version. - s32 parseMessageFile(GameMessages* messages, const FilePath* path, s32 mode) - { - FileStream file; - if (!file.open(path, Stream::MODE_READ)) { return 0; } - - size_t size = file.getSize(); - s_buffer = (char*)game_realloc(s_buffer, size); - if (!s_buffer) { return 0; } - - file.readBuffer(s_buffer, (u32)size); - file.close(); - - TFE_Parser parser; - parser.addCommentString("#"); - parser.init(s_buffer, size); - - size_t bufferPos = 0; - const char* fileData = parser.readLine(bufferPos); - - s32 v0 = 0, v1 = 0; - s32 count = sscanf(fileData, "MSG %d.%d", &v0, &v1); - if (count != 2 || v0 != 1 || v1 != 0) - { - TFE_System::logWrite(LOG_ERROR, "Game Message", "Invalid version: %d.%d. Only version 1.0 is supported.", v0, v1); - return 0; - } - - fileData = parser.readLine(bufferPos); - s32 msgCount; - count = sscanf(fileData, "MSGS %d", &msgCount); - if (count != 1) - { - TFE_System::logWrite(LOG_ERROR, "Game Message", "Cannot parse message count"); - return 0; - } - - messages->count = msgCount; - messages->msgList = (GameMessage*)game_alloc(msgCount * sizeof(GameMessage)); - GameMessage* msg = messages->msgList; - for (s32 i = 0; i < msgCount; i++, msg++) - { - fileData = parser.readLine(bufferPos); - if (!fileData) - { - TFE_System::logWrite(LOG_ERROR, "Game Message", "The message count is incorrect!"); - return 0; - } - if (sscanf(fileData, "%d %d", &msg->id, &msg->priority) != 2) - { - TFE_System::logWrite(LOG_ERROR, "Game Message", "Cannot parse message ID and Priority."); - return 0; - } - - const char* line = fileData; - char c = *line; - while (c) - { - if (c == '"') - { - break; - } - else if (!c) - { - line = nullptr; - break; - } - line++; - c = *line; - } - - if (!line) - { - TFE_System::logWrite(LOG_ERROR, "Game Message", "Failed to find the start of the message body."); - return 0; - } - line++; - const char* strStart = line; - - c = *line; - while (c) - { - if (c == '"') - { - break; - } - else if (!c) - { - line = nullptr; - break; - } - line++; - c = *line; - } - if (!line) - { - TFE_System::logWrite(LOG_ERROR, "Game Message", "Failed to find the end of the message body."); - return 0; - } - msg->text = copyAndAllocateString(strStart, line); - } // for (s32 i = 0; i < msgCount; i++, msg++) - return 1; - } - - GameMessage* getGameMessage(GameMessages* messages, s32 msgId) - { - s32 count = messages->count; - GameMessage* msg = messages->msgList; - - for (s32 i = 0; i < count; i++, msg++) - { - if (msgId == msg->id) - { - return msg; - } - } - return nullptr; - } -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/gameMessage.h b/components/darkforces/tfe/TFE_DarkForces/gameMessage.h deleted file mode 100644 index ee129099..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/gameMessage.h +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces Game Message -// This handles HUD messages, local messages, etc. -////////////////////////////////////////////////////////////////////// -#include -#include - -namespace TFE_DarkForces -{ - struct GameMessage - { - s32 id; - char* text; - s32 priority; - }; - struct GameMessages - { - s32 count = 0; - GameMessage* msgList = nullptr; - }; - - void gameMessage_freeBuffer(); - s32 parseMessageFile(GameMessages* messages, const FilePath* path, s32 mode); - GameMessage* getGameMessage(GameMessages* messages, s32 msgId); -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/gameMusic.cpp b/components/darkforces/tfe/TFE_DarkForces/gameMusic.cpp deleted file mode 100644 index 25021d13..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/gameMusic.cpp +++ /dev/null @@ -1,566 +0,0 @@ -#include "gameMusic.h" -#include "util.h" -#include "random.h" -#include -#include -#include -#include -#include -#include -#include - -#define SHOW_GAME_MUSIC_MSG 0 - -#if SHOW_GAME_MUSIC_MSG -#define GMUSIC_MSG(fmt, ...) TFE_System::logWrite(LOG_MSG, "Music", fmt, __VA_ARGS__) -#else -#define GMUSIC_MSG(fmt, ...) -#endif - -namespace TFE_DarkForces -{ - // Internally, iMuse stores opcodes as integers (ptrdiff_t in TFE, so it is big enough to hold a pointer). - // So this macro is a nice way of signifying the intent in the code. - #define MUSIC_CALLBACK(c) std::ptrdiff_t(c) - #define GAME_INVALID_TRIGGER 16 - - enum MusicConstants - { - MUS_LEVEL_COUNT = 14, - MUS_STATE_COUNT = 5, - MUS_FIGHT_TIME = TICKS(3), - }; - - static const char c_levelMusic[MUS_LEVEL_COUNT][MUS_STATE_COUNT][10] = - { - // LEVEL 1 - { - "", - "fight-01", - "", - "stalk-01", - "", - }, - // LEVEL 2 - { - "", - "fight-02", - "", - "stalk-02", - "", - }, - // LEVEL 3 - { - "", - "fight-03", - "", - "stalk-03", - "", - }, - // LEVEL 4 - { - "", - "fight-04", - "", - "stalk-04", - "", - }, - // LEVEL 5 - { - "boss-05", - "fight-05", - "", - "stalk-05", - "", - }, - // LEVEL 6 - { - "", - "fight-06", - "", - "stalk-06", - "", - }, - // LEVEL 7 - { - "", - "fight-07", - "", - "stalk-07", - "", - }, - // LEVEL 8 - { - "boss-08", - "fight-08", - "", - "stalk-08", - "", - }, - // LEVEL 9 - { - "", - "fight-09", - "", - "stalk-09", - "", - }, - // LEVEL 10 - { - "boss-10", - "fight-10", - "", - "stalk-10", - "", - }, - // LEVEL 11 - { - "boss-11", - "fight-11", - "", - "stalk-11", - "", - }, - // LEVEL 12 - { - "", - "fight-12", - "", - "stalk-12", - "", - }, - // LEVEL 13 - { - "", - "fight-13", - "", - "stalk-13", - "", - }, - // LEVEL 14 - { - "boss-14", - "fight-14", - "", - "stalk-14", - "", - }, - }; - - MusicState s_currentState = MUS_STATE_NULLSTATE; - MusicState s_oldState = MUS_STATE_NULLSTATE; - static s32 s_stateEntrances[MUS_STATE_UNDEFINED] = { 0 }; - static s32 s_currentLevel = 0; - static ImSoundId s_oldSong = IM_NULL_SOUNDID; - static ImSoundId s_newSong = IM_NULL_SOUNDID; - static s32 s_transChunk = 0; - static u32 s_savedMeasure = 0; - static u32 s_savedBeat = 0; - static Task* s_musicTask = nullptr; - static JBool s_desiredFightState = JFALSE; - - s32 gameMusic_setLevel(s32 level); - s32 gameMusic_random(s32 low, s32 high); - void gameMusic_taskFunc(MessageType msg); - void iMuseCallback1(char* marker); - void iMuseCallback2(char* marker); - void iMuseCallback3(char* marker); - - s32 readNumber(char** ptrptr); - char* parseEvent(char* ptr); - - void gameMusic_start(s32 level) - { - memset(s_stateEntrances, 0, MUS_STATE_UNDEFINED * sizeof(s32)); - s_musicTask = createSubTask("iMuse", gameMusic_taskFunc); - - gameMusic_setLevel(level); - gameMusic_setState(MUS_STATE_STALK); - s_desiredFightState = JFALSE; - } - - void gameMusic_stop() - { - gameMusic_setState(MUS_STATE_NULLSTATE); - s_musicTask = nullptr; - s_currentLevel = -1; - } - - s32 gameMusic_setLevel(s32 level) - { - s_oldSong = IM_NULL_SOUNDID; - - // In the original code, there are two values - a 'number' and 'value' - // But the only number that is used is 0, which is the current level. - // No other "attribute" is supported. - if (level <= MUS_LEVEL_COUNT) - { - s32 oldLevel = s_currentLevel; - s_currentLevel = level; - - if (s_currentLevel != oldLevel) - { - ImStopAllSounds(); - ImUnloadAll(); - s_currentState = MUS_STATE_NULLSTATE; - if (s_currentLevel) - { - for (s32 i = 1; i < MUS_STATE_UNDEFINED; i++) - { - if (c_levelMusic[s_currentLevel - 1][i - 1][0]) - { - ImLoadMidi(c_levelMusic[s_currentLevel-1][i-1]); - } - } - } - } - return s_currentLevel; - } - return 0; - } - - void gameMusic_setState(MusicState state) - { - ImPause(); - - if (s_currentLevel && state < MUS_STATE_UNDEFINED && state != s_currentState) - { - if (state == MUS_STATE_NULLSTATE) - { - s_currentState = state; - ImStopAllSounds(); - } - else if (ImFindMidi(c_levelMusic[s_currentLevel-1][state-1])) - { - if (s_currentState) - { - // If there is no trigger set yet, set callback 1, otherwise we keep the current trigger. - if (!ImCheckTrigger(-1, -1, -1)) - { - s_oldSong = ImFindMidi(c_levelMusic[s_currentLevel - 1][s_currentState - 1]); - ImSetTrigger(s_oldSong, 0, MUSIC_CALLBACK(iMuseCallback1)); - } - } - else - { - // Start the sound from scratch since this is the initial state. - ImStartSound(ImFindMidi(c_levelMusic[s_currentLevel - 1][state - 1]), 64); - } - - s_oldState = s_currentState; - s_currentState = state; - } - else - { - TFE_System::logWrite(LOG_ERROR, "Music", "Cannot start music."); - } - } - - ImResume(); - } - - MusicState gameMusic_getState() - { - return s_currentState; - } - - void gameMusic_startFight() - { - static s32 fightTimer = 0; - // Allow the user to disable fight music transitions. - // If this is changed while in the fight state or already transitioning, then nothing will - // happen until the next available transition point. - TFE_Settings_Game* gameSettings = TFE_Settings::getGameSettings(); - if (gameSettings->df_disableFightMusic) - { - s_desiredFightState = JFALSE; - fightTimer = 0; - if (gameMusic_getState() != MUS_STATE_STALK) - { - gameMusic_setState(MUS_STATE_STALK); - } - return; - } - - if (s_curTick - fightTimer > TICKS(8)) - { - fightTimer = s_curTick - TICKS(6); - } - else - { - fightTimer += TICKS(3); - } - - if (fightTimer > (s32)s_curTick) - { - task_setNextTick(s_musicTask, s_curTick + MUS_FIGHT_TIME); - if (!s_desiredFightState) - { - s_desiredFightState = JTRUE; - gameMusic_setState(MUS_STATE_FIGHT); - } - } - } - - void gameMusic_sustainFight() - { - if (s_desiredFightState) - { - gameMusic_startFight(); - } - } - - void gameMusic_taskFunc(MessageType msg) - { - task_begin; - while (msg != MSG_FREE_TASK) - { - task_yield(TASK_SLEEP); - - gameMusic_setState(MUS_STATE_STALK); - s_desiredFightState = JFALSE; - } - task_end; - } - - // Initial callback. - void iMuseCallback1(char* marker) - { - if (!strncmp(marker, "to ", 3)) - { - s32 punt = 0; - if (!strncmp(&marker[4], "slow", 4)) - { - if (s_currentState <= s_oldState || s_currentState == MUS_STATE_FIGHT) - { - punt = 1; - } - } - else if ((s_currentState > s_oldState && s_currentState != MUS_STATE_FIGHT) || (s_currentState == s_oldState)) - { - punt = 1; - } - - if (!punt) - { - // Get the current measure and beat so we can return to it later. - ImPause(); - s_savedMeasure = ImGetParam(s_oldSong, midiMeasure); - s_savedBeat = ImGetParam(s_oldSong, midiBeat); - ImResume(); - - // This is a transition, so update the trigger. - s_transChunk = marker[3] - 'A'; // "to A", "to B", etc. - ImJumpMidi(s_oldSong, 1 + s_transChunk, 1, 1, 0, 1); - ImSetTrigger(s_oldSong, 0, MUSIC_CALLBACK(iMuseCallback2)); - } - else - { - // Reset the trigger. - GMUSIC_MSG("Punt!..."); - ImSetTrigger(s_oldSong, 0, MUSIC_CALLBACK(iMuseCallback1)); - } - } - else - { - GMUSIC_MSG("Callback1 got bogus marker..."); - } - } - - // Callback after transition. - void iMuseCallback2(char* marker) - { - char* lptr = parseEvent(marker); - s32 count = 0; - if (lptr) - { - // Jump to transition piece. - while (lptr[count]) { count++; } - s32 r = gameMusic_random(0, count - 1); - - GMUSIC_MSG("trans%lu=%lu...", s_oldState, lptr[r]); - ImJumpMidi(s_oldSong, 1 + s_transChunk, lptr[r] - 1, 4, 300, 1); - ImSetTrigger(s_oldSong, 0, MUSIC_CALLBACK(iMuseCallback2)); - } - else if (size_t(marker) >= GAME_INVALID_TRIGGER && !strcmp(marker, "start new")) // TFE: handle invalid integral markers from mods. - { - s_newSong = ImFindMidi(c_levelMusic[s_currentLevel - 1][s_currentState - 1]); - if (s_oldSong != s_newSong) - { - ImDeferCommand(15, imStopSound, s_oldSong); - ImStartSound(s_newSong, 64); - ImShareParts(s_oldSong, s_newSong); - ImSetTrigger(s_newSong, 0, MUSIC_CALLBACK(iMuseCallback3)); - } - else - { - GMUSIC_MSG("Reset position!..."); - ImJumpMidi(s_newSong, 1, s_savedMeasure, s_savedBeat, 300, 1); - } - } - else - { - ImSetTrigger(s_oldSong, 0, MUSIC_CALLBACK(iMuseCallback2)); - } - } - - void iMuseCallback3(char* marker) - { - char* lptr = parseEvent(marker); - if (lptr) - { - s32 count = 0; - while (lptr[count]) { count++; } - s32 r = gameMusic_random(0, count - 1); - - if (lptr[r] == s_stateEntrances[s_currentState]) - { - r = gameMusic_random(0, count - 1); - } - if (lptr[r] == s_stateEntrances[s_currentState]) - { - r = gameMusic_random(0, count - 1); - } - s_stateEntrances[s_currentState] = lptr[r]; - - GMUSIC_MSG("entry%lu=%lu...", s_currentState, lptr[r]); - ImJumpMidi(s_newSong, 1, lptr[r] - 1, 4, 400, 0); - } - else if (strcmp(marker, "clear callback")) // Keep going until the "clear callback" marker is set. - { - ImSetTrigger(s_newSong, 0, MUSIC_CALLBACK(iMuseCallback3)); - } - } - - s32 readNumber(char** ptrptr) - { - s32 num = 0; - char* ptr = *ptrptr; - - while ((*ptr) && ((*ptr) < '0' || (*ptr) > '9')) - { - ptr++; - } - - if (!(*ptr)) { return 0; } - - while ((*ptr) >= '0' && (*ptr) <= '9') - { - num *= 10; - num += (*ptr) - '0'; - ptr++; - } - - *ptrptr = ptr; - return num; - } - - char* parseEvent(char* ptr) - { - static char buf[32]; - // TFE: Some mods have an invalid integral value here. - if (size_t(ptr) < GAME_INVALID_TRIGGER) - { - return nullptr; - } - - s32 i = 0; - if (!strncmp(ptr, "from ", 5)) // "from" markers - { - ptr += strlen("from "); - - if (!strncmp(ptr, "boss ", 5) && (s_oldState == MUS_STATE_BOSS)) - { - ptr += 5; - while (buf[i++] = readNumber(&ptr)); - return buf[0] ? buf : nullptr; - } - if (!strncmp(ptr, "fight ", 6) && (s_oldState == MUS_STATE_FIGHT)) - { - ptr += 6; - while (buf[i++] = readNumber(&ptr)); - return buf[0] ? buf : nullptr; - } - if (!strncmp(ptr, "engage ", 7) && (s_oldState == MUS_STATE_ENGAGE)) - { - ptr += 7; - while (buf[i++] = readNumber(&ptr)); - return buf[0] ? buf : nullptr; - } - if (!strncmp(ptr, "stalk ", 6) && (s_oldState == MUS_STATE_STALK)) - { - ptr += 6; - while (buf[i++] = readNumber(&ptr)); - return buf[0] ? buf : nullptr; - } - if (!strncmp(ptr, "explore ", 8) && (s_oldState == MUS_STATE_EXPLORE)) - { - ptr += 8; - while (buf[i++] = readNumber(&ptr)); - return buf[0] ? buf : nullptr; - } - } - else // "to" markers - { - if (!strncmp(ptr, "boss ", 5) && (s_currentState == MUS_STATE_BOSS)) - { - ptr += 5; - ptr += strlen("trans "); - while (buf[i++] = readNumber(&ptr)); - return buf[0] ? buf : nullptr; - } - if (!strncmp(ptr, "fight ", 6) && (s_currentState == MUS_STATE_FIGHT)) - { - ptr += 6; - while (buf[i++] = readNumber(&ptr)); - return buf[0] ? buf : nullptr; - } - if (!strncmp(ptr, "engage ", 7) && (s_currentState == MUS_STATE_ENGAGE)) - { - ptr += 7; - while (buf[i++] = readNumber(&ptr)); - return buf[0] ? buf : nullptr; - } - if (!strncmp(ptr, "stalk ", 6) && (s_currentState == MUS_STATE_STALK)) - { - ptr += 6; - while (buf[i++] = readNumber(&ptr)); - return buf[0] ? buf : nullptr; - } - if (!strncmp(ptr, "explore ", 8) && (s_currentState == MUS_STATE_EXPLORE)) - { - ptr += 8; - while (buf[i++] = readNumber(&ptr)); - return buf[0] ? buf : nullptr; - } - } - return nullptr; - } - - s32 gameMusic_random(s32 low, s32 high) - { - static s32 rseed1, rseed2, initFlag = 0; - if (!initFlag) - { - initFlag = 1; - rseed1 = (s32)(size_t)(&rseed2); - rseed2 = ~(s32)(size_t)(&rseed1); - } - - for (s32 i = 0; i < 23; i++) - { - s32 c = ((rseed1 & 0x40000000) != 0) ^ ((rseed2 & 0x20000000) == 0); - rseed1 <<= 1; - rseed1 += c; - } - for (s32 i = 0; i < 37; i++) - { - s32 c = ((rseed2 & 0x40000000) != 0) ^ ((rseed1 & 0x20000000) == 0); - rseed1 <<= 1; - rseed1 += c; - } - - s32 range = high - low; - return min(high, ((u16(rseed1 + rseed2) * s32(range + 1)) >> 16) + low); - } -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/gameMusic.h b/components/darkforces/tfe/TFE_DarkForces/gameMusic.h deleted file mode 100644 index 9cfdf2e4..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/gameMusic.h +++ /dev/null @@ -1,30 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces Game Music -// Handles music states and iMuse callbacks. -////////////////////////////////////////////////////////////////////// -#include -#include - -enum MusicState -{ - MUS_STATE_NULLSTATE = 0, - MUS_STATE_BOSS, // Partially implemented and then removed from the game. - MUS_STATE_FIGHT, - MUS_STATE_ENGAGE, // Removed from the game. - MUS_STATE_STALK, - MUS_STATE_EXPLORE, // Removed from the game. - MUS_STATE_UNDEFINED -}; - -namespace TFE_DarkForces -{ - void gameMusic_start(s32 level); - void gameMusic_stop(); - - void gameMusic_setState(MusicState state); - void gameMusic_startFight(); - void gameMusic_sustainFight(); - - MusicState gameMusic_getState(); -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/generator.cpp b/components/darkforces/tfe/TFE_DarkForces/generator.cpp deleted file mode 100644 index f43685fa..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/generator.cpp +++ /dev/null @@ -1,338 +0,0 @@ -#include - -#include "generator.h" -#include "time.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - struct Generator - { - Logic logic; - - KEYWORD type; - Tick delay; - Tick interval; - s32 maxAlive; - fixed16_16 minDist; - fixed16_16 maxDist; - Allocator* entities; - s32 aliveCount; - s32 numTerminate; - Tick wanderTime; - Wax* wax; - JBool active; - }; - - void generatorTaskFunc(MessageType msg) - { - struct LocalContext - { - Generator* gen; - SecObject* obj; - }; - task_begin_ctx; - local(gen) = (Generator*)task_getUserData(); - local(obj) = local(gen)->logic.obj; - - // Initial delay before it starts working. - do - { - entity_yield(local(gen)->delay); - } while (msg != MSG_RUN_TASK); - - while (1) - { - entity_yield(local(gen)->interval); - while (local(gen)->numTerminate == 0 && msg == MSG_RUN_TASK) - { - entity_yield(TASK_SLEEP); - } - - if (msg == MSG_FREE) - { - Generator* gen = local(gen); - assert(gen && gen->entities && allocator_validate(gen->entities)); - - SecObject* entity = (SecObject*)s_msgEntity; - SecObject** entityList = (SecObject**)allocator_getHead(gen->entities); - while (entityList) - { - if (entity == *entityList) - { - allocator_deleteItem(gen->entities, entityList); - gen->aliveCount--; - break; - } - entityList = (SecObject**)allocator_getNext(gen->entities); - } - } - else if (msg == MSG_MASTER_ON) - { - local(gen)->active |= 1; - } - else if (msg == MSG_MASTER_OFF) - { - local(gen)->active &= ~1; - } - else if (msg == MSG_RUN_TASK && (local(gen)->active & 1) && local(gen)->aliveCount < local(gen)->maxAlive) - { - Generator* gen = local(gen); - SecObject* obj = local(obj); - SecObject* spawn = allocateObject(); - assert(gen->numTerminate != 0); - spawn->posWS = obj->posWS; - spawn->yaw = random_next() & ANGLE_MASK; - spawn->worldHeight = FIXED(7); - sector_addObject(obj->sector, spawn); - - assert(gen->entities && allocator_validate(gen->entities)); - - fixed16_16 dy = TFE_Jedi::abs(s_playerObject->posWS.y - spawn->posWS.y); - fixed16_16 dist = dy + distApprox(spawn->posWS.x, spawn->posWS.z, s_playerObject->posWS.x, s_playerObject->posWS.z); - if (dist >= gen->minDist && dist <= gen->maxDist && !actor_canSeeObject(spawn, s_playerObject)) - { - sprite_setData(spawn, gen->wax); - obj_setEnemyLogic(spawn, gen->type, nullptr); - Logic** head = (Logic**)allocator_getHead_noIterUpdate((Allocator*)spawn->logic); - ActorDispatch* actorLogic = *((ActorDispatch**)head); - - actorLogic->flags &= ~1; - actorLogic->freeTask = task_getCurrent(); - gen->aliveCount++; - gen->numTerminate--; - if (gen->wanderTime == 0xffffffff) - { - s_actorState.attackMod->timing.nextTick = 0xffffffff; - } - else - { - s32 randomWanderOffset = floor16(random(intToFixed16(gen->wanderTime >> 1))); - s_actorState.attackMod->timing.nextTick = s_curTick + gen->wanderTime + floor16(randomWanderOffset); - } - - SecObject** entityPtr = (SecObject**)allocator_newItem(gen->entities); - *entityPtr = spawn; - actor_removeRandomCorpse(); - } - else - { - freeObject(spawn); - } - } - } - - task_end; - } - - void generatorLogicCleanupFunc(Logic* logic) - { - } - - JBool generatorLogicSetupFunc(Logic* logic, KEYWORD key) - { - Generator* genLogic = (Generator*)logic; - - if (key == KW_MASTER) - { - genLogic->active &= ~1; - return JTRUE; - } - else if (key == KW_DELAY) - { - genLogic->delay = strToInt(s_objSeqArg1) * 145; - return JTRUE; - } - else if (key == KW_INTERVAL) - { - Tick interval = strToInt(s_objSeqArg1) * 145; - Tick intInSec = strToInt(s_objSeqArg1); - fixed16_16 halfIntervalInSec = (intInSec - (intInSec < 0 ? 1 : 0)) << 15; - // Adds a random interval offset: interval = Seconds*145 + floor(random(HalfSeconds)) - genLogic->interval = interval + (Tick)floor16(random(halfIntervalInSec)); - return JTRUE; - } - else if (key == KW_MAX_ALIVE) - { - genLogic->maxAlive = strToInt(s_objSeqArg1); - return JTRUE; - } - else if (key == KW_MIN_DIST) - { - genLogic->minDist = strToInt(s_objSeqArg1) << 16; - return JTRUE; - } - else if (key == KW_MAX_DIST) - { - genLogic->maxDist = strToInt(s_objSeqArg1) << 16; - return JTRUE; - } - else if (key == KW_NUM_TERMINATE) - { - genLogic->numTerminate = strToInt(s_objSeqArg1); - return JTRUE; - } - else if (key == KW_WANDER_TIME) - { - s32 wanderTime = strToInt(s_objSeqArg1); - if (wanderTime == -1) - { - genLogic->wanderTime = 0xffffffffu; - } - else - { - genLogic->wanderTime = Tick(wanderTime * 145); - } - return JTRUE; - } - return JFALSE; - } - - Logic* obj_createGenerator(SecObject* obj, LogicSetupFunc* setupFunc, KEYWORD genType) - { - Generator* generator = (Generator*)level_alloc(sizeof(Generator)); - memset(generator, 0, sizeof(Generator)); - - generator->type = genType; - generator->active = 1; - generator->delay = 0; - - generator->maxAlive = 4; - generator->minDist = FIXED(60); - generator->interval = floor16(random(FIXED(728))) + 2913; - generator->maxDist = FIXED(200); - generator->entities = allocator_create(sizeof(SecObject**)); - generator->aliveCount = 0; - generator->numTerminate = -1; - generator->wax = obj->wax; - generator->wanderTime = 17478; - - spirit_setData(obj); - - obj->worldWidth = 0; - obj->worldHeight = 0; - obj->entityFlags |= ETFLAG_CAN_DISABLE; - *setupFunc = generatorLogicSetupFunc; - - Task* task = createSubTask("Generator", generatorTaskFunc); - task_setUserData(task, generator); - obj_addLogic(obj, (Logic*)generator, LOGIC_GENERATOR, task, generatorLogicCleanupFunc); - - return (Logic*)generator; - } - - // Fixup - void generatorLogic_fixup(Logic* logic) - { - Generator* gen = (Generator*)logic; - allocator_saveIter(gen->entities); - SecObject** entityList = (SecObject**)allocator_getHead(gen->entities); - while (entityList) - { - SecObject* obj = *entityList; - if (obj && obj->logic) - { - // Now find the dispatch logic and link it back to the generator. - allocator_saveIter((Allocator*)obj->logic); - Logic** logicPtr = (Logic**)allocator_getHead((Allocator*)obj->logic); - while (logicPtr) - { - Logic* logic = *logicPtr; - if (logic->type == LOGIC_DISPATCH) - { - ActorDispatch* actorLogic = (ActorDispatch*)logic; - actorLogic->freeTask = gen->logic.task; - break; - } - logicPtr = (Logic**)allocator_getNext((Allocator*)obj->logic); - } - allocator_restoreIter((Allocator*)obj->logic); - } - entityList = (SecObject**)allocator_getNext(gen->entities); - } - allocator_restoreIter(gen->entities); - } - - // Serialization - void generatorLogic_serialize(Logic*& logic, SecObject* obj, Stream* stream) - { - Generator* gen; - if (serialization_getMode() == SMODE_WRITE) - { - gen = (Generator*)logic; - } - else - { - gen = (Generator*)level_alloc(sizeof(Generator)); - gen->entities = allocator_create(sizeof(SecObject**)); - logic = (Logic*)gen; - - Task* task = createSubTask("Generator", generatorTaskFunc); - task_setUserData(task, gen); - gen->logic.task = task; - gen->logic.cleanupFunc = generatorLogicCleanupFunc; - } - - SERIALIZE(ObjState_InitVersion, gen->type, KW_UNKNOWN); - SERIALIZE(ObjState_InitVersion, gen->delay, 0); - SERIALIZE(ObjState_InitVersion, gen->interval, 0); - SERIALIZE(ObjState_InitVersion, gen->maxAlive, 0); - SERIALIZE(ObjState_InitVersion, gen->minDist, 0); - SERIALIZE(ObjState_InitVersion, gen->maxDist, 0); - - if (serialization_getMode() == SMODE_WRITE) - { - s32 count = allocator_getCount(gen->entities); - SERIALIZE(ObjState_InitVersion, count, 0); - if (count) - { - allocator_saveIter(gen->entities); - SecObject** entityList = (SecObject**)allocator_getHead(gen->entities); - while (entityList) - { - SecObject* obj = *entityList; - s32 entityId = (obj) ? obj->serializeIndex : -1; - SERIALIZE(ObjState_InitVersion, entityId, -1); - entityList = (SecObject**)allocator_getNext(gen->entities); - } - allocator_restoreIter(gen->entities); - } - } - else - { - s32 count; - SERIALIZE(ObjState_InitVersion, count, 0); - for (s32 i = 0; i < count; i++) - { - s32 entityId; - SERIALIZE(ObjState_InitVersion, entityId, -1); - if (entityId < 0) { continue; } - - SecObject** entityPtr = (SecObject**)allocator_newItem(gen->entities); - *entityPtr = objData_getObjectBySerializationId_NoValidation(entityId); - } - } - - SERIALIZE(ObjState_InitVersion, gen->aliveCount, 0); - SERIALIZE(ObjState_InitVersion, gen->numTerminate, 0); - SERIALIZE(ObjState_InitVersion, gen->wanderTime, 0); - serialization_serializeWaxPtr(stream, ObjState_InitVersion, gen->wax); - SERIALIZE(ObjState_InitVersion, gen->active, 0); - } -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/generator.h b/components/darkforces/tfe/TFE_DarkForces/generator.h deleted file mode 100644 index eb50e1c1..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/generator.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces Enemy Generator -// This is a logic that handles spawning enemies based on various -// parameters. -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include "logic.h" -#include "time.h" - -namespace TFE_DarkForces -{ - Logic* obj_createGenerator(SecObject* obj, LogicSetupFunc* setupFunc, KEYWORD genType); - - // Serialization - void generatorLogic_serialize(Logic*& logic, SecObject* obj, Stream* stream); - void generatorLogic_fixup(Logic* logic); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/hitEffect.cpp b/components/darkforces/tfe/TFE_DarkForces/hitEffect.cpp deleted file mode 100644 index cae9e639..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/hitEffect.cpp +++ /dev/null @@ -1,460 +0,0 @@ -#include "hitEffect.h" -#include "animLogic.h" -#include "projectile.h" -#include "sound.h" -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - struct HitEffect - { - HitEffectID type; - RSector* sector; - fixed16_16 x; - fixed16_16 y; - fixed16_16 z; - SecObject* excludeObj; - }; - - enum HitEffectConstants - { - MAX_SPEC_EFFECT_COUNT = 5, - EXPLOSION_TRIGGER_DIST = FIXED(10), - }; - - static Wax* s_genExplosion; - static SoundSourceId s_concussionExplodeSnd; - static EffectData s_effectData[HEFFECT_COUNT]; - static Allocator* s_hitEffects; - - Task* s_hitEffectTask = nullptr; - vec3_fixed s_explodePos; - EffectData* s_curEffectData = nullptr; - - void hitEffectWakeupFunc(SecObject* obj); - void hitEffectExplodeFunc(SecObject* obj); - void hitEffectTaskFunc(MessageType msg); - - void hitEffect_clearState() - { - s_hitEffects = nullptr; - s_hitEffectTask = nullptr; - s_curEffectData = nullptr; - s_genExplosion = nullptr; - } - - void hitEffect_startup() - { - // TODO: Move Hit Effect data to an external file instead of hardcoding here. - s_effectData[HEFFECT_SMALL_EXP] = - { - HEFFECT_SMALL_EXP, // type - TFE_Sprite_Jedi::getWax("exptiny.wax", POOL_GAME), - 0, // force - 0, // damage - 0, // explosiveRange - FIXED(40), // wakeupRange - sound_load("ex-tiny1.voc", SOUND_PRIORITY_LOW0), // soundEffect - }; - s_effectData[HEFFECT_THERMDET_EXP] = - { - HEFFECT_THERMDET_EXP, // type - TFE_Sprite_Jedi::getWax("detexp.wax", POOL_GAME), - FIXED(50), // force - FIXED(60), // damage - FIXED(30), // explosiveRange - FIXED(50), // wakeupRange - sound_load("ex-small.voc", SOUND_PRIORITY_LOW0), // soundEffect - }; - s_effectData[HEFFECT_PLASMA_EXP] = - { - HEFFECT_PLASMA_EXP, // type - TFE_Sprite_Jedi::getWax("emisexp.wax", POOL_GAME), - 0, // force - 0, // damage - 0, // explosiveRange - FIXED(40), // wakeupRange - sound_load("ex-tiny1.voc", SOUND_PRIORITY_LOW0), // soundEffect - }; - s_effectData[HEFFECT_MORTAR_EXP] = - { - HEFFECT_MORTAR_EXP, // type - TFE_Sprite_Jedi::getWax("mortexp.wax", POOL_GAME), - FIXED(35), // force - FIXED(50), // damage - FIXED(40), // explosiveRange - FIXED(60), // wakeupRange - sound_load("ex-med1.voc", SOUND_PRIORITY_HIGH2), // soundEffect - }; - s_effectData[HEFFECT_CONCUSSION] = - { - HEFFECT_CONCUSSION, // type - TFE_Sprite_Jedi::getWax("concexp.wax", POOL_GAME), - FIXED(30), // force - FIXED(30), // damage - FIXED(25), // explosiveRange - FIXED(60), // wakeupRange - sound_load("ex-lrg1.voc", SOUND_PRIORITY_HIGH2), // soundEffect - }; - s_effectData[HEFFECT_CONCUSSION2] = - { - HEFFECT_CONCUSSION2, // type - nullptr, // spriteData - FIXED(30), // force - FIXED(30), // damage - FIXED(25), // explosiveRange - FIXED(60), // wakeupRange - sound_load("ex-lrg1.voc", SOUND_PRIORITY_HIGH2), // soundEffect - }; - s_effectData[HEFFECT_MISSILE_EXP] = - { - HEFFECT_MISSILE_EXP, // type - TFE_Sprite_Jedi::getWax("missexp.wax", POOL_GAME), - FIXED(70), // force - FIXED(70), // damage - FIXED(40), // explosiveRange - FIXED(70), // wakeupRange - sound_load("ex-med1.voc", SOUND_PRIORITY_HIGH2), // soundEffect - }; - s_effectData[HEFFECT_MISSILE_WEAK] = - { - HEFFECT_MISSILE_WEAK, // type - TFE_Sprite_Jedi::getWax("missexp.wax", POOL_GAME), - FIXED(50), // force - FIXED(25), // damage - FIXED(40), // explosiveRange - FIXED(70), // wakeupRange - sound_load("ex-med1.voc", SOUND_PRIORITY_HIGH2), // soundEffect - }; - s_effectData[HEFFECT_PUNCH] = - { - HEFFECT_PUNCH, // type - nullptr, // spriteData - 0, // force - 0, // damage - 0, // explosiveRange - FIXED(10), // wakeupRange - sound_load("punch.voc", SOUND_PRIORITY_LOW1), // soundEffect - }; - s_effectData[HEFFECT_CANNON_EXP] = - { - HEFFECT_CANNON_EXP, // type - TFE_Sprite_Jedi::getWax("plasexp.wax", POOL_GAME), - 0, // force - 0, // damage - 0, // explosiveRange - FIXED(50), // wakeupRange - sound_load("ex-med1.voc", SOUND_PRIORITY_LOW0), // soundEffect - }; - s_effectData[HEFFECT_REPEATER_EXP] = - { - HEFFECT_REPEATER_EXP, // type - TFE_Sprite_Jedi::getWax("bullexp.wax", POOL_GAME), - 0, // force - 0, // damage - 0, // explosiveRange - FIXED(50), // wakeupRange - sound_load("ex-tiny1.voc", SOUND_PRIORITY_LOW0), // soundEffect - }; - s_effectData[HEFFECT_LARGE_EXP] = - { - HEFFECT_LARGE_EXP, // type - TFE_Sprite_Jedi::getWax("mineexp.wax", POOL_GAME), - FIXED(80), // force - FIXED(90), // damage - FIXED(45), // explosiveRange - FIXED(90), // wakeupRange - sound_load("ex-lrg1.voc", SOUND_PRIORITY_HIGH2), // soundEffect - }; - s_effectData[HEFFECT_EXP_BARREL] = - { - HEFFECT_EXP_BARREL, // type - nullptr, // spriteData - FIXED(120), // force - FIXED(60), // damage - FIXED(40), // explosiveRange - FIXED(60), // wakeupRange - sound_load("ex-med1.voc", SOUND_PRIORITY_MED3), // soundEffect - }; - s_effectData[HEFFECT_EXP_INVIS] = - { - HEFFECT_EXP_INVIS, // type - nullptr, // spriteData - FIXED(60), // force - FIXED(40), // damage - FIXED(20), // explosiveRange - FIXED(60), // wakeupRange - 0, // soundEffect - }; - s_effectData[HEFFECT_SPLASH] = - { - HEFFECT_SPLASH, // type - TFE_Sprite_Jedi::getWax("splash.wax", POOL_GAME), - 0, // force - 0, // damage - 0, // explosiveRange - FIXED(40), // wakeupRange - sound_load("swim-in.voc", SOUND_PRIORITY_LOW3), // soundEffect - }; - - s_genExplosion = TFE_Sprite_Jedi::getWax("genexp.wax", POOL_GAME); - // Different types of explosions that use the above animation. - s_effectData[HEFFECT_EXP_35] = - { - HEFFECT_EXP_35, // type - s_genExplosion, // spriteData - FIXED(30), // force - FIXED(35), // damage - FIXED(30), // explosiveRange - FIXED(50), // wakeupRange - sound_load("ex-med1.voc", SOUND_PRIORITY_HIGH2), // soundEffect - }; - s_effectData[HEFFECT_EXP_NO_DMG] = - { - HEFFECT_EXP_NO_DMG, // type - s_genExplosion, // spriteData - 0, // force - 0, // damage - 0, // explosiveRange - FIXED(50), // wakeupRange - sound_load("ex-med1.voc", SOUND_PRIORITY_HIGH2), // soundEffect - }; - s_effectData[HEFFECT_EXP_25] = - { - HEFFECT_EXP_25, // type - s_genExplosion, // spriteData - FIXED(20), // force - FIXED(25), // damage - FIXED(20), // explosiveRange - FIXED(50), // wakeupRange - sound_load("ex-med1.voc", SOUND_PRIORITY_HIGH2), // soundEffect - }; - } - - void spawnHitEffect(HitEffectID hitEffectId, RSector* sector, vec3_fixed pos, SecObject* excludeObj) - { - if (hitEffectId != HEFFECT_NONE) - { - HitEffect* effect = (HitEffect*)allocator_newItem(s_hitEffects); - effect->type = hitEffectId; - effect->sector = sector; - effect->x = pos.x; - effect->y = pos.y; - effect->z = pos.z; - effect->excludeObj = excludeObj; - - // Make the hit effect task active since there is at least one effect to process. - task_makeActive(s_hitEffectTask); - } - } - - void hitEffect_createTask() - { - hitEffect_clearState(); - s_hitEffects = allocator_create(sizeof(HitEffect)); - s_hitEffectTask = createSubTask("hitEffects", hitEffectTaskFunc); - } - - void hitEffect_serializeTasks(Stream* stream) - { - u8 hasTask = 0; - if (serialization_getMode() == SMODE_WRITE) - { - hasTask = s_hitEffectTask ? 1 : 0; - } - SERIALIZE(SaveVersionInit, hasTask, 0); - if (hasTask && s_hitEffectTask) - { - task_serializeState(stream, s_hitEffectTask); - } - } - - //////////////////////////////////////////////////////////////////////// - // Hit effect logic function. - // This handles all effects currently queued up. - //////////////////////////////////////////////////////////////////////// - void hitEffectTaskFunc(MessageType msg) - { - struct LocalContext - { - s32 count; - }; - task_begin_ctx; - taskCtx->count = 0; - while (1) - { - // The task sleeps until there are effects to process. - task_yield(TASK_SLEEP); - - // When it is woken up, either it will be directly called with id = 20 after an animation is complete or - // is called during the update because there are effects to process. - if (msg == MSG_SEQ_COMPLETE) - { - taskCtx->count--; - } - else if (msg == MSG_RUN_TASK) - { - // There are no yields in this block, so using purely local variables is safe. - HitEffect* effect = (HitEffect*)allocator_getHead(s_hitEffects); - while (effect) - { - RSector* sector = effect->sector; - fixed16_16 x = effect->x; - fixed16_16 y = effect->y; - fixed16_16 z = effect->z; - - EffectData* data = &s_effectData[effect->type]; - s_curEffectData = data; - - if (data->spriteData) - { - JBool createEffectObj = JTRUE; - if (effect->type == HEFFECT_PLASMA_EXP || effect->type == HEFFECT_CANNON_EXP) - { - if (taskCtx->count >= MAX_SPEC_EFFECT_COUNT) - { - createEffectObj = false; - } - else - { - taskCtx->count++; - } - } - - // Avoid creating a new effect object if there are too many. - if (createEffectObj) - { - SecObject* obj = allocateObject(); - // If effect is Concussion, adjust y so it sits on the floor. - if (effect->type == HEFFECT_CONCUSSION || effect->type == HEFFECT_CONCUSSION2) - { - fixed16_16 dummy; - sector_getObjFloorAndCeilHeight(sector, y, &y, &dummy); - } - - setObjPos_AddToSector(obj, x, y, z, sector); - if (effect->type != HEFFECT_SPLASH) - { - obj->flags |= OBJ_FLAG_FULLBRIGHT; - } - sprite_setData(obj, s_curEffectData->spriteData); - SpriteAnimLogic* animLogic = (SpriteAnimLogic*)obj_setSpriteAnim(obj); - - // Setup to call this task when animation is finished. - if (effect->type == HEFFECT_PLASMA_EXP || effect->type == HEFFECT_CANNON_EXP) - { - setAnimCompleteTask(animLogic, s_hitEffectTask); - } - - setupAnimationFromLogic(animLogic, 0/*animIndex*/, 0/*firstFrame*/, 0xffffffff/*lastFrame*/, 1/*loopCount*/); - obj->worldWidth = 0; - } - } - if (s_curEffectData->soundEffect) - { - vec3_fixed soundPos = { x,y,z }; - sound_playCued(s_curEffectData->soundEffect, soundPos); - } - - if (s_curEffectData->explosiveRange) - { - s_explodePos.x = x; - s_explodePos.y = y; - s_explodePos.z = z; - collision_effectObjectsInRange3D(sector, s_curEffectData->explosiveRange, s_explodePos, hitEffectExplodeFunc, effect->excludeObj, - ETFLAG_AI_ACTOR | ETFLAG_SCENERY | ETFLAG_LANDMINE | ETFLAG_LANDMINE_WPN | ETFLAG_PLAYER); - - if (s_curEffectData->type != HEFFECT_PUNCH) - { - fixed16_16 range = s_curEffectData->explosiveRange; - inf_handleExplosion(sector, x, z, range >> 3); - } - } - if (s_curEffectData->wakeupRange) - { - // Wakes up all objects with a valid collision path to (x,y,z) that are within s_curEffectData->wakeupRange units. - vec3_fixed hitPos = { x, y, z }; - collision_effectObjectsInRangeXZ(sector, s_curEffectData->wakeupRange, hitPos, hitEffectWakeupFunc, effect->excludeObj, ETFLAG_AI_ACTOR); - } - allocator_deleteItem(s_hitEffects, effect); - // Since the current item is deleted, "head" is the next item in the list. - effect = (HitEffect*)allocator_getHead(s_hitEffects); - } // while (effect) - } // if (id == 0) - } // while (1) - task_end; - } - - /////////////////////////////////////// - // Internal - /////////////////////////////////////// - void hitEffectWakeupFunc(SecObject* obj) - { - message_sendToObj(obj, MSG_WAKEUP, actor_hitEffectMsgFunc); - } - - void hitEffectExplodeFunc(SecObject* obj) - { - const u32 flags = ETFLAG_AI_ACTOR | ETFLAG_SCENERY | ETFLAG_LANDMINE | ETFLAG_LANDMINE_WPN | ETFLAG_PLAYER; - if (!(obj->entityFlags & flags)) - { - return; - } - - fixed16_16 dy = TFE_Jedi::abs(s_explodePos.y - obj->posWS.y); - fixed16_16 approxDist = dy + distApprox(obj->posWS.x, obj->posWS.z, s_explodePos.x, s_explodePos.z); - // This triggers when an explosive is hit with an explosion. - if ((obj->entityFlags & ETFLAG_LANDMINE) || (obj->entityFlags & ETFLAG_LANDMINE_WPN)) - { - if (approxDist < EXPLOSION_TRIGGER_DIST) - { - triggerLandMine((ProjectileLogic*)obj->projectileLogic, (obj->entityFlags & ETFLAG_LANDMINE) ? 87 : 145); - } - } - else - { - fixed16_16 radius = s_curEffectData->explosiveRange; - fixed16_16 leftOverRadius = max(radius - approxDist, 0); - HitEffectID type = s_curEffectData->type; - if (type == HEFFECT_CONCUSSION || type == HEFFECT_CONCUSSION2) - { - fixed16_16 floor, dummy; - RSector* sector = obj->sector; - SecObject* newObj = allocateObject(); - - sprite_setData(newObj, s_effectData[HEFFECT_CONCUSSION].spriteData); - sector_getObjFloorAndCeilHeight(sector, s_explodePos.y, &floor, &dummy); - setObjPos_AddToSector(newObj, obj->posWS.x, floor, obj->posWS.z, sector); - - newObj->flags |= OBJ_FLAG_FULLBRIGHT; - newObj->worldWidth = 0; - - SpriteAnimLogic* logic = (SpriteAnimLogic*)obj_setSpriteAnim(newObj); - setupAnimationFromLogic(logic, 0/*animIndex*/, 0/*firstFrame*/, 0xffffffff/*lastFrame*/, 1/*loopCount*/); - sound_playCued(s_concussionExplodeSnd, newObj->posWS); - - s_msgArg1 = s_curEffectData->damage; - } - else - { - fixed16_16 damage = s_curEffectData->damage; - fixed16_16 attenDmg = mul16(div16(leftOverRadius, radius), damage); - s_msgArg1 = attenDmg; - } - - fixed16_16 force = s_curEffectData->force; - fixed16_16 attenForce = mul16(div16(leftOverRadius, radius), force); - s_msgArg2 = attenForce; - message_sendToObj(obj, MSG_EXPLOSION, actor_hitEffectMsgFunc); - } - } -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/hitEffect.h b/components/darkforces/tfe/TFE_DarkForces/hitEffect.h deleted file mode 100644 index bcc9400a..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/hitEffect.h +++ /dev/null @@ -1,65 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces Hit Effect - -// Hit effects play a one-shot animation when a projectile hits -// something solid. -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include "sound.h" - -enum HitEffectID -{ - HEFFECT_NONE = -1, // no visible effect. - HEFFECT_SMALL_EXP = 0, // small "puff" - blaster weapons. - HEFFECT_THERMDET_EXP = 1, // thermal detonator explosion. - HEFFECT_PLASMA_EXP = 2, // plasma "puff". - HEFFECT_MORTAR_EXP = 3, // mortar explosion - HEFFECT_CONCUSSION = 4, // concussion - first stage. - HEFFECT_CONCUSSION2 = 5, // concussion - second stage. - HEFFECT_MISSILE_EXP = 6, // missile explosion. - HEFFECT_MISSILE_WEAK = 7, // weaker version of the missle explosion. - HEFFECT_PUNCH = 8, // punch - HEFFECT_CANNON_EXP = 9, // cannon "puff". - HEFFECT_REPEATER_EXP = 10, // repeater "puff". - HEFFECT_LARGE_EXP = 11, // large explosion such as land mine. - HEFFECT_EXP_BARREL = 12, // exploding barrel. - HEFFECT_EXP_INVIS = 13, // an explosion that makes no sound and has no visual effect. - HEFFECT_SPLASH = 14, // water splash - HEFFECT_EXP_35 = 15, // medium explosion, 35 damage. - HEFFECT_EXP_NO_DMG = 16, // medium explosion, no damage. - HEFFECT_EXP_25 = 17, // medium explosion, 25 damage. - HEFFECT_COUNT, -}; - -struct EffectData -{ - HitEffectID type; - Wax* spriteData; - fixed16_16 force; - fixed16_16 damage; - fixed16_16 explosiveRange; - fixed16_16 wakeupRange; - SoundSourceId soundEffect; -}; - -namespace TFE_DarkForces -{ - extern vec3_fixed s_explodePos; - extern EffectData* s_curEffectData; - - void hitEffect_startup(); - void hitEffect_createTask(); - void hitEffect_clearState(); - - // Serialization - void hitEffect_serializeTasks(Stream* stream); - - // Spawn a new hit effect at location (x,y,z) in 'sector'. - // The ExcludeObj field is used to avoid effecting a specific object during wakeup or explosions. - void spawnHitEffect(HitEffectID hitEffectId, RSector* sector, vec3_fixed pos, SecObject* excludeObj); - void hitEffectWakeupFunc(SecObject* obj); - void hitEffectExplodeFunc(SecObject* obj); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/hud.cpp b/components/darkforces/tfe/TFE_DarkForces/hud.cpp deleted file mode 100644 index 276f4cd5..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/hud.cpp +++ /dev/null @@ -1,1329 +0,0 @@ -#include "hud.h" -#include "time.h" -#include "automap.h" -#include "config.h" -#include "gameMessage.h" -#include "mission.h" -#include "util.h" -#include "player.h" -#include "weapon.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define TFE_CONVERT_CAPS 0 -#if TFE_CONVERT_CAPS -#include -#endif - -namespace TFE_DarkForces -{ - /////////////////////////////////////////// - // Constants - /////////////////////////////////////////// - enum HudConstants - { - HUD_COLORS_START = 24, - HUD_COLORS_COUNT = 8, - HUD_MAX_PRIORITY = 0, - HUD_HIGH_PRIORITY = 1, - HUD_LOWEST_PRIORITY = 9, - - HUD_MSG_LONG_DUR = 1165, // 8 seconds - HUD_MSG_SHORT_DUR = 436, // 3 seconds - }; - - static const s32 c_hudVertAnimTable[] = - { - 160, 170, 185, 200, - }; - - /////////////////////////////////////////// - // Internal State - /////////////////////////////////////////// - static GameMessages s_hudMessages; - static Font* s_hudFont; - static u8 s_hudMessage[80]; - static s32 s_hudCurrentMsgId = 0; - static s32 s_hudMsgPriority = HUD_LOWEST_PRIORITY; - static Tick s_hudMsgExpireTick; - - static JBool s_screenDirtyLeft[4] = { 0 }; - static JBool s_screenDirtyRight[4] = { 0 }; - static JBool s_basePaletteCopyMode = JFALSE; - static JBool s_updateHudColors = JFALSE; - - static u8 s_tempBuffer[256 * 3]; - static u8 s_hudPalette[HUD_COLORS_COUNT * 3 + 10]; - static u8 s_hudWorkPalette[HUD_COLORS_COUNT * 3 + 10]; - static s32 s_hudColorCount = 8; - static s32 s_hudPaletteIndex = 24; - - static TextureData* s_hudStatusL = nullptr; - static TextureData* s_hudStatusR = nullptr; - static TextureData* s_hudLightOn = nullptr; - static TextureData* s_hudLightOff = nullptr; - static TextureData* s_hudCapLeft = nullptr; - static TextureData* s_hudCapRight = nullptr; - static Font* s_hudMainAmmoFont = nullptr; - static Font* s_hudSuperAmmoFont = nullptr; - static Font* s_hudShieldFont = nullptr; - static Font* s_hudHealthFont = nullptr; - static OffScreenBuffer* s_cachedHudLeft = nullptr; - static OffScreenBuffer* s_cachedHudRight = nullptr; - - static s32 s_rightHudVertTarget; - static s32 s_rightHudVertAnim; - static s32 s_rightHudShow; - static s32 s_rightHudMove; - static s32 s_leftHudVertTarget; - static s32 s_leftHudVertAnim; - static s32 s_leftHudShow; - static s32 s_leftHudMove; - static JBool s_forceHudPaletteUpdate = JFALSE; - - static s32 s_prevBatteryPower = 0; - static s32 s_prevLifeCount = 0; - static s32 s_prevShields = 0; - static s32 s_prevHealth = 0; - static s32 s_prevPrimaryAmmo = 0; - static s32 s_prevSecondaryAmmo = 0; - static JBool s_prevSuperchageHud = JFALSE; - static JBool s_prevHeadlampActive = JFALSE; - - /////////////////////////////////////////// - // Shared State - /////////////////////////////////////////// - fixed16_16 s_flashEffect = 0; - fixed16_16 s_healthDamageFx = 0; - fixed16_16 s_shieldDamageFx = 0; - - s32 s_secretsFound = 0; - s32 s_secretsPercent = 0; - JBool s_showData = JFALSE; - - /////////////////////////////////////////// - // Forward Declarations - /////////////////////////////////////////// - TextureData* hud_loadTexture(const char* texFile); - Font* hud_loadFont(const char* fontFile); - void copyIntoPalette(u8* dst, u8* src, s32 count, s32 mode); - void getCameraXZ(fixed16_16* x, fixed16_16* z); - void displayHudMessage(Font* font, DrawRect* rect, s32 x, s32 y, u8* msg, u8* framebuffer); - void hud_drawString(OffScreenBuffer* elem, Font* font, s32 x0, s32 y0, const char* str); -#if TFE_CONVERT_CAPS - void hud_convertCapsToBM(); -#endif - - /////////////////////////////////////////// - // API Implementation - /////////////////////////////////////////// - void hud_sendTextMessage(s32 msgId) - { - GameMessage* msg = getGameMessage(&s_hudMessages, msgId); - // Only display the message if it is the same or lower priority than the current message. - if (!msg || msg->priority > s_hudMsgPriority) - { - // Always write the message to the console - if (msg && msg->text) { TFE_Console::addToHistory(msg->text); } - return; - } - - const char* msgText = msg->text; - if (!msgText[0]) { return; } - strCopyAndZero((char*)s_hudMessage, msgText, 80); - - s_hudMsgExpireTick = s_curTick + ((msg->priority <= HUD_HIGH_PRIORITY) ? HUD_MSG_LONG_DUR : HUD_MSG_SHORT_DUR); - s_hudCurrentMsgId = msgId; - s_hudMsgPriority = msg->priority; - - // TFE specific - TFE_Console::addToHistory(msgText); - } - - void hud_sendTextMessage(const char* msg, s32 priority) - { - // Only display the message if it is the same or lower priority than the current message. - if (!msg || priority > s_hudMsgPriority) - { - // Always write the message to the console - if (msg) { TFE_Console::addToHistory(msg); } - return; - } - strCopyAndZero((char*)s_hudMessage, msg, 80); - - s_hudMsgExpireTick = s_curTick + ((priority <= HUD_HIGH_PRIORITY) ? HUD_MSG_LONG_DUR : HUD_MSG_SHORT_DUR); - s_hudCurrentMsgId = 0; - s_hudMsgPriority = priority; - - // TFE specific - TFE_Console::addToHistory(msg); - } - - void hud_clearMessage() - { - s_hudMessage[0] = 0; - s_hudCurrentMsgId = 0; - s_hudMsgPriority = HUD_LOWEST_PRIORITY; - for (s32 i = 0; i < 4; i++) - { - s_screenDirtyLeft[i] = JFALSE; - s_screenDirtyRight[i] = JFALSE; - } - } - - void hud_addTexture(TextureInfoList& texList, TextureData* tex) - { - TextureInfo texInfo = {}; - texInfo.type = TEXINFO_DF_TEXTURE_DATA; - texInfo.texData = tex; - texList.push_back(texInfo); - } - - void hud_addFont(TextureInfoList& texList, Font* font) - { - for (s32 i = font->minChar; i <= font->maxChar; i++) - { - hud_addTexture(texList, &font->glyphs[i - font->minChar]); - } - } - - bool hud_getTextures(TextureInfoList& texList, AssetPool pool) - { - // First load the fonts. - hud_addFont(texList, s_hudFont); - hud_addFont(texList, s_hudMainAmmoFont); - hud_addFont(texList, s_hudSuperAmmoFont); - hud_addFont(texList, s_hudShieldFont); - hud_addFont(texList, s_hudHealthFont); - return true; - } - - void hud_loadGameMessages() - { - s_hudMessages.count = 0; - s_hudMessages.msgList = nullptr; - - FilePath filePath; - if (TFE_Paths::getFilePath("text.msg", &filePath)) - { - parseMessageFile(&s_hudMessages, &filePath, 1); - } - s_hudMessage[0] = 0; - s_hudFont = nullptr; - if (TFE_Paths::getFilePath("glowing.fnt", &filePath)) - { - s_hudFont = font_load(&filePath); - } - - // TFE - TFE_Jedi::renderer_addHudTextureCallback(hud_getTextures); - } - - void hud_reset() - { - freeOffScreenBuffer(s_cachedHudLeft); - freeOffScreenBuffer(s_cachedHudRight); - s_cachedHudLeft = nullptr; - s_cachedHudRight = nullptr; - } - - void hud_loadGraphics() - { - s_hudStatusL = hud_loadTexture("StatusLf.bm"); - s_hudStatusR = hud_loadTexture("StatusRt.bm"); - s_hudLightOn = hud_loadTexture("lighton.bm"); - s_hudLightOff = hud_loadTexture("lightoff.bm"); - s_hudMainAmmoFont = hud_loadFont("AmoNum.fnt"); - s_hudSuperAmmoFont = hud_loadFont("SuperWep.fnt"); - s_hudShieldFont = hud_loadFont("ArmNum.fnt"); - s_hudHealthFont = hud_loadFont("HelNum.fnt"); - - // Gracefully handle 'StatusLf' or 'StatusRt' not loading correctly. - // The original code just crashes (probably) in this case. - bool canDrawHud = true; - if (!s_hudStatusL) - { - TFE_System::logWrite(LOG_ERROR, "HUD", "Failed to load 'StatusLf.bm' - cannot draw HUD."); - canDrawHud = false; - } - if (!s_hudStatusR) - { - TFE_System::logWrite(LOG_ERROR, "HUD", "Failed to load 'StatusRt.bm' - cannot draw HUD."); - canDrawHud = false; - } - if (!canDrawHud) { return; } - - // Create offscreen buffers for the HUD elements. - s_cachedHudLeft = createOffScreenBuffer(s_hudStatusL->width, s_hudStatusL->height, OBF_TRANS); - s_cachedHudRight = createOffScreenBuffer(s_hudStatusR->width, s_hudStatusR->height, OBF_TRANS); - // Clear the buffer images to transparent (0). - offscreenBuffer_clearImage(s_cachedHudLeft, 0/*clear_color*/); - offscreenBuffer_clearImage(s_cachedHudRight, 0/*clear_color*/); - - if (s_hudStatusL) - { - offscreenBuffer_drawTexture(s_cachedHudLeft, s_hudStatusL, 0, 0); - } - if (s_hudStatusR) - { - offscreenBuffer_drawTexture(s_cachedHudRight, s_hudStatusR, 0, 0); - } - - #if TFE_CONVERT_CAPS - hud_convertCapsToBM(); - #endif - -#ifndef TFE_ESPBOX - // TFE: - // Load the caps - s_hudCapLeft = hud_loadTexture("HudStatusLeftAddon.bm"); - s_hudCapRight = hud_loadTexture("HudStatusRightAddon.bm"); -#endif - } - - void hud_updateBasePalette(u8* srcBuffer, s32 offset, s32 count) - { - u8* dstBuffer = s_tempBuffer + offset * 3; - memcpy(dstBuffer, srcBuffer, count * 3); - copyIntoPalette(s_basePalette + (offset * 3), srcBuffer, count, s_basePaletteCopyMode); - - s_hudPaletteIndex = offset; - s_hudColorCount = count; - s_updateHudColors = JTRUE; - } - - void hud_initAnimation() - { - s_rightHudMove = 4; - s_leftHudMove = 4; - s_forceHudPaletteUpdate = JTRUE; - s_rightHudShow = 4; - s_leftHudShow = 4; - } - - JBool hud_setupToggleAnim1(JBool enable) - { - if (enable) - { - s_leftHudVertTarget = 0; - s_rightHudVertTarget = 0; - - s_leftHudVertAnim = 0; - s_rightHudVertAnim = 0; - - s_leftHudShow = 4; - s_rightHudShow = 4; - - s_leftHudMove = 4; - s_rightHudMove = 4; - } - else - { - s_leftHudVertTarget = s_leftHudVertAnim == 0 ? 3 : 0; - s_rightHudVertTarget = s_rightHudVertAnim == 0 ? 3 : 0; - - s_leftHudShow = 4; - s_rightHudShow = 4; - - s_leftHudMove = 4; - s_rightHudMove = 4; - } - return s_leftHudVertTarget == 0 ? JTRUE : JFALSE; - } - - void hud_toggleDataDisplay() - { - s_showData = ~s_showData; - } - - void hud_startup(JBool fromSave) - { - // Reset cached values. - s_prevBatteryPower = 0; - s_prevLifeCount = 0; - s_prevShields = 0; - s_prevHealth = 0; - s_prevPrimaryAmmo = 0; - s_prevSecondaryAmmo = 0; - s_prevSuperchageHud = JFALSE; - s_prevHeadlampActive = JFALSE; - - if (!fromSave) - { - s_secretsFound = 0; - s_secretsPercent = 0; - } - - hud_initAnimation(); - if (s_config.showUI) - { - hud_setupToggleAnim1(JTRUE); - } - offscreenBuffer_drawTexture(s_cachedHudRight, s_hudLightOff, 19, 0); - } - - void hud_drawMessage(u8* framebuffer) - { - if (s_missionMode == MISSION_MODE_MAIN && s_hudMessage[0]) - { - displayHudMessage(s_hudFont, (DrawRect*)vfb_getScreenRect(VFB_RECT_UI), 4, 10, s_hudMessage, framebuffer); - if (s_curTick > s_hudMsgExpireTick) - { - s_hudMessage[0] = 0; - s_hudCurrentMsgId = 0; - s_hudMsgPriority = HUD_LOWEST_PRIORITY; - } - // s_screenDirtyLeft[s_curFrameBufferIdx] = JTRUE; - } - - if (s_showData && s_playerEye) - { - fixed16_16 x, z; - getCameraXZ(&x, &z); - - s32 xOffset = floor16(div16(intToFixed16(vfb_getWidescreenOffset()), vfb_getXScale())); - - u8 dataStr[64]; - sprintf((char*)dataStr, "X:%04d Y:%.1f Z:%04d H:%.1f S:%d%%", floor16(x), -fixed16ToFloat(s_playerEye->posWS.y), floor16(z), fixed16ToFloat(s_playerEye->worldHeight), s_secretsPercent); - displayHudMessage(s_hudFont, (DrawRect*)vfb_getScreenRect(VFB_RECT_UI), 164 + xOffset, 10, dataStr, framebuffer); - // s_screenDirtyRight[s_curFrameBufferIdx] = JTRUE; - } -#ifdef TFE_ESPBOX - TFE_Settings_Graphics* graphics = TFE_Settings::getGraphicsSettings(); - if (graphics->showFps) - { - u8 dataStr[64]; - static u64 localTimeCallback = 0; - f64 deltaTime = TFE_System::updateThreadLocal(&localTimeCallback); - sprintf((char*)dataStr, "%2d fps (%4.2f ms)", (int)(1.0 / deltaTime), deltaTime * 1000.0); - displayHudMessage(s_hudFont, (DrawRect*)vfb_getScreenRect(VFB_RECT_UI), 0, 1, dataStr, framebuffer); - } -#endif - } - - void hud_drawStringGpu(Font* font, fixed16_16 x0, fixed16_16 y0, fixed16_16 xScale, fixed16_16 yScale, const char* str) - { - if (!font) { return; } - - fixed16_16 x = x0; - fixed16_16 y = y0; - for (char c = *str; c != 0; ) - { - if (c == '\n') - { - y += mul16(intToFixed16(font->height + font->vertSpacing), yScale); - x = x0; - } - else - { - if (c == ' ') - { - x += mul16(intToFixed16(font->width), xScale); - } - else if (c >= font->minChar && c <= font->maxChar) - { - s32 charIndex = c - font->minChar; - s32 offset = charIndex * 28; - - TextureData* glyph = &font->glyphs[charIndex]; - screenGPU_blitTextureScaled(glyph, nullptr, x, y, xScale, yScale, 31); - x += mul16(intToFixed16(glyph->width + font->horzSpacing), xScale); - } - } - str++; - c = *str; - } - } - - void hud_drawGpu() - { - if (s_rightHudMove) - { - s_rightHudMove--; - } - if (s_leftHudMove) - { - s_leftHudMove--; - } - - // 1. Draw the base. - TFE_Settings_Hud* hudSettings = TFE_Settings::getHudSettings(); - - // HUD scaling. - fixed16_16 xScale = vfb_getXScale(); - fixed16_16 yScale = vfb_getYScale(); - fixed16_16 hudScaleX = xScale; - fixed16_16 hudScaleY = yScale; - u32 dispWidth, dispHeight; - vfb_getResolution(&dispWidth, &dispHeight); - - if (hudSettings->hudScale == TFE_HUDSCALE_SCALED) - { - hudScaleX = floatToFixed16(hudSettings->scale); - hudScaleY = floatToFixed16(hudSettings->scale); - } - else if (hudSettings->scale != 0) - { - hudScaleX = floatToFixed16(fixed16ToFloat(xScale) * hudSettings->scale); - hudScaleY = floatToFixed16(fixed16ToFloat(yScale) * hudSettings->scale); - } - - fixed16_16 x0, x1; - if (hudSettings->hudPos == TFE_HUDPOS_4_3) - { - x0 = mul16(intToFixed16(260), xScale) + intToFixed16(vfb_getWidescreenOffset()); - x1 = intToFixed16(vfb_getWidescreenOffset()); - } - else - { - x0 = intToFixed16(dispWidth) - mul16(intToFixed16(s_cachedHudRight->width - 1), hudScaleX); - x1 = 0; - } - x0 -= intToFixed16(hudSettings->pixelOffset[0]); - x1 += intToFixed16(hudSettings->pixelOffset[1]); - - fixed16_16 y0 = yScale + mul16(intToFixed16(c_hudVertAnimTable[s_rightHudVertAnim]), yScale); - fixed16_16 y1 = yScale + mul16(intToFixed16(c_hudVertAnimTable[s_leftHudVertAnim]), yScale); - y0 += intToFixed16(hudSettings->pixelOffset[2]); - y1 += intToFixed16(hudSettings->pixelOffset[2]); - - screenGPU_blitTextureScaled(s_hudStatusR, nullptr, x0, y0, hudScaleX, hudScaleY, 31); - screenGPU_blitTextureScaled(s_hudStatusL, nullptr, x1, y1, hudScaleX, hudScaleY, 31); - if ((hudSettings->hudPos == TFE_HUDPOS_4_3 || hudSettings->pixelOffset[0] > 0 || hudSettings->pixelOffset[1] > 0) && - s_hudCapLeft && s_hudCapRight) - { - screenGPU_blitTextureScaled(s_hudCapLeft, nullptr, x1 - mul16(intToFixed16(s_hudCapLeft->width - 1), hudScaleX), y1, hudScaleX, hudScaleY, 31); - screenGPU_blitTextureScaled(s_hudCapRight, nullptr, x0 + mul16(intToFixed16(s_hudStatusR->width), hudScaleX), y1, hudScaleX, hudScaleY, 31); - } - - // Energy - fixed16_16 batteryPower = TFE_Jedi::abs(s_batteryPower * 100); - s32 percent = round16(batteryPower >> 1); - { - const s32 offset = 3 * 3 + 1; // offset 3 color indices + 1 because we are only changing the green color. - // I think this should be < 5, since there are 5 pips. - // This actually overwrites memory in DOS, but here I just made the array larger. - for (s32 clrIndex = 0; clrIndex <= 5; clrIndex++) - { - if (percent > 20) - { - s_hudWorkPalette[3 * clrIndex + offset] = 58; - percent -= 20; - } - else - { - // Color value between [8, 58], where 8 @ 0% and 58 @ 20% - s_hudWorkPalette[3 * clrIndex + offset] = 8 + ((percent * 5) >> 1); - percent = 0; - } - } - } - s32 lifeCount = player_getLifeCount() % 10; - { - char lifeCountStr[8]; - sprintf(lifeCountStr, "%1d", lifeCount); - - fixed16_16 xPos = mul16(intToFixed16(52), hudScaleX) + x1; - fixed16_16 yPos = mul16(intToFixed16(26), hudScaleY) + y1; - hud_drawStringGpu(s_hudHealthFont, xPos, yPos, hudScaleX, hudScaleY, lifeCountStr); - - s_rightHudShow = 4; - } - // Headlamp - { - fixed16_16 xPos = mul16(intToFixed16(19), hudScaleX) + x0; - fixed16_16 yPos = y0; - if (s_headlampActive) - { - screenGPU_blitTextureScaled(s_hudLightOn, nullptr, xPos, yPos, hudScaleX, hudScaleY, 31); - } - else - { - screenGPU_blitTextureScaled(s_hudLightOff, nullptr, xPos, yPos, hudScaleX, hudScaleY, 31); - } - s_rightHudShow = 4; - } - // Shields - { - char shieldStr[8]; - if (s_playerInfo.shields == -1) - { - s_hudWorkPalette[0] = 55; - s_hudWorkPalette[1] = 55; - s_hudWorkPalette[3] = 55; - s_hudWorkPalette[4] = 55; - - strcpy(shieldStr, "200"); - } - else - { - s_hudWorkPalette[0] = 0; - s32 upperShields; - if (s_playerInfo.shields > 100) - { - upperShields = s_playerInfo.shields; - } - else - { - upperShields = 100; - } - upperShields -= 100; - u8 upperColor = 8 + (upperShields >> 1); - s_hudWorkPalette[1] = upperColor; - - s_hudWorkPalette[3] = 0; - s32 lowerShields; - if (s_playerInfo.shields < 100) - { - lowerShields = s_playerInfo.shields; - } - else - { - lowerShields = 100; - } - s_hudWorkPalette[4] = 8 + (lowerShields >> 1); - sprintf(shieldStr, "%03d", s_playerInfo.shields); - } - - fixed16_16 xPos = mul16(intToFixed16(15), hudScaleX) + x1; - fixed16_16 yPos = mul16(intToFixed16(26), hudScaleY) + y1; - hud_drawStringGpu(s_hudShieldFont, xPos, yPos, hudScaleX, hudScaleY, shieldStr); - } - // Health - { - s32 health = min(100, s_playerInfo.health); - // 6: color 2, red channel, 7 = green channel - s_hudWorkPalette[6] = 8 + (health >> 1); - s_hudWorkPalette[7] = health * 63 / 400; - - char healthStr[32]; - sprintf(healthStr, "%03d", s_playerInfo.health); - fixed16_16 xPos = mul16(intToFixed16(33), hudScaleX) + x1; - fixed16_16 yPos = mul16(intToFixed16(26), hudScaleY) + y1; - hud_drawStringGpu(s_hudHealthFont, xPos, yPos, hudScaleX, hudScaleY, healthStr); - - s_leftHudShow = 4; - } - - if (s_forceHudPaletteUpdate || memcmp(s_hudPalette, s_hudWorkPalette, HUD_COLORS_COUNT * 3) != 0) - { - // Copy work palette into hud palette. - memcpy(s_hudPalette, s_hudWorkPalette, HUD_COLORS_COUNT * 3); - // Copy hud palette into the base palette, this will update next time render_setPalette() is called. - hud_updateBasePalette(s_hudPalette, HUD_COLORS_START, HUD_COLORS_COUNT); - // Copy the final 8 HUD colors to the loaded palette. - memcpy(s_levelPalette + HUD_COLORS_START * 3, s_hudPalette, HUD_COLORS_COUNT * 3); - - s_forceHudPaletteUpdate = JFALSE; - } - - s32 ammo0 = -1; - s32 ammo1 = -1; - PlayerWeapon* weapon = s_curPlayerWeapon; - if (weapon) - { - if (weapon->ammo) - { - ammo0 = *weapon->ammo; - } - if (weapon->secondaryAmmo) - { - ammo1 = *weapon->secondaryAmmo; - } - } - - // Ammo readouts. - { - char str[32]; - if (ammo0 < 0) - { - strcpy(str, ":::"); - } - else - { - sprintf(str, "%03d", ammo0); - } - fixed16_16 xPos = mul16(intToFixed16(12), hudScaleX) + x0; - fixed16_16 yPos = mul16(intToFixed16(21), hudScaleY) + y0; - hud_drawStringGpu(s_superChargeHud ? s_hudSuperAmmoFont : s_hudMainAmmoFont, xPos, yPos, hudScaleX, hudScaleY, str); - - // Draw a colored quad to hide single-pixel "leaking" from beneath. - xPos = mul16(intToFixed16(25), hudScaleX) + x0; - yPos = mul16(intToFixed16(12), hudScaleY) + y0; - fixed16_16 quadWidth = mul16(intToFixed16(11), hudScaleX); - fixed16_16 quadHeight = mul16(intToFixed16(7), hudScaleY); - - screenGPU_drawColoredQuad(xPos, yPos, xPos + quadWidth, yPos + quadHeight, 0); - - if (ammo1 < 0) - { - strcpy(str, "::"); - } - else - { - sprintf(str, "%02d", ammo1); - } - hud_drawStringGpu(s_hudShieldFont, xPos, yPos, hudScaleX, hudScaleY, str); - - s_rightHudShow = 4; - } - - if (s_rightHudShow) - { - if (s_rightHudVertAnim > s_rightHudVertTarget) - { - s_rightHudVertAnim--; - } - else if (s_rightHudVertAnim < s_rightHudVertTarget) - { - s_rightHudVertAnim++; - s_rightHudMove = 4; - } - else if (s_rightHudShow) - { - s_rightHudShow--; - } - } - if (s_leftHudShow) - { - if (s_leftHudVertAnim > s_leftHudVertTarget) - { - s_leftHudVertAnim--; - s_leftHudMove = 4; - } - else if (s_leftHudVertAnim < s_leftHudVertTarget) - { - s_leftHudVertAnim++; - s_leftHudMove = 4; - } - else if (s_leftHudShow) - { - s_leftHudShow--; - } - } - } - - void hud_drawAndUpdate(u8* framebuffer) - { - // Handle the case where the HUD has not been loaded. - if (!s_hudStatusL || !s_hudStatusR) { return; } - - ScreenRect* screenRect = vfb_getScreenRect(VFB_RECT_UI); - - // TFE Note: drawing the HUD when GPU rendering is enabled is a bit different, since we can just draw all of the items scaled. - if (TFE_Jedi::getSubRenderer() == TSR_CLASSIC_GPU) - { - hud_drawGpu(); - return; - } - - // Clear the 3D view while the HUD positions are being animated. - if (s_rightHudMove || s_leftHudMove) - { - if (s_rightHudMove) - { - s_rightHudMove--; - } - if (s_leftHudMove) - { - s_leftHudMove--; - } - clear3DView(framebuffer); - } - - // Go ahead and just update the HUD every frame, there are already checks to see if each item changed. - //if (s_leftHudShow || s_rightHudShow) - { - fixed16_16 batteryPower = TFE_Jedi::abs(s_batteryPower * 100); - s32 percent = round16(batteryPower >> 1); - if (s_prevBatteryPower != percent) // True when energy ticks down. - { - s_prevBatteryPower = percent; - const s32 offset = 3 * 3 + 1; // offset 3 color indices + 1 because we are only changing the green color. - // I think this should be < 5, since there are 5 pips. - // This actually overwrites memory in DOS, but here I just made the array larger. - for (s32 clrIndex = 0; clrIndex <= 5; clrIndex++) - { - if (percent > 20) - { - s_hudWorkPalette[3 * clrIndex + offset] = 58; - percent -= 20; - } - else - { - // Color value between [8, 58], where 8 @ 0% and 58 @ 20% - s_hudWorkPalette[3 * clrIndex + offset] = 8 + ((percent * 5) >> 1); - percent = 0; - } - } - } - s32 lifeCount = player_getLifeCount() % 10; - if (s_prevLifeCount != lifeCount) - { - s_prevLifeCount = lifeCount; - - char lifeCountStr[8]; - sprintf(lifeCountStr, "%1d", lifeCount); - hud_drawString(s_cachedHudLeft, s_hudHealthFont, 52, 26, lifeCountStr); - - s_rightHudShow = 4; - } - if (s_prevHeadlampActive != s_headlampActive) - { - s_prevHeadlampActive = s_headlampActive; - if (s_headlampActive) - { - offscreenBuffer_drawTexture(s_cachedHudRight, s_hudLightOn, 19, 0); - } - else - { - offscreenBuffer_drawTexture(s_cachedHudRight, s_hudLightOff, 19, 0); - } - s_rightHudShow = 4; - } - if (s_playerInfo.shields != s_prevShields) - { - char shieldStr[8]; - - if (s_playerInfo.shields == -1) - { - s_hudWorkPalette[0] = 55; - s_hudWorkPalette[1] = 55; - s_hudWorkPalette[3] = 55; - s_hudWorkPalette[4] = 55; - - strcpy(shieldStr, "200"); - } - else - { - s_hudWorkPalette[0] = 0; - s32 upperShields; - if (s_playerInfo.shields > 100) - { - upperShields = s_playerInfo.shields; - } - else - { - upperShields = 100; - } - upperShields -= 100; - u8 upperColor = 8 + (upperShields >> 1); - s_hudWorkPalette[1] = upperColor; - - s_hudWorkPalette[3] = 0; - s32 lowerShields; - if (s_playerInfo.shields < 100) - { - lowerShields = s_playerInfo.shields; - } - else - { - lowerShields = 100; - } - s_hudWorkPalette[4] = 8 + (lowerShields >> 1); - sprintf(shieldStr, "%03d", s_playerInfo.shields); - } - s_prevShields = s_playerInfo.shields; - hud_drawString(s_cachedHudLeft, s_hudShieldFont, 15, 26, shieldStr); - } - if (s_playerInfo.health != s_prevHealth) - { - s32 health = min(100, s_playerInfo.health); - // 6: color 2, red channel, 7 = green channel - s_hudWorkPalette[6] = 8 + (health >> 1); - s_hudWorkPalette[7] = health * 63 / 400; - s_prevHealth = s_playerInfo.health; - - char healthStr[32]; - sprintf(healthStr, "%03d", s_playerInfo.health); - hud_drawString(s_cachedHudLeft, s_hudHealthFont, 33, 26, healthStr); - - s_leftHudShow = 4; - } - - if (s_forceHudPaletteUpdate || memcmp(s_hudPalette, s_hudWorkPalette, HUD_COLORS_COUNT * 3) != 0) - { - // Copy work palette into hud palette. - memcpy(s_hudPalette, s_hudWorkPalette, HUD_COLORS_COUNT * 3); - // Copy hud palette into the base palette, this will update next time render_setPalette() is called. - hud_updateBasePalette(s_hudPalette, HUD_COLORS_START, HUD_COLORS_COUNT); - // Copy the final 8 HUD colors to the loaded palette. - memcpy(s_levelPalette + HUD_COLORS_START * 3, s_hudPalette, HUD_COLORS_COUNT * 3); - - s_forceHudPaletteUpdate = JFALSE; - } - - s32 ammo0 = -1; - s32 ammo1 = -1; - PlayerWeapon* weapon = s_curPlayerWeapon; - if (weapon) - { - if (weapon->ammo) - { - ammo0 = *weapon->ammo; - } - if (weapon->secondaryAmmo) - { - ammo1 = *weapon->secondaryAmmo; - } - } - - if (ammo0 != s_prevPrimaryAmmo || ammo1 != s_prevSecondaryAmmo || s_superChargeHud != s_prevSuperchageHud) - { - char str[32]; - if (ammo0 < 0) - { - strcpy(str, ":::"); - } - else - { - sprintf(str, "%03d", ammo0); - } - hud_drawString(s_cachedHudRight, s_superChargeHud ? s_hudSuperAmmoFont : s_hudMainAmmoFont, 12, 21, str); - - if (ammo1 < 0) - { - strcpy(str, "::"); - } - else - { - sprintf(str, "%02d", ammo1); - } - hud_drawString(s_cachedHudRight, s_hudShieldFont, 25, 12, str); - - s_rightHudShow = 4; - s_prevPrimaryAmmo = ammo0; - s_prevSecondaryAmmo = ammo1; - s_prevSuperchageHud = s_superChargeHud; - } - - if (s_rightHudShow || screenRect->bot >= 160) - { - if (s_rightHudVertAnim > s_rightHudVertTarget) - { - s_rightHudVertAnim--; - } - else if (s_rightHudVertAnim < s_rightHudVertTarget) - { - s_rightHudVertAnim++; - s_rightHudMove = 4; - } - else if (s_rightHudShow) - { - s_rightHudShow--; - } - } - if (s_leftHudShow || screenRect->bot >= 160) - { - if (s_leftHudVertAnim > s_leftHudVertTarget) - { - s_leftHudVertAnim--; - s_leftHudMove = 4; - } - else if (s_leftHudVertAnim < s_leftHudVertTarget) - { - s_leftHudVertAnim++; - s_leftHudMove = 4; - } - else if (s_leftHudShow) - { - s_leftHudShow--; - } - } - } - assert(s_rightHudVertAnim >= 0 && s_rightHudVertAnim < 4); - u32 dispWidth, dispHeight; - vfb_getResolution(&dispWidth, &dispHeight); - if (dispWidth == 320 && dispHeight == 200) - { - // The original 320x200 code. - hud_drawElementToScreen(s_cachedHudRight, screenRect, 260, c_hudVertAnimTable[s_rightHudVertAnim], framebuffer); - hud_drawElementToScreen(s_cachedHudLeft, screenRect, 0, c_hudVertAnimTable[s_leftHudVertAnim], framebuffer); - } - else - { - TFE_Settings_Hud* hudSettings = TFE_Settings::getHudSettings(); - - // HUD scaling. - fixed16_16 xScale = vfb_getXScale(); - fixed16_16 yScale = vfb_getYScale(); - fixed16_16 hudScaleX = xScale; - fixed16_16 hudScaleY = yScale; - u32 dispWidth, dispHeight; - vfb_getResolution(&dispWidth, &dispHeight); - - if (hudSettings->hudScale == TFE_HUDSCALE_SCALED) - { - hudScaleX = floatToFixed16(hudSettings->scale); - hudScaleY = floatToFixed16(hudSettings->scale); - } - else if (hudSettings->scale != 0) - { - hudScaleX = floatToFixed16(fixed16ToFloat(xScale) * hudSettings->scale); - hudScaleY = floatToFixed16(fixed16ToFloat(yScale) * hudSettings->scale); - } - - s32 x0, x1; - if (hudSettings->hudPos == TFE_HUDPOS_4_3) - { - x0 = floor16(mul16(intToFixed16(260), xScale)) + vfb_getWidescreenOffset(); - x1 = vfb_getWidescreenOffset(); - } - else - { - x0 = dispWidth - floor16(mul16(intToFixed16(s_cachedHudRight->width - 1), hudScaleX)); - x1 = 0; - } - x0 -= hudSettings->pixelOffset[0]; - x1 += hudSettings->pixelOffset[1]; - - s32 y0 = floor16(yScale + mul16(intToFixed16(c_hudVertAnimTable[s_rightHudVertAnim]), yScale)); - s32 y1 = floor16(yScale + mul16(intToFixed16(c_hudVertAnimTable[s_leftHudVertAnim]), yScale)); - y0 += hudSettings->pixelOffset[2]; - y1 += hudSettings->pixelOffset[2]; - - hud_drawElementToScreenScaled(s_cachedHudRight, screenRect, x0, y0, hudScaleX, hudScaleY, framebuffer); - hud_drawElementToScreenScaled(s_cachedHudLeft, screenRect, x1, y1, hudScaleX, hudScaleY, framebuffer); - - if ((hudSettings->hudPos == TFE_HUDPOS_4_3 || hudSettings->pixelOffset[0] > 0 || hudSettings->pixelOffset[1] > 0) && - s_hudCapLeft && s_hudCapRight) - { - DrawRect rect = { screenRect->left, screenRect->top, screenRect->right, screenRect->bot }; - s32 y0Scaled = (dispHeight == 200) ? y0 : floor16(intToFixed16(y0) + mul16(ONE_16, hudScaleY)); - s32 y1Scaled = (dispHeight == 200) ? y1 : floor16(intToFixed16(y1) + mul16(ONE_16, hudScaleY)); - - blitTextureToScreenScaled(s_hudCapLeft, &rect, floor16(intToFixed16(x1) - mul16(intToFixed16(s_hudCapLeft->width - 1), hudScaleX)), y1Scaled, hudScaleX, hudScaleY, framebuffer); - blitTextureToScreenScaled(s_hudCapRight, &rect, floor16(intToFixed16(x0) + mul16(intToFixed16(s_hudStatusR->width - 1), hudScaleX)), y0Scaled, hudScaleX, hudScaleY, framebuffer); - } - } - } - - /////////////////////////////////////////// - // Internal Implementation - /////////////////////////////////////////// - TextureData* hud_loadTexture(const char* texFile) - { - TextureData* hudTex = bitmap_load(texFile, 0, POOL_GAME); - if (!hudTex) - { - TFE_System::logWrite(LOG_ERROR, "HUD", "Cannot load texture '%s'", texFile); - } - return hudTex; - } - - Font* hud_loadFont(const char* fontFile) - { - FilePath filePath; - if (TFE_Paths::getFilePath(fontFile, &filePath)) - { - return font_load(&filePath); - } - TFE_System::logWrite(LOG_ERROR, "HUD", "Cannot load font '%s'", fontFile); - return nullptr; - } - - void copyIntoPalette(u8* dst, u8* src, s32 count, s32 mode) - { - memcpy(dst, src, count * 3); - } - - void getCameraXZ(fixed16_16* x, fixed16_16* z) - { - if (s_drawAutomap) - { - *x = s_mapX0; - *z = s_mapZ0; - } - else - { - *x = s_eyePos.x; - *z = s_eyePos.z; - } - } - - void displayHudMessage(Font* font, DrawRect* rect, s32 x, s32 y, u8* msg, u8* framebuffer) - { - if (!font || !rect || !framebuffer) { return; } - u32 dispWidth, dispHeight; - vfb_getResolution(&dispWidth, &dispHeight); - - if (dispHeight == 200) - { - s32 xi = x; - s32 x0 = x; - for (u8 c = *msg; c != 0;) - { - if (c == '\n') - { - xi = x0; - y += font->height + font->vertSpacing; - } - else if (c == ' ') - { - xi += font->width; - } - else if (c >= font->minChar && c <= font->maxChar) - { - s32 charIndex = c - font->minChar; - TextureData* glyph = &font->glyphs[charIndex]; - blitTextureToScreen(glyph, rect, xi, y, framebuffer); - - xi += font->horzSpacing + glyph->width; - } - msg++; - c = *msg; - } - } - else - { - fixed16_16 xScale = vfb_getXScale(); - fixed16_16 yScale = vfb_getYScale(); - - fixed16_16 xf = mul16(intToFixed16(x), xScale); - fixed16_16 yf = mul16(intToFixed16(y), yScale); - fixed16_16 x0 = xf; - - fixed16_16 fWidth = mul16(intToFixed16(font->width), xScale); - for (u8 c = *msg; c != 0;) - { - if (c == '\n') - { - xf = x0; - yf += mul16(intToFixed16(font->height + font->vertSpacing), yScale); - } - else if (c == ' ') - { - xf += fWidth; - } - else if (c >= font->minChar && c <= font->maxChar) - { - s32 charIndex = c - font->minChar; - TextureData* glyph = &font->glyphs[charIndex]; - blitTextureToScreenScaledText(glyph, rect, floor16(xf), floor16(yf), xScale, yScale, framebuffer); - xf += mul16(intToFixed16(font->horzSpacing + glyph->width), xScale); - } - msg++; - c = *msg; - } - } - } - - void hud_drawString(OffScreenBuffer* elem, Font* font, s32 x0, s32 y0, const char* str) - { - if (!font) { return; } - - s32 x = x0; - s32 y = y0; - for (char c = *str; c != 0; ) - { - if (c == '\n') - { - y += font->height + font->vertSpacing; - x = x0; - } - else - { - if (c == ' ') - { - x += font->width; - } - else if (c >= font->minChar && c <= font->maxChar) - { - s32 charIndex = c - font->minChar; - s32 offset = charIndex * 28; - - TextureData* glyph = &font->glyphs[charIndex]; - offscreenBuffer_drawTexture(elem, glyph, x, y); - x += glyph->width + font->horzSpacing; - } - } - str++; - c = *str; - } - } - - void hud_drawElementToScreen(OffScreenBuffer* elem, ScreenRect* rect, s32 x0, s32 y0, u8* framebuffer) - { - s32 x1 = x0 + elem->width - 1; - u8* image = elem->image; - s32 y1 = y0 + elem->height - 1; - if (x0 > rect->right || x1 < rect->left || y0 > rect->bot || y1 < rect->top) - { - return; - } - if (y0 < rect->top) - { - image += (rect->top - y0) * elem->width; - y0 = rect->top; - } - if (y1 > rect->bot) - { - y1 = rect->bot; - } - if (x0 < rect->left) - { - image += rect->left - x0; - x0 = rect->left; - } - if (x1 > rect->right) - { - x1 = rect->right; - } - const u32 stride = vfb_getStride(); - s32 yOffset = y0 * stride; - if (elem->flags & OBF_TRANS) - { - for (s32 x = x0; x <= x1; x++) - { - u8* output = framebuffer + x + yOffset; - u8* imageSrc = image + x - x0; - for (s32 y = y0; y <= y1; y++, output += stride, imageSrc += elem->width) - { - u8 color = *imageSrc; - if (color) - { - *output = color; - } - } - } - } - else - { - for (s32 x = x0; x <= x1; x++) - { - u8* output = framebuffer + x + yOffset; - u8* imageSrc = image + x - x0; - for (s32 y = y0; y <= y1; y++, output += stride, imageSrc += elem->width) - { - *output = *imageSrc; - } - } - } - } - - void hud_drawElementToScreenScaled(OffScreenBuffer* elem, ScreenRect* rect, s32 x0, s32 y0, fixed16_16 xScale, fixed16_16 yScale, u8* framebuffer) - { - ScreenImage image = - { - elem->width, - elem->height, - elem->image, - (elem->flags & OBF_TRANS) ? JTRUE : JFALSE, - JFALSE - }; - blitTextureToScreenScaled(&image, (DrawRect*)rect, x0, y0, xScale, yScale, framebuffer); - } - - // This should not be enabled in released builds - it is only kept in case the images need to be regenerated. -#if TFE_CONVERT_CAPS - u8 hud_findColorInPalette(u32 color, u32 colorCount, const u8* colors, const u8* palette) - { - // Transparent. - if ((color >> 24) < 16) - { - return 0; - } - - s32 srcR = color & 0xff; - s32 srcG = (color >> 8) & 0xff; - s32 srcB = (color >> 16) & 0xff; - s32 colorDist = INT_MAX; - s32 match = -1; - for (u32 i = 0; i < colorCount; i++) - { - s32 dstR = CONV_6bitTo8bit(palette[colors[i] * 3 + 0]); - s32 dstG = CONV_6bitTo8bit(palette[colors[i] * 3 + 1]); - s32 dstB = CONV_6bitTo8bit(palette[colors[i] * 3 + 2]); - s32 distApprox = TFE_Jedi::abs(srcR - dstR) + TFE_Jedi::abs(srcG - dstG) + TFE_Jedi::abs(srcB - dstB); - if (distApprox < colorDist) - { - colorDist = distApprox; - match = colors[i]; - } - } - assert(colorDist < 4); - return match >= 0 ? match : 0; - } - - void hud_convertPngToBM(const char* path, const char* name, u32 colorCount, const u8* colors, const u8* palette) - { - char srcPath[TFE_MAX_PATH]; - char dstPath[TFE_MAX_PATH]; - sprintf(srcPath, "%sTFE/AdjustableHud/%s.png", path, name); - sprintf(dstPath, "%sTFE/AdjustableHud/%s.bm", path, name); - - Image* srcImage = TFE_Image::get(srcPath); - if (!srcImage) { return; } - - u32 pixelCount = srcImage->width * srcImage->height; - u8* output = (u8*)malloc(pixelCount); - const u32* input = srcImage->data; - // Convert to column format. - for (u32 y = 0; y < srcImage->height; y++) - { - for (u32 x = 0; x < srcImage->width; x++) - { - output[x*srcImage->height + y] = hud_findColorInPalette(input[(srcImage->height - y - 1)*srcImage->width + x], colorCount, colors, palette); - } - } - - bitmap_writeTransparent(dstPath, u16(srcImage->width), u16(srcImage->height), output); - free(output); - } - - void hud_convertCapsToBM() - { - // First make sure the colors match, so grab all colors used by the original HUD backgrounds. - u8 colorMap[256] = { 0 }; - u8 colors[256]; - u8 colorCount = 0; - const u8* image = s_hudStatusL->image; - for (s32 i = 0; i < s_hudStatusL->dataSize; i++) - { - if (image[i] == 0) { continue; } - if (colorMap[image[i]] == 0) - { - colorMap[image[i]] = 1; - colors[colorCount++] = image[i]; - } - } - - image = s_hudStatusR->image; - for (s32 i = 0; i < s_hudStatusR->dataSize; i++) - { - if (image[i] == 0) { continue; } - if (colorMap[image[i]] == 0) - { - colorMap[image[i]] = 1; - colors[colorCount++] = image[i]; - } - } - - // Load default palette. - FilePath filePath; - u8 pal[768]; - if (TFE_Paths::getFilePath("SECBASE.PAL", &filePath)) - { - FileStream::readContents(&filePath, pal, 768); - } - - // Next load the true-color images. - const char* programDir = TFE_Paths::getPath(PATH_PROGRAM); - char programDirModDir[TFE_MAX_PATH]; - sprintf(programDirModDir, "%sMods/", programDir); - TFE_Paths::fixupPathAsDirectory(programDirModDir); - - hud_convertPngToBM(programDirModDir, "HudStatusLeftAddon", colorCount, colors, pal); - hud_convertPngToBM(programDirModDir, "HudStatusRightAddon", colorCount, colors, pal); - } -#endif -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/hud.h b/components/darkforces/tfe/TFE_DarkForces/hud.h deleted file mode 100644 index 90d87c7a..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/hud.h +++ /dev/null @@ -1,41 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces HUD - -// This handles the heads up display and on-screen messages during -// gameplay. -////////////////////////////////////////////////////////////////////// -#include -#include - -using namespace TFE_Jedi; - -struct OffScreenBuffer; -struct ScreenRect; - -namespace TFE_DarkForces -{ - void hud_sendTextMessage(s32 msgId); - void hud_sendTextMessage(const char* msg, s32 priority); - void hud_clearMessage(); - - void hud_loadGameMessages(); - void hud_loadGraphics(); - void hud_reset(); - - void hud_startup(JBool fromSave); - void hud_initAnimation(); - void hud_toggleDataDisplay(); - JBool hud_setupToggleAnim1(JBool enable); - - void hud_drawMessage(u8* framebuffer); - void hud_drawAndUpdate(u8* framebuffer); - void hud_drawElementToScreen(OffScreenBuffer* elem, ScreenRect* rect, s32 x0, s32 y0, u8* framebuffer); - void hud_drawElementToScreenScaled(OffScreenBuffer* elem, ScreenRect* rect, s32 x0, s32 y0, fixed16_16 xScale, fixed16_16 yScale, u8* framebuffer); - - extern fixed16_16 s_flashEffect; - extern fixed16_16 s_healthDamageFx; - extern fixed16_16 s_shieldDamageFx; - extern s32 s_secretsFound; - extern s32 s_secretsPercent; - extern JBool s_showData; -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/item.cpp b/components/darkforces/tfe/TFE_DarkForces/item.cpp deleted file mode 100644 index 733e1179..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/item.cpp +++ /dev/null @@ -1,119 +0,0 @@ -#include - -#include "item.h" -#include "pickup.h" -#include "animLogic.h" -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - /////////////////////////////////////////// - // Constants - /////////////////////////////////////////// - // TODO: Move into data file for TFE, rather than hardcoding here. - static const char* c_itemResoure[ITEM_COUNT] = - { - "IDPLANS.WAX", // ITEM_PLANS - "IPHRIK.WAX", // ITEM_PHRIK - "INAVA.WAX", // ITEM_NAVA - "IDTGUN.WAX", // ITEM_DT_WEAPON - "IDATA.FME", // ITEM_DATATAPE - "IST-GUNI.FME", // ITEM_RIFLE - "IAUTOGUN.FME", // ITEM_AUTOGUN - "IMORTAR.FME", // ITEM_MORTAR - "IFUSION.FME", // ITEM_FUSION - "ICONCUS.FME", // ITEM_CONCUSSION - "ICANNON.FME", // ITEM_CANNON - "IENERGY.FME", // ITEM_ENERGY - "IPOWER.FME", // ITEM_POWER - "IPLAZMA.FME", // ITEM_PLASMA - "IDET.FME", // ITEM_DETONATOR - "IDETS.FME", // ITEM_DETONATORS - "ISHELL.FME", // ITEM_SHELL - "ISHELLS.FME", // ITEM_SHELLS - "IMINE.FME", // ITEM_MINE - "IMINES.FME", // ITEM_MINES - "IMSL.FME", // ITEM_MISSILE - "IMSLS.FME", // ITEM_MISSILES - "IARMOR.WAX", // ITEM_SHIELD - "IKEYR.FME", // ITEM_RED_KEY - "IKEYY.FME", // ITEM_YELLOW_KEY - "IKEYB.FME", // ITEM_BLUE_KEY - "IGOGGLES.FME", // ITEM_GOGGLES - "ICLEATS.FME", // ITEM_CLEATS - "IMASK.FME", // ITEM_MASK - "IBATTERY.FME", // ITEM_BATTERY - "DET_CODE.FME", // ITEM_CODE1 - "DET_CODE.FME", // ITEM_CODE2 - "DET_CODE.FME", // ITEM_CODE3 - "DET_CODE.FME", // ITEM_CODE4 - "DET_CODE.FME", // ITEM_CODE5 - "DET_CODE.FME", // ITEM_CODE6 - "DET_CODE.FME", // ITEM_CODE7 - "DET_CODE.FME", // ITEM_CODE8 - "DET_CODE.FME", // ITEM_CODE9 - "IINVINC.WAX", // ITEM_INVINCIBLE - "ICHARGE.FME", // ITEM_SUPERCHARGE - "IREVIVE.WAX", // ITEM_REVIVE - "ILIFE.WAX", // ITEM_LIFE - "IMEDKIT.FME", // ITEM_MEDKIT - "IPILE.FME", // ITEM_PILE - }; - - /////////////////////////////////////////// - // Shared State - /////////////////////////////////////////// - SoundSourceId s_powerupPickupSnd; - SoundSourceId s_invItemPickupSnd; - SoundSourceId s_wpnPickupSnd; - ItemData s_itemData[ITEM_COUNT]; - - /////////////////////////////////////////// - // API Implementation - /////////////////////////////////////////// - void item_loadData() - { - s_powerupPickupSnd = sound_load("bonus.voc", SOUND_PRIORITY_HIGH4); - s_invItemPickupSnd = sound_load("complete.voc", SOUND_PRIORITY_HIGH5); - s_wpnPickupSnd = sound_load("key.voc", SOUND_PRIORITY_MED5); - - for (s32 i = 0; i < ITEM_COUNT; i++) - { - const char* item = c_itemResoure[i]; - if (strstr(item, ".WAX")) - { - s_itemData[i].wax = TFE_Sprite_Jedi::getWax(item, POOL_GAME); - s_itemData[i].isWax = JTRUE; - } - else - { - s_itemData[i].frame = TFE_Sprite_Jedi::getFrame(item, POOL_GAME); - s_itemData[i].isWax = JFALSE; - } - } - } - - SecObject* item_create(ItemId itemId) - { - SecObject* newObj = allocateObject(); - - if (s_itemData[itemId].isWax) - { - sprite_setData(newObj, s_itemData[itemId].wax); - } - else - { - frame_setData(newObj, s_itemData[itemId].frame); - } - - obj_createPickup(newObj, itemId); - if (s_itemData[itemId].isWax) - { - obj_setSpriteAnim(newObj); - } - - return newObj; - } -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/item.h b/components/darkforces/tfe/TFE_DarkForces/item.h deleted file mode 100644 index de5126fe..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/item.h +++ /dev/null @@ -1,92 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces Item IDs. -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include "sound.h" - -namespace TFE_DarkForces -{ - enum ItemId - { - ITEM_NONE = -1, // -1 - ITEM_PLANS = 0, // 0x00 - ITEM_PHRIK = 1, // 0x01 - ITEM_NAVA = 2, // 0x02 - ITEM_DT_WEAPON = 3, // 0x03 - ITEM_DATATAPE = 4, // 0x04 - ITEM_RIFLE = 5, // 0x05 - ITEM_AUTOGUN = 6, // 0x06 - ITEM_MORTAR = 7, // 0x07 - ITEM_FUSION = 8, // 0x08 - ITEM_CONCUSSION = 9, // 0x09 - ITEM_CANNON = 10, // 0x0a - ITEM_ENERGY = 11, // 0x0b - ITEM_POWER = 12, // 0x0c - ITEM_PLASMA = 13, // 0x0d - ITEM_DETONATOR = 14, // 0x0e - ITEM_DETONATORS = 15, // 0x0f - ITEM_SHELL = 16, // 0x10 - ITEM_SHELLS = 17, // 0x11 - ITEM_MINE = 18, // 0x12 - ITEM_MINES = 19, // 0x13 - ITEM_MISSILE = 20, // 0x14 - ITEM_MISSILES = 21, // 0x15 - ITEM_SHIELD = 22, // 0x16 - ITEM_RED_KEY = 23, // 0x17 - ITEM_YELLOW_KEY = 24, // 0x18 - ITEM_BLUE_KEY = 25, // 0x19 - ITEM_GOGGLES = 26, // 0x1a - ITEM_CLEATS = 27, // 0x1b - ITEM_MASK = 28, // 0x1c - ITEM_BATTERY = 29, // 0x1d - ITEM_CODE1 = 30, // 0x1e - ITEM_CODE2 = 31, // 0x1f - ITEM_CODE3 = 32, // 0x20 - ITEM_CODE4 = 33, // 0x21 - ITEM_CODE5 = 34, // 0x22 - ITEM_CODE6 = 35, // 0x23 - ITEM_CODE7 = 36, // 0x24 - ITEM_CODE8 = 37, // 0x25 - ITEM_CODE9 = 38, // 0x26 - ITEM_INVINCIBLE = 39, // 0x27 - ITEM_SUPERCHARGE = 40, // 0x28 - ITEM_REVIVE = 41, // 0x29 - ITEM_LIFE = 42, // 0x2a - ITEM_MEDKIT = 43, // 0x2b - ITEM_PILE = 44, // 0x2c - ITEM_COUNT = 45, // 0x2d - }; - - enum ItemType - { - ITYPE_NONE = 0, - ITYPE_OBJECTIVE= 1, // Mission objective item. - ITYPE_WEAPON = 2, // Weapons - ITYPE_AMMO = 4, // Pickups that refill ammo, health, shields, etc. - ITYPE_KEY_ITEM = 8, // Keys and usable inventory items. - ITYPE_INV_ITEM = 16, // Non-usable Inventory Items - ITYPE_POWERUP = 32, // Powerups & Extra lives. - ITYPE_SPECIAL = 64, // Special - only a single item fits in this type (ITEM_PILE). - }; - - struct ItemData - { - union - { - Wax* wax; - WaxFrame* frame; - }; - JBool isWax; - }; - - extern SoundSourceId s_powerupPickupSnd; - extern SoundSourceId s_invItemPickupSnd; - extern SoundSourceId s_wpnPickupSnd; - extern ItemData s_itemData[ITEM_COUNT]; - - void item_loadData(); - SecObject* item_create(ItemId itemId); -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/logic.cpp b/components/darkforces/tfe/TFE_DarkForces/logic.cpp deleted file mode 100644 index bc070999..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/logic.cpp +++ /dev/null @@ -1,439 +0,0 @@ -#include - -#include "logic.h" -#include "pickup.h" -#include "player.h" -#include "updateLogic.h" -#include "animLogic.h" -#include "vueLogic.h" -#include "projectile.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// Regular Enemies -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// Bosses -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - char s_objSeqArg0[256]; - char s_objSeqArg1[256]; - char s_objSeqArg2[256]; - char s_objSeqArg3[256]; - char s_objSeqArg4[256]; - char s_objSeqArg5[256]; - s32 s_objSeqArgCount; - - Logic* obj_setEnemyLogic(SecObject* obj, KEYWORD logicId, LogicSetupFunc* setupFunc); - - void obj_addLogic(SecObject* obj, Logic* logic, LogicType type, Task* task, LogicCleanupFunc cleanupFunc) - { - if (!obj->logic) - { - obj->logic = allocator_create(sizeof(Logic**)); - } - - Logic** logicItem = (Logic**)allocator_newItem((Allocator*)obj->logic); - *logicItem = logic; - logic->obj = obj; - logic->type = type; - logic->parent = logicItem; - logic->task = task; - logic->cleanupFunc = cleanupFunc; - } - - void deleteLogicAndObject(Logic* logic) - { - if (s_freeObjLock) { return; } - - SecObject* obj = logic->obj; - Logic** parent = logic->parent; - Logic** logics = (Logic**)allocator_getHead_noIterUpdate((Allocator*)obj->logic); - - allocator_deleteItem((Allocator*)obj->logic, parent); - if (parent == logics) - { - freeObject(obj); - } - } - - JBool logic_defaultSetupFunc(SecObject* obj, KEYWORD key) - { - char* endPtr; - JBool retValue = JTRUE; - if (key == KW_EYE) - { - player_setupEyeObject(obj); - } - else if (key == KW_BOSS) - { - obj->flags |= OBJ_FLAG_BOSS; - } - else if (key == KW_HEIGHT) - { - obj->worldHeight = floatToFixed16(strtof(s_objSeqArg1, &endPtr)); - } - else if (key == KW_RADIUS) - { - obj->worldWidth = floatToFixed16(strtof(s_objSeqArg1, &endPtr)); - } - else // Invalid key. - { - retValue = JFALSE; - } - return retValue; - } - - JBool object_parseSeq(SecObject* obj, TFE_Parser* parser, size_t* bufferPos) - { - LogicSetupFunc setupFunc = nullptr; - - const char* line = parser->readLine(*bufferPos); - if (!line || !strstr(line, "SEQ")) - { - return JFALSE; - } - - Logic* newLogic = nullptr; - while (1) - { - line = parser->readLine(*bufferPos); - if (!line) { return JFALSE; } - - s_objSeqArgCount = sscanf(line, " %s %s %s %s %s %s", s_objSeqArg0, s_objSeqArg1, s_objSeqArg2, s_objSeqArg3, s_objSeqArg4, s_objSeqArg5); - KEYWORD key = getKeywordIndex(s_objSeqArg0); - if (key == KW_TYPE || key == KW_LOGIC) - { - KEYWORD logicId = getKeywordIndex(s_objSeqArg1); - if (logicId == KW_PLAYER) // Player Logic. - { - player_setupObject(obj); - setupFunc = nullptr; - } - else if (logicId == KW_ANIM) // Animated Sprites Logic. - { - newLogic = obj_setSpriteAnim(obj); - } - else if (logicId == KW_UPDATE) // "Update" logic is usually used for rotating 3D objects, like the Death Star. - { - newLogic = obj_setUpdate(obj, &setupFunc); - } - else if (logicId >= KW_TROOP && logicId <= KW_SCENERY) // Enemies, explosives barrels, land mines, and scenery. - { - newLogic = obj_setEnemyLogic(obj, logicId, &setupFunc); - } - else if (logicId == KW_KEY) // Vue animation logic. - { - newLogic = obj_createVueLogic(obj, &setupFunc); - } - else if (logicId == KW_GENERATOR) // Enemy generator, used for in-level enemy spawning. - { - KEYWORD genType = getKeywordIndex(s_objSeqArg2); - newLogic = obj_createGenerator(obj, &setupFunc, genType); - } - else if (logicId == KW_DISPATCH) - { - newLogic = (Logic*)actor_createDispatch(obj, &setupFunc); - } - else if ((logicId >= KW_BATTERY && logicId <= KW_AUTOGUN) || logicId == KW_ITEM) - { - if (logicId >= KW_BATTERY && logicId <= KW_AUTOGUN) - { - strcpy(s_objSeqArg2, s_objSeqArg1); - } - ItemId itemId = getPickupItemId(s_objSeqArg2); - obj_createPickup(obj, itemId); - setupFunc = nullptr; - } - } - else if (key == KW_SEQEND) - { - return JTRUE; - } - else - { - if (setupFunc && setupFunc(newLogic, key)) - { - continue; - } - logic_defaultSetupFunc(obj, key); - } - } - - return JTRUE; - } - - Logic* obj_setEnemyLogic(SecObject* obj, KEYWORD logicId, LogicSetupFunc* setupFunc) - { - obj->flags |= OBJ_FLAG_AIM; - - switch (logicId) - { - case KW_TROOP: - case KW_STORM1: - { - obj->entityFlags = ETFLAG_AI_ACTOR | ETFLAG_HAS_GRAVITY; - return trooper_setup(obj, setupFunc); - } break; - case KW_INT_DROID: - { - obj->entityFlags = (ETFLAG_AI_ACTOR | ETFLAG_FLYING); - return intDroid_setup(obj, setupFunc); - } break; - case KW_PROBE_DROID: - { - obj->entityFlags = (ETFLAG_AI_ACTOR | ETFLAG_FLYING); - return probeDroid_setup(obj, setupFunc); - } break; - case KW_D_TROOP1: - { - return phaseOne_setup(obj, setupFunc); - } break; - case KW_D_TROOP2: - { - return phaseTwo_setup(obj, setupFunc); - } break; - case KW_D_TROOP3: - { - return phaseThree_setup(obj, setupFunc); - } break; - case KW_BOBA_FETT: - { - return bobaFett_setup(obj, setupFunc); - } break; - case KW_COMMANDO: - { - obj->entityFlags = ETFLAG_AI_ACTOR | ETFLAG_HAS_GRAVITY; - return commando_setup(obj, setupFunc); - } break; - case KW_I_OFFICER: - case KW_I_OFFICER1: - case KW_I_OFFICER2: - case KW_I_OFFICER3: - case KW_I_OFFICER4: - case KW_I_OFFICER5: - case KW_I_OFFICER6: - case KW_I_OFFICER7: - case KW_I_OFFICER8: - case KW_I_OFFICER9: - case KW_I_OFFICERR: - case KW_I_OFFICERY: - case KW_I_OFFICERB: - { - obj->entityFlags = ETFLAG_AI_ACTOR | ETFLAG_HAS_GRAVITY; - return officer_setup(obj, setupFunc, logicId); - } break; - case KW_G_GUARD: - { - obj->entityFlags = ETFLAG_AI_ACTOR | ETFLAG_HAS_GRAVITY; - return gamor_setup(obj, setupFunc); - } break; - case KW_REE_YEES: - { - obj->entityFlags = ETFLAG_AI_ACTOR | ETFLAG_HAS_GRAVITY; - return reeyees_setup(obj, setupFunc); - } break; - case KW_REE_YEES2: - { - obj->entityFlags = ETFLAG_AI_ACTOR | ETFLAG_HAS_GRAVITY; - return reeyees2_setup(obj, setupFunc); - } break; - case KW_BOSSK: - { - obj->entityFlags = ETFLAG_AI_ACTOR | ETFLAG_HAS_GRAVITY; - return bossk_setup(obj, setupFunc); - } break; - case KW_BARREL: - { - obj->entityFlags = ETFLAG_AI_ACTOR; - return barrel_setup(obj, setupFunc); - } break; - case KW_LAND_MINE: - { - ProjectileLogic* mineLogic = (ProjectileLogic*)createProjectile(PROJ_LAND_MINE_PLACED, obj->sector, obj->posWS.x, obj->posWS.y, obj->posWS.z, obj); - freeObject(obj); - - SecObject* mineObj = mineLogic->logic.obj; - mineObj->entityFlags |= ETFLAG_LANDMINE; - mineObj->projectileLogic = (Logic*)mineLogic; - - landmine_setup(mineObj, setupFunc); - return (Logic*)mineLogic; - } break; - case KW_KELL: - { - return kellDragon_setup(obj, setupFunc); - } break; - case KW_SEWER1: - { - return sewerCreature_setup(obj, setupFunc); - } break; - case KW_REMOTE: - { - return remote_setup(obj, setupFunc); - } break; - case KW_TURRET: - { - return turret_setup(obj, setupFunc); - } break; - case KW_MOUSEBOT: - { - return mousebot_setup(obj, setupFunc); - } break; - case KW_WELDER: - { - return welder_setup(obj, setupFunc); - } break; - case KW_SCENERY: - { - obj->flags &= ~OBJ_FLAG_AIM; - obj->entityFlags = ETFLAG_SCENERY; - return scenery_setup(obj, setupFunc); - } break; - } - - TFE_System::logWrite(LOG_ERROR, "Logic", "Unknown logic type - %d.", logicId); - return nullptr; - } - - SecObject* logic_spawnEnemy(const char* waxName, const char* typeName) - { - Wax* wax = TFE_Sprite_Jedi::getWax(waxName); - if (!wax) - { - return nullptr; - } - KEYWORD type = getKeywordIndex(typeName); - if (type == KW_UNKNOWN || type < KW_TROOP || type > KW_SCENERY) - { - return nullptr; - } - - vec3_fixed pos = s_playerObject->posWS; - fixed16_16 sinYaw, cosYaw; - sinCosFixed(s_playerObject->yaw, &sinYaw, &cosYaw); - - vec3_fixed spawnPos; - fixed16_16 dist = FIXED(8); - spawnPos.x = pos.x + mul16(sinYaw, dist); - spawnPos.y = pos.y; - spawnPos.z = pos.z + mul16(cosYaw, dist); - - RSector* sector = s_playerObject->sector; - RWall* wall = collision_wallCollisionFromPath(sector, pos.x, pos.z, spawnPos.x, spawnPos.z); - fixed16_16 floorHeight = sector->floorHeight; - fixed16_16 ceilingHeight = sector->ceilingHeight; - while (wall) - { - if (wall->nextSector) - { - RSector* next = wall->nextSector; - floorHeight = min(floorHeight, next->floorHeight); - ceilingHeight = max(ceilingHeight, next->ceilingHeight); - fixed16_16 opening = floorHeight - ceilingHeight; - if (opening < FIXED(5) || TFE_Jedi::abs(sector->floorHeight - next->floorHeight) > FIXED(2)) - { - break; - } - - sector = next; - wall = collision_wallCollisionFromPath(sector, pos.x, pos.z, spawnPos.x, spawnPos.z); - } - else - { - break; - } - } - - if (wall) - { - return nullptr; - } - - SecObject* spawn = allocateObject(); - spawn->posWS = spawnPos; - spawn->yaw = random_next() & ANGLE_MASK; - sector_addObject(sector, spawn); - - sprite_setData(spawn, wax); - obj_setEnemyLogic(spawn, type, nullptr); - - return spawn; - } - - /////////////////////////////////////////////////// - // Logic Serialization - // TODO: It probably makes sense to move this to - // its own file at some point. - /////////////////////////////////////////////////// - // Type -> Serialization function tables. - typedef void(*LogicSerializationFunc)(Logic*&, SecObject* obj, Stream*); - LogicSerializationFunc c_serializeFn[] = - { - actorDispatch_serialize, // LOGIC_DISPATCH - bobaFett_serialize, // LOGIC_BOBA_FETT - kellDragon_serialize, // LOGIC_DRAGON - mousebot_serialize, // LOGIC_MOUSEBOT - phaseOne_serialize, // LOGIC_PHASE_ONE - phaseTwo_serialize, // LOGIC_PHASE_TWO - phaseThree_serialize, // LOGIC_PHASE_THREE - turret_serialize, // LOGIC_TURRET - welder_serialize, // LOGIC_WELDER - animLogic_serialize, // LOGIC_ANIM - updateLogic_serialize, // LOGIC_UPDATE - generatorLogic_serialize, // LOGIC_GENERATOR - pickupLogic_serialize, // LOGIC_PICKUP - playerLogic_serialize, // LOGIC_PLAYER - projLogic_serialize, // LOGIC_PROJECTILE - vueLogic_serialize, // LOGIC_VUE - nullptr, // LOGIC_UNKNOWN - }; - - // Root serialization functions for Logics. - void logic_serialize(Logic*& logic, SecObject* obj, Stream* stream) - { - LogicType type; - if (serialization_getMode() == SMODE_WRITE) - { - type = logic->type; - } - - SERIALIZE(ObjState_InitVersion, type, LOGIC_UNKNOWN); - const u32 index = type < LOGIC_UNKNOWN ? type : LOGIC_UNKNOWN; - - if (c_serializeFn[index]) - { - c_serializeFn[index](logic, obj, stream); - if (logic) { logic->type = type; } - } - else - { - TFE_System::logWrite(LOG_ERROR, "Logic", "Serialize - invalid logic type: %d.", type); - if (logic) { logic->type = LOGIC_UNKNOWN; } - assert(0); - } - } -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/logic.h b/components/darkforces/tfe/TFE_DarkForces/logic.h deleted file mode 100644 index bba88e9e..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/logic.h +++ /dev/null @@ -1,70 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces Logic - -// The base Logic structure and functionality. -////////////////////////////////////////////////////////////////////// - -#include -#include -#include -#include -#include -#include - -struct Logic; -typedef void(*LogicCleanupFunc)(Logic*); -typedef JBool(*LogicSetupFunc)(Logic*, KEYWORD); - -// Added for TFE to help with serialization. -enum LogicType : u32 -{ - // AI - LOGIC_DISPATCH = 0, - LOGIC_BOBA_FETT, - LOGIC_DRAGON, - LOGIC_MOUSEBOT, - LOGIC_PHASE_ONE, - LOGIC_PHASE_TWO, - LOGIC_PHASE_THREE, - LOGIC_TURRET, - LOGIC_WELDER, - // General - LOGIC_ANIM, - LOGIC_UPDATE, - LOGIC_GENERATOR, - LOGIC_PICKUP, - LOGIC_PLAYER, - LOGIC_PROJECTILE, - LOGIC_VUE, - - LOGIC_UNKNOWN, -}; - -struct Logic -{ - LogicType type = LOGIC_UNKNOWN; // changed this slot for TFE, for serialization. - SecObject* obj = nullptr; - Logic** parent = nullptr; - Task* task = nullptr; - LogicCleanupFunc cleanupFunc = nullptr; -}; - -namespace TFE_DarkForces -{ - void obj_addLogic(SecObject* obj, Logic* logic, LogicType type, Task* task, LogicCleanupFunc cleanupFunc); - void deleteLogicAndObject(Logic* logic); - JBool object_parseSeq(SecObject* obj, TFE_Parser* parser, size_t* bufferPos); - Logic* obj_setEnemyLogic(SecObject* obj, KEYWORD logicId, LogicSetupFunc* setupFunc); - SecObject* logic_spawnEnemy(const char* waxName, const char* typeName); - - void logic_serialize(Logic*& logic, SecObject* obj, Stream* stream); - - // Shared variables used for loading. - extern char s_objSeqArg0[]; - extern char s_objSeqArg1[]; - extern char s_objSeqArg2[]; - extern char s_objSeqArg3[]; - extern char s_objSeqArg4[]; - extern char s_objSeqArg5[]; - extern s32 s_objSeqArgCount; -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/mission.cpp b/components/darkforces/tfe/TFE_DarkForces/mission.cpp deleted file mode 100644 index e7802a75..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/mission.cpp +++ /dev/null @@ -1,1508 +0,0 @@ -#include "mission.h" -#include -#include "agent.h" -#include "animLogic.h" -#include "automap.h" -#include "cheats.h" -#include "config.h" -#include "gameMusic.h" -#include "hud.h" -#include "updateLogic.h" -#include "pickup.h" -#include "player.h" -#include "projectile.h" -#include "weapon.h" -#include "darkForcesMain.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; -using namespace TFE_Input; - -namespace TFE_DarkForces -{ - // Show the loading screen for at least 1 second. - #define MIN_LOAD_TIME 145 - - ///////////////////////////////////////////// - // Shared State - ///////////////////////////////////////////// - JBool s_gamePaused = JTRUE; - JBool s_canTeleport = JTRUE; - GameMissionMode s_missionMode = MISSION_MODE_MAIN; - - TextureData* s_loadScreen = nullptr; - u8 s_loadingScreenPal[768]; - u8 s_levelPalette[768]; - u8 s_basePalette[768]; - u8 s_escMenuPalette[768]; - u8 s_framePalette[768]; - - // Move these to color? - JBool s_palModified = JTRUE; - JBool s_canChangePal = JTRUE; - JBool s_screenFxEnabled = JTRUE; - JBool s_screenBrightnessEnabled = JTRUE; - JBool s_luminanceMask[3] = { JFALSE, JFALSE, JFALSE }; - JBool s_updateHudColors = JFALSE; - - JBool s_screenBrightnessChanged = JFALSE; - JBool s_screenFxChanged = JFALSE; - JBool s_lumMaskChanged = JFALSE; - - JBool s_loadingFromSave = JFALSE; - - s32 s_flashFxLevel = 0; - s32 s_healthFxLevel = 0; - s32 s_shieldFxLevel = 0; - s32 s_screenBrightness = ONE_16; - - u8* s_colormap; - u8* s_lightSourceRamp; - - // Loading - u8* s_levelColorMap = nullptr; - u8* s_levelColorMapBasePtr = nullptr; - u8 s_levelLightRamp[LIGHT_SOURCE_LEVELS]; - - ///////////////////////////////////////////// - // Internal State - ///////////////////////////////////////////// - static u8* s_framebuffer = nullptr; - static JBool s_exitLevel = JFALSE; - static Task* s_levelEndTask = nullptr; - static Task* s_mainTask = nullptr; - static Task* s_missionLoadTask = nullptr; - - static s32 s_visionFxCountdown = 0; - static s32 s_visionFxEndCountdown = 0; - - ///////////////////////////////////////////// - // Forward Declarations - ///////////////////////////////////////////// - void mission_mainTaskFunc(MessageType msg); - void setPalette(u8* pal); - void blitLoadingScreen(); - void displayLoadingScreen(); - u8* color_loadMap(FilePath* path, u8* lightRamp, u8** basePtr); - - void setScreenBrightness(fixed16_16 brightness); - void setScreenFxLevels(s32 healthFx, s32 shieldFx, s32 flashFx); - void setLuminanceMask(JBool r, JBool g, JBool b); - void setCurrentColorMap(u8* colorMap, u8* lightRamp); - void mainTask_handleCall(MessageType msg); - void handleGeneralInput(); - - void updateScreensize(); - - // Palette Filters and Effects - void handlePaletteFx(); - void applyLuminanceFilter(u8* pal, JBool lumRedMask, JBool lumGreenMask, JBool lumBlueMask); - void applyScreenFxToPalette(u8* pal, s32 healthFxLevel, s32 shieldFxLevel, s32 flashFxLevel); - void applyScreenBrightness(u8* pal, s32 brightness); - void blankScreen(); - - void executeCheat(CheatID cheatID); - extern void resumeLevelSound(); - extern void skipToLevelNextScene(s32 index); - - ///////////////////////////////////////////// - // API Implementation - ///////////////////////////////////////////// - static Tick s_loadingScreenStart; - static Tick s_loadingScreenDelta; - static CheatID s_queuedCheatID = CHEAT_NONE; - - void console_cheat(const ConsoleArgList& args) - { - if (args.size() < 2) { return; } - - const char* cheatStr = args[1].c_str(); - s_queuedCheatID = cheat_getIDFromString(cheatStr); - - // Close the console so the cheat can be executed. - TFE_FrontEndUI::toggleConsole(); - mission_pause(JFALSE); - TFE_Input::enableRelativeMode(true); - } - -#define CHEAT_CMD(c) \ - void console_##c (const ConsoleArgList& args)\ - { \ - if (s_playerDying) \ - { \ - return; \ - } \ - s_queuedCheatID = CHEAT_##c ; \ - TFE_FrontEndUI::toggleConsole(); \ - mission_pause(JFALSE); \ - TFE_Input::enableRelativeMode(true); \ - } - CHEAT_CMD(LACDS); - CHEAT_CMD(LANTFH); - CHEAT_CMD(LAPOGO); - CHEAT_CMD(LARANDY); - CHEAT_CMD(LAIMLAME); - CHEAT_CMD(LAPOSTAL); - CHEAT_CMD(LADATA); - CHEAT_CMD(LABUG); - CHEAT_CMD(LAREDLITE); - CHEAT_CMD(LASECBASE); - CHEAT_CMD(LATALAY); - CHEAT_CMD(LASEWERS); - CHEAT_CMD(LATESTBASE); - CHEAT_CMD(LAGROMAS); - CHEAT_CMD(LADTENTION); - CHEAT_CMD(LARAMSHED); - CHEAT_CMD(LAROBOTICS); - CHEAT_CMD(LANARSHADA); - CHEAT_CMD(LAJABSHIP); - CHEAT_CMD(LAIMPCITY); - CHEAT_CMD(LAFUELSTAT); - CHEAT_CMD(LAEXECUTOR); - CHEAT_CMD(LAARC); - CHEAT_CMD(LASKIP); - CHEAT_CMD(LABRADY); - CHEAT_CMD(LAUNLOCK); - CHEAT_CMD(LAMAXOUT); - CHEAT_CMD(LAFLY); - CHEAT_CMD(LANOCLIP); - CHEAT_CMD(LATESTER); - - void console_spawnEnemy(const ConsoleArgList& args) - { - if (args.size() < 3) { return; } - logic_spawnEnemy(args[1].c_str(), args[2].c_str()); - } - - void mission_createDisplay() - { - vfb_setResolution(320, 200); - s_framebuffer = vfb_getCpuBuffer(); - } - - void mission_createRenderDisplay() - { - TFE_Settings_Graphics* graphics = TFE_Settings::getGraphicsSettings(); - DisplayInfo info; - TFE_RenderBackend::getDisplayInfo(&info); - - s32 adjustedWidth = graphics->gameResolution.x; - if (graphics->widescreen && (graphics->gameResolution.z == 200 || graphics->gameResolution.z == 400)) - { - adjustedWidth = (graphics->gameResolution.z * info.width / info.height) * 12 / 10; - } - else if (graphics->widescreen) - { - adjustedWidth = graphics->gameResolution.z * info.width / info.height; - } - // Make sure the adjustedWidth is divisible by 4. - adjustedWidth = 4*((adjustedWidth + 3) >> 2); - - vfb_setResolution(adjustedWidth, graphics->gameResolution.z); - s_framebuffer = vfb_getCpuBuffer(); - - if (graphics->gameResolution.x != 320 || graphics->gameResolution.z != 200 || graphics->widescreen) - { - TFE_Jedi::setSubRenderer(TSR_HIGH_RESOLUTION); - } - else - { - TFE_Jedi::setSubRenderer(TSR_CLASSIC_FIXED); - } - automap_resetScale(); - - TFE_Jedi::renderer_setType(RendererType(graphics->rendererIndex)); - TFE_Jedi::render_setResolution(); - TFE_Jedi::renderer_setLimits(); - - // Clear the palette for now. - blankScreen(); - } - - void mission_setLoadingFromSave() - { - s_loadingFromSave = JTRUE; - } - -#ifdef TFE_ESPBOX - char* s_colormapName = nullptr; // TFE_MAX_PATH (shared memory) -#else - char s_colormapName[TFE_MAX_PATH] = { 0 }; -#endif - - void mission_loadColormap() - { - FilePath filePath; - if (TFE_Paths::getFilePath(s_colormapName, &filePath)) - { - s_levelColorMap = color_loadMap(&filePath, s_levelLightRamp, &s_levelColorMapBasePtr); - } - else if (TFE_Paths::getFilePath("DEFAULT.CMP", &filePath)) - { - TFE_System::logWrite(LOG_WARNING, "mission_startTaskFunc", "USING DEFAULT.CMP"); - s_levelColorMap = color_loadMap(&filePath, s_levelLightRamp, &s_levelColorMapBasePtr); - } - setCurrentColorMap(s_levelColorMap, s_levelLightRamp); - } - - void mission_serialize(Stream* stream) - { - SERIALIZE(SaveVersionInit, s_palModified, JTRUE); - SERIALIZE(SaveVersionInit, s_canChangePal, JTRUE); - SERIALIZE(SaveVersionInit, s_screenFxEnabled, JTRUE); - SERIALIZE(SaveVersionInit, s_screenBrightnessEnabled, JTRUE); - SERIALIZE_BUF(SaveVersionInit, s_luminanceMask, 3 * sizeof(JBool)); - SERIALIZE(SaveVersionInit, s_updateHudColors, JFALSE); - SERIALIZE(SaveVersionInit, s_screenBrightnessChanged, JFALSE); - SERIALIZE(SaveVersionInit, s_screenFxChanged, JFALSE); - SERIALIZE(SaveVersionInit, s_lumMaskChanged, JFALSE); - - SERIALIZE(SaveVersionInit, s_flashFxLevel, 0); - SERIALIZE(SaveVersionInit, s_healthFxLevel, 0); - SERIALIZE(SaveVersionInit, s_shieldFxLevel, 0); - SERIALIZE(SaveVersionInit, s_screenBrightness, ONE_16); - - SERIALIZE(SaveVersionInit, s_visionFxCountdown, 0); - SERIALIZE(SaveVersionInit, s_visionFxEndCountdown, 0); - } - - void mission_serializeColorMap(Stream* stream) - { - u8 length = 0; - if (serialization_getMode() == SMODE_WRITE) - { - length = (u8)strlen(s_colormapName); - } - SERIALIZE(SaveVersionInit, length, 0); - SERIALIZE_BUF(SaveVersionInit, s_colormapName, length); - s_colormapName[length] = 0; - - if (serialization_getMode() == SMODE_READ) - { - mission_loadColormap(); - } - } - - void mission_addCheatCommands() - { - TFE_Console::ConsoleFunc cheatFunc[] = - { - nullptr, // CHEAT_NONE = 0, - console_LACDS, // CHEAT_LACDS, - console_LANTFH, // CHEAT_LANTFH, - console_LAPOGO, // CHEAT_LAPOGO, - console_LARANDY, // CHEAT_LARANDY, - console_LAIMLAME, // CHEAT_LAIMLAME, - console_LAPOSTAL, // CHEAT_LAPOSTAL, - console_LADATA, // CHEAT_LADATA, - console_LABUG, // CHEAT_LABUG, - console_LAREDLITE, // CHEAT_LAREDLITE, - console_LASECBASE, // CHEAT_LASECBASE, - console_LATALAY, // CHEAT_LATALAY, - console_LASEWERS, // CHEAT_LASEWERS, - console_LATESTBASE, // CHEAT_LATESTBASE, - console_LAGROMAS, // CHEAT_LAGROMAS, - console_LADTENTION, // CHEAT_LADTENTION, - console_LARAMSHED, // CHEAT_LARAMSHED, - console_LAROBOTICS, // CHEAT_LAROBOTICS, - console_LANARSHADA, // CHEAT_LANARSHADA, - console_LAJABSHIP, // CHEAT_LAJABSHIP, - console_LAIMPCITY, // CHEAT_LAIMPCITY, - console_LAFUELSTAT, // CHEAT_LAFUELSTAT, - console_LAEXECUTOR, // CHEAT_LAEXECUTOR, - console_LAARC, // CHEAT_LAARC, - console_LASKIP, // CHEAT_LASKIP, - console_LABRADY, // CHEAT_LABRADY, - console_LAUNLOCK, // CHEAT_LAUNLOCK, - console_LAMAXOUT, // CHEAT_LAMAXOUT, - console_LAFLY, // CHEAT_LAFLY, - console_LANOCLIP, // CHEAT_LANOCLIP, - console_LATESTER, // CHEAT_LATESTER, - }; - - CCMD("cheat", console_cheat, 1, "Enter a Dark Forces cheat code as a string, example: cheat lacds"); - for (u32 i = CHEAT_NONE + 1; i < CHEAT_COUNT; i++) - { - const char* str = cheat_getStringFromID(CheatID(i)); - // Add "LA" to the beginning. - char finalStr[256]; - sprintf(finalStr, "LA%s", str); - char helpMsg[256]; - sprintf(helpMsg, "Activate the %s cheat.", finalStr); - CCMD(finalStr, cheatFunc[i], 0, helpMsg); - } - } - - void mission_startTaskFunc(MessageType msg) - { - task_begin; - { - // TFE-specific - mission_addCheatCommands(); - CCMD("spawnEnemy", console_spawnEnemy, 2, "spawnEnemy(waxName, enemyTypeName) - spawns an enemy 8 units away in the player direction. Example: spawnEnemy offcfin.wax i_officer"); - - // Make sure the loading screen is displayed for at least 1 second. - if (!s_loadingFromSave) - { - time_pause(JFALSE); - mission_createDisplay(); - displayLoadingScreen(); - task_yield(MIN_LOAD_TIME); - - s_prevTick = s_curTick; - s_playerTick = s_curTick; - s_levelComplete = JFALSE; - } - s_mainTask = createTask("main task", mission_mainTaskFunc); - - s_invalidLevelIndex = JFALSE; - s_exitLevel = JFALSE; - - if (!s_loadingFromSave) - { - s_missionMode = MISSION_MODE_LOAD_START; - mission_setupTasks(); - - displayLoadingScreen(); - - // Add a yield here, so the loading screen is shown immediately. - task_yield(TASK_NO_DELAY); - s_loadingScreenStart = s_curTick; - { - const char* levelName = agent_getLevelName(); - // For now always load medium difficulty since it cannot be selected. - if (level_load(levelName, s_agentData[s_agentId].difficulty)) - { - setScreenBrightness(ONE_16); - setScreenFxLevels(0, 0, 0); - setLuminanceMask(0, 0, 0); - - strcpy(s_colormapName, levelName); - strcat(s_colormapName, ".CMP"); - s_levelColorMap = nullptr; - - mission_loadColormap(); - automap_updateMapData(MAP_CENTER_PLAYER); - setSkyParallax(s_levelState.parallax0, s_levelState.parallax1); - s_missionMode = MISSION_MODE_MAIN; - s_gamePaused = JFALSE; - mission_createRenderDisplay(); - hud_startup(JFALSE); - - reticle_enable(true); - } - s_flatLighting = JFALSE; - s_nightvisionActive = JFALSE; - } - } - else // Loading from save. - { - s_missionMode = MISSION_MODE_MAIN; - mission_createRenderDisplay(); - hud_startup(JTRUE); - reticle_enable(true); - } - s_loadingFromSave = JFALSE; - TFE_Input::clearAccumulatedMouseMove(); - - s_gamePaused = JFALSE; - escapeMenu_resetLevel(); - } - // Sleep until we are done with the main task. - task_yield(TASK_SLEEP); - - // Cleanup - shut down all tasks. - task_freeAll(); - - // End the task. - task_end; - } - - void mission_setLoadMissionTask(Task* task) - { - s_missionLoadTask = task; - } - - // In DOS, this was part of drawWorld() - - // for TFE I split it out to limit the amount of game code in the renderer. - void handleVisionFx() - { - // Countdown to enable the night vision effect. - if (s_visionFxCountdown != 0) - { - s_visionFxCountdown--; - if (s_visionFxCountdown == 0) - { - setLuminanceMask(JFALSE, JTRUE, JFALSE); - } - } - - // Countdown to disable the night vision effect. - if (s_visionFxEndCountdown != 0) - { - s_visionFxEndCountdown--; - if (s_visionFxEndCountdown == 0) - { - setLuminanceMask(JFALSE, JFALSE, JFALSE); - } - } - } - - void mission_exitLevel() - { - s_exitLevel = JTRUE; - } - - void mission_render(s32 rendererIndex) - { - if (task_getCount() > 1 && s_missionMode == MISSION_MODE_MAIN) - { - TFE_Jedi::renderer_setType(rendererIndex == 0 ? RENDERER_SOFTWARE : RENDERER_HARDWARE); - TFE_Jedi::render_setResolution(); - TFE_Jedi::renderer_setLimits(); - - s_framebuffer = vfb_getCpuBuffer(); - TFE_Jedi::beginRender(); - - updateScreensize(); - drawWorld(s_framebuffer, s_playerEye->sector, s_levelColorMap, s_lightSourceRamp); - weapon_draw(s_framebuffer, (DrawRect*)vfb_getScreenRect(VFB_RECT_UI)); - handleVisionFx(); - handlePaletteFx(); - hud_drawAndUpdate(s_framebuffer); - hud_drawMessage(s_framebuffer); - automap_resetScale(); - - TFE_Jedi::endRender(); - vfb_swap(); - } - } - - void mission_mainTaskFunc(MessageType msg) - { - task_begin; - blankScreen(); - - while (msg != MSG_FREE_TASK) - { - // This means it is time to abort, we are done with this level. - if (s_curTick >= 0 && (s_exitLevel || msg < MSG_RUN_TASK)) - { - break; - } - - // Grab the current framebuffer in case in changed. - s_framebuffer = vfb_getCpuBuffer(); - TFE_Jedi::beginRender(); - - // Handle delta time. -#ifdef TFE_ESPBOX - s_deltaTime = intToFixed16(s_curTick - s_prevTick) / TICKS_PER_SECOND; -#else - s_deltaTime = div16(intToFixed16(s_curTick - s_prevTick), FIXED(TICKS_PER_SECOND)); -#endif - s_deltaTime = min(s_deltaTime, MAX_DELTA_TIME); - s_prevTick = s_curTick; - s_playerTick = s_curTick; - - if (!escapeMenu_isOpen() && !pda_isOpen()) - { - player_setupCamera(); - - if (s_missionMode == MISSION_MODE_LOADING) - { - blitLoadingScreen(); - } - else if (s_missionMode == MISSION_MODE_MAIN) - { - updateScreensize(); - drawWorld(s_framebuffer, s_playerEye->sector, s_levelColorMap, s_lightSourceRamp); - weapon_draw(s_framebuffer, (DrawRect*)vfb_getScreenRect(VFB_RECT_UI)); - handleVisionFx(); - } - } - - if (!escapeMenu_isOpen() && !pda_isOpen()) - { - handleGeneralInput(); - if (s_drawAutomap) - { - automap_draw(s_framebuffer); - } - hud_drawAndUpdate(s_framebuffer); - hud_drawMessage(s_framebuffer); - handlePaletteFx(); - } - - // Move this out of handleGeneralInput so that the HUD is properly copied. - if (escapeMenu_isOpen()) - { - EscapeMenuAction action = escapeMenu_update(); - if (action == ESC_RETURN || action == ESC_CONFIG) - { - s_gamePaused = JFALSE; - TFE_Input::clearAccumulatedMouseMove(); - task_pause(s_gamePaused); - time_pause(s_gamePaused); - - if (action == ESC_CONFIG) - { - TFE_System::postSystemUiRequest(); - } -#ifdef TFE_ESPBOX - s_palModified = JTRUE; -#else - blankScreen(); -#endif - } - else if (action == ESC_ABORT_OR_NEXT) - { - s_exitLevel = JTRUE; - TFE_Input::clearAccumulatedMouseMove(); - task_pause(JFALSE); - time_pause(JFALSE); - } - else if (action == ESC_QUIT) - { - saveLevelStatus(); - if (TFE_Settings::getSystemSettings()->gameQuitExitsToMenu) - { - TFE_FrontEndUI::exitToMenu(); - } - else - { - TFE_System::postQuitMessage(); - } - } - } - else if (pda_isOpen()) - { - pda_update(); - - // If the PDA was closed, then unpause the game. - if (!pda_isOpen()) - { - mission_pause(JFALSE); - resumeLevelSound(); -#ifdef TFE_ESPBOX - s_palModified = JTRUE; -#endif - } - } - else if (inputMapping_getActionState(IADF_MENU_TOGGLE) == STATE_PRESSED && !s_playerDying && !TFE_FrontEndUI::isConsoleOpen()) - { - escapeMenu_open(s_framebuffer, s_basePalette); - s_gamePaused = JTRUE; - task_pause(s_gamePaused, s_mainTask); - time_pause(s_gamePaused); - } - - // vgaSwapBuffers() in the DOS code. - TFE_Jedi::endRender(); - vfb_swap(); - - // Pump tasks and look for any with a different ID. - do - { - task_yield(TASK_NO_DELAY); - if (msg != MSG_FREE_TASK && msg != MSG_RUN_TASK) - { - mainTask_handleCall(msg); - } - } while (msg != MSG_FREE_TASK && msg != MSG_RUN_TASK); - } - - s_mainTask = nullptr; - task_makeActive(s_missionLoadTask); - task_end; - } - - ///////////////////////////////////////////// - // Internal Implementation - ///////////////////////////////////////////// - void mainTask_handleCall(MessageType msg) - { - if (msg == MSG_LIGHTS) - { - sector_changeGlobalLightLevel(); - } - } - - // Convert the palette to 32 bit color and then send to the render backend. - // This is functionally similar to loading the palette into VGA registers. - void setPalette(u8* pal) - { - // Update the palette. - u32 palette[256]; - u32* outColor = palette; - u8* srcColor = pal; - for (s32 i = 0; i < 256; i++, outColor++, srcColor += 3) - { - *outColor = CONV_6bitTo8bit(srcColor[0]) | (CONV_6bitTo8bit(srcColor[1]) << 8u) | (CONV_6bitTo8bit(srcColor[2]) << 16u) | (0xffu << 24u); - } - vfb_setPalette(palette); - } - - void blitLoadingScreen() - { - if (!s_loadScreen) { return; } - blitTextureToScreen(s_loadScreen, (DrawRect*)vfb_getScreenRect(VFB_RECT_UI), 0/*x0*/, 0/*y0*/, s_framebuffer, JFALSE, JTRUE); - } - - void displayLoadingScreen() - { - blitLoadingScreen(); - - // Update twice to make sure the loading screen is visible. - // The virtual display is buffered, meaning there is a frame of latency. - // This hackery basically removes that latency so the image is properly displayed immediately. - setPalette(s_loadingScreenPal); - setPalette(s_loadingScreenPal); - vfb_swap(); - vfb_swap(); - } - - void mission_setupTasks() - { - setSpriteAnimation(nullptr, nullptr); - bitmap_setupAnimationTask(); - hud_startup(JFALSE); - hud_clearMessage(); - automap_computeScreenBounds(); - weapon_clearFireRate(); - weapon_createPlayerWeaponTask(); - projectile_createTask(); - player_createController(s_loadingFromSave ? JFALSE : JTRUE); - inf_createElevatorTask(); - player_clearEyeObject(); - pickup_createTask(); - inf_createTeleportTask(); - inf_createTriggerTask(); - actor_createTask(); - hitEffect_createTask(); - level_clearData(); - updateLogic_clearTask(); - s_drawAutomap = JFALSE; - s_levelEndTask = nullptr; - s_cheatString[0] = 0; - s_cheatCharIndex = 0; - s_cheatInputCount = 0; - s_queuedCheatID = CHEAT_NONE; - } - - void setScreenBrightness(fixed16_16 brightness) - { - if (brightness != s_screenBrightness) - { - s_screenBrightness = brightness; - s_screenBrightnessChanged = JTRUE; - } - } - - void setScreenFxLevels(s32 healthFx, s32 shieldFx, s32 flashFx) - { - if (healthFx != s_healthFxLevel || shieldFx != s_shieldFxLevel || flashFx != s_flashFxLevel) - { - s_healthFxLevel = healthFx; - s_shieldFxLevel = shieldFx; - s_flashFxLevel = flashFx; - s_screenFxChanged = JTRUE; - } - } - - void setLuminanceMask(JBool r, JBool g, JBool b) - { - if (r != s_luminanceMask[0] || g != s_luminanceMask[1] || b != s_luminanceMask[2]) - { - s_luminanceMask[0] = r; - s_luminanceMask[1] = g; - s_luminanceMask[2] = b; - s_lumMaskChanged = JTRUE; - } - } - - void handlePaletteFx() - { - JBool useFramePal = JFALSE; - JBool updateBasePal = JFALSE; - JBool copiedPalette = JFALSE; - if (!s_canChangePal) { return; } - - if (s_luminanceMask[0] || s_luminanceMask[1] || s_luminanceMask[2]) - { - if (!copiedPalette) - { - memcpy(s_framePalette, s_basePalette, 768); - copiedPalette = JTRUE; - } - applyLuminanceFilter(s_framePalette, s_luminanceMask[0], s_luminanceMask[1], s_luminanceMask[2]); - s_palModified = JTRUE; - useFramePal = JTRUE; - } - else if (s_palModified) - { - updateBasePal = JTRUE; - } - - s_lumMaskChanged = JFALSE; - if (s_screenFxEnabled) - { - if (s_healthFxLevel || s_shieldFxLevel || s_flashFxLevel) - { - if (!copiedPalette) - { - memcpy(s_framePalette, s_basePalette, 768); - copiedPalette = JTRUE; - } - applyScreenFxToPalette(s_framePalette, s_healthFxLevel, s_shieldFxLevel, s_flashFxLevel); - useFramePal = JTRUE; - s_palModified = JTRUE; - } - else if (s_palModified) - { - updateBasePal = JTRUE; - } - s_screenFxChanged = JFALSE; - } - - if (s_screenBrightnessEnabled) - { - if (s_screenBrightness < ONE_16) - { - if (!copiedPalette) - { - memcpy(s_framePalette, s_basePalette, 768); - copiedPalette = JTRUE; - } - applyScreenBrightness(s_framePalette, s_screenBrightness); - s_palModified = JTRUE; - useFramePal = JTRUE; - } - else if (s_palModified) - { - updateBasePal = JTRUE; - } - s_screenBrightnessChanged = JFALSE; - } - - if (useFramePal) - { - // Convert the palette to true color and send to the render backend. - setPalette(s_framePalette); - s_updateHudColors = JFALSE; - } - else - { - if (updateBasePal) - { - copiedPalette = JFALSE; - setPalette(s_basePalette); - s_updateHudColors = JFALSE; - } - else if (s_updateHudColors) - { - // Update the HUD shield color indices. - // For TFE, just upload the full palette, the original DOS code - // only updated the VGA registers for the changed HUD colors. - setPalette(s_basePalette); - s_updateHudColors = JFALSE; - } - } - - // TFE uses a dynamic multi-buffered texture for the palette. This doesn't work well when trying to set it only once. - // For this reason, it is easier to just set the palette every frame regardless of change. - #if 0 - if (!s_luminanceMask[0] && !s_luminanceMask[1] && !s_luminanceMask[2] && !s_healthFxLevel && !s_shieldFxLevel && !s_flashFxLevel && s_screenBrightness == ONE_16) - { - s_palModified = JFALSE; - } - #endif -#ifdef TFE_ESPBOX - if (!s_luminanceMask[0] && !s_luminanceMask[1] && !s_luminanceMask[2] && !s_healthFxLevel && !s_shieldFxLevel && !s_flashFxLevel && s_screenBrightness == ONE_16) - { - s_palModified = JFALSE; - } -#endif - } - - void setCurrentColorMap(u8* colorMap, u8* lightRamp) - { - s_colormap = colorMap; - s_lightSourceRamp = lightRamp; - } - - // Move to the appropriate place. - u8* color_loadMap(FilePath* path, u8* lightRamp, u8** basePtr) - { - FileStream file; - if (!file.open(path, Stream::MODE_READ)) - { - TFE_System::logWrite(LOG_ERROR, "color_loadMap", "Error loading color map."); - return nullptr; - } - - // Allocate 256 colors * 32 light levels + 256, where the last 256 is so that the address can be rounded to the next 256 byte boundary. - u8* colorMapBase = (u8*)level_alloc(8576); - u8* colorMap = colorMapBase; - *basePtr = colorMapBase; - if (size_t(colorMap) & 0xffu) - { - // colorMap2 is rounded to the next 256 bytes. - colorMap = colorMapBase + 256 - (size_t(colorMap) & 0xff); - } - // 256 colors * 32 light levels = 8192 - file.readBuffer(colorMap, 8192); - file.readBuffer(lightRamp, LIGHT_SOURCE_LEVELS); - file.close(); - - return colorMap; - } - - void disableHeadlamp() - { - hud_sendTextMessage(12); - s_headlampActive = JFALSE; - } - - void enableHeadlamp() - { - if (s_batteryPower) - { - s_headlampActive = JTRUE; - hud_sendTextMessage(13); - } - } - - void beginNightVision(s32 ambient) - { - s_flatAmbient = ambient; - s_flatLighting = JTRUE; - s_visionFxCountdown = 2; - } - - void disableNightvisionInternal() - { - s_flatLighting = JFALSE; - s_visionFxEndCountdown = 3; - } - - void disableNightvision() - { - disableNightvisionInternal(); - s_nightvisionActive = JFALSE; - hud_sendTextMessage(9); - } - - void enableNightVision() - { - if (!s_playerInfo.itemGoggles) { return; } - - if (!s_batteryPower) - { - hud_sendTextMessage(11); - sound_play(s_nightVisionDeactiveSoundSource); - s_nightvisionActive = JFALSE; - return; - } - - s_nightvisionActive = JTRUE; - beginNightVision(16); - hud_sendTextMessage(10); - sound_play(s_nightVisionActiveSoundSource); - } - - void disableCleats() - { - if (s_wearingCleats) - { - s_wearingCleats = JFALSE; - hud_sendTextMessage(21); - } - } - - void enableCleats() - { - s_wearingCleats = JTRUE; - hud_sendTextMessage(22); - } - - void disableMask() - { - if (!s_wearingGasmask) - { - return; - } - - hud_sendTextMessage(19); - s_wearingGasmask = JFALSE; - if (s_gasmaskTask) - { - task_free(s_gasmaskTask); - s_gasmaskTask = nullptr; - } - } - - void enableMask() - { - if (!s_playerInfo.itemMask) { return; } - - if (!s_batteryPower) - { - hud_sendTextMessage(11); - s_wearingGasmask = JFALSE; - if (s_gasmaskTask) - { - task_free(s_gasmaskTask); - s_gasmaskTask = nullptr; - } - return; - } - - s_wearingGasmask = JTRUE; - hud_sendTextMessage(20); - if (!s_gasmaskTask) - { - s_gasmaskTask = createSubTask("gasmask", gasmaskTaskFunc); - } - } - - void cheat_gotoLevel(s32 index) - { - agent_setNextLevelByIndex(index); - s_levelComplete = JTRUE; - s_exitLevel = JTRUE; - - skipToLevelNextScene(index + 1); - } - - void cheat_levelSkip() - { - agent_levelComplete(); - s_exitLevel = JTRUE; - } - - void executeCheat(CheatID cheatID) - { - if (cheatID == CHEAT_NONE) - { - return; - } - - switch (cheatID) - { - case CHEAT_LACDS: - { - automap_updateMapData(MAP_INCR_SECTOR_MODE); - } break; - case CHEAT_LANTFH: - { - automap_updateMapData(MAP_TELEPORT); - cheat_teleport(); - } break; - case CHEAT_LAPOGO: - { - cheat_enableNoheightCheck(); - } break; - case CHEAT_LARANDY: - { - pickupSupercharge(); - hud_sendTextMessage(701); - } break; - case CHEAT_LAIMLAME: - { - cheat_godMode(); - } break; - case CHEAT_LAPOSTAL: - { - cheat_postal(); - } break; - case CHEAT_LADATA: - { - hud_toggleDataDisplay(); - } break; - case CHEAT_LABUG: - { - cheat_bugMode(); - } break; - case CHEAT_LAREDLITE: - { - cheat_pauseAI(); - } break; - case CHEAT_LASECBASE: - { - cheat_gotoLevel(0); - } break; - case CHEAT_LATALAY: - { - cheat_gotoLevel(1); - } break; - case CHEAT_LASEWERS: - { - cheat_gotoLevel(2); - } break; - case CHEAT_LATESTBASE: - { - cheat_gotoLevel(3); - } break; - case CHEAT_LAGROMAS: - { - cheat_gotoLevel(4); - } break; - case CHEAT_LADTENTION: - { - cheat_gotoLevel(5); - } break; - case CHEAT_LARAMSHED: - { - cheat_gotoLevel(6); - } break; - case CHEAT_LAROBOTICS: - { - cheat_gotoLevel(7); - } break; - case CHEAT_LANARSHADA: - { - cheat_gotoLevel(8); - } break; - case CHEAT_LAJABSHIP: - { - cheat_gotoLevel(9); - } break; - case CHEAT_LAIMPCITY: - { - cheat_gotoLevel(10); - } break; - case CHEAT_LAFUELSTAT: - { - cheat_gotoLevel(11); - } break; - case CHEAT_LAEXECUTOR: - { - cheat_gotoLevel(12); - } break; - case CHEAT_LAARC: - { - cheat_gotoLevel(13); - } break; - case CHEAT_LASKIP: - { - cheat_levelSkip(); - } break; - case CHEAT_LABRADY: - { - cheat_fullAmmo(); - } break; - case CHEAT_LAUNLOCK: - { - cheat_unlock(); - } break; - case CHEAT_LAMAXOUT: - { - cheat_maxout(); - } break; - case CHEAT_LAFLY: - { - cheat_fly(); - } break; - case CHEAT_LANOCLIP: - { - cheat_noclip(); - } break; - case CHEAT_LATESTER: - { - cheat_tester(); - } break; - } - } - - void handleBufferedInput() - { - const char* bufferedText = TFE_Input::getBufferedText(); - const size_t bufferedLen = strlen(bufferedText); - - for (size_t i = 0; i < bufferedLen; i++) - { - char c = toupper(bufferedText[i]); - if (s_cheatInputCount < 2 && c == 'L') - { - s_cheatInputCount = 1; - } - else if (s_cheatInputCount == 1) - { - if (c == 'A') - { - s_cheatInputCount = 2; - s_cheatCharIndex = 0; - s_cheatString[0] = 0; - } - else - { - s_cheatInputCount = 0; - } - } - else if (s_cheatInputCount >= 2) - { - s32 index = s_cheatCharIndex; - s_cheatCharIndex++; - - s_cheatString[index] = c; - s_cheatString[s_cheatCharIndex] = 0; - - CheatID cheatID = cheat_getID(); - executeCheat(cheatID); - } - } - } - - void mission_pause(JBool pause) - { - s_gamePaused = pause; - task_pause(s_gamePaused, s_mainTask); - time_pause(s_gamePaused); - TFE_Input::clearAccumulatedMouseMove(); - } - - void handleGeneralInput() - { - // Early out if the player is dying. - if (s_playerDying) - { - return; - } - - // In the DOS code, the game would just loop here - checking to see if paused has been pressed and then continue. - // Obviously that won't work for TFE, so the game paused variable is set and the game will have to handle it. - if (inputMapping_getActionState(IADF_PAUSE) == STATE_PRESSED) - { - mission_pause(~s_gamePaused); - } - - if (!s_gamePaused) - { - handleBufferedInput(); - if (s_queuedCheatID != CHEAT_NONE) - { - executeCheat(s_queuedCheatID); - s_queuedCheatID = CHEAT_NONE; - } - - // For now just deal with a few controls. - if (inputMapping_getActionState(IADF_PDA_TOGGLE) == STATE_PRESSED) - { - // Clear out the PDA_TOGGLE state for this frame since it will be read again later. - inputMapping_removeState(IADF_PDA_TOGGLE); - - mission_pause(JTRUE); - pda_start(agent_getLevelName()); - } - if (inputMapping_getActionState(IADF_NIGHT_VISION_TOG) == STATE_PRESSED && s_playerInfo.itemGoggles) - { - if (s_nightvisionActive) - { - disableNightvision(); - } - else - { - enableNightVision(); - } - } - if (inputMapping_getActionState(IADF_CLEATS_TOGGLE) == STATE_PRESSED && s_playerInfo.itemCleats) - { - if (s_wearingCleats) - { - disableCleats(); - } - else - { - enableCleats(); - } - } - if (inputMapping_getActionState(IADF_GAS_MASK_TOGGLE) == STATE_PRESSED && s_playerInfo.itemMask) - { - if (s_wearingGasmask) - { - disableMask(); - } - else - { - enableMask(); - } - } - if (inputMapping_getActionState(IADF_HEAD_LAMP_TOGGLE) == STATE_PRESSED) - { - if (s_headlampActive) - { - disableHeadlamp(); - } - else - { - enableHeadlamp(); - } - } - renderer_setupCameraLight(JFALSE, s_headlampActive); - - if (inputMapping_getActionState(IADF_HEADWAVE_TOGGLE) == STATE_PRESSED) - { - s_config.headwave = ~s_config.headwave; - if (s_config.headwave) - { - hud_sendTextMessage(14); - } - else - { - hud_sendTextMessage(15); - } - } - - if (inputMapping_getActionState(IADF_HUD_TOGGLE) == STATE_PRESSED) - { - s_config.showUI = hud_setupToggleAnim1(JFALSE); - } - - if (inputMapping_getActionState(IADF_HOLSTER_WEAPON) == STATE_PRESSED) - { - weapon_holster(); - } - - if (inputMapping_getActionState(IADF_AUTOMOUNT_TOGGLE) == STATE_PRESSED) - { - s_config.wpnAutoMount = ~s_config.wpnAutoMount; - weapon_enableAutomount(s_config.wpnAutoMount); - if (!s_config.wpnAutoMount) - { - hud_sendTextMessage(23); - } - else - { - hud_sendTextMessage(24); - } - } - - if (inputMapping_getActionState(IADF_CYCLEWPN_PREV)) - { - player_cycleWeapons(-1); - } - else if (inputMapping_getActionState(IADF_CYCLEWPN_NEXT)) - { - player_cycleWeapons(1); - } - - if (inputMapping_getActionState(IADF_AUTOMAP) == STATE_PRESSED) - { - s_drawAutomap = ~s_drawAutomap; - if (s_drawAutomap) - { - automap_updateMapData(MAP_ENABLE_AUTOCENTER); - automap_updateMapData(MAP_CENTER_PLAYER); - s_canTeleport = JTRUE; - reticle_enable(false); - } - else - { - s_canTeleport = JFALSE; - reticle_enable(true); - } - } - - if (s_drawAutomap) - { - reticle_enable(false); - - if (inputMapping_getActionState(IADF_MAP_ENABLE_SCROLL)) - { - automap_disableLock(); - } - else - { - automap_enableLock(); - } - - if (inputMapping_getActionState(IADF_MAP_ZOOM_IN)) - { - automap_updateMapData(MAP_ZOOM_IN); - } - else if (inputMapping_getActionState(IADF_MAP_ZOOM_OUT)) - { - automap_updateMapData(MAP_ZOOM_OUT); - } - - if (inputMapping_getActionState(IADF_MAP_LAYER_UP) == STATE_PRESSED) - { - automap_updateMapData(MAP_LAYER_UP); - - s32 msgId = min(automap_getLayer() + 609, 618); - hud_sendTextMessage(msgId); - } - else if (inputMapping_getActionState(IADF_MAP_LAYER_DN) == STATE_PRESSED) - { - automap_updateMapData(MAP_LAYER_DOWN); - - s32 msgId = min(automap_getLayer() + 609, 618); - hud_sendTextMessage(msgId); - } - - if (!s_automapLocked) - { - if (inputMapping_getActionState(IADF_MAP_SCROLL_UP)) - { - automap_updateMapData(MAP_MOVE1_UP); - } - if (inputMapping_getActionState(IADF_MAP_SCROLL_DN)) - { - automap_updateMapData(MAP_MOVE1_DN); - } - if (inputMapping_getActionState(IADF_MAP_SCROLL_LT)) - { - automap_updateMapData(MAP_MOVE1_LEFT); - } - if (inputMapping_getActionState(IADF_MAP_SCROLL_RT)) - { - automap_updateMapData(MAP_MOVE1_RIGHT); - } - } - } - else - { - automap_enableLock(); - } - } - - // DEBUG - change music state. - #if 0 - if (TFE_Input::keyPressed(KEY_F)) - { - gameMusic_setState(MUS_STATE_FIGHT); - } - else if (TFE_Input::keyPressed(KEY_G)) - { - gameMusic_setState(MUS_STATE_STALK); - } - #endif - } - - void updateScreensize() - { - // STUB: Not needed until screensizes are supported. - } - - //////////////////////////////////////////// - // Palette Filters and Effects - //////////////////////////////////////////// - void applyLuminanceFilter(u8* pal, JBool lumRedMask, JBool lumGreenMask, JBool lumBlueMask) - { - u8* end = &pal[768]; - for (; pal < end; pal += 3) - { - // Compute the approximate luminance (red/4 + green/2 + blue/4) - u32 L = (pal[0] >> 2) + (pal[1] >> 1) + (pal[2] >> 2); - // Then assign the luminance to the requested channels. - pal[0] = lumRedMask ? L : 0; - pal[1] = lumGreenMask ? L : 0; - pal[2] = lumBlueMask ? L : 0; - } - } - - void applyScreenFxToPalette(u8* pal, s32 healthFxLevel, s32 shieldFxLevel, s32 flashFxLevel) - { - s32 intensity; - s32 filterIndex; - s32 clrIndex0, clrIndex1; - if (healthFxLevel) - { - intensity = 63 - (healthFxLevel & 63); - filterIndex = 0; - clrIndex0 = 1; - clrIndex1 = 2; - } - else if (shieldFxLevel) - { - intensity = 63 - (shieldFxLevel & 63); - filterIndex = 1; - clrIndex0 = 0; - clrIndex1 = 2; - } - else - { - intensity = 63 - (flashFxLevel & 63); - filterIndex = 2; - clrIndex0 = 0; - clrIndex1 = 1; - } - - u8* c0 = &pal[clrIndex0]; - u8* c1 = &pal[clrIndex1]; - u8* filterColor = &pal[filterIndex]; - - for (s32 i = 0; i < 256; i++) - { - // Essentially: 63 - abs(63 - color) * (1 - flashLevel) - // Note that when flashLevel = 0: 63 - 63 + color = color - // flashLevel = 1: 63 = pure blue. - *filterColor = 63 - (TFE_Jedi::abs((63 - (*filterColor)) * intensity) >> 6); - - // Color channel = color * (1 - flashLevel) - *c0 = TFE_Jedi::abs((*c0) * intensity) >> 6; - *c1 = TFE_Jedi::abs((*c1) * intensity) >> 6; - - filterColor += 3; - c0 += 3; - c1 += 3; - } - } - - void applyScreenBrightness(u8* pal, s32 brightness) - { - u8* end = &pal[768]; - for (s32 i = 0; i < 256; i++, pal += 3) - { - fixed16_16 color = intToFixed16(pal[0]); - color = mul16(color, brightness) + HALF_16; - pal[0] = floor16(color); - - color = intToFixed16(pal[1]); - color = mul16(color, brightness) + HALF_16; - pal[1] = floor16(color); - - color = intToFixed16(pal[2]); - color = mul16(color, brightness) + HALF_16; - pal[2] = floor16(color); - } - } - - void blankScreen() - { - u32 zero[256] = { 0 }; - // Make sure both buffers are cleared out to avoid flashes. - vfb_setPalette(zero); - vfb_setPalette(zero); - } - -} // TFE_DarkForces -#ifdef TFE_ESPBOX -void espbox_shared_mission(bool alloc) -{ - ESPBOX_SHARED_ALLOC(TFE_DarkForces::s_colormapName, TFE_MAX_PATH); -} -#endif diff --git a/components/darkforces/tfe/TFE_DarkForces/mission.h b/components/darkforces/tfe/TFE_DarkForces/mission.h deleted file mode 100644 index 23d85dfb..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/mission.h +++ /dev/null @@ -1,50 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces Mission Loop -// The main mission loop, including loading and shutdown. -////////////////////////////////////////////////////////////////////// - -#include -#include -#include -#include -#include - -#define CONV_6bitTo8bit(x) (((x)<<2) | ((x)>>4)) - -namespace TFE_DarkForces -{ - enum GameMissionMode - { - MISSION_MODE_LOADING = 0, // causes the loading screen to be displayed. - MISSION_MODE_MAIN = 1, // the main in-game experience. - MISSION_MODE_UNKNOWN = 2, // unknown - not set (as far as I can tell). - MISSION_MODE_LOAD_START = 3, // set right as loading starts. - }; - - void mission_setLoadingFromSave(); - void mission_startTaskFunc(MessageType msg); - void mission_setLoadMissionTask(Task* task); - void mission_exitLevel(); - void mission_pause(JBool pause); - - void setScreenFxLevels(s32 healthFx, s32 shieldFx, s32 flashFx); - void disableNightvisionInternal(); - - void disableMask(); - void disableCleats(); - void disableNightvision(); - - void mission_render(s32 rendererIndex = 0); - - void mission_setupTasks(); - void mission_serialize(Stream* stream); - void mission_serializeColorMap(Stream* stream); - - extern JBool s_gamePaused; - extern GameMissionMode s_missionMode; - extern TextureData* s_loadScreen; - extern u8 s_loadingScreenPal[]; - extern u8 s_levelPalette[]; - extern u8 s_basePalette[]; -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/pickup.cpp b/components/darkforces/tfe/TFE_DarkForces/pickup.cpp deleted file mode 100644 index b43dfad5..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/pickup.cpp +++ /dev/null @@ -1,1174 +0,0 @@ -#include "pickup.h" -#include "player.h" -#include "hud.h" -#include "weapon.h" -#include "sound.h" -#include -#include -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - ////////////////////////////////////////////////////////////// - // Structures and Constants - ////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////// - // Internal State - ////////////////////////////////////////////////////////////// - u32 s_playerDying = 0; - // Pointer to memory where player inventory is saved. - Task* s_pickupTask = nullptr; - Task* s_superchargeTask = nullptr; - Task* s_invincibilityTask = nullptr; - Task* s_gasmaskTask = nullptr; - Task* s_gasSectorTask = nullptr; - - enum { MAX_PICKUP_FREE_ITEMS = 128 }; - static Pickup* s_listToFree[MAX_PICKUP_FREE_ITEMS]; - static s32 s_listToFreeCnt = 0; - - ////////////////////////////////////////////////////////////// - // Forward Declarations - ////////////////////////////////////////////////////////////// - void pickTaskFunc(MessageType msg); - void pickupInvincibility(); - void pickupInventory(); - void pickupItem(MessageType msg); - - void gasmaskTaskFunc(MessageType msg); - void invincibilityTaskFunc(MessageType msg); - void superchargeTaskFunc(MessageType msg); - - ////////////////////////////////////////////////////////////// - // API Implementation - ////////////////////////////////////////////////////////////// - void pickup_clearState() - { - s_playerDying = 0; - s_listToFreeCnt = 0; - // Pointer to memory where player inventory is saved. - s_pickupTask = nullptr; - s_superchargeTask = nullptr; - s_invincibilityTask = nullptr; - s_gasmaskTask = nullptr; - s_gasSectorTask = nullptr; - } - - // TODO: Move keyword to pickup mapping to a datafile to avoid hardcoding. - ItemId getPickupItemId(const char* keyword) - { - const KEYWORD kw = getKeywordIndex(keyword); - ItemId id; - switch (kw) - { - case KW_BATTERY: id = ITEM_BATTERY; break; - case KW_BLUE: id = ITEM_BLUE_KEY; break; - case KW_CANNON: id = ITEM_CANNON; break; - case KW_CLEATS: id = ITEM_CLEATS; break; - case KW_CODE1: id = ITEM_CODE1; break; - case KW_CODE2: id = ITEM_CODE2; break; - case KW_CODE3: id = ITEM_CODE3; break; - case KW_CODE4: id = ITEM_CODE4; break; - case KW_CODE5: id = ITEM_CODE5; break; - case KW_CODE6: id = ITEM_CODE6; break; - case KW_CODE7: id = ITEM_CODE7; break; - case KW_CODE8: id = ITEM_CODE8; break; - case KW_CODE9: id = ITEM_CODE9; break; - case KW_CONCUSSION: id = ITEM_CONCUSSION; break; - case KW_DETONATOR: id = ITEM_DETONATOR; break; - case KW_DETONATORS: id = ITEM_DETONATORS; break; - case KW_DT_WEAPON: id = ITEM_DT_WEAPON; break; - case KW_DATATAPE: id = ITEM_DATATAPE; break; - case KW_ENERGY: id = ITEM_ENERGY; break; - case KW_FUSION: id = ITEM_FUSION; break; - case KW_GOGGLES: id = ITEM_GOGGLES; break; - case KW_MASK: id = ITEM_MASK; break; - case KW_MINE: id = ITEM_MINE; break; - case KW_MINES: id = ITEM_MINES; break; - case KW_MISSILE: id = ITEM_MISSILE; break; - case KW_MISSILES: id = ITEM_MISSILES; break; - case KW_MORTAR: id = ITEM_MORTAR; break; - case KW_NAVA: id = ITEM_NAVA; break; - case KW_PHRIK: id = ITEM_PHRIK; break; - case KW_PLANS: id = ITEM_PLANS; break; - case KW_PLASMA: id = ITEM_PLASMA; break; - case KW_POWER: id = ITEM_POWER; break; - case KW_RED: id = ITEM_RED_KEY; break; - case KW_RIFLE: id = ITEM_RIFLE; break; - case KW_SHELL: id = ITEM_SHELL; break; - case KW_SHELLS: id = ITEM_SHELLS; break; - case KW_SHIELD: id = ITEM_SHIELD; break; - case KW_INVINCIBLE: id = ITEM_INVINCIBLE; break; - case KW_REVIVE: id = ITEM_REVIVE; break; - case KW_SUPERCHARGE:id = ITEM_SUPERCHARGE;break; - case KW_LIFE: id = ITEM_LIFE; break; - case KW_MEDKIT: id = ITEM_MEDKIT; break; - case KW_PILE: id = ITEM_PILE; break; - case KW_YELLOW: id = ITEM_YELLOW_KEY; break; - case KW_AUTOGUN: id = ITEM_AUTOGUN; break; - default: id = ITEM_PLANS; - } - return id; - } - - void pickup_cleanupFunc(Logic* logic) - { - deleteLogicAndObject(logic); - } - - void pickup_createTask() - { - pickup_clearState(); - s_pickupTask = createSubTask("pickups", pickTaskFunc, pickupItem); - } - - void pickupItem(MessageType msg) - { - Pickup* pickup = (Pickup*)s_msgTarget; - SecObject* entity = (SecObject*)s_msgEntity; - if (msg == MSG_DAMAGE || msg == MSG_EXPLOSION) - { - return; - } - // Only the player can pickup an item. - if (entity && !(entity->entityFlags & ETFLAG_PLAYER)) - { - return; - } - - JBool pickedUpItem = s_playerDying ? JFALSE : JTRUE; - // Cannot pickup items while dying! - if (!pickedUpItem) - { - return; - } - - // Handle pickup based on type. - if (pickup->type == ITYPE_WEAPON) - { - s32 maxAmount = pickup->maxAmount; - if (!(*pickup->item) || *pickup->value < maxAmount) - { - *pickup->value = pickup_addToValue(*pickup->value, pickup->amount, maxAmount); - if (*pickup->item) - { - hud_sendTextMessage(pickup->msgId[1]); - } - else - { - *pickup->item = JTRUE; - hud_sendTextMessage(pickup->msgId[0]); - s_playerInfo.newWeapon = pickup->index; - } - } - else - { - pickedUpItem = JFALSE; - } - } - else if (pickup->type == ITYPE_AMMO) - { - // Shield powerups cannot be picked up while invincibility is enabled even if shields are at less than maximum. - if (pickup->id == ITEM_SHIELD && s_invincibility) - { - pickedUpItem = JFALSE; - } - s32 curValue = *pickup->value; - if (pickedUpItem && curValue < pickup->maxAmount) - { - *pickup->value = pickup_addToValue(*pickup->value, pickup->amount, pickup->maxAmount); - hud_sendTextMessage(pickup->msgId[0]); - } - else - { - pickedUpItem = JFALSE; - } - } - else if (pickup->type == ITYPE_KEY_ITEM) - { - *pickup->item = JTRUE; - hud_sendTextMessage(pickup->msgId[0]); - if (pickup->value) - { - *pickup->value = pickup_addToValue(*pickup->value, pickup->amount, pickup->maxAmount); - } - if (pickup->id == ITEM_CLEATS && s_wearingCleats == 0) - { - s_wearingCleats = JTRUE; - } - } - else if (pickup->type == ITYPE_OBJECTIVE) - { - *pickup->item = JTRUE; - hud_sendTextMessage(pickup->msgId[0]); - if (s_levelState.completeSector) - { - message_sendToSector(s_levelState.completeSector, nullptr, 0, MSG_TRIGGER); - } - - switch (pickup->id) - { - case ITEM_PLANS: - { - s_levelState.complete[1][0] = JTRUE; - } break; - case ITEM_PHRIK: - { - s_levelState.complete[1][1] = JTRUE; - } break; - case ITEM_NAVA: - { - s_levelState.complete[1][2] = JTRUE; - } break; - case ITEM_DT_WEAPON: - { - s_levelState.complete[1][5] = JTRUE; - } break; - case ITEM_DATATAPE: - { - s_levelState.complete[1][4] = JTRUE; - } break; - } - } - else if (pickup->type == ITYPE_INV_ITEM) - { - *pickup->item = JTRUE; - hud_sendTextMessage(pickup->msgId[0]); - } - else if (pickup->type == ITYPE_POWERUP) - { - switch (pickup->id) - { - case ITEM_INVINCIBLE: - { - pickupInvincibility(); - } break; - case ITEM_SUPERCHARGE: - { - pickupSupercharge(); - } break; - case ITEM_REVIVE: - { - if (s_playerInfo.health < 100 || s_playerInfo.shields < 200) - { - player_revive(); - // The function sets shields to 100, so set it to the proper value here. - s_playerInfo.shields = 200; - } - else - { - pickedUpItem = JFALSE; - } - } break; - case ITEM_LIFE: - { - if (s_lifeCount < 9) - { - s_lifeCount++; - } - else - { - pickedUpItem = 0; - } - } break; - } - if (pickedUpItem) - { - hud_sendTextMessage(pickup->msgId[0]); - } - } - else if (pickup->type == ITYPE_SPECIAL) - { - hud_sendTextMessage(312); - pickupInventory(); - s_levelState.complete[1][6] = JTRUE; - - if (s_levelState.completeSector) - { - message_sendToSector(s_levelState.completeSector, nullptr, 0, MSG_TRIGGER); - } - } - - // Finish - if (!pickedUpItem) - { - return; - } - // Set the world width to 0 so the object cannot be picked up even if it isn't fully deleted. - SecObject* pickupObj = pickup->logic.obj; - pickupObj->worldWidth = 0; - - // Play pickup sound. - if (pickup->type == ITYPE_KEY_ITEM || pickup->type == ITYPE_POWERUP) - { - sound_play(s_powerupPickupSnd); - } - else if (pickup->type == ITYPE_OBJECTIVE || pickup->type == ITYPE_SPECIAL) - { - sound_play(s_invItemPickupSnd); - } - else - { - sound_play(s_wpnPickupSnd); - } - - // Initialize effect - s_flashEffect = FIXED(15); - task_makeActive(s_pickupTask); - - // Instead of setting up a task, I just add it to a free list that will run next time the pickup task runs - which will be next frame since it is made active. - { - s_listToFree[s_listToFreeCnt++] = pickup; - } - } - - void freeItems() - { - for (s32 i = s_listToFreeCnt - 1; i >= 0; i--) - { - pickup_cleanupFunc((Logic*)s_listToFree[i]); - } - s_listToFreeCnt = 0; - } - - // The current pickup being processed is stored in Message::s_msgTarget - // The object "picking up" the item is stored in Message::s_msgEntity - void pickTaskFunc(MessageType msg) - { - struct LocalContext - { - SecObject* pickupObj; - SecObject* entity; - Pickup* pickup; - JBool pickedUpItem; - }; - task_begin_ctx; - while (msg != MSG_FREE_TASK) - { - // Sleep until called. - task_yield(TASK_SLEEP); - if (msg == MSG_RUN_TASK) - { - freeItems(); - } - - if (msg == MSG_FREE) - { - pickup_cleanupFunc((Logic*)s_msgTarget); - } - else if (msg == MSG_PICKUP) - { - pickupItem(msg); - } // if (id == PICKUP_ACQUIRE) - } // while (id != -1) - task_end; - } - - // TODO: Move pickup data to an external data file to avoid hardcoding. - Logic* obj_createPickup(SecObject* obj, ItemId id) - { - Pickup* pickup = (Pickup*)level_alloc(sizeof(Pickup)); - obj_addLogic(obj, (Logic*)pickup, LOGIC_PICKUP, s_pickupTask, pickup_cleanupFunc); - - obj->entityFlags |= ETFLAG_PICKUP; - obj->worldHeight = 16384; // 0.25 - - // Setup the pickup based on the ItemId. - pickup->id = id; - pickup->index = -1; - pickup->item = nullptr; - pickup->value = nullptr; - pickup->amount = 0; - pickup->msgId[0] = -1; - pickup->msgId[1] = -1; - - switch (id) - { - // MISSION ITEMS - case ITEM_PLANS: - { - pickup->type = ITYPE_OBJECTIVE; - pickup->item = &s_playerInfo.itemPlans; - pickup->msgId[0] = 400; - - obj->flags |= (OBJ_FLAG_FULLBRIGHT | OBJ_FLAG_MISSION); - } break; - case ITEM_PHRIK: - { - pickup->type = ITYPE_OBJECTIVE; - pickup->item = &s_playerInfo.itemPhrik; - pickup->msgId[0] = 401; - - obj->flags |= (OBJ_FLAG_FULLBRIGHT | OBJ_FLAG_MISSION); - } break; - case ITEM_NAVA: - { - pickup->type = ITYPE_OBJECTIVE; - pickup->item = &s_playerInfo.itemNava; - pickup->msgId[0] = 402; - - obj->flags |= (OBJ_FLAG_FULLBRIGHT | OBJ_FLAG_MISSION); - } break; - case ITEM_DT_WEAPON: - { - pickup->type = ITYPE_OBJECTIVE; - pickup->item = &s_playerInfo.itemDtWeapon; - pickup->msgId[0] = 405; - - obj->flags |= OBJ_FLAG_MISSION; - } break; - case ITEM_DATATAPE: - { - pickup->type = ITYPE_OBJECTIVE; - pickup->item = &s_playerInfo.itemDatatape; - pickup->msgId[0] = 406; - - obj->flags |= OBJ_FLAG_MISSION; - } break; - // WEAPONS - case ITEM_RIFLE: - { - pickup->index = 2; - pickup->type = ITYPE_WEAPON; - pickup->item = &s_playerInfo.itemRifle; - pickup->value = &s_playerInfo.ammoEnergy; - pickup->amount = 15; - pickup->msgId[0] = 100; - pickup->msgId[1] = 101; - pickup->maxAmount = 500; - } break; - case ITEM_AUTOGUN: - { - pickup->index = 4; - pickup->type = ITYPE_WEAPON; - pickup->item = &s_playerInfo.itemAutogun; - pickup->value = &s_playerInfo.ammoPower; - pickup->amount = 30; - pickup->msgId[0] = 103; - pickup->msgId[1] = 104; - pickup->maxAmount = 500; - } break; - case ITEM_MORTAR: - { - pickup->index = 6; - pickup->type = ITYPE_WEAPON; - pickup->item = &s_playerInfo.itemMortar; - pickup->value = &s_playerInfo.ammoShell; - pickup->amount = 3; - pickup->msgId[0] = 105; - pickup->msgId[1] = 106; - pickup->maxAmount = 50; - } break; - case ITEM_FUSION: - { - pickup->index = 5; - pickup->type = ITYPE_WEAPON; - pickup->item = &s_playerInfo.itemFusion; - pickup->value = &s_playerInfo.ammoPower; - pickup->amount = 50; - pickup->msgId[0] = 107; - pickup->msgId[1] = 108; - pickup->maxAmount = 500; - } break; - case ITEM_CONCUSSION: - { - pickup->index = 8; - pickup->type = ITYPE_WEAPON; - pickup->item = &s_playerInfo.itemConcussion; - pickup->value = &s_playerInfo.ammoPower; - pickup->amount = 100; - pickup->msgId[0] = 110; - pickup->msgId[1] = 111; - pickup->maxAmount = 500; - } break; - case ITEM_CANNON: - { - pickup->index = 9; - pickup->type = ITYPE_WEAPON; - pickup->item = &s_playerInfo.itemCannon; - pickup->value = &s_playerInfo.ammoPlasma; - pickup->amount = 30; - pickup->msgId[0] = 112; - pickup->msgId[1] = 113; - pickup->maxAmount = 400; - } break; - // AMMO - case ITEM_ENERGY: - { - pickup->type = ITYPE_AMMO; - pickup->value = &s_playerInfo.ammoEnergy; - pickup->amount = 15; - pickup->msgId[0] = 200; - pickup->maxAmount = 500; - } break; - case ITEM_POWER: - { - pickup->type = ITYPE_AMMO; - pickup->value = &s_playerInfo.ammoPower; - pickup->amount = 10; - pickup->msgId[0] = 201; - pickup->maxAmount = 500; - } break; - case ITEM_PLASMA: - { - pickup->type = ITYPE_AMMO; - pickup->value = &s_playerInfo.ammoPlasma; - pickup->amount = 20; - pickup->msgId[0] = 202; - pickup->maxAmount = 400; - } break; - case ITEM_DETONATOR: - { - pickup->type = ITYPE_AMMO; - pickup->value = &s_playerInfo.ammoDetonator; - pickup->amount = 1; - pickup->msgId[0] = 203; - pickup->maxAmount = 50; - } break; - case ITEM_DETONATORS: - { - pickup->type = ITYPE_AMMO; - pickup->value = &s_playerInfo.ammoDetonator; - pickup->amount = 5; - pickup->msgId[0] = 204; - pickup->maxAmount = 50; - } break; - case ITEM_SHELL: - { - pickup->type = ITYPE_AMMO; - pickup->value = &s_playerInfo.ammoShell; - pickup->amount = 1; - pickup->msgId[0] = 205; - pickup->maxAmount = 50; - } break; - case ITEM_SHELLS: - { - pickup->type = ITYPE_AMMO; - pickup->value = &s_playerInfo.ammoShell; - pickup->amount = 5; - pickup->msgId[0] = 206; - pickup->maxAmount = 50; - } break; - case ITEM_MINE: - { - pickup->type = ITYPE_AMMO; - pickup->value = &s_playerInfo.ammoMine; - pickup->amount = 1; - pickup->msgId[0] = 207; - pickup->maxAmount = 30; - } break; - case ITEM_MINES: - { - pickup->type = ITYPE_AMMO; - pickup->value = &s_playerInfo.ammoMine; - pickup->amount = 5; - pickup->msgId[0] = 208; - pickup->maxAmount = 30; - } break; - case ITEM_MISSILE: - { - pickup->type = ITYPE_AMMO; - pickup->value = &s_playerInfo.ammoMissile; - pickup->amount = 1; - pickup->msgId[0] = 209; - pickup->maxAmount = 20; - } break; - case ITEM_MISSILES: - { - pickup->type = ITYPE_AMMO; - pickup->value = &s_playerInfo.ammoMissile; - pickup->amount = 5; - pickup->msgId[0] = 210; - pickup->maxAmount = 20; - } break; - // PICKUPS & KEYS - case ITEM_SHIELD: - { - pickup->type = ITYPE_AMMO; - pickup->value = &s_playerInfo.shields; - pickup->amount = 20; - pickup->msgId[0] = 114; - pickup->maxAmount = 200; - } break; - case ITEM_RED_KEY: - { - pickup->type = ITYPE_KEY_ITEM; - pickup->item = &s_playerInfo.itemRedKey; - pickup->msgId[0] = 300; - } break; - case ITEM_YELLOW_KEY: - { - pickup->type = ITYPE_KEY_ITEM; - pickup->item = &s_playerInfo.itemYellowKey; - pickup->msgId[0] = 301; - } break; - case ITEM_BLUE_KEY: - { - pickup->type = ITYPE_KEY_ITEM; - pickup->item = &s_playerInfo.itemBlueKey; - pickup->msgId[0] = 302; - } break; - case ITEM_GOGGLES: - { - pickup->type = ITYPE_KEY_ITEM; - pickup->item = &s_playerInfo.itemGoggles; - pickup->value = &s_batteryPower; - pickup->msgId[0] = 303; - pickup->amount = ONE_16; - pickup->maxAmount = 2 * ONE_16; - } break; - case ITEM_CLEATS: - { - pickup->type = ITYPE_KEY_ITEM; - pickup->item = &s_playerInfo.itemCleats; - pickup->msgId[0] = 304; - } break; - case ITEM_MASK: - { - pickup->type = ITYPE_KEY_ITEM; - pickup->item = &s_playerInfo.itemMask; - pickup->value = &s_batteryPower; - pickup->msgId[0] = 305; - pickup->amount = ONE_16; - pickup->maxAmount = 2 * ONE_16; - } break; - case ITEM_BATTERY: - { - pickup->type = ITYPE_AMMO; - pickup->value = &s_batteryPower; - pickup->msgId[0] = 211; - pickup->amount = ONE_16; - pickup->maxAmount = 2 * ONE_16; - } break; - case ITEM_CODE1: - { - pickup->type = ITYPE_INV_ITEM; - pickup->item = &s_playerInfo.itemCode1; - pickup->msgId[0] = 501; - - obj->flags |= (OBJ_FLAG_FULLBRIGHT | OBJ_FLAG_MISSION); - } break; - case ITEM_CODE2: - { - pickup->type = ITYPE_INV_ITEM; - pickup->item = &s_playerInfo.itemCode2; - pickup->msgId[0] = 502; - - obj->flags |= (OBJ_FLAG_FULLBRIGHT | OBJ_FLAG_MISSION); - } break; - case ITEM_CODE3: - { - pickup->type = ITYPE_INV_ITEM; - pickup->item = &s_playerInfo.itemCode3; - pickup->msgId[0] = 503; - - obj->flags |= (OBJ_FLAG_FULLBRIGHT | OBJ_FLAG_MISSION); - } break; - case ITEM_CODE4: - { - pickup->type = ITYPE_INV_ITEM; - pickup->item = &s_playerInfo.itemCode4; - pickup->msgId[0] = 504; - - obj->flags |= (OBJ_FLAG_FULLBRIGHT | OBJ_FLAG_MISSION); - } break; - case ITEM_CODE5: - { - pickup->type = ITYPE_INV_ITEM; - pickup->item = &s_playerInfo.itemCode5; - pickup->msgId[0] = 505; - - obj->flags |= (OBJ_FLAG_FULLBRIGHT | OBJ_FLAG_MISSION); - } break; - case ITEM_CODE6: - { - pickup->type = ITYPE_INV_ITEM; - pickup->item = &s_playerInfo.itemCode6; - pickup->msgId[0] = 506; - - obj->flags |= (OBJ_FLAG_FULLBRIGHT | OBJ_FLAG_MISSION); - } break; - case ITEM_CODE7: - { - pickup->type = ITYPE_INV_ITEM; - pickup->item = &s_playerInfo.itemCode7; - pickup->msgId[0] = 507; - - obj->flags |= (OBJ_FLAG_FULLBRIGHT | OBJ_FLAG_MISSION); - } break; - case ITEM_CODE8: - { - pickup->type = ITYPE_INV_ITEM; - pickup->item = &s_playerInfo.itemCode8; - pickup->msgId[0] = 508; - - obj->flags |= (OBJ_FLAG_FULLBRIGHT | OBJ_FLAG_MISSION); - } break; - case ITEM_CODE9: - { - pickup->type = ITYPE_INV_ITEM; - pickup->item = &s_playerInfo.itemCode9; - pickup->msgId[0] = 509; - - obj->flags |= (OBJ_FLAG_FULLBRIGHT | OBJ_FLAG_MISSION); - } break; - case ITEM_INVINCIBLE: - { - pickup->type = ITYPE_POWERUP; - pickup->item = nullptr; - pickup->msgId[0] = 306; - } break; - case ITEM_SUPERCHARGE: - { - pickup->type = ITYPE_POWERUP; - pickup->item = nullptr; - pickup->msgId[0] = 307; - } break; - case ITEM_REVIVE: - { - pickup->type = ITYPE_POWERUP; - pickup->item = nullptr; - pickup->msgId[0] = 308; - } break; - case ITEM_LIFE: - { - pickup->type = ITYPE_POWERUP; - pickup->item = nullptr; - pickup->msgId[0] = 310; - } break; - case ITEM_MEDKIT: - { - pickup->type = ITYPE_AMMO; - pickup->value = &s_playerInfo.health; - pickup->amount = 20; - pickup->msgId[0] = 311; - pickup->maxAmount = 100; - } break; - case ITEM_PILE: - { - pickup->type = ITYPE_SPECIAL; - } break; - } - return (Logic*)pickup; - } - - s32 pickup_addToValue(s32 curValue, s32 amountToAdd, s32 maxAmount) - { - s32 newValue = curValue + amountToAdd; - if (newValue < 0) - { - newValue = 0; - } - else if (newValue > maxAmount) - { - newValue = maxAmount; - } - return newValue; - } - - // Serialization - void pickupLogic_setItemValue(Pickup* pickup) - { - pickup->item = nullptr; - pickup->value = nullptr; - - switch (pickup->id) - { - case ITEM_PLANS: - { - pickup->item = &s_playerInfo.itemPlans; - } break; - case ITEM_PHRIK: - { - pickup->item = &s_playerInfo.itemPhrik; - } break; - case ITEM_NAVA: - { - pickup->item = &s_playerInfo.itemNava; - } break; - case ITEM_DT_WEAPON: - { - pickup->item = &s_playerInfo.itemDtWeapon; - } break; - case ITEM_DATATAPE: - { - pickup->item = &s_playerInfo.itemDatatape; - } break; - // WEAPONS - case ITEM_RIFLE: - { - pickup->item = &s_playerInfo.itemRifle; - pickup->value = &s_playerInfo.ammoEnergy; - } break; - case ITEM_AUTOGUN: - { - pickup->item = &s_playerInfo.itemAutogun; - pickup->value = &s_playerInfo.ammoPower; - } break; - case ITEM_MORTAR: - { - pickup->item = &s_playerInfo.itemMortar; - pickup->value = &s_playerInfo.ammoShell; - } break; - case ITEM_FUSION: - { - pickup->item = &s_playerInfo.itemFusion; - pickup->value = &s_playerInfo.ammoPower; - } break; - case ITEM_CONCUSSION: - { - pickup->item = &s_playerInfo.itemConcussion; - pickup->value = &s_playerInfo.ammoPower; - } break; - case ITEM_CANNON: - { - pickup->item = &s_playerInfo.itemCannon; - pickup->value = &s_playerInfo.ammoPlasma; - } break; - case ITEM_ENERGY: - { - pickup->value = &s_playerInfo.ammoEnergy; - } break; - case ITEM_POWER: - { - pickup->value = &s_playerInfo.ammoPower; - } break; - case ITEM_PLASMA: - { - pickup->value = &s_playerInfo.ammoPlasma; - } break; - case ITEM_DETONATOR: - { - pickup->value = &s_playerInfo.ammoDetonator; - } break; - case ITEM_DETONATORS: - { - pickup->value = &s_playerInfo.ammoDetonator; - } break; - case ITEM_SHELL: - { - pickup->value = &s_playerInfo.ammoShell; - } break; - case ITEM_SHELLS: - { - pickup->value = &s_playerInfo.ammoShell; - } break; - case ITEM_MINE: - { - pickup->value = &s_playerInfo.ammoMine; - } break; - case ITEM_MINES: - { - pickup->value = &s_playerInfo.ammoMine; - } break; - case ITEM_MISSILE: - { - pickup->value = &s_playerInfo.ammoMissile; - } break; - case ITEM_MISSILES: - { - pickup->value = &s_playerInfo.ammoMissile; - } break; - case ITEM_SHIELD: - { - pickup->value = &s_playerInfo.shields; - } break; - case ITEM_RED_KEY: - { - pickup->item = &s_playerInfo.itemRedKey; - } break; - case ITEM_YELLOW_KEY: - { - pickup->item = &s_playerInfo.itemYellowKey; - } break; - case ITEM_BLUE_KEY: - { - pickup->item = &s_playerInfo.itemBlueKey; - } break; - case ITEM_GOGGLES: - { - pickup->item = &s_playerInfo.itemGoggles; - pickup->value = &s_batteryPower; - } break; - case ITEM_CLEATS: - { - pickup->item = &s_playerInfo.itemCleats; - } break; - case ITEM_MASK: - { - pickup->item = &s_playerInfo.itemMask; - pickup->value = &s_batteryPower; - } break; - case ITEM_BATTERY: - { - pickup->value = &s_batteryPower; - } break; - case ITEM_CODE1: - { - pickup->item = &s_playerInfo.itemCode1; - } break; - case ITEM_CODE2: - { - pickup->item = &s_playerInfo.itemCode2; - } break; - case ITEM_CODE3: - { - pickup->item = &s_playerInfo.itemCode3; - } break; - case ITEM_CODE4: - { - pickup->item = &s_playerInfo.itemCode4; - } break; - case ITEM_CODE5: - { - pickup->item = &s_playerInfo.itemCode5; - } break; - case ITEM_CODE6: - { - pickup->item = &s_playerInfo.itemCode6; - } break; - case ITEM_CODE7: - { - pickup->item = &s_playerInfo.itemCode7; - } break; - case ITEM_CODE8: - { - pickup->item = &s_playerInfo.itemCode8; - } break; - case ITEM_CODE9: - { - pickup->item = &s_playerInfo.itemCode9; - } break; - case ITEM_MEDKIT: - { - pickup->value = &s_playerInfo.health; - } break; - } - } - - void pickupLogic_serializeTasks(Stream* stream) - { - enum PickupTasks - { - PT_GASMASK = FLAG_BIT(0), - PT_INV = FLAG_BIT(1), - PT_SUPERCHARGE = FLAG_BIT(2), - }; - - u8 pickupTasks = 0; - if (serialization_getMode() == SMODE_WRITE) - { - pickupTasks |= s_gasmaskTask ? PT_GASMASK : 0; - pickupTasks |= s_invincibilityTask ? PT_INV : 0; - pickupTasks |= s_superCharge ? PT_SUPERCHARGE : 0; - } - SERIALIZE(SaveVersionInit, pickupTasks, 0); - if (pickupTasks & PT_GASMASK) - { - if (serialization_getMode() == SMODE_READ) - { - s_gasmaskTask = createSubTask("gasmask", gasmaskTaskFunc); - } - task_serializeState(stream, s_gasmaskTask); - } - if (pickupTasks & PT_INV) - { - if (serialization_getMode() == SMODE_READ) - { - s_invincibilityTask = createSubTask("invincibility", invincibilityTaskFunc); - } - task_serializeState(stream, s_invincibilityTask); - } - if (pickupTasks & PT_SUPERCHARGE) - { - if (serialization_getMode() == SMODE_READ) - { - s_superchargeTask = createSubTask("supercharge", superchargeTaskFunc); - } - task_serializeState(stream, s_superchargeTask); - } - } - - void pickupLogic_serialize(Logic*& logic, SecObject* obj, Stream* stream) - { - Pickup* pickup; - if (serialization_getMode() == SMODE_WRITE) - { - pickup = (Pickup*)logic; - } - else - { - pickup = (Pickup*)level_alloc(sizeof(Pickup)); - logic = (Logic*)pickup; - } - SERIALIZE(ObjState_InitVersion, pickup->id, ITEM_NONE); - SERIALIZE(ObjState_InitVersion, pickup->index, 0); - SERIALIZE(ObjState_InitVersion, pickup->type, ITYPE_NONE); - // item and value need to be setup based on type. - SERIALIZE(ObjState_InitVersion, pickup->amount, 0); - SERIALIZE_BUF(ObjState_InitVersion, pickup->msgId, sizeof(pickup->msgId[0]) * 2); - SERIALIZE(ObjState_InitVersion, pickup->maxAmount, 0); - - if (serialization_getMode() == SMODE_READ) - { - pickup->logic.task = s_pickupTask; - pickup->logic.cleanupFunc = pickup_cleanupFunc; - pickupLogic_setItemValue(pickup); - } - } - - ////////////////////////////////////////////////////////////// - // Internal Implementation - ////////////////////////////////////////////////////////////// - void gasmaskTaskFunc(MessageType msg) - { - struct LocalContext - { - SoundEffectId soundId; - }; - task_begin_ctx; - - while (1) - { - task_yield(291); // ~2 seconds. - - taskCtx->soundId = sound_play(s_maskSoundSource1); - sound_pitchShift(taskCtx->soundId, -16); - - task_yield(291); // ~2 seconds. - - taskCtx->soundId = sound_play(s_maskSoundSource2); - sound_pitchShift(taskCtx->soundId, 16); - } - - task_end; - } - - void invincibilityTaskFunc(MessageType msg) - { - struct LocalContext - { - s32 i; - }; - task_begin_ctx; - task_waitWhileIdNotZero(6554); // ~45 seconds. - - for (taskCtx->i = 4; taskCtx->i >= 0; taskCtx->i--) - { - sound_play(s_invCountdownSound); - s_playerInfo.shields = 200; - task_waitWhileIdNotZero(87); // 0.6 seconds. - - s_playerInfo.shields = 0xffffffff; - task_waitWhileIdNotZero(87); // 0.6 seconds. - } - s_playerInfo.shields = 200; - s_invincibility = 0; - s_invincibilityTask = nullptr; - - task_end; - } - - void superchargeTaskFunc(MessageType msg) - { - struct LocalContext - { - s32 i; - }; - task_begin_ctx; - - s_superChargeHud = JTRUE; - s_superCharge = JTRUE; - - // This causes the task to be suspended for 45 seconds - which is the time the supercharge is active - // without the running out warning. - task_waitWhileIdNotZero(6554); // ~45 seconds. - - for (taskCtx->i = 4; taskCtx->i >= 0; taskCtx->i--) - { - sound_play(s_superchargeCountdownSound); - s_superChargeHud = JFALSE; - task_waitWhileIdNotZero(87); // 0.6 seconds. - - s_superChargeHud = JTRUE; - task_waitWhileIdNotZero(87); // 0.6 seconds. - } - s_superCharge = JFALSE; - s_superChargeHud = JFALSE; - s_superchargeTask = nullptr; - - task_end; - } - - void pickupInvincibility() - { - s_invincibility = -1; - s_playerInfo.shields = JTRUE; // This seems like a bug... - // Free old invincibility task and create a new invincibility task. - if (s_invincibilityTask) - { - task_free(s_invincibilityTask); - } - s_invincibilityTask = createSubTask("invincibility", invincibilityTaskFunc); - } - - void pickupSupercharge() - { - // Free old supercharge task and create a new supercharge task. - if (s_superchargeTask) - { - task_free(s_superchargeTask); - } - s_superchargeTask = createSubTask("supercharge", superchargeTaskFunc); - } - - void pickupInventory() - { - // Get the size of the PlayerInfo structure up to but not including s_playerInfo.stateUnknown. - size_t size = (size_t)&s_playerInfo.pileSaveMarker - (size_t)&s_playerInfo; - if (s_playerInvSaved) - { - // Copy the saved player info and add it to the current player info. - u32* dst = (u32*)&s_playerInfo; - u32* src = s_playerInvSaved; - for (s32 sizeCopied = 0; sizeCopied < size; sizeCopied += 4, src++, dst++) - { - (*dst) += (*src); - } - - // Clear out the nava card item since it is one of the current objectives. - s_playerInfo.itemNava = JFALSE; - if (s_playerInfo.maxWeapon != s_playerInfo.curWeapon) - { - if (s_playerWeaponTask) - { - weapon_queueWeaponSwitch(s_playerInfo.maxWeapon); - s_playerInfo.maxWeapon = max(s_playerInfo.curWeapon, s_playerInfo.maxWeapon); - } - else - { - s_playerInfo.saveWeapon = s_playerInfo.maxWeapon; - } - } - - // Free saved inventory. - level_free(s_playerInvSaved); - s_playerInvSaved = nullptr; - // Clamp ammo values. - s_playerInfo.ammoEnergy = pickup_addToValue(s_playerInfo.ammoEnergy, 0, 500); - s_playerInfo.ammoPower = pickup_addToValue(s_playerInfo.ammoPower, 0, 500); - s_playerInfo.ammoPlasma = pickup_addToValue(s_playerInfo.ammoPlasma, 0, 400); - s_playerInfo.ammoDetonator = pickup_addToValue(s_playerInfo.ammoDetonator, 0, 50); - s_playerInfo.ammoShell = pickup_addToValue(s_playerInfo.ammoShell, 0, 50); - s_playerInfo.ammoMine = pickup_addToValue(s_playerInfo.ammoMine, 0, 30); - s_playerInfo.ammoMissile = pickup_addToValue(s_playerInfo.ammoMissile, 0, 20); - } - } -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/pickup.h b/components/darkforces/tfe/TFE_DarkForces/pickup.h deleted file mode 100644 index 787d2563..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/pickup.h +++ /dev/null @@ -1,50 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces Pickup - -// Items that can be picked up such as ammo, keys, extra lives, -// and weapons. -////////////////////////////////////////////////////////////////////// - -#include -#include -#include -#include -#include "logic.h" -#include "item.h" - -namespace TFE_DarkForces -{ - // This is a type of "Logic" and can be safety cast to Logic {}. - struct Pickup - { - Logic logic; // Logic header. - ItemId id; - s32 index; - ItemType type; - JBool* item; - s32* value; - s32 amount; - s32 msgId[2]; - s32 maxAmount; - }; - - ItemId getPickupItemId(const char* keyword); - Logic* obj_createPickup(SecObject* obj, ItemId id); - s32 pickup_addToValue(s32 curValue, s32 amountToAdd, s32 maxAmount); - void gasmaskTaskFunc(MessageType msg); - - // Logic update function, called when pickups are handled. - void pickup_createTask(); - // Called when the player respawns. - void pickupSupercharge(); - - // Serialization - void pickupLogic_serializeTasks(Stream* stream); - void pickupLogic_serialize(Logic*& logic, SecObject* obj, Stream* stream); - - extern u32 s_playerDying; - extern Task* s_superchargeTask; - extern Task* s_invincibilityTask; - extern Task* s_gasmaskTask; - extern Task* s_gasSectorTask; -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/player.cpp b/components/darkforces/tfe/TFE_DarkForces/player.cpp deleted file mode 100644 index 5a82784a..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/player.cpp +++ /dev/null @@ -1,3014 +0,0 @@ -#include - -#include "player.h" -#include "playerLogic.h" -#include "playerCollision.h" -#include "projectile.h" -#include "automap.h" -#include "agent.h" -#include "config.h" -#include "hud.h" -#include "mission.h" -#include "pickup.h" -#include "weapon.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -// Internal types need to be included in this case. -#include -#include -#include -#include - -// TFE -#include -#include - -using namespace TFE_Input; - -namespace TFE_Jedi -{ - extern s32 s_flatAmbient; - extern JBool s_flatLighting; -} - -namespace TFE_DarkForces -{ - /////////////////////////////////////////// - // Constants - /////////////////////////////////////////// - enum PlayerConstants - { - PLAYER_HEIGHT = 0x5cccc, // 5.8 units - PLAYER_WIDTH = 0x1cccc, // 1.8 units - PLAYER_PICKUP_ADJ = 0x18000, // 1.5 units - PLAYER_SIZE_SMALL = 0x4ccc, // 0.3 units - PLAYER_STEP = 0x38000, // 3.5 units - PLAYER_INF_STEP = COL_INFINITY, - PLAYER_HEADWAVE_VERT_SPD = 0xc000, // 0.75 units/sec. - PLAYER_HEADWAVE_VERT_WATER_SPD = 0x3000, // 0.1875 units/sec. -#ifdef TFE_ESPBOX - PLAYER_DMG_FLOOR_LOW = (5), // Low damage floors apply 5 dmg/sec. - PLAYER_DMG_FLOOR_HIGH = (10), // High damage floors apply 10 dmg/sec. - PLAYER_DMG_WALL = (20), // Damage walls apply 20 dmg/sec. - PLAYER_DMG_CRUSHING = (10), // The player suffers 10 dmg/sec. from crushing damage. -#else - PLAYER_DMG_FLOOR_LOW = FIXED(5), // Low damage floors apply 5 dmg/sec. - PLAYER_DMG_FLOOR_HIGH = FIXED(10), // High damage floors apply 10 dmg/sec. - PLAYER_DMG_WALL = FIXED(20), // Damage walls apply 20 dmg/sec. - PLAYER_DMG_CRUSHING = FIXED(10), // The player suffers 10 dmg/sec. from crushing damage. -#endif - PLAYER_FALL_SCREAM_VEL = FIXED(60), // Fall speed when the player starts screaming. - PLAYER_FALL_SCREAM_MINHEIGHT = FIXED(55), // The player needs to be at least 55 units from the ground before screaming. - PLAYER_FALL_HIT_SND_HEIGHT = FIXED(4), // 4.0 units, fall height for player to make a sound when hitting the ground. - PLAYER_LAND_VEL_CHANGE = FIXED(60), // Point wear landing velocity to head change velocity changes slope. - PLAYER_LAND_VEL_MAX = FIXED(1000), // Maximum head change landing velocity. - -#ifdef TFE_ESPBOX - PLAYER_FORWARD_SPEED = (256), // Forward speed in units/sec. - PLAYER_STRAFE_SPEED = (192), // Strafe speed in units/sec. -#else - PLAYER_FORWARD_SPEED = FIXED(256), // Forward speed in units/sec. - PLAYER_STRAFE_SPEED = FIXED(192), // Strafe speed in units/sec. -#endif - PLAYER_CROUCH_SPEED = 747108, // 11.4 units/sec - PLAYER_MOUSE_TURN_SPD = 8, // Mouse position delta to turn speed multiplier. -#ifdef TFE_ESPBOX - PLAYER_KB_TURN_SPD = 4915, // Keyboard turn speed in angles/sec. (0.075) -#else - PLAYER_KB_TURN_SPD = 3413, // Keyboard turn speed in angles/sec. -#endif - PLAYER_CONTROLLER_TURN_SPD = 3413*3, // Controller turn speed in angles/sec. - PLAYER_CONTROLLER_PITCH_SPD = 3413*2, // Controller turn speed in angles/sec. - PLAYER_JUMP_IMPULSE = -2850816, // Jump vertical impuse: -43.5 units/sec. - - PLAYER_MAX_MOVE_DIST = FIXED(32), - PLAYER_STOP_ACCEL = -540672, // -8.25 - PLAYER_MIN_EYE_DIST_FLOOR = FIXED(2), - PLAYER_GRAVITY_ACCEL = FIXED(150), - - HEADLAMP_ENERGY_CONSUMPTION = 0x111, // fraction of energy consumed per second = ~0.004 - GASMASK_ENERGY_CONSUMPTION = 0x444, // fraction of energy consumed per second = ~0.0167 - GOGGLES_ENERGY_CONSUMPTION = 0x444, // fraction of energy consumed per second = ~0.0167 - }; - - static const s32 c_pitchLimits[] = - { - 2047, // PITCH_VANILLA - 2730, // PITCH_VANILLA_PLUS - 3413, // PITCH_HIGH - 4050, // PITCH_MAXIMUM - }; - static s32 PITCH_LIMIT = c_pitchLimits[PITCH_VANILLA]; - - // Lower = Less sliding/stops faster, - // Higher = More sliding, takes longer to stop. - enum Friction - { - FRICTION_CLEATS = 0xf333, // 0.950 - FRICTION_DEFAULT = 0xf999, // 0.975 - FRICTION_FALLING = 0xfef9, // 0.996 - FRICTION_ICE = 0xffbe, // 0.999 - }; - - enum SpecialSpeeds - { - ICE_SPEED_MUL = 0x11eb, // 0.070 - MOVING_SURFACE_MUL = 0xcccc, // 0.8 - }; - - static const s32 c_healthDmgToFx[] = - { - 4, 8, 12, 16, 20, 24, 28, 32, - 36, 40, 44, 48, 52, 56, 60, 63, - }; - - static const s32 c_shieldDmgToFx[] = - { - 2, 4, 6, 8, 10, 12, 14, 16, - 18, 20, 22, 24, 26, 28, 30, 32 - }; - - static const s32 c_flashAmtToFx[] = - { - 1, 2, 3, 4, 5, 6, 7, 8, 9, - 10, 11, 12, 13, 14, 15, 16 - }; - - const fixed16_16 c_flashDelta = 39321 * 145; // 0.6 seconds in fixed point ticks (i.e. FIXED(0.6) * TICKS_PER_SEC) - const fixed16_16 c_damageDelta = 6553 * 145; // 0.1 - const fixed16_16 c_shieldDelta = 13107 * 145; // 0.2 - - /////////////////////////////////////////// - // Internal State - /////////////////////////////////////////// - // Player Controller - static fixed16_16 s_externalYawSpd; - static angle14_32 s_playerPitch; - static angle14_32 s_playerRoll; - static fixed16_16 s_forwardSpd; - static fixed16_16 s_strafeSpd; - static fixed16_16 s_maxMoveDist; - static fixed16_16 s_playerStopAccel; - static fixed16_16 s_minEyeDistFromFloor; - static fixed16_16 s_postLandVel; - static fixed16_16 s_landUpVel = 0; - static fixed16_16 s_playerVelX; - static fixed16_16 s_playerUpVel; - static fixed16_16 s_playerUpVel2; - static fixed16_16 s_playerVelZ; - static fixed16_16 s_externalVelX; - static fixed16_16 s_externalVelZ; - static fixed16_16 s_playerCrouchSpd; - static fixed16_16 s_playerSpeedAve; - static fixed16_16 s_prevDistFromFloor = 0; - static fixed16_16 s_wpnSin = 0; - static fixed16_16 s_wpnCos = 0; - static fixed16_16 s_moveDirX; - static fixed16_16 s_moveDirZ; - static fixed16_16 s_dist; - static fixed16_16 s_distScale; - // Misc - static s32 s_levelAtten = 0; - static s32 s_prevCollisionFrameWall; - static Safe* s_curSafe = nullptr; - // Actions - static JBool s_playerUse = JFALSE; - static JBool s_playerActionUse = JFALSE; - static JBool s_playerPrimaryFire = JFALSE; - static JBool s_playerSecFire = JFALSE; - static JBool s_playerJumping = JFALSE; - static JBool s_playerInWater = JFALSE; - static JBool s_limitStepHeight = JTRUE; - static JBool s_smallModeEnabled = JFALSE; - JBool s_aiActive = JTRUE; - // Currently playing sound effects. - static SoundEffectId s_crushSoundId = 0; - static SoundEffectId s_kyleScreamSoundId = 0; - // Position and orientation. - static vec3_fixed s_playerPos; - static fixed16_16 s_playerObjHeight; - static angle14_32 s_playerObjPitch; - static angle14_32 s_playerObjYaw; - static RSector* s_playerObjSector; - static RWall* s_playerSlideWall; - - /////////////////////////////////////////// - // Shared State - /////////////////////////////////////////// - PlayerInfo s_playerInfo = { 0 }; - PlayerLogic s_playerLogic = {}; - fixed16_16 s_batteryPower = 2 * ONE_16; - s32 s_lifeCount; - s32 s_playerLight = 0; - s32 s_headwaveVerticalOffset; - JBool s_onFloor = JTRUE; - s32 s_weaponLight = 0; - s32 s_baseAtten = 0; - fixed16_16 s_gravityAccel; - - s32 s_invincibility = 0; - JBool s_weaponFiring = JFALSE; - JBool s_weaponFiringSec = JFALSE; - JBool s_wearingCleats = JFALSE; - JBool s_wearingGasmask = JFALSE; - JBool s_nightvisionActive = JFALSE; - JBool s_headlampActive = JFALSE; - JBool s_superCharge = JFALSE; - JBool s_superChargeHud= JFALSE; - JBool s_playerSecMoved = JFALSE; - JBool s_flyMode = JFALSE; - JBool s_noclip = JFALSE; - u32* s_playerInvSaved = nullptr; - - RSector* s_playerSector = nullptr; - SecObject* s_playerObject = nullptr; - SecObject* s_playerEye = nullptr; - vec3_fixed s_eyePos = { 0 }; // s_camX, s_camY, s_camZ in the DOS code. - angle14_32 s_pitch = 0, s_yaw = 0, s_roll = 0; - u32 s_playerEyeFlags = 4; - Tick s_playerTick; - Tick s_prevPlayerTick; - Tick s_nextShieldDmgTick; - Tick s_reviveTick = 0; - Tick s_nextPainSndTick = 0; - Task* s_playerTask = nullptr; - - fixed16_16 s_playerYPos; - vec3_fixed s_camOffset = { 0 }; - angle14_32 s_camOffsetPitch = 0; - angle14_32 s_camOffsetYaw = 0; - angle14_32 s_camOffsetRoll = 0; - angle14_32 s_playerYaw; - - JBool s_itemUnknown1; // 0x282428 - JBool s_itemUnknown2; // 0x28242c - - SoundSourceId s_landSplashSound; - SoundSourceId s_landSolidSound; - SoundSourceId s_gasDamageSoundSource; - SoundSourceId s_maskSoundSource1; - SoundSourceId s_maskSoundSource2; - SoundSourceId s_invCountdownSound; - SoundSourceId s_jumpSoundSource; - SoundSourceId s_nightVisionActiveSoundSource; - SoundSourceId s_nightVisionDeactiveSoundSource; - SoundSourceId s_playerDeathSoundSource; - SoundSourceId s_crushSoundSource; - SoundSourceId s_playerHealthHitSoundSource; - SoundSourceId s_kyleScreamSoundSource; - SoundSourceId s_playerShieldHitSoundSource; - - fixed16_16 s_playerHeight; - // Speed Modifiers - s32 s_playerRun = 0; - s32 s_jumpScale = 0; - s32 s_playerSlow = 0; - s32 s_onMovingSurface = 0; - - /////////////////////////////////////////// - // Forward Declarations - /////////////////////////////////////////// - void playerControlTaskFunc(MessageType msg); - void playerControlMsgFunc(MessageType msg); - void setPlayerLight(s32 atten); - void setCameraOffset(fixed16_16 offsetX, fixed16_16 offsetY, fixed16_16 offsetZ); - void setCameraAngleOffset(angle14_32 offsetPitch, angle14_32 offsetYaw, angle14_32 offsetRoll); - void gasSectorTaskFunc(MessageType msg); - - void handlePlayerMoveControls(); - void handlePlayerPhysics(); - void handlePlayerActions(); - void handlePlayerScreenFx(); - - void tfe_showSecretFoundMsg(); - - // TFE - void player_warp(const ConsoleArgList& args); - void player_sector(const ConsoleArgList& args); - - /////////////////////////////////////////// - // API Implentation - /////////////////////////////////////////// - void player_init() - { - s_landSplashSound = sound_load("swim-in.voc", SOUND_PRIORITY_HIGH4); - s_landSolidSound = sound_load("land-1.voc", SOUND_PRIORITY_HIGH4); - s_gasDamageSoundSource = sound_load("choke.voc", SOUND_PRIORITY_MED2); - s_maskSoundSource1 = sound_load("mask1.voc", SOUND_PRIORITY_MED2); - s_maskSoundSource2 = sound_load("mask2.voc", SOUND_PRIORITY_MED2); - s_invCountdownSound = sound_load("quarter.voc", SOUND_PRIORITY_HIGH4); - s_jumpSoundSource = sound_load("jump-1.voc", SOUND_PRIORITY_HIGH4); - s_nightVisionActiveSoundSource = sound_load("goggles1.voc", SOUND_PRIORITY_MED2); - s_nightVisionDeactiveSoundSource = sound_load("goggles2.voc", SOUND_PRIORITY_MED2); - s_playerDeathSoundSource = sound_load("kyledie1.voc", SOUND_PRIORITY_HIGH5); - s_crushSoundSource = sound_load("crush.voc", SOUND_PRIORITY_HIGH4); - s_playerHealthHitSoundSource = sound_load("health1.voc", SOUND_PRIORITY_HIGH4); - s_kyleScreamSoundSource = sound_load("fall.voc", SOUND_PRIORITY_MED4); - s_playerShieldHitSoundSource = sound_load("shield1.voc", SOUND_PRIORITY_MED5); - - s_playerInfo = { 0 }; // Make sure this is clear... - s_playerInfo.ammoEnergy = pickup_addToValue(0, 100, 999); - s_playerInfo.ammoPower = pickup_addToValue(0, 100, 999); - s_playerInfo.ammoPlasma = pickup_addToValue(0, 100, 999); - s_playerInfo.shields = pickup_addToValue(0, 100, 200); - s_playerInfo.health = pickup_addToValue(0, 100, 100); - s_playerInfo.healthFract = 0; - s_batteryPower = FIXED(2); - s_reviveTick = 0; - - s_automapLocked = JTRUE; - - CCMD("warp", player_warp, 3, "Warp to the specific x, y, z position."); - CCMD_NOREPEAT("sector", player_sector, 0, "Get the current sector ID."); - - initPlayerCollision(); - } - - void player_setPitchLimit(PitchLimit limit) - { - if (limit < PITCH_VANILLA || limit > PITCH_COUNT) - { - PITCH_LIMIT = c_pitchLimits[PITCH_VANILLA]; - } - else - { - PITCH_LIMIT = c_pitchLimits[limit]; - } - s_playerPitch = clamp(s_playerPitch, -PITCH_LIMIT, PITCH_LIMIT); - } - - void player_readInfo(u8* inv, s32* ammo) - { - // Read the inventory. - s_playerInfo.itemPistol = inv[0]; - s_playerInfo.itemRifle = inv[1]; - s_itemUnknown1 = inv[2]; - s_playerInfo.itemAutogun = inv[3]; - s_playerInfo.itemMortar = inv[4]; - s_playerInfo.itemFusion = inv[5]; - s_itemUnknown2 = inv[6]; - s_playerInfo.itemConcussion= inv[7]; - s_playerInfo.itemCannon = inv[8]; - s_playerInfo.itemRedKey = inv[9]; - s_playerInfo.itemYellowKey = inv[10]; - s_playerInfo.itemBlueKey = inv[11]; - s_playerInfo.itemGoggles = inv[12]; - s_playerInfo.itemCleats = inv[13]; - s_playerInfo.itemMask = inv[14]; - s_playerInfo.itemPlans = inv[15]; - s_playerInfo.itemPhrik = inv[16]; - s_playerInfo.itemNava = inv[17]; - s_playerInfo.itemDatatape = inv[18]; - s_playerInfo.itemUnused = inv[19]; - s_playerInfo.itemDtWeapon = inv[20]; - s_playerInfo.itemCode1 = inv[21]; - s_playerInfo.itemCode2 = inv[22]; - s_playerInfo.itemCode3 = inv[23]; - s_playerInfo.itemCode4 = inv[24]; - s_playerInfo.itemCode5 = inv[25]; - s_playerInfo.itemCode6 = inv[26]; - s_playerInfo.itemCode7 = inv[27]; - s_playerInfo.itemCode8 = inv[28]; - s_playerInfo.itemCode9 = inv[29]; - - // Handle current weapon. - s32 curWeapon = inv[30]; - weapon_setNext(curWeapon); - s_playerInfo.maxWeapon = max(curWeapon, s_playerInfo.maxWeapon); - s_playerInfo.newWeapon = -1; - - // Life Count. - s_lifeCount = inv[31]; - - // Read Ammo, shields, health and energy. - s_playerInfo.ammoEnergy = ammo[0]; - s_playerInfo.ammoPower = ammo[1]; - s_playerInfo.ammoPlasma = ammo[2]; - s_playerInfo.ammoDetonator = ammo[3]; - s_playerInfo.ammoShell = ammo[4]; - s_playerInfo.ammoMine = ammo[5]; - s_playerInfo.ammoMissile = ammo[6]; - s_playerInfo.shields = ammo[7]; - s_playerInfo.health = ammo[8]; - s_batteryPower = ammo[9]; - } - - void player_writeInfo(u8* inv, s32* ammo) - { - // Write the inventory. - inv[0] = s_playerInfo.itemPistol; - inv[1] = s_playerInfo.itemRifle; - inv[2] = s_itemUnknown1; - inv[3] = s_playerInfo.itemAutogun; - inv[4] = s_playerInfo.itemMortar; - inv[5] = s_playerInfo.itemFusion; - inv[6] = s_itemUnknown2; - inv[7] = s_playerInfo.itemConcussion; - inv[8] = s_playerInfo.itemCannon; - inv[9] = s_playerInfo.itemRedKey; - inv[10] = s_playerInfo.itemYellowKey; - inv[11] = s_playerInfo.itemBlueKey; - inv[12] = s_playerInfo.itemGoggles; - inv[13] = s_playerInfo.itemCleats; - inv[14] = s_playerInfo.itemMask; - inv[15] = s_playerInfo.itemPlans; - inv[16] = s_playerInfo.itemPhrik; - inv[17] = s_playerInfo.itemNava; - inv[18] = s_playerInfo.itemDatatape; - inv[19] = s_playerInfo.itemUnused; - inv[20] = s_playerInfo.itemDtWeapon; - inv[21] = s_playerInfo.itemCode1; - inv[22] = s_playerInfo.itemCode2; - inv[23] = s_playerInfo.itemCode3; - inv[24] = s_playerInfo.itemCode4; - inv[25] = s_playerInfo.itemCode5; - inv[26] = s_playerInfo.itemCode6; - inv[27] = s_playerInfo.itemCode7; - inv[28] = s_playerInfo.itemCode8; - inv[29] = s_playerInfo.itemCode9; - inv[30] = s_playerInfo.curWeapon; - inv[31] = s_lifeCount; - - // Write Ammo, Shields, Health, and Energy. - ammo[0] = s_playerInfo.ammoEnergy; - ammo[1] = s_playerInfo.ammoPower; - ammo[2] = s_playerInfo.ammoPlasma; - ammo[3] = s_playerInfo.ammoDetonator; - ammo[4] = s_playerInfo.ammoShell; - ammo[5] = s_playerInfo.ammoMine; - ammo[6] = s_playerInfo.ammoMissile; - ammo[7] = s_playerInfo.shields; - ammo[8] = s_playerInfo.health; - ammo[9] = s_batteryPower; - } - - void player_setNextWeapon(s32 nextWpn) - { - weapon_setNext(nextWpn); - if (nextWpn > s_playerInfo.maxWeapon) - { - s_playerInfo.maxWeapon = nextWpn; - } - } - - void player_createController(JBool clearData) - { - s_playerTask = createTask("player control", playerControlTaskFunc, JFALSE, playerControlMsgFunc); - task_setNextTick(s_playerTask, TASK_SLEEP); - if (!clearData) { return; } - - // Clear out inventory items that the player shouldn't start a level with, such as objectives and keys - s_playerInfo.itemPlans = JFALSE; - s_playerInfo.itemPhrik = JFALSE; - s_playerInfo.itemNava = JFALSE; - s_playerInfo.itemDatatape = JFALSE; - s_playerInfo.itemUnused = JFALSE; - s_playerInfo.itemDtWeapon = JFALSE; - s_playerInfo.itemCode1 = JFALSE; - s_playerInfo.itemCode2 = JFALSE; - s_playerInfo.itemCode3 = JFALSE; - s_playerInfo.itemCode4 = JFALSE; - s_playerInfo.itemCode5 = JFALSE; - s_playerInfo.itemCode6 = JFALSE; - s_playerInfo.itemCode7 = JFALSE; - s_playerInfo.itemCode8 = JFALSE; - s_playerInfo.itemCode9 = JFALSE; - s_playerInfo.itemRedKey = JFALSE; - s_playerInfo.itemYellowKey= JFALSE; - s_playerInfo.itemBlueKey = JFALSE; - - // Clear out any lingering damage or flash effects. - s_healthDamageFx = 0; - s_shieldDamageFx = 0; - s_flashEffect = 0; - - s_playerDying = 0; - s_externalYawSpd = 0; - s_playerPitch = 0; - s_playerRoll = 0; - s_forwardSpd = 0; - s_strafeSpd = 0; - - // Set constants. - s_maxMoveDist = PLAYER_MAX_MOVE_DIST; - s_playerStopAccel = PLAYER_STOP_ACCEL; - s_minEyeDistFromFloor = PLAYER_MIN_EYE_DIST_FLOOR; - s_gravityAccel = PLAYER_GRAVITY_ACCEL; - - // Initialize values. - s_postLandVel = 0; - s_playerRun = 0; - s_jumpScale = 0; - s_playerSlow = 0; - s_onMovingSurface = 0; - s_reviveTick = 0; - - s_playerVelX = 0; - s_playerUpVel = 0; - s_playerUpVel2 = 0; - s_playerVelZ = 0; - s_externalVelX = 0; - s_externalVelZ = 0; - s_playerCrouchSpd = 0; - s_playerSpeedAve = 0; - - s_weaponLight = 0; - s_levelAtten = 0; - s_prevPlayerTick = 0; - s_headwaveVerticalOffset = 0; - - s_playerUse = JFALSE; - s_playerActionUse = JFALSE; - s_weaponFiring = JFALSE; - s_weaponFiringSec = JFALSE; - s_playerPrimaryFire = JFALSE; - s_playerSecFire = JFALSE; - s_playerJumping = JFALSE; - - s_crushSoundId = 0; - s_kyleScreamSoundId = 0; - - s_curSafe = nullptr; - // The player will always start a level with at least 3 lives. - s_lifeCount = max(3, s_lifeCount); - - s_playerInvSaved = nullptr; - s_invincibilityTask = nullptr; - s_gasmaskTask = nullptr; - s_gasSectorTask = nullptr; - s_nextShieldDmgTick = 0; - s_invincibility = 0; - s_flyMode = JFALSE; - s_noclip = JFALSE; - - // The player will always start a level with at least 100 shields, though if they have more it carries over. - s_playerInfo.shields = max(100, s_playerInfo.shields); - // The player starts a new level with full health and energy. - s_playerInfo.health = 100; - s_playerInfo.healthFract = 0; - s_batteryPower = FIXED(2); - - s_wearingGasmask = JFALSE; - s_wearingCleats = JFALSE; - s_nightvisionActive = JFALSE; - s_headlampActive = JFALSE; - - // Handle level-specific hacks. - const char* levelName = agent_getLevelName(); - TFE_System::logWrite(LOG_MSG, "Player", "Setting up level '%s'", levelName); - if (!strcasecmp(levelName, "jabship")) - { - u8* src = (u8*)&s_playerInfo; - size_t size = (size_t)&s_playerInfo.pileSaveMarker - (size_t)&s_playerInfo; - assert(size == 140); - s_playerInvSaved = nullptr; // This should already be null, but... - if (!s_playerInvSaved) - { - u8* dst = (u8*)level_alloc(size); - if (!dst) - { - TFE_System::logWrite(LOG_ERROR, "Player", "Cannot allocate player inventory space - %u bytes.", size); - dst = (u8*)level_alloc(140); - } - - s_playerInvSaved = (u32*)dst; - memcpy(dst, src, size); - memset(src, 0, size); - - TFE_System::logWrite(LOG_MSG, "Player", "Player Inventory copied, size = %u", size); - - player_setNextWeapon(0); - disableMask(); - disableCleats(); - disableNightvision(); - hud_clearMessage(); - } - } - else if (!strcasecmp(levelName, "gromas")) - { - // Adjust the lighting on gromas in order to accenuate the fog effect. - s_levelAtten = 30; - } - } - - void player_clearEyeObject() - { - s_playerEye = nullptr; - } - - void playerLogicCleanupFunc(Logic* logic) - { - // TODO(Core Game Loop Release) - } - - void player_getVelocity(vec3_fixed* vel) - { - vel->x = s_playerVelX; - vel->y = s_playerUpVel; - vel->z = s_playerVelZ; - } - - fixed16_16 player_getSquaredDistance(SecObject* obj) - { - fixed16_16 dx = obj->posWS.x - s_playerObject->posWS.x; - fixed16_16 dy = obj->posWS.y - s_playerObject->posWS.y; - fixed16_16 dz = obj->posWS.z - s_playerObject->posWS.z; - - // distSq overflows if dist > 181 units. - return mul16(dx, dx) + mul16(dy, dy) + mul16(dz, dz); - } - - void player_setupObject(SecObject* obj) - { - s_playerObject = obj; - obj_addLogic(obj, (Logic*)&s_playerLogic, LOGIC_PLAYER, s_playerTask, playerLogicCleanupFunc); - - s_playerObject->entityFlags|= ETFLAG_PLAYER; - s_playerObject->flags |= OBJ_FLAG_MOVABLE; - s_playerObject->worldHeight = PLAYER_HEIGHT; - s_playerObject->worldWidth = PLAYER_WIDTH; - - s_playerYaw = s_playerObject->yaw; - s_playerPitch = 0; - s_playerRoll = 0; - - s_playerYPos = s_playerObject->posWS.y; - s_playerLogic.stepHeight = PLAYER_STEP; - - task_makeActive(s_playerTask); - - weapon_setNext(s_playerInfo.curWeapon); - s_playerInfo.maxWeapon = max(s_playerInfo.curWeapon, s_playerInfo.maxWeapon); - - s_playerSecMoved = JFALSE; - s_playerSector = obj->sector; - } - - void player_setupEyeObject(SecObject* obj) - { - if (s_playerEye) - { - s_playerEye->flags &= ~OBJ_FLAG_EYE; - s_playerEye->flags |= s_playerEyeFlags; - } - s_playerEye = obj; - player_setupCamera(); - - s_playerEye->flags |= OBJ_FLAG_EYE; - s_playerEyeFlags = s_playerEye->flags & 4; - s_playerEye->flags &= ~4; - - s_eyePos.x = s_playerEye->posWS.x; - s_eyePos.y = s_playerEye->posWS.y; - s_eyePos.z = s_playerEye->posWS.z; - - s_pitch = s_playerEye->pitch; - s_yaw = s_playerEye->yaw; - s_roll = s_playerEye->roll; - - setCameraOffset(0, 0, 0); - setCameraAngleOffset(0, 0, 0); - } - - void player_revive() - { - // player_revive() is called when the player respawns, which is why it sets 100 for shields here. - // In the case of picking up the item, the value is then set to 200 after the function call. - s_playerInfo.shields = 100; - s_playerInfo.health = 100; - s_playerInfo.healthFract = 0; - s_playerDying = 0; - } - - s32 player_getLifeCount() - { - return s_lifeCount; - } - - void setCameraOffset(fixed16_16 offsetX, fixed16_16 offsetY, fixed16_16 offsetZ) - { - s_camOffset = { offsetX, offsetY, offsetZ }; - } - - void setCameraAngleOffset(angle14_32 offsetPitch, angle14_32 offsetYaw, angle14_32 offsetRoll) - { - s_camOffsetPitch = offsetPitch; - s_camOffsetYaw = offsetYaw; - s_camOffsetRoll = offsetRoll; - } - - void giveAllWeaponsAndHealth() - { - s_playerInfo.health = 100; - s_playerInfo.healthFract = 0; - s_playerDying = 0; - s_playerInfo.shields = 200; - - s_playerInfo.itemPistol = JTRUE; - s_playerInfo.itemRifle = JTRUE; - // s_282428 = JTRUE; - s_playerInfo.itemAutogun = JTRUE; - s_playerInfo.itemMortar = JTRUE; - s_playerInfo.itemFusion = JTRUE; - // s_28242c = JTRUE; - s_playerInfo.itemConcussion = JTRUE; - s_playerInfo.itemCannon = JTRUE; - s_playerInfo.itemGoggles = JTRUE; - s_playerInfo.itemCleats = JTRUE; - s_playerInfo.itemMask = JTRUE; - - s_playerInfo.ammoEnergy = 500; - s_playerInfo.ammoPower = 500; - s_playerInfo.ammoDetonator = 50; - s_playerInfo.ammoShell = 50; - s_playerInfo.ammoPlasma = 400; - s_playerInfo.ammoMine = 30; - s_playerInfo.ammoMissile = 20; - - s_batteryPower = FIXED(2); - weapon_fixupAnim(); - } - - void giveHealthAndFullAmmo() - { - s_playerInfo.health = 100; - s_playerInfo.healthFract = 0; - s_playerDying = 0; - s_playerInfo.shields = 200; - s_playerInfo.ammoEnergy = 500; - - if (s_playerInfo.itemAutogun || s_playerInfo.itemFusion || s_playerInfo.itemConcussion) - { - s_playerInfo.ammoPower = 500; - } - if (s_playerInfo.itemCannon) - { - s_playerInfo.ammoPlasma = 400; - } - s_playerInfo.ammoDetonator = 50; - if (s_playerInfo.itemMortar) - { - s_playerInfo.ammoShell = 50; - } - s_playerInfo.ammoMine = 30; - if (s_playerInfo.itemCannon) - { - s_playerInfo.ammoMissile = 20; - } - s_batteryPower = FIXED(2); - weapon_fixupAnim(); - } - - void giveAllInventoryAndHealth() - { - s_playerInfo.health = 100; - s_playerInfo.healthFract = 0; - s_playerDying = 0; - s_playerInfo.shields = 200; - s_playerInfo.itemPistol = JTRUE; - s_playerInfo.itemRifle = JTRUE; - // s_282428 = JTRUE; - s_playerInfo.itemAutogun = JTRUE; - s_playerInfo.itemMortar = JTRUE; - s_playerInfo.itemFusion = JTRUE; - // s_28242c = JTRUE; - s_playerInfo.itemConcussion = JTRUE; - s_playerInfo.itemCannon = JTRUE; - s_playerInfo.itemRedKey = JTRUE; - s_playerInfo.itemYellowKey = JTRUE; - s_playerInfo.itemBlueKey = JTRUE; - s_playerInfo.itemGoggles = JTRUE; - s_playerInfo.itemCleats = JTRUE; - s_playerInfo.itemMask = JTRUE; - s_playerInfo.itemPlans = JTRUE; - s_playerInfo.itemPhrik = JTRUE; - s_playerInfo.itemNava = JTRUE; - s_playerInfo.itemDatatape = JTRUE; - s_playerInfo.itemUnused = JTRUE; - s_playerInfo.itemDtWeapon = JTRUE; - s_playerInfo.itemCode1 = JTRUE; - s_playerInfo.itemCode2 = JTRUE; - s_playerInfo.itemCode3 = JTRUE; - s_playerInfo.itemCode4 = JTRUE; - s_playerInfo.itemCode5 = JTRUE; - s_playerInfo.itemCode6 = JTRUE; - s_playerInfo.itemCode7 = JTRUE; - s_playerInfo.itemCode8 = JTRUE; - s_playerInfo.itemCode9 = JTRUE; - s_playerInfo.ammoEnergy = 500; - s_playerInfo.ammoPower = 500; - s_playerInfo.ammoDetonator = 50; - s_playerInfo.ammoShell = 50; - s_playerInfo.ammoMissile = 20; - s_playerInfo.ammoPlasma = 400; - s_playerInfo.ammoMine = 30; - s_batteryPower = FIXED(2); - - weapon_fixupAnim(); - } - - void giveKeys() - { - s_playerInfo.itemRedKey = JTRUE; - s_playerInfo.itemYellowKey = JTRUE; - s_playerInfo.itemBlueKey = JTRUE; - s_playerInfo.itemGoggles = JTRUE; - s_playerInfo.itemCleats = JTRUE; - s_playerInfo.itemMask = JTRUE; - s_playerInfo.itemPlans = JTRUE; - s_playerInfo.itemPhrik = JTRUE; - s_playerInfo.itemNava = JTRUE; - s_playerInfo.itemDatatape = JTRUE; - s_playerInfo.itemUnused = JTRUE; - s_playerInfo.itemDtWeapon = JTRUE; - s_playerInfo.itemCode1 = JTRUE; - s_playerInfo.itemCode2 = JTRUE; - s_playerInfo.itemCode3 = JTRUE; - s_playerInfo.itemCode4 = JTRUE; - s_playerInfo.itemCode5 = JTRUE; - s_playerInfo.itemCode6 = JTRUE; - s_playerInfo.itemCode7 = JTRUE; - s_playerInfo.itemCode8 = JTRUE; - s_playerInfo.itemCode9 = JTRUE; - } - - void cheat_teleport() - { - RSector* sector = sector_which3D_Map(s_mapX0, s_mapZ0, s_mapLayer); - if (sector) - { - s_playerEye->posWS.x = s_mapX0; - s_playerEye->posWS.z = s_mapZ0; - s_playerEye->posWS.y = sector->floorHeight; - s_playerObject->posWS = s_playerEye->posWS; - s_playerPos = s_playerEye->posWS; - s_playerYPos = sector->floorHeight; - - // Reset gravity. - s_playerUpVel2 = 0; - s_playerUpVel = 0; - - sector_addObject(sector, s_playerEye); - s_playerSector = sector; - - player_setupEyeObject(s_playerEye); - player_setupCamera(); - } - } - - void cheat_enableNoheightCheck() - { - s_limitStepHeight = ~s_limitStepHeight; - hud_sendTextMessage(700); - } - - void cheat_bugMode() - { - s_smallModeEnabled = ~s_smallModeEnabled; - hud_sendTextMessage(705); - } - - void cheat_pauseAI() - { - s_aiActive = ~s_aiActive; - hud_sendTextMessage(706); - } - - void cheat_postal() - { - giveAllWeaponsAndHealth(); - hud_sendTextMessage(703); - } - - void cheat_fullAmmo() - { - giveHealthAndFullAmmo(); - hud_sendTextMessage(708); - } - - void cheat_unlock() - { - giveKeys(); - hud_sendTextMessage(709); - } - - void cheat_maxout() - { - giveAllInventoryAndHealth(); - hud_sendTextMessage(710); - } - - void cheat_godMode() - { - if (!s_invincibility) - { - s_invincibility = -2; - } - else - { - s_invincibility = 0; - } - hud_sendTextMessage(702); - } - - // New TFE Cheats. - void cheat_fly() - { - // Write the cheat message. - const char* msg = TFE_System::getMessage(TFE_MSG_FLYMODE); - if (msg) { hud_sendTextMessage(msg, 1); } - - s_flyMode = ~s_flyMode; - } - - void cheat_noclip() - { - // Write the cheat message. - const char* msg = TFE_System::getMessage(TFE_MSG_NOCLIP); - if (msg) { hud_sendTextMessage(msg, 1); } - - s_noclip = ~s_noclip; - } - - void cheat_tester() - { - // Write the cheat message. - const char* msg = TFE_System::getMessage(TFE_MSG_TESTER); - if (msg) { hud_sendTextMessage(msg, 1); } - - if (s_noclip) - { - if (s_invincibility == -2) { s_invincibility = 0; } - s_aiActive = JTRUE; - s_noclip = JFALSE; - s_flyMode = JFALSE; - } - else - { - s_invincibility = -2; - s_aiActive = JFALSE; - s_noclip = JTRUE; - s_flyMode = JTRUE; - } - } - - void player_setupCamera() - { - if (s_playerEye) - { - s_eyePos.x = s_playerEye->posWS.x + s_camOffset.x; - s_eyePos.y = s_playerEye->posWS.y + s_camOffset.y - s_playerEye->worldHeight; - s_eyePos.z = s_playerEye->posWS.z + s_camOffset.z; - - s_pitch = s_playerEye->pitch + s_camOffsetPitch; - s_yaw = s_playerEye->yaw + s_camOffsetYaw; - s_roll = s_playerEye->roll + s_camOffsetRoll; - - if (s_playerEye->sector) - { - renderer_computeCameraTransform(s_playerEye->sector, s_pitch, s_yaw, s_eyePos.x, s_eyePos.y, s_eyePos.z); - } - renderer_setWorldAmbient(s_playerLight); - } - } - - void computeDamagePushVelocity(ProjectileLogic* proj, vec3_fixed* vel) - { - fixed16_16 push = mul16(proj->projForce, proj->speed); - vel->x = mul16(push, proj->dir.x); - vel->z = mul16(push, proj->dir.z); - - if (proj->dir.y < 0) - { - vel->y = mul16(push, proj->dir.y) * 2; - } - else - { - vel->y = 0; - } - } - - void computeExplosionPushDir(vec3_fixed* pos, vec3_fixed* pushDir) - { - vec3_fixed delta = { pos->x - s_explodePos.x, pos->y - s_explodePos.y, pos->z - s_explodePos.z }; - - fixed16_16 dirZ, dirX; - fixed16_16 len = computeDirAndLength(delta.x, delta.z, &dirX, &dirZ); - - fixed16_16 dirY; - computeDirAndLength(len, delta.y, &dirY, &pushDir->y); - pushDir->x = mul16(dirY, dirX); - pushDir->z = mul16(dirY, dirZ); - } - - void playerControlMsgFunc(MessageType msg) - { - fixed16_16 shieldDmg = 0; - JBool playHitSound = JFALSE; - - if (msg == MSG_DAMAGE) - { - ProjectileLogic* proj = (ProjectileLogic*)s_msgEntity; - vec3_fixed pushVel; - computeDamagePushVelocity(proj, &pushVel); - - s_playerVelX += pushVel.x; - s_playerUpVel2 += pushVel.y; - s_playerVelZ += pushVel.z; - - if (s_invincibility || s_config.superShield) - { - // TODO - - // Return because no damage is applied. - return; - } - else - { - playHitSound = JTRUE; - shieldDmg = proj->dmg; - } - } - else if (msg == MSG_EXPLOSION) - { - vec3_fixed pos = { s_playerObject->posWS.x, s_playerObject->posWS.y - s_playerObject->worldHeight, s_playerObject->posWS.z }; - vec3_fixed pushDir; - computeExplosionPushDir(&pos, &pushDir); - - fixed16_16 force = s_msgArg2; - s_playerVelX += mul16(force, pushDir.x); - s_playerUpVel2 += mul16(force, pushDir.y); - s_playerVelZ += mul16(force, pushDir.z); - - if (s_invincibility || s_config.superShield) - { - // Return because no damage is applied. - return; - } - - playHitSound = JTRUE; - if (s_curEffectData->type == HEFFECT_THERMDET_EXP) - { - shieldDmg = s_msgArg1 >> 1; - } - else - { - shieldDmg = s_msgArg1; - } - } - - player_applyDamage(0, shieldDmg, playHitSound); - } - - void player_reset() - { - s_externalYawSpd = 0; - s_playerPitch = 0; - s_playerRoll = 0; - s_forwardSpd = 0; - s_strafeSpd = 0; - s_maxMoveDist = FIXED(2); - // s_282344 = 34; - s_minEyeDistFromFloor = FIXED(2); - s_postLandVel = 0; - s_landUpVel = 0; - s_playerVelX = 0; - s_playerUpVel = 0; - s_playerUpVel2 = 0; - s_playerVelZ = 0; - s_externalVelX = 0; - // s_282380 = 0; - s_externalVelZ = 0; - s_playerSpeedAve = 0; - s_weaponLight = 0; - s_headwaveVerticalOffset = 0; - s_playerUse = JFALSE; - s_playerActionUse = JFALSE; - s_onFloor = JFALSE; - - s_playerStopAccel = -540672; // -8.25 - s_playerCrouchSpd = 0; - s_prevDistFromFloor = 0; - s_playerObject->worldHeight = 0x5cccc; // 5.8 - } - - void player_changeSector(RSector* newSector) - { - if (!newSector) { return; } - - RSector* prevSector = s_playerObject->sector; - if (newSector != prevSector) - { - if (newSector->layer != prevSector->layer) - { - automap_setLayer(newSector->layer); - } - sector_addObject(newSector, s_playerObject); - } - } - - void player_clearSuperCharge() - { - if (s_superchargeTask) - { - task_free(s_superchargeTask); - } - s_superCharge = JFALSE; - s_superChargeHud = JFALSE; - s_superchargeTask = nullptr; - weapon_setFireRate(); - } - - void handlePlayerDying() - { - s_minEyeDistFromFloor = ONE_16; - s_playerCrouchSpd = 0x5b332; // 5.7 - s_playerPitch += mul16(0x6aa, s_deltaTime); - s_playerRoll -= mul16(0xd55, s_deltaTime); - - s_playerPitch = clamp(s_playerPitch, -1023, 1023); - s_playerRoll = clamp(s_playerRoll, -1592, 1592); - - s_playerSecFire = JFALSE; - s_playerPrimaryFire = JFALSE; - - if (inputMapping_getActionState(IADF_JUMP) || inputMapping_getActionState(IADF_MENU_TOGGLE) || inputMapping_getActionState(IADF_USE)) - { - inputMapping_removeState(IADF_JUMP); - inputMapping_removeState(IADF_MENU_TOGGLE); - inputMapping_removeState(IADF_USE); - - if (s_lifeCount != 0 && s_curSafe) - { - s_lifeCount -= 1; - player_revive(); - player_reset(); - s_headlampActive = JFALSE; - s_nightvisionActive = JFALSE; - disableNightvisionInternal(); - - s_playerObject->yaw = s_curSafe->yaw; - s_playerYaw = s_curSafe->yaw; - s_playerObject->posWS.x = s_curSafe->x; - s_playerObject->posWS.z = s_curSafe->z; - - RSector* sector = s_curSafe->sector; - fixed16_16 floorHeight = sector->floorHeight + sector->secHeight; - s_playerObject->posWS.y = floorHeight; - s_playerYPos = s_playerObject->posWS.y; - player_changeSector(sector); - - s_nextShieldDmgTick = s_curTick + 436; - if (s_invincibilityTask) - { - task_free(s_invincibilityTask); - } - s_invincibilityTask = nullptr; - s_invincibility = 0; - s_flyMode = JFALSE; - s_noclip = JFALSE; - player_clearSuperCharge(); - } - else - { - player_revive(); - player_reset(); - s_levelComplete = JFALSE; - mission_exitLevel(); - } - } - } - - void playerControlTaskFunc(MessageType msg) - { - task_begin; - if (!s_curSafe) - { - s_curSafe = level_getSafeFromSector(s_playerObject->sector); - } - - s_playerPos.x = s_playerObject->posWS.x; - s_playerPos.y = s_playerObject->posWS.y; - s_playerPos.z = s_playerObject->posWS.z; - s_playerObjHeight = s_playerObject->worldHeight; - s_playerObjPitch = s_playerObject->pitch; - s_playerObjYaw = s_playerObject->yaw; - s_playerObjSector = s_playerObject->sector; - s_playerTick = s_curTick; - s_prevPlayerTick = s_curTick; - - while (msg != MSG_FREE_TASK) - { - if (msg == MSG_RUN_TASK) - { - if (!s_gamePaused) - { - // TFE: Add pitch limit setting. - // Note that if running with the software renderer, it is always forced to the vanilla limit. - if (TFE_Jedi::getSubRenderer() == TFE_SubRenderer::TSR_CLASSIC_GPU) - { - TFE_Settings_Game* gameSettings = TFE_Settings::getGameSettings(); - player_setPitchLimit(gameSettings->df_pitchLimit); - } - else - { - player_setPitchLimit(PITCH_VANILLA); - } - - handlePlayerMoveControls(); - handlePlayerPhysics(); - handlePlayerActions(); - handlePlayerScreenFx(); - if (s_playerDying) - { - handlePlayerDying(); - } - } - } - - s_prevPlayerTick = s_playerTick; - task_yield(TASK_NO_DELAY); - } - task_end; - } - - /////////////////////////////////////////// - // Internal Implentation - /////////////////////////////////////////// - void setPlayerLight(s32 atten) - { - s_playerLight = atten; - } - - void handlePlayerMoveControls() - { - TFE_Settings_Game* settings = TFE_Settings::getGameSettings(); - - s_externalYawSpd = 0; - s_forwardSpd = 0; - s_strafeSpd = 0; - s_playerRun = 0; - s_jumpScale = 0; - s_playerSlow = 0; - - if (s_playerDying) - { - return; - } - - s_playerCrouchSpd = s_playerStopAccel; - - s32 mdx, mdy; - TFE_Input::getAccumulatedMouseMove(&mdx, &mdy); - InputConfig* inputConfig = TFE_Input::inputMapping_get(); - - // Yaw change - if (inputConfig->mouseMode == MMODE_TURN || inputConfig->mouseMode == MMODE_LOOK) - { - s_playerYaw += s32(f32(mdx * PLAYER_MOUSE_TURN_SPD) * inputMapping_getHorzMouseSensitivity()); - s_playerYaw &= ANGLE_MASK; - } - // Pitch change - if (inputConfig->mouseMode == MMODE_LOOK) - { - f32 pitchDelta = f32(mdy * PLAYER_MOUSE_TURN_SPD) * inputMapping_getVertMouseSensitivity(); - // Counteract the tan() call later in the delta in order to make the movement perceptually linear. -#ifndef TFE_ESPBOX - pitchDelta = atanf(pitchDelta/2047.0f * PI) / PI * 2047.0f; -#endif - s_playerPitch = clamp(s_playerPitch - s32(pitchDelta), -PITCH_LIMIT, PITCH_LIMIT); - } - - // Controls - if (s_automapLocked) - { - if (inputMapping_getActionState(IADF_FORWARD)) - { -#ifdef TFE_ESPBOX - fixed16_16 speed = PLAYER_FORWARD_SPEED * s_deltaTime; -#else - fixed16_16 speed = mul16(PLAYER_FORWARD_SPEED, s_deltaTime); -#endif - s_forwardSpd = max(speed, s_forwardSpd); - } - else if (inputMapping_getActionState(IADF_BACKWARD)) - { -#ifdef TFE_ESPBOX - fixed16_16 speed = -(PLAYER_FORWARD_SPEED * s_deltaTime); -#else - fixed16_16 speed = -mul16(PLAYER_FORWARD_SPEED, s_deltaTime); -#endif - s_forwardSpd = min(speed, s_forwardSpd); - } - else if (inputMapping_getAnalogAxis(AA_MOVE)) - { -#ifdef TFE_ESPBOX - // TODO calculate in floating point - fixed16_16 speed = mul16((PLAYER_FORWARD_SPEED * s_deltaTime), floatToFixed16(clamp(inputMapping_getAnalogAxis(AA_MOVE), -1.0f, 1.0f))); -#else - fixed16_16 speed = mul16(mul16(PLAYER_FORWARD_SPEED, s_deltaTime), floatToFixed16(clamp(inputMapping_getAnalogAxis(AA_MOVE), -1.0f, 1.0f))); -#endif - if (speed < 0) - { - s_forwardSpd = min(speed, s_forwardSpd); - } - else - { - s_forwardSpd = max(speed, s_forwardSpd); - } - } - } - - if (settings->df_autorun) // TFE: Optional feature. - { - s_playerRun = 1; - if (inputMapping_getActionState(IADF_RUN)) - { - s_playerRun = 0; - } - else if (inputMapping_getActionState(IADF_SLOW)) - { - s_playerSlow |= 1; - s_playerRun = 0; - } - } - else // Normal vanilla behavior. - { - if (inputMapping_getActionState(IADF_RUN)) - { - s_playerRun |= 1; - } - else if (inputMapping_getActionState(IADF_SLOW)) - { - s_playerSlow |= 1; - } - } - - s32 crouch = inputMapping_getActionState(IADF_CROUCH) ? 1 : 0; - if (s_flyMode) - { - if ((!s_onFloor || s_noclip) && crouch) - { - fixed16_16 speed = -(PLAYER_JUMP_IMPULSE << s_jumpScale); - s_playerUpVel = speed; - s_playerUpVel2 = speed; - } - else if (s_playerUpVel > 0) - { - s_playerUpVel = 0; - s_playerUpVel2 = 0; - } - s_playerCrouchSpd = 0; - } - - if (s_onFloor & crouch) - { - fixed16_16 speed = PLAYER_CROUCH_SPEED; - speed <<= s_playerRun; // this will be '1' if running. - speed >>= s_playerSlow; // this will be '1' if moving slowly. - s_playerCrouchSpd = speed; - } - - JBool wasJumping = s_playerJumping; - s_playerJumping = JFALSE; - if (inputMapping_getActionState(IADF_JUMP)) - { - if (!s_onFloor || wasJumping) - { - s_playerJumping = wasJumping; - if (s_flyMode) - { - fixed16_16 speed = PLAYER_JUMP_IMPULSE << s_jumpScale; - s_playerUpVel = speed; - s_playerUpVel2 = speed; - } - } - else - { - sound_play(s_jumpSoundSource); - - fixed16_16 speed = PLAYER_JUMP_IMPULSE << s_jumpScale; - s_playerJumping = JTRUE; - s_playerUpVel = speed; - s_playerUpVel2 = speed; - } - } - else if (s_flyMode && s_playerUpVel < 0) - { - s_playerUpVel = 0; - s_playerUpVel2 = 0; - } - - ////////////////////////////////////////// - // Pitch and Roll controls. - ////////////////////////////////////////// - if (s_automapLocked) - { - if (inputMapping_getActionState(IADF_TURN_LT)) - { - fixed16_16 turnSpeed = PLAYER_KB_TURN_SPD; // angle units per second. - fixed16_16 dYaw = mul16(turnSpeed, s_deltaTime); - dYaw <<= s_playerRun; // double for "run" - dYaw >>= s_playerSlow; // half for "slow" - - s_playerYaw -= dYaw; - s_playerYaw &= ANGLE_MASK; - } - else if (inputMapping_getActionState(IADF_TURN_RT)) - { - fixed16_16 turnSpeed = PLAYER_KB_TURN_SPD; // angle units per second. - fixed16_16 dYaw = mul16(turnSpeed, s_deltaTime); - dYaw <<= s_playerRun; // double for "run" - dYaw >>= s_playerSlow; // half for "slow" - - s_playerYaw += dYaw; - s_playerYaw &= ANGLE_MASK; - } - else if (inputMapping_getAnalogAxis(AA_LOOK_HORZ)) - { - // TODO calculate in floating point - fixed16_16 turnSpeed = mul16(mul16(PLAYER_CONTROLLER_TURN_SPD, s_deltaTime), floatToFixed16(inputMapping_getAnalogAxis(AA_LOOK_HORZ))); - s_playerYaw += turnSpeed; - s_playerYaw &= ANGLE_MASK; - } - - if (inputMapping_getActionState(IADF_LOOK_UP)) - { - fixed16_16 turnSpeed = PLAYER_KB_TURN_SPD; // angle units per second. - fixed16_16 dPitch = mul16(turnSpeed, s_deltaTime); - dPitch <<= s_playerRun; // double for "run" - dPitch >>= s_playerSlow; // half for "slow" - s_playerPitch = clamp(s_playerPitch + dPitch, -PITCH_LIMIT, PITCH_LIMIT); - } - else if (inputMapping_getActionState(IADF_LOOK_DN)) - { - fixed16_16 turnSpeed = PLAYER_KB_TURN_SPD; // angle units per second. - fixed16_16 dPitch = mul16(turnSpeed, s_deltaTime); - dPitch <<= s_playerRun; // double for "run" - dPitch >>= s_playerSlow; // half for "slow" - s_playerPitch = clamp(s_playerPitch - dPitch, -PITCH_LIMIT, PITCH_LIMIT); - } - else if (inputMapping_getAnalogAxis(AA_LOOK_VERT)) - { - // TODO calculate in floating point - fixed16_16 turnSpeed = mul16(mul16(PLAYER_CONTROLLER_PITCH_SPD, s_deltaTime), floatToFixed16(inputMapping_getAnalogAxis(AA_LOOK_VERT))); - // Counteract the tan() call later in the delta in order to make the movement perceptually linear. -#ifndef TFE_ESPBOX - turnSpeed = (fixed16_16)floatToFixed16(atanf((f32)fixed16ToFloat(turnSpeed) / 2047.0f * PI) / PI * 2047.0f); -#endif - - s_playerPitch = clamp(s_playerPitch + turnSpeed, -PITCH_LIMIT, PITCH_LIMIT); - } - - if (inputMapping_getActionState(IADF_CENTER_VIEW)) - { - s_playerPitch = 0; - s_playerRoll = 0; - } - - if (inputMapping_getActionState(IADF_STRAFE_RT)) - { -#ifdef TFE_ESPBOX - fixed16_16 speed = PLAYER_STRAFE_SPEED * s_deltaTime; -#else - fixed16_16 speed = mul16(PLAYER_STRAFE_SPEED, s_deltaTime); -#endif - s_strafeSpd = max(speed, s_strafeSpd); - } - else if (inputMapping_getActionState(IADF_STRAFE_LT)) - { -#ifdef TFE_ESPBOX - fixed16_16 speed = -(PLAYER_STRAFE_SPEED * s_deltaTime); -#else - fixed16_16 speed = -mul16(PLAYER_STRAFE_SPEED, s_deltaTime); -#endif - s_strafeSpd = min(speed, s_strafeSpd); - } - else if (inputMapping_getAnalogAxis(AA_STRAFE)) - { -#ifdef TFE_ESPBOX - // TODO calculate in floating point - fixed16_16 speed = mul16((PLAYER_STRAFE_SPEED * s_deltaTime), floatToFixed16(clamp(inputMapping_getAnalogAxis(AA_STRAFE), -1.0f, 1.0f))); -#else - fixed16_16 speed = mul16(mul16(PLAYER_STRAFE_SPEED, s_deltaTime), floatToFixed16(clamp(inputMapping_getAnalogAxis(AA_STRAFE), -1.0f, 1.0f))); -#endif - if (speed < 0) - { - s_strafeSpd = min(speed, s_strafeSpd); - } - else - { - s_strafeSpd = max(speed, s_strafeSpd); - } - } - } - - if (inputMapping_getActionState(IADF_USE)) - { - s_playerUse = JTRUE; - } - - if (inputMapping_getActionState(IADF_PRIMARY_FIRE)) - { - s_playerPrimaryFire = JTRUE; - } - else if (inputMapping_getActionState(IADF_SECONDARY_FIRE)) - { - s_playerSecFire = JTRUE; - } - - // Reduce the players ability to adjust the velocity while they have vertical velocity. - if (s_playerUpVel && !s_flyMode) - { - // TFE specific - const s32 airControl = 8 - TFE_Settings::getGameSettings()->df_airControl; - // In the original DOS code, airControl = 8. - s_forwardSpd >>= airControl; - s_strafeSpd >>= airControl; - } - } - - fixed16_16 adjustForwardSpeed(fixed16_16 spd) - { - spd <<= s_playerRun; - spd >>= s_playerSlow; - spd >>= s_onMovingSurface; // slows down the player movement on a moving surface. - spd <<= s_jumpScale; - return spd; - } - - fixed16_16 adjustStrafeSpeed(fixed16_16 spd) - { - spd <<= s_playerRun; - spd >>= s_playerSlow; - spd >>= s_onMovingSurface; // slows down the player movement on a moving surface. - return spd; - } - - void computeDirectionFromAngle(angle14_32 yaw, fixed16_16* xDir, fixed16_16* zDir) - { - sinCosFixed(yaw, xDir, zDir); - } - - // Rescales the vector if it is longer than maxDist. - void limitVectorLength(fixed16_16* dx, fixed16_16* dz, fixed16_16 maxDist) - { - fixed16_16 halfDx = TFE_Jedi::abs(*dx) >> 1; - fixed16_16 halfDz = TFE_Jedi::abs(*dz) >> 1; - fixed16_16 distSq = mul16(halfDx, halfDx) + mul16(halfDz, halfDz); - - fixed16_16 dist = fixedSqrt(distSq); - s_dist = dist * 2; - - if (s_dist > maxDist) - { - s_distScale = div16(maxDist, s_dist); - *dx = mul16(*dx, s_distScale); - *dz = mul16(*dz, s_distScale); - } - } - - void computeMoveFromAngleAndSpeed(fixed16_16* outMoveX, fixed16_16* outMoveZ, angle14_32 yaw, fixed16_16 speed) - { - computeDirectionFromAngle(yaw, &s_moveDirX, &s_moveDirZ); - *outMoveX += mul16(s_moveDirX, speed); - *outMoveZ += mul16(s_moveDirZ, speed); - } - - void handlePlayerPhysics() - { - SecObject* player = s_playerObject; - RSector* origSector = player->sector; - fixed16_16 yVel = s_playerUpVel; - s_playerInWater = JFALSE; - - // Calculate the friction coefficient. - fixed16_16 friction; - if (yVel) - { - friction = FRICTION_FALLING; - } - else - { - JBool wearingCleats = s_wearingCleats; - friction = FRICTION_DEFAULT; - if ((s_playerSector->flags1 & SEC_FLAGS1_ICE_FLOOR) && !wearingCleats) // On Ice without cleats. - { - s_playerRun = JFALSE; - friction = FRICTION_ICE; - } - else if ((s_playerSector->flags1 & SEC_FLAGS1_SNOW_FLOOR) || wearingCleats) // On snow or wearing cleats. - { - // Lower friction means the player will stop sliding sooner. - friction = FRICTION_CLEATS; - } - else if (s_playerSector->secHeight - 1 >= 0) // In water - { - friction = FRICTION_DEFAULT; - s_playerRun = wearingCleats; // Once you get cleats, you move faster through water. - s_playerInWater = JTRUE; - } - } - - // Apply friction to existing velocity. - if (s_playerVelX || s_playerVelZ) - { - Tick dt = s_playerTick - s_prevPlayerTick; - // Exponential friction, this is the same as vel * friction^dt - for (Tick i = 0; i < dt; i++) - { - s_playerVelX = mul16(friction, s_playerVelX); - s_playerVelZ = mul16(friction, s_playerVelZ); - } - // Just stop moving if the velocity is low enough, to avoid jittering forever. - // Note: The jitter threshold has been halved in TFE in order to work at higher framerates. - if (distApprox(0, 0, s_playerVelX, s_playerVelZ) < HALF_16/2) - { - s_playerVelX = 0; - s_playerVelZ = 0; - } - } - - // Handle moving surfaces. - JBool onMovingSurface = JFALSE; - fixed16_16 floorHeight = s_playerSector->floorHeight; - fixed16_16 secHeight = s_playerSector->secHeight; - fixed16_16 secFloorHeight = floorHeight + secHeight; - s_onMovingSurface = 0; - if (player->posWS.y == floorHeight || player->posWS.y == secFloorHeight) - { - Allocator* links = s_playerSector->infLink; - InfLink* link = (InfLink*)allocator_getHead(links); - while (link) - { - if (link->type == LTYPE_SECTOR) - { - InfElevator* elev = link->elev; - JBool moved = JFALSE; - - if (player->posWS.y == s_playerSector->floorHeight) - { - if (elev->flags & INF_EFLAG_MOVE_FLOOR) { moved = JTRUE; } - } - else if (elev->flags & INF_EFLAG_MOVE_SECHT) - { - moved = JTRUE; - } - - if (moved) - { - fixed16_16 angularSpd; - vec3_fixed vel; - inf_getMovingElevatorVelocity(elev, &vel, &angularSpd); - - if (!angularSpd && secHeight > 0) - { - // liquid behavior - dampens velocity. - vel.x = mul16(vel.x, MOVING_SURFACE_MUL); - vel.z = mul16(vel.z, MOVING_SURFACE_MUL); - } - else if (angularSpd) - { - // This is never hit in Dark Forces because it appears that the angularSpd update in - // inf_getMovingElevatorVelocity() was removed for some reason. - assert(0); - } - - if (vel.x || vel.z) - { - if (!onMovingSurface) - { - s_externalVelX = vel.x; - s_externalVelZ = vel.z; - onMovingSurface = JTRUE; - } - else - { - s_externalVelX += vel.x; - // This is a bug in Dark Forces, and should have been += vel.z; - // However mods rely on this bug, so we have to keep it. - s_externalVelZ += angularSpd; - } - s_onMovingSurface = 1; - } - } - } - - link = (InfLink*)allocator_getNext(links); - } - } - - // Handle player movement. - if (s_forwardSpd || s_strafeSpd) - { - RSector* sector = player->sector; - if (!s_wearingCleats && (s_playerSector->flags1 & SEC_FLAGS1_ICE_FLOOR)) - { - s_forwardSpd = mul16(s_forwardSpd, ICE_SPEED_MUL); - s_strafeSpd = mul16(s_strafeSpd, ICE_SPEED_MUL); - } - fixed16_16 speed = adjustForwardSpeed(s_forwardSpd); - computeMoveFromAngleAndSpeed(&s_playerVelX, &s_playerVelZ, player->yaw, speed); - - // Add 90 degrees to get the strafe direction. - speed = adjustStrafeSpeed(s_strafeSpd); - computeMoveFromAngleAndSpeed(&s_playerVelX, &s_playerVelZ, player->yaw + 4095, speed); - limitVectorLength(&s_playerVelX, &s_playerVelZ, s_maxMoveDist); - } - - // Then convert from player velocity to per-frame movement. - fixed16_16 moveX = adjustForwardSpeed(s_playerVelX); - fixed16_16 moveZ = adjustForwardSpeed(s_playerVelZ); - s_playerLogic.move.x = mul16(moveX, s_deltaTime) + mul16(s_externalVelX, s_deltaTime); - s_playerLogic.move.z = mul16(moveZ, s_deltaTime) + mul16(s_externalVelZ, s_deltaTime); - s_playerLogic.stepHeight = s_limitStepHeight ? PLAYER_STEP : PLAYER_INF_STEP; - fixed16_16 width = (s_smallModeEnabled) ? PLAYER_SIZE_SMALL : PLAYER_WIDTH; - player->worldWidth = width; - - // Handle collision detection and response. - JBool collided = JFALSE; - JBool moved = JFALSE; - JBool prevResponseStep = JFALSE; - fixed16_16 slideDirX = 0; - fixed16_16 slideDirZ = 0; - s_playerSlideWall = nullptr; - // Up to 4 iterations, to handle sliding on walls. - if (s_noclip) - { - if (s_playerLogic.move.x || s_playerLogic.move.y) - { - moved = JTRUE; - } - if (s_playerSector) - { - s_colCurLowestFloor = s_playerSector->floorHeight; - s_colCurHighestCeil = s_playerSector->ceilingHeight; - s_colExtFloorHeight = s_playerSector->colFloorHeight; - s_colExtCeilHeight = s_playerSector->colCeilHeight; - } - } - else - { - for (s32 collisionIter = 4; collisionIter != 0; collisionIter--) - { - if (!handlePlayerCollision(&s_playerLogic, s_playerUpVel)) - { - if (s_playerLogic.move.x || s_playerLogic.move.y) - { - moved = JTRUE; - } - break; - } - - // Determine if a collision response is required. - collided = JTRUE; - if (!s_colResponseStep) - { - break; - } - prevResponseStep = s_colResponseStep; - - if (s_colWall0) - { - s_playerSlideWall = s_colWall0; - } - slideDirX = s_colResponseDir.x; - slideDirZ = s_colResponseDir.z; - } - } - - // If the player moved after collision, handle that here. - if (moved) - { - // Adjust velocity based on collision response. - if (collided) - { - // Adjust the velocity based on the collision response. - fixed16_16 projVel = mul16(s_playerVelX, slideDirX) + mul16(s_playerVelZ, slideDirZ); - s_playerVelX = mul16(projVel, slideDirX); - s_playerVelZ = mul16(projVel, slideDirZ); - - // Adjust the external velocity based on the collision response. - if (s_externalVelX || s_externalVelZ) - { - projVel = mul16(s_externalVelX, slideDirX) + mul16(s_externalVelZ, slideDirZ); - s_externalVelX = mul16(projVel, slideDirX); - s_externalVelZ = mul16(projVel, slideDirZ); - } - } - - // If this fails, the system will treat it as if the player didn't move (see below). - // However, it should succeed since the original collision detection did. - moved = playerMove(s_noclip); - if (moved) - { - s_colWidth += PLAYER_PICKUP_ADJ; // s_colWidth + 1.5 - playerHandleCollisionFunc(player->sector, collision_checkPickups, nullptr); - s_colWidth -= PLAYER_PICKUP_ADJ; - if (s_noclip) - { - s_colMinSector = player->sector; - } - } - } - - if (!moved) - { - s_colDstPosX = player->posWS.x; - s_colDstPosZ = player->posWS.z; - col_computeCollisionResponse(player->sector, s_playerUpVel); - s_playerLogic.move.x = 0; - s_playerLogic.move.z = 0; - s_playerVelX = 0; - s_playerVelZ = 0; - } - s_playerSector = s_colMinSector; - - if (s_externalVelX || s_externalVelZ) - { - fixed16_16 friction = FRICTION_DEFAULT; - Tick dt = s_playerTick - s_prevPlayerTick; - for (Tick i = 0; i < dt; i++) - { - s_externalVelX = mul16(s_externalVelX, friction); - s_externalVelZ = mul16(s_externalVelZ, friction); - } - fixed16_16 approxLen = distApprox(0, 0, s_externalVelX, s_externalVelZ); - // Reduce the friction min length by half to account for higher framerates. - if (approxLen < HALF_16/2) - { - s_externalVelX = 0; - s_externalVelZ = 0; - } - } - - if (s_playerSecMoved) - { - RSector* newSector = sector_which3D(player->posWS.x, player->posWS.y, player->posWS.z); - RSector* curSector = player->sector; - // Handle the case where the player changed sectors due to moving sectors. - if (newSector && newSector != curSector) - { - if (newSector->layer != curSector->layer) - { - automap_setLayer(newSector->layer); - } - sector_addObject(newSector, player); - } - s_playerSecMoved = JFALSE; - } - - if (origSector != player->sector) - { - RSector* newSector = player->sector; - if (newSector->flags1 & SEC_FLAGS1_SAFESECTOR) - { - Safe* safe = level_getSafeFromSector(newSector); - if (safe) - { - s_curSafe = safe; - } - } - - if (newSector->flags1 & SEC_FLAGS1_SECRET) - { - // If enabled, show the secret found message. - tfe_showSecretFoundMsg(); - - // Remove the flag so the secret isn't counted twice. - newSector->flags1 &= ~SEC_FLAGS1_SECRET; - s_secretsFound++; - level_updateSecretPercent(); - } - } - - // Adjust angles. - player->yaw = s_playerYaw & ANGLE_MASK; - player->pitch = s_playerPitch; - if (s_externalYawSpd) - { - s_externalYawSpd = mul16(s_externalYawSpd, s_deltaTime); - fixed16_16 speed = s_externalYawSpd << s_playerRun; - speed >>= s_playerSlow; - player->yaw += speed; - } - sinCosFixed(player->yaw, &s_playerLogic.dir.x, &s_playerLogic.dir.z); - - // Handle falling and jumping. - fixed16_16 ceilHeight; - sector_getObjFloorAndCeilHeight(s_playerSector, player->posWS.y, &floorHeight, &ceilHeight); - fixed16_16 floorRelHeight = floorHeight - player->posWS.y; - if (floorRelHeight > PLAYER_FALL_SCREAM_MINHEIGHT && s_playerUpVel2 > PLAYER_FALL_SCREAM_VEL && !s_kyleScreamSoundId && !s_playerDying) - { - s_kyleScreamSoundId = sound_play(s_kyleScreamSoundSource); - } - sector_getObjFloorAndCeilHeight(player->sector, player->posWS.y, &floorHeight, &ceilHeight); - - // Gravity. - fixed16_16 gravityAccelDt = mul16(s_gravityAccel, s_deltaTime); - // This happens in an interrupt in the original DOS code. - if (!s_flyMode) - { - s_playerUpVel2 += gravityAccelDt; - } - s_playerUpVel = s_playerUpVel2; - s_playerYPos += mul16(s_playerUpVel, s_deltaTime); - s_playerLogic.move.y = s_playerYPos - player->posWS.y; - player->posWS.y = s_playerYPos; - - if (s_playerYPos >= s_colCurLowestFloor && (!s_noclip || !s_flyMode)) - { - if (s_kyleScreamSoundId) - { - sound_stop(s_kyleScreamSoundId); - s_kyleScreamSoundId = NULL_SOUND; - } - // Handle player land event - this both plays a sound effect and sends an INF message. - if (s_prevDistFromFloor) - { - if (s_colMinSector->secHeight - 1 >= 0) - { - // Second height is below ground, so this is liquid. - sound_play(s_landSplashSound); - } - else if (s_prevDistFromFloor > PLAYER_FALL_HIT_SND_HEIGHT) - { - // Second height is at or above ground. - sound_play(s_landSolidSound); - } - message_sendToSector(s_colMinSector, player, INF_EVENT_LAND, MSG_TRIGGER); - - // 's_playerUpVel' determines how much the view collapses to the ground based on hit velocity. - if (s_playerUpVel < PLAYER_LAND_VEL_CHANGE) - { - s_postLandVel = min(s_playerUpVel >> 2, PLAYER_LAND_VEL_MAX); - } - else - { - s_postLandVel = min((s_playerUpVel >> 2) - ((s_playerUpVel - PLAYER_LAND_VEL_CHANGE) >> 3), PLAYER_LAND_VEL_MAX); - } - s_landUpVel = s_playerUpVel; - } - else - { - fixed16_16 yPos = player->posWS.y; - fixed16_16 yMove = s_playerLogic.move.y; - fixed16_16 distFromFloor = player->posWS.y - s_colCurLowestFloor; - // This adjusts the world height to compensate for the step height. - // Over time the world height will be restored. - if (distFromFloor > yMove) - { - player->worldHeight += (s_colCurBot - yPos + yMove); - } - } - - s_playerYPos = s_colCurLowestFloor; - player->posWS.y = s_colCurLowestFloor; - fixed16_16 newUpVel = min(0, s_playerUpVel2); - s_playerUpVel = newUpVel; - s_playerUpVel2 = newUpVel; - } - else - { - fixed16_16 playerTop = s_playerYPos - player->worldHeight - ONE_16; - if (playerTop < s_colCurHighestCeil && (!s_noclip || !s_flyMode)) - { - fixed16_16 yVel = max(0, s_playerUpVel2); - s_playerUpVel = yVel; - s_playerUpVel2 = yVel; - - fixed16_16 newPlayerBot = s_colCurHighestCeil + player->worldHeight + ONE_16; - s_playerYPos = min(s_colCurLowestFloor, newPlayerBot); - player->posWS.y = s_playerYPos; - } - } - - // Crouch - player->worldHeight -= mul16(s_playerCrouchSpd, s_deltaTime); - - // Land animation. - if (s_postLandVel) - { - // Modify the player height by post land velocity. - player->worldHeight -= mul16(s_postLandVel, s_deltaTime); - // Reduce the post land velocity by 20 units / second. - s_postLandVel -= mul16(FIXED(20), s_deltaTime); - s_postLandVel = max(0, s_postLandVel); - } - else - { - s_landUpVel = 0; - } - - fixed16_16 eyeToCeil = max(0, player->posWS.y - s_colCurHighestCeil); - fixed16_16 eyeHeight = eyeToCeil; - eyeToCeil = min(ONE_16, eyeToCeil); // the player eye should be clamped to 1 unit below the ceiling if possible. - eyeHeight -= eyeToCeil; - eyeHeight = min(PLAYER_HEIGHT, eyeHeight); - - RSector* sector = player->sector; - fixed16_16 minEyeDistFromFloor = (s_smallModeEnabled) ? PLAYER_SIZE_SMALL : s_minEyeDistFromFloor; - secHeight = sector->secHeight; - // The base min distance from the floor is (0) for solid floors and (depth + 0.25) for liquids. - fixed16_16 minDistToFloor = (sector->secHeight >= 0) ? secHeight + 0x4000 : 0; - // Then the base is adjusted so it is never smaller than s_minEyeDistFromFloor. - minDistToFloor = max(minEyeDistFromFloor, minDistToFloor); - - // Adjust world height over time to stand straight up and be the correct distance from the floor. - if (player->worldHeight < minDistToFloor) - { - if (s_postLandVel) - { - // Fall Damage if moving at faster than 107 units / second. - if (s_landUpVel > FIXED(107)) - { - fixed16_16 dmg = 2 * (s_landUpVel - FIXED(107)); - player_applyDamage(dmg, 0, JFALSE); - s_landUpVel = 0; - } - } - player->worldHeight = minDistToFloor; - } - // Make sure eye height is clamped. - if (!s_noclip || !s_flyMode) - { - player->worldHeight = min(eyeHeight, player->worldHeight); - } - - // Crushing Damage. - if (player->worldHeight < minEyeDistFromFloor && (!s_noclip || !s_flyMode)) - { - if (!s_crushSoundId) - { - s_crushSoundId = sound_play(s_crushSoundSource); - } - // Crushing damage is 10 damage/second -#ifdef TFE_ESPBOX - fixed16_16 crushingDmg = PLAYER_DMG_CRUSHING * s_deltaTime; -#else - fixed16_16 crushingDmg = mul16(PLAYER_DMG_CRUSHING, s_deltaTime); -#endif - player_applyDamage(0, crushingDmg, JFALSE); - player->worldHeight = minDistToFloor; - playerHandleCollisionFunc(player->sector, collision_handleCrushing, nullptr); - } - else if (s_crushSoundId) - { - sound_stop(s_crushSoundId); - s_crushSoundId = NULL_SOUND; - } - - if (!s_smallModeEnabled) - { - fixed16_16 dH = PLAYER_HEIGHT - player->worldHeight; - fixed16_16 maxMove = (s_playerInWater) ? FIXED(25) : FIXED(32); - s_maxMoveDist = maxMove - dH * 4; - } - else - { - s_maxMoveDist = (s_playerInWater) ? FIXED(25) : FIXED(32); - } - - // Headwave - s32 xWpnWaveOffset = 0; - s_headwaveVerticalOffset = 0; - if (s_config.headwave && (player->flags & OBJ_FLAG_EYE)) - { - fixed16_16 playerSpeedAve = distApprox(0, 0, s_playerVelX, s_playerVelZ); - if (!moved) - { - playerSpeedAve = 0; - } - if ((s_playerSector->flags1 & SEC_FLAGS1_ICE_FLOOR) && !s_wearingCleats) - { - playerSpeedAve = 0; - } - - if (s_playerSpeedAve != playerSpeedAve) - { - fixed16_16 maxFrameChange = mul16(FIXED(32), s_deltaTime); - fixed16_16 speedDelta = clamp(playerSpeedAve - s_playerSpeedAve, -maxFrameChange, maxFrameChange); - s_playerSpeedAve += speedDelta; - } - - sinCosFixed(s_curTick << 7, &s_wpnSin, &s_wpnCos); - fixed16_16 playerSpeedFract = div16(s_playerSpeedAve, FIXED(32)); - s_headwaveVerticalOffset = mul16(mul16(s_wpnCos, PLAYER_HEADWAVE_VERT_SPD), playerSpeedFract); - - sinCosFixed(s_curTick << 6, &s_wpnSin, &s_wpnCos); - xWpnWaveOffset = mul16(playerSpeedFract, s_wpnCos) >> 12; - - // Water... - if (s_playerSector->secHeight - 1 >= 0 && (s_externalVelX || s_externalVelZ)) - { - fixed16_16 externSpd = distApprox(0, 0, s_externalVelX, s_externalVelZ) >> 17; - sinCosFixed(s_curTick << 4, &s_wpnSin, &s_wpnCos); - s_headwaveVerticalOffset += mul16(s_wpnCos, PLAYER_HEADWAVE_VERT_WATER_SPD); - } - } - setCameraOffset(0, s_headwaveVerticalOffset, 0); - - // Apply the weapon motion. - PlayerWeapon* weapon = s_curPlayerWeapon; - weapon->xWaveOffset = xWpnWaveOffset; // the x offset has 4 bits of sub-texel precision. - weapon->yWaveOffset = s_headwaveVerticalOffset >> 13; // the y offset is probably the same 4 bits of precision & multiplied by half. - - // The moves the player can make are restricted based on whether they are on the floor or not. - if (s_colCurLowestFloor == player->posWS.y) - { - s_onFloor = JTRUE; - s_prevDistFromFloor = 0; - } - else - { - // Player is *not* on the floor, so things like crouching and jumping are not available. - s_onFloor = JFALSE; - } - - // Apply sector or floor damage. - u32 lowAndHighFlag = SEC_FLAGS1_LOW_DAMAGE | SEC_FLAGS1_HIGH_DAMAGE; - u32 dmgFlags = s_playerSector->flags1 & lowAndHighFlag; - // Handle damage floors. - if (dmgFlags == SEC_FLAGS1_LOW_DAMAGE && s_onFloor) - { -#ifdef TFE_ESPBOX - fixed16_16 dmg = PLAYER_DMG_FLOOR_LOW * s_deltaTime; -#else - fixed16_16 dmg = mul16(PLAYER_DMG_FLOOR_LOW, s_deltaTime); -#endif - player_applyDamage(dmg, 0, JTRUE); - } - else if (dmgFlags == SEC_FLAGS1_HIGH_DAMAGE && s_onFloor) - { -#ifdef TFE_ESPBOX - fixed16_16 dmg = PLAYER_DMG_FLOOR_HIGH * s_deltaTime; -#else - fixed16_16 dmg = mul16(PLAYER_DMG_FLOOR_HIGH, s_deltaTime); -#endif - player_applyDamage(dmg, 0, JTRUE); - } - else if (dmgFlags == lowAndHighFlag && !s_wearingGasmask && !s_playerDying) - { -#ifdef TFE_ESPBOX - fixed16_16 dmg = PLAYER_DMG_FLOOR_LOW * s_deltaTime; -#else - fixed16_16 dmg = mul16(PLAYER_DMG_FLOOR_LOW, s_deltaTime); -#endif - player_applyDamage(dmg, 0, JFALSE); - - if (!s_gasSectorTask) - { - s_gasSectorTask = createSubTask("gas sector", gasSectorTaskFunc); - } - } - // Free the gas damage task if the gas mask is worn or if the damage flags no longer match up. - if (s_gasSectorTask && (s_wearingGasmask || dmgFlags != lowAndHighFlag || s_playerDying)) - { - task_free(s_gasSectorTask); - s_gasSectorTask = nullptr; - } - - // Handle damage walls. - if (s_playerSlideWall && (s_playerSlideWall->flags1 & WF1_DAMAGE_WALL)) - { -#ifdef TFE_ESPBOX - fixed16_16 dmg = PLAYER_DMG_WALL * s_deltaTime; -#else - fixed16_16 dmg = mul16(PLAYER_DMG_WALL, s_deltaTime); -#endif - player_applyDamage(dmg, 0, JTRUE); - } - - // Double check the player Y position against the floor and ceiling. - if (!s_noclip || !s_flyMode) - { - if (player->posWS.y > s_colCurLowestFloor) - { - s_playerYPos = s_colCurLowestFloor; - player->posWS.y = s_colCurLowestFloor; - } - if (player->posWS.y < s_colCurHighestCeil) - { - s_playerYPos = s_colCurHighestCeil; - player->posWS.y = s_colCurHighestCeil; - } - } - - // Clamp the height if needed. - fixed16_16 yTop = player->posWS.y - s_colExtCeilHeight; - fixed16_16 yBot = player->posWS.y - s_colExtFloorHeight + 0x4000; - if (!s_noclip || !s_flyMode) - { - if (player->worldHeight - s_camOffset.y > yTop) - { - player->worldHeight = yTop + s_camOffset.y; - } - if (player->worldHeight - s_camOffset.y < yBot) - { - player->worldHeight = yBot + s_camOffset.y; - } - } - - weapon->rollOffset = -s_playerRoll / 13; - weapon->pchOffset = s_playerPitch / 64; - - // Handle camera lighting and night vision. - if (player->flags & OBJ_FLAG_EYE) - { - // This code is incorrect but it doesn't actually matter... - // roll is always 0. - setCameraAngleOffset(0, s_playerRoll, 0); - - s32 headlamp = 0; - if (s_headlampActive) - { - fixed16_16 batteryPower = min(ONE_16, s_batteryPower); - headlamp = floor16(mul16(batteryPower, FIXED(64))); - headlamp = min(MAX_LIGHT_LEVEL, headlamp); - } - s32 atten = max(headlamp, s_weaponLight + s_levelAtten); - s_baseAtten = atten; - if (s_nightvisionActive) - { - atten = 0; - } - setPlayerLight(atten); - } - - fixed16_16 distFromFloor = s_colCurLowestFloor - player->posWS.y; - if (distFromFloor <= s_prevDistFromFloor) - { - distFromFloor = s_prevDistFromFloor; - } - s_prevDistFromFloor = max(distFromFloor, s_prevDistFromFloor); - } - - void player_applyDamage(fixed16_16 healthDmg, fixed16_16 shieldDmg, JBool playHitSound) - { - fixed16_16 shields = intToFixed16(s_playerInfo.shields); - fixed16_16 health = intToFixed16(s_playerInfo.health); - health += s_playerInfo.healthFract; - - s32 applyDmg = s_invincibility ? 0 : 1; - if (applyDmg && health && shieldDmg >= 0) - { - if (shieldDmg && s_curTick > s_nextShieldDmgTick && !s_config.superShield) - { - // The amount of shield energy left after taking *half* damage. - fixed16_16 halfShieldDmg = TFE_Jedi::abs(shieldDmg) >> 1; - shields = max(0, shields - halfShieldDmg); - if (shields < FIXED(50)) - { - // healthDmg += shieldDmg * (1 - shields/50.0) - fixed16_16 fracDmgToHealth = ONE_16 - div16(shields, FIXED(50)); - healthDmg += mul16(fracDmgToHealth, shieldDmg); - } - // Now take the other half away. - shields = max(0, shields - halfShieldDmg); - s_playerInfo.shields = pickup_addToValue(floor16(shields), 0, 200); - if (playHitSound) - { - sound_play(s_playerShieldHitSoundSource); - } - - s_shieldDamageFx += (shieldDmg << 2); - s_shieldDamageFx = min(FIXED(17), s_shieldDamageFx); - } - } - applyDmg = (s_invincibility == -2) ? 0 : 1; - if (applyDmg && healthDmg && health) - { - health -= healthDmg; - if (health < ONE_16) - { - s_playerInfo.healthFract = 0; - // We could just set the health to 0 here... - s_playerInfo.health = pickup_addToValue(0, 0, 100); - if (playHitSound) - { - sound_play(s_playerDeathSoundSource); - } - if (s_gasSectorTask) - { - task_free(s_gasSectorTask); - } - health = 0; - s_gasSectorTask = nullptr; - s_playerDying = JTRUE; - s_reviveTick = s_curTick + 436; - } - else - { - if (playHitSound && s_curTick > s_nextPainSndTick) - { - sound_play(s_playerHealthHitSoundSource); - s_nextPainSndTick = s_curTick + 72; // half a second. - } - health = max(0, health); - s32 healthInt = floor16(health); - s32 healthFrac = fract16(health); - s_playerInfo.health = healthInt; - s_playerInfo.healthFract = healthFrac; - } - s_healthDamageFx += TFE_Jedi::abs(healthDmg) >> 1; - s_healthDamageFx = clamp(s_healthDamageFx, ONE_16, FIXED(17)); - } - } - - void handlePlayerUseAction() - { - SecObject* player = s_playerObject; - RSector* sector = player->sector; - - // Trigger the sector the player is standing in. - message_sendToSector(sector, s_playerObject, INF_EVENT_NUDGE_FRONT, MSG_TRIGGER); - - // Then cast a ray and see if the wall in front of the player is close enough to trigger. - fixed16_16 x0 = player->posWS.x; - fixed16_16 z0 = player->posWS.z; - fixed16_16 x1 = x0 + mul16(FIXED(4), s_playerLogic.dir.x); - fixed16_16 z1 = z0 + mul16(FIXED(4), s_playerLogic.dir.z); - RWall* wall = collision_wallCollisionFromPath(sector, x0, z0, x1, z1); - if (wall) - { - RSector* nextSector = wall->nextSector; - fixed16_16 eyeHeight = player->posWS.y - player->worldHeight; - if (nextSector) - { - s_prevCollisionFrameWall = s_collisionFrameWall; - fixed16_16 x, z; - collision_getHitPoint(&x, &z); - - // Nudge the wall. - fixed16_16 distFromW0 = vec2Length(wall->w0->x - x, wall->w0->z - z); - inf_wallAndMirrorSendMessageAtPos(wall, s_playerObject, INF_EVENT_NUDGE_FRONT, distFromW0, eyeHeight); - // Nudge the next sector from the outside. - message_sendToSector(nextSector, s_playerObject, INF_EVENT_NUDGE_BACK, MSG_TRIGGER); - // Set the sector collision frame to avoid infinite loops. - nextSector->collisionFrame = s_collisionFrameWall; - - // The eye ray can go through the opening. - if (eyeHeight > nextSector->ceilingHeight && eyeHeight < nextSector->floorHeight) - { - // Loop as the ray goes from sector to sector. - do - { - wall = collision_pathWallCollision(nextSector); - if (wall) - { - // Trigger the next wall. - collision_getHitPoint(&x, &z); - distFromW0 = vec2Length(wall->w0->x - x, wall->w0->z - z); - inf_wallAndMirrorSendMessageAtPos(wall, s_playerObject, INF_EVENT_NUDGE_FRONT, distFromW0, eyeHeight); - - nextSector = wall->nextSector; - if (nextSector) - { - if (s_collisionFrameWall != nextSector->collisionFrame) - { - // Nudge the next sector from the outside. - message_sendToSector(nextSector, s_playerObject, INF_EVENT_NUDGE_BACK, MSG_TRIGGER); - nextSector->collisionFrame = s_collisionFrameWall; - } - // Make sure the eye ray fits in the opening. - if (eyeHeight < nextSector->ceilingHeight || eyeHeight > nextSector->floorHeight) - { - break; - } - } - } - } while (wall && nextSector); - } - if (s_collisionFrameWall != s_prevCollisionFrameWall) - { - TFE_System::logWrite(LOG_ERROR, "Player Use", "MARK HAS UNEXPECTEDLY CHANGED."); - } - } - else - { - fixed16_16 x, z; - collision_getHitPoint(&x, &z); - - s32 distFromW0 = vec2Length(wall->w0->x - x, wall->w0->z - z); - inf_wallAndMirrorSendMessageAtPos(wall, s_playerObject, INF_EVENT_NUDGE_FRONT, distFromW0, eyeHeight); - } - } - } - - void handlePlayerActions() - { - if (s_batteryPower) - { - if (s_headlampActive) - { - fixed16_16 powerDelta = mul16(HEADLAMP_ENERGY_CONSUMPTION, s_deltaTime); - s_batteryPower -= powerDelta; - } - if (s_wearingGasmask) - { - fixed16_16 powerDelta = mul16(GASMASK_ENERGY_CONSUMPTION, s_deltaTime); - s_batteryPower -= powerDelta; - } - if (s_nightvisionActive) - { - fixed16_16 powerDelta = mul16(GOGGLES_ENERGY_CONSUMPTION, s_deltaTime); - s_batteryPower -= powerDelta; - } - if (s_batteryPower <= 0) - { - if (s_nightvisionActive) - { - s_nightvisionActive = JFALSE; - disableNightvisionInternal(); - hud_sendTextMessage(9); - } - if (s_headlampActive) - { - hud_sendTextMessage(12); - s_headlampActive = JFALSE; - } - if (s_wearingGasmask) - { - hud_sendTextMessage(19); - s_wearingGasmask = JFALSE; - if (s_gasmaskTask) - { - task_free(s_gasmaskTask); - s_gasmaskTask = nullptr; - } - } - s_batteryPower = 0; - } - } - if (s_playerUse) - { - s_playerUse = JFALSE; - if (!s_playerActionUse) - { - handlePlayerUseAction(); - s_playerActionUse = JTRUE; - } - } - else - { - s_playerActionUse = JFALSE; - } - - if (s_playerPrimaryFire) - { - s_playerPrimaryFire = JFALSE; - if (!s_weaponFiring && s_playerWeaponTask) - { - s_weaponFiring = JTRUE; - // This causes the weapon to fire. - s_msgArg1 = WFIRETYPE_PRIMARY; - task_runAndReturn(s_playerWeaponTask, MSG_START_FIRING); - } - } - // This happens when the player *stops* firing. - else if (s_weaponFiring && s_playerWeaponTask) - { - s_weaponFiring = JFALSE; - if (!s_weaponFiringSec) - { - // Spin down. - task_runAndReturn(s_playerWeaponTask, MSG_STOP_FIRING); - } - else - { - // Start secondary fire. - s_msgArg1 = WFIRETYPE_SECONDARY; - task_runAndReturn(s_playerWeaponTask, MSG_START_FIRING); - } - } - - if (s_playerSecFire) - { - s_playerSecFire = JFALSE; - if (!s_weaponFiringSec && s_playerWeaponTask) - { - s_weaponFiringSec = JTRUE; - s_msgArg1 = WFIRETYPE_SECONDARY; - task_runAndReturn(s_playerWeaponTask, MSG_START_FIRING); - } - } - // This happens when the player *stops* firing. - else if (s_weaponFiringSec && s_playerWeaponTask) - { - s_weaponFiringSec = JFALSE; - if (!s_weaponFiring) - { - // Spin down - task_runAndReturn(s_playerWeaponTask, MSG_STOP_FIRING); - } - else - { - // Start primary fire. - s_msgArg1 = WFIRETYPE_PRIMARY; - task_runAndReturn(s_playerWeaponTask, MSG_START_FIRING); - } - } - - if (!s_playerDying) - { - // Weapon select. - if (inputMapping_getActionState(IADF_WEAPON_1) == STATE_PRESSED) - { - s_playerInfo.newWeapon = WPN_FIST; - } - if (inputMapping_getActionState(IADF_WEAPON_2) == STATE_PRESSED && s_playerInfo.itemPistol) - { - s_playerInfo.newWeapon = WPN_PISTOL; - } - if (inputMapping_getActionState(IADF_WEAPON_3) == STATE_PRESSED && s_playerInfo.itemRifle) - { - s_playerInfo.newWeapon = WPN_RIFLE; - } - if (inputMapping_getActionState(IADF_WEAPON_4) == STATE_PRESSED) - { - s_playerInfo.newWeapon = WPN_THERMAL_DET; - } - if (inputMapping_getActionState(IADF_WEAPON_5) == STATE_PRESSED && s_playerInfo.itemAutogun) - { - s_playerInfo.newWeapon = WPN_REPEATER; - } - if (inputMapping_getActionState(IADF_WEAPON_6) == STATE_PRESSED && s_playerInfo.itemFusion) - { - s_playerInfo.newWeapon = WPN_FUSION; - } - if (inputMapping_getActionState(IADF_WEAPON_7) == STATE_PRESSED) - { - s_playerInfo.newWeapon = WPN_MINE; - } - if (inputMapping_getActionState(IADF_WEAPON_8) == STATE_PRESSED && s_playerInfo.itemMortar) - { - s_playerInfo.newWeapon = WPN_MORTAR; - } - if (inputMapping_getActionState(IADF_WEAPON_9) == STATE_PRESSED && s_playerInfo.itemConcussion) - { - s_playerInfo.newWeapon = WPN_CONCUSSION; - } - if (inputMapping_getActionState(IADF_WEAPON_10) == STATE_PRESSED && s_playerInfo.itemCannon) - { - s_playerInfo.newWeapon = WPN_CANNON; - } - if (inputMapping_getActionState(IADF_WPN_PREV) == STATE_PRESSED) - { - s_playerInfo.newWeapon = WPN_COUNT; - } - - s32 newWeapon = s_playerInfo.newWeapon; - if (newWeapon != -1) - { - s32 curWeapon = s_playerInfo.curWeapon; - if (newWeapon != curWeapon) - { - if (s_playerWeaponTask) - { - // Change weapon - s_msgArg1 = newWeapon < WPN_COUNT ? newWeapon : -1; - task_runAndReturn(s_playerWeaponTask, MSG_SWITCH_WPN); - - if (s_playerInfo.curWeapon > s_playerInfo.maxWeapon) - { - s_playerInfo.maxWeapon = s_playerInfo.curWeapon; - } - } - else - { - s_playerInfo.saveWeapon = newWeapon; - } - } - s_playerInfo.newWeapon = -1; - } - } - } - - void handlePlayerScreenFx() - { - s32 healthFx, shieldFx, flashFx; - if (s_healthDamageFx) - { - s32 effectIndex = min(15, s_healthDamageFx >> 16); - healthFx = c_healthDmgToFx[effectIndex]; - s_healthDamageFx = max(0, s_healthDamageFx - mul16(c_damageDelta, s_deltaTime)); - } - else - { - healthFx = 0; - } - if (s_shieldDamageFx) - { - s32 effectIndex = min(15, s_shieldDamageFx >> 16); - shieldFx = c_shieldDmgToFx[effectIndex]; - s_shieldDamageFx = max(0, s_shieldDamageFx - mul16(c_shieldDelta, s_deltaTime)); - } - else - { - shieldFx = 0; - } - if (s_flashEffect) - { - s32 effectIndex = min(15, s_flashEffect >> 16); - flashFx = c_flashAmtToFx[effectIndex]; - s_flashEffect = max(0, s_flashEffect - mul16(c_flashDelta, s_deltaTime)); - } - else - { - flashFx = 0; - } - setScreenFxLevels(healthFx, shieldFx, flashFx); - } - - void gasSectorTaskFunc(MessageType msg) - { - task_begin; - while (1) - { - sound_play(s_gasDamageSoundSource); - task_yield(291); // wait for 2 seconds. - } - task_end; - } - - JBool player_hasWeapon(s32 weaponIndex) - { - JBool retval = JFALSE; - switch (weaponIndex) - { - case 2: // WPN_PISTOL + 1 - retval = s_playerInfo.itemPistol; - break; - case 3: - retval = s_playerInfo.itemRifle; - break; - case 4: - retval = s_playerInfo.ammoDetonator > 0 ? JTRUE : JFALSE; - break; - case 5: - retval = s_playerInfo.itemAutogun; - break; - case 6: - retval = s_playerInfo.itemFusion; - break; - case 7: - retval = s_playerInfo.ammoMine > 0 ? JTRUE : JFALSE; - break; - case 8: - retval = s_playerInfo.itemMortar; - break; - case 9: - retval = s_playerInfo.itemConcussion; - break; - case 10: - retval = s_playerInfo.itemCannon; - break; - } - return retval; - } - - JBool player_hasItem(s32 itemIndex) - { - JBool retval = JFALSE; - switch (itemIndex) - { - case 0: - retval = s_playerInfo.itemRedKey; - break; - case 1: - retval = s_playerInfo.itemYellowKey; - break; - case 2: - retval = s_playerInfo.itemBlueKey; - break; - case 3: - retval = s_playerInfo.itemGoggles; - break; - case 4: - retval = s_playerInfo.itemCleats; - break; - case 5: - retval = s_playerInfo.itemMask; - break; - case 6: - retval = s_playerInfo.itemPlans; - break; - case 7: - retval = s_playerInfo.itemPhrik; - break; - case 8: - retval = s_playerInfo.itemNava; - break; - case 9: - retval = s_playerInfo.itemDatatape; - break; - case 10: - retval = s_playerInfo.itemUnused; - break; - case 11: - retval = s_playerInfo.itemDtWeapon; - break; - case 12: - retval = s_playerInfo.itemCode1; - break; - case 13: - retval = s_playerInfo.itemCode2; - break; - case 14: - retval = s_playerInfo.itemCode3; - break; - case 15: - retval = s_playerInfo.itemCode4; - break; - case 16: - retval = s_playerInfo.itemCode5; - break; - case 17: - retval = s_playerInfo.itemCode6; - break; - case 18: - retval = s_playerInfo.itemCode7; - break; - case 19: - retval = s_playerInfo.itemCode8; - break; - case 20: - retval = s_playerInfo.itemCode9; - break; - } - return retval; - } - - // TFE - void player_warp(const ConsoleArgList& args) - { - if (args.size() < 4) { return; } - fixed16_16 x = floatToFixed16(TFE_Console::getFloatArg(args[1])); - fixed16_16 y = -floatToFixed16(TFE_Console::getFloatArg(args[2])); - fixed16_16 z = floatToFixed16(TFE_Console::getFloatArg(args[3])); - RSector* sector = sector_which3D(x, y, z); - - if (sector) - { - s_playerObject->posWS = { x, y, z }; - s_playerPos = s_playerObject->posWS; - - sector_addObject(sector, s_playerObject); - s_playerSector = s_playerObject->sector; - } - } - - void player_sector(const ConsoleArgList& args) - { - RSector* sector = s_playerObject->sector; - if (sector) - { - char sectorIdStr[256]; - sprintf(sectorIdStr, "Sector ID: %d", sector->id); - TFE_Console::addToHistory(sectorIdStr); - } - else - { - TFE_Console::addToHistory("Invalid sector"); - } - } - - // Serialization - void playerLogic_serialize(Logic*& logic, SecObject* obj, Stream* stream) - { - PlayerLogic* playerLogic; - if (serialization_getMode() == SMODE_WRITE) - { - playerLogic = (PlayerLogic*)logic; - } - else - { - playerLogic = &s_playerLogic; - logic = (Logic*)playerLogic; - task_makeActive(s_playerTask); - - playerLogic->logic.task = s_playerTask; - playerLogic->logic.cleanupFunc = playerLogicCleanupFunc; - } - assert(playerLogic == &s_playerLogic); - - const vec2_fixed defV2 = { 0 }; - const vec3_fixed defV3 = { 0 }; - SERIALIZE(ObjState_InitVersion, playerLogic->dir, defV2); - SERIALIZE(ObjState_InitVersion, playerLogic->move, defV3); - SERIALIZE(ObjState_InitVersion, playerLogic->stepHeight, 0); - - SERIALIZE(ObjState_InitVersion, s_externalYawSpd, 0); - SERIALIZE(ObjState_InitVersion, s_playerPitch, 0); - SERIALIZE(ObjState_InitVersion, s_playerRoll, 0); - SERIALIZE(ObjState_InitVersion, s_forwardSpd, 0); - SERIALIZE(ObjState_InitVersion, s_strafeSpd, 0); - SERIALIZE(ObjState_InitVersion, s_maxMoveDist, 0); - SERIALIZE(ObjState_InitVersion, s_playerStopAccel, 0); - SERIALIZE(ObjState_InitVersion, s_minEyeDistFromFloor, 0); - SERIALIZE(ObjState_InitVersion, s_postLandVel, 0); - SERIALIZE(ObjState_InitVersion, s_landUpVel, 0); - SERIALIZE(ObjState_InitVersion, s_playerVelX, 0); - SERIALIZE(ObjState_InitVersion, s_playerUpVel, 0); - SERIALIZE(ObjState_InitVersion, s_playerUpVel2, 0); - SERIALIZE(ObjState_InitVersion, s_playerVelZ, 0); - SERIALIZE(ObjState_InitVersion, s_externalVelX, 0); - SERIALIZE(ObjState_InitVersion, s_externalVelZ, 0); - SERIALIZE(ObjState_InitVersion, s_playerCrouchSpd, 0); - SERIALIZE(ObjState_InitVersion, s_playerSpeedAve, 0); - SERIALIZE(ObjState_InitVersion, s_prevDistFromFloor, 0); - SERIALIZE(ObjState_InitVersion, s_wpnSin, 0); - SERIALIZE(ObjState_InitVersion, s_wpnCos, 0); - SERIALIZE(ObjState_InitVersion, s_moveDirX, 0); - SERIALIZE(ObjState_InitVersion, s_moveDirZ, 0); - SERIALIZE(ObjState_InitVersion, s_dist, 0); - SERIALIZE(ObjState_InitVersion, s_distScale, 0); - - SERIALIZE(ObjState_InitVersion, s_levelAtten, 0); - SERIALIZE(ObjState_InitVersion, s_prevCollisionFrameWall, 0); - - // Store safe sector, derive the safe itself from it on load. - RSector* safeSector = nullptr; - if (serialization_getMode() == SMODE_WRITE) { safeSector = s_curSafe ? s_curSafe->sector : nullptr; } - serialization_serializeSectorPtr(stream, ObjState_InitVersion, safeSector); - if (serialization_getMode() == SMODE_READ) { s_curSafe = safeSector ? level_getSafeFromSector(safeSector) : nullptr; } - // There should always be a safe the level start always acts as one. - assert(s_curSafe); - - SERIALIZE(ObjState_InitVersion, s_playerUse, 0); - SERIALIZE(ObjState_InitVersion, s_playerActionUse, 0); - SERIALIZE(ObjState_InitVersion, s_playerPrimaryFire, 0); - SERIALIZE(ObjState_InitVersion, s_playerSecFire, 0); - SERIALIZE(ObjState_InitVersion, s_playerJumping, 0); - SERIALIZE(ObjState_InitVersion, s_playerInWater, 0); - SERIALIZE(ObjState_InitVersion, s_limitStepHeight, 0); - SERIALIZE(ObjState_InitVersion, s_smallModeEnabled, 0); - SERIALIZE(ObjState_InitVersion, s_aiActive, 0); - - // Clear sound effects - s_crushSoundId, s_kyleScreamSoundId - if (serialization_getMode() == SMODE_READ) - { - s_crushSoundId = 0; - s_kyleScreamSoundId = 0; - } - - SERIALIZE(ObjState_InitVersion, s_playerPos, defV3); - SERIALIZE(ObjState_InitVersion, s_playerObjHeight, 0); - SERIALIZE(ObjState_InitVersion, s_playerObjPitch, 0); - SERIALIZE(ObjState_InitVersion, s_playerObjYaw, 0); - serialization_serializeSectorPtr(stream, ObjState_InitVersion, s_playerObjSector); - - // Save wall data. - RSector* slideWallSector = nullptr; - s32 wallId = -1; - if (serialization_getMode() == SMODE_WRITE) - { - slideWallSector = s_playerSlideWall ? s_playerSlideWall->sector : nullptr; - wallId = s_playerSlideWall ? s_playerSlideWall->id : -1; - } - serialization_serializeSectorPtr(stream, ObjState_InitVersion, slideWallSector); - SERIALIZE(ObjState_InitVersion, wallId, -1); - if (serialization_getMode() == SMODE_READ) - { - s_playerSlideWall = slideWallSector ? &slideWallSector->walls[wallId] : nullptr; - } - - SERIALIZE(ObjState_InitVersion, s_playerInfo, { 0 }); - SERIALIZE(ObjState_InitVersion, s_batteryPower, 0); - SERIALIZE(ObjState_InitVersion, s_lifeCount, 0); - SERIALIZE(ObjState_InitVersion, s_playerLight, 0); - SERIALIZE(ObjState_InitVersion, s_headwaveVerticalOffset, 0); - SERIALIZE(ObjState_InitVersion, s_onFloor, 0); - SERIALIZE(ObjState_InitVersion, s_weaponLight, 0); - SERIALIZE(ObjState_InitVersion, s_baseAtten, 0); - SERIALIZE(ObjState_InitVersion, s_gravityAccel, 0); - SERIALIZE(ObjState_InitVersion, s_invincibility, 0); - SERIALIZE(ObjState_InitVersion, s_weaponFiring, 0); - SERIALIZE(ObjState_InitVersion, s_weaponFiringSec, 0); - SERIALIZE(ObjState_InitVersion, s_wearingCleats, 0); - SERIALIZE(ObjState_InitVersion, s_wearingGasmask, 0); - SERIALIZE(ObjState_InitVersion, s_nightvisionActive, 0); - SERIALIZE(ObjState_InitVersion, s_headlampActive, 0); - SERIALIZE(ObjState_InitVersion, s_superCharge, 0); - SERIALIZE(ObjState_InitVersion, s_superChargeHud, 0); - SERIALIZE(ObjState_InitVersion, s_playerSecMoved, 0); - SERIALIZE(ObjState_FlyModeAdded, s_flyMode, JFALSE); - - s32 invSavedSize = 0; - if (serialization_getMode() == SMODE_WRITE && s_playerInvSaved) - { - invSavedSize = s32((size_t)&s_playerInfo.pileSaveMarker - (size_t)&s_playerInfo); - assert(invSavedSize == 140); - } - else if (serialization_getMode() == SMODE_READ) - { - s_playerInvSaved = nullptr; - } - SERIALIZE(ObjState_InitVersion, invSavedSize, 0); - if (invSavedSize) - { - if (serialization_getMode() == SMODE_READ) - { - s_playerInvSaved = (u32*)level_alloc(invSavedSize); - } - SERIALIZE_BUF(ObjState_InitVersion, s_playerInvSaved, invSavedSize); - } - - serialization_serializeSectorPtr(stream, ObjState_InitVersion, s_playerSector); - - s32 playerObjId = -1, playerEyeId = -1; - if (serialization_getMode() == SMODE_WRITE) - { - playerObjId = s_playerObject ? s_playerObject->serializeIndex : -1; - playerEyeId = s_playerEye ? s_playerEye->serializeIndex : -1; - } - SERIALIZE(ObjState_InitVersion, playerObjId, -1); - SERIALIZE(ObjState_InitVersion, playerEyeId, -1); - if (serialization_getMode() == SMODE_READ) - { - s_playerObject = playerObjId < 0 ? nullptr : objData_getObjectBySerializationId(playerObjId); - s_playerEye = playerEyeId < 0 ? nullptr : objData_getObjectBySerializationId(playerEyeId); - - if (s_nightvisionActive) - { - TFE_Jedi::s_flatAmbient = 16; - TFE_Jedi::s_flatLighting = JTRUE; - } - else - { - TFE_Jedi::s_flatLighting = JFALSE; - } - } - - SERIALIZE(ObjState_InitVersion, s_eyePos, defV3); - SERIALIZE(ObjState_InitVersion, s_pitch, 0); - SERIALIZE(ObjState_InitVersion, s_yaw, 0); - SERIALIZE(ObjState_InitVersion, s_roll, 0); - SERIALIZE(ObjState_InitVersion, s_playerEyeFlags, 0); - SERIALIZE(ObjState_InitVersion, s_playerTick, 0); - SERIALIZE(ObjState_InitVersion, s_prevPlayerTick, 0); - SERIALIZE(ObjState_InitVersion, s_nextShieldDmgTick, 0); - SERIALIZE(ObjState_InitVersion, s_reviveTick, 0); - SERIALIZE(ObjState_InitVersion, s_nextPainSndTick, 0); - - SERIALIZE(ObjState_InitVersion, s_playerYPos, 0); - SERIALIZE(ObjState_InitVersion, s_camOffset, defV3); - SERIALIZE(ObjState_InitVersion, s_camOffsetPitch, 0); - SERIALIZE(ObjState_InitVersion, s_camOffsetYaw, 0); - SERIALIZE(ObjState_InitVersion, s_camOffsetRoll, 0); - SERIALIZE(ObjState_InitVersion, s_playerYaw, 0); - - SERIALIZE(ObjState_InitVersion, s_itemUnknown1, 0); - SERIALIZE(ObjState_InitVersion, s_itemUnknown2, 0); - - SERIALIZE(ObjState_InitVersion, s_playerHeight, 0); - SERIALIZE(ObjState_InitVersion, s_playerRun, 0); - SERIALIZE(ObjState_InitVersion, s_jumpScale, 0); - SERIALIZE(ObjState_InitVersion, s_playerSlow, 0); - SERIALIZE(ObjState_InitVersion, s_onMovingSurface, 0); - - // Handle the player saving as they die and then reloading... - if (serialization_getMode() == SMODE_READ) - { - fixed16_16 health = intToFixed16(s_playerInfo.health); - health += s_playerInfo.healthFract; - - if (health < ONE_16) - { - s_playerInfo.healthFract = 0; - // We could just set the health to 0 here... - s_playerInfo.health = pickup_addToValue(0, 0, 100); - if (s_gasSectorTask) - { - task_free(s_gasSectorTask); - } - s_gasSectorTask = nullptr; - s_playerDying = JTRUE; - s_reviveTick = s_curTick + 436; - } - } - } - - // TFE Specific - void tfe_showSecretFoundMsg() - { - TFE_Settings_Game* settings = TFE_Settings::getGameSettings(); - if (settings->df_showSecretFoundMsg) - { - const char* msg = TFE_System::getMessage(TFE_MSG_SECRET); - if (msg) - { - hud_sendTextMessage(msg, 1); // high priority. - } - } - } -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/player.h b/components/darkforces/tfe/TFE_DarkForces/player.h deleted file mode 100644 index 26a44d84..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/player.h +++ /dev/null @@ -1,171 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces Player - -// Player information and object data. -////////////////////////////////////////////////////////////////////// - -#include -#include -#include -#include -#include -#include -#include "sound.h" -#include "time.h" - -struct ProjectileLogic; -struct Logic; - -namespace TFE_DarkForces -{ - // TODO: Factor out the PlayerItems into a struct - // so that it can be directly allocated and copied when saving the inventory for - // Jabba's Ship. - struct PlayerInfo - { - // Items - // Weapons - JBool itemPistol; - JBool itemRifle; - JBool itemAutogun; - JBool itemMortar; - JBool itemFusion; - JBool itemConcussion; - JBool itemCannon; - // Keys - JBool itemRedKey; - JBool itemYellowKey; - JBool itemBlueKey; - JBool itemGoggles; - JBool itemCleats; - JBool itemMask; - // Inventory - JBool itemPlans; - JBool itemPhrik; - JBool itemDatatape; - JBool itemUnused; - JBool itemNava; - JBool itemDtWeapon; - JBool itemCode1; - JBool itemCode2; - JBool itemCode3; - JBool itemCode4; - JBool itemCode5; - JBool itemCode6; - JBool itemCode7; - JBool itemCode8; - JBool itemCode9; - // Ammo - s32 ammoEnergy; - s32 ammoPower; - s32 ammoPlasma; - s32 ammoDetonator; - s32 ammoShell; - s32 ammoMine; - s32 ammoMissile; - // Health & Shields - s32 pileSaveMarker; - s32 shields; - s32 health; - s32 healthFract; - // Weapon - s32 newWeapon; - s32 curWeapon; - s32 maxWeapon; - s32 saveWeapon; - }; - - extern PlayerInfo s_playerInfo; - extern fixed16_16 s_batteryPower; - extern s32 s_lifeCount; - extern s32 s_playerLight; - extern s32 s_headwaveVerticalOffset; - extern s32 s_weaponLight; - extern s32 s_baseAtten; - extern s32 s_invincibility; - extern fixed16_16 s_gravityAccel; - extern JBool s_weaponFiring; - extern JBool s_weaponFiringSec; - extern JBool s_wearingCleats; - extern JBool s_wearingGasmask; - extern JBool s_nightvisionActive; - extern JBool s_headlampActive; - extern JBool s_superCharge; - extern JBool s_superChargeHud; - extern JBool s_playerSecMoved; - extern JBool s_aiActive; - extern u32* s_playerInvSaved; - // Eye parameters - extern fixed16_16 s_playerHeight; - extern fixed16_16 s_playerYPos; - extern vec3_fixed s_eyePos; // s_camX, s_camY, s_camZ in the DOS code. - extern angle14_32 s_pitch, s_yaw, s_roll; - extern angle14_32 s_playerYaw; - extern Tick s_playerTick; - extern Tick s_reviveTick; - - extern SecObject* s_playerObject; - extern SecObject* s_playerEye; - - // Speed Modifiers - extern s32 s_playerRun; - extern s32 s_jumpScale; - extern s32 s_playerSlow; - extern s32 s_waterSpeed; - - extern Task* s_playerTask; - - // Sounds - extern SoundSourceId s_landSplashSound; - extern SoundSourceId s_landSolidSound; - extern SoundSourceId s_gasDamageSoundSource; - extern SoundSourceId s_maskSoundSource1; - extern SoundSourceId s_maskSoundSource2; - extern SoundSourceId s_invCountdownSound; - extern SoundSourceId s_jumpSoundSource; - extern SoundSourceId s_nightVisionActiveSoundSource; - extern SoundSourceId s_nightVisionDeactiveSoundSource; - extern SoundSourceId s_playerDeathSoundSource; - extern SoundSourceId s_crushSoundSource; - extern SoundSourceId s_playerHealthHitSoundSource; - extern SoundSourceId s_kyleScreamSoundSource; - extern SoundSourceId s_playerShieldHitSoundSource; - - void player_init(); - void player_readInfo(u8* inv, s32* ammo); - void player_writeInfo(u8* inv, s32* ammo); - void player_clearEyeObject(); - void player_createController(JBool clearData = JTRUE); - void player_setupObject(SecObject* obj); - void player_setupEyeObject(SecObject* obj); - void player_revive(); - s32 player_getLifeCount(); - void player_getVelocity(vec3_fixed* vel); - fixed16_16 player_getSquaredDistance(SecObject* obj); - void player_setupCamera(); - void player_applyDamage(fixed16_16 healthDmg, fixed16_16 shieldDmg, JBool playHitSound); - - JBool player_hasWeapon(s32 weaponIndex); - JBool player_hasItem(s32 itemIndex); - - void computeExplosionPushDir(vec3_fixed* pos, vec3_fixed* pushDir); - void computeDamagePushVelocity(ProjectileLogic* proj, vec3_fixed* vel); - - void cheat_teleport(); - void cheat_enableNoheightCheck(); - void cheat_bugMode(); - void cheat_pauseAI(); - void cheat_postal(); - void cheat_fullAmmo(); - void cheat_unlock(); - void cheat_maxout(); - void cheat_godMode(); - - // New TFE Cheats - void cheat_fly(); - void cheat_noclip(); - void cheat_tester(); - - // Serialization - void playerLogic_serialize(Logic*& logic, SecObject* obj, Stream* stream); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/playerCollision.cpp b/components/darkforces/tfe/TFE_DarkForces/playerCollision.cpp deleted file mode 100644 index 314f902d..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/playerCollision.cpp +++ /dev/null @@ -1,839 +0,0 @@ -#include "player.h" -#include "playerCollision.h" -#include "automap.h" -#include "pickup.h" -#include -#include -#include -#include -#include -#include -#include -// Internal types need to be included in this case. -#include -#include -#include - -// TFE -#include -#include -#include -#include - -// TFE -namespace TFE_Jedi -{ - extern Vec3f s_cameraPos; - extern Vec3f s_cameraDir; -} - -namespace TFE_DarkForces -{ - /////////////////////////////////////////// - // Constants - /////////////////////////////////////////// - enum Passability - { - PASS_ALWAYS_WALK = 0, - PASS_DEFAULT = 0xffffffff, - }; - - enum CollisionAjustments - { - COL_BOT_ADJ_THRESHOLD = 800, // The delta time threshold at which point the collision bottom should be adjusted. - COL_BOT_ADJ = 8192, // The collision bottom is adjusted by 1/8 DFU. - }; - - /////////////////////////////////////////// - // Internal State - /////////////////////////////////////////// - static PlayerLogic* s_curPlayerLogic; - - /////////////////////////////////////////// - // TODO: Move to collision - /////////////////////////////////////////// - SecObject* s_collidedObj; - ColObject s_colObject; - ColObject s_colObj1; - RWall* s_colWallCollided; - fixed16_16 s_colSrcPosX; - fixed16_16 s_colSrcPosY; - fixed16_16 s_colSrcPosZ; - fixed16_16 s_colHeight; - fixed16_16 s_colDoubleRadius; - fixed16_16 s_colHeightBase; - fixed16_16 s_colRealFloorHeight; - fixed16_16 s_colRealCeilHeight; - fixed16_16 s_colBottom; - fixed16_16 s_colTop; - fixed16_16 s_colY1; - fixed16_16 s_colCurTop; - angle14_32 s_colResponseAngle; - vec2_fixed s_colResponsePos; - vec2_fixed s_colWallV0; - s32 s_collisionFrameSector; - - CollisionObjFunc s_objCollisionFunc; - CollisionProxFunc s_objCollisionProxFunc; - - /////////////////////////////////////////// - // Shared State - /////////////////////////////////////////// - fixed16_16 s_colCurLowestFloor; - fixed16_16 s_colCurHighestCeil; - fixed16_16 s_colCurBot; - fixed16_16 s_colExtCeilHeight; - fixed16_16 s_colExtFloorHeight; - - fixed16_16 s_colWidth; - fixed16_16 s_colDstPosX; - fixed16_16 s_colDstPosY; - fixed16_16 s_colDstPosZ; - RSector* s_colMaxSector; - RSector* s_colMinSector; - RWall* s_colWall0; - JBool s_colResponseStep; - JBool s_objCollisionEnabled = JTRUE; - vec2_fixed s_colResponseDir; - - void console_exportTexture(const std::vector& args); - - /////////////////////////////////////////// - // Implementation - /////////////////////////////////////////// - - // Returns a collision object or nullptr if no object is hit. - SecObject* col_findObjectCollision(RSector* sector) - { - if (!s_aiActive) { return nullptr; } - - fixed16_16 colWidth = s_colWidth; - if (s_objCollisionEnabled) - { - s32 objCount = sector->objectCount; - s32 objCapacity = sector->objectCapacity; - fixed16_16 relHeight = s_colDstPosY - s_colHeightBase; - - fixed16_16 dirX, dirZ; - fixed16_16 pathDz = s_colDstPosZ - s_colSrcPosZ; - fixed16_16 pathDx = s_colDstPosX - s_colSrcPosX; - computeDirAndLength(pathDx, pathDz, &dirX, &dirZ); - - for (s32 objIndex = 0, objListIndex = 0; objIndex < objCount && objListIndex < objCapacity; objListIndex++) - { - SecObject* obj = sector->objectList[objListIndex]; - if (obj) - { - objIndex++; - if (!(obj->entityFlags & ETFLAG_PICKUP) && obj->worldWidth && (s_colSrcPosX != obj->posWS.x || s_colSrcPosZ != obj->posWS.z)) - { - // Check the seperation of the object and destination position. - // If they are seperated by more than their combined widths on the X or Z axis, then there is no collision. - fixed16_16 sepX = TFE_Jedi::abs(obj->posWS.x - s_colDstPosX); - fixed16_16 sepZ = TFE_Jedi::abs(obj->posWS.z - s_colDstPosZ); - fixed16_16 width = obj->worldWidth + colWidth; - if (sepX >= width || sepZ >= width) - { - continue; - } - - // The top of the object is *below* the final position. - fixed16_16 objTop = obj->posWS.y - obj->worldHeight; - if (objTop >= s_colDstPosY || relHeight >= obj->posWS.y) - { - continue; - } - - // Check XZ seperation again... (this second test can be skipped) - sepX = TFE_Jedi::abs(s_colDstPosX - obj->posWS.x); - sepZ = TFE_Jedi::abs(s_colDstPosZ - obj->posWS.z); - if ((sepX >= obj->worldWidth + s_colWidth) || (sepZ >= obj->worldWidth + s_colWidth)) - { - continue; - } - - // Check to see if the path starts already colliding with the object. - // And if it is, then skip collision (so they come apart and don't get stuck). - fixed16_16 startSepX = TFE_Jedi::abs(s_colSrcPosX - obj->posWS.x); - fixed16_16 startSepZ = TFE_Jedi::abs(s_colSrcPosZ - obj->posWS.z); - if (startSepX < width && startSepZ < width) - { - continue; - } - - fixed16_16 dx = s_colDstPosX - s_colSrcPosX; - fixed16_16 dz = s_colDstPosZ - s_colSrcPosZ; - s32 xSign = (dx < 0) ? -1 : 1; - s32 zSign = (dz < 0) ? -1 : 1; - - // Compute the object AABB edges that need to be considered for the collision. - // this is the same as: objEdgeX = obj->posWS.x - obj->worldWidth * xSign; - fixed16_16 objEdgeX = (xSign >= 0) ? (obj->posWS.x - obj->worldWidth) : (obj->posWS.x + obj->worldWidth); - fixed16_16 objEdgeZ = (zSign >= 0) ? (obj->posWS.z - obj->worldWidth) : (obj->posWS.z + obj->worldWidth); - - // Cross product between the vector from the destination to the nearest AABB corner to the start and - // the path direction. - // This is *zero* if the corner is exactly on the path, *negative* if the corner is between the start and destination, - // and *positive* if the point is *past* the destination (i.e. unreachable). - fixed16_16 cprod = mul16(objEdgeX - s_colDstPosX, dirZ) - mul16(objEdgeZ - s_colDstPosZ, dirX); - s32 cSign = cprod < 0 ? -1 : 1; - - // Is the sign of the product different than the sign of either x or z. - s32 signDiff = (cSign^xSign) ^ zSign; - if (signDiff < 0) // condition above is *true* - { - s_colResponseStep = JTRUE; - if (zSign >= 0) - { - s_colResponseAngle = 4095; // ~90 degrees - s_colResponsePos.x = obj->posWS.x - obj->worldWidth; - s_colResponsePos.z = obj->posWS.z - obj->worldWidth; - s_colResponseDir.x = ONE_16; - s_colResponseDir.z = 0; - return obj; - } - else // zSign < 0 - { - s_colResponseAngle = 12287; // ~270 degrees - s_colResponsePos.x = obj->posWS.x + obj->worldWidth; - s_colResponsePos.z = obj->posWS.z + obj->worldWidth; - s_colResponseDir.x = -ONE_16; - s_colResponseDir.z = 0; - - return obj; - } - } - else - { - s_colResponseStep = JTRUE; - if (xSign >= 0) - { - s_colResponseAngle = 8191; // ~180 degrees - s_colResponsePos.x = obj->posWS.x - obj->worldWidth; - s_colResponsePos.z = obj->posWS.z + obj->worldWidth; - s_colResponseDir.x = 0; - s_colResponseDir.z = -ONE_16; - - return obj; - } - else - { - s_colResponseAngle = 0; // 0 degrees - s_colResponsePos.x = obj->posWS.x + obj->worldWidth; - s_colResponsePos.z = obj->posWS.z - obj->worldWidth; - s_colResponseDir.x = 0; - s_colResponseDir.z = ONE_16; - - return obj; - } - } - } - } - } - } - return nullptr; - } - - // Get the "feature" to collide against, such as an object or wall. - // Returns JFALSE if collision else JTRUE - u32 col_getCollisionFeature(RSector* sector, JBool ignore, fixed16_16 yVel) - { - fixed16_16 realFloorHeight = sector->floorHeight; - fixed16_16 realCeilHeight = sector->ceilingHeight; - fixed16_16 extFloorHeight = sector->colFloorHeight; - fixed16_16 extCeilHeight = sector->colCeilHeight; - fixed16_16 curFloor, curCeil; - - // Allows the player to "climb" second heights when jumping. - // Note that always setting the offset will allow players to climb second heights when not jumping as well. - fixed16_16 secHeightOffset = yVel < 0 ? COL_SEC_HEIGHT_OFFSET : 0; - - if (sector->secHeight < 0 && s_colDstPosY > sector->colSecHeight + secHeightOffset) - { - curFloor = extFloorHeight; - curCeil = realFloorHeight + sector->secHeight; - } - else - { - curFloor = sector->colSecHeight; - curCeil = sector->colSecCeilHeight; - } - - s_colRealFloorHeight = min(realFloorHeight, s_colRealFloorHeight); - s_colRealCeilHeight = max(realCeilHeight, s_colRealCeilHeight); - s_colExtFloorHeight = min(extFloorHeight, s_colExtFloorHeight); - s_colExtCeilHeight = max(extCeilHeight, s_colExtCeilHeight); - s_colCurLowestFloor = min(curFloor, s_colCurLowestFloor); - s_colCurHighestCeil = max(curCeil, s_colCurHighestCeil); - - if (s_colCurHighestCeil > s_colCurTop) - { - s_colCurTop = s_colCurHighestCeil; - s_colMaxSector = sector; - } - if (s_colCurLowestFloor < s_colCurBot) - { - s_colCurBot = s_colCurLowestFloor; - s_colMinSector = sector; - } - - if (ignore || (s_colCurBot >= s_colBottom && s_colCurTop <= s_colTop && TFE_Jedi::abs(s_colCurBot - s_colCurTop) >= s_colHeight && curFloor <= s_colY1)) - { - s_collidedObj = col_findObjectCollision(sector); - if (s_collidedObj) - { - return JFALSE; - } - RWall* wall = sector->walls; - s32 wallCount = sector->wallCount; - sector->collisionFrame = s_collisionFrameSector; - for (s32 i = 0; i < wallCount; i++, wall++) - { - s_colWallV0 = *wall->w0; - fixed16_16 length = wall->length; - - JBool canPass = JFALSE; - // Note WF3_ALWAYS_WALK overrides WF3_SOLID_WALL. - if ((wall->flags3 & (WF3_ALWAYS_WALK | WF3_SOLID_WALL)) != WF3_SOLID_WALL && wall->nextSector) - { - canPass = JTRUE; - } - - // Given line: (v0, v1) and position (p) compute the distance from the line: - // dist = (p - v0).N; where N = (dz, -dx) = wall normal. - fixed16_16 dist = mul16(s_colDstPosX - s_colWallV0.x, wall->wallDir.z) - mul16(s_colDstPosZ - s_colWallV0.z, wall->wallDir.x); - // Convert to unsigned distance. - if (dist < 0) { dist = -dist; } - // Further checks can be avoided if the position is too far from the line to collide. - if (dist < s_colWidth) - { - // Project s_colDstPosX/Z onto the wall, i.e. - // u = (p-v0).D; where D = direction and v = v0 + u*D - fixed16_16 u = mul16(s_colDstPosX - s_colWallV0.x, wall->wallDir.x) + mul16(s_colDstPosZ - s_colWallV0.z, wall->wallDir.z); - fixed16_16 maxEdge = u + s_colWidth; - fixed16_16 maxCol = length + s_colDoubleRadius; - if ((u >= 0 && u <= length) || (maxEdge >= 0 && maxEdge <= maxCol)) - { - JBool sideTest = JTRUE; - if (canPass) - { - RSector* next = wall->nextSector; - fixed16_16 srcY = s_colSrcPosY; - fixed16_16 secHeight = next->colSecHeight; - // If the path starts *above* the second height and then ends at or *below* it. - if (srcY <= secHeight && s_colY1 >= secHeight && s_colTop > next->colSecCeilHeight) - { - sideTest = JFALSE; - } - } - // Skip the side test if dealing with a passable wall. - if (sideTest) - { - // Make sure the start point is in front side of the wall. - // side = (s_colSrcPos - s_colWallV0) x (wallDir) - fixed16_16 side = mul16(s_colSrcPosX - s_colWallV0.x, wall->wallDir.z) - mul16(s_colSrcPosZ - s_colWallV0.z, wall->wallDir.x); - if (side < 0) - { - // We hit the back side of the wall. - continue; - } - fixed16_16 x1 = s_colDstPosX; - fixed16_16 z1 = s_colDstPosZ; - fixed16_16 z0 = s_colSrcPosZ; - fixed16_16 x0 = s_colSrcPosX; - fixed16_16 dz = z1 - z0; - fixed16_16 dx = x1 - x0; - // Check to see if the movement direction is not moving *away* from the wall. - side = mul16(dx, wall->wallDir.z) - mul16(dz, wall->wallDir.x); - if (side > 0) - { - // The collision path is moving away from the wall. - continue; - } - } - - // This wall might be passable. - if (canPass) - { - RSector* next = wall->nextSector; - fixed16_16 nextFloor = (next->secHeight >= 0) ? next->colSecHeight : next->floorHeight; - // Check to see if the object fits between the next sector floor and ceiling. - if ((wall->flags3 & (WF3_ALWAYS_WALK | WF3_SOLID_WALL)) != WF3_ALWAYS_WALK) - { - if (s_colBottom > nextFloor) - { - s_colWallCollided = wall; - return JFALSE; - } - if (s_colTop < next->colSecCeilHeight) - { - s_colWallCollided = wall; - return JFALSE; - } - } - // Check to see if this sector has already been tested this "collision frame" - if (s_collisionFrameSector != next->collisionFrame) - { - JBool nextIgnore = (wall->flags3 & (WF3_ALWAYS_WALK | WF3_SOLID_WALL)) == WF3_ALWAYS_WALK ? JTRUE : JFALSE; - if (!col_getCollisionFeature(next, nextIgnore, yVel)) - { - if (!s_colWallCollided) { s_colWallCollided = wall; } - return JFALSE; - } - } - continue; - } - else // !canPass - { - s_colWallCollided = wall; - return JFALSE; - } - } - } - } - return JTRUE; - } - s_colObj1.sector = sector; - return JFALSE; - } - - // Returns JFALSE if there was a collision. - JBool col_computeCollisionResponse(RSector* sector, fixed16_16 yVel) - { - s_colRealFloorHeight = COL_INFINITY; - s_colRealCeilHeight = -COL_INFINITY; - s_colExtFloorHeight = COL_INFINITY; - s_colExtCeilHeight = -COL_INFINITY; - s_colCurLowestFloor = COL_INFINITY; - s_colCurHighestCeil = -COL_INFINITY; - s_colCurBot = COL_INFINITY; - s_colCurTop = -COL_INFINITY; - - s_collisionFrameSector++; - s_colWallCollided = nullptr; - s_colDoubleRadius = s_colWidth + s_colWidth; - s_colResponseStep = JFALSE; - // Is there a collision? - if (!col_getCollisionFeature(sector, JFALSE, yVel)) - { - s_colWall0 = s_colWallCollided; - if (s_colWall0) - { - s_colResponseStep = JTRUE; - s_colResponseDir = s_colWall0->wallDir; - s_colResponseAngle = s_colWall0->angle; - s_colResponsePos = *s_colWall0->w0; - } - return JFALSE; - } - return JTRUE; - } - - void handleCollisionResponse(fixed16_16 dirX, fixed16_16 dirZ, fixed16_16 posX, fixed16_16 posZ) - { - SecObject* obj = s_curPlayerLogic->logic.obj; - // Project the movement vector onto the wall direction to get how much sliding movement is left. - fixed16_16 proj = mul16(s_curPlayerLogic->move.x, dirX) + mul16(s_curPlayerLogic->move.z, dirZ); - - // Normal = (dirZ, -dirX) - // -P.Normal - fixed16_16 dx = obj->posWS.x - posX; - fixed16_16 dz = obj->posWS.z - posZ; - fixed16_16 planarDist = mul16(dx, dirZ) - mul16(dz, dirX); - - fixed16_16 r = obj->worldWidth + 65; // worldWidth + 0.001 - // if overlap is > 0, the player cylinder is embedded in the wall. - fixed16_16 overlap = r - planarDist; - if (overlap >= 0) - { - // push at a rate of 4 units / second. - fixed16_16 pushSpd = FIXED(4); - // make sure the overlap adjustment is at least the size of the "push" - overlap = min(overlap, mul16(pushSpd, s_deltaTime)); - s_colCurBot = obj->sector->floorHeight; - } - // Move along 'overlap' so that the cylinder is nearly touching and move along move direction based on projection. - // This has the effect of attracting or pushing the object in order to remove the gap or overlap. - s_curPlayerLogic->move.x = mul16(overlap, dirZ) + mul16(proj, dirX); - s_curPlayerLogic->move.z = -mul16(overlap, dirX) + mul16(proj, dirZ); - } - - // Returns JTRUE in the case of a collision, otherwise returns JFALSE. - JBool handlePlayerCollision(PlayerLogic* playerLogic, fixed16_16 yVel) - { - s_curPlayerLogic = playerLogic; - SecObject* obj = playerLogic->logic.obj; - s_colObject.obj = obj; - - s_colSrcPosX = obj->posWS.x; - s_colDstPosY = obj->posWS.y; - fixed16_16 z = obj->posWS.z; - s_colWidth = obj->worldWidth; - - s_colHeightBase = obj->worldHeight; - s_colSrcPosY = obj->posWS.y; - - // Handles maximum stair height. - // This has to be adjusted to handle differences between odd and even tick counts - // due to small differences in how high the player can reach before gravity kicks in. - // Note anything much over 60fps no longer needs the delta. - const fixed16_16 tickAdj = s_deltaTime > COL_BOT_ADJ_THRESHOLD ? COL_BOT_ADJ : 0; - s_colBottom = obj->posWS.y - playerLogic->stepHeight - tickAdj; - - s_colSrcPosZ = obj->posWS.z; - s_colTop = obj->posWS.y - obj->worldHeight - ONE_16; - - s_colY1 = COL_INFINITY; - s_colHeight = obj->worldHeight + HALF_16; // this is 1.0 is DOS, but needs to be lowered in TFE due to framerate differences. - RSector* sector = obj->sector; - - s_colWall0 = nullptr; - s_colObj1.ptr = nullptr; - - s_colDstPosX = obj->posWS.x + playerLogic->move.x; - s_colDstPosZ = obj->posWS.z + playerLogic->move.z; - - // If there was no collision, return false. - if (col_computeCollisionResponse(sector, yVel)) - { - return JFALSE; - } - if (s_colResponseStep) - { - handleCollisionResponse(s_colResponseDir.x, s_colResponseDir.z, s_colResponsePos.x, s_colResponsePos.z); - } - return JTRUE; - } - - // Attempts to move the player. Note that collision detection has already occured accounting for step height, - // objects, collision reponse, etc.. So this is a more basic collision detection function to validate the - // results and fire off INF_EVENT_CROSS_LINE_XXX events as needed. - JBool playerMove(JBool alwaysMove) - { - SecObject* player = s_playerObject; - fixed16_16 ceilHeight; - fixed16_16 floorHeight; - sector_getObjFloorAndCeilHeight(player->sector, player->posWS.y, &floorHeight, &ceilHeight); - - fixed16_16 finalCeilHeight = ceilHeight; - fixed16_16 finalFloorHeight = floorHeight; - - fixed16_16 x0 = player->posWS.x; - fixed16_16 z0 = player->posWS.z; - fixed16_16 x1 = x0 + s_curPlayerLogic->move.x; - fixed16_16 z1 = z0 + s_curPlayerLogic->move.z; - RSector* nextSector = player->sector; - RWall* wall = collision_wallCollisionFromPath(player->sector, x0, z0, x1, z1); - while (wall) - { - RSector* adjoinSector = wall->nextSector; - // If the player collides with a wall, nextSector will be set to null, which means that the movement is not applied. - nextSector = nullptr; - if (adjoinSector && (!(wall->flags3&WF3_SOLID_WALL) || alwaysMove)) - { - if (!s_playerDying) - { - inf_triggerWallEvent(wall, s_playerObject, INF_EVENT_CROSS_LINE_FRONT); - } - nextSector = adjoinSector; - sector_getObjFloorAndCeilHeight(adjoinSector, player->posWS.y, &floorHeight, &ceilHeight); - - // Current ceiling is higher than the adjoining sector, meaning there is an upper wall part. - finalCeilHeight = max(ceilHeight, finalCeilHeight); - // Current floor is lower than the adjoining sector, meaning there is a lower wall part. - finalFloorHeight = min(floorHeight, finalFloorHeight); - wall = collision_pathWallCollision(adjoinSector); - // Handle the no clip cheat. - if (alwaysMove && wall && !wall->nextSector) - { - wall = nullptr; - } - } - else - { - wall = nullptr; - } - } - // nextSector will be null if the collision failed, in which case we don't move the player and return false. - if (nextSector || alwaysMove) - { - fixed16_16 stepLimit = player->posWS.y - s_curPlayerLogic->stepHeight; - fixed16_16 topLimit = player->posWS.y - player->worldHeight - ONE_16; - // If the player cannot fit, then again we don't move the player and return false. - if ((finalFloorHeight >= stepLimit && finalCeilHeight <= topLimit) || alwaysMove) - { - // The collision was a success! - // Move the player, change sectors if needed and adjust the map layer. - player->posWS.x += s_curPlayerLogic->move.x; - player->posWS.z += s_curPlayerLogic->move.z; - - if (alwaysMove) - { - if (nextSector && !sector_pointInsideDF(nextSector, player->posWS.x, player->posWS.z)) - { - nextSector = nullptr; - } - if (!nextSector) - { - nextSector = sector_which3D(player->posWS.x, player->posWS.y, player->posWS.z); - } - } - if (nextSector) - { - RSector* curSector = player->sector; - if (nextSector != curSector) - { - if (nextSector->layer != curSector->layer) - { - automap_setLayer(nextSector->layer); - } - sector_addObject(nextSector, player); - } - } - return JTRUE; - } - } - return JFALSE; - } - - JBool handleCollisionFunc(RSector* sector) - { - if (!s_objCollisionFunc || s_objCollisionFunc(sector)) - { - sector->collisionFrame = s_collisionFrameSector; - - RWall* wall = sector->walls; - s32 wallCount = sector->wallCount; - for (s32 i = 0; i < wallCount; i++, wall++) - { - vec2_fixed* w0 = wall->w0; - s_colWallV0.x = w0->x; - s_colWallV0.z = w0->z; - - fixed16_16 length = wall->length; - fixed16_16 dx = s_colDstPosZ - s_colWallV0.z; - fixed16_16 dz = s_colDstPosX - s_colWallV0.x; - - fixed16_16 pz = mul16(dz, wall->wallDir.z); - fixed16_16 px = mul16(dx, wall->wallDir.x); - - fixed16_16 dp = pz - px; - fixed16_16 adp = TFE_Jedi::abs(dp); - if (adp <= s_colWidth) - { - fixed16_16 paramPos = TFE_Jedi::abs(mul16(dx, wall->wallDir.z) + mul16(dz, wall->wallDir.x)); - if (paramPos > length) - { - if (paramPos + s_colWidth > length + s_colDoubleRadius) - { - continue; - } - } - if (s_objCollisionProxFunc && !s_objCollisionProxFunc()) - { - return JFALSE; - } - RSector* nextSector = wall->nextSector; - if (nextSector) - { - if ((wall->flags3 & (WF3_ALWAYS_WALK | WF3_SOLID_WALL)) != WF3_SOLID_WALL) - { - if (s_collisionFrameSector != nextSector->collisionFrame) - { - if (!handleCollisionFunc(nextSector)) - { - return JFALSE; - } - } - } - } - } - } - } - return JTRUE; - } - - void playerHandleCollisionFunc(RSector* sector, CollisionObjFunc func, CollisionProxFunc proxFunc) - { - s_objCollisionFunc = func; - s_colDoubleRadius = s_colWidth * 2; - s_objCollisionProxFunc = proxFunc; - s_collisionFrameSector++; - handleCollisionFunc(sector); - } - - JBool collision_handleCrushing(RSector* sector) - { - message_sendToSector(sector, s_playerObject, 0, MSG_CRUSH); - return JTRUE; - } - - JBool collision_checkPickups(RSector* sector) - { - fixed16_16 floorHeight = sector->floorHeight; - fixed16_16 ceilHeight = sector->ceilingHeight; - if (floorHeight == ceilHeight) { return JFALSE; } - - s32 objCount = sector->objectCount; - s32 objCapacity = sector->objectCapacity; - for (s32 objIndex = 0, objListIndex = 0; objIndex < objCount && objListIndex < objCapacity; objListIndex++) - { - SecObject* obj = sector->objectList[objListIndex]; - if (obj) - { - objIndex++; - if (obj->worldWidth && (obj->entityFlags & ETFLAG_PICKUP)) - { - fixed16_16 dx = obj->posWS.x - s_colDstPosX; - fixed16_16 dz = obj->posWS.z - s_colDstPosZ; - fixed16_16 adx = TFE_Jedi::abs(dx); - fixed16_16 adz = TFE_Jedi::abs(dz); - fixed16_16 radius = obj->worldWidth + s_colWidth; - if (adx < radius && adz < radius) - { - fixed16_16 objTop = obj->posWS.y - obj->worldHeight; - fixed16_16 colliderTop = s_colDstPosY - s_colHeightBase; - if (objTop < s_colDstPosY && colliderTop < obj->posWS.y) - { - s_msgEntity = s_colObject.obj; - message_sendToObj(obj, MSG_PICKUP, nullptr); - } - } - } - } - } - return JTRUE; - } - - // TFE - static std::vector s_exportBuffer; - - void initPlayerCollision() - { - CCMD("exportTexture", console_exportTexture, 0, "Export the texture at the center of the screen."); - } - - const char* getTextureName(TextureData* hitTex) - { - AssetPool pool; - s32 index; - if (bitmap_getTextureIndex(hitTex, &index, &pool)) - { - return bitmap_getTextureName(index, pool); - } - - if (hitTex->animIndex >= 0) - { - return bitmap_getTextureName(hitTex->animIndex, POOL_LEVEL); - } - return nullptr; - } - - void console_exportTexture(const std::vector& args) - { - // Raycast to determine the wall, floor, or ceiling hit. - const SecObject* playerObj = s_curPlayerLogic->logic.obj; - const vec3_fixed p0 = { floatToFixed16(s_cameraPos.x), floatToFixed16(s_cameraPos.y), floatToFixed16(s_cameraPos.z) }; - const vec3_fixed p1 = { p0.x + floatToFixed16(TFE_Jedi::s_cameraDir.x * 100.0f), - p0.y + floatToFixed16(TFE_Jedi::s_cameraDir.y * 100.0f), p0.z + floatToFixed16(TFE_Jedi::s_cameraDir.z * 100.0f) }; - - const RayHitInfo hitInfo = collision_rayCast3d(playerObj->sector, p0, p1, true); - TextureData* hitTex = nullptr; - if (hitInfo.hit == RHit_Floor) - { - hitTex = hitInfo.sector->floorTex ? *hitInfo.sector->floorTex : nullptr; - } - else if (hitInfo.hit == RHit_Ceiling) - { - hitTex = hitInfo.sector->ceilTex ? *hitInfo.sector->ceilTex : nullptr; - } - else if (hitInfo.hit == RHit_WallMid || hitInfo.hit == RHit_WallMid_Trans) - { - hitTex = hitInfo.wall->midTex ? *hitInfo.wall->midTex : nullptr; - } - else if (hitInfo.hit == RHit_WallBot) - { - hitTex = hitInfo.wall->botTex ? *hitInfo.wall->botTex : nullptr; - } - else if (hitInfo.hit == RHit_WallTop) - { - hitTex = hitInfo.wall->topTex ? *hitInfo.wall->topTex : nullptr; - } - else if (hitInfo.hit == RHit_WallSign) - { - hitTex = hitInfo.wall->signTex ? *hitInfo.wall->signTex : nullptr; - } - if (!hitTex) { return; } - - // Now export the texture. - const char* name = getTextureName(hitTex); - if (name) - { - // Create a folder - FileUtil::makeDirectory("Exports"); - - char msg[TFE_MAX_PATH]; - sprintf(msg, "Exported texture to 'Exports/%s'", name); - TFE_Console::addToHistory(msg); - - // Write the original BM to the current directory. - FilePath path; - if (TFE_Paths::getFilePath(name, &path)) - { - // Load the data. - FileStream file; - if (!file.open(&path, Stream::MODE_READ)) { return; } - s_exportBuffer.resize(file.getSize()); - file.readBuffer(s_exportBuffer.data(), (u32)file.getSize()); - file.close(); - - // Write it out to disk. - char outputName[TFE_MAX_PATH]; - sprintf(outputName, "Exports/%s", name); - if (file.open(outputName, Stream::MODE_WRITE)) - { - file.writeBuffer(s_exportBuffer.data(), (u32)s_exportBuffer.size()); - file.close(); - } - } - - // Write out a PNG of the original texture. - char baseName[TFE_MAX_PATH]; - char outputName[TFE_MAX_PATH]; - FileUtil::getFileNameFromPath(name, baseName); - sprintf(outputName, "Exports/%s.png", baseName); - - s_exportBuffer.resize(4 * hitTex->width * hitTex->height); - u32* outBuffer = (u32*)s_exportBuffer.data(); - // Use the current palette. - const u32* pal = TFE_RenderBackend::getPalette(); - const u32 pixelCount = hitTex->width * hitTex->height; - for (u32 i = 0; i < pixelCount; i++) - { - const u32 x = i % hitTex->width; - const u32 y = i / hitTex->width; - const u8 color = hitTex->image[x * hitTex->height + y]; - outBuffer[i] = pal[color]; - if ((hitInfo.hit == RHit_WallMid_Trans || hitInfo.hit == RHit_WallSign) && color == 0) - { - outBuffer[i] = 0; - } - } - TFE_Image::writeImage(outputName, hitTex->width, hitTex->height, outBuffer); - - // Now write the generated emissive map. - sprintf(outputName, "Exports/%s_mtl.png", baseName); - outBuffer = (u32*)s_exportBuffer.data(); - const u32 white = 0xffffffff; - const u32 black = 0xff000000; - for (u32 i = 0; i < pixelCount; i++) - { - const u32 x = i % hitTex->width; - const u32 y = i / hitTex->width; - const u8 color = hitTex->image[x * hitTex->height + y]; - outBuffer[i] = (color > 0 && color < 32) ? white : black; - } - TFE_Image::writeImage(outputName, hitTex->width, hitTex->height, outBuffer); - } - } -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/playerCollision.h b/components/darkforces/tfe/TFE_DarkForces/playerCollision.h deleted file mode 100644 index bd7d6221..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/playerCollision.h +++ /dev/null @@ -1,44 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces Player Collision -////////////////////////////////////////////////////////////////////// - -#include -#include -#include "logic.h" -#include "playerLogic.h" - -namespace TFE_DarkForces -{ - typedef JBool(*CollisionObjFunc)(RSector*); - typedef JBool(*CollisionProxFunc)(); - - void initPlayerCollision(); - - JBool collision_handleCrushing(RSector* sector); - JBool collision_checkPickups(RSector* sector); - JBool handleCollisionFunc(RSector* sector); - void playerHandleCollisionFunc(RSector* sector, CollisionObjFunc func, CollisionProxFunc proxFunc); - - JBool handlePlayerCollision(PlayerLogic* playerLogic, fixed16_16 yVel); - JBool col_computeCollisionResponse(RSector* sector, fixed16_16 yVel); - JBool playerMove(JBool alwaysMove); - - extern fixed16_16 s_colWidth; - extern fixed16_16 s_colDstPosX; - extern fixed16_16 s_colDstPosY; - extern fixed16_16 s_colDstPosZ; - - extern fixed16_16 s_colCurLowestFloor; - extern fixed16_16 s_colCurHighestCeil; - extern fixed16_16 s_colCurBot; - extern fixed16_16 s_colExtCeilHeight; - extern fixed16_16 s_colExtFloorHeight; - - extern RSector* s_colMinSector; - extern RSector* s_colMaxSector; - extern RWall* s_colWall0; - extern vec2_fixed s_colResponseDir; - extern JBool s_colResponseStep; - extern JBool s_objCollisionEnabled; -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/playerLogic.h b/components/darkforces/tfe/TFE_DarkForces/playerLogic.h deleted file mode 100644 index 89218335..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/playerLogic.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces Player - -// Player information and object data. -////////////////////////////////////////////////////////////////////// - -#include -#include "logic.h" - -namespace TFE_DarkForces -{ - struct PlayerLogic - { - Logic logic; - - vec2_fixed dir; - vec3_fixed move; - fixed16_16 stepHeight; - }; -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/projectile.cpp b/components/darkforces/tfe/TFE_DarkForces/projectile.cpp deleted file mode 100644 index 569a951f..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/projectile.cpp +++ /dev/null @@ -1,1745 +0,0 @@ -#include "projectile.h" -#include "animLogic.h" -#include "random.h" -#include "player.h" -#include "sound.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - ////////////////////////////////////////////////////////////// - // Structures and Constants - ////////////////////////////////////////////////////////////// - enum ProjectileConstants - { - PROJ_GRAVITY_ACCEL = FIXED(120), // Gravity acceleration = 120.0 units / s^2 - PL_LANDMINE_TRIGGER_RADIUS = FIXED(20), // Pre-placed landmine trigger radius. - WP_LANDMINE_TRIGGER_RADIUS = FIXED(15), // Player Weapon landmine trigger radius. - CAMERA_SOUND_RANGE = FIXED(15), // At this distance, the projectile plays its "near camera" sound. - HOMING_MISSILE_EXPLODE_RNG = FIXED(8), // The approximate distance when a homing missile might explode early. - MAX_HOMING_ANGULAR_VEL = 9102, // Maximum angle change per second: ~200 degrees / second. - HOMING_ANGULAR_ACCEL = 1820, // Rate at which homing speed increases in angular units / second: ~40 degrees / second. - HOMING_PITCH_ZERO_MIN = 2047, // Range of pitch angles that are mapped to zero degrees. - HOMING_PITCH_ZERO_MAX = 14335, // Range of pitch angles that are mapped to zero degrees. - PROJ_PATH_MAX_SECTORS = 16, // The maximum number of sectors in a projectile path (i.e. how many sectors can a projectile cross in a single frame). - }; - - ////////////////////////////////////////////////////////////// - // Internal State - ////////////////////////////////////////////////////////////// - static Allocator* s_projectiles = nullptr; - - static JediModel* s_boltModel; - static JediModel* s_greenBoltModel; - static Wax* s_plasmaProj; - static WaxFrame* s_repeaterProj; - static Wax* s_mortarProj; - static Wax* s_missileProj; - static Wax* s_cannonProj; - static Wax* s_probeProj; - static Wax* s_homingMissileProj; - static Wax* s_bobafetBall; - static WaxFrame* s_landmineWpnFrame; - static WaxFrame* s_landmineFrame; - static WaxFrame* s_thermalDetProj; - - static SoundSourceId s_stdProjCameraSnd = NULL_SOUND; - static SoundSourceId s_stdProjReflectSnd = NULL_SOUND; - static SoundSourceId s_thermalDetReflectSnd = NULL_SOUND; - static SoundSourceId s_plasmaCameraSnd = NULL_SOUND; - static SoundSourceId s_plasmaReflectSnd = NULL_SOUND; - static SoundSourceId s_missileLoopingSnd = NULL_SOUND; - static SoundSourceId s_landMineTriggerSnd = NULL_SOUND; - static SoundSourceId s_bobaBallCameraSnd = NULL_SOUND; - static SoundSourceId s_homingMissileFlightSnd = NULL_SOUND; - - static RSector* s_projPath[PROJ_PATH_MAX_SECTORS]; - static RSector* s_projSector; - static s32 s_projIter; - static fixed16_16 s_projNextPosX; - static fixed16_16 s_projNextPosY; - static fixed16_16 s_projNextPosZ; - static JBool s_hitWater; - static RWall* s_hitWall; - - // Projectile specific collisions - static RSector* s_colObjSector; - static SecObject* s_colHitObj; - static fixed16_16 s_colObjAdjX; - static fixed16_16 s_colObjAdjY; - static fixed16_16 s_colObjAdjZ; - - // Task - static Task* s_projectileTask = nullptr; - - WallHitFlag s_hitWallFlag = WH_IGNORE; - angle14_32 s_projReflectOverrideYaw = 0; - - ////////////////////////////////////////////////////////////// - // Forward Declarations - ////////////////////////////////////////////////////////////// - void projectileLogicCleanupFunc(Logic* logic); - void proj_setTransform(ProjectileLogic* logic, angle14_32 pitch, angle14_32 yaw); - JBool proj_move(ProjectileLogic* logic); - JBool proj_getHitObj(ProjectileLogic* logic); - - ProjectileHitType stdProjectileUpdateFunc(ProjectileLogic* logic); - ProjectileHitType landMineUpdateFunc(ProjectileLogic* logic); - ProjectileHitType arcingProjectileUpdateFunc(ProjectileLogic* logic); - ProjectileHitType homingMissileProjectileUpdateFunc(ProjectileLogic* logic); - - void projectileTaskFunc(MessageType msg); - - static ProjectileFunc c_projUpdateFunc[] = - { - stdProjectileUpdateFunc, - landMineUpdateFunc, - arcingProjectileUpdateFunc, - homingMissileProjectileUpdateFunc - }; - - ////////////////////////////////////////////////////////////// - // API Implementation - ////////////////////////////////////////////////////////////// - void projectile_startup() - { - s_boltModel = TFE_Model_Jedi::get("wrbolt.3do", POOL_GAME); - s_thermalDetProj = TFE_Sprite_Jedi::getFrame("wdet.fme", POOL_GAME); - s_repeaterProj = TFE_Sprite_Jedi::getFrame("bullet.fme", POOL_GAME); - s_plasmaProj = TFE_Sprite_Jedi::getWax("wemiss.wax", POOL_GAME); - s_mortarProj = TFE_Sprite_Jedi::getWax("wshell.wax", POOL_GAME); - s_landmineWpnFrame = TFE_Sprite_Jedi::getFrame("wmine.fme", POOL_GAME); - s_cannonProj = TFE_Sprite_Jedi::getWax("wplasma.wax", POOL_GAME); - s_missileProj = TFE_Sprite_Jedi::getWax("wmsl.wax", POOL_GAME); - s_landmineFrame = TFE_Sprite_Jedi::getFrame("wlmine.fme", POOL_GAME); - s_greenBoltModel = TFE_Model_Jedi::get("wgbolt.3do", POOL_GAME); - s_probeProj = TFE_Sprite_Jedi::getWax("widball.wax", POOL_GAME); - s_homingMissileProj = TFE_Sprite_Jedi::getWax("wdt3msl.wax", POOL_GAME); - s_bobafetBall = TFE_Sprite_Jedi::getWax("bobaball.wax", POOL_GAME); - - s_stdProjReflectSnd = sound_load("boltref1.voc", SOUND_PRIORITY_LOW1); - s_thermalDetReflectSnd = sound_load("thermal1.voc", SOUND_PRIORITY_LOW1); - s_plasmaReflectSnd = sound_load("bigrefl1.voc", SOUND_PRIORITY_LOW1); - s_stdProjCameraSnd = sound_load("lasrby.voc", SOUND_PRIORITY_LOW3); - s_plasmaCameraSnd = sound_load("emisby.voc", SOUND_PRIORITY_LOW3); - s_missileLoopingSnd = sound_load("rocket-1.voc", SOUND_PRIORITY_LOW3); - s_homingMissileFlightSnd = sound_load("tracker.voc", SOUND_PRIORITY_LOW3); - s_bobaBallCameraSnd = sound_load("fireball.voc", SOUND_PRIORITY_LOW3); - s_landMineTriggerSnd = sound_load("beep-10.voc", SOUND_PRIORITY_HIGH3); - } - - void projectile_clearState() - { - s_projectiles = nullptr; - s_projectileTask = nullptr; - s_projReflectOverrideYaw = 0; - } - - void projectile_createTask() - { - projectile_clearState(); - s_projectiles = allocator_create(sizeof(ProjectileLogic)); - s_projectileTask = createSubTask("projectiles", projectileTaskFunc); - } - - // TODO: Move projectile data to an external file to avoid hardcoding it for TFE. - Logic* createProjectile(ProjectileType type, RSector* sector, fixed16_16 x, fixed16_16 y, fixed16_16 z, SecObject* obj) - { - ProjectileLogic* projLogic = (ProjectileLogic*)allocator_newItem(s_projectiles); - SecObject* projObj = allocateObject(); - - projObj->entityFlags |= ETFLAG_PROJECTILE; - projObj->flags &= ~OBJ_FLAG_MOVABLE; - projObj->projectileLogic = projLogic; - - projLogic->prevColObj = nullptr; - projLogic->excludeObj = nullptr; - projLogic->reflVariation = 0; - projLogic->cameraPassSnd = NULL_SOUND; - projLogic->flightSndSource = NULL_SOUND; - projLogic->flightSndId = NULL_SOUND; - projLogic->reflectSnd = NULL_SOUND; - projLogic->flags = PROJFLAG_CAMERA_PASS_SOUND; - projLogic->prevObj = obj; // 'obj' gets deleted after this function is called so this is likely a bug. - projLogic->vel.x = 0; - projLogic->vel.y = 0; - projLogic->vel.z = 0; - projLogic->minDmg = 0; - - obj_addLogic(projObj, (Logic*)projLogic, LOGIC_PROJECTILE, s_projectileTask, projectileLogicCleanupFunc); - - switch (type) - { - case PROJ_PUNCH: - { - spirit_setData(projObj); - - projLogic->type = PROJ_PUNCH; - projLogic->updateFunc = stdProjectileUpdateFunc; - projLogic->dmg = FIXED(6); - projLogic->falloffAmt = 0; - projLogic->projForce = 1310; - projLogic->speed = FIXED(230); - projLogic->horzBounciness = 0; - projLogic->vertBounciness = 0; - projLogic->bounceCnt = 0; - projLogic->reflectEffectId = HEFFECT_NONE; - projLogic->hitEffectId = HEFFECT_NONE; - projLogic->duration = s_curTick; - } break; - case PROJ_PISTOL_BOLT: - { - if (s_boltModel) - { - obj3d_setData(projObj, s_boltModel); - } - projObj->flags |= OBJ_FLAG_FULLBRIGHT; - projObj->worldWidth = 0; - - projLogic->type = PROJ_PISTOL_BOLT; - projLogic->updateFunc = stdProjectileUpdateFunc; - projLogic->dmg = FIXED(10); - projLogic->minDmg = ONE_16; - projLogic->falloffAmt = ONE_16; - projLogic->dmgFalloffDelta = 14; - - projLogic->projForce = 655; - projLogic->speed = FIXED(250); - projLogic->horzBounciness = ONE_16; - projLogic->vertBounciness = ONE_16; - projLogic->bounceCnt = 3; - projLogic->reflVariation = 9; - projLogic->nextFalloffTick = s_curTick + 14; // ~0.1 seconds - projLogic->reflectEffectId = HEFFECT_SMALL_EXP; - projLogic->hitEffectId = HEFFECT_SMALL_EXP; - projLogic->duration = s_curTick + 436; // ~3 seconds - projLogic->cameraPassSnd = s_stdProjCameraSnd; - projLogic->reflectSnd = s_stdProjReflectSnd; - } break; - case PROJ_RIFLE_BOLT: - { - if (s_boltModel) - { - obj3d_setData(projObj, s_boltModel); - } - projObj->flags |= OBJ_FLAG_FULLBRIGHT; - projObj->worldWidth = 0; - - projLogic->type = PROJ_RIFLE_BOLT; - projLogic->updateFunc = stdProjectileUpdateFunc; - projLogic->dmg = FIXED(10); - projLogic->minDmg = ONE_16; - projLogic->falloffAmt = 52428; // 0.8 damage - projLogic->dmgFalloffDelta = 14; - - projLogic->projForce = 655; - projLogic->speed = FIXED(250); - projLogic->horzBounciness = ONE_16; - projLogic->vertBounciness = ONE_16; - projLogic->bounceCnt = 3; - projLogic->reflVariation = 9; - projLogic->nextFalloffTick = s_curTick + 14; // ~0.1 seconds - projLogic->reflectEffectId = HEFFECT_SMALL_EXP; - projLogic->hitEffectId = HEFFECT_SMALL_EXP; - projLogic->duration = s_curTick + 582; // ~4 seconds - projLogic->cameraPassSnd = s_stdProjCameraSnd; - projLogic->reflectSnd = s_stdProjReflectSnd; - } break; - case PROJ_THERMAL_DET: - { - if (s_thermalDetProj) - { - frame_setData(projObj, s_thermalDetProj); - } - projObj->flags |= OBJ_FLAG_MOVABLE; - projObj->worldWidth = 0; - - projLogic->flags |= PROJFLAG_EXPLODE; - projLogic->type = PROJ_THERMAL_DET; - projLogic->updateFunc = arcingProjectileUpdateFunc; - projLogic->dmg = 0; - projLogic->minDmg = ONE_16; - projLogic->falloffAmt = 0; - projLogic->dmgFalloffDelta = 0; - - projLogic->projForce = 6553; - projLogic->speed = FIXED(80); - projLogic->horzBounciness = 29491; // 0.45 - projLogic->vertBounciness = 58327; // 0.89 - projLogic->bounceCnt = -1; - projLogic->reflectEffectId = HEFFECT_NONE; - projLogic->hitEffectId = HEFFECT_THERMDET_EXP; - projLogic->duration = s_curTick + 436; // ~3 seconds - projLogic->cameraPassSnd = NULL_SOUND; - projLogic->reflectSnd = s_thermalDetReflectSnd; - } break; - case PROJ_REPEATER: - { - if (s_repeaterProj) - { - frame_setData(projObj, s_repeaterProj); - } - projObj->flags |= OBJ_FLAG_FULLBRIGHT; - projObj->worldWidth = 0; - - projLogic->type = PROJ_REPEATER; - projLogic->updateFunc = stdProjectileUpdateFunc; - projLogic->dmg = FIXED(10); - projLogic->minDmg = ONE_16; - projLogic->falloffAmt = 19660; // 0.3 damage - projLogic->dmgFalloffDelta = 19660; // 135 seconds, this probably should have been 0.3 seconds, or 43 - - projLogic->projForce = 1966; - projLogic->speed = FIXED(270); - projLogic->horzBounciness = 0; - projLogic->vertBounciness = 0; - projLogic->bounceCnt = 3; - projLogic->reflVariation = 9; - projLogic->nextFalloffTick = s_curTick + 19660; // ~135 seconds, should have been ~0.3 seconds. - projLogic->reflectEffectId = HEFFECT_NONE; - projLogic->hitEffectId = HEFFECT_REPEATER_EXP; - projLogic->duration = s_curTick + 582; // ~4 seconds - projLogic->cameraPassSnd = s_stdProjCameraSnd; - projLogic->reflectSnd = s_stdProjReflectSnd; - } break; - case PROJ_PLASMA: - { - if (s_plasmaProj) - { - sprite_setData(projObj, s_plasmaProj); - } - projObj->flags |= OBJ_FLAG_FULLBRIGHT; - projObj->worldWidth = 0; - // Setup the looping wax animation. - obj_setSpriteAnim(projObj); - - projLogic->type = PROJ_PLASMA; - projLogic->updateFunc = stdProjectileUpdateFunc; - projLogic->dmg = FIXED(15); - projLogic->minDmg = ONE_16; - projLogic->falloffAmt = 39321; // 0.6 damage - projLogic->dmgFalloffDelta = 29; // 0.2 seconds - - projLogic->projForce = 3276; - projLogic->speed = FIXED(100); - projLogic->horzBounciness = 58982; // 0.9 - projLogic->vertBounciness = 58982; - projLogic->bounceCnt = 3; - projLogic->reflVariation = 9; - projLogic->nextFalloffTick = s_curTick + 29; // ~0.2 second - projLogic->reflectEffectId = HEFFECT_NONE; - projLogic->hitEffectId = HEFFECT_PLASMA_EXP; - projLogic->duration = s_curTick + 1456; // ~10 seconds - projLogic->cameraPassSnd = s_plasmaCameraSnd; - projLogic->reflectSnd = s_plasmaReflectSnd; - } break; - case PROJ_MORTAR: - { - if (s_mortarProj) - { - sprite_setData(projObj, s_mortarProj); - } - // Setup the looping wax animation. - obj_setSpriteAnim(projObj); - projObj->worldWidth = 0; - - projLogic->type = PROJ_MORTAR; - projLogic->updateFunc = arcingProjectileUpdateFunc; - projLogic->dmg = 0; // Damage is set to 0 for some reason. - projLogic->falloffAmt = 0; // No falloff - projLogic->dmgFalloffDelta = 0; - - projLogic->projForce = 13107; - projLogic->speed = FIXED(110); - projLogic->horzBounciness = 26214; // 0.4 - projLogic->vertBounciness = 39321; // 0.6 - projLogic->bounceCnt = 0; - projLogic->reflectEffectId = HEFFECT_NONE; - projLogic->hitEffectId = HEFFECT_MORTAR_EXP; - projLogic->duration = s_curTick + 582; // ~4 seconds -> ~440 units - } break; - case PROJ_LAND_MINE: - { - if (s_landmineWpnFrame) - { - frame_setData(projObj, s_landmineWpnFrame); - } - projObj->entityFlags |= ETFLAG_LANDMINE_WPN; - projObj->flags |= OBJ_FLAG_MOVABLE; - projObj->worldWidth = 0; - - projLogic->type = PROJ_LAND_MINE; - projLogic->updateFunc = arcingProjectileUpdateFunc; - projLogic->dmg = 0; - projLogic->falloffAmt = 0; - projLogic->dmgFalloffDelta = 0; - - projLogic->projForce = 13107; - projLogic->speed = 0; - projLogic->horzBounciness = 0; - projLogic->vertBounciness = 0; - projLogic->bounceCnt = -1; - projLogic->reflectEffectId = HEFFECT_NONE; - projLogic->flags |= PROJFLAG_EXPLODE; - projLogic->hitEffectId = HEFFECT_LARGE_EXP; - projLogic->duration = s_curTick + 436; // ~3 seconds - } break; - case PROJ_LAND_MINE_PROX: - { - if (s_landmineWpnFrame) - { - frame_setData(projObj, s_landmineWpnFrame); - } - projObj->entityFlags |= ETFLAG_LANDMINE_WPN; - projObj->flags |= OBJ_FLAG_MOVABLE; - projObj->worldWidth = 0; - - projLogic->type = PROJ_LAND_MINE_PROX; - projLogic->updateFunc = arcingProjectileUpdateFunc; - projLogic->dmg = 0; - projLogic->falloffAmt = 0; - projLogic->dmgFalloffDelta = 0; - - projLogic->projForce = 13107; - projLogic->speed = 0; - projLogic->horzBounciness = 0; - projLogic->vertBounciness = 0; - projLogic->bounceCnt = -1; - projLogic->reflectEffectId = HEFFECT_NONE; - projLogic->flags |= PROJFLAG_EXPLODE; - projLogic->hitEffectId = HEFFECT_LARGE_EXP; - projLogic->duration = s_curTick + 436; // ~3 seconds - } break; - case PROJ_LAND_MINE_PLACED: - { - if (s_landmineFrame) - { - frame_setData(projObj, s_landmineFrame); - } - projLogic->type = PROJ_LAND_MINE_PLACED; - projObj->flags |= OBJ_FLAG_MOVABLE; - projObj->worldWidth = 0; - - projLogic->updateFunc = landMineUpdateFunc; - projLogic->dmg = 0; - projLogic->falloffAmt = 0; - projLogic->projForce = 13107; - projLogic->speed = 0; - projLogic->horzBounciness = 0; - projLogic->vertBounciness = 0; - projLogic->bounceCnt = -1; - projLogic->duration = 0; - projLogic->reflectEffectId = HEFFECT_NONE; - projLogic->flags |= PROJFLAG_EXPLODE; - projLogic->hitEffectId = HEFFECT_LARGE_EXP; - } break; - case PROJ_CONCUSSION: - { - spirit_setData(projObj); - projObj->worldWidth = 0; - - projLogic->type = PROJ_CONCUSSION; - projLogic->updateFunc = stdProjectileUpdateFunc; - projLogic->dmg = 0; - projLogic->falloffAmt = 0; - projLogic->dmgFalloffDelta = 0; - - projLogic->projForce = 3932; - projLogic->speed = FIXED(190); - projLogic->horzBounciness = 58982; // 0.9 - projLogic->vertBounciness = 58982; - projLogic->bounceCnt = 0; - projLogic->reflectEffectId = HEFFECT_NONE; - projLogic->hitEffectId = HEFFECT_CONCUSSION; - projLogic->duration = s_curTick + 728; // ~5 seconds - } break; - case PROJ_CANNON: - { - if (s_cannonProj) - { - sprite_setData(projObj, s_cannonProj); - } - projObj->flags |= OBJ_FLAG_FULLBRIGHT; - projObj->worldWidth = 0; - // Setup the looping wax animation. - obj_setSpriteAnim(projObj); - - projLogic->type = PROJ_CANNON; - projLogic->updateFunc = stdProjectileUpdateFunc; - projLogic->dmg = FIXED(30); - projLogic->falloffAmt = 0; // No falloff - projLogic->dmgFalloffDelta = 0; - - projLogic->projForce = 4032; - projLogic->speed = FIXED(100); - projLogic->horzBounciness = 58982; // 0.9 - projLogic->vertBounciness = 58982; - projLogic->bounceCnt = 3; - projLogic->reflVariation = 18; - projLogic->reflectEffectId = HEFFECT_NONE; - projLogic->hitEffectId = HEFFECT_CANNON_EXP; - projLogic->duration = s_curTick + 582; // ~4 seconds -> ~400 units - projLogic->cameraPassSnd = s_plasmaCameraSnd; - projLogic->reflectSnd = s_plasmaReflectSnd; - } break; - case PROJ_MISSILE: - { - if (s_missileProj) - { - sprite_setData(projObj, s_missileProj); - } - // Setup the looping wax animation. - obj_setSpriteAnim(projObj); - projObj->worldWidth = 0; - - projLogic->type = PROJ_MISSILE; - projLogic->updateFunc = stdProjectileUpdateFunc; - projLogic->dmg = 0; // Damage is set to 0 for some reason. - projLogic->falloffAmt = 0; // No falloff - projLogic->dmgFalloffDelta = 0; - - projLogic->projForce = ONE_16; - projLogic->speed = FIXED(74); - projLogic->horzBounciness = 58982; // 0.9 - projLogic->vertBounciness = 58982; - projLogic->bounceCnt = 0; - projLogic->reflectEffectId = HEFFECT_NONE; - projLogic->hitEffectId = HEFFECT_MISSILE_EXP; - projLogic->duration = s_curTick + 1019; // ~7 seconds -> ~518 units - projLogic->flightSndSource = s_missileLoopingSnd; - } break; - case PROJ_TURRET_BOLT: - { - if (s_greenBoltModel) - { - obj3d_setData(projObj, s_greenBoltModel); - } - projObj->flags |= OBJ_FLAG_FULLBRIGHT; - projObj->worldWidth = 0; - - projLogic->type = PROJ_TURRET_BOLT; - projLogic->updateFunc = stdProjectileUpdateFunc; - projLogic->dmg = FIXED(17); - projLogic->minDmg = ONE_16; - projLogic->falloffAmt = ONE_16; - projLogic->dmgFalloffDelta = 14; - - projLogic->projForce = 1966; - projLogic->speed = FIXED(300); - projLogic->horzBounciness = ONE_16; - projLogic->vertBounciness = ONE_16; - projLogic->bounceCnt = 3; - projLogic->reflVariation = 9; - projLogic->nextFalloffTick = s_curTick + 14; // ~0.1 seconds - projLogic->reflectEffectId = HEFFECT_SMALL_EXP; - projLogic->hitEffectId = HEFFECT_SMALL_EXP; - projLogic->duration = s_curTick + 436; // ~3 seconds - projLogic->cameraPassSnd = s_stdProjCameraSnd; - projLogic->reflectSnd = s_stdProjReflectSnd; - } break; - case PROJ_REMOTE_BOLT: - { - if (s_greenBoltModel) - { - obj3d_setData(projObj, s_greenBoltModel); - } - projObj->flags |= OBJ_FLAG_FULLBRIGHT; - projObj->worldWidth = 0; - - projLogic->type = PROJ_REMOTE_BOLT; - projLogic->updateFunc = stdProjectileUpdateFunc; - projLogic->dmg = ONE_16; - projLogic->minDmg = 0; - projLogic->falloffAmt = ONE_16; - projLogic->dmgFalloffDelta = 14; - - projLogic->projForce = 655; - projLogic->speed = FIXED(300); - projLogic->horzBounciness = ONE_16; - projLogic->vertBounciness = ONE_16; - projLogic->bounceCnt = 3; - projLogic->reflVariation = 9; - projLogic->nextFalloffTick = s_curTick + 14; // ~0.1 seconds - projLogic->reflectEffectId = HEFFECT_SMALL_EXP; - projLogic->hitEffectId = HEFFECT_SMALL_EXP; - projLogic->duration = s_curTick + 436; // ~3 seconds - projLogic->cameraPassSnd = s_stdProjCameraSnd; - projLogic->reflectSnd = s_stdProjReflectSnd; - } break; - case PROJ_EXP_BARREL: - { - spirit_setData(projObj); - - projLogic->type = PROJ_EXP_BARREL; - projLogic->updateFunc = stdProjectileUpdateFunc; - projLogic->dmg = 0; - projLogic->falloffAmt = 0; - projLogic->dmgFalloffDelta = 0; - - projLogic->projForce = 0; - projLogic->speed = 0; - projLogic->horzBounciness = 0; - projLogic->vertBounciness = 0; - projLogic->bounceCnt = 0; - projLogic->reflectEffectId = HEFFECT_NONE; - projLogic->flags |= PROJFLAG_EXPLODE; - projLogic->hitEffectId = HEFFECT_EXP_BARREL; - projLogic->duration = s_curTick; - } break; - case PROJ_HOMING_MISSILE: - { - if (s_homingMissileProj) - { - sprite_setData(projObj, s_homingMissileProj); - } - obj_setSpriteAnim(projObj); - projObj->flags |= OBJ_FLAG_AIM; - - projLogic->flags |= PROJFLAG_EXPLODE; - projLogic->type = PROJ_HOMING_MISSILE; - projLogic->updateFunc = homingMissileProjectileUpdateFunc; - projLogic->dmg = 0; - projLogic->minDmg = ONE_16; - projLogic->falloffAmt = 0; - projLogic->dmgFalloffDelta = ONE_16; - - projLogic->projForce = ONE_16; - projLogic->speed = FIXED(58) / 2; // try slowing them down...; the value is correct according to the code, but they are slower in DOS. - projLogic->horzBounciness = 58982; // 0.9 - projLogic->vertBounciness = 58982; - projLogic->bounceCnt = 0; - projLogic->homingAngleSpd = 455; // Starting homing rate = 10 degrees / second - projLogic->reflectEffectId = HEFFECT_NONE; - projLogic->flightSndSource = s_homingMissileFlightSnd; - projLogic->hitEffectId = HEFFECT_MISSILE_EXP; - projLogic->duration = s_curTick + 1456; - projLogic->reflectSnd = 0; - } break; - case PROJ_PROBE_PROJ: - { - if (s_probeProj) - { - sprite_setData(projObj, s_probeProj); - } - projObj->flags |= OBJ_FLAG_FULLBRIGHT; - projObj->worldWidth = 0; - // Setup the looping wax animation. - obj_setSpriteAnim(projObj); - - projLogic->type = PROJ_PROBE_PROJ; - projLogic->updateFunc = stdProjectileUpdateFunc; - projLogic->dmg = FIXED(10); - projLogic->minDmg = ONE_16; - projLogic->falloffAmt = ONE_16; // 1.0 damage - projLogic->dmgFalloffDelta = 14; - - projLogic->projForce = 2621; - projLogic->speed = FIXED(100); - projLogic->horzBounciness = 58982; // 0.9 - projLogic->vertBounciness = 58982; - projLogic->bounceCnt = 3; - projLogic->reflVariation = 9; - projLogic->nextFalloffTick = s_curTick + 14; - projLogic->reflectEffectId = HEFFECT_NONE; - projLogic->hitEffectId = HEFFECT_PLASMA_EXP; - projLogic->duration = s_curTick + 1165; // ~8 seconds - projLogic->cameraPassSnd = s_plasmaCameraSnd; - projLogic->reflectSnd = s_plasmaReflectSnd; - } break; - case PROJ_BOBAFET_BALL: - { - if (s_bobafetBall) - { - sprite_setData(projObj, s_bobafetBall); - } - // Setup the looping wax animation. - obj_setSpriteAnim(projObj); - projObj->worldWidth = 0; - - projLogic->type = PROJ_BOBAFET_BALL; - projLogic->updateFunc = stdProjectileUpdateFunc; - projLogic->dmg = 0; - projLogic->falloffAmt = 0; - - projLogic->projForce = ONE_16; - projLogic->speed = FIXED(90); - projLogic->horzBounciness = 58982; // 0.9 - projLogic->vertBounciness = 58982; - projLogic->bounceCnt = 0; - projLogic->reflectEffectId = HEFFECT_NONE; - projLogic->hitEffectId = HEFFECT_EXP_25; - projLogic->duration = s_curTick + 1456; - projLogic->cameraPassSnd = s_bobaBallCameraSnd; - } break; - } - projLogic->col_speed = projLogic->speed; - - projObj->posWS.x = x; - projObj->posWS.y = y; - projObj->posWS.z = z; - sector_addObject(sector, projObj); - task_makeActive(s_projectileTask); - - return (Logic*)projLogic; - } - - void projectileTaskFunc(MessageType msg) - { - struct LocalContext - { - ProjectileLogic* projLogic; - }; - task_begin_ctx; - - while (msg != MSG_FREE_TASK) - { - taskCtx->projLogic = nullptr; - task_yield(TASK_NO_DELAY); - - // Keep looping until a projectile becomes active. - // Note: this task will need to be made active by something else to wake up. - while (!taskCtx->projLogic) - { - taskCtx->projLogic = (ProjectileLogic*)allocator_getHead(s_projectiles); - if (!taskCtx->projLogic) - { - task_yield(TASK_SLEEP); - } - } - - taskCtx->projLogic = (ProjectileLogic*)allocator_getHead(s_projectiles); - while (taskCtx->projLogic) - { - ProjectileLogic* projLogic = taskCtx->projLogic; - - SecObject* obj = projLogic->logic.obj; - ProjectileHitType projHitType = PHIT_NONE; - Tick curTick = s_curTick; - - // The projectile is still active. - if (curTick < projLogic->duration) - { - // Handle damage falloff. - if (projLogic->falloffAmt && curTick > projLogic->nextFalloffTick) - { - projLogic->dmg -= projLogic->falloffAmt; - if (projLogic->dmg < projLogic->minDmg) - { - projLogic->nextFalloffTick = 0xffffffff; // This basically sets the falloff to "infinity" so it never enters this block again. - projLogic->dmg = projLogic->minDmg; - } - else - { - projLogic->nextFalloffTick += projLogic->dmgFalloffDelta; - } - } - } - else // The projectile has reached the end of its life. - { - const ProjectileType type = projLogic->type; - // Note that proximity landmines that have reached end of life don't explode right away, but instead check for valid object proximity. - if (type == PROJ_LAND_MINE_PLACED) // Pre-placed landmines. - { - const fixed16_16 approxDist = distApprox(s_playerObject->posWS.x, s_playerObject->posWS.z, obj->posWS.x, obj->posWS.z); - if (approxDist <= PL_LANDMINE_TRIGGER_RADIUS) - { - if (s_playerObject->posWS.y >= obj->posWS.y - PL_LANDMINE_TRIGGER_RADIUS && s_playerObject->posWS.y <= obj->posWS.y + PL_LANDMINE_TRIGGER_RADIUS && - collision_isAnyObjectInRange(obj->sector, PL_LANDMINE_TRIGGER_RADIUS, obj->posWS, obj, ETFLAG_PLAYER)) - { - projLogic->type = PROJ_LAND_MINE; - projLogic->duration = s_curTick + 87; // The landmine will explode in 0.6 seconds. - sound_playCued(s_landMineTriggerSnd, obj->posWS); - } - } - } - else if (type == PROJ_LAND_MINE_PROX) // Player placed proximity landmine (secondary fire). - { - if (collision_isAnyObjectInRange(obj->sector, WP_LANDMINE_TRIGGER_RADIUS, obj->posWS, obj, ETFLAG_PLAYER | ETFLAG_AI_ACTOR)) - { - projLogic->type = PROJ_LAND_MINE; - projLogic->duration = s_curTick + TICKS_PER_SECOND; // The landmine will explode in 1 second. - sound_playCued(s_landMineTriggerSnd, obj->posWS); - } - } - else - { - projHitType = PHIT_OUT_OF_RANGE; - } - } // if (curTick < projLogic->duration) - - if (projHitType == PHIT_NONE) - { - RSector* sector = obj->sector; - InfLink* link = (InfLink*)allocator_getHead(sector->infLink); - if (link && link->type == LTYPE_SECTOR && inf_isOnMovingFloor(obj, link->elev, sector)) - { - fixed16_16 res; - vec3_fixed vel; - inf_getMovingElevatorVelocity(link->elev, &vel, &res); - projLogic->vel.y = vel.y; - projLogic->vel.x += vel.x; - projLogic->vel.z += vel.z; - } - if (projLogic->updateFunc) - { - projHitType = projLogic->updateFunc(projLogic); - } - } - - // Play a looping sound as the projectile travels, this updates its position if already playing. - if (projLogic->flightSndSource) - { - projLogic->flightSndId = sound_maintain(projLogic->flightSndId, projLogic->flightSndSource, obj->posWS); - } - // Play a sound as the object passes near the camera. - if (projLogic->cameraPassSnd && (projLogic->flags & PROJFLAG_CAMERA_PASS_SOUND)) - { - fixed16_16 dy = TFE_Jedi::abs(obj->posWS.y - s_eyePos.y); - fixed16_16 approxDist = dy + distApprox(s_eyePos.x, s_eyePos.z, obj->posWS.x, obj->posWS.z); - if (approxDist < CAMERA_SOUND_RANGE) - { - projLogic->flightSndId = sound_playCued(projLogic->cameraPassSnd, obj->posWS); - projLogic->flags &= ~PROJFLAG_CAMERA_PASS_SOUND; - } - } - else if (projLogic->cameraPassSnd && projLogic->flightSndId) - { - sound_adjustCued(projLogic->flightSndId, obj->posWS); - projLogic->flightSndId = NULL_SOUND; - } - // Finally handle the hit itself (this includes going out of range). - if (projHitType != PHIT_NONE) - { - handleProjectileHit(projLogic, projHitType); - } - taskCtx->projLogic = (ProjectileLogic*)allocator_getNext(s_projectiles); - } // while (taskCtx->projLogic) - } // while (id != -1) - - task_end; - } - - void triggerLandMine(ProjectileLogic* projLogic, Tick delay) - { - projLogic->type = PROJ_LAND_MINE; - projLogic->duration = s_curTick + delay; - - SecObject* obj = projLogic->logic.obj; - sound_playCued(s_landMineTriggerSnd, obj->posWS); - } - - ////////////////////////////////////////////////////////////// - // Internal Implementation - ////////////////////////////////////////////////////////////// - // This function never actually gets called because the Projectile system handles the cleanup. - void projectileLogicCleanupFunc(Logic* logic) - { - allocator_addRef(s_projectiles); - deleteLogicAndObject(logic); - allocator_deleteItem(s_projectiles, logic); - // Bug: allocator_release() is never called - } - - // The "standard" update function - projectiles travel in a straight line with a fixed velocity. - ProjectileHitType stdProjectileUpdateFunc(ProjectileLogic* projLogic) - { - // Calculate how much the projectile moves this timeslice. - const fixed16_16 dt = s_deltaTime; - projLogic->delta.x = mul16(projLogic->vel.x, dt); - projLogic->delta.y = mul16(projLogic->vel.y, dt); - projLogic->delta.z = mul16(projLogic->vel.z, dt); - - return proj_handleMovement(projLogic); - } - - // Landmines do not move but can fall if off of the ground. - ProjectileHitType landMineUpdateFunc(ProjectileLogic* projLogic) - { - SecObject* obj = projLogic->logic.obj; - fixed16_16 ceilHeight, floorHeight; - sector_getObjFloorAndCeilHeight(obj->sector, obj->posWS.y, &floorHeight, &ceilHeight); - - // Gravity - fall if the landmine is above the ground. - if (obj->posWS.y < floorHeight) - { - const fixed16_16 dt = s_deltaTime; - projLogic->vel.y += mul16(PROJ_GRAVITY_ACCEL, dt); - projLogic->delta.y = mul16(projLogic->vel.y, dt); - return proj_handleMovement(projLogic); - } - return PHIT_NONE; - } - - // Projectiles, such as Thermal Detonators and Mortars fly in an arc. - // This is done by giving them an initial velocity and then modifying that velocity - // over time based on gravity. - ProjectileHitType arcingProjectileUpdateFunc(ProjectileLogic* projLogic) - { - const fixed16_16 dt = s_deltaTime; - // The projectile arcs due to gravity, accel = 120.0 units / s^2 - projLogic->vel.y += mul16(PROJ_GRAVITY_ACCEL, dt); - // Get the frame delta from the velocity and delta time. - projLogic->delta.x = mul16(projLogic->vel.x, dt); - projLogic->delta.y = mul16(projLogic->vel.y, dt); - projLogic->delta.z = mul16(projLogic->vel.z, dt); - - // Arcing projectiles cannot move straight up or down. - const fixed16_16 horzSpeed = vec2Length(projLogic->vel.x, projLogic->vel.z); - projLogic->dir.y = (horzSpeed) ? div16(projLogic->vel.y, horzSpeed) : 0; - - return proj_handleMovement(projLogic); - } - - ProjectileHitType homingMissileProjectileUpdateFunc(ProjectileLogic* projLogic) - { - SecObject* missileObj = projLogic->logic.obj; - SecObject* targetObj = s_playerObject; - fixed16_16 dt = s_deltaTime; - - angle14_32 homingAngleSpd = projLogic->homingAngleSpd; - // Target near the head/upper chest. - fixed16_16 yTarget = targetObj->posWS.y - targetObj->worldHeight + ONE_16; - angle14_32 homingAngleDelta = mul16(homingAngleSpd, dt); - - // Calculate the horizontal turn amount (change in yaw). - fixed16_16 dx = targetObj->posWS.x - missileObj->posWS.x; - fixed16_16 dz = targetObj->posWS.z - missileObj->posWS.z; - angle14_32 hAngle = vec2ToAngle(dx, dz); - angle14_32 hAngleDiff = getAngleDifference(missileObj->yaw, hAngle); - if (hAngleDiff > homingAngleDelta) - { - hAngleDiff = homingAngleDelta; - } - else if (hAngleDiff < -homingAngleDelta) - { - hAngleDiff = -homingAngleDelta; - } - // Turn toward the target (yaw). - missileObj->yaw += hAngleDiff; - - // Calculate the vertical turn amount (change in pitch). - fixed16_16 cosYaw, sinYaw; - sinCosFixed(missileObj->yaw, &sinYaw, &cosYaw); - - fixed16_16 hDir = mul16(sinYaw, dx) + mul16(cosYaw, dz); - fixed16_16 dy = missileObj->posWS.y - yTarget; - angle14_32 vAngle = vec2ToAngle(dy, hDir); - if (vAngle > HOMING_PITCH_ZERO_MIN && vAngle < HOMING_PITCH_ZERO_MAX) - { - vAngle = 0; - } - angle14_32 vAngleDiff = getAngleDifference(missileObj->pitch, homingAngleDelta); - if (vAngleDiff > homingAngleDelta) - { - vAngleDiff = homingAngleDelta; - } - else if (vAngleDiff < -homingAngleDelta) - { - vAngleDiff = -homingAngleDelta; - } - // Turn toward the target (pitch). - missileObj->pitch += vAngleDiff; - - // The missile will continue homing at a faster rate, up until the maximum. - if (projLogic->homingAngleSpd < MAX_HOMING_ANGULAR_VEL) - { - projLogic->homingAngleSpd += mul16(HOMING_ANGULAR_ACCEL, dt); - } - - // Set the projectile transform based on the new yaw and pitch. - proj_setTransform(projLogic, missileObj->pitch, missileObj->yaw); - - // Finally calculate the per-frame movement from the velocity computed in proj_setTransform(). - projLogic->delta.x = mul16(projLogic->vel.x, dt); - projLogic->delta.y = mul16(projLogic->vel.y, dt); - projLogic->delta.z = mul16(projLogic->vel.z, dt); - - // Then apply movement and handle the 'explode early' special case. - s_collision_excludeEntityFlags = ETFLAG_PROJECTILE; - ProjectileHitType hitType = proj_handleMovement(projLogic); - s_collision_excludeEntityFlags = 0; - if (hitType == PHIT_NONE) - { - // There is a chance that the missile will explode early, once it gets within a certain range. - fixed16_16 approxDist = distApprox(missileObj->posWS.x, missileObj->posWS.z, targetObj->posWS.x, targetObj->posWS.z); - if (approxDist < HOMING_MISSILE_EXPLODE_RNG && (s_curTick & 1)) - { - hitType = PHIT_SOLID; - } - } - return hitType; - } - - - void proj_computeTransform3D(SecObject* obj, fixed16_16 sinPitch, fixed16_16 cosPitch, fixed16_16 sinYaw, fixed16_16 cosYaw, fixed16_16 dt) - { - fixed16_16* transform = obj->transform; - transform[0] = cosYaw; - transform[1] = mul16(sinPitch, sinYaw); - transform[2] = mul16(mul16(cosPitch, sinYaw), dt); - - transform[3] = 0; - transform[4] = cosPitch; - transform[5] = -mul16(sinPitch, dt); - - transform[6] = -sinYaw; - transform[7] = mul16(sinPitch, cosYaw); - transform[8] = mul16(mul16(cosPitch, cosYaw), dt); - } - - void proj_setYawPitch(ProjectileLogic* projLogic, fixed16_16 sinPitch, fixed16_16 cosPitch, fixed16_16 sinYaw, fixed16_16 cosYaw) - { - projLogic->dir.x = sinYaw; - projLogic->dir.z = cosYaw; - projLogic->vel.x = mul16(mul16(sinYaw, projLogic->speed), cosPitch); - projLogic->vel.z = mul16(mul16(cosYaw, projLogic->speed), cosPitch); - projLogic->vel.y = -mul16(sinPitch, projLogic->speed); - - // Projectiles cannot point straight up or down. - const fixed16_16 horzSpeed = vec2Length(projLogic->vel.x, projLogic->vel.z); - projLogic->dir.y = (horzSpeed) ? div16(projLogic->vel.y, horzSpeed) : 0; - - SecObject* obj = projLogic->logic.obj; - if (obj->type == OBJ_TYPE_3D) - { - proj_computeTransform3D(obj, sinPitch, cosPitch, sinYaw, cosYaw, s_deltaTime); - } - } - - void proj_setTransform(ProjectileLogic* projLogic, angle14_32 pitch, angle14_32 yaw) - { - SecObject* obj = projLogic->logic.obj; - obj->roll = 0; - obj->pitch = pitch; - obj->yaw = yaw; - - fixed16_16 cosYaw, sinYaw; - fixed16_16 cosPitch, sinPitch; - sinCosFixed(yaw, &sinYaw, &cosYaw); - sinCosFixed(pitch, &sinPitch, &cosPitch); - - proj_setYawPitch(projLogic, sinPitch, cosPitch, sinYaw, cosYaw); - } - - // Originally this code was inlined in the final DOS code, but I am splitting it out to reduce redundant code. - // This code adds some variation to the final yaw and pitch of a projectile after reflection if - // projLogic->reflVariation is non-zero. - void handleReflectVariation(ProjectileLogic* projLogic, SecObject* obj) - { - if (!projLogic->reflVariation) { return; } - - // Random variation between [-projLogic->reflVariation, projLogic->reflVariation] - obj->yaw += random(2 * projLogic->reflVariation) - projLogic->reflVariation; - obj->pitch += random(2 * projLogic->reflVariation) - projLogic->reflVariation; - } - - void proj_reflect(SecObject* obj, ProjectileLogic* projLogic) - { - angle14_32 angleDiff = getAngleDifference(obj->yaw, s_projReflectOverrideYaw); - obj->yaw = (angleDiff + s_projReflectOverrideYaw) & ANGLE_MASK; - - if (projLogic->reflVariation) - { - obj->yaw += random(projLogic->reflVariation * 2) - projLogic->reflVariation; - obj->pitch += random(projLogic->reflVariation * 2) - projLogic->reflVariation; - } - projLogic->prevColObj = nullptr; - projLogic->excludeObj = nullptr; - proj_setTransform(projLogic, obj->pitch, obj->yaw); - sound_playCued(projLogic->reflectSnd, obj->posWS); - - projLogic->flags |= PROJFLAG_CAMERA_PASS_SOUND; - } - - // Handle projectile movement. - // Returns 0 if it moved without hitting anything. - ProjectileHitType proj_handleMovement(ProjectileLogic* projLogic) - { - SecObject* obj = projLogic->logic.obj; - JBool envHit = proj_move(projLogic); - JBool objHit = proj_getHitObj(projLogic); - if (objHit) - { - obj->posWS.y = s_colObjAdjY; - fixed16_16 dz = s_colObjAdjZ - obj->posWS.z; - fixed16_16 dx = s_colObjAdjX - obj->posWS.x; - collision_moveObj(obj, dx, dz); - - if (projLogic->bounceCnt == -1) - { - projLogic->speed = mul16(projLogic->speed, projLogic->horzBounciness); - angle14_32 offsetYaw = obj->yaw + 4096; - // getAngleDifference() will always return 4096, then we add yaw + 4096 = yaw + 8192 = 180 degrees. - // This could have been accomplished with: obj->yaw = (obj->yaw + 8192) & 16383 - obj->yaw = (getAngleDifference(obj->yaw, offsetYaw) + offsetYaw) & 16383; - handleReflectVariation(projLogic, obj); - - projLogic->prevColObj = nullptr; - projLogic->excludeObj = nullptr; - proj_setTransform(projLogic, obj->pitch, obj->yaw); - sound_playCued(projLogic->reflectSnd, obj->posWS); - - projLogic->flags |= PROJFLAG_CAMERA_PASS_SOUND; - projLogic->delta.x = mul16(HALF_16, projLogic->dir.x); - projLogic->delta.z = mul16(HALF_16, projLogic->dir.z); - collision_moveObj(obj, projLogic->delta.x, projLogic->delta.z); - - projLogic->delta.x = 0; - projLogic->delta.y = 0; - projLogic->delta.z = 0; - } - else - { - if (projLogic->type == PROJ_PUNCH) - { - vec3_fixed effectPos = { s_colObjAdjX, s_colObjAdjY, s_colObjAdjZ }; - spawnHitEffect(projLogic->hitEffectId, obj->sector, effectPos, projLogic->excludeObj); - } - s_hitWallFlag = WH_STDEXP; - if (s_colHitObj->entityFlags & ETFLAG_PROJECTILE) - { - s_hitWallFlag = WH_IGNORE; - Logic** objLogicPtr = (Logic**)allocator_getHead((Allocator*)s_colHitObj->logic); - if (objLogicPtr) - { - ProjectileLogic* objLogic = (ProjectileLogic*)*objLogicPtr; - // PROJ_HOMING_MISSILE can be destroyed by shooting it with a different type of projectile. - if (projLogic->type != objLogic->type && objLogic->type == PROJ_HOMING_MISSILE) - { - s_hitWallFlag = WH_STDEXP; - objLogic->duration = 0; - } - } - } - else if (projLogic->dmg) - { - s_msgEntity = projLogic; - message_sendToObj(s_colHitObj, MSG_DAMAGE, nullptr); - } - - switch (s_hitWallFlag) - { - case WH_IGNORE: - { - // Do nothing, this will proceed to the next section. - } break; - case WH_NOEXP: - { - return PHIT_SKY; - } break; - case WH_STDEXP: - case WH_CUSTEXP: // CUSTEXP is not actually used but is included for completeness. - { - return PHIT_SOLID; - } break; - case WH_BOUNCE: - { - proj_reflect(obj, projLogic); - return PHIT_NONE; - } break; - default: - { - return PHIT_SOLID; - } - } - } - } - - if (envHit) - { - obj->posWS.y = s_projNextPosY; - fixed16_16 dz = s_projNextPosZ - obj->posWS.z; - fixed16_16 dx = s_projNextPosX - obj->posWS.x; - RSector* newSector = collision_moveObj(obj, dx, dz); - - if (s_hitWall) - { - s_hitWallFlag = (s_projSector->flags1 & SEC_FLAGS1_NOWALL_DRAW) ? WH_NOEXP : WH_STDEXP; - - vec2_fixed* w0 = s_hitWall->w0; - fixed16_16 paramPos = vec2Length(s_projNextPosX - w0->x, s_projNextPosZ - w0->z); - inf_wallAndMirrorSendMessageAtPos(s_hitWall, projLogic->logic.obj, INF_EVENT_SHOOT_LINE, paramPos, s_projNextPosY); - - switch (s_hitWallFlag) - { - case WH_IGNORE: - case WH_NOEXP: - { - return PHIT_SKY; - } break; - case WH_STDEXP: - { - return PHIT_SOLID; - } break; - case WH_BOUNCE: - { - proj_reflect(obj, projLogic); - return PHIT_NONE; - } break; - } - } - return s_hitWater ? PHIT_WATER : PHIT_SOLID; - } - - // Hit nothing. - obj->posWS.y += projLogic->delta.y; - collision_moveObj(obj, projLogic->delta.x, projLogic->delta.z); - return PHIT_NONE; - } - - // Return JTRUE if something was hit during movement. - JBool proj_move(ProjectileLogic* projLogic) - { - SecObject* obj = projLogic->logic.obj; - RSector* sector = obj->sector; - - s_hitWall = nullptr; - s_hitWater = JFALSE; - s_projSector = sector; - s_projPath[0] = sector; - s_projIter = 1; - s_projNextPosX = obj->posWS.x + projLogic->delta.x; - s_projNextPosY = obj->posWS.y + projLogic->delta.y; - s_projNextPosZ = obj->posWS.z + projLogic->delta.z; - - fixed16_16 y0CeilHeight; - fixed16_16 y0FloorHeight; - bool hitFloor = false, hitCeil = false; - - RWall* wall = collision_wallCollisionFromPath(s_projSector, obj->posWS.x, obj->posWS.z, s_projNextPosX, s_projNextPosZ); - while (wall) - { - fixed16_16 bot, top; - if (wall->nextSector && !(wall->flags3 & WF3_CANNOT_FIRE_THROUGH)) - { - // Determine the opening in the wall. - wall_getOpeningHeightRange(wall, &top, &bot); - - // The check if the projectile trivially passes through. - fixed16_16 y0 = s_projNextPosY; - fixed16_16 y1 = projLogic->type == PROJ_THERMAL_DET ? s_projNextPosY - obj->worldHeight : s_projNextPosY; - if (obj->posWS.y <= bot && obj->posWS.y >= top && y0 <= bot && y1 >= top) - { - s_projSector = wall->nextSector; - s_projPath[s_projIter] = s_projSector; - s_projIter++; - assert(s_projIter <= PROJ_PATH_MAX_SECTORS); - wall = collision_pathWallCollision(s_projSector); - continue; - } - } - else - { - // There is no opening in the wall. - bot = -SEC_SKY_HEIGHT; - top = SEC_SKY_HEIGHT; - } - - collision_getHitPoint(&s_projNextPosX, &s_projNextPosZ); - fixed16_16 len = vec2Length(s_projNextPosX - obj->posWS.x, s_projNextPosZ - obj->posWS.z); - fixed16_16 yDelta = mul16(len, projLogic->dir.y); - - fixed16_16 y0 = obj->posWS.y; - fixed16_16 y1 = obj->posWS.y + yDelta; - sector_getObjFloorAndCeilHeight(s_projSector, y0, &y0FloorHeight, &y0CeilHeight); - // In the case of water, the real floor height is the actual floor. - if (s_projSector->secHeight > 0) - { - y0FloorHeight = s_projSector->floorHeight; - } - - fixed16_16 nextY = y1; - if (y1 > y0FloorHeight) - { - nextY = y0FloorHeight; - } - else if (y1 < y0CeilHeight) - { - nextY = y0CeilHeight; - } - - fixed16_16 nY0 = nextY; - fixed16_16 nY1 = projLogic->type == PROJ_THERMAL_DET ? nextY - obj->worldHeight : nextY; - if (nY0 <= bot && nY1 >= top) - { - if (y1 >= y0FloorHeight) - { - hitFloor = true; - break; - } - if (y1 <= y0CeilHeight) - { - hitCeil = true; - break; - } - } - else // Wall Hit! - { - fixed16_16 offset = ONE_16 + HALF_16; - fixed16_16 offsetX = mul16(offset, projLogic->dir.x); - fixed16_16 offsetZ = mul16(offset, projLogic->dir.z); - - s_projNextPosY = nextY; - s_projNextPosX -= offsetX; - s_projNextPosZ -= offsetZ; - - projLogic->delta.x = s_projNextPosX - obj->posWS.x; - projLogic->delta.y = s_projNextPosY - obj->posWS.y; - projLogic->delta.z = s_projNextPosZ - obj->posWS.z; - - if (projLogic->bounceCnt == -1) - { - if (s_projNextPosY < s_projSector->ceilingHeight) - { - s_hitWall = wall; - s_hitWallFlag = WH_NOEXP; - return JTRUE; - } - projLogic->speed = mul16(projLogic->speed, projLogic->horzBounciness); - obj->pitch = (getAngleDifference(obj->pitch, 0) & 16383); - obj->yaw = (getAngleDifference(obj->yaw, wall->angle) + wall->angle) & 16383; - handleReflectVariation(projLogic, obj); - - projLogic->prevColObj = nullptr; - projLogic->excludeObj = nullptr; - proj_setTransform(projLogic, obj->pitch, obj->yaw); - sound_playCued(projLogic->reflectSnd, obj->posWS); - - projLogic->flags |= PROJFLAG_CAMERA_PASS_SOUND; - obj->posWS.y = s_projNextPosY; - collision_moveObj(obj, projLogic->delta.x, projLogic->delta.z); - s_projSector = obj->sector; - - projLogic->delta.x = 0; - projLogic->delta.y = 0; - projLogic->delta.z = 0; - - return JFALSE; - } - else if (s_projSector->flags1 & SEC_FLAGS1_MAG_SEAL) - { - if (s_projNextPosY < s_projSector->ceilingHeight) - { - s_hitWall = wall; - s_hitWallFlag = WH_NOEXP; - return JTRUE; - } - s32 count = projLogic->bounceCnt; - projLogic->bounceCnt--; - if (count) - { - vec3_fixed effectPos = { s_projNextPosX, s_projNextPosY, s_projNextPosZ }; - spawnHitEffect(projLogic->reflectEffectId, s_projSector, effectPos, projLogic->excludeObj); - - SecObject* obj = projLogic->logic.obj; - obj->yaw = (getAngleDifference(obj->yaw, wall->angle) + wall->angle) & 16383; - handleReflectVariation(projLogic, obj); - - projLogic->prevColObj = nullptr; - projLogic->excludeObj = nullptr; - proj_setTransform(projLogic, obj->pitch, obj->yaw); - sound_playCued(projLogic->reflectSnd, obj->posWS); - - projLogic->flags |= 1; - obj->posWS.y = s_projNextPosY; - collision_moveObj(obj, projLogic->delta.x, projLogic->delta.z); - s_projSector = obj->sector; - - projLogic->delta.x = 0; - projLogic->delta.y = 0; - projLogic->delta.z = 0; - return JFALSE; - } - } - - // Wall Hit! - s_hitWall = wall; - return JTRUE; - } - - s_projSector = wall->nextSector; - s_projPath[s_projIter] = s_projSector; - s_projIter++; - assert(s_projIter <= PROJ_PATH_MAX_SECTORS); - wall = collision_pathWallCollision(s_projSector); - } - - if (!hitFloor && !hitCeil) - { - sector_getObjFloorAndCeilHeight(s_projSector, obj->posWS.y, &y0FloorHeight, &y0CeilHeight); - if (s_projSector->secHeight > 0) - { - y0FloorHeight = s_projSector->floorHeight; - } - - if (s_projNextPosY > y0FloorHeight) - { - hitFloor = true; - } - else if (s_projNextPosY < y0CeilHeight) - { - hitCeil = true; - } - else // Nothing Hit! - { - // Projectile doesn't hit anything. - return JFALSE; - } - } - - if (hitFloor) - { - SecObject* obj = projLogic->logic.obj; - // fraction of the path where the path hits the floor. - assert(projLogic->delta.y != 0); - fixed16_16 dy = projLogic->delta.y == 0 ? 1 : projLogic->delta.y; // avoid possible divide-by-zero. - fixed16_16 u = div16(y0FloorHeight - obj->posWS.y, dy); - s_projNextPosX = obj->posWS.x + mul16(projLogic->delta.x, u); - s_projNextPosY = y0FloorHeight; - s_projNextPosZ = obj->posWS.z + mul16(projLogic->delta.z, u); - - if (s_projSector->secHeight > 0) // Hit water. - { - s_hitWater = JTRUE; - return JTRUE; - } - } - else if (hitCeil) - { - SecObject* obj = projLogic->logic.obj; - // fraction of the path where the path hits the floor. - assert(projLogic->delta.y != 0); - fixed16_16 dy = projLogic->delta.y == 0 ? 1 : projLogic->delta.y; // avoid possible divide-by-zero. - fixed16_16 u = div16(y0CeilHeight - obj->posWS.y, dy); - s_projNextPosX = obj->posWS.x + mul16(projLogic->delta.x, u); - s_projNextPosY = y0CeilHeight; - s_projNextPosZ = obj->posWS.z + mul16(projLogic->delta.z, u); - } - - // If the thermal detonator is hitting the ground at a fast enough speed, play the reflect sound. - if (projLogic->type == PROJ_THERMAL_DET && TFE_Jedi::abs(projLogic->speed) > FIXED(7)) - { - sound_playCued(projLogic->reflectSnd, obj->posWS); - } - - if (projLogic->bounceCnt == -1) - { - obj->pitch = -obj->pitch; - projLogic->prevColObj = nullptr; - projLogic->prevObj = nullptr; - - // Some projectiles can bounce when hitting the floor or ceiling. - projLogic->speed = mul16(projLogic->speed, projLogic->vertBounciness); - proj_setTransform(projLogic, obj->pitch, obj->yaw); - - obj->posWS.y = s_projNextPosY; - collision_moveObj(obj, projLogic->delta.x, projLogic->delta.z); - s_projSector = obj->sector; // eax - - projLogic->delta.x = 0; - projLogic->delta.y = 0; - projLogic->delta.z = 0; - return JFALSE; - } - else if (s_projSector->flags1 & SEC_FLAGS1_MAG_SEAL) - { - s32 count = projLogic->bounceCnt; - projLogic->bounceCnt--; - if (count > 0) - { - vec3_fixed effectPos = { s_projNextPosX, s_projNextPosY, s_projNextPosZ }; - spawnHitEffect(projLogic->reflectEffectId, s_projSector, effectPos, projLogic->excludeObj); - // Hit the floor or ceiling simply negates the pitch to reflect. - obj->pitch = -obj->pitch; - handleReflectVariation(projLogic, obj); - - projLogic->prevColObj = nullptr; - projLogic->excludeObj = nullptr; - proj_setTransform(projLogic, obj->pitch, obj->yaw); - sound_playCued(projLogic->reflectSnd, obj->posWS); - - obj->posWS.y = s_projNextPosY; - collision_moveObj(obj, projLogic->delta.x, projLogic->delta.z); - s_projSector = obj->sector; - - projLogic->delta.x = 0; - projLogic->delta.y = 0; - projLogic->delta.z = 0; - return JFALSE; - } - } - - // Hit floor or ceiling. - return JTRUE; - } - - // return JTRUE if an object is hit. - JBool proj_getHitObj(ProjectileLogic* projLogic) - { - SecObject* obj = projLogic->logic.obj; - if (!projLogic->speed) - { - return JFALSE; - } - - const fixed16_16 move = mul16(projLogic->col_speed, s_deltaTime); - CollisionInterval interval = - { - obj->posWS.x, // x0 - s_projNextPosX, // x1 - obj->posWS.y, // y0 - s_projNextPosY, // y1 - obj->posWS.z, // z0 - s_projNextPosZ, // z1 - move, // move during timestep - projLogic->dir.x, // dirX - projLogic->dir.z // dirZ - }; - - SecObject* hitObj = nullptr; - while (!hitObj && s_projIter > 0) - { - s_projIter--; - hitObj = collision_getObjectCollision(s_projPath[s_projIter], &interval, projLogic->prevColObj); - } - if (hitObj) - { - s_colHitObj = hitObj; - s_colObjAdjX = obj->posWS.x + mul16(projLogic->dir.x, s_colObjOverlap); - s_colObjAdjY = obj->posWS.y + mul16(projLogic->dir.y, s_colObjOverlap); - s_colObjAdjZ = obj->posWS.z + mul16(projLogic->dir.z, s_colObjOverlap); - s_colObjSector = collision_tryMove(obj->sector, obj->posWS.x, obj->posWS.z, s_colObjAdjX, s_colObjAdjZ); - - if (s_colObjSector) - { - s_colObjAdjY = min(max(s_colObjAdjY, s_colObjSector->ceilingHeight), s_colObjSector->floorHeight); - if (projLogic->type == PROJ_CONCUSSION) - { - projLogic->hitEffectId = HEFFECT_CONCUSSION2; - } - return JTRUE; - } - } - return JFALSE; - } - - void proj_aimAtTarget(ProjectileLogic* proj, vec3_fixed target) - { - SecObject* obj = proj->logic.obj; - vec3_fixed delta = { target.x - obj->posWS.x, target.y - obj->posWS.y, target.z - obj->posWS.z }; - - fixed16_16 dirX, dirZ; - computeDirAndLength(delta.x, delta.z, &dirX, &dirZ); - - // This is a roundabout but mathematically correct way of deriving the length... - fixed16_16 len = mul16(dirX, delta.x) + mul16(dirZ, delta.z); - - fixed16_16 dirY, dirH; - computeDirAndLength(-delta.y, len, &dirY, &dirH); - - proj_setYawPitch(proj, dirY/*sinPitch*/, dirH/*cosPitch*/, dirX/*sinYaw*/, dirZ/*cosYaw*/); - } - - void proj_aimArcing(ProjectileLogic* proj, vec3_fixed target, fixed16_16 speed) - { - assert(speed != 0); - - SecObject* obj = proj->logic.obj; - fixed16_16 dist = distApprox(obj->posWS.x, obj->posWS.z, target.x, target.z); - fixed16_16 distOverSpd = speed ? div16(dist, speed) : dist; - fixed16_16 gravityHalfDistOverSpd = mul16(FIXED(120), distOverSpd >> 1); - - fixed16_16 dy = obj->posWS.y - target.y; - angle14_32 vertAngle = vec2ToAngle(dy, dist); - - fixed16_16 sinAngle = speed ? div16(gravityHalfDistOverSpd, speed) : gravityHalfDistOverSpd; - angle14_32 pitch = vertAngle + arcCosFixed(sinAngle, vertAngle); - proj->speed = distOverSpd ? div16(dist + dy, distOverSpd) : (dist + dy); - proj_setTransform(proj, pitch, obj->yaw); - } - - // TFE: Serialization functionality. - s32 proj_getLogicIndex(ProjectileLogic* logic) - { - return allocator_getIndex(s_projectiles, logic); - } - - ProjectileLogic* proj_getByLogicIndex(s32 index) - { - if (index < 0) { return nullptr; } - return (ProjectileLogic*)allocator_getByIndex(s_projectiles, index); - } - - // Serialization - void projLogic_serialize(Logic*& logic, SecObject* obj, Stream* stream) - { - ProjectileLogic* proj; - if (serialization_getMode() == SMODE_WRITE) - { - proj = (ProjectileLogic*)logic; - } - else - { - proj = (ProjectileLogic*)allocator_newItem(s_projectiles); - logic = (Logic*)proj; - - proj->logic.task = s_projectileTask; - proj->logic.cleanupFunc = projectileLogicCleanupFunc; - task_makeActive(s_projectileTask); - } - SERIALIZE(ObjState_InitVersion, proj->type, PROJ_COUNT); - SERIALIZE(ObjState_InitVersion, proj->dmg, 0); - SERIALIZE(ObjState_InitVersion, proj->falloffAmt, 0); - SERIALIZE(ObjState_InitVersion, proj->nextFalloffTick, 0); - SERIALIZE(ObjState_InitVersion, proj->dmgFalloffDelta, 0); - SERIALIZE(ObjState_InitVersion, proj->minDmg, 0); - - const vec3_fixed def = { 0 }; - SERIALIZE(ObjState_InitVersion, proj->projForce, 0); - SERIALIZE(ObjState_InitVersion, proj->delta, def); - SERIALIZE(ObjState_InitVersion, proj->vel, def); - SERIALIZE(ObjState_InitVersion, proj->speed, 0); - SERIALIZE(ObjState_InitVersion, proj->col_speed, 0); - SERIALIZE(ObjState_InitVersion, proj->dir, def); - SERIALIZE(ObjState_InitVersion, proj->horzBounciness, 0); - SERIALIZE(ObjState_InitVersion, proj->vertBounciness, 0); - - s32 prevColObjId, prevObjId, excludeObjId; - if (serialization_getMode() == SMODE_WRITE) - { - prevColObjId = proj->prevColObj ? proj->prevColObj->serializeIndex : -1; - prevObjId = proj->prevObj ? proj->prevObj->serializeIndex : -1; - excludeObjId = proj->excludeObj ? proj->excludeObj->serializeIndex : -1; - } - SERIALIZE(ObjState_InitVersion, prevColObjId, -1); - SERIALIZE(ObjState_InitVersion, prevObjId, -1); - SERIALIZE(ObjState_InitVersion, excludeObjId, -1); - if (serialization_getMode() == SMODE_READ) - { - proj->prevColObj = (prevColObjId >= 0) ? objData_getObjectBySerializationId(prevColObjId) : nullptr; - proj->prevObj = (prevObjId >= 0) ? objData_getObjectBySerializationId(prevObjId) : nullptr; - proj->excludeObj = (excludeObjId >= 0) ? objData_getObjectBySerializationId(excludeObjId) : nullptr; - } - - SERIALIZE(ObjState_InitVersion, proj->duration, 0); - SERIALIZE(ObjState_InitVersion, proj->homingAngleSpd, 0); - SERIALIZE(ObjState_InitVersion, proj->bounceCnt, 0); - SERIALIZE(ObjState_InitVersion, proj->reflVariation, 0); - - if (serialization_getMode() == SMODE_READ) - { - proj->flightSndId = 0; - } - serialization_serializeDfSound(stream, ObjState_InitVersion, &proj->flightSndSource); - serialization_serializeDfSound(stream, ObjState_InitVersion, &proj->cameraPassSnd); - serialization_serializeDfSound(stream, ObjState_InitVersion, &proj->reflectSnd); - - s32 projUpdateFuncId = -1; - if (serialization_getMode() == SMODE_WRITE && proj->updateFunc) - { - for (s32 i = 0; i < TFE_ARRAYSIZE(c_projUpdateFunc); i++) - { - if (proj->updateFunc == c_projUpdateFunc[i]) - { - projUpdateFuncId = i; - break; - } - } - } - SERIALIZE(ObjState_InitVersion, projUpdateFuncId, -1); - if (serialization_getMode() == SMODE_READ) - { - proj->updateFunc = (projUpdateFuncId >= 0) ? c_projUpdateFunc[projUpdateFuncId] : nullptr; - // There is at least one projectile, so make sure the task is running. - task_makeActive(s_projectileTask); - } - - SERIALIZE(ObjState_InitVersion, proj->reflectEffectId, HEFFECT_NONE); - SERIALIZE(ObjState_InitVersion, proj->hitEffectId, HEFFECT_NONE); - SERIALIZE(ObjState_InitVersion, proj->flags, 0); - } - - // Returns JTRUE if the hit was properly handled, otherwise returns JFALSE. - JBool handleProjectileHit(ProjectileLogic* projLogic, ProjectileHitType hitType) - { - SecObject* obj = projLogic->logic.obj; - RSector* sector = obj->sector; - switch (hitType) - { - case PHIT_SKY: - { - sound_stop(projLogic->flightSndId); - - // Delete the projectile itself. - allocator_addRef(s_projectiles); - deleteLogicAndObject((Logic*)projLogic); - allocator_release(s_projectiles); - - allocator_deleteItem(s_projectiles, projLogic); - return JTRUE; - } break; - case PHIT_SOLID: - { - // Stop the projectiles in-flight sound. - sound_stop(projLogic->flightSndId); - - // Spawn the projectile hit effect. - if (obj->posWS.y <= sector->floorHeight && obj->posWS.y >= sector->ceilingHeight && (projLogic->type != PROJ_PUNCH || hitType != PHIT_OUT_OF_RANGE)) - { - spawnHitEffect(projLogic->hitEffectId, obj->sector, obj->posWS, projLogic->excludeObj); - } - - // Delete the projectile itself. - allocator_addRef(s_projectiles); - deleteLogicAndObject((Logic*)projLogic); - allocator_release(s_projectiles); - allocator_deleteItem(s_projectiles, projLogic); - return JTRUE; - } break; - case PHIT_OUT_OF_RANGE: - { - sound_stop(projLogic->flightSndId); - if (projLogic->flags & PROJFLAG_EXPLODE) - { - if (obj->posWS.y <= sector->floorHeight && obj->posWS.y >= sector->ceilingHeight && (projLogic->type != PROJ_PUNCH || hitType != PHIT_OUT_OF_RANGE)) - { - spawnHitEffect(projLogic->hitEffectId, sector, obj->posWS, projLogic->excludeObj); - } - } - - // Delete the projectile itself. - allocator_addRef(s_projectiles); - deleteLogicAndObject((Logic*)projLogic); - allocator_release(s_projectiles); - allocator_deleteItem(s_projectiles, projLogic); - return JTRUE; - } break; - case PHIT_WATER: - { - sound_stop(projLogic->flightSndId); - spawnHitEffect(HEFFECT_SPLASH, obj->sector, obj->posWS, projLogic->excludeObj); - - // Delete the projectile itself. - allocator_addRef(s_projectiles); - deleteLogicAndObject((Logic*)projLogic); - allocator_release(s_projectiles); - allocator_deleteItem(s_projectiles, projLogic); - return JTRUE; - } break; - } - - return JFALSE; - } - -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/projectile.h b/components/darkforces/tfe/TFE_DarkForces/projectile.h deleted file mode 100644 index 3b7e1aa3..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/projectile.h +++ /dev/null @@ -1,135 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces Projectile - -// The projectile Logic handles the creation, update and effect of -// projectiles in the world. The same system is used by both player -// and enemy projectiles. -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include "logic.h" -#include "hitEffect.h" -#include "sound.h" -#include "time.h" - -namespace TFE_DarkForces -{ - enum ProjectileType - { - PROJ_PUNCH = 0, - PROJ_PISTOL_BOLT, - PROJ_RIFLE_BOLT, - PROJ_THERMAL_DET, - PROJ_REPEATER, - PROJ_PLASMA, - PROJ_MORTAR, - PROJ_LAND_MINE, - PROJ_LAND_MINE_PROX, - PROJ_LAND_MINE_PLACED, - PROJ_CONCUSSION, - PROJ_CANNON, - PROJ_MISSILE, - PROJ_TURRET_BOLT, - PROJ_REMOTE_BOLT, - PROJ_EXP_BARREL, - PROJ_HOMING_MISSILE, - PROJ_PROBE_PROJ, - PROJ_BOBAFET_BALL, - PROJ_COUNT - }; - - enum ProjectileHitType - { - PHIT_SKY = -1, - PHIT_NONE = 0, - PHIT_SOLID = 4, - PHIT_OUT_OF_RANGE = 5, - PHIT_WATER = 6, - }; - - enum WallHitFlag - { - WH_IGNORE = 0, - WH_NOEXP, - WH_STDEXP, - WH_CUSTEXP, - WH_BOUNCE, - WM_COUNT - }; - - enum ProjectileFlags - { - PROJFLAG_CAMERA_PASS_SOUND = FLAG_BIT(0), - PROJFLAG_EXPLODE = FLAG_BIT(1), - }; - - struct ProjectileLogic; - typedef ProjectileHitType(*ProjectileFunc)(ProjectileLogic*); - - // This is a type of "Logic" and can be safety cast to Logic {}. - struct ProjectileLogic - { - Logic logic; // Logic header. - ProjectileType type; - // Damage & Damage falloff. - fixed16_16 dmg; // Base damage - fixed16_16 falloffAmt; // Amount to reduce damage when falloff occurs. - Tick nextFalloffTick; // Next tick that falloff occurs. - Tick dmgFalloffDelta; // Ticks between falloff changes. - fixed16_16 minDmg; // Minimum damage - - fixed16_16 projForce; // How much of the projectile speed translates into force on hit. - vec3_fixed delta; // Movement amount in the current timeslice in units. - vec3_fixed vel; // Projectile velocity in units / second. - fixed16_16 speed; // Projectile speed in units / second. - fixed16_16 col_speed; // Added for TFE to adjust for initial speed for collision detection purposes with small timesteps. - vec3_fixed dir; // Projectile facing direction. - fixed16_16 horzBounciness; - fixed16_16 vertBounciness; - SecObject* prevColObj; - SecObject* prevObj; - SecObject* excludeObj; - Tick duration; // How long the projectile continues to move before going out of range (and being destroyed). - angle14_32 homingAngleSpd; // How quickly a homing projectile lines up in angle units / second. - s32 bounceCnt; - s32 reflVariation; - SoundEffectId flightSndId; // Looping sound instance played while the projectile moves. - SoundSourceId flightSndSource; // Source looping sound. - SoundSourceId cameraPassSnd; // Sound effect played when the projectile passes near the camera. - SoundSourceId reflectSnd; // Sound effect played when the projectile is reflected off of the floor, ceiling or wall. - ProjectileFunc updateFunc; // Projectile update function, this determines how the projectile moves. - HitEffectID reflectEffectId; - HitEffectID hitEffectId; // The effect to play when the projectile hits a solid surface. - u32 flags; - }; - - // Startup the projectile system. - void projectile_startup(); - void projectile_createTask(); - - // Create a new projectile. - Logic* createProjectile(ProjectileType type, RSector* sector, fixed16_16 x, fixed16_16 y, fixed16_16 z, SecObject* obj); - - // Trigger a landmine. - void triggerLandMine(ProjectileLogic* logic, Tick delay); - - void proj_setYawPitch(ProjectileLogic* projLogic, fixed16_16 sinPitch, fixed16_16 cosPitch, fixed16_16 sinYaw, fixed16_16 cosYaw); - void proj_setTransform(ProjectileLogic* projLogic, angle14_32 pitch, angle14_32 yaw); - ProjectileHitType proj_handleMovement(ProjectileLogic* logic); - JBool handleProjectileHit(ProjectileLogic* logic, ProjectileHitType hitType); - - void proj_aimAtTarget(ProjectileLogic* proj, vec3_fixed target); - void proj_aimArcing(ProjectileLogic* proj, vec3_fixed target, fixed16_16 speed); - - // TFE: Serialization functionality. - s32 proj_getLogicIndex(ProjectileLogic* logic); - ProjectileLogic* proj_getByLogicIndex(s32 index); - - // Serialization - void projLogic_serialize(Logic*& logic, SecObject* obj, Stream* stream); - - extern WallHitFlag s_hitWallFlag; - extern angle14_32 s_projReflectOverrideYaw; -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/random.cpp b/components/darkforces/tfe/TFE_DarkForces/random.cpp deleted file mode 100644 index 72ea3eeb..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/random.cpp +++ /dev/null @@ -1,50 +0,0 @@ -#include "random.h" -#include - -namespace TFE_DarkForces -{ - // TODO(Core Game Loop Release): Figure out what this value is at program start up. The value here is from when the program was already running. - // This should cause the random numbers to match up between TFE and DOS. - static u32 s_seed = 0xf444bb3b; - - void random_serialize(Stream* stream) - { - SERIALIZE(SaveVersionInit, s_seed, 0xf444bb3b); - } - - s32 random_next() - { - // Shift the seed by 1 (divide by two), and - // xor the top 8 bits with b10100011 (163) if the starting seed is odd. - // This has the effect of increasing the size of the seed if it gets too small due to the shifts, and increasing "randomness" - if (s_seed & 1) - { - s_seed = (s_seed >> 1) ^ 0xa3000000; - } - else - { - s_seed = (s_seed >> 1); - } - return s32(s_seed); - } - - // Generate a random value as: - // 1) random_next() or - // 2) fixed16_16(value) * fract(random_next()) - s32 random(s32 value) - { - s32 newValue = random_next(); - if (newValue > value || newValue < 0) - { - // Note the value is cast to fixed16_16 but is not actually converted. - // This means that if the incoming value is not fixed point, the result will also not be fixed point. - newValue = mul16(fixed16_16(value), fract16(newValue)); - } - return newValue; - } - - void random_seed(u32 seed) - { - s_seed = seed; - } -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/random.h b/components/darkforces/tfe/TFE_DarkForces/random.h deleted file mode 100644 index a7563b2b..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/random.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces Random number generator -////////////////////////////////////////////////////////////////////// - -#include -#include -#include -#include -#include "logic.h" -#include "time.h" - -namespace TFE_DarkForces -{ - // Generate a random value between [0, value] - s32 random(s32 value); - s32 random_next(); - void random_serialize(Stream* stream); - - void random_seed(u32 seed); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/sound.cpp b/components/darkforces/tfe/TFE_DarkForces/sound.cpp deleted file mode 100644 index c9b91722..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/sound.cpp +++ /dev/null @@ -1,469 +0,0 @@ -#include - -#include "sound.h" -#include "player.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace TFE_DarkForces -{ - struct GameSound - { - SoundEffectId id; - u32 time; - u8* data; - u32 size; - - s32 volume; - s32 refCount; - - s32 priority; - s32 mark; - char name[13]; - }; - struct SoundState - { - Allocator* gameSoundList = nullptr; - s32 instance = 0; - s32 soundLevelStart = -1; - }; - - #define MAX_LEVEL_SOUNDS 300 - #define CUE_RING1 FIXED(30) - #define CUE_RING2 FIXED(150) - - // SoundID is structed as: - // <- Higher .... Lower -> - // 1-bit: always zero (this is the midi flag bit) | 15-bits: instance | 48-bits: pointer offset - static const s64 c_soundIdMask = 0xffffffffffffll; // (1 << 48) - 1 - static const s64 c_soundInstanceShift = 48ll; - static const s32 c_soundInstanceMask = 0x7fff; - static const s32 s_tPan[32] = { 00,-06,-12,-18,-24,-30,-36,-42,-48,-42,-36,-30,-24,-18,-12,-06,00,06,12,18,24,30,36,42,48,42,36,30,24,18,12,06 }; - - static SoundState s_state = {}; - s32 s_lastMaintainVolume; - - SoundEffectId soundInstance(SoundSourceId soundId, s32 instance); - GameSound* getSoundPtr(SoundSourceId id); - void soundCalculateCue(GameSound* sound, fixed16_16 x, fixed16_16 y, fixed16_16 z, s32* vol, s32* pan); - u8* sound_getResource(SoundEffectId id); - void sound_alwaysFree(GameSound* sound); - void sound_clearLevelSounds(); - - // Called at game startup and shutdown. - void sound_open(MemoryRegion* memRegion) - { - s_state = {}; - s_state.gameSoundList = allocator_create(sizeof(GameSound), s_gameRegion); - ImInitialize(memRegion); - - TFE_Settings_Sound* sound = TFE_Settings::getSoundSettings(); - if (sound->use16Channels) - { - ImSetDigitalChannelCount(16); - } - } - - void sound_close() - { - sound_levelStop(); - allocator_free(s_state.gameSoundList); - ImTerminate(); - s_state = {}; - } - - // Called at level startup and shutdown. - void sound_levelStart() - { - TFE_Settings_Sound* soundSettings = TFE_Settings::getSoundSettings(); - TFE_Audio::setVolume(soundSettings->soundFxVolume * soundSettings->masterVolume); - TFE_MidiPlayer::setVolume(soundSettings->musicVolume * soundSettings->masterVolume); - - ImSetResourceCallback(sound_getResource); - s_state.instance = 1; - - // Unload any existing level sounds. - sound_clearLevelSounds(); - } - - void sound_levelStop() - { - sound_stopAll(); - ImSetResourceCallback(nullptr); - } - - s32 sound_getIndexFromId(SoundSourceId id) - { - if (!id) { return -1; } - GameSound* sound = getSoundPtr(id); - return allocator_getIndex(s_state.gameSoundList, sound); - } - - SoundSourceId sound_getSoundFromIndex(s32 index, bool refCount) - { - GameSound* sound = (GameSound*)allocator_getByIndex(s_state.gameSoundList, index); - if (sound) - { - if (refCount) { sound->refCount++; } - return soundInstance((SoundSourceId)sound, 0); - } - return NULL_SOUND; - } - - void sound_setLevelStart() - { - s_state.soundLevelStart = allocator_getCount(s_state.gameSoundList); - } - - void sound_serializeLevelSounds(Stream* stream) - { - s32 count; - if (serialization_getMode() == SMODE_WRITE) - { - count = max(0, allocator_getCount(s_state.gameSoundList) - s_state.soundLevelStart); - } - SERIALIZE(SaveVersionInit, count, 0); - if (serialization_getMode() == SMODE_WRITE) - { - allocator_saveIter(s_state.gameSoundList); - allocator_setPos(s_state.gameSoundList, s_state.soundLevelStart); - GameSound* sound = (GameSound*)allocator_getIter(s_state.gameSoundList); - while (sound) - { - u8 length = (u8)strlen(sound->name); - SERIALIZE(SaveVersionInit, length, 0); - SERIALIZE_BUF(SaveVersionInit, sound->name, length); - SERIALIZE(SaveVersionInit, sound->priority, 64); - sound = (GameSound*)allocator_getNext(s_state.gameSoundList); - } - allocator_restoreIter(s_state.gameSoundList); - } - else - { - sound_clearLevelSounds(); - for (s32 i = 0; i < count; i++) - { - u32 priority; - u8 length; - char name[32]; - SERIALIZE(SaveVersionInit, length, 0); - SERIALIZE_BUF(SaveVersionInit, name, length); - SERIALIZE(SaveVersionInit, priority, 64); - name[length] = 0; - sound_load(name, priority); - } - } - } - - void sound_clearLevelSounds() - { - if (s_state.soundLevelStart < 0) { return; } - allocator_setPos(s_state.gameSoundList, s_state.soundLevelStart); - GameSound* sound = (GameSound*)allocator_getIter(s_state.gameSoundList); - while (sound) - { - sound_alwaysFree(sound); - sound = (GameSound*)allocator_getNext(s_state.gameSoundList); - } - } - - SoundSourceId sound_load(const char* fileName, u32 priority) - { - SoundSourceId newId = NULL_SOUND; - GameSound* sound = (GameSound*)allocator_getHead(s_state.gameSoundList); - while (sound) - { - if (!strcasecmp(fileName, sound->name)) - { - sound->refCount++; - return soundInstance((SoundSourceId)sound, 0); - } - sound = (GameSound*)allocator_getNext(s_state.gameSoundList); - } - - u32 size = 0; -#ifdef TFE_ESPBOX - // The game registers every sound it might need up front (~1.6MB for all enemies, - // weapons and items). Only register the name here; the data is read from the SD - // card the first time the sound plays (sound_playPriority). - u8* data = nullptr; - if (vocFileExists(fileName)) -#else - u8* data = readVocFileData(fileName, &size); - if (data) -#endif - { - sound = (GameSound*)allocator_newItem(s_state.gameSoundList); - sound->id = (SoundSourceId)sound; - sound->time = s_curTick; - sound->data = data; - strncpy(sound->name, fileName, 13); - sound->priority = priority; - sound->size = size; - sound->volume = 127; - sound->refCount = 1; - newId = soundInstance(sound->id, 0); - } - - return newId; - } - - void sound_free(SoundSourceId id) - { - if (id) - { - GameSound* sound = getSoundPtr(id); - sound->refCount--; - - if (sound->refCount == 0) - { - if (sound->data) - { - game_free(sound->data); - } - sound->data = nullptr; - allocator_deleteItem(s_state.gameSoundList, sound); - } - } - } - - void sound_alwaysFree(GameSound* sound) - { - if (sound) - { - if (sound->data) - { - game_free(sound->data); - } - sound->data = nullptr; - allocator_deleteItem(s_state.gameSoundList, sound); - } - } - - void sound_setBaseVolume(SoundSourceId id, s32 volume) - { - GameSound* sound = getSoundPtr(id); - if (sound) - { - sound->volume = volume; - } - } - - void sound_setVolume(SoundEffectId id, s32 volume) - { - if (id) - { - ImSetParam(id, soundVol, volume & 0x7f); - } - } - - void sound_setPan(SoundEffectId id, s32 pan) - { - if (id) - { - ImSetParam(id, soundPan, (pan + 64) & 0x7f); - } - } - - void sound_pitchShift(SoundEffectId soundId, s32 shift) - { - // no-op. - } - - // TFE: added `withCaptions` argument, for non-cued sounds like player weaps and mission VO - SoundEffectId sound_playPriority(SoundSourceId id, s32 priority, JBool withCaptions) - { - if (!id) { return 0; } - - GameSound* sound = getSoundPtr(id); - SoundEffectId idInstance = soundInstance(sound->id, s_state.instance++); - -#ifdef TFE_ESPBOX - if (!sound->data) - { - sound->data = readVocFileData(sound->name, &sound->size); - } -#endif - if (!sound->data) - { - return 0; - } - - if (priority < 0) - { - priority = sound->priority; - } - ImStartSfx(idInstance, priority); - sound_setVolume(idInstance, sound->volume); - if (withCaptions && TFE_A11Y::gameplayCaptionsEnabled()) - { - TFE_A11Y::onSoundPlay(sound->name, TFE_A11Y::CaptionEnv::CC_Gameplay); - } - - return idInstance; - } - - SoundEffectId sound_play(SoundSourceId id) - { - return sound_playPriority(id, -1, JTRUE); - } - - // TFE - SoundEffectId sound_play_noCaptions(SoundSourceId id) - { - return sound_playPriority(id, -1, JFALSE); - } - - SoundEffectId sound_playCued(SoundSourceId id, vec3_fixed pos) - { - SoundEffectId idInstance = 0; - if (id) - { - GameSound* sound = getSoundPtr(id); - s32 vol, pan; - soundCalculateCue(sound, pos.x, pos.y, pos.z, &vol, &pan); - - idInstance = sound_play_noCaptions(id); // TFE; captions for cued sounds come from soundCalculateCue - sound_setVolume(idInstance, vol); - sound_setPan(idInstance, pan); - } - return idInstance; - } - - void sound_adjustCued(SoundEffectId id, vec3_fixed pos) - { - if (id) - { - s32 vol, pan; - GameSound* sound = getSoundPtr(id); - soundCalculateCue(sound, pos.x, pos.y, pos.z, &vol, &pan); - sound_setVolume(id, vol); - sound_setPan(id, pan); - } - } - - void sound_stop(SoundEffectId id) - { - if (id) - { - ImStopSound(id); - } - } - - void sound_stopAll() - { - ImStopAllSounds(); - } - - SoundEffectId sound_maintain(SoundEffectId idInstance, SoundSourceId idSound, vec3_fixed pos) - { - if (idSound) - { - s32 vol, pan; - GameSound* sound = getSoundPtr(idSound); - soundCalculateCue(sound, pos.x, pos.y, pos.z, &vol, &pan); - s_lastMaintainVolume = vol; - - if (vol) - { - // Check to see if the sound is still playing at specific intervals. - if (idInstance && !(s_curTick & 0x0f)) - { - if (ImGetParam(idInstance, soundPlayCount) == 0) - { - sound_stop(idInstance); - idInstance = 0; - } - } - - if (!idInstance) - { - idInstance = sound_play(idSound); - } - sound_setVolume(idInstance, vol); - sound_setPan(idInstance, pan); - } - else if (idInstance) - { - sound_stop(idInstance); - idInstance = 0; - } - return idInstance; - } - return 0; - } - - //////////////////////////////////////////////////////////////////// - // Internal - //////////////////////////////////////////////////////////////////// - void soundCalculateCue(GameSound* sound, fixed16_16 x, fixed16_16 y, fixed16_16 z, s32* vol, s32* pan) - { - fixed16_16 dist = TFE_Jedi::abs(s_eyePos.y - y) + distApprox(x, z, s_eyePos.x, s_eyePos.z); - - // Calculate the volume. - s32 volume = 0; - if (dist < CUE_RING2) - { - if (dist < CUE_RING1) - { - // The sound is within the full volume radius. - volume = sound->volume; - } - else - { - // The sound will be attenuated based on distance. - fixed16_16 ratio = div16(CUE_RING2 - dist, CUE_RING2 - CUE_RING1); - assert(ratio >= 0 && ratio <= ONE_16); -#ifdef TFE_ESPBOX - volume = floor16(ratio * sound->volume); -#else - volume = floor16(mul16(ratio, intToFixed16(sound->volume))); -#endif - volume = min(127, volume); - } - } - *vol = volume; - - // Calculate the pan. - angle14_32 angle = vec2ToAngle(x - s_eyePos.x, z - s_eyePos.z); - angle = getAngleDifference(s_yaw, angle); - *pan = s_tPan[((angle + 8192) / 512) & 31]; - - // TFE subtitles/captions - if (TFE_A11Y::gameplayCaptionsEnabled() && *vol > TFE_Settings::getA11ySettings()->gameplayCaptionMinVolume) - { - TFE_A11Y::onSoundPlay(sound->name, TFE_A11Y::CaptionEnv::CC_Gameplay); - } - } - - SoundEffectId soundInstance(SoundSourceId soundId, s32 instance) - { - SoundEffectId id = soundId; - assert(id >= 0 && id <= c_soundIdMask); - id |= s64(instance & c_soundInstanceMask) << c_soundInstanceShift; - return id; - } - - GameSound* getSoundPtr(SoundSourceId id) - { - assert((id & c_soundIdMask) >= 0); - return (GameSound*)((u8*)(id & c_soundIdMask)); - } - - u8* sound_getResource(SoundEffectId id) - { - GameSound* sound = getSoundPtr(id); - return sound ? sound->data : nullptr; - } -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/sound.h b/components/darkforces/tfe/TFE_DarkForces/sound.h deleted file mode 100644 index dcf26888..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/sound.h +++ /dev/null @@ -1,82 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Jedi Sound System -// Derived from the DOS Dark Forces code. -// This system uses the TFE Framework low level sound system to -// actually manage sounds, but this system is used as a front end to -// ensure the behavior matches the original game. -////////////////////////////////////////////////////////////////////// -#include -#include -#include - -using namespace TFE_Jedi; - -typedef s64 SoundSourceId; -typedef s64 SoundEffectId; -// Null or invalid sound ID -#define NULL_SOUND 0 - -enum SoundPriority -{ - SOUND_PRIORITY_LOW0 = 1, - SOUND_PRIORITY_LOW1 = 4, - SOUND_PRIORITY_LOW2 = 8, - SOUND_PRIORITY_LOW3 = 12, - SOUND_PRIORITY_LOW4 = 16, - SOUND_PRIORITY_LOW5 = 20, - - SOUND_PRIORITY_MED0 = 64, - SOUND_PRIORITY_MED1 = 68, - SOUND_PRIORITY_MED2 = 72, - SOUND_PRIORITY_MED3 = 76, - SOUND_PRIORITY_MED4 = 80, - SOUND_PRIORITY_MED5 = 84, - - SOUND_PRIORITY_HIGH0 = 107, - SOUND_PRIORITY_HIGH1 = 111, - SOUND_PRIORITY_HIGH2 = 115, - SOUND_PRIORITY_HIGH3 = 119, - SOUND_PRIORITY_HIGH4 = 123, - SOUND_PRIORITY_HIGH5 = 127, -}; - -namespace TFE_DarkForces -{ - void sound_open(MemoryRegion* memRegion); - void sound_close(); - - void sound_levelStart(); - void sound_levelStop(); - - SoundEffectId sound_play(SoundSourceId sourceId); - SoundEffectId sound_playPriority(SoundSourceId id, s32 priority); - SoundEffectId sound_playCued(SoundSourceId id, vec3_fixed pos); - SoundEffectId sound_maintain(SoundEffectId idInstance, SoundSourceId idSound, vec3_fixed pos); - void sound_adjustCued(SoundEffectId id, vec3_fixed pos); - // Stop a sound effect that is currently playing. - void sound_stop(SoundEffectId sourceId); - void sound_stopAll(); - - // Let the sound system now where the level sounds start... - void sound_setLevelStart(); - - // Serialization - void sound_serializeLevelSounds(Stream* stream); - - // Load a sound source from disk. - SoundSourceId sound_load(const char* sound, u32 priority = SOUND_PRIORITY_MED0); - void sound_free(SoundSourceId id); - // Change the sound source base volume, range: [0, 127] - void sound_setBaseVolume(SoundSourceId soundId, s32 volume); - // Change the sound effect volume. - void sound_setVolume(SoundEffectId soundId, s32 volume); - // Change the sound effect pan. - void sound_setPan(SoundEffectId soundId, s32 pan); - - void sound_pitchShift(SoundEffectId soundId, s32 shift); - - // Get the sound data index from the id. - s32 sound_getIndexFromId(SoundSourceId id); - SoundSourceId sound_getSoundFromIndex(s32 index, bool refCount = true); -} // namespace TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/time.cpp b/components/darkforces/tfe/TFE_DarkForces/time.cpp deleted file mode 100644 index 1f1b9a96..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/time.cpp +++ /dev/null @@ -1,66 +0,0 @@ -#include "time.h" -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - Tick s_curTick = 0; - Tick s_prevTick = 0; - static f64 s_timeAccum = 0.0; - fixed16_16 s_deltaTime; - fixed16_16 s_frameTicks[13] = { 0 }; - JBool s_pauseTimeUpdate = JFALSE; - - void time_serialize(Stream* stream) - { - SERIALIZE(SaveVersionInit, s_curTick, 0); - SERIALIZE(SaveVersionInit, s_prevTick, 0); - SERIALIZE(SaveVersionInit, s_timeAccum, 0.0); - SERIALIZE(SaveVersionInit, s_deltaTime, 0); - SERIALIZE_BUF(SaveVersionInit, s_frameTicks, sizeof(fixed16_16) * TFE_ARRAYSIZE(s_frameTicks)); - } - - Tick time_frameRateToDelay(u32 frameRate) - { - return Tick(SECONDS_TO_TICKS_ROUNDED / f32(frameRate)); - } - - Tick time_frameRateToDelay(s32 frameRate) - { - return Tick(SECONDS_TO_TICKS_ROUNDED / f32(frameRate)); - } - - Tick time_frameRateToDelay(f32 frameRate) - { - return Tick(SECONDS_TO_TICKS_ROUNDED / frameRate); - } - - void time_pause(JBool pause) - { - s_pauseTimeUpdate = pause; - } - - void updateTime() - { - if (!s_pauseTimeUpdate) - { - s_timeAccum += TFE_System::getDeltaTime() * TIMER_FREQ; - } - - Tick prevTick = s_curTick; - s_curTick = Tick(s_timeAccum); - -#ifdef TFE_ESPBOX - fixed16_16 dt = intToFixed16(s_curTick - prevTick) / TICKS_PER_SECOND; -#else - fixed16_16 dt = div16(intToFixed16(s_curTick - prevTick), FIXED(TICKS_PER_SECOND)); -#endif - for (s32 i = 0; i < 13; i++) - { - s_frameTicks[i] += mul16(dt, intToFixed16(i)); - } - } -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/time.h b/components/darkforces/tfe/TFE_DarkForces/time.h deleted file mode 100644 index 9a22a9be..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/time.h +++ /dev/null @@ -1,57 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces Player - -// Player information and object data. -////////////////////////////////////////////////////////////////////// - -#include -#include -#include -#include - -typedef u32 Tick; -typedef s32 TickSigned; - -namespace TFE_DarkForces -{ - // The actual timer frequency used by the DOS code. - #define TIMER_FREQ 145.6521 - - // Integer number of ticks per second. - #define TICKS_PER_SECOND 145 - - // Exact value from converting from seconds to ticks. - #define SECONDS_TO_TICKS_EXACT f32(TICKS_PER_SECOND) - // Note the extra 0.5f, this seems to be a way of 'rounding' the results. - // This seems to have been done to make the timing slightly more "generous" in some cases (such as elevator delays). - #define SECONDS_TO_TICKS_ROUNDED (SECONDS_TO_TICKS_EXACT + 0.5f) - - // Simple way of setting readable tick constants. - // This is the integer equivalent to x * SECONDS_TO_TICKS_ROUNDED - #define TICKS(x) ((x)*TICKS_PER_SECOND + ((x)>>1)) - - // The maximum delta time = 64 seconds. - // I'm not sure why it is so high, but the original value in the DF code is 0x400000 = 64 * ONE_16 - #define MAX_DELTA_TIME FIXED(64) - - // Current game-time in "ticks" - extern Tick s_curTick; - // Previous frame time in "ticks" - used when calculating s_deltaTime. - extern Tick s_prevTick; - // Delta-time since the last frame in "seconds" - though it is derived from the delta in ticks, so the smallest non-zero - // delta is 1.0 / 145.0, i.e. s_deltaTime = (s_curTick - s_prevTick) / 145.0 - // This is used for movement, physics, elevator value changes based on speed, and similar situations. - extern fixed16_16 s_deltaTime; - // This array ticks at the fps defined by its index. - // Each computes dt*frameRate and the indexed framerate (i.e. s_frameTicks[12] = 12 fps). - extern fixed16_16 s_frameTicks[13]; - - // Convert from frames per second (fps) to Ticks. - Tick time_frameRateToDelay(u32 frameRate); - Tick time_frameRateToDelay(s32 frameRate); - Tick time_frameRateToDelay(f32 frameRate); - void updateTime(); - void time_pause(JBool pause); - - void time_serialize(Stream* stream); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/updateLogic.cpp b/components/darkforces/tfe/TFE_DarkForces/updateLogic.cpp deleted file mode 100644 index 792292c0..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/updateLogic.cpp +++ /dev/null @@ -1,284 +0,0 @@ -#include "updateLogic.h" -#include "player.h" -#include "time.h" -#include "util.h" -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - struct UpdateLogic - { - Logic logic; - - fixed16_16 xVel; - fixed16_16 yVel; - fixed16_16 zVel; - angle14_16 pitchRate; - angle14_16 yawRate; - angle14_16 rollRate; - s16 pad16; - u32 flags; - }; - - enum UpdateLogicFlags - { - ULFLAG_GRAVITY = FLAG_BIT(1), - ULFLAG_PITCH = FLAG_BIT(3), - ULFLAG_YAW = FLAG_BIT(4), - ULFLAG_ROLL = FLAG_BIT(5), - ULFLAG_ALL = 0xffffffff - }; - - static Task* s_logicUpdateTask = nullptr; - static Allocator* s_logicUpdateList = nullptr; - - void updateLogicTaskFunc(MessageType msg); - void updateLogicCleanupFunc(Logic* logic); - - void updateLogic_clearTask() - { - s_logicUpdateList = nullptr; - s_logicUpdateTask = nullptr; - } - - JBool updateLogic_setupFunc(Logic* logic, KEYWORD key) - { - UpdateLogic* updateLogic = (UpdateLogic*)logic; - - char* endPtr = nullptr; - if (key == KW_FLAGS) - { - updateLogic->flags = strToUInt(s_objSeqArg1); - return JTRUE; - } - else if (key == KW_D_PITCH) - { - updateLogic->pitchRate = angle14_16(strtof(s_objSeqArg1, &endPtr) * 16384.0f / 360.0f); - return JTRUE; - } - else if (key == KW_D_YAW) - { - updateLogic->yawRate = angle14_16(strtof(s_objSeqArg1, &endPtr) * 16384.0f / 360.0f); - return JTRUE; - } - else if (key == KW_D_ROLL) - { - updateLogic->rollRate = angle14_16(strtof(s_objSeqArg1, &endPtr) * 16384.0f / 360.0f); - return JTRUE; - } - - return JFALSE; - } - - Logic* obj_setUpdate(SecObject* obj, LogicSetupFunc* setupFunc) - { - if (!s_logicUpdateList) - { - s_logicUpdateList = allocator_create(sizeof(UpdateLogic)); - } - if (!s_logicUpdateTask) - { - s_logicUpdateTask = createTask("update logic", updateLogicTaskFunc); - } - if (setupFunc) - { - *setupFunc = updateLogic_setupFunc; - } - - UpdateLogic* updateLogic = (UpdateLogic*)allocator_newItem(s_logicUpdateList); - updateLogic->flags = ULFLAG_ALL; - updateLogic->zVel = 0; - updateLogic->yVel = 0; - updateLogic->xVel = 0; - updateLogic->rollRate = 0; - updateLogic->pad16 = 0; - updateLogic->yawRate = 0; - updateLogic->pitchRate = 0; - - if (!obj->logic) - { - obj->logic = allocator_create(sizeof(Logic**)); - } - Logic** logicItem = (Logic**)allocator_newItem((Allocator*)obj->logic); - *logicItem = (Logic*)updateLogic; - - updateLogic->logic.obj = obj; - updateLogic->logic.type = LOGIC_UPDATE; - updateLogic->logic.parent = logicItem; - updateLogic->logic.cleanupFunc = updateLogicCleanupFunc; - updateLogic->logic.task = s_logicUpdateTask; - obj->flags &= ~OBJ_FLAG_MOVABLE; - - return (Logic*)updateLogic; - } - - // Serialization - void updateLogic_serialize(Logic*& logic, SecObject* obj, Stream* stream) - { - UpdateLogic* updateLogic; - if (serialization_getMode() == SMODE_WRITE) - { - updateLogic = (UpdateLogic*)logic; - } - else - { - if (!s_logicUpdateList) - { - s_logicUpdateList = allocator_create(sizeof(UpdateLogic)); - } - if (!s_logicUpdateTask) - { - s_logicUpdateTask = createTask("update logic", updateLogicTaskFunc); - } - - updateLogic = (UpdateLogic*)allocator_newItem(s_logicUpdateList); - logic = (Logic*)updateLogic; - - updateLogic->pad16 = 0; - updateLogic->logic.task = s_logicUpdateTask; - updateLogic->logic.cleanupFunc = updateLogicCleanupFunc; - } - SERIALIZE(ObjState_InitVersion, updateLogic->xVel, 0); - SERIALIZE(ObjState_InitVersion, updateLogic->yVel, 0); - SERIALIZE(ObjState_InitVersion, updateLogic->zVel, 0); - SERIALIZE(ObjState_InitVersion, updateLogic->pitchRate, 0); - SERIALIZE(ObjState_InitVersion, updateLogic->yawRate, 0); - SERIALIZE(ObjState_InitVersion, updateLogic->rollRate, 0); - SERIALIZE(ObjState_InitVersion, updateLogic->flags, 0); - } - - void updateLogicTaskFunc(MessageType msg) - { - task_begin; - while (msg != MSG_FREE_TASK) - { - // No need for locals to be persistant. - { - fixed16_16 gravityDelta = mul16(s_gravityAccel, s_deltaTime); - UpdateLogic* updateLogic = (UpdateLogic*)allocator_getHead(s_logicUpdateList); - while (updateLogic) - { - SecObject* renderObj = updateLogic->logic.obj; - fixed16_16 ceilHeight, floorHeight; - fixed16_16 y = renderObj->posWS.y; - RSector* sector = renderObj->sector; - sector_getObjFloorAndCeilHeight(sector, y, &floorHeight, &ceilHeight); - - InfLink* link = (InfLink*)allocator_getHead(sector->infLink); - if (link && link->type == LTYPE_SECTOR) - { - InfElevator* elev = link->elev; - JBool move = JFALSE; - /* TODO: How to get this information from the INF system. - if ((y == sector->floorHeight && (elev->flags & INF_EFLAG_MOVE_FLOOR)) || - (y == sector->floorHeight + sector->secHeight && (elev->flags & INF_EFLAG_MOVE_SECHT))) - { - // This clears out the ceilHeight. - s32 speed; - vec3_fixed vel = { updateLogic->xVel, ceilHeight, updateLogic->zVel }; - inf_getMovingElevatorVelocity(elev, &vel, &speed); - } - */ - } - - if (updateLogic->xVel || updateLogic->zVel) - { - fixed16_16 dx = mul16(updateLogic->xVel, s_deltaTime); - fixed16_16 dz = mul16(updateLogic->zVel, s_deltaTime); - RSector* curSector = renderObj->sector; - fixed16_16 x0 = renderObj->posWS.x; - fixed16_16 z0 = renderObj->posWS.z; - fixed16_16 x1 = renderObj->posWS.x + dx; - fixed16_16 z1 = renderObj->posWS.z + dz; - - RSector* newSector = collision_tryMove(curSector, x0, z0, x1, z1); - if (newSector) - { - renderObj->posWS.x = x1; - renderObj->posWS.z = z1; - if (newSector != curSector) - { - sector_addObject(newSector, renderObj); - } - } - } - - if (updateLogic->flags & ULFLAG_GRAVITY) - { - fixed16_16 yVel = updateLogic->yVel + gravityDelta; - updateLogic->yVel = yVel; - fixed16_16 yNew = renderObj->posWS.y + mul16(s_deltaTime, yVel); - renderObj->posWS.y = yNew; - // Below the ground - if (yNew > floorHeight) - { - updateLogic->yVel = 0; - renderObj->posWS.y = floorHeight; - } - } - - if (updateLogic->xVel || updateLogic->zVel) - { - fixed16_16 friction = ONE_16 - 2*s_deltaTime; // This is NOT the same friction model used by the player. - // xVel *= (1.0 - 2*dt) - updateLogic->xVel = mul16(updateLogic->xVel, friction); - updateLogic->zVel = mul16(updateLogic->zVel, friction); - } - - angle14_16 pitchRate = updateLogic->pitchRate; - angle14_16 yawRate = updateLogic->yawRate; - angle14_16 rollRate = updateLogic->rollRate; - if (pitchRate || yawRate || rollRate) - { - if (pitchRate && (updateLogic->flags & ULFLAG_PITCH)) - { - renderObj->pitch += mul16(pitchRate, s_deltaTime); - } - if (yawRate && (updateLogic->flags & ULFLAG_YAW)) - { - renderObj->yaw += mul16(yawRate, s_deltaTime); - } - if (rollRate && (updateLogic->flags & ULFLAG_ROLL)) - { - renderObj->roll += mul16(rollRate, s_deltaTime); - } - if (renderObj->type == OBJ_TYPE_3D) - { - obj3d_computeTransform(renderObj); - } - } - - updateLogic = (UpdateLogic*)allocator_getNext(s_logicUpdateList); - } - } - task_yield(TASK_NO_DELAY); - } - task_end; - } - - void updateLogicCleanupFunc(Logic* logic) - { - if (!s_freeObjLock) - { - SecObject* obj = logic->obj; - Logic** parent = logic->parent; - Logic** head = (Logic**)allocator_getHead_noIterUpdate((Allocator*)obj->logic); - if (parent == head) - { - allocator_deleteItem((Allocator*)obj->logic, parent); - freeObject(obj); - } - else - { - allocator_deleteItem((Allocator*)obj->logic, parent); - } - } - allocator_deleteItem(s_logicUpdateList, logic); - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/updateLogic.h b/components/darkforces/tfe/TFE_DarkForces/updateLogic.h deleted file mode 100644 index d840bdd3..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/updateLogic.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces Animation Logic- -// Handles cyclic "fire and forget" sprite animations. -// This includes animated sprite objects, explosions, and hit effects. -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include "logic.h" -#include "time.h" - -namespace TFE_DarkForces -{ - void updateLogic_clearTask(); - Logic* obj_setUpdate(SecObject* obj, LogicSetupFunc* setupFunc); - - // Serialization - void updateLogic_serialize(Logic*& logic, SecObject* obj, Stream* stream); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/util.cpp b/components/darkforces/tfe/TFE_DarkForces/util.cpp deleted file mode 100644 index 65bebe53..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/util.cpp +++ /dev/null @@ -1,60 +0,0 @@ -#include - -#include "util.h" -#include - -namespace TFE_DarkForces -{ - char* copyAndAllocateString(const char* start, const char* end) - { - s32 count = s32(end - start); - char* outString = (char*)game_alloc(count + 1); - memcpy(outString, start, count); - outString[count] = 0; - - return outString; - } - - char* copyAndAllocateString(const char* str) - { - size_t count = strlen(str); - char* outString = (char*)game_alloc(count + 1); - memcpy(outString, str, count); - outString[count] = 0; - - return outString; - } - - char* strCopyAndZero(char* dst, const char* src, s32 bufferSize) - { - char* dstPtr = dst; - while (bufferSize > 0) - { - char ch = *src; - if (ch == 0) { break; } - bufferSize--; - *dst = ch; - - src++; - dst++; - } - while (bufferSize) - { - bufferSize--; - *dst = 0; - dst++; - } - return dstPtr; - } - - s32 strToInt(const char* param) - { - char* endPtr = nullptr; - return strtol(param, &endPtr, 10); - } - - u32 strToUInt(const char* param) - { - return (u32)strToInt(param); - } -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/util.h b/components/darkforces/tfe/TFE_DarkForces/util.h deleted file mode 100644 index 3fdf781a..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/util.h +++ /dev/null @@ -1,33 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces Game Message -// This handles HUD messages, local messages, etc. -////////////////////////////////////////////////////////////////////// -#include -#include -#include - -namespace TFE_DarkForces -{ - // language-specific hotkeys - struct LangHotkeys { - KeyboardCode k_yes; - KeyboardCode k_quit; - KeyboardCode k_cont; // resume mission - KeyboardCode k_conf; // configure - KeyboardCode k_agdel; // delete agent - KeyboardCode k_begin; // begin mission - KeyboardCode k_easy; - KeyboardCode k_med; - KeyboardCode k_hard; - KeyboardCode k_canc; - }; - - char* copyAndAllocateString(const char* start, const char* end); - char* copyAndAllocateString(const char* str); - - char* strCopyAndZero(char* dst, const char* src, s32 bufferSize); - - s32 strToInt(const char* param); - u32 strToUInt(const char* param); -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/vueLogic.cpp b/components/darkforces/tfe/TFE_DarkForces/vueLogic.cpp deleted file mode 100644 index 024c34d0..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/vueLogic.cpp +++ /dev/null @@ -1,661 +0,0 @@ -#include -#include - -#include "vueLogic.h" -#include "time.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace TFE_Jedi; - -namespace TFE_DarkForces -{ - enum VueFlags - { - VUE_PAUSED = FLAG_BIT(0), - }; - - enum VueFrameFlags - { - VFRAME_FIRST = FLAG_BIT(0), - }; - - struct VueLogic - { - Logic logic; - - Allocator* frames; - Task* task; - s32 isCamera; - Tick frameDelay; - RSector* sector; - u32 flags; - }; - - struct VueFrame - { - fixed16_16 mtx[9]; - vec3_fixed offset; - - angle14_16 pitch; - angle14_16 yaw; - angle14_16 roll; - u32 flags; - }; - - // Make sure this is local to the current file. - namespace - { - struct LocalContext - { - VueLogic* vue; - JBool searchForSector; - SecObject* obj; - VueFrame* frame; - VueFrame* interpolatedFrame; - VueFrame* previous; - VueFrame* current; - Tick tick; - Tick pauseTick; - s32 prevFrame; - }; - } - - static char* s_workBuffer = nullptr; - static size_t s_workBufferSize = 0; - - JBool vueLogicSetupFunc(Logic* logic, KEYWORD key); - void vueLogicTaskFunc(MessageType msg); - void vueLogicCleanupFunc(Logic *logic); - - Logic* obj_createVueLogic(SecObject* obj, LogicSetupFunc* setupFunc) - { - VueLogic* vueLogic = (VueLogic*)level_alloc(sizeof(VueLogic)); - - vueLogic->logic.obj = obj; - vueLogic->frames = nullptr; - vueLogic->frameDelay = 9; // 9 Ticks between frames = ~16 fps - vueLogic->flags = 0; - - obj->entityFlags |= ETFLAG_CAN_WAKE; - - Task* task = createSubTask("vueLogic", vueLogicTaskFunc); - vueLogic->task = task; - task_setUserData(task, vueLogic); - - obj_addLogic(obj, (Logic*)vueLogic, LOGIC_VUE, task, vueLogicCleanupFunc); - *setupFunc = vueLogicSetupFunc; - - return (Logic*)vueLogic; - } - - void vueLogic_serializeFramePointer(Stream* stream, VueLogic* logic, VueFrame** frame, bool modeWrite, s32 version) - { - s32 index = -1; - if (modeWrite && logic->frames && *frame) - { - index = allocator_getIndex(logic->frames, *frame); - } - SERIALIZE(version, index, -1); - if (!modeWrite) - { - *frame = (index >= 0) ? (VueFrame*)allocator_getByIndex(logic->frames, index) : nullptr; - } - } - - void vueLogic_serializeTaskLocalMemory(Stream* stream, void* userData, void* mem) - { - VueLogic* self = (VueLogic*)userData; - LocalContext* locals = (LocalContext*)mem; - bool modeWrite = serialization_getMode() == SMODE_WRITE; - if (!modeWrite) - { - locals->vue = self; - } - SERIALIZE(SaveVersionInit, locals->searchForSector, 0); - s32 objIndex = -1; - if (modeWrite) - { - objIndex = locals->obj->serializeIndex; - } - SERIALIZE(SaveVersionInit, objIndex, -1); - if (!modeWrite) - { - locals->obj = nullptr; - if (objIndex >= 0) - { - locals->obj = objData_getObjectBySerializationId(objIndex); - } - } - - // local frame pointers. - vueLogic_serializeFramePointer(stream, self, &locals->frame, modeWrite, SaveVersionInit); - vueLogic_serializeFramePointer(stream, self, &locals->interpolatedFrame, modeWrite, ObjState_VueSmoothing); - vueLogic_serializeFramePointer(stream, self, &locals->previous, modeWrite, ObjState_VueSmoothing); - vueLogic_serializeFramePointer(stream, self, &locals->current, modeWrite, ObjState_VueSmoothing); - - SERIALIZE(SaveVersionInit, locals->tick, 0); - SERIALIZE(SaveVersionInit, locals->pauseTick, 0); - SERIALIZE(SaveVersionInit, locals->prevFrame, 0); - } - - // Serialization - void vueLogic_serialize(Logic*& logic, SecObject* obj, Stream* stream) - { - VueLogic* vueLogic; - if (serialization_getMode() == SMODE_WRITE) - { - vueLogic = (VueLogic*)logic; - } - else - { - vueLogic = (VueLogic*)level_alloc(sizeof(VueLogic)); - logic = (Logic*)vueLogic; - - Task* task = createSubTask("vueLogic", vueLogicTaskFunc); - vueLogic->task = task; - task_setUserData(task, vueLogic); - - vueLogic->logic.task = task; - vueLogic->logic.cleanupFunc = vueLogicCleanupFunc; - } - - s32 frameCount; - if (serialization_getMode() == SMODE_WRITE) - { - // Frames - frameCount = allocator_getCount(vueLogic->frames); - SERIALIZE(ObjState_InitVersion, frameCount, 0); - allocator_saveIter(vueLogic->frames); - VueFrame* frame = (VueFrame*)allocator_getHead(vueLogic->frames); - while (frame) - { - SERIALIZE(ObjState_InitVersion, (*frame), { 0 }); - frame = (VueFrame*)allocator_getNext(vueLogic->frames); - } - allocator_restoreIter(vueLogic->frames); - } - else - { - SERIALIZE(ObjState_InitVersion, frameCount, 0); - vueLogic->frames = allocator_create(sizeof(VueFrame)); - for (s32 i = 0; i < frameCount; i++) - { - VueFrame* frame = (VueFrame*)allocator_newItem(vueLogic->frames); - SERIALIZE(ObjState_InitVersion, (*frame), { 0 }); - } - } - - SERIALIZE(ObjState_InitVersion, vueLogic->isCamera, 0); - SERIALIZE(ObjState_InitVersion, vueLogic->frameDelay, 0); - serialization_serializeSectorPtr(stream, ObjState_InitVersion, vueLogic->sector); - SERIALIZE(ObjState_InitVersion, vueLogic->flags, 0); - - task_serializeState(stream, vueLogic->logic.task, vueLogic, vueLogic_serializeTaskLocalMemory); - } - - void loadVueFile(Allocator* vueList, char* transformName, TFE_Parser* parser) - { - size_t bufferPos = 0; - if (!strcasecmp(transformName, "camera")) - { - while (1) - { - const char* line = parser->readLine(bufferPos); - if (!line) { break; } - - f32 x1, z1, y1, x2, z2, y2, r, lens; - if (sscanf(line, "camera %f %f %f %f %f %f %f %f", &x1, &z1, &y1, &x2, &z2, &y2, &r, &lens) == 8) - { - y1 = -y1; - y2 = -y2; - VueFrame* frame = (VueFrame*)allocator_newItem(vueList); - frame->offset.x = floatToFixed16(x1); - frame->offset.y = floatToFixed16(y1); - frame->offset.z = floatToFixed16(z1); - frame->yaw = vec2ToAngle(floatToFixed16(x2 - x1), floatToFixed16(z2 - z1)); - frame->pitch = 0; - frame->roll = angle14_32(r * 16383.0f / 360.0f); - } - } - } - else - { - // Matrix 0 - fixed16_16 mtx0[9]; - mtx0[0] = ONE_16; - mtx0[1] = 0; - mtx0[2] = 0; - - mtx0[3] = 0; - mtx0[4] = 1; - mtx0[5] = ONE_16 - 1; - - mtx0[6] = 0; - mtx0[7] = -ONE_16 + 1; - mtx0[8] = 1; - - // Matrix 1 - fixed16_16 mtx1[9]; - mtx1[0] = ONE_16; - mtx1[1] = 0; - mtx1[2] = 0; - - mtx1[3] = 0; - mtx1[4] = 1; - mtx1[5] = ONE_16 - 1; - - mtx1[6] = 0; - mtx1[7] = -ONE_16 + 1; - mtx1[8] = 1; - - VueFrame* frame = (VueFrame*)allocator_newItem(vueList); - frame->flags = VFRAME_FIRST; - - while (1) - { - const char* line = parser->readLine(bufferPos); - if (!line) - { - break; - } - - char name[32]; - f32 f00, f01, f02, f03, f04, f05, f06, f07, f08, f09, f10, f11; - s32 count = sscanf(line, "transform %s %f %f %f %f %f %f %f %f %f %f %f %f", name, &f00, &f01, &f02, &f03, &f04, &f05, &f06, &f07, &f08, &f09, &f10, &f11); - if (count == 13) - { - // Is this the correct transform? - if (transformName[0] == '*' || strcasecmp(name, transformName) == 0) - { - frame = (VueFrame*)allocator_newItem(vueList); - - // Rotation/Scale matrix. - fixed16_16 frameMtx[9]; - frameMtx[0] = floatToFixed16(f00); - frameMtx[1] = floatToFixed16(f01); - frameMtx[2] = floatToFixed16(f02); - frameMtx[3] = floatToFixed16(f03); - frameMtx[4] = floatToFixed16(f04); - frameMtx[5] = floatToFixed16(f05); - frameMtx[6] = floatToFixed16(f06); - frameMtx[7] = floatToFixed16(f07); - frameMtx[8] = floatToFixed16(f08); - - // Transform to DF coordinate system. - fixed16_16 tempMtx[9]; - mulMatrix3x3(mtx1, frameMtx, tempMtx); - mulMatrix3x3(tempMtx, mtx0, frame->mtx); - - frame->offset.x = floatToFixed16(f09); - frame->offset.y = -floatToFixed16(f11); - frame->offset.z = floatToFixed16(f10); - - frame->yaw = 8191; - frame->flags = 0; - } - } - } - } - } - - void vue_resetState() - { - s_workBufferSize = 0; - s_workBuffer = nullptr; - } - - char* allocateWorkBuffer(size_t size) - { - if (size > s_workBufferSize) - { - s_workBufferSize = size + 1024; - s_workBuffer = (char*)game_realloc(s_workBuffer, s_workBufferSize); - } - assert(s_workBuffer); - return s_workBuffer; - } - - JBool createParserFromFile(FilePath* filePath, TFE_Parser* parser) - { - assert(filePath && parser); - - FileStream file; - size_t size = 0; - char* buffer = nullptr; - if (file.open(filePath, Stream::MODE_READ)) - { - size = file.getSize(); - buffer = allocateWorkBuffer(size); - file.readBuffer(buffer, (u32)size); - } - file.close(); - - if (!buffer || !size) - { - return JFALSE; - } - - parser->init(buffer, size); - parser->addCommentString("//"); - parser->addCommentString("#"); - return JTRUE; - } - - Allocator* key_loadVue(char* arg1, char* arg2, s32 isCamera) - { - FilePath filePath; - if (!TFE_Paths::getFilePath(arg1, &filePath)) - { - TFE_System::logWrite(LOG_ERROR, "VUE", "key_loadVue: COULD NOT OPEN."); - return nullptr; - } - TFE_Parser parser; - if (!createParserFromFile(&filePath, &parser)) - { - TFE_System::logWrite(LOG_ERROR, "VUE", "key_loadVue: COULD NOT OPEN."); - return nullptr; - } - - Allocator* vueList = allocator_create(sizeof(VueFrame)); - loadVueFile(vueList, arg2, &parser); - - return vueList; - } - - Allocator* key_appendVue(char* arg1, char* arg2, Allocator* frames) - { - FilePath filePath; - if (!TFE_Paths::getFilePath(arg1, &filePath)) - { - TFE_System::logWrite(LOG_ERROR, "VUE", "key_appendVue: COULD NOT OPEN."); - return frames; - } - TFE_Parser parser; - if (!createParserFromFile(&filePath, &parser)) - { - TFE_System::logWrite(LOG_ERROR, "VUE", "key_appendVue: COULD NOT OPEN."); - return frames; - } - - loadVueFile(frames, arg2, &parser); - return frames; - } - - void key_setViewFrames(VueLogic* vueLogic, Allocator* frames, s32 isCamera) - { - vueLogic->frames = frames; - vueLogic->isCamera = isCamera; - task_makeActive(vueLogic->task); - } - - JBool vueLogicSetupFunc(Logic* logic, KEYWORD key) - { - VueLogic* vueLogic = (VueLogic*)logic; - char* endPtr = nullptr; - - if (key == KW_VUE) - { - s32 isCamera = 0; - if (s_objSeqArgCount < 3) - { - s_objSeqArg2[0] = '*'; - } - else - { - __strupr(s_objSeqArg2); - if (strstr(s_objSeqArg2, "CAMERA")) - { - isCamera = 1; - } - } - Allocator* frames = key_loadVue(s_objSeqArg1, s_objSeqArg2, isCamera); - key_setViewFrames(vueLogic, frames, isCamera); - return JTRUE; - } - else if (key == KW_VUE_APPEND) - { - s32 isCamera = 0; - if (s_objSeqArgCount < 3) - { - s_objSeqArg2[0] = '*'; - } - else - { - __strupr(s_objSeqArg2); - if (strstr(s_objSeqArg2, "CAMERA")) - { - isCamera = 1; - } - } - key_appendVue(s_objSeqArg1, s_objSeqArg2, vueLogic->frames); - return JTRUE; - } - else if (key == KW_FRAME_RATE) - { - vueLogic->frameDelay = time_frameRateToDelay(strtof(s_objSeqArg1, &endPtr)); - return JTRUE; - } - else if (key == KW_PAUSE) - { - vueLogic->flags |= VUE_PAUSED; - return JTRUE; - } - return JFALSE; - } - - fixed16_16 lerp(fixed16_16 a, fixed16_16 b, f32 t) - { - fixed16_16 tfixed = floatToFixed16(t); - fixed16_16 invtfixed = floatToFixed16(1 - t); - return mul16(b, tfixed) + mul16(a, invtfixed); - } - - // Interpolate from 'previous' to 'current' based on 't' and store the results in 'interpolatedFrame'. - void interpolateFrame(VueFrame* interpolatedFrame, const VueFrame* previous, const VueFrame* current, f32 t) - { - // This is a linear approximation that works due to the regular nature of the keyframes and small deltas. - for (s32 i = 0; i < 9; i++) - { - interpolatedFrame->mtx[i] = lerp(previous->mtx[i], current->mtx[i], t); - } - // Use linear interpolation for offset and angles. - interpolatedFrame->offset.x = lerp(previous->offset.x, current->offset.x, t); - interpolatedFrame->offset.y = lerp(previous->offset.y, current->offset.y, t); - interpolatedFrame->offset.z = lerp(previous->offset.z, current->offset.z, t); - interpolatedFrame->pitch = lerp(previous->pitch, current->pitch, t); - interpolatedFrame->yaw = lerp(previous->yaw, current->yaw, t); - interpolatedFrame->roll = lerp(previous->roll, current->roll, t); - // Copy the flags from the current frame. - interpolatedFrame->flags = current->flags; - } - - void vueLogicTaskFunc(MessageType msg) - { - task_begin_ctx; - - local(vue) = (VueLogic*)task_getUserData(); - local(searchForSector) = JTRUE; - local(obj) = local(vue)->logic.obj; - local(vue)->sector = local(obj)->sector; - - while (msg != MSG_FREE_TASK) - { - if (local(vue)->frames) - { - if (local(vue)->isCamera > 0) - { - // The original code sets the camera pointer to the VUE. - // But then this is never used. - // - // s_camera = local(vue); - } - - local(frame) = (VueFrame*)allocator_getHead(local(vue)->frames); - local(searchForSector) = JTRUE; - local(tick) = s_curTick; - local(prevFrame) = 0; - if (!local(frame)) - { - break; - } - - while (local(frame)) - { - if (local(frame)->flags & VFRAME_FIRST) - { - if (local(vue)->flags & VUE_PAUSED) - { - local(pauseTick) = s_curTick; - entity_yield(TASK_SLEEP); - - task_makeActive(task_getCurrent()); - local(tick) += s_curTick - local(pauseTick); - entity_yield(TASK_NO_DELAY); - } - local(frame) = (VueFrame*)allocator_getNext(local(vue)->frames); - } - else - { - task_localBlockBegin; - memcpy(local(obj)->transform, local(frame)->mtx, 9 * sizeof(fixed16_16)); - RSector* newSector = nullptr; - - JBool useCollision = JFALSE; - if (local(vue)->sector && local(vue)->sector != s_levelState.controlSector) - { - useCollision = !local(searchForSector); - } - - if (useCollision) - { - RWall* wall = collision_wallCollisionFromPath(local(vue)->sector, local(obj)->posWS.x, local(obj)->posWS.z, local(frame)->offset.x, local(frame)->offset.z); - while (wall) - { - if (wall->nextSector) - { - newSector = wall->nextSector; - wall = collision_pathWallCollision(newSector); - } - else - { - break; - } - } - if (wall) - { - newSector = s_levelState.controlSector; - } - } - else - { - newSector = sector_which3D(local(frame)->offset.x, local(frame)->offset.y, local(frame)->offset.z); - if (!newSector) - { - newSector = s_levelState.controlSector; - } - local(searchForSector) = JFALSE; - } - - if (newSector) - { - sector_addObject(newSector, local(obj)); - local(vue)->sector = newSector; - } - - local(obj)->posWS = local(frame)->offset; - local(obj)->yaw = local(frame)->yaw; - task_localBlockEnd; - - entity_yield(TASK_NO_DELAY); - if (msg == MSG_FREE_TASK) { break; } - - Tick dt = s_curTick - local(tick); - s32 frameIndex; - f32 t = 0.0f; - bool smoothVUEs = TFE_Settings::getGameSettings()->df_smoothVUEs; - if (smoothVUEs) - { - f32 frameIndexF = f32(dt) / f32(local(vue)->frameDelay); - t = std::modf(frameIndexF, &frameIndexF); //normalized progress from prev to cur frame - frameIndex = s32(frameIndexF); - } - else - { - //vanilla behavior - frameIndex = dt / local(vue)->frameDelay; - } - - for (; local(prevFrame) != frameIndex && local(frame); local(prevFrame)++) - { - local(frame) = (VueFrame*)allocator_getNext(local(vue)->frames); - - // We added the interpolated frame to the end of the frame sequence, so we need to make sure we ignore it rather - // than trying to play it as part of the sequence. - if (local(interpolatedFrame) && local(frame) == local(interpolatedFrame)) { local(frame) = nullptr; } - - if (smoothVUEs) - { - if (local(frame) && local(current) != local(frame)) { - local(previous) = local(current); - local(current) = local(frame); - } - } - - if (!local(frame) || ((local(vue)->flags & VUE_PAUSED) && (local(frame)->flags & VFRAME_FIRST))) - { - break; - } - } - - // If VUE smoothing is enabled, interpolate from previous frame to current frame, giving smooth motion at high framerates. - if (smoothVUEs) - { - // If distance between frames is longer than this, object teleported. - const fixed16_16 MAX_INTERP_DISTANCE = FIXED(2500); // FIXED(50 * 50) - - if (!local(interpolatedFrame)) { local(interpolatedFrame) = (VueFrame*)allocator_newItem(local(vue)->frames); } - if (local(frame) && local(current) && local(previous)) - { - const fixed16_16 dist = fixedSquaredDistance(local(current)->offset, local(previous)->offset); - - // Sanity check; distance will be less than 0 if it overflowed (e.g. talay takeoff animation) - if (dist >= 0 && dist < MAX_INTERP_DISTANCE) - { - interpolateFrame(local(interpolatedFrame), local(previous), local(current), t); - local(frame) = local(interpolatedFrame); - } - } - } - } - } // while (frame) - } - else - { - entity_yield(TASK_SLEEP); - } - } // while (msg != MSG_FREE_TASK) - - deleteLogicAndObject((Logic*)local(vue)); - task_end; - } - - void vueLogicCleanupFunc(Logic *logic) - { - deleteLogicAndObject(logic); - task_free(logic->task); - } - -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/vueLogic.h b/components/darkforces/tfe/TFE_DarkForces/vueLogic.h deleted file mode 100644 index a41a5a58..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/vueLogic.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces Animation Logic- -// Handles cyclic "fire and forget" sprite animations. -// This includes animated sprite objects, explosions, and hit effects. -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include "logic.h" -#include "time.h" - -namespace TFE_DarkForces -{ - Logic* obj_createVueLogic(SecObject* obj, LogicSetupFunc* setupFunc); - - void vue_resetState(); - - // Serialization - void vueLogic_serialize(Logic*& logic, SecObject* obj, Stream* stream); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/weapon.cpp b/components/darkforces/tfe/TFE_DarkForces/weapon.cpp deleted file mode 100644 index 7bd1a397..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/weapon.cpp +++ /dev/null @@ -1,1332 +0,0 @@ -#include "weapon.h" -#include -#include "player.h" -#include "pickup.h" -#include "weaponFireFunc.h" -#include -#include -#include -#include -#include -#include -#include -#include - -namespace TFE_DarkForces -{ - /////////////////////////////////////////// - // Internal State - /////////////////////////////////////////// - static JBool s_weaponTexturesLoaded = JFALSE; - static JBool s_switchWeapons = JFALSE; - static JBool s_queWeaponSwitch = JFALSE; - - static TextureData* s_rhand1 = nullptr; - static TextureData* s_gasmaskTexture = nullptr; -#ifdef TFE_ESPBOX - static PlayerWeapon* s_playerWeaponList = nullptr; // WPN_COUNT entries (shared memory) -#else - static PlayerWeapon s_playerWeaponList[WPN_COUNT]; -#endif - - static Tick s_weaponDelayPrimary; - static Tick s_weaponDelaySeconary; - static s32* s_canFirePrimPtr; - static s32* s_canFireSecPtr; - - WeaponAnimState s_weaponAnimState; - - s32 s_prevWeapon; - s32 s_curWeapon; - s32 s_nextWeapon; - s32 s_lastWeapon; - - JBool s_weaponAutoMount2 = JFALSE; - JBool s_secondaryFire = JFALSE; - JBool s_weaponOffAnim = JFALSE; - JBool s_isShooting = JFALSE; - s32 s_canFireWeaponSec; - s32 s_canFireWeaponPrim; - u32 s_fireFrame = 0; - - SoundSourceId s_punchSwingSndSrc; - SoundSourceId s_pistolSndSrc; - SoundSourceId s_pistolEmptySndSrc; - SoundSourceId s_rifleSndSrc; - SoundSourceId s_rifleEmptySndSrc; - SoundSourceId s_fusion1SndSrc; - SoundSourceId s_fusion2SndSrc; - SoundSourceId s_repeaterSndSrc; - SoundSourceId s_repeater1SndSrc; - SoundSourceId s_repeaterEmptySndSrc; - SoundSourceId s_mortarFireSndSrc; - SoundSourceId s_mortarFireSndSrc2; - SoundSourceId s_mortarEmptySndSrc; - SoundSourceId s_mineSndSrc; - SoundSourceId s_concussion6SndSrc; - SoundSourceId s_concussion5SndSrc; - SoundSourceId s_concussion1SndSrc; - SoundSourceId s_plasma4SndSrc; - SoundSourceId s_plasmaEmptySndSrc; - SoundSourceId s_missile1SndSrc; - SoundSourceId s_weaponChangeSnd; - - SoundEffectId s_repeaterFireSndID = 0; - - /////////////////////////////////////////// - // Shared State - /////////////////////////////////////////// - PlayerWeapon* s_curPlayerWeapon = nullptr; - SoundSourceId s_superchargeCountdownSound; - Task* s_playerWeaponTask = nullptr; - - /////////////////////////////////////////// - // Forward Declarations - /////////////////////////////////////////// - TextureData* loadWeaponTexture(const char* texName); - void weapon_loadTextures(); - void weapon_setFireRateInternal(WeaponFireMode mode, Tick delay, s32* canFire); - void weapon_playerWeaponTaskFunc(MessageType msg); - void weapon_handleOnAnimation(MessageType msg); - void weapon_prepareToFire(); - - static WeaponFireFunc s_weaponFireFunc[WPN_COUNT] = - { - weaponFire_fist, // WPN_FIST - weaponFire_pistol, // WPN_PISTOL - weaponFire_rifle, // WPN_RIFLE - weaponFire_thermalDetonator,// WPN_THERMAL_DET - weaponFire_repeater, // WPN_REPEATER - weaponFire_fusion, // WPN_FUSION - weaponFire_mortar, // WPN_MORTAR - weaponFire_mine, // WPN_MINE - weaponFire_concussion, // WPN_CONCUSSION - weaponFire_cannon // WPN_CANNON - }; - - /////////////////////////////////////////// - // API Implementation - /////////////////////////////////////////// - void weapon_resetState() - { - s_weaponTexturesLoaded = JFALSE; - s_switchWeapons = JFALSE; - s_queWeaponSwitch = JFALSE; - - s_rhand1 = nullptr; - s_gasmaskTexture = nullptr; - - s_weaponAutoMount2 = JFALSE; - s_secondaryFire = JFALSE; - s_weaponOffAnim = JFALSE; - s_isShooting = JFALSE; - - s_fireFrame = 0; - s_curPlayerWeapon = nullptr; - s_playerWeaponTask = nullptr; - } - - void weapon_serialize(Stream* stream) - { - SERIALIZE(SaveVersionInit, s_weaponAnimState, { 0 }); - SERIALIZE(SaveVersionInit, s_prevWeapon, 0); - SERIALIZE(SaveVersionInit, s_curWeapon, 0); - SERIALIZE(SaveVersionInit, s_nextWeapon, 0); - SERIALIZE(SaveVersionInit, s_lastWeapon, 0); - - SERIALIZE(SaveVersionInit, s_switchWeapons, JFALSE); - SERIALIZE(SaveVersionInit, s_queWeaponSwitch, JFALSE); - SERIALIZE(SaveVersionInit, s_weaponAutoMount2, JFALSE); - SERIALIZE(SaveVersionInit, s_secondaryFire, JFALSE); - SERIALIZE(SaveVersionInit, s_weaponOffAnim, JFALSE); - SERIALIZE(SaveVersionInit, s_isShooting, JFALSE); - SERIALIZE(SaveVersionInit, s_fireFrame, 0); - - s32 curWpnIndex = -1; - if (serialization_getMode() == SMODE_WRITE && s_curPlayerWeapon) - { - curWpnIndex = PTR_INDEX_S32(s_curPlayerWeapon, s_playerWeaponList, sizeof(PlayerWeapon)); - } - SERIALIZE(SaveVersionInit, curWpnIndex, -1); - if (serialization_getMode() == SMODE_READ) - { - s_curPlayerWeapon = nullptr; - if (curWpnIndex >= 0) - { - s_curPlayerWeapon = &s_playerWeaponList[curWpnIndex]; - } - } - - if (s_curPlayerWeapon) - { - SERIALIZE(SaveVersionInit, s_curPlayerWeapon->frame, 0); - SERIALIZE(SaveVersionInit, s_curPlayerWeapon->flags, 0); - SERIALIZE(SaveVersionInit, s_curPlayerWeapon->rollOffset, 0); - SERIALIZE(SaveVersionInit, s_curPlayerWeapon->pchOffset, 0); - SERIALIZE(SaveVersionInit, s_curPlayerWeapon->xWaveOffset, 0); - SERIALIZE(SaveVersionInit, s_curPlayerWeapon->yWaveOffset, 0); - SERIALIZE(SaveVersionInit, s_curPlayerWeapon->xOffset, 0); - SERIALIZE(SaveVersionInit, s_curPlayerWeapon->yOffset, 0); - } - } - - void weapon_startup() - { - // TODO: Move this into data instead of hard coding it like vanilla Dark Forces. - s_playerWeaponList[WPN_FIST] = - { - 4, // frameCount - {nullptr}, // frames[] - 0, // frame - {172, 55, 59, 56}, // xPos[] - {141, 167, 114, 141}, // yPos[] - 7, // flags - 0, // rollOffset - 0, // pchOffset - 0, // xWaveOffset - 0, // yWaveOffset - 0, // xOffset - 0, // yOffset - nullptr, // ammo - nullptr, // secondaryAmmo - 0, // u8c - 0, // u90 - 0, // wakeupRange - 0, // variation - }; - s_playerWeaponList[WPN_PISTOL] = - { - 3, // frameCount - {nullptr}, // frames[] - 0, // frame - {0xa5, 0xa9, 0xa9}, // xPos[] - {0x8e, 0x88, 0x88}, // yPos[] - 7, // flags - 0, // rollOffset - 0, // pchOffset - 0, // xWaveOffset - 0, // yWaveOffset - 0, // xOffset - 0, // yOffset - &s_playerInfo.ammoEnergy,// ammo - nullptr, // secondaryAmmo - 0, // u8c - 0, // u90 - FIXED(45), // wakeupRange - 22, // variation - }; - s_playerWeaponList[WPN_RIFLE] = - { - 2, // frameCount - {nullptr}, // frames[] - 0, // frame - {0x71, 0x70}, // xPos[] - {0x7f, 0x72}, // yPos[] - 7, // flags - 0, // rollOffset - 0, // pchOffset - 0, // xWaveOffset - 0, // yWaveOffset - 0, // xOffset - 0, // yOffset - &s_playerInfo.ammoEnergy,// ammo - nullptr, // secondaryAmmo - 0, // u8c - 0, // u90 - FIXED(50), // wakeupRange - 0x56, // variation - }; - s_playerWeaponList[WPN_THERMAL_DET] = - { - 4, // frameCount - {nullptr}, // frames[] - 0, // frame - {0xa1, 0xb3, 0xb4, 0x84},// xPos[] - {0x83, 0xa5, 0x66, 0x96},// yPos[] - 7, // flags - 0, // rollOffset - 0, // pchOffset - 0, // xWaveOffset - 0, // yWaveOffset - 0, // xOffset - 0, // yOffset - &s_playerInfo.ammoDetonator,// ammo - nullptr, // secondaryAmmo - 0, // u8c - 0, // u90 - 0, // wakeupRange - 0x2d002d, // variation - }; - s_playerWeaponList[WPN_REPEATER] = - { - 3, // frameCount - {nullptr}, // frames[] - 0, // frame - {0x9c, 0xa3, 0xa3}, // xPos[] - {0x8a, 0x8c, 0x8c}, // yPos[] - 7, // flags - 0, // rollOffset - 0, // pchOffset - 0, // xWaveOffset - 0, // yWaveOffset - 0, // xOffset - 0, // yOffset - &s_playerInfo.ammoPower,// ammo - nullptr, // secondaryAmmo - 0, // u8c - 0, // u90 - FIXED(60), // wakeupRange - 0x2d002d, // variation - }; - s_playerWeaponList[WPN_FUSION] = - { - 6, // frameCount - {nullptr}, // frames[] - 0, // frame - {0x13, 0x17, 0x17, 0x17, 0x17, 0x17},// xPos[] - {0x98, 0x9b, 0x9b, 0x9b, 0x9b, 0x9b},// yPos[] - 7, // flags - 0, // rollOffset - 0, // pchOffset - 0, // xWaveOffset - 0, // yWaveOffset - 0, // xOffset - 0, // yOffset - &s_playerInfo.ammoPower,// ammo - nullptr, // secondaryAmmo - 0, // u8c - 0, // u90 - FIXED(55), // wakeupRange - 0x2d, // variation - }; - s_playerWeaponList[WPN_MORTAR] = - { - 4, // frameCount - {nullptr}, // frames[] - 0, // frame - {0x7b, 0x7e, 0x7f, 0x7b},// xPos[] - {0x77, 0x75, 0x77, 0x74},// yPos[] - 7, // flags - 0, // rollOffset - 0, // pchOffset - 0, // xWaveOffset - 0, // yWaveOffset - 0, // xOffset - 0, // yOffset - &s_playerInfo.ammoShell,// ammo - nullptr, // secondaryAmmo - 0, // u8c - 0, // u90 - FIXED(60), // wakeupRange - 0x2d, // variation - }; - s_playerWeaponList[WPN_MINE] = - { - 3, // frameCount - {nullptr}, // frames[] - 0, // frame - {0x69, 0x69, 0x84}, // xPos[] - {0x99, 0x99, 0x96}, // yPos[] - 7, // flags - 0, // rollOffset - 0, // pchOffset - 0, // xWaveOffset - 0, // yWaveOffset - 0, // xOffset - 0, // yOffset - &s_playerInfo.ammoMine, // ammo - nullptr, // secondaryAmmo - 0, // u8c - 0, // u90 - 0, // wakeupRange - 0, // variation - }; - s_playerWeaponList[WPN_CONCUSSION] = - { - 3, // frameCount - {nullptr}, // frames[] - 0, // frame - {0x82, 0xbf, 0xbc}, // xPos[] - {0x83, 0x81, 0x84}, // yPos[] - 7, // flags - 0, // rollOffset - 0, // pchOffset - 0, // xWaveOffset - 0, // yWaveOffset - 0, // xOffset - 0, // yOffset - &s_playerInfo.ammoPower,// ammo - nullptr, // secondaryAmmo - 0, // u8c - 0, // u90 - FIXED(70), // wakeupRange - 0, // variation - }; - s_playerWeaponList[WPN_CANNON] = - { - 4, // frameCount - {nullptr}, // frames[] - 0, // frame - {206, 208, 224, 230}, // xPos[] - {-74, -60, 81, 86}, // yPos[] - 7, // flags - 0, // rollOffset - 0, // pchOffset - 0, // xWaveOffset - 0, // yWaveOffset - 0, // xOffset - 0, // yOffset - &s_playerInfo.ammoPlasma,// ammo - &s_playerInfo.ammoMissile,// secondaryAmmo - 0, // u8c - 0, // u90 - FIXED(55), // wakeupRange - 0x2d002d, // variation - }; - - // Load Textures. - weapon_loadTextures(); - - // Load Sounds. - s_punchSwingSndSrc = sound_load("swing.voc", SOUND_PRIORITY_HIGH3); - s_pistolSndSrc = sound_load("pistol-1.voc", SOUND_PRIORITY_HIGH0); - s_pistolEmptySndSrc = sound_load("pistout1.voc", SOUND_PRIORITY_HIGH0); - s_rifleSndSrc = sound_load("rifle-1.voc", SOUND_PRIORITY_HIGH0); - s_rifleEmptySndSrc = sound_load("riflout.voc", SOUND_PRIORITY_HIGH0); - s_fusion1SndSrc = sound_load("fusion1.voc", SOUND_PRIORITY_HIGH3); - s_fusion2SndSrc = sound_load("fusion2.voc", SOUND_PRIORITY_HIGH3); - s_repeaterSndSrc = sound_load("repeater.voc", SOUND_PRIORITY_HIGH3); - s_repeater1SndSrc = sound_load("repeat-1.voc", SOUND_PRIORITY_HIGH3); - s_repeaterEmptySndSrc = sound_load("rep-emp.voc", SOUND_PRIORITY_HIGH3); - s_mortarFireSndSrc = sound_load("mortar4.voc", SOUND_PRIORITY_HIGH3); - s_mortarFireSndSrc2 = sound_load("mortar2.voc", SOUND_PRIORITY_HIGH3); - s_mortarEmptySndSrc = sound_load("mortar9.voc", SOUND_PRIORITY_HIGH3); - s_mineSndSrc = sound_load("claymor1.voc", SOUND_PRIORITY_HIGH3); - s_concussion6SndSrc = sound_load("concuss6.voc", SOUND_PRIORITY_HIGH3); - s_concussion5SndSrc = sound_load("concuss5.voc", SOUND_PRIORITY_HIGH3); - s_concussion1SndSrc = sound_load("concuss1.voc", SOUND_PRIORITY_HIGH3); - s_plasma4SndSrc = sound_load("plasma4.voc", SOUND_PRIORITY_HIGH3); - s_plasmaEmptySndSrc = sound_load("plas-emp.voc", SOUND_PRIORITY_HIGH3); - s_missile1SndSrc = sound_load("missile1.voc", SOUND_PRIORITY_HIGH3); - s_weaponChangeSnd = sound_load("weapon1.voc", SOUND_PRIORITY_LOW4); - s_superchargeCountdownSound = sound_load("quarter.voc", SOUND_PRIORITY_HIGH4); - - s_isShooting = JFALSE; - s_secondaryFire = JFALSE; - s_superCharge = JFALSE; - s_superChargeHud = JFALSE; - s_superchargeTask = nullptr; - s_weaponAutoMount2 = JFALSE; - s_prevWeapon = WPN_PISTOL; - s_curWeapon = WPN_PISTOL; - s_lastWeapon = WPN_PISTOL; - s_curPlayerWeapon = &s_playerWeaponList[WPN_PISTOL]; - } - - void weapon_enableAutomount(JBool enable) - { - s_weaponAutoMount2 = enable; - } - - void player_cycleWeapons(s32 change) - { - s32 dir = (change < 0) ? -1 : 1; - s32 nextWeapon = s_curWeapon + change; - JBool hasWeapon = JFALSE; - while (!hasWeapon) - { - if (nextWeapon < 0) - { - nextWeapon = WPN_COUNT - 1; - } - else if (nextWeapon == WPN_COUNT) - { - nextWeapon = WPN_FIST; - } - - switch (nextWeapon) - { - case WPN_FIST: - { - hasWeapon = JTRUE; - } break; - case WPN_PISTOL: - { - if (!s_playerInfo.itemPistol) { nextWeapon += dir; } - else { hasWeapon = JTRUE; } - } break; - case WPN_RIFLE: - { - if (!s_playerInfo.itemRifle) { nextWeapon += dir; } - else { hasWeapon = JTRUE; } - } break; - case WPN_THERMAL_DET: - { - // TODO(Core Game Loop Release): Check this. - if (!s_playerInfo.ammoDetonator) { nextWeapon += dir; } - else { hasWeapon = JTRUE; } - } break; - case WPN_REPEATER: - { - if (!s_playerInfo.itemAutogun) { nextWeapon += dir; } - else { hasWeapon = JTRUE; } - } break; - case WPN_FUSION: - { - if (!s_playerInfo.itemFusion) { nextWeapon += dir; } - else { hasWeapon = JTRUE; } - } break; - case WPN_MORTAR: - { - if (!s_playerInfo.itemMortar) { nextWeapon += dir; } - else { hasWeapon = JTRUE; } - } break; - case WPN_MINE: - { - // TODO(Core Game Loop Release): Check this. - if (!s_playerInfo.ammoMine) { nextWeapon += dir; } - else { hasWeapon = JTRUE; } - } break; - case WPN_CONCUSSION: - { - if (!s_playerInfo.itemConcussion) { nextWeapon += dir; } - else { hasWeapon = JTRUE; } - } break; - case WPN_CANNON: - { - if (!s_playerInfo.itemCannon) { nextWeapon += dir; } - else { hasWeapon = JTRUE; } - } break; - } - } - - if (nextWeapon != s_playerInfo.curWeapon && s_playerWeaponTask) - { - s_msgArg1 = nextWeapon; - task_runAndReturn(s_playerWeaponTask, MSG_SWITCH_WPN); - - if (s_playerInfo.curWeapon > s_playerInfo.maxWeapon) - { - s_playerInfo.maxWeapon = s_playerInfo.curWeapon; - } - } - else - { - s_playerInfo.saveWeapon = nextWeapon; - } - } - - void weapon_setNext(s32 wpnIndex) - { - PlayerWeapon* prevWeapon = s_curPlayerWeapon; - s_curWeapon = wpnIndex; - - s_prevWeapon = wpnIndex; - PlayerWeapon* nextWeapon = &s_playerWeaponList[wpnIndex]; - s_playerInfo.curWeapon = wpnIndex; - - if (wpnIndex == WPN_THERMAL_DET && !(*nextWeapon->ammo)) - { - nextWeapon->frame = 3; - } - else if (wpnIndex == WPN_MINE && !(*nextWeapon->ammo)) - { - nextWeapon->frame = 2; - } - else - { - nextWeapon->frame = 0; - } - - s_curPlayerWeapon = nextWeapon; - weapon_setFireRate(); - - PlayerWeapon* weapon = s_curPlayerWeapon; - weapon->rollOffset = prevWeapon->rollOffset; - weapon->pchOffset = prevWeapon->pchOffset; - weapon->xWaveOffset = prevWeapon->xWaveOffset; - weapon->yWaveOffset = prevWeapon->yWaveOffset; - weapon->xOffset = prevWeapon->xOffset; - weapon->yOffset = prevWeapon->yOffset; - } - - void weapon_setFireRate() - { - s_canFireWeaponPrim = 1; - s_canFireWeaponSec = 1; - - // Clear both fire modes. - weapon_setFireRateInternal(WFIRE_PRIMARY, 0, nullptr); - weapon_setFireRateInternal(WFIRE_SECONDARY, 0, nullptr); - - switch (s_prevWeapon) - { - case WPN_PISTOL: - { - Tick fireDelay = s_superCharge ? 35 : 71; - weapon_setFireRateInternal(WFIRE_PRIMARY, fireDelay, &s_canFireWeaponPrim); - } break; - case WPN_RIFLE: - { - Tick fireDelay = s_superCharge ? 10 : 21; - weapon_setFireRateInternal(WFIRE_PRIMARY, fireDelay, &s_canFireWeaponPrim); - } break; - case WPN_THERMAL_DET: - case WPN_MINE: - { - weapon_setFireRateInternal(WFIRE_PRIMARY, 1, &s_canFireWeaponPrim); - } break; - case WPN_REPEATER: - { - Tick fireDelay = s_superCharge ? 14 : 30; - weapon_setFireRateInternal(WFIRE_PRIMARY, fireDelay, &s_canFireWeaponPrim); - - fireDelay = s_superCharge ? 18 : 37; - weapon_setFireRateInternal(WFIRE_SECONDARY, fireDelay, &s_canFireWeaponSec); - } break; - case WPN_FUSION: - { - Tick fireDelay = s_superCharge ? 17 : 35; - weapon_setFireRateInternal(WFIRE_PRIMARY, fireDelay, &s_canFireWeaponPrim); - - fireDelay = s_superCharge ? 33 : 68; - weapon_setFireRateInternal(WFIRE_SECONDARY, fireDelay, &s_canFireWeaponSec); - } break; - case WPN_MORTAR: - { - Tick fireDelay = s_superCharge ? 50 : 100; - weapon_setFireRateInternal(WFIRE_PRIMARY, fireDelay, &s_canFireWeaponPrim); - } break; - case WPN_CONCUSSION: - { - Tick fireDelay = s_superCharge ? 57 : 115; - weapon_setFireRateInternal(WFIRE_PRIMARY, fireDelay, &s_canFireWeaponPrim); - } break; - case WPN_CANNON: - { - Tick fireDelay = s_superCharge ? 17 : 35; - weapon_setFireRateInternal(WFIRE_PRIMARY, fireDelay, &s_canFireWeaponPrim); - - fireDelay = s_superCharge ? 86 : 87; - weapon_setFireRateInternal(WFIRE_SECONDARY, fireDelay, &s_canFireWeaponSec); - } break; - } - } - - void weapon_clearFireRate() - { - s_weaponDelayPrimary = 0; - s_weaponDelaySeconary = 0; - } - - void weapon_createPlayerWeaponTask() - { - //s_playerWeaponTask = createSubTask("player weapon", weapon_playerWeaponTaskFunc); - // TODO: In the original code, createTask() was called - but then the firing is a frame behind. - // Making it a "createTask" instead makes it happen before the main task, which is what we want. - s_playerWeaponTask = createTask("player weapon", weapon_playerWeaponTaskFunc); - - s_superCharge = JFALSE; - s_superChargeHud = JFALSE; - s_queWeaponSwitch = JFALSE; - s_superchargeTask = nullptr; - } - - void weapon_fixupAnim() - { - PlayerWeapon* weapon = s_curPlayerWeapon; - s32 ammo = weapon->ammo ? *weapon->ammo : 0; - - if (s_prevWeapon == WPN_THERMAL_DET && !ammo) - { - weapon->frame = 3; - } - else if (s_prevWeapon == WPN_MINE && !ammo) - { - weapon->frame = 2; - } - } - - void weapon_computeMatrix(fixed16_16* mtx, angle14_32 pitch, angle14_32 yaw) - { - fixed16_16 cosPch, sinPch; - sinCosFixed(pitch, &sinPch, &cosPch); - - fixed16_16 cosYaw, sinYaw; - sinCosFixed(yaw, &sinYaw, &cosYaw); - - mtx[0] = cosYaw; - mtx[1] = 0; - mtx[2] = sinYaw; - mtx[3] = mul16(sinYaw, sinPch); - mtx[4] = cosPch; - mtx[5] = -mul16(cosYaw, sinPch); - mtx[6] = -mul16(sinYaw, cosPch); - mtx[7] = sinPch; - mtx[8] = mul16(cosPch, cosYaw); - } - - /////////////////////////////////////////// - // Internal Implementation - /////////////////////////////////////////// - void weapon_setFireRateInternal(WeaponFireMode mode, Tick delay, s32* canFire) - { - if (mode == WFIRE_PRIMARY) - { - s_weaponDelayPrimary = delay; - s_canFirePrimPtr = canFire; - } - else - { - s_weaponDelaySeconary = delay; - s_canFireSecPtr = canFire; - } - } - - void weapon_addTexture(TextureInfoList& texList, TextureData* tex) - { - TextureInfo texInfo = {}; - texInfo.type = TEXINFO_DF_TEXTURE_DATA; - texInfo.texData = tex; - texList.push_back(texInfo); - } - - bool weapon_getTextures(TextureInfoList& texList) - { - // Get weapon textures. - weapon_addTexture(texList, s_rhand1); - weapon_addTexture(texList, s_gasmaskTexture); - for (s32 i = 0; i < WPN_COUNT; i++) - { - for (s32 f = 0; f < s_playerWeaponList[i].frameCount; f++) - { - weapon_addTexture(texList, s_playerWeaponList[i].frames[f]); - } - } - return true; - } - - void weapon_loadTextures() - { - if (!s_weaponTexturesLoaded) - { - s_rhand1 = loadWeaponTexture("rhand1.bm"); - s_gasmaskTexture = loadWeaponTexture("gmask.bm"); - - s_playerWeaponList[WPN_FIST].frames[0] = s_rhand1; - s_playerWeaponList[WPN_FIST].frames[1] = loadWeaponTexture("punch1.bm"); - s_playerWeaponList[WPN_FIST].frames[2] = loadWeaponTexture("punch2.bm"); - s_playerWeaponList[WPN_FIST].frames[3] = loadWeaponTexture("punch3.bm"); - - s_playerWeaponList[WPN_PISTOL].frames[0] = loadWeaponTexture("pistol1.bm"); - s_playerWeaponList[WPN_PISTOL].frames[1] = loadWeaponTexture("pistol2.bm"); - s_playerWeaponList[WPN_PISTOL].frames[2] = loadWeaponTexture("pistol3.bm"); - - s_playerWeaponList[WPN_RIFLE].frames[0] = loadWeaponTexture("rifle1.bm"); - s_playerWeaponList[WPN_RIFLE].frames[1] = loadWeaponTexture("rifle2.bm"); - - s_playerWeaponList[WPN_THERMAL_DET].frames[0] = loadWeaponTexture("therm1.bm"); - s_playerWeaponList[WPN_THERMAL_DET].frames[1] = loadWeaponTexture("therm2.bm"); - s_playerWeaponList[WPN_THERMAL_DET].frames[2] = loadWeaponTexture("therm3.bm"); - s_playerWeaponList[WPN_THERMAL_DET].frames[3] = s_rhand1; - - s_playerWeaponList[WPN_REPEATER].frames[0] = loadWeaponTexture("autogun1.bm"); - s_playerWeaponList[WPN_REPEATER].frames[1] = loadWeaponTexture("autogun2.bm"); - s_playerWeaponList[WPN_REPEATER].frames[2] = loadWeaponTexture("autogun3.bm"); - - s_playerWeaponList[WPN_FUSION].frames[0] = loadWeaponTexture("fusion1.bm"); - s_playerWeaponList[WPN_FUSION].frames[1] = loadWeaponTexture("fusion2.bm"); - s_playerWeaponList[WPN_FUSION].frames[2] = loadWeaponTexture("fusion3.bm"); - s_playerWeaponList[WPN_FUSION].frames[3] = loadWeaponTexture("fusion4.bm"); - s_playerWeaponList[WPN_FUSION].frames[4] = loadWeaponTexture("fusion5.bm"); - s_playerWeaponList[WPN_FUSION].frames[5] = loadWeaponTexture("fusion6.bm"); - - s_playerWeaponList[WPN_MORTAR].frames[0] = loadWeaponTexture("mortar1.bm"); - s_playerWeaponList[WPN_MORTAR].frames[1] = loadWeaponTexture("mortar2.bm"); - s_playerWeaponList[WPN_MORTAR].frames[2] = loadWeaponTexture("mortar3.bm"); - s_playerWeaponList[WPN_MORTAR].frames[3] = loadWeaponTexture("mortar4.bm"); - - s_playerWeaponList[WPN_MINE].frames[0] = loadWeaponTexture("clay1.bm"); - s_playerWeaponList[WPN_MINE].frames[1] = loadWeaponTexture("clay2.bm"); - s_playerWeaponList[WPN_MINE].frames[2] = s_rhand1; - - s_playerWeaponList[WPN_CONCUSSION].frames[0] = loadWeaponTexture("concuss1.bm"); - s_playerWeaponList[WPN_CONCUSSION].frames[1] = loadWeaponTexture("concuss2.bm"); - s_playerWeaponList[WPN_CONCUSSION].frames[2] = loadWeaponTexture("concuss3.bm"); - - s_playerWeaponList[WPN_CANNON].frames[0] = loadWeaponTexture("assault1.bm"); - s_playerWeaponList[WPN_CANNON].frames[1] = loadWeaponTexture("assault2.bm"); - s_playerWeaponList[WPN_CANNON].frames[2] = loadWeaponTexture("assault3.bm"); - s_playerWeaponList[WPN_CANNON].frames[3] = loadWeaponTexture("assault4.bm"); - - s_weaponTexturesLoaded = JTRUE; - } - } - - TextureData* loadWeaponTexture(const char* texName) - { - TextureData* weaponTex = bitmap_load(texName, 0, POOL_GAME); - if (!weaponTex) - { - TFE_System::logWrite(LOG_ERROR, "Weapon", "Weapon_Startup: %s NOT FOUND.", texName); - } - return weaponTex; - } - - void weapon_setShooting(u32 secondaryFire) - { - s_isShooting = JTRUE; - s_secondaryFire = secondaryFire ? JTRUE : JFALSE; - - if (s_weaponOffAnim) - { - // TODO(Core Game Loop Release) - } - - PlayerWeapon* weapon = s_curPlayerWeapon; - weapon->flags &= ~2; - s32 wpnIndex = s_prevWeapon; - - if (wpnIndex == 4) - { - // TODO(Core Game Loop Release) - } - else if (wpnIndex == 9) - { - // TODO(Core Game Loop Release) - } - - weapon_setFireRate(); - } - - void weapon_queueWeaponSwitch(s32 wpnId) - { - s_queWeaponSwitch = JTRUE; - s_msgArg1 = wpnId; - task_makeActive(s_playerWeaponTask); - } - - void weapon_handleState(MessageType msg) - { - task_begin; - if (msg == MSG_STOP_FIRING) - { - s_isShooting = JFALSE; - weapon_prepareToFire(); - s_curPlayerWeapon->flags |= 2; - } - else if (msg == MSG_START_FIRING) - { - s_secondaryFire = s_msgArg1 ? JTRUE : JFALSE; - s_isShooting = JTRUE; - if (s_weaponOffAnim) - { - task_callTaskFunc(weapon_handleOnAnimation); - } - s_curPlayerWeapon->flags &= ~2; - } - else if (msg == MSG_SWITCH_WPN) - { - s_switchWeapons = JTRUE; - s_nextWeapon = s_msgArg1; - } - task_end; - } - - void weapon_stopFiring() - { - s_isShooting = JFALSE; - if (s_prevWeapon == WPN_REPEATER) - { - if (s_repeaterFireSndID) - { - sound_stop(s_repeaterFireSndID); - s_repeaterFireSndID = 0; - } - s_curPlayerWeapon->frame = 0; - } - else if (s_prevWeapon == WPN_CANNON) - { - if (s_secondaryFire) - { - s_curPlayerWeapon->frame = 0; - } - } - PlayerWeapon* weapon = s_curPlayerWeapon; - weapon->flags |= 2; - } - - void weapon_handleState2(MessageType msg) - { - task_begin; - task_makeActive(s_playerWeaponTask); - task_yield(TASK_NO_DELAY); - - if (msg == MSG_STOP_FIRING) - { - weapon_stopFiring(); - } - else if (msg == MSG_START_FIRING) - { - weapon_setShooting(s_msgArg1); - } - else if (msg == MSG_SWITCH_WPN) - { - s_switchWeapons = JTRUE; - s_nextWeapon = s_msgArg1; - } - task_end; - } - - // This task function handles animating a weapon on or off screen, based on the inputs. - void weapon_animateOnOrOffscreen(MessageType msg) - { - struct LocalContext - { - Tick startTick; - }; - task_begin_ctx; - - s_curPlayerWeapon->xOffset = s_weaponAnimState.startOffsetX; - s_curPlayerWeapon->yOffset = s_weaponAnimState.startOffsetY; - task_makeActive(s_playerWeaponTask); - - task_yield(TASK_NO_DELAY); - task_callTaskFunc(weapon_handleState); - - s_curPlayerWeapon->frame = s_weaponAnimState.frame; - while (s_weaponAnimState.frameCount) - { - taskCtx->startTick = s_curTick; - // We may get calls to the weapon task while animating, so handle them as we get them. - do - { - task_yield((msg != MSG_RUN_TASK) ? TASK_NO_DELAY : s_weaponAnimState.ticksPerFrame); - - if (msg == MSG_STOP_FIRING) - { - weapon_stopFiring(); - } - else if (msg == MSG_START_FIRING) - { - weapon_setShooting(s_msgArg1/*secondaryFire*/); - } - else if (msg == MSG_SWITCH_WPN) - { - s_switchWeapons = JTRUE; - s_nextWeapon = s_msgArg1; - } - } while (msg != MSG_RUN_TASK); - - // Calculate the number of elapsed frames. - Tick elapsed = s_curTick - taskCtx->startTick; - if (elapsed <= s_weaponAnimState.ticksPerFrame + 1 || s_weaponAnimState.frameCount < 2) - { - s_curPlayerWeapon->xOffset += s_weaponAnimState.xSpeed; - s_curPlayerWeapon->yOffset += s_weaponAnimState.ySpeed; - s_weaponAnimState.frameCount--; - } - else - { - s32 elapsedFrames = min((s32)s_weaponAnimState.frameCount, (s32)(elapsed / s_weaponAnimState.ticksPerFrame)); - s_curPlayerWeapon->xOffset += s_weaponAnimState.xSpeed * elapsedFrames; - s_curPlayerWeapon->yOffset += s_weaponAnimState.ySpeed * elapsedFrames; - s_weaponAnimState.frameCount -= elapsedFrames; - } - } - - task_end; - } - - void weapon_handleOffAnimation(MessageType msg) - { - task_begin; - // s_prevWeapon is the weapon we are switching away from. - if (s_prevWeapon == WPN_REPEATER) - { - if (s_repeaterFireSndID) - { - sound_stop(s_repeaterFireSndID); - s_repeaterFireSndID = 0; - } - s_curPlayerWeapon->frame = 0; - } - else if (s_prevWeapon == WPN_CANNON && !s_secondaryFire) - { - s_curPlayerWeapon->frame = 0; - } - - s_weaponAnimState = - { - s_curPlayerWeapon->frame, // frame - s_curPlayerWeapon->xOffset, s_curPlayerWeapon->yOffset, - 3, 4, // xSpeed, ySpeed - 10, s_superCharge ? 1u : 2u // frameCount, ticksPerFrame - }; - task_callTaskFunc(weapon_animateOnOrOffscreen); - s_weaponOffAnim = JTRUE; - - task_end; - } - - void weapon_handleOnAnimation(MessageType msg) - { - task_begin; - s_weaponOffAnim = JFALSE; - if (s_curWeapon != WPN_FIST && s_curWeapon != WPN_THERMAL_DET && s_curWeapon != WPN_MINE) - { - sound_play(s_weaponChangeSnd); - } - - if (s_prevWeapon == WPN_THERMAL_DET) - { - // TODO(Core Game Loop Release) - } - else if (s_prevWeapon == WPN_MINE) - { - // TODO(Core Game Loop Release) - } - - // s_prevWeapon is the weapon we are switching away from. - s_weaponAnimState = - { - 0, // frame - 30, 40, // startOffsetX, startOffsetY: was 14, 40 - -3, -4, // xSpeed, ySpeed - 10, s_superCharge ? 1u : 2u // frameCount, ticksPerFrame - }; - task_callTaskFunc(weapon_animateOnOrOffscreen); - task_end; - } - - void weapon_holster() - { - if (s_playerWeaponTask) - { - task_runAndReturn(s_playerWeaponTask, MSG_HOLSTER); - } - } - - void weapon_prepareToFire() - { - PlayerWeapon* weapon = s_curPlayerWeapon; - if (s_prevWeapon == WPN_REPEATER) - { - if (s_repeaterFireSndID) - { - sound_stop(s_repeaterFireSndID); - s_repeaterFireSndID = 0; - } - weapon->frame = 0; - } - else if (s_prevWeapon == WPN_CANNON) - { - if (!s_secondaryFire) - { - weapon->frame = 0; - } - } - } - - void weapon_playerWeaponTaskFunc(MessageType msg) - { - struct LocalContext - { - JBool secondaryFire; - }; - task_begin_ctx; - while (1) - { - // If the weapon task is called with a non-zero id, handle it here. - if (msg == MSG_FREE_TASK) - { - task_free(s_playerWeaponTask); - s_playerWeaponTask = nullptr; - return; - } - else if (msg == MSG_SWITCH_WPN || s_queWeaponSwitch) - { - s_queWeaponSwitch = JFALSE; - - task_makeActive(s_playerWeaponTask); - s_nextWeapon = s_msgArg1; - task_makeActive(s_playerWeaponTask); - task_yield(TASK_NO_DELAY); - task_callTaskFunc(weapon_handleState); - - if (s_nextWeapon == -1) - { - swap(s_curWeapon, s_lastWeapon); - } - else - { - s32 lastWeapon = s_curWeapon; - s_curWeapon = s_nextWeapon; - s_lastWeapon = lastWeapon; - } - s_playerInfo.curWeapon = s_prevWeapon; - - if (!s_weaponOffAnim) - { - task_callTaskFunc(weapon_handleOffAnimation); - } - weapon_setNext(s_curWeapon); - task_callTaskFunc(weapon_handleOnAnimation); - } - else if (msg == MSG_START_FIRING) - { - taskCtx->secondaryFire = s_msgArg1; - task_makeActive(s_playerWeaponTask); - task_makeActive(s_playerWeaponTask); - task_yield(TASK_NO_DELAY); - - task_callTaskFunc(weapon_handleState); - s_isShooting = JTRUE; - s_secondaryFire = taskCtx->secondaryFire ? JTRUE : JFALSE; - if (s_weaponOffAnim) - { - task_callTaskFunc(weapon_handleOnAnimation); - } - s_curPlayerWeapon->flags &= ~2; - - weapon_prepareToFire(); - weapon_setFireRate(); - } - else if (msg == MSG_STOP_FIRING) - { - s_isShooting = JFALSE; - weapon_prepareToFire(); - s_curPlayerWeapon->flags |= 2; - } - else if (msg == MSG_HOLSTER) - { - task_makeActive(s_playerWeaponTask); - task_yield(TASK_NO_DELAY); - task_callTaskFunc(weapon_handleState); - - if (!s_weaponOffAnim) - { - weapon_prepareToFire(); - - s_weaponAnimState = - { - s_curPlayerWeapon->frame, // frame - 0, 0, // startOffsetX, startOffsetY - 3, 4, // xSpeed, ySpeed - 10, s_superCharge ? 1u : 2u // frameCount, ticksPerFrame - }; - task_callTaskFunc(weapon_animateOnOrOffscreen); - s_weaponOffAnim = JTRUE; - } - else - { - s_weaponOffAnim = JFALSE; - if (s_curWeapon == WPN_PISTOL || s_curWeapon == WPN_RIFLE || s_curWeapon == WPN_REPEATER || s_curWeapon == WPN_FUSION || s_curWeapon == WPN_MORTAR || - s_curWeapon == WPN_CONCUSSION || s_curWeapon == WPN_CANNON) - { - sound_play(s_weaponChangeSnd); - } - - weapon_fixupAnim(); - - s_weaponAnimState = - { - s_curPlayerWeapon->frame, // frame - 30, 40, // startOffsetX, startOffsetY - -3, -4, // xSpeed, ySpeed - 10, s_superCharge ? 1u : 2u // frameCount, ticksPerFrame - }; - task_callTaskFunc(weapon_animateOnOrOffscreen); - } - } - - // Handle shooting. - while (s_isShooting) - { - s_switchWeapons = JFALSE; - s_queWeaponSwitch = JFALSE; - s_fireFrame++; - - while (msg != MSG_RUN_TASK) - { - task_makeActive(s_playerWeaponTask); - task_yield(TASK_NO_DELAY); - task_callTaskFunc(weapon_handleState); - } - - if ((s_secondaryFire && s_canFireWeaponSec) || s_canFireWeaponPrim) - { - // Fire the weapon. - task_callTaskFunc(s_weaponFireFunc[s_prevWeapon]); - } - else - { - task_makeActive(s_playerWeaponTask); - task_yield(TASK_NO_DELAY); - task_callTaskFunc(weapon_handleState); - } - - if (s_switchWeapons) - { - if (s_nextWeapon == -1) - { - swap(s_curWeapon, s_lastWeapon); - } - else - { - s_lastWeapon = s_curWeapon; - s_curWeapon = s_nextWeapon; - } - s_playerInfo.curWeapon = s_prevWeapon; - - // Move the next weapon off screen, if it is not already off. - // Then move the next one on screen. - if (!s_weaponOffAnim) - { - task_callTaskFunc(weapon_handleOffAnimation); - } - weapon_setNext(s_curWeapon); - task_callTaskFunc(weapon_handleOnAnimation); - } - } - - // Go to sleep until needed. - task_yield(TASK_SLEEP); - } - task_end; - } - - // In DOS, this was part of drawWorld() - - // for TFE I split it out to limit the amount of game code in the renderer. - void weapon_draw(u8* display, DrawRect* rect) - { - const fixed16_16 weaponLightingZDist = FIXED(6); - const fixed16_16 gasmaskLightingZDist = FIXED(2); - - PlayerWeapon* weapon = s_curPlayerWeapon; - if (weapon && !s_weaponOffAnim) - { - s32 x = weapon->xPos[weapon->frame]; - s32 y = weapon->yPos[weapon->frame]; - if (weapon->flags & 1) - { - x += weapon->rollOffset; - y += weapon->pchOffset; - } - if (weapon->flags & 2) - { - x += weapon->xWaveOffset; - y += weapon->yWaveOffset; - } - if (weapon->flags & 4) - { - x += weapon->xOffset; - y += weapon->yOffset; - } - - const u8* atten = RClassic_Fixed::computeLighting(weaponLightingZDist, 0); - TextureData* tex = weapon->frames[weapon->frame]; - if (weapon->ammo && *weapon->ammo == 0 && (weapon->ammo == &s_playerInfo.ammoDetonator || weapon->ammo == &s_playerInfo.ammoMine)) - { - tex = s_playerWeaponList[WPN_FIST].frames[0]; - } - - u32 dispWidth, dispHeight; - vfb_getResolution(&dispWidth, &dispHeight); - - if (dispWidth == 320 && dispHeight == 200 && TFE_Jedi::getSubRenderer() != TSR_CLASSIC_GPU) - { - if (atten && !s_weaponLight) - { - blitTextureToScreenLit(tex, rect, x, y, atten, display, JTRUE); - } - else - { - blitTextureToScreen(tex, rect, x, y, display, JTRUE); - } - } - else - { - // HUD scaling. - fixed16_16 xScale = vfb_getXScale(); - fixed16_16 yScale = vfb_getYScale(); - x = floor16(mul16(xScale, intToFixed16(x))) + vfb_getWidescreenOffset(); - y = floor16(mul16(yScale, intToFixed16(y))); - - // Hack to handle the Dark Trooper rifle. - if (weapon->frames[0]->width == 169) - { - x += vfb_getWidescreenOffset(); - } - - // TFE: Handle extended pitch limits. - s32 texHeight = floor16(mul16(intToFixed16(tex->height), yScale)); - s32 y1 = y + texHeight; - if (y1 < s32(dispHeight) - 3) - { - y = dispHeight + 2 - texHeight; - } - - if (atten && !s_weaponLight) - { - blitTextureToScreenLitScaled(tex, rect, x, y, xScale, yScale, atten, display, JTRUE); - } - else - { - blitTextureToScreenScaled(tex, rect, x, y, xScale, yScale, display, JTRUE); - } - } - } - - if (s_wearingGasmask) - { - s32 x = 105; - s32 y = 141; - if (weapon) - { - x -= (weapon->xWaveOffset >> 3); - y += (weapon->yWaveOffset >> 2); - } - const u8* atten = RClassic_Fixed::computeLighting(gasmaskLightingZDist, 0); - TextureData* tex = s_gasmaskTexture; - - u32 dispWidth, dispHeight; - vfb_getResolution(&dispWidth, &dispHeight); - - if (dispWidth == 320 && dispHeight == 200) - { - if (atten) - { - blitTextureToScreenLit(tex, rect, x, y, atten, display, JTRUE); - } - else - { - blitTextureToScreen(tex, rect, x, y, display, JTRUE); - } - } - else - { - // HUD scaling. - fixed16_16 xScale = vfb_getXScale(); - fixed16_16 yScale = vfb_getYScale(); - x = floor16(mul16(xScale, intToFixed16(x))) + vfb_getWidescreenOffset(); - y = floor16(yScale + mul16(yScale, intToFixed16(y))); - - if (atten && !s_weaponLight) - { - blitTextureToScreenLitScaled(tex, rect, x, y, xScale, yScale, atten, display, JTRUE); - } - else - { - blitTextureToScreenScaled(tex, rect, x, y, xScale, yScale, display, JTRUE); - } - } - } - } -} // namespace TFE_DarkForces -#ifdef TFE_ESPBOX -void espbox_shared_weapon(bool alloc) -{ - ESPBOX_SHARED_ALLOC(TFE_DarkForces::s_playerWeaponList, TFE_DarkForces::WPN_COUNT); -} -#endif diff --git a/components/darkforces/tfe/TFE_DarkForces/weapon.h b/components/darkforces/tfe/TFE_DarkForces/weapon.h deleted file mode 100644 index 3e2032a6..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/weapon.h +++ /dev/null @@ -1,126 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces Player - -// Player information and object data. -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include "sound.h" - -namespace TFE_Jedi -{ - struct DrawRect; -} - -namespace TFE_DarkForces -{ - struct PlayerWeapon - { - s32 frameCount; - TextureData* frames[8]; - s32 frame; - s32 xPos[8]; - s32 yPos[8]; - u32 flags; - s32 rollOffset; - s32 pchOffset; - s32 xWaveOffset; - s32 yWaveOffset; - s32 xOffset; - s32 yOffset; - s32* ammo; - s32* secondaryAmmo; - s32 u8c; - s32 u90; - fixed16_16 wakeupRange; - s32 variation; - }; - - struct WeaponAnimState - { - s32 frame; - s32 startOffsetX; - s32 startOffsetY; - s32 xSpeed; - s32 ySpeed; - s32 frameCount; - u32 ticksPerFrame; - }; - - /////////////////////////////////////////// - // Constants - /////////////////////////////////////////// - enum WeaponID - { - WPN_FIST = 0, - WPN_PISTOL, - WPN_RIFLE, - WPN_THERMAL_DET, - WPN_REPEATER, - WPN_FUSION, - WPN_MORTAR, - WPN_MINE, - WPN_CONCUSSION, - WPN_CANNON, - WPN_COUNT - }; - - enum WeaponFireMode - { - WFIRE_PRIMARY = 0, - WFIRE_SECONDARY, - }; - - enum WeaponFireType - { - WFIRETYPE_PRIMARY = JFALSE, // Primary fire. - WFIRETYPE_SECONDARY = JTRUE, // Secondary fire. - }; - - void weapon_resetState(); - void weapon_startup(); - void weapon_enableAutomount(JBool enable); - void weapon_setNext(s32 wpnIndex); - void weapon_setFireRate(); - void weapon_clearFireRate(); - void weapon_createPlayerWeaponTask(); - void weapon_holster(); - void weapon_draw(u8* display, DrawRect* rect); - void weapon_fixupAnim(); - void weapon_stopFiring(); - void player_cycleWeapons(s32 change); - void weapon_computeMatrix(fixed16_16* mtx, angle14_32 pitch, angle14_32 yaw); - - void weapon_queueWeaponSwitch(s32 wpnId); - - // Serialization - void weapon_serialize(Stream* stream); - - extern PlayerWeapon* s_curPlayerWeapon; - extern SoundSourceId s_superchargeCountdownSound; - extern Task* s_playerWeaponTask; - - // Weapon sounds (external since AI uses it). - extern SoundSourceId s_punchSwingSndSrc; - extern SoundSourceId s_pistolSndSrc; - extern SoundSourceId s_pistolEmptySndSrc; - extern SoundSourceId s_rifleSndSrc; - extern SoundSourceId s_rifleEmptySndSrc; - extern SoundSourceId s_fusion1SndSrc; - extern SoundSourceId s_fusion2SndSrc; - extern SoundSourceId s_repeaterSndSrc; - extern SoundSourceId s_repeater1SndSrc; - extern SoundSourceId s_repeaterEmptySndSrc; - extern SoundSourceId s_mortarFireSndSrc; - extern SoundSourceId s_mortarFireSndSrc2; - extern SoundSourceId s_mortarEmptySndSrc; - extern SoundSourceId s_mineSndSrc; - extern SoundSourceId s_concussion6SndSrc; - extern SoundSourceId s_concussion5SndSrc; - extern SoundSourceId s_concussion1SndSrc; - extern SoundSourceId s_plasma4SndSrc; - extern SoundSourceId s_plasmaEmptySndSrc; - extern SoundSourceId s_missile1SndSrc; - extern SoundSourceId s_weaponChangeSnd; -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/weaponFireFunc.cpp b/components/darkforces/tfe/TFE_DarkForces/weaponFireFunc.cpp deleted file mode 100644 index f9ee0ee2..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/weaponFireFunc.cpp +++ /dev/null @@ -1,2182 +0,0 @@ -#include "weaponFireFunc.h" -#include "weapon.h" -#include "random.h" -#include "player.h" -#include "pickup.h" -#include "projectile.h" -#include "hitEffect.h" -#include -#include -// TFE -#include - -namespace TFE_DarkForces -{ - enum WeaponFireConst - { - MAX_AUTOAIM_DIST = COL_INFINITY, - }; - - static SoundEffectId s_punchSwingSndId = 0; - static SoundEffectId s_pistolSndId = 0; - static SoundEffectId s_rifleSndId = 0; - static SoundEffectId s_mortarFireSndID = 0; - static SoundEffectId s_mortarFireSndID2 = 0; - static SoundEffectId s_outOfAmmoSndId = 0; - static SoundEffectId s_mortarOutofAmmoSndId = 0; - static SoundEffectId s_repeaterFireSndID1 = 0; - static SoundEffectId s_repeaterOutOfAmmoSndId = 0; - static SoundEffectId s_fusionFireSndID = 0; - static SoundEffectId s_fusionOutOfAmmoSndID = 0; - static SoundEffectId s_mineSndId = 0; - static SoundEffectId s_concussionFireSndID = 0; - static SoundEffectId s_concussionFireSndID1 = 0; - static SoundEffectId s_concussionOutOfAmmoSndID = 0; - static SoundEffectId s_cannonOutOfAmmoSndID = 0; - static SoundEffectId s_cannonFireSndID = 0; - static SoundEffectId s_cannonFireSndID1 = 0; - static fixed16_16 s_autoAimDirX; - static fixed16_16 s_autoAimDirZ; - static fixed16_16 s_wpnPitchSin; - static fixed16_16 s_wpnPitchCos; - static angle14_32 s_weaponFirePitch; - static angle14_32 s_weaponFireYaw; - - extern WeaponAnimState s_weaponAnimState; - extern SoundEffectId s_repeaterFireSndID; - - extern JBool s_weaponAutoMount2; - extern JBool s_secondaryFire; - extern JBool s_weaponOffAnim; - extern JBool s_isShooting; - extern s32 s_canFireWeaponSec; - extern s32 s_canFireWeaponPrim; - extern u32 s_fireFrame; - - extern s32 s_prevWeapon; - extern s32 s_curWeapon; - extern s32 s_nextWeapon; - extern s32 s_lastWeapon; - - struct WeaponAnimFrame - { - s32 waxFrame; - s32 weaponLight; - Tick delaySupercharge; - Tick delayNormal; - }; - static const WeaponAnimFrame c_punchAnim[4] = - { - { 1, 0, 5, 10 }, - { 2, 0, 10, 21 }, - { 3, 0, 10, 21 }, - { 0, 0, 10, 21 }, - }; - static const WeaponAnimFrame c_pistolAnim[3] = - { - { 1, 40, 7, 14 }, - { 2, 0, 7, 14 }, - { 0, 0, 21, 43 }, - }; - static const WeaponAnimFrame c_rifleAnim[2] = - { - { 1, 40, 3, 7 }, - { 0, 0, 7, 14 }, - }; - static const WeaponAnimFrame c_mortarAnim[4] = - { - { 1, 36, 29, 58 }, - { 2, 36, 7, 14 }, - { 3, 36, 7, 14 }, - { 0, 0, 7, 14 }, - }; - static const WeaponAnimFrame c_thermalDetAnim[5] = - { - { 1, 0, 11, 11 }, - { 2, 0, 58, 58 }, - { 1, 0, 29, 29 }, - { 0, 0, 29, 29 }, - { 3, 0, 29, 29 }, - }; - static const WeaponAnimFrame c_repeaterAnim[4] = - { - { 1, 0, 2, 5 }, // primary - { 1, 0, 4, 8 }, // secondary - { 2, 33, 5, 11 }, - { 0, 0, 14, 29 }, - }; - static const WeaponAnimFrame c_concussionAnim[] = - { - { 1, 36, 21, 43 }, - { 2, 0, 7, 14 }, - { 0, 0, 29, 58 }, - }; - static const angle14_32 c_repeaterYawOffset[3] = { 0, 136, -136 }; - static const angle14_32 c_repeaterPitchOffset[3] = { 136, -136, -136 }; - // Deltas for repeater - note the order is ZXY - static fixed16_16 c_repeaterDelta[3 * 3] = - { - 0x50000, 0xe666, 0xfae1, // 5.0, 0.9, 0.98 - 0x50000, 0x8000, 0x18000, // 5.0, 0.5, 1.5 - 0x50000, 0x18000, 0x18000, // 5.0, 1.5, 1.5 - }; - static s32 s_fusionCylinder = 1; - static fixed16_16 s_fusionOffset[] = - { - FIXED(3), -ONE_16, 0x8000, // 3.0, -1.0, 0.5 - FIXED(3), -19660, 0xcccc, // 3.0, -0.3, 0.8 - FIXED(3), 0x4ccc, 0x11999, // 3.0, 0.3, 1.1 - FIXED(3), 0xcccc, 0x14ccc, // 3.0, 0.8, 1.3 - }; - static angle14_32 s_fusionYawOffset[] = - { - -375, -125, 125, 375 - }; - static JBool s_fusionCycleForward = JTRUE; - - extern void weapon_handleState(MessageType msg); - extern void weapon_handleState2(MessageType msg); - extern void weapon_handleOffAnimation(MessageType msg); - extern void weapon_handleOnAnimation(MessageType msg); - extern void weapon_animateOnOrOffscreen(MessageType msg); - JBool computeAutoaim(fixed16_16 xPos, fixed16_16 yPos, fixed16_16 zPos, angle14_32 pitch, angle14_32 yaw, s32 variation); - - // Adjust the speed - in TFE the framerate may be higher than expected by the original code, which means that this - // step (proj->delta) is too large for the 'speed'. - void tfe_adjustWeaponCollisionSpeed(ProjectileLogic* proj) - { - fixed16_16 initSpeed = div16(vec3Length(proj->delta.x, proj->delta.y, proj->delta.z), max(1, s_deltaTime)); - proj->col_speed = proj->speed; - if (initSpeed > proj->speed) - { - proj->col_speed = initSpeed; - } - } - - void tfe_restoreWeaponCollisionSpeed(ProjectileLogic* proj) - { - proj->col_speed = proj->speed; - } - - void weaponFire_fist(MessageType msg) - { - struct LocalContext - { - Tick delay; - s32 iFrame; - }; - task_begin_ctx; - - taskCtx->delay = (s_superCharge) ? c_punchAnim[0].delaySupercharge : c_punchAnim[0].delayNormal; - s_curPlayerWeapon->frame = c_punchAnim[0].waxFrame; - s_weaponLight = c_punchAnim[0].weaponLight; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - - if (s_punchSwingSndId) - { - sound_stop(s_punchSwingSndId); - } - s_punchSwingSndId = sound_play(s_punchSwingSndSrc); - - if (s_curPlayerWeapon->wakeupRange) - { - vec3_fixed origin = { s_playerObject->posWS.x, s_playerObject->posWS.y, s_playerObject->posWS.z }; - collision_effectObjectsInRangeXZ(s_playerObject->sector, s_curPlayerWeapon->wakeupRange, origin, hitEffectWakeupFunc, s_playerObject, ETFLAG_AI_ACTOR); - } - - task_localBlockBegin; - fixed16_16 mtx[9]; - weapon_computeMatrix(mtx, -s_playerObject->pitch, -s_playerObject->yaw); - - fixed16_16 xOffset = -114688; // -1.75 - angle14_32 yawOffset = -910; - for (s32 i = 0; i < 3; i++, xOffset += 0x1c000, yawOffset += 910) - { - ProjectileLogic* proj = (ProjectileLogic*)createProjectile(ProjectileType::PROJ_PUNCH, s_playerObject->sector, s_playerObject->posWS.x, s_playerObject->posWS.y - s_playerObject->worldHeight + s_headwaveVerticalOffset, s_playerObject->posWS.z, s_playerObject); - - s_weaponFirePitch = s_playerObject->pitch + 0x638; - s_weaponFireYaw = s_playerObject->yaw + yawOffset; - proj_setTransform(proj, s_weaponFirePitch, s_weaponFireYaw); - - proj->hitEffectId = HEFFECT_PUNCH; - proj->prevColObj = s_playerObject; - proj->excludeObj = s_playerObject; - - vec3_fixed inVec = - { - xOffset, // -1.75, 0.0, +1.75 - 0x18000, // 1.5 - 0x60000 // 6.0 - }; - rotateVectorM3x3(&inVec, &proj->delta, mtx); - - tfe_adjustWeaponCollisionSpeed(proj); - - ProjectileHitType hitType = proj_handleMovement(proj); - handleProjectileHit(proj, hitType); - - tfe_restoreWeaponCollisionSpeed(proj); - } - task_localBlockEnd; - - // Animation. - for (taskCtx->iFrame = 1; taskCtx->iFrame < TFE_ARRAYSIZE(c_punchAnim); taskCtx->iFrame++) - { - s_curPlayerWeapon->frame = c_punchAnim[taskCtx->iFrame].waxFrame; - s_weaponLight = c_punchAnim[taskCtx->iFrame].weaponLight; - taskCtx->delay = (s_superCharge) ? c_punchAnim[taskCtx->iFrame].delaySupercharge : c_punchAnim[taskCtx->iFrame].delayNormal; - - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - } - s_canFireWeaponPrim = 1; - s_canFireWeaponSec = 1; - - task_end; - } - - void weaponFire_pistol(MessageType msg) - { - struct LocalContext - { - Tick delay; - s32 iFrame; - }; - task_begin_ctx; - - if (*s_curPlayerWeapon->ammo) - { - task_localBlockBegin; - if (s_pistolSndId) - { - sound_stop(s_pistolSndId); - } - s_pistolSndId = sound_play(s_pistolSndSrc); - - if (s_curPlayerWeapon->wakeupRange) - { - vec3_fixed origin = { s_playerObject->posWS.x, s_playerObject->posWS.y, s_playerObject->posWS.z }; - collision_effectObjectsInRangeXZ(s_playerObject->sector, s_curPlayerWeapon->wakeupRange, origin, hitEffectWakeupFunc, s_playerObject, ETFLAG_AI_ACTOR); - } - - fixed16_16 mtx[9]; - weapon_computeMatrix(mtx, -s_playerObject->pitch, -s_playerObject->yaw); - - vec3_fixed inVec = - { - 0x6666, // 0.4 - 0x9999, // 0.6 - 0x33333 // 3.2 - }; - vec3_fixed outVec; - rotateVectorM3x3(&inVec, &outVec, mtx); - - fixed16_16 xPos = s_playerObject->posWS.x + outVec.x; - fixed16_16 yPos = outVec.y + s_playerObject->posWS.y - s_playerObject->worldHeight + s_headwaveVerticalOffset; - fixed16_16 zPos = s_playerObject->posWS.z + outVec.z; - - JBool targetFound = computeAutoaim(xPos, yPos, zPos, s_playerObject->pitch, s_playerObject->yaw, s_curPlayerWeapon->variation & 0xffff); - if (!targetFound) - { - s32 variation = s_curPlayerWeapon->variation & 0xffff; - variation = random(variation * 2) - variation; - s_weaponFirePitch = s_playerObject->pitch + variation; - - variation = s_curPlayerWeapon->variation & 0xffff; - variation = random(variation * 2) - variation; - s_weaponFireYaw = s_playerObject->yaw + variation; - } - - s32 canFire = s_canFireWeaponPrim; - fixed16_16 mtx2[9]; - s_canFireWeaponPrim = 0; - if (canFire > 1) - { - weapon_computeMatrix(mtx2, -s_weaponFirePitch, -s_weaponFireYaw); - } - - // Spawn projectiles. - fixed16_16 fire = intToFixed16(canFire); - while (canFire) - { - if (*s_curPlayerWeapon->ammo == 0) - { - break; - } - fire -= ONE_16; - canFire--; - s32 superChargeFrame = s_superCharge ? 0 : 1; - // This is always true if super charge is *not* active otherwise - // it is true every other frame. - if (superChargeFrame | (s_fireFrame & 1)) - { - *s_curPlayerWeapon->ammo = pickup_addToValue(s_playerInfo.ammoEnergy, -1, 500); - } - - ProjectileLogic* projLogic; - fixed16_16 yPos = s_playerObject->posWS.y - s_playerObject->worldHeight + s_headwaveVerticalOffset; - projLogic = (ProjectileLogic*)createProjectile(PROJ_PISTOL_BOLT, s_playerObject->sector, s_playerObject->posWS.x, yPos, s_playerObject->posWS.z, s_playerObject); - projLogic->flags &= ~PROJFLAG_CAMERA_PASS_SOUND; - projLogic->prevColObj = s_playerObject; - - if (targetFound) - { - proj_setYawPitch(projLogic, s_wpnPitchSin, s_wpnPitchCos, s_autoAimDirX, s_autoAimDirZ); - - SecObject* projObj = projLogic->logic.obj; - projObj->pitch = s_weaponFirePitch; - projObj->yaw = s_weaponFireYaw; - } - else - { - proj_setTransform(projLogic, s_weaponFirePitch, s_weaponFireYaw); - } - - if (canFire) - { - vec3_fixed inVec2 = { 0 }; - if (canFire > 1) - { - // TODO: This doesn't seem to be hit in the base game. - assert(0); - } - - Tick v0 = (s_superCharge) ? 21 : 43; - Tick v1 = (s_superCharge) ? 7 : 14; - Tick v2 = (s_superCharge) ? 7 : 14; - inVec2.z = intToFixed16(s32(float(v0 + v1 + v2) * 1.71f)); - - vec3_fixed outVec2; - rotateVectorM3x3(&inVec2, &outVec2, mtx2); - // First try using the outVec value computed above. - projLogic->delta = outVec; - tfe_adjustWeaponCollisionSpeed(projLogic); - - ProjectileHitType hitType = proj_handleMovement(projLogic); - if (!handleProjectileHit(projLogic, hitType)) - { - // If that fails, then try the new value. - projLogic->delta = outVec2; - tfe_adjustWeaponCollisionSpeed(projLogic); - - hitType = proj_handleMovement(projLogic); - fire = handleProjectileHit(projLogic, hitType); - } - } - else - { - projLogic->delta = outVec; - tfe_adjustWeaponCollisionSpeed(projLogic); - - ProjectileHitType hitType = proj_handleMovement(projLogic); - handleProjectileHit(projLogic, hitType); - } - tfe_restoreWeaponCollisionSpeed(projLogic); - } - task_localBlockEnd; - - // Animation. - for (taskCtx->iFrame = 0; taskCtx->iFrame < TFE_ARRAYSIZE(c_pistolAnim); taskCtx->iFrame++) - { - s_curPlayerWeapon->frame = c_pistolAnim[taskCtx->iFrame].waxFrame; - s_weaponLight = c_pistolAnim[taskCtx->iFrame].weaponLight; - taskCtx->delay = (s_superCharge) ? c_pistolAnim[taskCtx->iFrame].delaySupercharge : c_pistolAnim[taskCtx->iFrame].delayNormal; - - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - } - - s_canFireWeaponPrim = 1; - s_canFireWeaponSec = 1; - } - else // Out of Ammo - { - if (s_outOfAmmoSndId) - { - sound_stop(s_outOfAmmoSndId); - } - s_outOfAmmoSndId = sound_play(s_pistolEmptySndSrc); - - taskCtx->delay = (s_superCharge) ? 3 : 7; - s_curPlayerWeapon->frame = 0; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - - s_canFireWeaponPrim = 0; - s_canFireWeaponSec = 0; - // if (s_weaponAutoMount2) - // { - // func_1ece78(); - // } - } - - task_end; - } - - void weaponFire_rifle(MessageType msg) - { - struct LocalContext - { - Tick delay; - s32 iFrame; - }; - task_begin_ctx; - - if (*s_curPlayerWeapon->ammo) - { - task_localBlockBegin; - if (s_rifleSndId) - { - sound_stop(s_rifleSndId); - } - s_rifleSndId = sound_play(s_rifleSndSrc); - - if (s_curPlayerWeapon->wakeupRange) - { - vec3_fixed origin = { s_playerObject->posWS.x, s_playerObject->posWS.y, s_playerObject->posWS.z }; - collision_effectObjectsInRangeXZ(s_playerObject->sector, s_curPlayerWeapon->wakeupRange, origin, hitEffectWakeupFunc, s_playerObject, ETFLAG_AI_ACTOR); - } - - fixed16_16 mtx[9]; - weapon_computeMatrix(mtx, -s_playerObject->pitch, -s_playerObject->yaw); - - vec3_fixed inVec = - { - 0x6666, // 0.4 - 0xc000, // 0.75 - 0x40000 // 4.0 - }; - vec3_fixed outVec; - rotateVectorM3x3(&inVec, &outVec, mtx); - - fixed16_16 xPos = s_playerObject->posWS.x + outVec.x; - fixed16_16 yPos = outVec.y + s_playerObject->posWS.y - s_playerObject->worldHeight + s_headwaveVerticalOffset; - fixed16_16 zPos = s_playerObject->posWS.z + outVec.z; - - JBool targetFound = computeAutoaim(xPos, yPos, zPos, s_playerObject->pitch, s_playerObject->yaw, s_curPlayerWeapon->variation & 0xffff); - if (!targetFound) - { - s32 variation = s_curPlayerWeapon->variation & 0xffff; - variation = random(variation * 2) - variation; - s_weaponFirePitch = s_playerObject->pitch + variation; - - variation = s_curPlayerWeapon->variation & 0xffff; - variation = random(variation * 2) - variation; - s_weaponFireYaw = s_playerObject->yaw + variation; - } - - s32 canFire = s_canFireWeaponPrim; - fixed16_16 mtx2[9]; - s_canFireWeaponPrim = 0; - if (canFire > 1) - { - weapon_computeMatrix(mtx2, -s_weaponFirePitch, -s_weaponFireYaw); - } - - // Spawn projectiles. - fixed16_16 fire = intToFixed16(canFire); - while (canFire) - { - if (*s_curPlayerWeapon->ammo == 0) - { - break; - } - fire -= ONE_16; - canFire--; - s32 superChargeFrame = s_superCharge ? 0 : 1; - // This is always true if super charge is *not* active otherwise - // it is true every other frame. - if (superChargeFrame | (s_fireFrame & 1)) - { - *s_curPlayerWeapon->ammo = pickup_addToValue(s_playerInfo.ammoEnergy, -2, 500); - } - - ProjectileLogic* projLogic; - fixed16_16 yPos = s_playerObject->posWS.y - s_playerObject->worldHeight + s_headwaveVerticalOffset; - projLogic = (ProjectileLogic*)createProjectile(PROJ_RIFLE_BOLT, s_playerObject->sector, s_playerObject->posWS.x, yPos, s_playerObject->posWS.z, s_playerObject); - projLogic->flags &= ~PROJFLAG_CAMERA_PASS_SOUND; - projLogic->prevColObj = s_playerObject; - - if (targetFound) - { - proj_setYawPitch(projLogic, s_wpnPitchSin, s_wpnPitchCos, s_autoAimDirX, s_autoAimDirZ); - - SecObject* projObj = projLogic->logic.obj; - projObj->pitch = s_weaponFirePitch; - projObj->yaw = s_weaponFireYaw; - } - else - { - proj_setTransform(projLogic, s_weaponFirePitch, s_weaponFireYaw); - } - - if (canFire) - { - vec3_fixed inVec2 = { 0 }; - if (canFire > 1) - { - // TODO: This doesn't seem to be hit in the base game. - assert(0); - } - - Tick v0 = (s_superCharge) ? 7 : 14; - Tick v1 = (s_superCharge) ? 3 : 7; - Tick v2 = (s_superCharge) ? 3 : 7; - inVec2.z = intToFixed16(s32(float(v0 + v1 + v2) * 1.71f)); - - vec3_fixed outVec2; - rotateVectorM3x3(&inVec2, &outVec2, mtx2); - // First try using the outVec value computed above. - projLogic->delta = outVec; - tfe_adjustWeaponCollisionSpeed(projLogic); - - ProjectileHitType hitType = proj_handleMovement(projLogic); - if (!handleProjectileHit(projLogic, hitType)) - { - // If that fails, then try the new value. - projLogic->delta = outVec2; - tfe_adjustWeaponCollisionSpeed(projLogic); - - hitType = proj_handleMovement(projLogic); - fire = handleProjectileHit(projLogic, hitType); - } - } - else - { - projLogic->delta = outVec; - tfe_adjustWeaponCollisionSpeed(projLogic); - - ProjectileHitType hitType = proj_handleMovement(projLogic); - handleProjectileHit(projLogic, hitType); - } - tfe_restoreWeaponCollisionSpeed(projLogic); - } - task_localBlockEnd; - - // Animation. - for (taskCtx->iFrame = 0; taskCtx->iFrame < TFE_ARRAYSIZE(c_rifleAnim); taskCtx->iFrame++) - { - s_curPlayerWeapon->frame = c_rifleAnim[taskCtx->iFrame].waxFrame; - s_weaponLight = c_rifleAnim[taskCtx->iFrame].weaponLight; - taskCtx->delay = (s_superCharge) ? c_rifleAnim[taskCtx->iFrame].delaySupercharge : c_rifleAnim[taskCtx->iFrame].delayNormal; - - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - } - - s_canFireWeaponPrim = 1; - s_canFireWeaponSec = 1; - } - else // Out of Ammo - { - if (s_outOfAmmoSndId) - { - sound_stop(s_outOfAmmoSndId); - } - s_outOfAmmoSndId = sound_play(s_pistolEmptySndSrc); - - taskCtx->delay = (s_superCharge) ? 3 : 7; - s_curPlayerWeapon->frame = 0; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - - s_canFireWeaponPrim = 0; - s_canFireWeaponSec = 0; - // if (s_weaponAutoMount2) - // { - // func_1ece78(); - // } - } - - task_end; - } - - void weaponFire_thermalDetonator(MessageType msg) - { - struct LocalContext - { - Tick delay; - Tick startTick; - s32 iFrame; - }; - task_begin_ctx; - - if (*s_curPlayerWeapon->ammo) - { - s_canFireWeaponPrim = 0; - s_canFireWeaponSec = 0; - *s_curPlayerWeapon->ammo = pickup_addToValue(s_playerInfo.ammoDetonator, -1, 50); - - // Weapon Frame 0. - s_curPlayerWeapon->frame = c_thermalDetAnim[0].waxFrame; - do - { - task_yield(c_thermalDetAnim[0].delayNormal); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - - s_curPlayerWeapon->xOffset = 100; - s_curPlayerWeapon->yOffset = 100; - taskCtx->startTick = s_curTick; - task_callTaskFunc(weapon_handleState2); - - // Wait until the player is no longer "shooting" - // This holds the thermal detonator in place. - while (s_isShooting) - { - task_yield(TASK_NO_DELAY); - task_callTaskFunc(weapon_handleState); - }; - - task_localBlockBegin; - task_callTaskFunc(weapon_handleState2); - fixed16_16 dt = intToFixed16(s_curTick - taskCtx->startTick); - - if (s_curPlayerWeapon->wakeupRange) - { - vec3_fixed origin = { s_playerObject->posWS.x, s_playerObject->posWS.y, s_playerObject->posWS.z }; - collision_effectObjectsInRangeXZ(s_playerObject->sector, s_curPlayerWeapon->wakeupRange, origin, hitEffectWakeupFunc, s_playerObject, ETFLAG_AI_ACTOR); - } - - fixed16_16 yPos = s_playerObject->posWS.y - s_playerObject->worldHeight + s_headwaveVerticalOffset; - ProjectileLogic* proj = (ProjectileLogic*)createProjectile(PROJ_THERMAL_DET, s_playerObject->sector, s_playerObject->posWS.x, yPos, s_playerObject->posWS.z, s_playerObject); - proj->flags &= ~PROJFLAG_CAMERA_PASS_SOUND; - proj->prevColObj = s_playerObject; - - // Calculate projectile speed and duration. - if (s_secondaryFire) - { - dt = max(dt, FIXED(23)); - } - else - { - proj->duration = 0xffffffff; - proj->bounceCnt = 0; - dt = max(dt, FIXED(58)); - } - dt = min(dt, FIXED(116)); - proj->speed = mul16(div16(dt, FIXED(116)), FIXED(100)); - - // Calculate projectile transform. - s32 baseVariation = s_curPlayerWeapon->variation & 0xffff; - s32 pitchVariation = random(baseVariation * 2) - baseVariation; - s_weaponFirePitch = (s_playerObject->pitch >> 1) + 0x638 + pitchVariation; - - s32 yawVariation = random(baseVariation * 2) - baseVariation; - s_weaponFireYaw = s_playerObject->yaw + yawVariation; - - proj_setTransform(proj, s_weaponFirePitch, s_weaponFireYaw); - - // Calculate initial projectile delta and handle up close collision. - fixed16_16 mtx[9]; - weapon_computeMatrix(mtx, -(s_playerObject->pitch + 0x638), -s_playerObject->yaw); - - vec3_fixed inVec = { FIXED(2), FIXED(2), FIXED(2) }; - rotateVectorM3x3(&inVec, &proj->delta, mtx); - tfe_adjustWeaponCollisionSpeed(proj); - - ProjectileHitType hitType = proj_handleMovement(proj); - handleProjectileHit(proj, hitType); - - tfe_restoreWeaponCollisionSpeed(proj); - task_localBlockEnd; - - // Handle animation - s_curPlayerWeapon->xOffset = 0; - s_curPlayerWeapon->yOffset = 0; - - // The initial frame is the same regardless of ammo. - s_curPlayerWeapon->frame = c_thermalDetAnim[1].waxFrame; - s_weaponLight = c_thermalDetAnim[1].weaponLight; - taskCtx->delay = c_thermalDetAnim[1].delayNormal; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - - if (*s_curPlayerWeapon->ammo) - { - for (taskCtx->iFrame = 2; taskCtx->iFrame <= 3; taskCtx->iFrame++) - { - s_curPlayerWeapon->frame = c_thermalDetAnim[taskCtx->iFrame].waxFrame; - s_weaponLight = c_thermalDetAnim[taskCtx->iFrame].weaponLight; - taskCtx->delay = c_thermalDetAnim[taskCtx->iFrame].delayNormal; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - } - } - else - { - s_curPlayerWeapon->frame = c_thermalDetAnim[4].waxFrame; - s_weaponLight = c_thermalDetAnim[4].weaponLight; - taskCtx->delay = c_thermalDetAnim[4].delayNormal; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - } - - s_canFireWeaponPrim = 1; - s_canFireWeaponSec = 1; - } - else // Out of Ammo - { - if (s_weaponAutoMount2) - { - //func_1ece78(); - //return; - } - - s_lastWeapon = s_curWeapon; - s_curWeapon = WPN_FIST; - s_playerInfo.curWeapon = s_prevWeapon; - if (s_weaponOffAnim) - { - task_callTaskFunc(weapon_handleOffAnimation); - } - weapon_setNext(s_curWeapon); - task_callTaskFunc(weapon_handleOnAnimation); - } - - task_end; - } - - void weaponFire_repeater(MessageType msg) - { - struct LocalContext - { - Tick delay; - s32 iFrame; - }; - task_begin_ctx; - - if (s_secondaryFire) - { - if (*s_curPlayerWeapon->ammo) - { - if (s_repeaterFireSndID1) - { - sound_stop(s_repeaterFireSndID1); - } - s_repeaterFireSndID1 = sound_play(s_repeater1SndSrc); - - if (s_curPlayerWeapon->wakeupRange) - { - vec3_fixed origin = { s_playerObject->posWS.x, s_playerObject->posWS.y, s_playerObject->posWS.z }; - collision_effectObjectsInRangeXZ(s_playerObject->sector, s_curPlayerWeapon->wakeupRange, origin, hitEffectWakeupFunc, s_playerObject, ETFLAG_AI_ACTOR); - } - - taskCtx->delay = s_superCharge ? c_repeaterAnim[1].delaySupercharge : c_repeaterAnim[1].delayNormal; - s_curPlayerWeapon->frame = c_repeaterAnim[1].waxFrame; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - - task_localBlockBegin; - fixed16_16 mtx[9]; - weapon_computeMatrix(mtx, -s_playerObject->pitch, -s_playerObject->yaw); - - s32 baseVariation = s_curPlayerWeapon->variation & 0xffff; - s32 variation = random(baseVariation * 2) - baseVariation; - s_weaponFirePitch = s_playerObject->pitch + variation; - - variation = random(variation * 2) - variation; - s_weaponFireYaw = s_playerObject->yaw + variation; - - s32 canFire = s_canFireWeaponSec; - s_canFireWeaponSec = 0; - - fixed16_16 mtx2[9]; - if (canFire > 1) - { - weapon_computeMatrix(mtx2, -s_weaponFirePitch, -s_weaponFireYaw); - } - - fixed16_16 fire = intToFixed16(canFire); - while (canFire) - { - if (!*s_curPlayerWeapon->ammo) - { - break; - } - canFire--; - fire -= ONE_16; - s32 superChargeFrame = s_superCharge ? 0 : 1; - // This is always true if super charge is *not* active otherwise - // it is true every other frame. - if (superChargeFrame | (s_fireFrame & 1)) - { - *s_curPlayerWeapon->ammo = pickup_addToValue(s_playerInfo.ammoPower, -3, 500); - } - - fixed16_16 yPos = s_playerObject->posWS.y - s_playerObject->worldHeight + s_headwaveVerticalOffset; - ProjectileLogic* proj[3]; - for (s32 i = 0; i < 3; i++) - { - proj[i] = (ProjectileLogic*)createProjectile(PROJ_REPEATER, s_playerObject->sector, s_playerObject->posWS.x, yPos, s_playerObject->posWS.z, s_playerObject); - proj[i]->flags &= ~PROJFLAG_CAMERA_PASS_SOUND; - proj_setTransform(proj[i], s_weaponFirePitch + c_repeaterPitchOffset[i], s_weaponFireYaw + c_repeaterYawOffset[i]); - proj[i]->prevColObj = s_playerObject; - } - - for (s32 i = 0; i < 3; i++) - { - vec3_fixed inVec = { c_repeaterDelta[1 + i*3], c_repeaterDelta[2 + i*3], c_repeaterDelta[i*3] }; - vec3_fixed outVec; - rotateVectorM3x3(&inVec, &outVec, mtx); - - if (canFire) - { - // TODO - assert(0); - } - else - { - proj[i]->delta = outVec; - tfe_adjustWeaponCollisionSpeed(proj[i]); - - // Initial movement to make sure the player isn't too close to a wall or adjoin. - ProjectileHitType hitType = proj_handleMovement(proj[i]); - handleProjectileHit(proj[i], hitType); - tfe_restoreWeaponCollisionSpeed(proj[i]); - } - } - } - task_localBlockEnd; - - // Animation - for (taskCtx->iFrame = 2; taskCtx->iFrame < TFE_ARRAYSIZE(c_repeaterAnim); taskCtx->iFrame++) - { - s_curPlayerWeapon->frame = c_repeaterAnim[taskCtx->iFrame].waxFrame; - s_weaponLight = c_repeaterAnim[taskCtx->iFrame].weaponLight; - taskCtx->delay = (s_superCharge) ? c_repeaterAnim[taskCtx->iFrame].delaySupercharge : c_repeaterAnim[taskCtx->iFrame].delayNormal; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - } - s_canFireWeaponSec = 1; - } - else - { - if (s_repeaterFireSndID) - { - sound_stop(s_repeaterFireSndID); - s_repeaterFireSndID = 0; - } - if (s_repeaterOutOfAmmoSndId) - { - sound_stop(s_repeaterOutOfAmmoSndId); - } - s_repeaterOutOfAmmoSndId = sound_play(s_repeaterEmptySndSrc); - - taskCtx->delay = (s_superCharge) ? 3 : 7; - s_curPlayerWeapon->frame = 0; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - - s_canFireWeaponPrim = 0; - s_canFireWeaponSec = 0; - - /* TODO: - if (s_weaponAutoMount2) - { - func_1ece78(); - }*/ - } - } - else // Primary Fire. - { - if (*s_curPlayerWeapon->ammo) - { - if (!s_repeaterFireSndID) - { - if (s_repeaterFireSndID1) - { - sound_stop(s_repeaterFireSndID1); - } - s_repeaterFireSndID1 = sound_play(s_repeater1SndSrc); - s_repeaterFireSndID = sound_play(s_repeaterSndSrc); - } - - if (s_curPlayerWeapon->wakeupRange) - { - vec3_fixed origin = { s_playerObject->posWS.x, s_playerObject->posWS.y, s_playerObject->posWS.z }; - collision_effectObjectsInRangeXZ(s_playerObject->sector, s_curPlayerWeapon->wakeupRange, origin, hitEffectWakeupFunc, s_playerObject, ETFLAG_AI_ACTOR); - } - - taskCtx->delay = s_superCharge ? c_repeaterAnim[0].delaySupercharge : c_repeaterAnim[0].delayNormal; - s_curPlayerWeapon->frame = c_repeaterAnim[0].waxFrame; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - - task_localBlockBegin; - fixed16_16 mtx[9]; - weapon_computeMatrix(mtx, -s_playerObject->pitch, -s_playerObject->yaw); - - vec3_fixed inVec = - { - 0xcccc, // 0.8 - 0xfae1, // 0.98 - 0x50000 // 5.0 - }; - vec3_fixed outVec; - rotateVectorM3x3(&inVec, &outVec, mtx); - - fixed16_16 xPos = s_playerObject->posWS.x + outVec.x; - fixed16_16 yPos = outVec.y + s_playerObject->posWS.y - s_playerObject->worldHeight + s_headwaveVerticalOffset; - fixed16_16 zPos = s_playerObject->posWS.z + outVec.z; - - s32 baseVariation = s_curPlayerWeapon->variation & 0xffff; - JBool targetFound = computeAutoaim(xPos, yPos, zPos, s_playerObject->pitch, s_playerObject->yaw, baseVariation); - if (!targetFound) - { - s32 variation = random(baseVariation * 2) - baseVariation; - s_weaponFirePitch = s_playerObject->pitch + variation; - - variation = random(variation * 2) - variation; - s_weaponFireYaw = s_playerObject->yaw + variation; - } - - s32 canFire = s_canFireWeaponPrim; - fixed16_16 mtx2[9]; - s_canFireWeaponPrim = 0; - if (canFire > 1) - { - weapon_computeMatrix(mtx2, -s_weaponFirePitch, -s_weaponFireYaw); - } - - fixed16_16 fire = intToFixed16(canFire); - while (canFire) - { - if (!*s_curPlayerWeapon->ammo) - { - break; - } - canFire--; - fire -= ONE_16; - s32 superChargeFrame = s_superCharge ? 0 : 1; - // This is always true if super charge is *not* active otherwise - // it is true every other frame. - if (superChargeFrame | (s_fireFrame & 1)) - { - *s_curPlayerWeapon->ammo = pickup_addToValue(s_playerInfo.ammoPower, -1, 500); - } - - fixed16_16 yPos = s_playerObject->posWS.y - s_playerObject->worldHeight + s_headwaveVerticalOffset; - ProjectileLogic* projLogic = (ProjectileLogic*)createProjectile(PROJ_REPEATER, s_playerObject->sector, s_playerObject->posWS.x, yPos, s_playerObject->posWS.z, s_playerObject); - projLogic->flags &= ~PROJFLAG_CAMERA_PASS_SOUND; - projLogic->prevColObj = s_playerObject; - if (targetFound) - { - proj_setYawPitch(projLogic, s_wpnPitchSin, s_wpnPitchCos, s_autoAimDirX, s_autoAimDirZ); - - SecObject* projObj = projLogic->logic.obj; - projObj->pitch = s_weaponFirePitch; - projObj->yaw = s_weaponFireYaw; - } - else - { - proj_setTransform(projLogic, s_weaponFirePitch, s_weaponFireYaw); - } - - if (canFire) - { - // TODO - assert(0); - } - else - { - projLogic->delta = outVec; - tfe_adjustWeaponCollisionSpeed(projLogic); - - // Initial movement to make sure the player isn't too close to a wall or adjoin. - ProjectileHitType hitType = proj_handleMovement(projLogic); - handleProjectileHit(projLogic, hitType); - tfe_restoreWeaponCollisionSpeed(projLogic); - } - } - task_localBlockEnd; - - taskCtx->delay = s_superCharge ? c_repeaterAnim[2].delaySupercharge : c_repeaterAnim[2].delayNormal; - s_weaponLight = c_repeaterAnim[2].weaponLight; - s_curPlayerWeapon->frame = c_repeaterAnim[2].waxFrame; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - - s_weaponLight = 0; - - // The repeater has an extra delay before it can be fired again. - if (s_isShooting) - { - taskCtx->delay = (s_superCharge) ? 5 : 10; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - } - - s_canFireWeaponPrim = 1; - } - else - { - if (s_repeaterFireSndID) - { - sound_stop(s_repeaterFireSndID); - s_repeaterFireSndID = 0; - } - if (s_repeaterOutOfAmmoSndId) - { - sound_stop(s_repeaterOutOfAmmoSndId); - } - s_repeaterOutOfAmmoSndId = sound_play(s_repeaterEmptySndSrc); - - taskCtx->delay = (s_superCharge) ? 3 : 7; - s_curPlayerWeapon->frame = 0; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - - s_canFireWeaponPrim = 0; - s_canFireWeaponSec = 0; - - /* TODO: - if (s_weaponAutoMount2) - { - func_1ece78(); - }*/ - } - } - - task_end; - } - - void weaponFire_fusion(MessageType msg) - { - struct LocalContext - { - Tick delay; - s32 iFrame; - }; - task_begin_ctx; - - if (s_secondaryFire) - { - if (*s_curPlayerWeapon->ammo) - { - if (s_fusionFireSndID) - { - sound_stop(s_fusionFireSndID); - } - s_fusionFireSndID = sound_play(s_fusion1SndSrc); - - if (s_curPlayerWeapon->wakeupRange) - { - vec3_fixed origin = { s_playerObject->posWS.x, s_playerObject->posWS.y, s_playerObject->posWS.z }; - collision_effectObjectsInRangeXZ(s_playerObject->sector, s_curPlayerWeapon->wakeupRange, origin, hitEffectWakeupFunc, s_playerObject, ETFLAG_AI_ACTOR); - } - - task_localBlockBegin; - fixed16_16 mtx[9]; - weapon_computeMatrix(mtx, -s_playerObject->pitch, -s_playerObject->yaw); - - s32 baseVariation = s_curPlayerWeapon->variation & 0xffff; - s32 variation = random(baseVariation * 2) - baseVariation; - s_weaponFirePitch = s_playerObject->pitch + variation; - - variation = random(variation * 2) - variation; - s_weaponFireYaw = s_playerObject->yaw + variation; - - s32 canFire = s_canFireWeaponSec; - s_canFireWeaponSec = 0; - - fixed16_16 mtx2[9]; - if (canFire > 1) - { - weapon_computeMatrix(mtx2, -s_weaponFirePitch, -s_weaponFireYaw); - } - - fixed16_16 fire = intToFixed16(canFire); - while (canFire) - { - if (!*s_curPlayerWeapon->ammo) - { - break; - } - canFire--; - fire -= ONE_16; - s32 superChargeFrame = s_superCharge ? 0 : 1; - // This is always true if super charge is *not* active otherwise - // it is true every other frame. - if (superChargeFrame | (s_fireFrame & 1)) - { - *s_curPlayerWeapon->ammo = pickup_addToValue(s_playerInfo.ammoPower, -8, 500); - } - - fixed16_16 yPos = s_playerObject->posWS.y - s_playerObject->worldHeight + s_headwaveVerticalOffset; - ProjectileLogic* proj[4]; - for (s32 i = 0; i < 4; i++) - { - proj[i] = (ProjectileLogic*)createProjectile(PROJ_PLASMA, s_playerObject->sector, s_playerObject->posWS.x, yPos, s_playerObject->posWS.z, s_playerObject); - proj[i]->flags &= ~PROJFLAG_CAMERA_PASS_SOUND; - proj_setTransform(proj[i], s_weaponFirePitch, s_weaponFireYaw + s_fusionYawOffset[i]); - proj[i]->prevColObj = s_playerObject; - } - - for (s32 i = 0; i < 4; i++) - { - vec3_fixed inVec = { s_fusionOffset[1 + i*3], s_fusionOffset[2 + i*3], s_fusionOffset[i*3] }; - vec3_fixed outVec; - rotateVectorM3x3(&inVec, &outVec, mtx); - - if (canFire) - { - // TODO - assert(0); - } - else - { - proj[i]->delta = outVec; - tfe_adjustWeaponCollisionSpeed(proj[i]); - - // Initial movement to make sure the player isn't too close to a wall or adjoin. - ProjectileHitType hitType = proj_handleMovement(proj[i]); - handleProjectileHit(proj[i], hitType); - tfe_restoreWeaponCollisionSpeed(proj[i]); - } - } - } - task_localBlockEnd; - - // Animation - // TODO: not using the tables for this due to differences - refactor later. - s_curPlayerWeapon->frame = 5; - s_weaponLight = 34; - taskCtx->delay = (s_superCharge) ? 14 : 29; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - - s_curPlayerWeapon->frame = 0; - s_weaponLight = 0; - taskCtx->delay = (s_superCharge) ? 19 : 39; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - - s_canFireWeaponSec = 1; - } - else - { - if (s_fusionOutOfAmmoSndID) - { - sound_stop(s_fusionOutOfAmmoSndID); - } - s_fusionOutOfAmmoSndID = sound_play(s_fusion2SndSrc); - - taskCtx->delay = (s_superCharge) ? 3 : 7; - s_curPlayerWeapon->frame = 0; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - - s_canFireWeaponPrim = 0; - s_canFireWeaponSec = 0; - - /* TODO: - if (s_weaponAutoMount2) - { - func_1ece78(); - }*/ - } - } - else // Primary Fire. - { - if (*s_curPlayerWeapon->ammo) - { - if (s_fusionFireSndID) - { - sound_stop(s_fusionFireSndID); - } - s_fusionFireSndID = sound_play(s_fusion1SndSrc); - - if (s_curPlayerWeapon->wakeupRange) - { - vec3_fixed origin = { s_playerObject->posWS.x, s_playerObject->posWS.y, s_playerObject->posWS.z }; - collision_effectObjectsInRangeXZ(s_playerObject->sector, s_curPlayerWeapon->wakeupRange, origin, hitEffectWakeupFunc, s_playerObject, ETFLAG_AI_ACTOR); - } - - task_localBlockBegin; - fixed16_16 mtx[9]; - weapon_computeMatrix(mtx, -s_playerObject->pitch, -s_playerObject->yaw); - - s32 canFire = s_canFireWeaponPrim; - fixed16_16 mtx2[9]; - s_canFireWeaponPrim = 0; - if (canFire > 1) - { - weapon_computeMatrix(mtx2, -s_weaponFirePitch, -s_weaponFireYaw); - } - - fixed16_16 fire = intToFixed16(canFire); - while (canFire) - { - if (!*s_curPlayerWeapon->ammo) - { - break; - } - canFire--; - fire -= ONE_16; - - vec3_fixed inVec = - { - s_fusionOffset[(s_fusionCylinder-1)*3 + 1], - s_fusionOffset[(s_fusionCylinder-1)*3 + 2], - s_fusionOffset[(s_fusionCylinder-1)*3 + 0] - }; - vec3_fixed outVec; - rotateVectorM3x3(&inVec, &outVec, mtx); - - fixed16_16 xPos = s_playerObject->posWS.x + outVec.x; - fixed16_16 yPos = outVec.y + s_playerObject->posWS.y - s_playerObject->worldHeight + s_headwaveVerticalOffset; - fixed16_16 zPos = s_playerObject->posWS.z + outVec.z; - - s32 baseVariation = s_curPlayerWeapon->variation & 0xffff; - JBool targetFound = computeAutoaim(xPos, yPos, zPos, s_playerObject->pitch, s_playerObject->yaw, baseVariation); - if (!targetFound) - { - s32 variation = random(baseVariation * 2) - baseVariation; - s_weaponFirePitch = s_playerObject->pitch + variation; - - variation = random(baseVariation * 2) - baseVariation; - s_weaponFireYaw = s_playerObject->yaw + variation; - } - - s32 superChargeFrame = s_superCharge ? 0 : 1; - // This is always true if super charge is *not* active otherwise - // it is true every other frame. - if (superChargeFrame | (s_fireFrame & 1)) - { - *s_curPlayerWeapon->ammo = pickup_addToValue(s_playerInfo.ammoPower, -1, 500); - } - - fixed16_16 yPlayerPos = s_playerObject->posWS.y - s_playerObject->worldHeight + s_headwaveVerticalOffset; - ProjectileLogic* projLogic = (ProjectileLogic*)createProjectile(PROJ_PLASMA, s_playerObject->sector, s_playerObject->posWS.x, yPlayerPos, s_playerObject->posWS.z, s_playerObject); - projLogic->flags &= ~PROJFLAG_CAMERA_PASS_SOUND; - projLogic->prevColObj = s_playerObject; - if (targetFound) - { - proj_setYawPitch(projLogic, s_wpnPitchSin, s_wpnPitchCos, s_autoAimDirX, s_autoAimDirZ); - - SecObject* projObj = projLogic->logic.obj; - projObj->pitch = s_weaponFirePitch; - projObj->yaw = s_weaponFireYaw; - } - else - { - proj_setTransform(projLogic, s_weaponFirePitch, s_weaponFireYaw); - } - - if (canFire) - { - // TODO - assert(0); - } - else - { - projLogic->delta = outVec; - tfe_adjustWeaponCollisionSpeed(projLogic); - - // Initial movement to make sure the player isn't too close to a wall or adjoin. - ProjectileHitType hitType = proj_handleMovement(projLogic); - handleProjectileHit(projLogic, hitType); - tfe_restoreWeaponCollisionSpeed(projLogic); - } - } - task_localBlockEnd; - - taskCtx->delay = s_superCharge ? 10 : 20; - s_weaponLight = 34; - s_curPlayerWeapon->frame = s_fusionCylinder; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - - if (s_fusionCycleForward) - { - s_fusionCylinder++; - if (s_fusionCylinder > 4) - { - s_fusionCylinder = 3; - s_fusionCycleForward = JFALSE; - } - } - else - { - s_fusionCylinder--; - if (s_fusionCylinder < 1) - { - s_fusionCylinder = 2; - s_fusionCycleForward = JTRUE; - } - } - - taskCtx->delay = s_superCharge ? 7 : 14; - s_weaponLight = 0; - s_curPlayerWeapon->frame = 0; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - - s_canFireWeaponPrim = 1; - } - else - { - if (s_fusionOutOfAmmoSndID) - { - sound_stop(s_fusionOutOfAmmoSndID); - } - s_fusionOutOfAmmoSndID = sound_play(s_fusion2SndSrc); - - taskCtx->delay = (s_superCharge) ? 3 : 7; - s_curPlayerWeapon->frame = 0; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - - s_canFireWeaponPrim = 0; - s_canFireWeaponSec = 0; - - /* TODO: - if (s_weaponAutoMount2) - { - func_1ece78(); - }*/ - } - } - - task_end; - } - - void weaponFire_mortar(MessageType msg) - { - struct LocalContext - { - Tick delay; - s32 iFrame; - }; - task_begin_ctx; - - if (*s_curPlayerWeapon->ammo) - { - task_localBlockBegin; - if (s_mortarFireSndID) - { - sound_stop(s_mortarFireSndID); - } - s_mortarFireSndID = sound_play(s_mortarFireSndSrc); - - if (s_curPlayerWeapon->wakeupRange) - { - vec3_fixed origin = { s_playerObject->posWS.x, s_playerObject->posWS.y, s_playerObject->posWS.z }; - collision_effectObjectsInRangeXZ(s_playerObject->sector, s_curPlayerWeapon->wakeupRange, origin, hitEffectWakeupFunc, s_playerObject, ETFLAG_AI_ACTOR); - } - - fixed16_16 mtx[9]; - weapon_computeMatrix(mtx, -s_playerObject->pitch, -s_playerObject->yaw); - - s32 canFire = s_canFireWeaponPrim; - s_canFireWeaponPrim = 0; - - s32 wpnVariation = s_curPlayerWeapon->variation & 0xffff; - s32 variation; - if (canFire > 1) - { - variation = random(wpnVariation * 2) - wpnVariation + 0x333; - s_weaponFirePitch = s_playerObject->pitch + (variation >> 2); - } - else - { - variation = random(wpnVariation * 2) - wpnVariation + 0x333; - s_weaponFirePitch = s_playerObject->pitch + variation; - } - - variation = random(wpnVariation * 2) - wpnVariation; - s_weaponFireYaw = s_playerObject->yaw + variation; - - vec3_fixed inVec = - { - 0xb333, // 0.7 - 0x1b333, // 1.7 - 0x20000 // 2.0 - }; - vec3_fixed outVec; - rotateVectorM3x3(&inVec, &outVec, mtx); - - fixed16_16 mtx2[9]; - if (canFire > 1) - { - weapon_computeMatrix(mtx2, -s_weaponFirePitch, -s_weaponFireYaw); - } - - // Spawn projectiles. - fixed16_16 fire = intToFixed16(canFire); - while (canFire) - { - if (*s_curPlayerWeapon->ammo == 0) - { - break; - } - fire -= ONE_16; - canFire--; - s32 superChargeFrame = s_superCharge ? 0 : 1; - // This is always true if super charge is *not* active otherwise - // it is true every other frame. - if (superChargeFrame | (s_fireFrame & 1)) - { - *s_curPlayerWeapon->ammo = pickup_addToValue(s_playerInfo.ammoShell, -1, 50); - } - - ProjectileLogic* projLogic; - fixed16_16 yPos = s_playerObject->posWS.y - s_playerObject->worldHeight + s_headwaveVerticalOffset; - projLogic = (ProjectileLogic*)createProjectile(PROJ_MORTAR, s_playerObject->sector, s_playerObject->posWS.x, yPos, s_playerObject->posWS.z, s_playerObject); - projLogic->flags &= ~PROJFLAG_CAMERA_PASS_SOUND; - projLogic->prevColObj = s_playerObject; - proj_setTransform(projLogic, s_weaponFirePitch, s_weaponFireYaw); - - if (canFire) - { - vec3_fixed worldUp = { 0 }; - if (canFire > 1) - { - // TODO: This doesn't seem to be hit in the base game. - assert(0); - } - - Tick v0 = (s_superCharge) ? 7 : 14; - Tick v1 = (s_superCharge) ? 29 : 58; - Tick v2 = (s_superCharge) ? 7 : 14; - Tick v3 = (s_superCharge) ? 7 : 14; - worldUp.z = intToFixed16(s32(float(v0 + v1 + v2 + v3) * 0.75f)); - - vec3_fixed outVec2; - rotateVectorM3x3(&worldUp, &outVec2, mtx2); - // First try using the outVec value computed above. - projLogic->delta = outVec; - tfe_adjustWeaponCollisionSpeed(projLogic); - - ProjectileHitType hitType = proj_handleMovement(projLogic); - if (!handleProjectileHit(projLogic, hitType)) - { - // If that fails, then try the new value. - projLogic->delta = outVec2; - tfe_adjustWeaponCollisionSpeed(projLogic); - - hitType = proj_handleMovement(projLogic); - fire = handleProjectileHit(projLogic, hitType); - } - } - else - { - projLogic->delta = outVec; - tfe_adjustWeaponCollisionSpeed(projLogic); - - ProjectileHitType hitType = proj_handleMovement(projLogic); - handleProjectileHit(projLogic, hitType); - } - tfe_restoreWeaponCollisionSpeed(projLogic); - } - task_localBlockEnd; - - // Animation. - for (taskCtx->iFrame = 0; taskCtx->iFrame < TFE_ARRAYSIZE(c_mortarAnim); taskCtx->iFrame++) - { - if (taskCtx->iFrame == 1) - { - if (s_mortarFireSndID2) - { - sound_stop(s_mortarFireSndID2); - } - s_mortarFireSndID2 = sound_play(s_mortarFireSndSrc2); - } - - s_curPlayerWeapon->frame = c_mortarAnim[taskCtx->iFrame].waxFrame; - s_weaponLight = c_mortarAnim[taskCtx->iFrame].weaponLight; - taskCtx->delay = (s_superCharge) ? c_mortarAnim[taskCtx->iFrame].delaySupercharge : c_mortarAnim[taskCtx->iFrame].delayNormal; - - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - } - - s_canFireWeaponPrim = 1; - s_canFireWeaponSec = 1; - } - else // Out of Ammo - { - if (s_mortarOutofAmmoSndId) - { - sound_stop(s_mortarOutofAmmoSndId); - } - s_mortarOutofAmmoSndId = sound_play(s_mortarEmptySndSrc); - - taskCtx->delay = (s_superCharge) ? 3 : 7; - s_curPlayerWeapon->frame = 0; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - - s_canFireWeaponPrim = 0; - s_canFireWeaponSec = 0; - // if (s_weaponAutoMount2) - // { - // func_1ece78(); - // } - } - - task_end; - } - - void weaponFire_mine(MessageType msg) - { - task_begin; - if (*s_curPlayerWeapon->ammo) - { - *s_curPlayerWeapon->ammo = pickup_addToValue(s_playerInfo.ammoMine, -1, 30); - if (s_curPlayerWeapon->wakeupRange) - { - vec3_fixed origin = { s_playerObject->posWS.x, s_playerObject->posWS.y, s_playerObject->posWS.z }; - collision_effectObjectsInRangeXZ(s_playerObject->sector, s_curPlayerWeapon->wakeupRange, origin, hitEffectWakeupFunc, s_playerObject, ETFLAG_AI_ACTOR); - } - - s_weaponAnimState = - { - 1, // frame - 0, 0, // offset - 0, 20, // xSpeed, ySpeed - 5, 7 // frameCount, ticksPerFrame - }; - task_callTaskFunc(weapon_animateOnOrOffscreen); - - task_localBlockBegin; - fixed16_16 floorHeight, ceilHeight; - sector_getObjFloorAndCeilHeight(s_playerObject->sector, s_playerObject->posWS.y, &floorHeight, &ceilHeight); - - ProjectileType type = (s_secondaryFire) ? PROJ_LAND_MINE_PROX : PROJ_LAND_MINE; - ProjectileLogic* mine = (ProjectileLogic*)createProjectile(type, s_playerObject->sector, s_playerObject->posWS.x, floorHeight, s_playerObject->posWS.z, s_playerObject); - mine->vel = { 0, 0, 0 }; - - if (s_mineSndId) - { - sound_stop(s_mineSndId); - } - s_mineSndId = sound_play(s_mineSndSrc); - - s32 frame = (*s_curPlayerWeapon->ammo) ? 0 : 2; - s_weaponAnimState = - { - frame, // frame - 0, 100, // offset - 0, -20, // xSpeed, ySpeed - 5, 7 // frameCount, ticksPerFrame - }; - task_localBlockEnd; - task_callTaskFunc(weapon_animateOnOrOffscreen); - - task_yield(2); - } - else - { - if (s_weaponAutoMount2) - { - // func_1ece78(); - // return; - } - - s_lastWeapon = s_curWeapon; - s_curWeapon = WPN_FIST; - s_playerInfo.curWeapon = s_prevWeapon; - if (s_weaponOffAnim) - { - task_callTaskFunc(weapon_handleOffAnimation); - } - weapon_setNext(s_curWeapon); - task_callTaskFunc(weapon_handleOnAnimation); - } - task_end; - } - - void weaponFire_concussion(MessageType msg) - { - struct LocalContext - { - Tick delay; - s32 iFrame; - }; - task_begin_ctx; - - if (*s_curPlayerWeapon->ammo) - { - task_localBlockBegin; - if (s_concussionFireSndID) - { - sound_stop(s_concussionFireSndID); - } - s_concussionFireSndID = sound_play(s_concussion6SndSrc); - - if (s_curPlayerWeapon->wakeupRange) - { - vec3_fixed origin = { s_playerObject->posWS.x, s_playerObject->posWS.y, s_playerObject->posWS.z }; - collision_effectObjectsInRangeXZ(s_playerObject->sector, s_curPlayerWeapon->wakeupRange, origin, hitEffectWakeupFunc, s_playerObject, ETFLAG_AI_ACTOR); - } - - fixed16_16 mtx[9]; - weapon_computeMatrix(mtx, -s_playerObject->pitch, -s_playerObject->yaw); - - vec3_fixed inVec = - { - 0x10000, // 1.0 - 0x8000, // 0.5 - 0x30000 // 3.0 - }; - vec3_fixed outVec; - rotateVectorM3x3(&inVec, &outVec, mtx); - - fixed16_16 xPos = s_playerObject->posWS.x + outVec.x; - fixed16_16 yPos = s_playerObject->posWS.y + outVec.y - s_playerObject->worldHeight + s_headwaveVerticalOffset; - fixed16_16 zPos = s_playerObject->posWS.z + outVec.z; - - s32 baseVariation = s_curPlayerWeapon->variation & 0xffff; - JBool targetFound = computeAutoaim(xPos, yPos, zPos, s_playerObject->pitch, s_playerObject->yaw, s_curPlayerWeapon->variation & 0xffff); - if (!targetFound) - { - s32 variation = random(baseVariation * 2) - baseVariation; - s_weaponFirePitch = s_playerObject->pitch + variation; - - variation = random(baseVariation * 2) - baseVariation; - s_weaponFireYaw = s_playerObject->yaw + variation; - } - - s32 canFire = s_canFireWeaponPrim; - fixed16_16 mtx2[9]; - s_canFireWeaponPrim = 0; - if (canFire > 1) - { - weapon_computeMatrix(mtx2, -s_weaponFirePitch, -s_weaponFireYaw); - } - - // Spawn projectiles. - fixed16_16 fire = intToFixed16(canFire); - while (canFire) - { - if (*s_curPlayerWeapon->ammo == 0) - { - break; - } - fire -= ONE_16; - canFire--; - s32 superChargeFrame = s_superCharge ? 0 : 1; - // This is always true if super charge is *not* active otherwise - // it is true every other frame. - if (superChargeFrame | (s_fireFrame & 1)) - { - *s_curPlayerWeapon->ammo = pickup_addToValue(s_playerInfo.ammoPower, -4, 500); - } - - ProjectileLogic* projLogic; - fixed16_16 yPos = s_playerObject->posWS.y - s_playerObject->worldHeight + s_headwaveVerticalOffset; - projLogic = (ProjectileLogic*)createProjectile(PROJ_CONCUSSION, s_playerObject->sector, s_playerObject->posWS.x, yPos, s_playerObject->posWS.z, s_playerObject); - projLogic->flags &= ~PROJFLAG_CAMERA_PASS_SOUND; - projLogic->prevColObj = s_playerObject; - - if (targetFound) - { - proj_setYawPitch(projLogic, s_wpnPitchSin, s_wpnPitchCos, s_autoAimDirX, s_autoAimDirZ); - - SecObject* projObj = projLogic->logic.obj; - projObj->pitch = s_weaponFirePitch; - projObj->yaw = s_weaponFireYaw; - } - else - { - proj_setTransform(projLogic, s_weaponFirePitch, s_weaponFireYaw); - } - - if (canFire) - { - assert(0); - // TODO - } - else - { - projLogic->delta = outVec; - tfe_adjustWeaponCollisionSpeed(projLogic); - - ProjectileHitType hitType = proj_handleMovement(projLogic); - handleProjectileHit(projLogic, hitType); - - tfe_restoreWeaponCollisionSpeed(projLogic); - } - } - task_localBlockEnd; - - // Animation. - if (s_concussionFireSndID1) - { - sound_stop(s_concussionFireSndID1); - } - s_concussionFireSndID1 = sound_play(s_concussion5SndSrc); - - for (taskCtx->iFrame = 0; taskCtx->iFrame < TFE_ARRAYSIZE(c_concussionAnim); taskCtx->iFrame++) - { - s_curPlayerWeapon->frame = c_concussionAnim[taskCtx->iFrame].waxFrame; - s_weaponLight = c_concussionAnim[taskCtx->iFrame].weaponLight; - taskCtx->delay = (s_superCharge) ? c_concussionAnim[taskCtx->iFrame].delaySupercharge : c_concussionAnim[taskCtx->iFrame].delayNormal; - - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - } - - s_canFireWeaponPrim = 1; - s_canFireWeaponSec = 1; - } - else // Out of Ammo - { - if (s_concussionOutOfAmmoSndID) - { - sound_stop(s_concussionOutOfAmmoSndID); - } - s_concussionOutOfAmmoSndID = sound_play(s_concussion1SndSrc); - - taskCtx->delay = (s_superCharge) ? 3 : 7; - s_curPlayerWeapon->frame = 0; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - - s_canFireWeaponPrim = 0; - s_canFireWeaponSec = 0; - // if (s_weaponAutoMount2) - // { - // func_1ece78(); - // } - } - - task_end; - } - - void weaponFire_cannon(MessageType msg) - { - struct LocalContext - { - Tick delay; - s32 iFrame; - }; - task_begin_ctx; - - if (s_secondaryFire) - { - if (*s_curPlayerWeapon->secondaryAmmo) - { - taskCtx->delay = (s_superCharge) ? 14 : 29; - s_curPlayerWeapon->frame = 2; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - - if (s_cannonFireSndID1) - { - sound_stop(s_cannonFireSndID1); - } - s_cannonFireSndID1 = sound_play(s_missile1SndSrc); - - if (s_curPlayerWeapon->wakeupRange) - { - vec3_fixed origin = { s_playerObject->posWS.x, s_playerObject->posWS.y, s_playerObject->posWS.z }; - collision_effectObjectsInRangeXZ(s_playerObject->sector, s_curPlayerWeapon->wakeupRange, origin, hitEffectWakeupFunc, s_playerObject, ETFLAG_AI_ACTOR); - } - - task_localBlockBegin; - fixed16_16 mtx[9]; - weapon_computeMatrix(mtx, -s_playerObject->pitch, -s_playerObject->yaw); - - vec3_fixed outVec; - vec3_fixed inVec = - { - 0x20000, // 2.0 - 0x4000, // 0.25 - 0x40000, // 4.0 - }; - rotateVectorM3x3(&inVec, &outVec, mtx); - - fixed16_16 xPos = s_playerObject->posWS.x + outVec.x; - fixed16_16 yPos = s_playerObject->posWS.y + outVec.y - s_playerObject->worldHeight + s_headwaveVerticalOffset; - fixed16_16 zPos = s_playerObject->posWS.z + outVec.z; - - s32 baseVariation = s_curPlayerWeapon->variation & 0xffff; - JBool targetFound = computeAutoaim(xPos, yPos, zPos, s_playerObject->pitch, s_playerObject->yaw, baseVariation); - if (!targetFound) - { - s32 variation = random(baseVariation * 2) - baseVariation; - s_weaponFirePitch = s_playerObject->pitch + variation; - - variation = random(baseVariation * 2) - baseVariation; - s_weaponFireYaw = s_playerObject->yaw + variation; - } - - s32 canFire = s_canFireWeaponSec; - s_canFireWeaponSec = 0; - - fixed16_16 mtx2[9]; - if (canFire > 1) - { - weapon_computeMatrix(mtx2, -s_weaponFirePitch, -s_weaponFireYaw); - } - - fixed16_16 fire = intToFixed16(canFire); - while (canFire && *s_curPlayerWeapon->secondaryAmmo) - { - canFire--; - fire -= ONE_16; - - s32 superChargeFrame = s_superCharge ? 0 : 1; - if (superChargeFrame | (s_fireFrame & 1)) - { - *s_curPlayerWeapon->secondaryAmmo = pickup_addToValue(s_playerInfo.ammoMissile, -1, 20); - } - - fixed16_16 yPos = s_playerObject->posWS.y - s_playerObject->worldHeight + s_headwaveVerticalOffset; - ProjectileLogic* projLogic = (ProjectileLogic*)createProjectile(PROJ_MISSILE, s_playerObject->sector, s_playerObject->posWS.x, yPos, s_playerObject->posWS.z, s_playerObject); - projLogic->flags &= ~PROJFLAG_CAMERA_PASS_SOUND; - projLogic->prevColObj = s_playerObject; - if (targetFound) - { - proj_setYawPitch(projLogic, s_wpnPitchSin, s_wpnPitchCos, s_autoAimDirX, s_autoAimDirZ); - - SecObject* projObj = projLogic->logic.obj; - projObj->pitch = s_weaponFirePitch; - projObj->yaw = s_weaponFireYaw; - } - else - { - proj_setTransform(projLogic, s_weaponFirePitch, s_weaponFireYaw); - } - - if (canFire) - { - // TODO - assert(0); - } - else - { - // Initial movement and collision. - projLogic->delta = outVec; - tfe_adjustWeaponCollisionSpeed(projLogic); - - ProjectileHitType hit = proj_handleMovement(projLogic); - handleProjectileHit(projLogic, hit); - - tfe_restoreWeaponCollisionSpeed(projLogic); - } - } - task_localBlockEnd; - - // Animation - s_curPlayerWeapon->frame = 3; - s_weaponLight = 33; - taskCtx->delay = (s_superCharge) ? 43 : 87; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - - s_curPlayerWeapon->frame = 0; - s_weaponLight = 0; - taskCtx->delay = (s_superCharge) ? 29 : 58; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - - s_canFireWeaponSec = 1; - } - else - { - s_curPlayerWeapon->frame = 0; - taskCtx->delay = (s_superCharge) ? 3 : 7; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - - s_canFireWeaponSec = 0; - } - } - else // Primary Fire. - { - if (*s_curPlayerWeapon->ammo) - { - if (s_cannonFireSndID) - { - sound_stop(s_cannonFireSndID); - } - s_cannonFireSndID = sound_play(s_plasma4SndSrc); - - if (s_curPlayerWeapon->wakeupRange) - { - vec3_fixed origin = { s_playerObject->posWS.x, s_playerObject->posWS.y, s_playerObject->posWS.z }; - collision_effectObjectsInRangeXZ(s_playerObject->sector, s_curPlayerWeapon->wakeupRange, origin, hitEffectWakeupFunc, s_playerObject, ETFLAG_AI_ACTOR); - } - - task_localBlockBegin; - fixed16_16 mtx[9]; - weapon_computeMatrix(mtx, -s_playerObject->pitch, -s_playerObject->yaw); - - vec3_fixed inVec = - { - 0x10000, // 1.0 - 0x9999, // 0.6 - 0x30000 // 3.0 - }; - vec3_fixed outVec; - rotateVectorM3x3(&inVec, &outVec, mtx); - - fixed16_16 xPos = s_playerObject->posWS.x + outVec.x; - fixed16_16 yPos = s_playerObject->posWS.y + outVec.y - s_playerObject->worldHeight + s_headwaveVerticalOffset; - fixed16_16 zPos = s_playerObject->posWS.z + outVec.z; - - s32 baseVariation = s_curPlayerWeapon->variation & 0xffff; - JBool targetFound = computeAutoaim(xPos, yPos, zPos, s_playerObject->pitch, s_playerObject->yaw, baseVariation); - if (!targetFound) - { - s32 variation = random(baseVariation * 2) - baseVariation; - s_weaponFirePitch = s_playerObject->pitch + variation; - - variation = random(variation * 2) - variation; - s_weaponFireYaw = s_playerObject->yaw + variation; - } - - s32 canFire = s_canFireWeaponPrim; - fixed16_16 mtx2[9]; - s_canFireWeaponPrim = 0; - if (canFire > 1) - { - weapon_computeMatrix(mtx2, -s_weaponFirePitch, -s_weaponFireYaw); - } - - fixed16_16 fire = intToFixed16(canFire); - while (canFire && *s_curPlayerWeapon->ammo) - { - canFire--; - fire -= ONE_16; - - s32 superChargeFrame = s_superCharge ? 0 : 1; - if (superChargeFrame | (s_fireFrame & 1)) - { - *s_curPlayerWeapon->ammo = pickup_addToValue(s_playerInfo.ammoPlasma, -1, 400); - } - - fixed16_16 yPos = s_playerObject->posWS.y - s_playerObject->worldHeight + s_headwaveVerticalOffset; - ProjectileLogic* projLogic = (ProjectileLogic*)createProjectile(PROJ_CANNON, s_playerObject->sector, s_playerObject->posWS.x, yPos, s_playerObject->posWS.z, s_playerObject); - projLogic->flags &= ~PROJFLAG_CAMERA_PASS_SOUND; - projLogic->prevColObj = s_playerObject; - if (targetFound) - { - proj_setYawPitch(projLogic, s_wpnPitchSin, s_wpnPitchCos, s_autoAimDirX, s_autoAimDirZ); - - SecObject* projObj = projLogic->logic.obj; - projObj->pitch = s_weaponFirePitch; - projObj->yaw = s_weaponFireYaw; - } - else - { - proj_setTransform(projLogic, s_weaponFirePitch, s_weaponFireYaw); - } - - if (canFire) - { - // TODO - assert(0); - } - else - { - projLogic->delta = outVec; - tfe_adjustWeaponCollisionSpeed(projLogic); - - // Initial movement to make sure the player isn't too close to a wall or adjoin. - ProjectileHitType hitType = proj_handleMovement(projLogic); - handleProjectileHit(projLogic, hitType); - - tfe_restoreWeaponCollisionSpeed(projLogic); - } - } - task_localBlockEnd; - - s_curPlayerWeapon->frame = 1; - s_weaponLight = 34; - taskCtx->delay = ((s_superCharge) ? 14 : 29) >> 1; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - - s_weaponLight = 0; - if (s_isShooting) - { - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - } - - s_canFireWeaponPrim = 1; - } - else - { - if (s_cannonOutOfAmmoSndID) - { - sound_stop(s_cannonOutOfAmmoSndID); - } - s_cannonOutOfAmmoSndID = sound_play(s_plasmaEmptySndSrc); - - taskCtx->delay = (s_superCharge) ? 3 : 7; - s_curPlayerWeapon->frame = 0; - do - { - task_yield(taskCtx->delay); - task_callTaskFunc(weapon_handleState); - } while (msg != MSG_RUN_TASK); - - s_canFireWeaponPrim = 0; - - /* TODO: - if (s_weaponAutoMount2) - { - func_1ece78(); - }*/ - } - } - - task_end; - } - - JBool computeAutoaim(fixed16_16 xPos, fixed16_16 yPos, fixed16_16 zPos, angle14_32 pitch, angle14_32 yaw, s32 variation) - { - if (!s_drawnObjCount || !TFE_Settings::getGameSettings()->df_enableAutoaim) - { - return JFALSE; - } - fixed16_16 closest = MAX_AUTOAIM_DIST; - for (s32 i = 0; i < s_drawnObjCount; i++) - { - SecObject* obj = s_drawnObj[i]; - if (obj && (obj->flags & OBJ_FLAG_AIM)) - { - const fixed16_16 height = (obj->worldHeight >> 1) + (obj->worldHeight >> 2); // 3/4 object height. - - fixed16_16 dx = obj->posWS.x - xPos; - fixed16_16 dy = obj->posWS.y - height - yPos; - fixed16_16 dz = obj->posWS.z - zPos; - - angle14_32 angle = vec2ToAngle(dx, dz) & ANGLE_MASK; - angle14_32 yawDelta = (angle - yaw) & ANGLE_MASK; - if (yawDelta > 227 && yawDelta < 16111) - { - continue; - } - - fixed16_16 dirX, dirZ; - fixed16_16 dist = computeDirAndLength(dx, dz, &dirX, &dirZ); - if (dist < closest) - { - closest = dist; - s_weaponFireYaw = angle; - s_weaponFirePitch = vec2ToAngle(-dy, dist) & ANGLE_MASK; - - s_autoAimDirX = dirX; - s_autoAimDirZ = dirZ; - } - } - } - if (closest == MAX_AUTOAIM_DIST) - { - return JFALSE; - } - if (variation) - { - s32 angleVar = random(variation << 6) - (variation << 5); - s_autoAimDirX += angleVar; - s_autoAimDirZ += angleVar; - s_weaponFirePitch += random(variation * 2) + (pitch >> 3) - variation; - } - sinCosFixed(s_weaponFirePitch, &s_wpnPitchSin, &s_wpnPitchCos); - return JTRUE; - } -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_DarkForces/weaponFireFunc.h b/components/darkforces/tfe/TFE_DarkForces/weaponFireFunc.h deleted file mode 100644 index 319f3d9a..00000000 --- a/components/darkforces/tfe/TFE_DarkForces/weaponFireFunc.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dark Forces Player - -// Player information and object data. -////////////////////////////////////////////////////////////////////// -#include -#include - -namespace TFE_DarkForces -{ - typedef void(*WeaponFireFunc)(MessageType msg); - - void weaponFire_fist(MessageType msg); - void weaponFire_pistol(MessageType msg); - void weaponFire_rifle(MessageType msg); - void weaponFire_thermalDetonator(MessageType msg); - void weaponFire_repeater(MessageType msg); - void weaponFire_fusion(MessageType msg); - void weaponFire_mortar(MessageType msg); - void weaponFire_mine(MessageType msg); - void weaponFire_concussion(MessageType msg); - void weaponFire_cannon(MessageType msg); -} // namespace TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_FileSystem/filestream-posix.cpp b/components/darkforces/tfe/TFE_FileSystem/filestream-posix.cpp deleted file mode 100644 index 82151ff3..00000000 --- a/components/darkforces/tfe/TFE_FileSystem/filestream-posix.cpp +++ /dev/null @@ -1,307 +0,0 @@ -#include "filestream.h" -#include "fileutil.h" -#include "paths.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// das ist wirklich grauslich: -#ifdef TFE_ESPBOX -extern u32* s_workBufferU32; -extern char* s_workBufferChar; -extern char* s_writeStringTmp; -#else -extern u32 s_workBufferU32[1024]; //4k buffer. -extern char s_workBufferChar[32768]; //32k buffer. -#endif - - -FileStream::FileStream() : Stream() -{ - m_file = nullptr; - m_archive = nullptr; - m_mode = MODE_INVALID; -} - -FileStream::~FileStream() -{ - close(); -} - -bool FileStream::exists(const char *filename) -{ - return FileUtil::existsNoCase(filename); -} - -bool FileStream::open(const char *filename, AccessMode mode) -{ - const char* modeStrings[] = { "rb", "wb", "rb+" }; - char fn[TFE_MAX_PATH]; - char *fn2; - - if (!filename || 1 > strlen(filename)) - return false; - - memset(fn, 0, TFE_MAX_PATH); - strcpy(fn, filename); - // relative path: try to find in one of the system paths. - if (filename[0] != '/') - TFE_Paths::mapSystemPath(fn); - - // try to open the given filename first; if that fails, - // because the filename cannot be found, try to find - // a matching filename with different case in the - // given directory. - m_file = fopen(fn, modeStrings[mode]); - if ((m_file == NULL) && (errno == ENOENT)) { - // ok, try harder to find a filename with different case - fn2 = FileUtil::findFileNoCase(filename); - if (fn2 == NULL) { - m_mode = MODE_INVALID; - return false; - } - m_file = fopen(fn2, modeStrings[mode]); - free(fn2); - } - m_mode = mode; - - return m_file != nullptr; -} - -bool FileStream::open(const FilePath *filePath, AccessMode mode) -{ - if (filePath->archive) { - // Note: this currently only supports reading. - assert(mode == Stream::MODE_READ); - - if (filePath->index < 0) - return false; - m_mode = mode; - m_file = nullptr; - m_archive = filePath->archive; -#ifdef TFE_ESPBOX - m_archiveIndex = filePath->index; -#endif - - return filePath->archive->openFile(filePath->index); - } - return open(filePath->path, mode); -} - -#ifdef TFE_ESPBOX -bool FileStream::reselect() -{ - if (m_archive && m_archiveIndex >= 0) - { - return m_archive->openFile((u32)m_archiveIndex); - } - return true; -} -#endif - -void FileStream::close() -{ - if (m_file) { - fclose(m_file); - m_file = nullptr; - } else if (m_archive) { - m_archive->closeFile(); - m_archive = nullptr; - } - m_mode = MODE_INVALID; -} - -u32 FileStream::readContents(const char *filePath, void **output) -{ - assert(output); - - u32 size = 0; - FileStream file; - if (file.open(filePath, MODE_READ)) { - size = (u32)file.getSize(); - *output = realloc(*output, size + 1); - file.readBuffer(*output, size); - file.close(); - } - return size; -} - -u32 FileStream::readContents(const char *filePath, void *output, size_t size) -{ - assert(output); - - FileStream file; - if (file.open(filePath, MODE_READ)) { - size_t fileSize = file.getSize(); - size = size <= fileSize ? size : fileSize; - file.readBuffer(output, (u32)size); - file.close(); - - return u32(size); - } - return 0; -} - -u32 FileStream::readContents(const FilePath *filePath, void **output) -{ - assert(output); - - u32 size = 0; - FileStream file; - if (file.open(filePath, MODE_READ)) { - size = (u32)file.getSize(); - *output = realloc(*output, size + 1); - file.readBuffer(*output, size); - file.close(); - } - return size; -} - -// It is assumed that output has already been allocated. -u32 FileStream::readContents(const FilePath *filePath, void *output, size_t size) -{ - FileStream file; - if (file.open(filePath, MODE_READ)) { - size_t fileSize = file.getSize(); - size = size <= fileSize ? size : fileSize; - file.readBuffer(output, (u32)size); - file.close(); - - return u32(size); - } - return 0; -} - -//derived from Stream -bool FileStream::seek(s32 offset, Origin origin/*=ORIGIN_START*/) -{ - const s32 forigin[] = { SEEK_SET, SEEK_END, SEEK_CUR }; - if (m_file) { - return fseek(m_file, offset, forigin[origin]) == 0; - } else if (m_archive) { - return m_archive->seekFile(offset, forigin[origin]); - } - return false; -} - -size_t FileStream::getLoc(void) -{ - if (!m_file && !m_archive) - return 0; - - if (m_file) - return ftell(m_file); - - return m_archive->getLocInFile(); -} - -size_t FileStream::getSize(void) -{ - if (!m_file && !m_archive) - return 0; - - size_t filesize = 0; - if (m_file) { - seek(0, FileStream::ORIGIN_END); - filesize = getLoc(); - seek(0, FileStream::ORIGIN_START); - } else { - filesize = m_archive->getFileLength(); - } - - return filesize; -} - -bool FileStream::isOpen(void) const -{ - return (m_file != nullptr) || (m_archive != nullptr); -} - -u32 FileStream::readBuffer(void *ptr, u32 size, u32 count) -{ - assert(m_mode == MODE_READ || m_mode == MODE_READWRITE); - if (m_file) { - // fread() returns the number of *elements* read, but we want the number of bytes read. - return (u32)fread(ptr, size, count, m_file) * size; - } else if (m_archive) { - return (u32)m_archive->readFile(ptr, size * count); - } - return 0; -} - -void FileStream::writeBuffer(const void *ptr, u32 size, u32 count) -{ - assert(m_mode == MODE_WRITE || m_mode == MODE_READWRITE); - if (m_file) { - fwrite(ptr, size, count, m_file); - } -} - -void FileStream::writeString(const char *fmt, ...) -{ -#ifdef TFE_ESPBOX - char* tmpStr = s_writeStringTmp; -#else - static char tmpStr[4096]; -#endif - assert(m_mode == MODE_WRITE || m_mode == MODE_READWRITE); - - if (m_file) { - va_list arg; - va_start(arg, fmt); - vsprintf(tmpStr, fmt, arg); - va_end(arg); - - const size_t len = strlen(tmpStr); - fwrite(tmpStr, len, 1, m_file); - } -} - -void FileStream::flush() -{ - if (m_file) { - fflush(m_file); - } -} - -void FileStream::readString(std::string *ptr, u32 count) -{ - assert(m_mode == MODE_READ || m_mode == MODE_READWRITE); - assert(count <= 256); - //first read the length. - readBuffer(s_workBufferU32, sizeof(u32), count); - - //then read the string data. - for (u32 s=0; s -#include -#include - -//////////////////////////////////////////////////// -// TODO: FileStream directly accesses arhive data. -//////////////////////////////////////////////////// - -class Archive; - -class FileStream : public Stream -{ -public: - FileStream(); - ~FileStream(); - - bool exists(const char* filename); - bool open(const char* filename, AccessMode mode); - bool open(const FilePath* filePath, AccessMode mode); - void close(); - - static u32 readContents(const char* filePath, void** output); - static u32 readContents(const char* filePath, void* output, size_t size); - static u32 readContents(const FilePath* filePath, void** output); - static u32 readContents(const FilePath* filePath, void* output, size_t size); - - //derived functions. - bool seek(s32 offset, Origin origin=ORIGIN_START) override; - size_t getLoc() override; - size_t getSize() override; - bool isOpen() const; - - void flush(); - - void read(s8* ptr, u32 count=1) override { readType(ptr, count); } - void read(u8* ptr, u32 count=1) override { readType(ptr, count); } - void read(s16* ptr, u32 count=1) override { readType(ptr, count); } - void read(u16* ptr, u32 count=1) override { readType(ptr, count); } - void read(s32* ptr, u32 count=1) override { readType(ptr, count); } - void read(u32* ptr, u32 count=1) override { readType(ptr, count); } - void read(s64* ptr, u32 count=1) override { readType(ptr, count); } - void read(u64* ptr, u32 count=1) override { readType(ptr, count); } - void read(f32* ptr, u32 count=1) override { readType(ptr, count); } - void read(f64* ptr, u32 count=1) override { readType(ptr, count); } - void read(std::string* ptr, u32 count=1) override { readString(ptr, count); } - u32 readBuffer(void* ptr, u32 size, u32 count=1) override; - - void write(const s8* ptr, u32 count=1) override { writeType(ptr, count); } - void write(const u8* ptr, u32 count=1) override { writeType(ptr, count); } - void write(const s16* ptr, u32 count=1) override { writeType(ptr, count); } - void write(const u16* ptr, u32 count=1) override { writeType(ptr, count); } - void write(const s32* ptr, u32 count=1) override { writeType(ptr, count); } - void write(const u32* ptr, u32 count=1) override { writeType(ptr, count); } - void write(const s64* ptr, u32 count=1) override { writeType(ptr, count); } - void write(const u64* ptr, u32 count=1) override { writeType(ptr, count); } - void write(const f32* ptr, u32 count=1) override { writeType(ptr, count); } - void write(const f64* ptr, u32 count=1) override { writeType(ptr, count); } - void write(const std::string* ptr, u32 count=1) override { writeString(ptr, count); } - void writeBuffer(const void* ptr, u32 size, u32 count=1) override; - - void writeString(const char* fmt, ...) override; - -private: - template - void readType(T* ptr, u32 count) - { - assert(m_mode == MODE_READ || m_mode == MODE_READWRITE); - readBuffer(ptr, sizeof(T), count); - } - - template - void writeType(const T* ptr, u32 count) - { - assert(m_mode == MODE_WRITE || m_mode == MODE_READWRITE); - assert(m_file); // TODO: Add Archive support. - fwrite(ptr, sizeof(T), count, m_file); - } - - void readString(std::string* ptr, u32 count); - void writeString(const std::string* ptr, u32 count); - -#ifdef TFE_ESPBOX -public: - // Archives keep one current file: another stream opened on the same archive - // moves it. Make this stream's file current again (no-op for plain files). - bool reselect(); -#endif - -private: - FILE* m_file; - Archive* m_archive; - AccessMode m_mode; -#ifdef TFE_ESPBOX - s32 m_archiveIndex = -1; -#endif -}; diff --git a/components/darkforces/tfe/TFE_FileSystem/fileutil-posix.cpp b/components/darkforces/tfe/TFE_FileSystem/fileutil-posix.cpp deleted file mode 100644 index a802b310..00000000 --- a/components/darkforces/tfe/TFE_FileSystem/fileutil-posix.cpp +++ /dev/null @@ -1,428 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#ifdef TFE_ESPBOX -#include // PATH_MAX -#endif -#include -#include "fileutil.h" -#include "filestream.h" - -// implement TFE FileUtil for Linux and compatibles. -namespace FileUtil -{ - static char *findFileObjectNoCase(const char *filename, bool objisdir); - - void readDirectory(const char *dir, const char *ext, FileList& fileList) - { - char buf[PATH_MAX]; - struct dirent *de; - struct stat st; - int el, dl, ret; - char *dn; - DIR *d; - - d = opendir(dir); - if (!d) { - TFE_System::logWrite(LOG_ERROR, "readDirectory", "opendir(%s) failed with %d\n", dir, errno); - return; - } - - el = strlen(ext); - while (NULL != (de = readdir(d))) { - dn = de->d_name; - dl = strlen(dn); - memset(buf, 0, PATH_MAX); - snprintf(buf, PATH_MAX - 1, "%s%s", dir, de->d_name); - ret = stat(buf, &st); - if (ret || !S_ISREG(st.st_mode)) - continue; - - // skip dotfiles, dotdirs, too short and files without extensions. - if ((dl < (el + 2)) || (dn[0] == '.')) - continue; - if (dn[dl - el - 1] != '.') - continue; - // does the extension match (unix: case sensitive!) - if (0 != strncasecmp(dn + dl - el, ext, el)) - continue; - // we have a winner - fileList.push_back(string(dn)); - } - closedir(d); - } - - void readSubdirectories(const char *dir, FileList& dirList) - { - char *dn, fp[PATH_MAX]; - struct dirent *de; - struct stat st; - int l1, l2, ret; - DIR *d; - - d = opendir(dir); - if (!d) { - TFE_System::logWrite(LOG_ERROR, "readSubdirctories", "opendir(%s) failed with %d\n", dir, errno); - return; - } - l1 = strlen(dir); - while (NULL != (de = readdir(d))) { - dn = de->d_name; - memset(fp, 0, PATH_MAX); - snprintf(fp, PATH_MAX - 2, "%s%s", dir, dn); - ret = stat(fp, &st); - if (ret || !S_ISDIR(st.st_mode)) - continue; - - if (!strcmp(dn, ".") || !strcmp(dn, "..")) - continue; - - strcat(fp, "/"); - dirList.push_back(string(fp)); - } - closedir(d); - } - - bool makeDirectory(const char *dir) - { -#ifdef TFE_ESPBOX - char buf[PATH_MAX], *c; - strncpy(buf, dir, sizeof(buf)); - // kill trailing slash - c = strrchr(buf, '/'); - if (c) - *c = 0; - - if (!mkdir(buf, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) || errno == EEXIST) -#else - if (!mkdir(dir, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) || errno == EEXIST) -#endif - return true; - return false; - } - - void getCurrentDirectory(char *dir) - { -#ifdef TFE_ESPBOX - strcpy(dir, TFE_ESPBOX_BASE_DIR); - return; -#endif - char *err = getcwd(dir, TFE_MAX_PATH); - /* should not happen, but just to be sure */ - if (err == NULL) { - TFE_System::logWrite(LOG_ERROR, "getCurrentDirectory", "getcwd() error %d", errno); - memset(dir, 0, TFE_MAX_PATH); - /* substitute home */ - strcpy(dir, getenv("HOME")); - } - } - - void getExecutionDirectory(char *dir) - { -#ifdef TFE_ESPBOX - strcpy(dir, TFE_ESPBOX_BASE_DIR); - return; -#endif - char exe[PATH_MAX], *c; - ssize_t r; - - memset(dir, 0, TFE_MAX_PATH); - memset(exe, 0, PATH_MAX); - sprintf(exe, "/proc/%d/exe", getpid()); - r = readlink(exe, dir, PATH_MAX); - if (r < 0) { - TFE_System::logWrite(LOG_CRITICAL, "getExecutionDirectory", "readlink %s failed with %d", exe, errno); - return; - } - - // kill trailing slash - c = strrchr(dir, '/'); - if (c) - *c = 0; - } - - void setCurrentDirectory(const char *dir) - { -#ifdef TFE_ESPBOX - return; -#endif - int ret = chdir(dir); - if (ret) { - TFE_System::logWrite(LOG_ERROR, "chdir(%s) failed with %d", dir, errno); - } - } - - void getFilePath(const char *fn, char *path) - { - char *tmpbuf, *dn; - int l; - - memset(path, 0, TFE_MAX_PATH); - if (!fn) - return; - l = strlen(fn); - if (!l) - return; - - // dirname() messes with the input buffer - make a copy. - tmpbuf = (char *)malloc(l + 1); - if (!tmpbuf) - return; - strcpy(tmpbuf, fn); - dn = dirname(tmpbuf); - sprintf(path, "%s/", dn); - free(tmpbuf); - } - - void getFileExtension(const char *filename, char *extension) - { - const char *c; - - memset(extension, 0, TFE_MAX_PATH); - c = strrchr(filename, '.'); - if (c) { - strcpy(extension, c + 1); - } - } - - void getFileNameFromPath(const char *path, char *name, bool ext) - { - char *tmpbuf, *fn, *c; - - // basename() messes with the input buffer - make a copy. - memset(name, 0, TFE_MAX_PATH); - tmpbuf = (char *)malloc(TFE_MAX_PATH + 1); - if (!tmpbuf) - return; - strcpy(tmpbuf, path); - fn = basename(tmpbuf); - strcpy(name, fn); - if (!ext) { - // find the last dot and null it. - c = strrchr(name, '.'); - if (c) - *c = 0; - } - free(tmpbuf); - } - - void copyFile(const char *src, const char *dst) - { - ssize_t rd, wr; - char buf[1024]; - int s, d; - - s = open(src, O_RDONLY); - if (!s) - return; - d = open(dst, O_WRONLY | O_CREAT, 00644); - if (!d) { - close(s); - return; - } - - do { - rd = read(s, buf, 1024); - if (rd <= 0) - break; - wr = write(d, buf, rd); - if (wr < 0 || wr != rd) - break; - } while (rd > 0); - close(d); - close(s); - } - - void deleteFile(const char *fn) - { - int ret = unlink(fn); - if (ret) { - TFE_System::logWrite(LOG_WARNING, "deleteFile", "unlink(%s) failed with %d\n", fn, errno); - } - } - - bool directoryExits(const char *path, char *outPath) - { -#ifdef TFE_ESPBOX - struct stat st; - char buf[PATH_MAX], *c; - - strncpy(buf, path, sizeof(buf)); - // kill trailing slash - c = strrchr(buf, '/'); - if (c) - *c = 0; - - if (stat(buf, &st) || !S_ISDIR(st.st_mode)) - return false; - - if (outPath) - snprintf(outPath, TFE_MAX_PATH, "%s/", buf); - return true; -#else - char *ret; - - ret = findFileObjectNoCase(path, true); - if (ret == NULL) - return false; - - // replace input with found path - if (outPath) - snprintf(outPath, TFE_MAX_PATH, "%s/", ret); - free(ret); - return true; -#endif - } - - bool exists(const char *path) - { - return existsNoCase(path); - } - - // Linux filesystems are case-sensitive; try to open the - // base directory and find a file/directory that has the same name - // with different case. - // Caller MUST free the pointer returned by this function! - // Input: full path to file or dir: /abs/path/to/object - // This function will try to find "object" with differently cased name - // in path "/abs/path/to/". - static char *findFileObjectNoCase(const char *filename, bool objisdir) - { - char *fncopy, *dn, *fn; - char *result = NULL; - char buf[PATH_MAX]; - int ol, dl, fl, nfl, ret; - struct stat st; - struct dirent *de; - DIR *dir; - - // dirname() and basename() screw with the input buffer, - // hence we need to make 2 copies. - ol = strlen(filename); - fncopy = (char *)malloc(ol * 2 + 2); - if (!fncopy) - return NULL; - memset(fncopy, 0, ol + ol + 2); - strncpy(fncopy, filename, ol); - strncpy(fncopy + ol + 1, filename, ol); - - dn = dirname(fncopy); - fn = basename(fncopy + ol +1); - - dl = strlen(dn); - fl = strlen(fn); - if ((dl < 1) || (fl < 1)) { - free(fncopy); - return NULL; - } - - dir = opendir(dn); - if (!dir) { - free(fncopy); - return NULL; - } - - while (NULL != (de = readdir(dir))) - { - memset(buf, 0, PATH_MAX); - snprintf(buf, PATH_MAX - 2, "%s/%s", dn, de->d_name); - ret = stat(buf, &st); - if (ret != 0) - continue; - if (objisdir) { - if (!S_ISDIR(st.st_mode)) - continue; - } else { - if (!S_ISREG(st.st_mode)) - continue; - } - - nfl = strlen(de->d_name); - if (nfl != fl) - continue; - - if (0 != strncasecmp(de->d_name, fn, fl)) - continue; - - // found a match - result = (char *)malloc(dl + 1 + nfl + 1); - if (!result) - break; - memset(result, 0, dl + 1 + nfl + 1); - sprintf(result, "%s/%s", dn, de->d_name); - break; // we're done. - } - free(fncopy); - closedir(dir); - return result; - } - - char *findFileNoCase(const char *filename) - { -#ifdef TFE_ESPBOX - struct stat st; - - if (stat(filename, &st) || !S_ISREG(st.st_mode)) - return nullptr; - - return strdup(filename); -#else - return findFileObjectNoCase(filename, false); -#endif - } - - bool existsNoCase(const char *filename) - { - char *fn2 = findFileNoCase(filename); - if (fn2 != NULL) { - free(fn2); - return true; - } - - return false; - } - - u64 getModifiedTime(const char *path) - { - struct timespec tslw; - struct stat st; - u64 mtim; - - int ret = stat(path, &st); - if (ret) { - TFE_System::logWrite(LOG_WARNING, "getModifiedTime", "stat(%s) failed with %d\n", path, errno); - return (u64)-1; // revisit - } -#ifdef TFE_ESPBOX - tslw.tv_sec = st.st_mtime; - tslw.tv_nsec = 0; -#else - tslw = st.st_mtim; -#endif - mtim = (u64)tslw.tv_sec * 10000 + (u64) ((double)tslw.tv_nsec / 100.0); - - return mtim; - } - - void fixupPath(char *path) - { - char *c = path; - while (NULL != (c = strchr(c, '\\'))) { - *c = '/'; - } - } - - void convertToOSPath(const char *in, char *out) - { - memset(out, 0, TFE_MAX_PATH); - strncpy(out, in, TFE_MAX_PATH - 1); - fixupPath(out); - } -} diff --git a/components/darkforces/tfe/TFE_FileSystem/fileutil.h b/components/darkforces/tfe/TFE_FileSystem/fileutil.h deleted file mode 100644 index 237602c8..00000000 --- a/components/darkforces/tfe/TFE_FileSystem/fileutil.h +++ /dev/null @@ -1,35 +0,0 @@ -#pragma once -#include -#include -#include - -using namespace std; -typedef vector FileList; - -namespace FileUtil -{ - void readDirectory(const char* dir, const char* ext, FileList& fileList); - bool makeDirectory(const char* dir); - void getCurrentDirectory(char* dir); - void getExecutionDirectory(char* dir); - void setCurrentDirectory(const char* dir); - - void readSubdirectories(const char* dir, FileList& dirList); - - void getFileNameFromPath(const char* path, char* name, bool includeExt=false); - void getFilePath(const char* filename, char* path); - void getFileExtension(const char* filename, char* extension); - - void copyFile(const char* srcFile, const char* dstFile); - void deleteFile(const char* srcFile); - - bool exists(const char* path); - bool existsNoCase(const char* path); - bool directoryExits(const char* path, char* outPath = nullptr); - u64 getModifiedTime(const char* path); - - void fixupPath(char* path); - void convertToOSPath(const char* path, char* pathOS); - - char *findFileNoCase(const char *fn); -} diff --git a/components/darkforces/tfe/TFE_FileSystem/filewriterAsync.h b/components/darkforces/tfe/TFE_FileSystem/filewriterAsync.h deleted file mode 100644 index 0d2a4ba5..00000000 --- a/components/darkforces/tfe/TFE_FileSystem/filewriterAsync.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once -#include - -// TODO: Flesh out error codes. -enum AsyncFileWriteCodes -{ - AFW_SUCCESS = 0, -}; - -typedef void(*FileWriteCompletionCallback)(size_t bytesWritten, void* userData, u32 errorCode); - -namespace FileWriterAsync -{ - bool writeFileToDisk(const char* path, u8* data, size_t dataSize, FileWriteCompletionCallback completionCallback = nullptr, void* userData = nullptr); -}; diff --git a/components/darkforces/tfe/TFE_FileSystem/memorystream.cpp b/components/darkforces/tfe/TFE_FileSystem/memorystream.cpp deleted file mode 100644 index bf4cdf38..00000000 --- a/components/darkforces/tfe/TFE_FileSystem/memorystream.cpp +++ /dev/null @@ -1,236 +0,0 @@ -#include "memorystream.h" -#include -#include -#include -#include -#include - -//Work buffers for handling special cases like std::string without allocating memory (beyond what the strings needs itself). -#ifdef TFE_ESPBOX -u32* s_workBufferU32 = nullptr; //4k buffer (shared memory). -char* s_workBufferChar = nullptr; //32k buffer (shared memory). -char* s_writeStringTmp = nullptr; //4k scratch for writeString() (shared memory). -#else -u32 s_workBufferU32[1024]; //4k buffer. -char s_workBufferChar[32768]; //32k buffer. -#endif - -enum MemStreamConst : u32 -{ - MS_PAGE_SHIFT = 18u, - MS_PAGE_SIZE = 1u << MS_PAGE_SHIFT, // 256Kb page size to avoid excessive allocations with large streams. -}; - -MemoryStream::MemoryStream() : Stream() -{ - m_memory = nullptr; - m_size = 0u; - m_capacity = 0u; - m_addr = 0u; - m_mode = MODE_INVALID; -} - -MemoryStream::~MemoryStream() -{ - close(); - free(m_memory); -} - -bool MemoryStream::open(AccessMode mode) -{ - m_mode = mode; - m_addr = 0u; - - // Pre-allocate if writing. - if ((mode == MODE_WRITE || mode == MODE_READWRITE) && m_capacity == 0u) - { - m_memory = (u8*)malloc(MS_PAGE_SIZE); - m_capacity = MS_PAGE_SIZE; - } - return m_memory != nullptr; -} - -bool MemoryStream::load(size_t size, const void* const mem) -{ - if (!size || !mem) { return false; } - - clear(); - resizeBuffer(size); - if (!m_memory) { return false; } - - memcpy(m_memory, mem, size); - return true; -} - -bool MemoryStream::allocate(size_t size) -{ - if (!size) { return false; } - - clear(); - resizeBuffer(size); - return m_memory != nullptr; -} - -const void* const MemoryStream::data() const -{ - return m_memory; -} - -void* MemoryStream::data() -{ - return m_memory; -} - -void MemoryStream::close() -{ - m_mode = MODE_INVALID; -} - -void MemoryStream::clear() -{ - close(); - m_addr = 0u; - m_size = 0u; -} - -//derived from Stream -bool MemoryStream::seek(s32 offset, Origin origin/*=ORIGIN_START*/) -{ - if (m_memory) - { - if (origin == ORIGIN_START) - { - m_addr = offset; - } - else if (origin == ORIGIN_END) - { - m_addr = m_size + offset; - } - else - { - m_addr += offset; - } - return (m_addr <= m_size); - } - return false; -} - -size_t MemoryStream::getLoc() -{ - return m_addr; -} - -size_t MemoryStream::getSize() -{ - return m_size; -} - -bool MemoryStream::isOpen() const -{ - return m_mode != MODE_INVALID; -} - -u32 MemoryStream::readBuffer(void* ptr, u32 size, u32 count) -{ - assert(m_mode == MODE_READ || m_mode == MODE_READWRITE); - if (m_memory && (m_mode == MODE_READ || m_mode == MODE_READWRITE)) - { - size_t totalSize = size * count; - if (m_addr + totalSize > m_size) - { - totalSize = m_addr < m_size ? (m_size - m_addr) : (0u); - } - memcpy(ptr, m_memory + m_addr, totalSize); - // Step - m_addr += totalSize; - - return (u32)totalSize; - } - return 0; -} - -void MemoryStream::writeBuffer(const void* ptr, u32 size, u32 count) -{ - assert(m_mode == MODE_WRITE || m_mode == MODE_READWRITE); - if (m_memory && (m_mode == MODE_WRITE || m_mode == MODE_READWRITE)) - { - const u32 totalSize = size * count; - resizeBuffer(m_addr + totalSize); - memcpy(m_memory + m_addr, ptr, totalSize); - // Step - m_addr += totalSize; - } -} - -void MemoryStream::writeString(const char* fmt, ...) -{ -#ifdef TFE_ESPBOX - char* tmpStr = s_writeStringTmp; -#else - static char tmpStr[4096]; -#endif - va_list arg; - va_start(arg, fmt); - vsprintf(tmpStr, fmt, arg); - va_end(arg); - - const size_t len = strlen(tmpStr); - writeBuffer(tmpStr, (u32)len); -} - -void MemoryStream::readStringType(std::string* ptr, u32 count) -{ - assert(count <= 256); - //first read the length. - readBuffer(s_workBufferU32, sizeof(u32), count); - - //then read the string data. - for (u32 s=0; s m_capacity) - { - const size_t newPageCount = (newSize + MS_PAGE_SIZE - 1) >> MS_PAGE_SHIFT; - const size_t newCapacity = newPageCount << MS_PAGE_SHIFT; - m_memory = (u8*)realloc(m_memory, newCapacity); - m_capacity = newCapacity; - } - m_size = newSize; -} -#ifdef TFE_ESPBOX -void espbox_shared_streams(bool alloc) -{ - ESPBOX_SHARED_ALLOC(s_workBufferU32, 1024); - ESPBOX_SHARED_ALLOC(s_workBufferChar, 32768); - ESPBOX_SHARED_ALLOC(s_writeStringTmp, 4096); -} -#endif diff --git a/components/darkforces/tfe/TFE_FileSystem/memorystream.h b/components/darkforces/tfe/TFE_FileSystem/memorystream.h deleted file mode 100644 index faa06cd5..00000000 --- a/components/darkforces/tfe/TFE_FileSystem/memorystream.h +++ /dev/null @@ -1,93 +0,0 @@ -#pragma once -#include -#include - -class MemoryStream : public Stream -{ -public: - MemoryStream(); - ~MemoryStream(); - - // Load the memory stream from pre-existing memory. - // This makes a copy, so the original memory can be freed. - // This will fail if size == 0 or mem == nullptr. - // This will also reset the memory stream. - bool load(size_t size, const void* const mem); - // Pre-allocate stream memory, this assumes that the client will call - // data() to get the pointer and then fill it in. - bool allocate(size_t size); - // Get the data so it can be saved or used elsewhere. - // Note the client should not modify the pointer or memory. - const void* const data() const; - // Writeable data pointer. - void* data(); - - // This clears out the size, address, mode, etc. so the stream can be re-used, - // but does not free memory. - void clear(); - - // Standard stream access. - bool open(AccessMode mode); - void close(); - - //derived functions. - bool seek(s32 offset, Origin origin=ORIGIN_START) override; - size_t getLoc() override; - size_t getSize() override; - bool isOpen() const; - - void read(s8* ptr, u32 count=1) override { readType(ptr, count); } - void read(u8* ptr, u32 count=1) override { readType(ptr, count); } - void read(s16* ptr, u32 count=1) override { readType(ptr, count); } - void read(u16* ptr, u32 count=1) override { readType(ptr, count); } - void read(s32* ptr, u32 count=1) override { readType(ptr, count); } - void read(u32* ptr, u32 count=1) override { readType(ptr, count); } - void read(s64* ptr, u32 count=1) override { readType(ptr, count); } - void read(u64* ptr, u32 count=1) override { readType(ptr, count); } - void read(f32* ptr, u32 count=1) override { readType(ptr, count); } - void read(f64* ptr, u32 count=1) override { readType(ptr, count); } - void read(std::string* ptr, u32 count=1) override { readStringType(ptr, count); } - u32 readBuffer(void* ptr, u32 size, u32 count=1) override; - - void write(const s8* ptr, u32 count=1) override { writeType(ptr, count); } - void write(const u8* ptr, u32 count=1) override { writeType(ptr, count); } - void write(const s16* ptr, u32 count=1) override { writeType(ptr, count); } - void write(const u16* ptr, u32 count=1) override { writeType(ptr, count); } - void write(const s32* ptr, u32 count=1) override { writeType(ptr, count); } - void write(const u32* ptr, u32 count=1) override { writeType(ptr, count); } - void write(const s64* ptr, u32 count=1) override { writeType(ptr, count); } - void write(const u64* ptr, u32 count=1) override { writeType(ptr, count); } - void write(const f32* ptr, u32 count=1) override { writeType(ptr, count); } - void write(const f64* ptr, u32 count=1) override { writeType(ptr, count); } - void write(const std::string* ptr, u32 count=1) override { writeStringType(ptr, count); } - void writeBuffer(const void* ptr, u32 size, u32 count=1) override; - - void writeString(const char* fmt, ...) override; - -private: - template - void readType(T* ptr, u32 count) - { - readBuffer(ptr, sizeof(T), count); - } - - template - void writeType(const T* ptr, u32 count) - { - assert(m_memory); - writeBuffer(ptr, sizeof(T), count); - } - - void resizeBuffer(size_t newSize); - - void readStringType(std::string* ptr, u32 count); - void writeStringType(const std::string* ptr, u32 count); - - -private: - u8* m_memory; - size_t m_size; - size_t m_capacity; - size_t m_addr; - AccessMode m_mode; -}; \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_FileSystem/paths-posix.cpp b/components/darkforces/tfe/TFE_FileSystem/paths-posix.cpp deleted file mode 100644 index f3fb0ae6..00000000 --- a/components/darkforces/tfe/TFE_FileSystem/paths-posix.cpp +++ /dev/null @@ -1,339 +0,0 @@ -#include -#include -#include "paths.h" -#include "fileutil.h" -#include "filestream.h" -#include -#include -#include -#include -#include - -namespace TFE_Paths -{ - struct FileMapping - { - std::string fileName; - std::string realPath; - }; - - static std::string s_paths[PATH_COUNT]; - static std::deque s_localArchives; - static std::deque s_searchPaths; - static std::deque s_fileMappings; - static std::deque s_systemPaths; // TFE Support data paths - - void setPath(TFE_PathType pathType, const char* path) - { - s_paths[pathType] = path; - } - - - // Where to store TFE settings, saves, screenshots. - // If the envvar "TFE_DATA_HOME" is set, and it is - // an absolute path, then this path defines where TFE data - // is stored (without the usual "TheForceEngine" string added); - // if it is a relative path, then this path is used relative - // to the cwd; otherwise store in $HOME/.local/share// - static void setTFEPath(const char *tfe, u32 pathid) - { - char *home = getenv("HOME"), *tdh = getenv("TFE_DATA_HOME"); - char path[TFE_MAX_PATH], cwd[TFE_MAX_PATH]; - int i; - - if (!home || strlen(home) < 1) { - // whoa, how did that happen? - fprintf(stderr, "[Error] %s\n", "$HOME is undefined! Defaulting to /tmp"); - home = strdup("/tmp"); - } - - if (!tdh || strlen(tdh) < 1) { - snprintf(path, TFE_MAX_PATH, "%s/.local/share/%s/", home, tfe); - } else { - // remove trailing slashes in custom dir - i = strlen(tdh); - while ((i > 0) && (tdh[i - 1] == '/')) { - tdh[i - 1] = 0; - i--; - } - - // no, we don't touch root. Use the standard path. - if (tdh[0] == 0) { - snprintf(path, TFE_MAX_PATH, "%s/.local/share/%s/", home, tfe); - } else if (tdh[0] == '/') { - snprintf(path, TFE_MAX_PATH, "%s/", tdh); - } else { - FileUtil::getCurrentDirectory(cwd); - snprintf(path, TFE_MAX_PATH, "%s/%s/", cwd, tdh); - } - } - s_paths[pathid] = path; - FileUtil::makeDirectory(path); - } - - // System Paths: where all the support data is located, which is - // accessed mainly via relative paths. We look at, in this order: - // directory of executable - // /usr/local/share/ - // /usr/share/ - // $HOME/.local/share/ - // the above last because it is not touched when a new version - // is installed via e.g. package manager or 'make install', - // and user might end up with incompatible data causing hard - // to debug (non-)issues. - bool setProgramDataPath(const char *append) - { - std::string s; - - s_systemPaths.push_back(getPath(PATH_PROGRAM)); - s = std::string("/usr/local/share/") + append + "/"; - s_systemPaths.push_back(s); - s = std::string("/usr/share/") + append + "/"; - s_systemPaths.push_back(s); - setTFEPath(append, PATH_PROGRAM_DATA); - s_systemPaths.push_back(getPath(PATH_PROGRAM_DATA)); - - return true; - } - - bool setUserDocumentsPath(const char *append) - { - // ensure SetProgramDataPath() was called before - assert(!s_paths[PATH_PROGRAM_DATA].empty()); - - s_paths[PATH_USER_DOCUMENTS] = s_paths[PATH_PROGRAM_DATA]; - s_systemPaths.push_back(getPath(PATH_USER_DOCUMENTS)); - // set cwd to user documents path, because Dear ImGUI drops - // its ini file at the cwd, we don't want it to litter somewhere - // else. Also, unlike the windows version, we don't expect - // support data to reside at where the executable was launched - // from. - FileUtil::setCurrentDirectory(s_paths[PATH_USER_DOCUMENTS].c_str()); - return true; - } - - bool setProgramPath(void) - { - char p[TFE_MAX_PATH]; - memset(p, 0, TFE_MAX_PATH); - FileUtil::getCurrentDirectory(p); - s_paths[PATH_PROGRAM] = p; - s_paths[PATH_PROGRAM] += "/"; - return true; - } - - const char* getPath(TFE_PathType pathType) - { - return s_paths[pathType].c_str(); - } - - bool hasPath(TFE_PathType pathType) - { - return !s_paths[pathType].empty(); - } - - void appendPath(TFE_PathType pathType, const char *filename, char *path, size_t bufferLen/* = TFE_MAX_PATH*/) - { - snprintf(path, bufferLen, "%s%s", getPath(pathType), filename); - } - - void fixupPathAsDirectory(char *fullPath) - { - char *c = fullPath; - int len = strlen(fullPath); - - while (NULL != (c = strchr(c, '\\'))) { - *c = '/'; - } - - // Make sure it ends with a slash. - if (fullPath[len - 1] != '/') - { - fullPath[len] = '/'; - fullPath[len + 1] = 0; - } - } - - // take a relative input filepath, try to find it anywhere in the - // system paths, and return an absolute path to the file if found. - // report whether a change was made to the input. - bool mapSystemPath(char *fname) - { - char fullname[TFE_MAX_PATH]; - for (auto it = s_systemPaths.begin(); it != s_systemPaths.end(); it++) { - sprintf(fullname, "%s%s", it->c_str(), fname); - if (FileUtil::existsNoCase(fullname)) { - strncpy(fname, fullname, TFE_MAX_PATH); - return true; - } - } - return false; - } - - void addSearchPath(const char *fullPath) - { - char workpath[TFE_MAX_PATH]; - - if (!FileUtil::directoryExits(fullPath, workpath)) - return; - - for (auto it = s_searchPaths.begin(); it != s_searchPaths.end(); it++) - { - // If the path already exists, then don't add it again. - if (!strcasecmp(it->c_str(), workpath)) - { - return; - } - } - s_searchPaths.push_back(workpath); - } - - void addSearchPathToHead(const char *fullPath) - { - char workpath[TFE_MAX_PATH]; - - if (!FileUtil::directoryExits(fullPath, workpath)) - return; - - for (auto it = s_searchPaths.begin(); it != s_searchPaths.end(); it++) - { - // If the path already exists, then don't add it again. - if (!strcasecmp(it->c_str(), workpath)) - { - return; - } - } - s_searchPaths.push_front(workpath); - } - - void clearSearchPaths(void) - { - s_searchPaths.clear(); - s_fileMappings.clear(); - } - - void clearLocalArchives(void) - { - std::for_each(s_localArchives.begin(), s_localArchives.end(), - [](Archive *a) { Archive::freeArchive(a); }); - s_localArchives.clear(); - } - - // Add a single file that can be referenced by 'fileName' even though the real name may be different. - void addSingleFilePath(const char *fileName, const char *filePath) - { - char fileNameLC[TFE_MAX_PATH]; - strcpy(fileNameLC, fileName); - __strlwr(fileNameLC); - - char filePathFixed[TFE_MAX_PATH]; - strcpy(filePathFixed, filePath); - FileUtil::fixupPath(filePathFixed); - - FileMapping mapping = { fileNameLC, filePathFixed }; - s_fileMappings.push_back(mapping); - } - - void addLocalSearchPath(const char *locpath) - { - char p[TFE_MAX_PATH]; - snprintf(p, TFE_MAX_PATH, "%s%s", getPath(PATH_SOURCE_DATA), locpath); - fixupPathAsDirectory(p); - - addSearchPath(p); - } - - void addAbsoluteSearchPathToHead(const char *abspath) - { - char p[TFE_MAX_PATH]; - strcpy(p, abspath); - fixupPathAsDirectory(p); - - addSearchPathToHead(p); - } - - void addAbsoluteSearchPath(const char *abspath) - { - char p[TFE_MAX_PATH]; - strcpy(p, abspath); - fixupPathAsDirectory(p); - - addSearchPath(p); - } - - void addLocalArchiveToFront(Archive *a) - { - s_localArchives.push_front(a); - } - - void removeFirstArchive(void) - { - s_localArchives.pop_front(); - } - - void addLocalArchive(Archive *a) - { - s_localArchives.push_back(a); - } - - void removeLastArchive(void) - { - s_localArchives.pop_back(); - } - - bool getFilePath(const char *fileName, FilePath *outPath) - { - char fullname[TFE_MAX_PATH]; - - outPath->archive = nullptr; - outPath->index = INVALID_FILE; - outPath->path[0] = 0; - - // Search for any filemappings. - // This is usually only used with mods and usually limited to 0-3 files. - for (auto it = s_fileMappings.begin(); it != s_fileMappings.end(); it++) { - if (0 == strcasecmp(it->fileName.c_str(), fileName)) { - strcpy(outPath->path, it->realPath.c_str()); - return true; - } - } - - // Search in the local search paths before local archives: s_searchPaths. - for (auto it = s_searchPaths.begin(); it != s_searchPaths.end(); it++) { - sprintf(fullname, "%s%s", it->c_str(), fileName); - if (FileUtil::existsNoCase(fullname)) { - strncpy(outPath->path, fullname, TFE_MAX_PATH); - return true; - } - } - - // Then archives: s_localArchives. - for (auto it = s_localArchives.begin(); it != s_localArchives.end(); it++) { - u32 index = (*it)->getFileIndex(fileName); - if (index != INVALID_FILE) { - outPath->archive = *it; - outPath->index = index; - return true; - } - } - - // Finally admit defeat. - return false; - } -} - -#ifdef TFE_ESPBOX -// Shutdown only: release this file's cached container storage so nothing is -// left in the 4MB ROM block when the session ends (see esp_alloc.cpp). -#include "esp_platform.h" -void espbox_release_paths_caches() -{ - // An empty deque still allocates its map: keep that on the PSRAM heap. - TFE_Memory::DfHeapScope heapScope; - for (auto& path : TFE_Paths::s_paths) { std::string().swap(path); } - std::deque().swap(TFE_Paths::s_localArchives); - std::deque().swap(TFE_Paths::s_searchPaths); - std::deque().swap(TFE_Paths::s_fileMappings); - std::deque().swap(TFE_Paths::s_systemPaths); -} -#endif diff --git a/components/darkforces/tfe/TFE_FileSystem/paths.h b/components/darkforces/tfe/TFE_FileSystem/paths.h deleted file mode 100644 index 809fa8ef..00000000 --- a/components/darkforces/tfe/TFE_FileSystem/paths.h +++ /dev/null @@ -1,59 +0,0 @@ -#pragma once -#include - -enum TFE_PathType -{ - PATH_PROGRAM = 0, // Program folder - PATH_PROGRAM_DATA, // ProgramData/ on Windows - save temporary or cached data here. - PATH_USER_DOCUMENTS, // Users/username/Documents/ on Windows - save settings here. - PATH_SOURCE_DATA, // This is the location of the source data, such as maps, textures, etc. - PATH_EMULATOR, // Path to the dosbox exe (for the editor). - PATH_MOD, // Use this to reference mods. - PATH_COUNT -}; - -// Use an extended MAX_PATH, the Windows value is actually too small for some valid paths. -#define TFE_MAX_PATH 1024 - -class Archive; - -struct FilePath -{ - Archive* archive; // archive pointer. - u32 index; // file index into an archive or INVALID_FILE. - char path[TFE_MAX_PATH]; // path string. -}; - -namespace TFE_Paths -{ - // Paths, such as the source data or mods. - void setPath(TFE_PathType pathType, const char* path); - - // Platform specific user data path. - bool setProgramDataPath(const char* append); - bool setUserDocumentsPath(const char* append); - // Platform specific executable path. - bool setProgramPath(); - // find a relative path in a TFE system directory. true if mapping was done. - bool mapSystemPath(char *path); - - const char* getPath(TFE_PathType pathType); - bool hasPath(TFE_PathType pathType); - void appendPath(TFE_PathType pathType, const char* filename, char* path, size_t bufferLen = TFE_MAX_PATH); - void fixupPathAsDirectory(char* fullPath); - - void clearSearchPaths(); - void clearLocalArchives(); - - void addLocalSearchPath(const char* localSearchPath); - void addAbsoluteSearchPath(const char* absoluteSearchPath); - void addAbsoluteSearchPathToHead(const char* absoluteSearchPath); - void addLocalArchive(Archive* archive); - void removeLastArchive(); - void addLocalArchiveToFront(Archive* archive); - void removeFirstArchive(); - bool getFilePath(const char* fileName, FilePath* path); - - // Add a single file that can be referenced by 'fileName' even though the real name may be different. - void addSingleFilePath(const char* fileName, const char* filePath); -} diff --git a/components/darkforces/tfe/TFE_FileSystem/stream.h b/components/darkforces/tfe/TFE_FileSystem/stream.h deleted file mode 100644 index 403ac4a2..00000000 --- a/components/darkforces/tfe/TFE_FileSystem/stream.h +++ /dev/null @@ -1,60 +0,0 @@ -#pragma once -#include -#include -#include - -class Stream -{ -public: - enum Origin - { - ORIGIN_START = 0, - ORIGIN_END, - ORIGIN_CURRENT, - ORIGIN_COUNT - }; - - enum AccessMode - { - MODE_READ = 0, //read-only (will fail if the file doesn't exist) - MODE_WRITE, //write (will overwrite the file) - MODE_READWRITE, //read-write (will create a new file if it doesn't exist, the file can be read from and written to). - MODE_COUNT, - MODE_INVALID = MODE_COUNT - }; -public: - Stream() {}; - ~Stream() {}; - - virtual bool seek(s32 offset, Origin origin=ORIGIN_START)=0; - virtual size_t getLoc()=0; - virtual size_t getSize()=0; - - virtual void read(s8* ptr, u32 count=1)=0; - virtual void read(u8* ptr, u32 count=1)=0; - virtual void read(s16* ptr, u32 count=1)=0; - virtual void read(u16* ptr, u32 count=1)=0; - virtual void read(s32* ptr, u32 count=1)=0; - virtual void read(u32* ptr, u32 count=1)=0; - virtual void read(s64* ptr, u32 count=1)=0; - virtual void read(u64* ptr, u32 count=1)=0; - virtual void read(f32* ptr, u32 count=1)=0; - virtual void read(f64* ptr, u32 count=1)=0; - virtual void read(std::string* ptr, u32 count=1)=0; - virtual u32 readBuffer(void* ptr, u32 size, u32 count=1)=0; - - virtual void write(const s8* ptr, u32 count=1)=0; - virtual void write(const u8* ptr, u32 count=1)=0; - virtual void write(const s16* ptr, u32 count=1)=0; - virtual void write(const u16* ptr, u32 count=1)=0; - virtual void write(const s32* ptr, u32 count=1)=0; - virtual void write(const u32* ptr, u32 count=1)=0; - virtual void write(const s64* ptr, u32 count=1)=0; - virtual void write(const u64* ptr, u32 count=1)=0; - virtual void write(const f32* ptr, u32 count=1)=0; - virtual void write(const f64* ptr, u32 count=1)=0; - virtual void write(const std::string* ptr, u32 count=1)=0; - virtual void writeBuffer(const void* ptr, u32 size, u32 count=1)=0; - - virtual void writeString(const char* fmt, ...)=0; -}; \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_FrontEndUI/console.h b/components/darkforces/tfe/TFE_FrontEndUI/console.h deleted file mode 100644 index d5741cd6..00000000 --- a/components/darkforces/tfe/TFE_FrontEndUI/console.h +++ /dev/null @@ -1,138 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Editor -// A system built to view and edit Dark Forces data files. -// The viewing aspect needs to be put in place at the beginning -// in order to properly test elements in isolation without having -// to "play" the game as intended. -////////////////////////////////////////////////////////////////////// - -#include -#include -#include -#include - -enum CVarFlag -{ - CVFLAG_NONE = 0, - CVFLAG_READ_ONLY = (1 << 0), - CVFLAG_DO_NOT_SERIALIZE = (1 << 1), -}; - -#define CVAR_INT(var, name, flags, help) TFE_Console::registerCVarInt(name, flags, &var, help) -#define CVAR_FLOAT(var, name, flags, help) TFE_Console::registerCVarFloat(name, flags, &var, help) -#define CVAR_BOOL(var, name, flags, help) TFE_Console::registerCVarBool(name, flags, &var, help) -#define CVAR_STRING(var, name, flags, help) TFE_Console::registerCVarString(name, flags, var, sizeof(var), help) - -// Register a basic command -#define CCMD(name, func, argCount, help) TFE_Console::registerCommand(name, func, argCount, help) -// Register a command that is not repeated in the output (such as echo). -#define CCMD_NOREPEAT(name, func, argCount, help) TFE_Console::registerCommand(name, func, argCount, help, false) - -typedef std::vector ConsoleArgList; - -namespace TFE_Console -{ - enum CVarType - { - CVAR_INT = 0, - CVAR_FLOAT, - CVAR_BOOL, - CVAR_STRING, - }; - - struct CValue - { - union - { - s32* valueInt; - f32* valueFloat; - bool* valueBool; - char* valueString; - void* valuePtr; - }; - }; - - struct CVar - { - std::string name; - std::string helpString; - CVarType type; - u32 flags = 0; - u32 maxLen = 0; - union - { - s32* valueInt; - f32* valueFloat; - bool* valueBool; - char* valueString; - void* valuePtr; - }; - - // default value (in case CVars are reset). - union - { - s32 defaultInt; - f32 defaultFlt; - bool defaultBool; - }; - std::string defaultString; - - // serialized value. - union - { - s32 serializedInt; - f32 serializedFlt; - bool serializedBool; - }; - std::string serializedString; - }; - - typedef void(*ConsoleFunc)(const std::vector& args); - - void registerCVarInt(const char* name, u32 flags, s32* var, const char* helpString); - void registerCVarFloat(const char* name, u32 flags, f32* var, const char* helpString); - void registerCVarBool(const char* name, u32 flags, bool* var, const char* helpString); - void registerCVarString(const char* name, u32 flags, char* var, u32 maxLen, const char* helpString); - void registerCommand(const char* name, ConsoleFunc func, u32 argCount, const char* helpString, bool repeat = true); - - void addSerializedCVarInt(const char* name, s32 value); - void addSerializedCVarFloat(const char* name, f32 value); - void addSerializedCVarBool(const char* name, bool value); - void addSerializedCVarString(const char* name, const char* value); - - bool init(); - void destroy(); - - void update(); - bool isOpen(); - bool isAnimating(); - void startOpen(); - void startClose(); - - void addToHistory(const char* str); - - u32 getCVarCount(); - const CVar* getCVarByIndex(u32 index); - - inline f32 getFloatArg(const std::string& arg) - { - char* endPtr = nullptr; - return (f32)strtod(arg.c_str(), &endPtr); - } - - inline bool getBoolArg(const std::string& arg) - { - const char* cstr = arg.c_str(); - if (strcasecmp(cstr, "false") == 0 || strcasecmp(cstr, "0") == 0) - { - return false; - } - return true; - } - - inline const char* getStringArg(const std::string& arg) - { - return arg.c_str(); - } -} diff --git a/components/darkforces/tfe/TFE_FrontEndUI/editorTexture.h b/components/darkforces/tfe/TFE_FrontEndUI/editorTexture.h deleted file mode 100644 index 0b2ba1b7..00000000 --- a/components/darkforces/tfe/TFE_FrontEndUI/editorTexture.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Editor -// A system built to view and edit Dark Forces data files. -// The viewing aspect needs to be put in place at the beginning -// in order to properly test elements in isolation without having -// to "play" the game as intended. -////////////////////////////////////////////////////////////////////// - -#include -#include - -struct EditorTexture -{ - TextureGpu* texture = nullptr; - u32 width = 0; - u32 height = 0; - f32 rect[4]; - Vec2f scale = { 1.0f, 1.0f }; -}; -struct TextureData; - -namespace TFE_FrontEndUI -{ - bool convertPalette(const u8* srcPalette, u32* dstPalette); - void convertDfTextureToTrueColor(const TextureData* src, const u32* palette, u32* image); - bool createTexture(const TextureData* src, const u32* palette, EditorTexture* tex, MagFilter filter = MAG_FILTER_NONE); -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_FrontEndUI/frontEndUi.h b/components/darkforces/tfe/TFE_FrontEndUI/frontEndUi.h deleted file mode 100644 index 5c9306eb..00000000 --- a/components/darkforces/tfe/TFE_FrontEndUI/frontEndUi.h +++ /dev/null @@ -1,69 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Editor -// A system built to view and edit Dark Forces data files. -// The viewing aspect needs to be put in place at the beginning -// in order to properly test elements in isolation without having -// to "play" the game as intended. -////////////////////////////////////////////////////////////////////// - -#include - -enum AppState -{ - APP_STATE_MENU = 0, - APP_STATE_EDITOR, - APP_STATE_LOAD, - APP_STATE_GAME, - APP_STATE_QUIT, - APP_STATE_NO_GAME_DATA, - APP_STATE_CANNOT_RUN, - APP_STATE_EXIT_TO_MENU, - APP_STATE_SET_DEFAULTS, - APP_STATE_COUNT, - APP_STATE_UNINIT = APP_STATE_COUNT -}; - -struct ImFont; -struct IGame; - -namespace TFE_FrontEndUI -{ - void init(); - void initConsole(); - void shutdown(); - - AppState update(); - void draw(bool drawFrontEnd = true, bool noGameData = false, bool setDefaults = false, bool showFps = false); - void setCurrentGame(IGame* game); - - void setAppState(AppState state); - void enableConfigMenu(); - AppState menuReturn(); - void setMenuReturnState(AppState state); - bool toggleConsole(); - void exitToMenu(); - - bool shouldClearScreen(); - - bool isConfigMenuOpen(); - bool isConsoleOpen(); - bool isConsoleAnimating(); - void logToConsole(const char* str); - bool uiControlsEnabled(); - - char* getSelectedMod(); - void clearSelectedMod(); - void setSelectedMod(const char* mod); - void* getGradientTexture(); - void setState(AppState state); - void clearMenuState(); - void clearNoDataState(); - bool isNoDataMessageSet(); - ImFont* getDialogFont(); - - void setCanSave(bool canSave); - bool getCanSave(); - - void toggleProfilerView(); -} diff --git a/components/darkforces/tfe/TFE_FrontEndUI/modLoader.h b/components/darkforces/tfe/TFE_FrontEndUI/modLoader.h deleted file mode 100644 index fd328f6a..00000000 --- a/components/darkforces/tfe/TFE_FrontEndUI/modLoader.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Editor -// A system built to view and edit Dark Forces data files. -// The viewing aspect needs to be put in place at the beginning -// in order to properly test elements in isolation without having -// to "play" the game as intended. -////////////////////////////////////////////////////////////////////// - -#include - -namespace TFE_FrontEndUI -{ - enum ViewMode - { - VIEW_IMAGES = 0, - VIEW_NAME_LIST, - VIEW_FILE_LIST, - VIEW_COUNT - }; - - void modLoader_read(); - void modLoader_cleanupResources(); - bool modLoader_selectionUI(); - - ViewMode modLoader_getViewMode(); -} diff --git a/components/darkforces/tfe/TFE_FrontEndUI/profilerView.h b/components/darkforces/tfe/TFE_FrontEndUI/profilerView.h deleted file mode 100644 index ada786ab..00000000 --- a/components/darkforces/tfe/TFE_FrontEndUI/profilerView.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Editor -// A system built to view and edit Dark Forces data files. -// The viewing aspect needs to be put in place at the beginning -// in order to properly test elements in isolation without having -// to "play" the game as intended. -////////////////////////////////////////////////////////////////////// - -#include -#include -#include - -namespace TFE_ProfilerView -{ - bool init(); - void destroy(); - - void update(); - bool isEnabled(); - void enable(bool enable); -} diff --git a/components/darkforces/tfe/TFE_Game/igame.cpp b/components/darkforces/tfe/TFE_Game/igame.cpp deleted file mode 100644 index 9886fa91..00000000 --- a/components/darkforces/tfe/TFE_Game/igame.cpp +++ /dev/null @@ -1,87 +0,0 @@ -#include "igame.h" -#include -#include -#include - -enum GameConstants -{ - GAME_MEMORY_BASE = 8 * 1024 * 1024, // 8 MB - LEVEL_MEMORY_BASE = 8 * 1024 * 1024, // 8 MB - RES_MEMORY_BASE = 8 * 1024 * 1024, // 8 MB -}; - -using namespace TFE_Memory; -MemoryRegion* s_gameRegion = nullptr; -MemoryRegion* s_levelRegion = nullptr; - -void displayMemoryUsage(const ConsoleArgList& args) -{ - char res[256]; - size_t blockCount, blockSize; - region_getBlockInfo(s_gameRegion, &blockCount, &blockSize); - TFE_Console::addToHistory("-------------------------------------------------------------------"); - TFE_Console::addToHistory("Region | Memory Used | Current Capacity | Block Count | BlockSize"); - TFE_Console::addToHistory("-------------------------------------------------------------------"); - sprintf(res, "Game | %11zu | %16zu | %11zu | %9zu", region_getMemoryUsed(s_gameRegion), region_getMemoryCapacity(s_gameRegion), blockCount, blockSize); - TFE_Console::addToHistory(res); - - region_getBlockInfo(s_levelRegion, &blockCount, &blockSize); - sprintf(res, "Level | %11zu | %16zu | %11zu | %9zu", region_getMemoryUsed(s_levelRegion), region_getMemoryCapacity(s_levelRegion), blockCount, blockSize); - TFE_Console::addToHistory(res); - TFE_Console::addToHistory("-------------------------------------------------------------------"); -} - -void game_init() -{ - s_gameRegion = region_create("game", GAME_MEMORY_BASE); // Region for "permanent" game allocations. - s_levelRegion = region_create("level", LEVEL_MEMORY_BASE); // Region for "per-level" game allocations. - - CCMD("displayMemoryUsage", displayMemoryUsage, 0, "Display memory usage."); -} - -void game_destroy() -{ - region_destroy(s_gameRegion); - region_destroy(s_levelRegion); - - s_gameRegion = nullptr; - s_levelRegion = nullptr; -} - -void game_clearLevelData() -{ - region_clear(s_levelRegion); -} - -IGame* createGame(GameID id) -{ - IGame* game = nullptr; - switch (id) - { - case Game_Dark_Forces: - { - game = new TFE_DarkForces::DarkForces(); - } break; - case Game_Outlaws: - { - game = new TFE_Outlaws::Outlaws(); - } break; - } - if (game) - { - game->id = id; - } - - return game; -} - -void freeGame(IGame* game) -{ - if (game) - { - game->exitGame(); - delete game; - } - region_clear(s_gameRegion); - region_clear(s_levelRegion); -} diff --git a/components/darkforces/tfe/TFE_Game/igame.h b/components/darkforces/tfe/TFE_Game/igame.h deleted file mode 100644 index 8c2f3ebe..00000000 --- a/components/darkforces/tfe/TFE_Game/igame.h +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Game Level -// Manages the game while playing levels in first person. -// This holds one or more players, handles input updates, etc. -////////////////////////////////////////////////////////////////////// -#include -#include - -extern MemoryRegion* s_gameRegion; -extern MemoryRegion* s_levelRegion; - -#define game_alloc(size) TFE_Memory::region_alloc(s_gameRegion, size) -#define game_realloc(ptr, size) TFE_Memory::region_realloc(s_gameRegion, ptr, size) -#define game_free(ptr) TFE_Memory::region_free(s_gameRegion, ptr) - -#define level_alloc(size) TFE_Memory::region_alloc(s_levelRegion, size) -#define level_realloc(ptr, size) TFE_Memory::region_realloc(s_levelRegion, ptr, size) -#define level_free(ptr) TFE_Memory::region_free(s_levelRegion, ptr) - -struct IGame -{ - virtual bool runGame(s32 argCount, const char* argv[], Stream* stream) = 0; - virtual void exitGame() = 0; - virtual void pauseGame(bool pause) = 0; - virtual void pauseSound(bool pause) = 0; - virtual void restartMusic() = 0; - virtual void loopGame() {}; - virtual bool serializeGameState(Stream* stream, const char* filename, bool writeState) { return false; }; - virtual bool canSave() { return false; } - virtual bool isPaused() { return false; } - virtual void getLevelName(char* name) {}; - virtual void getModList(char* modList) {}; - - GameID id; -}; - -IGame* createGame(GameID id); -void freeGame(IGame* game); - -void game_init(); -void game_destroy(); diff --git a/components/darkforces/tfe/TFE_Game/reticle.h b/components/darkforces/tfe/TFE_Game/reticle.h deleted file mode 100644 index 0aa9be69..00000000 --- a/components/darkforces/tfe/TFE_Game/reticle.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Reticle Support -// Support that can be used by all games. -////////////////////////////////////////////////////////////////////// -#include -#include - -bool reticle_init(); -void reticle_destroy(); - -void reticle_enable(bool enable); -void reticle_setShape(u32 index); -void reticle_setColor(const f32* color); -void reticle_setScale(f32 scale); - -bool reticle_enabled(); -u32 reticle_getShape(); -u32 reticle_getShapeCount(); -void reticle_getColor(f32* color); -f32 reticle_getScale(); diff --git a/components/darkforces/tfe/TFE_Game/saveSystem.cpp b/components/darkforces/tfe/TFE_Game/saveSystem.cpp deleted file mode 100644 index 5b9e15af..00000000 --- a/components/darkforces/tfe/TFE_Game/saveSystem.cpp +++ /dev/null @@ -1,401 +0,0 @@ -#include "saveSystem.h" -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -using namespace TFE_Input; - -#ifdef TFE_ESPBOX -namespace TFE_Settings -{ - static const char* c_gameName[] = - { - "Dark Forces", - "Outlaws", - }; -} -#endif - -namespace TFE_SaveSystem -{ - enum SaveRequest - { - SF_REQ_NONE = 0, - SF_REQ_SAVE, - SF_REQ_LOAD, - }; - - enum SaveMasterVersion - { - SVER_INIT = 1, - SVER_CUR = SVER_INIT - }; - - static SaveRequest s_req = SF_REQ_NONE; -#ifdef TFE_ESPBOX - // TFE_MAX_PATH each (shared memory) - static char* s_reqFilename = nullptr; - static char* s_reqSavename = nullptr; - static char* s_gameSavePath = nullptr; -#else - static char s_reqFilename[TFE_MAX_PATH]; - static char s_reqSavename[TFE_MAX_PATH]; - static char s_gameSavePath[TFE_MAX_PATH]; -#endif - static IGame* s_game = nullptr; - static s32 s_saveDelay = 0; - - static u32* s_imageBuffer[2] = { nullptr, nullptr }; - static size_t s_imageBufferSize[2] = { 0 }; - - void saveHeader(Stream* stream, const char* saveName) - { - // Generate a screenshot. - DisplayInfo displayInfo; - TFE_RenderBackend::getDisplayInfo(&displayInfo); - size_t size = displayInfo.width * displayInfo.height * 4; - if (size > s_imageBufferSize[0]) - { - s_imageBuffer[0] = (u32*)realloc(s_imageBuffer[0], size); - s_imageBufferSize[0] = size; - } - TFE_RenderBackend::captureScreenToMemory(s_imageBuffer[0]); - - // Scale and crop the image to fit inside 426 x 240 (widescreen). - s64 scale = SAVE_IMAGE_HEIGHT * 65536 / displayInfo.height; - s64 invScale = displayInfo.height * 65536 / SAVE_IMAGE_HEIGHT; - s32 scaledWidth = s32((displayInfo.width * scale) >> 16ll); - s32 newWidth = SAVE_IMAGE_WIDTH, newHeight = SAVE_IMAGE_HEIGHT; - - s32 dstOffset = 0; - s64 srcOffset = 0; - if (scaledWidth < newWidth) - { - dstOffset = (newWidth - scaledWidth) / 2; - } - else if (scaledWidth > newWidth) - { - srcOffset = (scaledWidth - newWidth) / 2; - srcOffset = srcOffset * invScale; - } - - size_t newSize = newWidth * newHeight * 4; - if (newSize > s_imageBufferSize[1]) - { - s_imageBuffer[1] = (u32*)realloc(s_imageBuffer[1], newSize); - s_imageBufferSize[1] = newSize; - } - - const u32 *src; - u32* dst = s_imageBuffer[1]; - memset(dst, 0, newWidth * newHeight * 4); - - s64 u = srcOffset, v = 0; - s64 du = invScale, dv = invScale; - for (s32 y = 0; y < newHeight; y++, v += dv, dst += newWidth) - { - u = srcOffset; - src = &s_imageBuffer[0][(v >> 16ll) * displayInfo.width]; - for (s32 x = dstOffset; x < newWidth - dstOffset; x++, u += du) - { - dst[x] = src[u >> 16ll]; - } - } - - // Save to memory. - u8* png; - u32 pngSize = (u32)TFE_Image::writeImageToMemory(png, newWidth, newHeight, s_imageBuffer[1]); - - // Master version. - u32 version = SVER_CUR; - stream->write(&version); - - // Save Name. - size_t saveNameLen = strlen(saveName); - if (saveNameLen > SAVE_MAX_NAME_LEN - 1) { saveNameLen = SAVE_MAX_NAME_LEN - 1; } - u8 len = (u8)saveNameLen; - stream->write(&len); - stream->writeBuffer(saveName, len); - - // Time and Date of Save. - char timeDate[256]; - TFE_System::getDateTimeString(timeDate); - len = (u8)strlen(timeDate); - stream->write(&len); - stream->writeBuffer(timeDate, len); - - // Level Name - char levelName[256]; - s_game->getLevelName(levelName); - len = (u8)strlen(levelName); - stream->write(&len); - stream->writeBuffer(levelName, len); - - // Mod List - char modList[256]; - s_game->getModList(modList); - len = (u8)strlen(modList); - stream->write(&len); - stream->writeBuffer(modList, len); - - // Image. - stream->write(&pngSize); - stream->writeBuffer(png, pngSize); - } - - void loadHeader(Stream* stream, SaveHeader* header, const char* fileName) - { - // Master version. - u32 version; - stream->read(&version); - - // Save Name. - u8 len; - stream->read(&len); - stream->readBuffer(header->saveName, len); - header->saveName[len] = 0; - // Fix existing invalid save names. - header->saveName[SAVE_MAX_NAME_LEN - 1] = 0; - - // Handle the case when there is no save name. - if (header->saveName[0] == 0 || header->saveName[0] == ' ') - { - FileUtil::getFileNameFromPath(fileName, header->saveName); - } - - // Time and Date of Save. - stream->read(&len); - stream->readBuffer(header->dateTime, len); - header->dateTime[len] = 0; - - // Level Name - stream->read(&len); - stream->readBuffer(header->levelName, len); - header->levelName[len] = 0; - - // Mod List - stream->read(&len); - stream->readBuffer(header->modNames, len); - header->modNames[len] = 0; - - // Image, re-use buffer 0 for the PNG. - u32 pngSize; - stream->read(&pngSize); - if (pngSize > s_imageBufferSize[0]) - { - s_imageBuffer[0] = (u32*)realloc(s_imageBuffer[0], pngSize); - s_imageBufferSize[0] = pngSize; - } - stream->readBuffer(s_imageBuffer[0], pngSize); - - Image image = { 0 }; - image.data = header->imageData; - TFE_Image::readImageFromMemory(&image, pngSize, s_imageBuffer[0]); - assert(image.width == SAVE_IMAGE_WIDTH && image.height == SAVE_IMAGE_HEIGHT); - } - - void populateSaveDirectory(std::vector& dir) - { - dir.clear(); - FileList fileList; - FileUtil::readDirectory(s_gameSavePath, "tfe", fileList); - size_t saveCount = fileList.size(); - dir.resize(saveCount); - - const std::string* filenames = fileList.data(); - SaveHeader* headers = dir.data(); - for (size_t i = 0; i < saveCount; i++) - { - loadGameHeader(filenames[i].c_str(), &headers[i]); - } - } - - void init() - { - } - - void destroy() - { - for (s32 i = 0; i < 2; i++) - { - free(s_imageBuffer[i]); - s_imageBuffer[i] = nullptr; // TFE_ESPBOX: the save system is re-initialized on every launch. - s_imageBufferSize[i] = 0; - } - s_req = SF_REQ_NONE; - s_game = nullptr; - } - - bool saveGame(const char* filename, const char* saveName) - { - char filePath[TFE_MAX_PATH]; - if (filename[0] == '/') { strcpy(filePath, filename); } // TFE_ESPBOX: absolute path (emulator save slot) - else { sprintf(filePath, "%s%s", s_gameSavePath, filename); } - - bool ret = false; - FileStream stream; - if (stream.open(filePath, Stream::MODE_WRITE)) - { - saveHeader(&stream, saveName); - ret = s_game->serializeGameState(&stream, filename, true); - stream.close(); - } - return ret; - } - - bool loadGame(const char* filename) - { - char filePath[TFE_MAX_PATH]; - if (filename[0] == '/') { strcpy(filePath, filename); } // TFE_ESPBOX: absolute path (emulator save slot) - else { sprintf(filePath, "%s%s", s_gameSavePath, filename); } - - bool ret = false; - FileStream stream; - if (stream.open(filePath, Stream::MODE_READ)) - { - SaveHeader header; - loadHeader(&stream, &header, filename); - ret = s_game->serializeGameState(&stream, filename, false); - stream.close(); - } - return ret; - } - - bool loadGameHeader(const char* filename, SaveHeader* header) - { - char filePath[TFE_MAX_PATH]; - if (filename[0] == '/') { strcpy(filePath, filename); } // TFE_ESPBOX: absolute path (emulator save slot) - else { sprintf(filePath, "%s%s", s_gameSavePath, filename); } - - bool ret = false; - FileStream stream; - if (stream.open(filePath, Stream::MODE_READ)) - { - loadHeader(&stream, header, filename); - strcpy(header->fileName, filename); - stream.close(); - ret = true; - } - return ret; - } - - void postLoadRequest(const char* filename) - { - s_req = SF_REQ_LOAD; - strcpy(s_reqFilename, filename); - } - - void postSaveRequest(const char* filename, const char* saveName, s32 delay) - { - s_req = SF_REQ_SAVE; - strcpy(s_reqFilename, filename); - strcpy(s_reqSavename, saveName); - s_saveDelay = delay; - } - - const char* loadRequestFilename() - { - if (s_req == SF_REQ_LOAD) - { - s_req = SF_REQ_NONE; - return s_reqFilename; - } - return nullptr; - } - - const char* saveRequestFilename() - { - if (s_req == SF_REQ_SAVE && s_saveDelay <= 0) - { - s_req = SF_REQ_NONE; - return s_reqFilename; - } - if (s_saveDelay > 0) { s_saveDelay--; } - return nullptr; - } - - void getSaveFilenameFromIndex(s32 index, char* name) - { - if (index == 0) - { - strcpy(name, c_quickSaveName); - } - else - { - sprintf(name, "save%03d.tfe", index - 1); - } - } - - void setCurrentGame(GameID id) - { - char relativeBasePath[TFE_MAX_PATH]; - TFE_Paths::appendPath(PATH_USER_DOCUMENTS, "Saves/", relativeBasePath); -#ifdef TFE_ESPBOX - if (!FileUtil::directoryExits(relativeBasePath)) -#else - if (!FileUtil::directoryExits(s_gameSavePath)) -#endif - { - FileUtil::makeDirectory(relativeBasePath); - } - - char relativePath[TFE_MAX_PATH]; - sprintf(relativePath, "Saves/%s/", TFE_Settings::c_gameName[id]); - - TFE_Paths::appendPath(PATH_USER_DOCUMENTS, relativePath, s_gameSavePath); - if (!FileUtil::directoryExits(s_gameSavePath)) - { - FileUtil::makeDirectory(s_gameSavePath); - } - } - - void setCurrentGame(IGame* game) - { - s_game = game; - setCurrentGame(game->id); - } - - void update() - { - if (!s_game) { return; } - - static s32 lastState = 0; - const char* saveFilename = saveRequestFilename(); - - bool canSave = !lastState && s_game->canSave(); - if (saveFilename && canSave) - { - saveGame(saveFilename, s_reqSavename); - lastState = 1; - } - else if (inputMapping_getActionState(IAS_QUICK_SAVE) == STATE_PRESSED && canSave) - { - saveGame(c_quickSaveName, "Quicksave"); - lastState = 1; - } - else if (inputMapping_getActionState(IAS_QUICK_LOAD) == STATE_PRESSED && !lastState) - { - postLoadRequest(c_quickSaveName); - lastState = 1; - } - else - { - lastState = 0; - } - } -} -#ifdef TFE_ESPBOX -void espbox_shared_saveSystem(bool alloc) -{ - ESPBOX_SHARED_ALLOC(TFE_SaveSystem::s_reqFilename, TFE_MAX_PATH); - ESPBOX_SHARED_ALLOC(TFE_SaveSystem::s_reqSavename, TFE_MAX_PATH); - ESPBOX_SHARED_ALLOC(TFE_SaveSystem::s_gameSavePath, TFE_MAX_PATH); -} -#endif diff --git a/components/darkforces/tfe/TFE_Game/saveSystem.h b/components/darkforces/tfe/TFE_Game/saveSystem.h deleted file mode 100644 index 4420c996..00000000 --- a/components/darkforces/tfe/TFE_Game/saveSystem.h +++ /dev/null @@ -1,51 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Shared save/load functionality used by all games. -////////////////////////////////////////////////////////////////////// -#include "igame.h" -#include - -namespace TFE_SaveSystem -{ - static const char* c_quickSaveName = "quicksave.tfe"; - enum SaveSystemConst - { - SAVE_MAX_NAME_LEN = 64, -#ifdef TFE_ESPBOX - SAVE_IMAGE_WIDTH = 4, - SAVE_IMAGE_HEIGHT = 4, -#else - SAVE_IMAGE_WIDTH = 426, - SAVE_IMAGE_HEIGHT = 240, -#endif - }; - struct SaveHeader - { - char fileName[256]; - char saveName[SAVE_MAX_NAME_LEN]; - char dateTime[256]; - char levelName[256]; - char modNames[256]; - u32 imageData[SAVE_IMAGE_WIDTH * SAVE_IMAGE_HEIGHT]; - }; - - void init(); - void destroy(); - - void setCurrentGame(IGame* game); - void setCurrentGame(GameID id); - void update(); - bool saveGame(const char* filename, const char* saveName); - bool loadGame(const char* filename); - // Load only the header for UI. - bool loadGameHeader(const char* filename, SaveHeader* header); - - void postLoadRequest(const char* filename); - void postSaveRequest(const char* filename, const char* saveName, s32 delay = 0); - const char* loadRequestFilename(); - const char* saveRequestFilename(); - - void getSaveFilenameFromIndex(s32 index, char* name); - - void populateSaveDirectory(std::vector& dir); -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Input/input.cpp b/components/darkforces/tfe/TFE_Input/input.cpp deleted file mode 100644 index 5464a62c..00000000 --- a/components/darkforces/tfe/TFE_Input/input.cpp +++ /dev/null @@ -1,488 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -namespace TFE_Input -{ - #define BUFFERED_TEXT_LEN 64 - - //////////////////////////////////////////////////////// - // Input State - //////////////////////////////////////////////////////// - f32 s_axis[AXIS_COUNT] = { 0 }; - u8 s_buttonDown[CONTROLLER_BUTTON_COUNT] = { 0 }; - u8 s_buttonPressed[CONTROLLER_BUTTON_COUNT] = { 0 }; - - u8 s_keyDown[KEY_COUNT] = { 0 }; - u8 s_keyPressed[KEY_COUNT] = { 0 }; - - char s_bufferedText[BUFFERED_TEXT_LEN]; - u8 s_bufferedKey[KEY_COUNT]; - - u8 s_mouseDown[MBUTTON_COUNT] = { 0 }; - u8 s_mousePressed[MBUTTON_COUNT] = { 0 }; - - s32 s_mouseWheel[2] = { 0 }; - s32 s_mouseMove[2] = { 0 }; - s32 s_mouseMoveAccum[2] = { 0 }; - s32 s_mousePos[2] = { 0 }; - - bool s_relativeMode = false; - - static const char* const* s_controllerAxisNames; - static const char* const* s_controllerButtonNames; - static const char* const* s_mouseAxisNames; - static const char* const* s_mouseButtonNames; - static const char* const* s_mouseWheelNames; - static const char* const* s_keyboardNames; - - const char* c_keyModNames[] = - { - "", // KEYMOD_NONE = 0, - "ALT", // KEYMOD_ALT, - "CTRL", // KEYMOD_CTRL, - "SHIFT", // KEYMOD_SHIFT, - }; - - //////////////////////////////////////////////////////// - // Implementation - //////////////////////////////////////////////////////// - void endFrame() - { - s_mouseWheel[0] = 0; - s_mouseWheel[1] = 0; - memset(s_buttonPressed, 0, CONTROLLER_BUTTON_COUNT); - memset(s_mousePressed, 0, MBUTTON_COUNT); - memset(s_keyPressed, 0, KEY_COUNT); - memset(s_bufferedKey, 0, KEY_COUNT); - memset(s_bufferedText, 0, BUFFERED_TEXT_LEN); - } - - // Set, from the OS - void setAxis(Axis axis, f32 value) - { - s_axis[axis] = value; - } - - void setButtonDown(Button button) - { - if (!s_buttonDown[button]) - { - s_buttonPressed[button] = 1; - } - s_buttonDown[button] = 1; - } - - void setButtonUp(Button button) - { - s_buttonDown[button] = 0; - } - - void setKeyDown(KeyboardCode key) - { - if (!s_keyDown[key]) - { - s_keyPressed[key] = 1; - } - s_keyDown[key] = 1; - } - - void setKeyUp(KeyboardCode key) - { - s_keyDown[key] = 0; - } - - void setMouseButtonDown(MouseButton button) - { - if (!s_mouseDown[button]) - { - s_mousePressed[button] = 1; - } - s_mouseDown[button] = 1; - } - - void setMouseButtonUp(MouseButton button) - { - s_mouseDown[button] = 0; - } - - void setMouseWheel(s32 dx, s32 dy) - { - s_mouseWheel[0] = dx; - s_mouseWheel[1] = dy; - } - - void setRelativeMousePos(s32 x, s32 y) - { - s_mouseMove[0] = x; - s_mouseMove[1] = y; - s_mouseMoveAccum[0] += x; - s_mouseMoveAccum[1] += y; - } - - void setMousePos(s32 x, s32 y) - { - s_mousePos[0] = x; - s_mousePos[1] = y; - } - - void enableRelativeMode(bool enable) - { - s_relativeMode = enable; - } - - // Buffered Input - void setBufferedInput(const char* text) - { - strcpy(s_bufferedText, text); - } - -#ifdef TFE_ESPBOX - void setBufferedChar(char ch) - { - s_bufferedText[0] = ch; - s_bufferedText[1] = 0; - } -#endif - - void setBufferedKey(KeyboardCode key) - { - s_bufferedKey[key] = 1; - } - - // Get - f32 getAxis(Axis axis) - { - return s_axis[axis]; - } - - void getMouseWheel(s32* dx, s32* dy) - { - assert(dx && dy); - - *dx = s_mouseWheel[0]; - *dy = s_mouseWheel[1]; - } - - void getMouseMove(s32* x, s32* y) - { - assert(x && y); - - *x = s_mouseMove[0]; - *y = s_mouseMove[1]; - } - - void getAccumulatedMouseMove(s32* x, s32* y) - { - assert(x && y); - - *x = s_mouseMoveAccum[0]; - *y = s_mouseMoveAccum[1]; - - s_mouseMoveAccum[0] = 0; - s_mouseMoveAccum[1] = 0; - } - - void clearAccumulatedMouseMove() - { - s_mouseMoveAccum[0] = 0; - s_mouseMoveAccum[1] = 0; - } - - void getMousePos(s32* x, s32* y) - { - assert(x && y); - - *x = s_mousePos[0]; - *y = s_mousePos[1]; - } - - bool buttonDown(Button button) - { - return s_buttonDown[button] != 0; - } - - bool buttonPressed(Button button) - { - return s_buttonPressed[button] != 0; - } - - bool keyDown(KeyboardCode key) - { - return s_keyDown[key] != 0; - } - - bool keyPressed(KeyboardCode key) - { - return s_keyPressed[key] != 0; - } - - void clearKeyPressed(KeyboardCode key) - { - s_keyPressed[key] = 0; - } - - KeyboardCode getKeyPressed() - { - for (s32 i = 0; i < KEY_COUNT; i++) - { - if (s_keyPressed[i]) - { - return KeyboardCode(i); - } - } - return KEY_UNKNOWN; - } - - Button getControllerButtonPressed() - { - for (s32 i = 0; i < CONTROLLER_BUTTON_COUNT; i++) - { - if (s_buttonPressed[i]) - { - return Button(i); - } - } - return CONTROLLER_BUTTON_UNKNOWN; - } - - Axis getControllerAnalogDown() - { - if (fabsf(s_axis[AXIS_RIGHT_TRIGGER]) > 0.5f) - { - return AXIS_RIGHT_TRIGGER; - } - else if (fabsf(s_axis[AXIS_LEFT_TRIGGER]) > 0.5f) - { - return AXIS_LEFT_TRIGGER; - } - return AXIS_UNKNOWN; - } - - MouseButton getMouseButtonPressed() - { - for (s32 i = 0; i < MBUTTON_COUNT; i++) - { - if (s_mousePressed[i]) - { - return MouseButton(i); - } - } - return MBUTTON_UNKNOWN; - } - - KeyModifier getKeyModifierDown() - { - if (keyDown(KEY_LALT) || keyDown(KEY_RALT)) - { - return KEYMOD_ALT; - } - else if (keyDown(KEY_LCTRL) || keyDown(KEY_RCTRL)) - { - return KEYMOD_CTRL; - } - else if (keyDown(KEY_LSHIFT) || keyDown(KEY_RSHIFT)) - { - return KEYMOD_SHIFT; - } - return KEYMOD_NONE; - } - - bool keyModDown(KeyModifier keyMod, bool allowAltOnNone) - { - switch (keyMod) - { - case KEYMOD_NONE: - { - return allowAltOnNone || (!keyDown(KEY_LALT) && !keyDown(KEY_RALT)); - } break; - case KEYMOD_ALT: - { - return keyDown(KEY_LALT) || keyDown(KEY_RALT); - } break; - case KEYMOD_CTRL: - { - return keyDown(KEY_LCTRL) || keyDown(KEY_RCTRL); - } break; - case KEYMOD_SHIFT: - { - return keyDown(KEY_LSHIFT) || keyDown(KEY_RSHIFT); - } break; - } - assert(0); // Invalid keymod. - return false; - } - - bool mouseDown(MouseButton button) - { - return s_mouseDown[button] != 0; - } - - bool mousePressed(MouseButton button) - { - return s_mousePressed[button] != 0; - } - - bool relativeModeEnabled() - { - return s_relativeMode; - } - - // Buffered Input - const char* getBufferedText() - { - return s_bufferedText; - } - - bool bufferedKeyDown(KeyboardCode key) - { - return s_bufferedKey[key]; - } - - bool loadKeyNames(const char* path) - { - FileStream file; - if (!file.open(path, Stream::MODE_READ)) - { - return false; - } - - // Read the file into memory. - const size_t len = file.getSize(); - char* contents = new char[len+1]; - if (!contents) - { - file.close(); - return false; - } - file.readBuffer(contents, (u32)len); - file.close(); - - TFE_Parser parser; - parser.init(contents, len); - parser.addCommentString(";"); - parser.addCommentString("#"); - parser.addCommentString("//"); - - size_t bufferPos = 0; - enum KeySection - { - Unknown = 0, - ControllerAxis, - ControllerButtons, - MouseAxis, - MouseButtons, - MouseWheelAxis, - Keyboard, - }; - - KeySection section = Unknown; - char** curList = nullptr; - while (bufferPos < len) - { - const char* line = parser.readLine(bufferPos); - if (!line) { break; } - - TokenList tokens; - parser.tokenizeLine(line, tokens); - if (tokens.size() < 1) { continue; } - const char* item = tokens[0].c_str(); - - if (strcasecmp(item, "[ControllerAxis]") == 0) - { - section = ControllerAxis; - s_controllerAxisNames = new const char*[AXIS_COUNT]; - curList = (char**)s_controllerAxisNames; - } - else if (strcasecmp(item, "[ControllerButtons]") == 0) - { - section = ControllerButtons; - s_controllerButtonNames = new const char*[CONTROLLER_BUTTON_COUNT]; - curList = (char**)s_controllerButtonNames; - } - else if (strcasecmp(item, "[MouseAxis]") == 0) - { - section = MouseAxis; - s_mouseAxisNames = new const char*[MOUSE_AXIS_COUNT]; - curList = (char**)s_mouseAxisNames; - } - else if (strcasecmp(item, "[MouseButtons]") == 0) - { - section = MouseButtons; - s_mouseButtonNames = new const char*[MBUTTON_COUNT]; - curList = (char**)s_mouseButtonNames; - } - else if (strcasecmp(item, "[MouseWheel]") == 0) - { - section = MouseWheelAxis; - s_mouseWheelNames = new const char*[MOUSEWHEEL_COUNT]; - curList = (char**)s_mouseWheelNames; - } - else if (strcasecmp(item, "[Keyboard]") == 0) - { - section = Keyboard; - s_keyboardNames = new const char*[KEY_LAST + 2]; - curList = (char**)s_keyboardNames; - } - else if (section == Unknown) - { - TFE_System::logWrite(LOG_ERROR, "Input", "Cannot parse Key Name lists '%s'", path); - delete[] contents; - return false; - } - else - { - *curList = new char[strlen(item) + 1]; - strcpy(*curList, item); - curList++; - } - }; - - delete[] contents; - return true; - } - - const char* getControllerAxisName(Axis axis) - { - return s_controllerAxisNames ? s_controllerAxisNames[axis] : ""; - } - - const char* getControllButtonName(Button button) - { - return s_controllerButtonNames ? s_controllerButtonNames[button] : ""; - } - - const char* getMouseAxisName(MouseAxis axis) - { - return s_mouseAxisNames ? s_mouseAxisNames[axis] : ""; - } - - const char* getMouseButtonName(MouseButton button) - { - return s_mouseButtonNames ? s_mouseButtonNames[button] : ""; - } - - const char* getMouseWheelName(MouseWheel axis) - { - return s_mouseWheelNames ? s_mouseWheelNames[axis] : ""; - } - - const char* getKeyboardName(KeyboardCode key) - { - if (key > KEY_LAST && s_controllerAxisNames) - { - return s_keyboardNames[KEY_LAST]; - } - - return s_keyboardNames ? s_keyboardNames[key] : ""; - } - - const char* getKeyboardModifierName(KeyModifier mod) - { - return c_keyModNames[mod]; - } -} diff --git a/components/darkforces/tfe/TFE_Input/input.h b/components/darkforces/tfe/TFE_Input/input.h deleted file mode 100644 index 2bbe2edc..00000000 --- a/components/darkforces/tfe/TFE_Input/input.h +++ /dev/null @@ -1,81 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Input Library -// A unified input repository that can be accessed by different -// systems. MAIN updates the raw input and this system organizes the -// data to make it easy for other systems to access. -// -// Due to the global access of the low level input, this is a -// namespace rather than a static class or "singleton" -////////////////////////////////////////////////////////////////////// - -#include -#include - -typedef void(*KeyBindingCallback)(f32 value); - -namespace TFE_Input -{ - // Call this once at the end of each frame - // to reset transient key events. - void endFrame(); - - // Set, from the OS - void setAxis(Axis axis, f32 value); - void setButtonDown(Button button); - void setButtonUp(Button button); - - void setKeyDown(KeyboardCode key); - void setKeyUp(KeyboardCode key); - - void setMouseButtonDown(MouseButton button); - void setMouseButtonUp(MouseButton button); - void setMouseWheel(s32 dx, s32 dy); - - void setRelativeMousePos(s32 x, s32 y); - void setMousePos(s32 x, s32 y); - - void enableRelativeMode(bool enable); - - // Buffered Input - void setBufferedInput(const char* text); -#ifdef TFE_ESPBOX - void setBufferedChar(char ch); -#endif - void setBufferedKey(KeyboardCode key); - - // Get - f32 getAxis(Axis axis); - void getMouseMove(s32* x, s32* y); - void getAccumulatedMouseMove(s32* x, s32* y); - void getMousePos(s32* x, s32* y); - void getMouseWheel(s32* dx, s32* dy); - bool buttonDown(Button button); - bool buttonPressed(Button button); - bool keyDown(KeyboardCode key); - bool keyPressed(KeyboardCode key); - bool keyModDown(KeyModifier keyMod, bool allowAltOnNone = false); - bool mouseDown(MouseButton button); - bool mousePressed(MouseButton button); - bool relativeModeEnabled(); - void clearKeyPressed(KeyboardCode key); - void clearAccumulatedMouseMove(); - // Buffered Input - const char* getBufferedText(); - bool bufferedKeyDown(KeyboardCode key); - - KeyboardCode getKeyPressed(); - KeyModifier getKeyModifierDown(); - Button getControllerButtonPressed(); - Axis getControllerAnalogDown(); - MouseButton getMouseButtonPressed(); - - bool loadKeyNames(const char* path); - const char* getControllerAxisName(Axis axis); - const char* getControllButtonName(Button button); - const char* getMouseAxisName(MouseAxis axis); - const char* getMouseButtonName(MouseButton button); - const char* getMouseWheelName(MouseWheel axis); - const char* getKeyboardName(KeyboardCode key); - const char* getKeyboardModifierName(KeyModifier mod); -}; diff --git a/components/darkforces/tfe/TFE_Input/inputEnum.h b/components/darkforces/tfe/TFE_Input/inputEnum.h deleted file mode 100644 index 00f3edcb..00000000 --- a/components/darkforces/tfe/TFE_Input/inputEnum.h +++ /dev/null @@ -1,322 +0,0 @@ -#pragma once -///////////////////////////////////////////////////////////// -// Input Enumerations used by the TFE_Input system. -///////////////////////////////////////////////////////////// - -enum Axis -{ - AXIS_LEFT_X = 0, - AXIS_LEFT_Y, - AXIS_RIGHT_X, - AXIS_RIGHT_Y, - AXIS_LEFT_TRIGGER, - AXIS_RIGHT_TRIGGER, - AXIS_COUNT, - AXIS_UNKNOWN = AXIS_COUNT -}; - -enum Button -{ - CONTROLLER_BUTTON_A = 0, - CONTROLLER_BUTTON_B, - CONTROLLER_BUTTON_X, - CONTROLLER_BUTTON_Y, - CONTROLLER_BUTTON_BACK, - CONTROLLER_BUTTON_GUIDE, - CONTROLLER_BUTTON_START, - CONTROLLER_BUTTON_LEFTSTICK, - CONTROLLER_BUTTON_RIGHTSTICK, - CONTROLLER_BUTTON_LEFTSHOULDER, - CONTROLLER_BUTTON_RIGHTSHOULDER, - CONTROLLER_BUTTON_DPAD_UP, - CONTROLLER_BUTTON_DPAD_DOWN, - CONTROLLER_BUTTON_DPAD_LEFT, - CONTROLLER_BUTTON_DPAD_RIGHT, - CONTROLLER_BUTTON_COUNT, - CONTROLLER_BUTTON_UNKNOWN = CONTROLLER_BUTTON_COUNT -}; - -enum MouseAxis -{ - MOUSE_AXIS_X = 0, - MOUSE_AXIS_Y, - MOUSE_AXIS_COUNT -}; - -enum MouseWheel -{ - MOUSEWHEEL_LEFT = 0, - MOUSEWHEEL_RIGHT, - MOUSEWHEEL_UP, - MOUSEWHEEL_DOWN, - MOUSEWHEEL_COUNT -}; - -enum MouseButton -{ - MBUTTON_LEFT = 0, - MBUTTON_MIDDLE, - MBUTTON_RIGHT, - MBUTTON_X1, - MBUTTON_X2, - MBUTTON_COUNT, - MBUTTON_UNKNOWN = MBUTTON_COUNT -}; - -// Matches SDL2 Keycodes but provided seperately for possible future changes and to avoid having to include SDL2 where it doesn't make sense. -enum KeyboardCode -{ - KEY_UNKNOWN = 0, - KEY_A = 4, - KEY_B = 5, - KEY_C = 6, - KEY_D = 7, - KEY_E = 8, - KEY_F = 9, - KEY_G = 10, - KEY_H = 11, - KEY_I = 12, - KEY_J = 13, - KEY_K = 14, - KEY_L = 15, - KEY_M = 16, - KEY_N = 17, - KEY_O = 18, - KEY_P = 19, - KEY_Q = 20, - KEY_R = 21, - KEY_S = 22, - KEY_T = 23, - KEY_U = 24, - KEY_V = 25, - KEY_W = 26, - KEY_X = 27, - KEY_Y = 28, - KEY_Z = 29, - KEY_1 = 30, - KEY_2 = 31, - KEY_3 = 32, - KEY_4 = 33, - KEY_5 = 34, - KEY_6 = 35, - KEY_7 = 36, - KEY_8 = 37, - KEY_9 = 38, - KEY_0 = 39, - KEY_RETURN = 40, - KEY_ESCAPE = 41, - KEY_BACKSPACE = 42, - KEY_TAB = 43, - KEY_SPACE = 44, - KEY_MINUS = 45, - KEY_EQUALS = 46, - KEY_LEFTBRACKET = 47, - KEY_RIGHTBRACKET = 48, - KEY_BACKSLASH = 49, - KEY_NONUSHASH = 50, - KEY_SEMICOLON = 51, - KEY_APOSTROPHE = 52, - KEY_GRAVE = 53, - KEY_COMMA = 54, - KEY_PERIOD = 55, - KEY_SLASH = 56, - KEY_CAPSLOCK = 57, - KEY_F1 = 58, - KEY_F2 = 59, - KEY_F3 = 60, - KEY_F4 = 61, - KEY_F5 = 62, - KEY_F6 = 63, - KEY_F7 = 64, - KEY_F8 = 65, - KEY_F9 = 66, - KEY_F10 = 67, - KEY_F11 = 68, - KEY_F12 = 69, - KEY_PRINTSCREEN = 70, - KEY_SCROLLLOCK = 71, - KEY_PAUSE = 72, - KEY_INSERT = 73, - KEY_HOME = 74, - KEY_PAGEUP = 75, - KEY_DELETE = 76, - KEY_END = 77, - KEY_PAGEDOWN = 78, - KEY_RIGHT = 79, - KEY_LEFT = 80, - KEY_DOWN = 81, - KEY_UP = 82, - KEY_NUMLOCKCLEAR = 83, - KEY_KP_DIVIDE = 84, - KEY_KP_MULTIPLY = 85, - KEY_KP_MINUS = 86, - KEY_KP_PLUS = 87, - KEY_KP_ENTER = 88, - KEY_KP_1 = 89, - KEY_KP_2 = 90, - KEY_KP_3 = 91, - KEY_KP_4 = 92, - KEY_KP_5 = 93, - KEY_KP_6 = 94, - KEY_KP_7 = 95, - KEY_KP_8 = 96, - KEY_KP_9 = 97, - KEY_KP_0 = 98, - KEY_KP_PERIOD = 99, - KEY_NONUSBACKSLASH = 100, - KEY_APPLICATION = 101, - KEY_POWER = 102, - KEY_KP_EQUALS = 103, - KEY_F13 = 104, - KEY_F14 = 105, - KEY_F15 = 106, - KEY_F16 = 107, - KEY_F17 = 108, - KEY_F18 = 109, - KEY_F19 = 110, - KEY_F20 = 111, - KEY_F21 = 112, - KEY_F22 = 113, - KEY_F23 = 114, - KEY_F24 = 115, - KEY_EXECUTE = 116, - KEY_HELP = 117, - KEY_MENU = 118, - KEY_SELECT = 119, - KEY_STOP = 120, - KEY_REDO = 121, - KEY_UNDO = 122, - KEY_CUT = 123, - KEY_COPY = 124, - KEY_PASTE = 125, - KEY_FIND = 126, - KEY_MUTE = 127, - KEY_VOLUMEUP = 128, - KEY_VOLUMEDOWN = 129, - KEY_KP_COMMA = 133, - KEY_KP_EQUALSAS400 = 134, - KEY_INTERNATIONAL1 = 135, - KEY_INTERNATIONAL2 = 136, - KEY_INTERNATIONAL3 = 137, - KEY_INTERNATIONAL4 = 138, - KEY_INTERNATIONAL5 = 139, - KEY_INTERNATIONAL6 = 140, - KEY_INTERNATIONAL7 = 141, - KEY_INTERNATIONAL8 = 142, - KEY_INTERNATIONAL9 = 143, - KEY_LANG1 = 144, - KEY_LANG2 = 145, - KEY_LANG3 = 146, - KEY_LANG4 = 147, - KEY_LANG5 = 148, - KEY_LANG6 = 149, - KEY_LANG7 = 150, - KEY_LANG8 = 151, - KEY_LANG9 = 152, - KEY_ALTERASE = 153, - KEY_SYSREQ = 154, - KEY_CANCEL = 155, - KEY_CLEAR = 156, - KEY_PRIOR = 157, - KEY_RETURN2 = 158, - KEY_SEPARATOR = 159, - KEY_OUT = 160, - KEY_OPER = 161, - KEY_CLEARAGAIN = 162, - KEY_CRSEL = 163, - KEY_EXSEL = 164, - KEY_KP_00 = 176, - KEY_KP_000 = 177, - KEY_THOUSANDSSEPARATOR = 178, - KEY_DECIMALSEPARATOR = 179, - KEY_CURRENCYUNIT = 180, - KEY_CURRENCYSUBUNIT = 181, - KEY_KP_LEFTPAREN = 182, - KEY_KP_RIGHTPAREN = 183, - KEY_KP_LEFTBRACE = 184, - KEY_KP_RIGHTBRACE = 185, - KEY_KP_TAB = 186, - KEY_KP_BACKSPACE = 187, - KEY_KP_A = 188, - KEY_KP_B = 189, - KEY_KP_C = 190, - KEY_KP_D = 191, - KEY_KP_E = 192, - KEY_KP_F = 193, - KEY_KP_XOR = 194, - KEY_KP_POWER = 195, - KEY_KP_PERCENT = 196, - KEY_KP_LESS = 197, - KEY_KP_GREATER = 198, - KEY_KP_AMPERSAND = 199, - KEY_KP_DBLAMPERSAND = 200, - KEY_KP_VERTICALBAR = 201, - KEY_KP_DBLVERTICALBAR = 202, - KEY_KP_COLON = 203, - KEY_KP_HASH = 204, - KEY_KP_SPACE = 205, - KEY_KP_AT = 206, - KEY_KP_EXCLAM = 207, - KEY_KP_MEMSTORE = 208, - KEY_KP_MEMRECALL = 209, - KEY_KP_MEMCLEAR = 210, - KEY_KP_MEMADD = 211, - KEY_KP_MEMSUBTRACT = 212, - KEY_KP_MEMMULTIPLY = 213, - KEY_KP_MEMDIVIDE = 214, - KEY_KP_PLUSMINUS = 215, - KEY_KP_CLEAR = 216, - KEY_KP_CLEARENTRY = 217, - KEY_KP_BINARY = 218, - KEY_KP_OCTAL = 219, - KEY_KP_DECIMAL = 220, - KEY_KP_HEXADECIMAL = 221, - KEY_LCTRL = 224, - KEY_LSHIFT = 225, - KEY_LALT = 226, - KEY_LGUI = 227, - KEY_RCTRL = 228, - KEY_RSHIFT = 229, - KEY_RALT = 230, - KEY_RGUI = 231, - KEY_MODE = 257, - KEY_AUDIONEXT = 258, - KEY_AUDIOPREV = 259, - KEY_AUDIOSTOP = 260, - KEY_AUDIOPLAY = 261, - KEY_AUDIOMUTE = 262, - KEY_MEDIASELECT = 263, - KEY_WWW = 264, - KEY_MAIL = 265, - KEY_CALCULATOR = 266, - KEY_COMPUTER = 267, - KEY_AC_SEARCH = 268, - KEY_AC_HOME = 269, - KEY_AC_BACK = 270, - KEY_AC_FORWARD = 271, - KEY_AC_STOP = 272, - KEY_AC_REFRESH = 273, - KEY_AC_BOOKMARKS = 274, - KEY_BRIGHTNESSDOWN = 275, - KEY_BRIGHTNESSUP = 276, - KEY_DISPLAYSWITCH = 277, - KEY_KBDILLUMTOGGLE = 278, - KEY_KBDILLUMDOWN = 279, - KEY_KBDILLUMUP = 280, - KEY_EJECT = 281, - KEY_SLEEP = 282, - KEY_APP1 = 283, - KEY_APP2 = 284, - KEY_AUDIOREWIND = 285, - KEY_AUDIOFASTFORWARD = 286, - KEY_LAST = 286, - KEY_COUNT = 512 // not a key, just marks the number of scancodes for array bounds -}; - -enum KeyModifier -{ - KEYMOD_NONE = 0, - KEYMOD_ALT, - KEYMOD_CTRL, - KEYMOD_SHIFT, -}; diff --git a/components/darkforces/tfe/TFE_Input/inputMapping.cpp b/components/darkforces/tfe/TFE_Input/inputMapping.cpp deleted file mode 100644 index 45301299..00000000 --- a/components/darkforces/tfe/TFE_Input/inputMapping.cpp +++ /dev/null @@ -1,519 +0,0 @@ -#include - -#include "inputMapping.h" -#include -#include -#include - -namespace TFE_Input -{ - enum InputVersion - { - INPUT_INIT_VER = 0x00010000, - INPUT_ADD_QUICKSAVE = 0x00020001, - INPUT_ADD_DEADZONE = 0x00020002, - INPUT_CUR_VERSION = INPUT_ADD_DEADZONE - }; - - static const char* c_inputRemappingName = "tfe_input_remapping.bin"; - static const char c_inputRemappingHdr[4] = { 'T', 'F', 'E', 0 }; - static const u32 c_inputRemappingVersion = INPUT_CUR_VERSION; - - static InputBinding s_defaultKeyboardBinds[] = - { - // System - { IAS_CONSOLE, ITYPE_KEYBOARD, KEY_GRAVE }, -#ifdef TFE_ESPBOX - { IAS_SYSTEM_MENU, ITYPE_KEYBOARD, KEY_LCTRL }, // strafe modifier -#else - { IAS_SYSTEM_MENU, ITYPE_KEYBOARD, KEY_F1, KEYMOD_ALT }, -#endif - - // General - { IADF_MENU_TOGGLE, ITYPE_KEYBOARD, KEY_ESCAPE }, - { IADF_PDA_TOGGLE, ITYPE_KEYBOARD, KEY_F1 }, - { IADF_NIGHT_VISION_TOG,ITYPE_KEYBOARD, KEY_F2 }, - { IADF_CLEATS_TOGGLE, ITYPE_KEYBOARD, KEY_F3 }, - { IADF_GAS_MASK_TOGGLE, ITYPE_KEYBOARD, KEY_F4 }, - { IADF_HEAD_LAMP_TOGGLE,ITYPE_KEYBOARD, KEY_F5 }, - { IADF_HEADWAVE_TOGGLE, ITYPE_KEYBOARD, KEY_F6 }, - { IADF_HUD_TOGGLE, ITYPE_KEYBOARD, KEY_F7 }, - { IADF_HOLSTER_WEAPON, ITYPE_KEYBOARD, KEY_F8 }, - { IADF_AUTOMOUNT_TOGGLE,ITYPE_KEYBOARD, KEY_F8, KEYMOD_ALT }, - { IADF_CYCLEWPN_PREV, ITYPE_MOUSEWHEEL, MOUSEWHEEL_DOWN }, - { IADF_CYCLEWPN_NEXT, ITYPE_MOUSEWHEEL, MOUSEWHEEL_UP }, - { IADF_WPN_PREV, ITYPE_KEYBOARD, KEY_BACKSPACE }, - { IADF_PAUSE, ITYPE_KEYBOARD, KEY_PAUSE }, - { IADF_AUTOMAP, ITYPE_KEYBOARD, KEY_TAB }, - { IADF_DEC_SCREENSIZE, ITYPE_KEYBOARD, KEY_MINUS, KEYMOD_ALT }, - { IADF_INC_SCREENSIZE, ITYPE_KEYBOARD, KEY_EQUALS, KEYMOD_ALT }, - - // Automap - { IADF_MAP_ZOOM_IN, ITYPE_KEYBOARD, KEY_EQUALS }, - { IADF_MAP_ZOOM_OUT, ITYPE_KEYBOARD, KEY_MINUS }, - { IADF_MAP_ENABLE_SCROLL, ITYPE_KEYBOARD, KEY_INSERT }, - { IADF_MAP_SCROLL_UP, ITYPE_KEYBOARD, KEY_UP }, - { IADF_MAP_SCROLL_DN, ITYPE_KEYBOARD, KEY_DOWN }, - { IADF_MAP_SCROLL_LT, ITYPE_KEYBOARD, KEY_LEFT }, - { IADF_MAP_SCROLL_RT, ITYPE_KEYBOARD, KEY_RIGHT }, - { IADF_MAP_LAYER_UP, ITYPE_KEYBOARD, KEY_RIGHTBRACKET }, - { IADF_MAP_LAYER_DN, ITYPE_KEYBOARD, KEY_LEFTBRACKET }, - - // Player Controls - { IADF_FORWARD, ITYPE_KEYBOARD, KEY_W }, - { IADF_BACKWARD, ITYPE_KEYBOARD, KEY_S }, - { IADF_STRAFE_LT, ITYPE_KEYBOARD, KEY_A }, - { IADF_STRAFE_RT, ITYPE_KEYBOARD, KEY_D }, - { IADF_TURN_LT, ITYPE_KEYBOARD, KEY_LEFT }, - { IADF_TURN_RT, ITYPE_KEYBOARD, KEY_RIGHT }, - { IADF_LOOK_UP, ITYPE_KEYBOARD, KEY_PAGEUP }, - { IADF_LOOK_DN, ITYPE_KEYBOARD, KEY_PAGEDOWN }, - { IADF_CENTER_VIEW, ITYPE_KEYBOARD, KEY_C }, - { IADF_RUN, ITYPE_KEYBOARD, KEY_LSHIFT }, - { IADF_SLOW, ITYPE_KEYBOARD, KEY_CAPSLOCK }, -#ifdef TFE_ESPBOX - { IADF_CROUCH, ITYPE_KEYBOARD, KEY_LALT }, -#else - { IADF_CROUCH, ITYPE_KEYBOARD, KEY_LCTRL }, -#endif - { IADF_JUMP, ITYPE_KEYBOARD, KEY_SPACE }, - { IADF_USE, ITYPE_KEYBOARD, KEY_E }, - { IADF_WEAPON_1, ITYPE_KEYBOARD, KEY_1 }, - { IADF_WEAPON_2, ITYPE_KEYBOARD, KEY_2 }, - { IADF_WEAPON_3, ITYPE_KEYBOARD, KEY_3 }, - { IADF_WEAPON_4, ITYPE_KEYBOARD, KEY_4 }, - { IADF_WEAPON_5, ITYPE_KEYBOARD, KEY_5 }, - { IADF_WEAPON_6, ITYPE_KEYBOARD, KEY_6 }, - { IADF_WEAPON_7, ITYPE_KEYBOARD, KEY_7 }, - { IADF_WEAPON_8, ITYPE_KEYBOARD, KEY_8 }, - { IADF_WEAPON_9, ITYPE_KEYBOARD, KEY_9 }, - { IADF_WEAPON_10, ITYPE_KEYBOARD, KEY_0 }, - { IADF_PRIMARY_FIRE, ITYPE_MOUSE, MBUTTON_LEFT }, - { IADF_SECONDARY_FIRE, ITYPE_MOUSE, MBUTTON_RIGHT }, - - // Saving - { IAS_QUICK_SAVE, ITYPE_KEYBOARD, KEY_F5, KEYMOD_ALT }, - { IAS_QUICK_LOAD, ITYPE_KEYBOARD, KEY_F9, KEYMOD_ALT }, - }; - - static InputBinding s_defaultControllerBinds[] = - { - { IAS_SYSTEM_MENU, ITYPE_CONTROLLER, CONTROLLER_BUTTON_RIGHTSTICK }, - - { IADF_JUMP, ITYPE_CONTROLLER, CONTROLLER_BUTTON_A }, - { IADF_RUN, ITYPE_CONTROLLER, CONTROLLER_BUTTON_B }, - { IADF_CROUCH, ITYPE_CONTROLLER, CONTROLLER_BUTTON_X }, - { IADF_USE, ITYPE_CONTROLLER, CONTROLLER_BUTTON_Y }, - -#ifdef TFE_ESPBOX - { IADF_MENU_TOGGLE, ITYPE_CONTROLLER, CONTROLLER_BUTTON_START }, -#else - { IADF_MENU_TOGGLE, ITYPE_CONTROLLER, CONTROLLER_BUTTON_GUIDE }, -#endif - - { IADF_PRIMARY_FIRE, ITYPE_CONTROLLER_AXIS, AXIS_RIGHT_TRIGGER }, - { IADF_SECONDARY_FIRE, ITYPE_CONTROLLER_AXIS, AXIS_LEFT_TRIGGER }, - - { IADF_HEAD_LAMP_TOGGLE, ITYPE_CONTROLLER, CONTROLLER_BUTTON_DPAD_RIGHT }, - { IADF_NIGHT_VISION_TOG, ITYPE_CONTROLLER, CONTROLLER_BUTTON_DPAD_LEFT }, - { IADF_AUTOMAP, ITYPE_CONTROLLER, CONTROLLER_BUTTON_DPAD_UP }, - { IADF_GAS_MASK_TOGGLE, ITYPE_CONTROLLER, CONTROLLER_BUTTON_DPAD_DOWN }, - - { IADF_CYCLEWPN_PREV, ITYPE_CONTROLLER, CONTROLLER_BUTTON_LEFTSHOULDER }, - { IADF_CYCLEWPN_NEXT, ITYPE_CONTROLLER, CONTROLLER_BUTTON_RIGHTSHOULDER }, - }; - - static InputConfig s_inputConfig = { 0 }; - static ActionState s_actions[IA_COUNT]; - - void addDefaultControlBinds(); - - void inputMapping_startup() - { - // First try to restore from disk. - if (inputMapping_restore()) - { - return; - } - - // If that fails, setup the defaults. - inputMapping_resetToDefaults(); - - // Once the defaults are setup, write out the file to disk for next time. - inputMapping_serialize(); - } - - void inputMapping_shutdown() - { - free(s_inputConfig.binds); - s_inputConfig.bindCount = 0; - s_inputConfig.bindCapacity = 0; - s_inputConfig.binds = nullptr; - } - - void inputMapping_resetToDefaults() - { - // If that fails, setup the defaults. - s_inputConfig.bindCount = 0; - s_inputConfig.bindCapacity = IA_COUNT * 2; - s_inputConfig.binds = (InputBinding*)realloc(s_inputConfig.binds, sizeof(InputBinding)*s_inputConfig.bindCapacity); - - // Controller - s_inputConfig.controllerFlags = CFLAG_ENABLE; - s_inputConfig.axis[AA_LOOK_HORZ] = AXIS_RIGHT_X; - s_inputConfig.axis[AA_LOOK_VERT] = AXIS_RIGHT_Y; - s_inputConfig.axis[AA_STRAFE] = AXIS_LEFT_X; - s_inputConfig.axis[AA_MOVE] = AXIS_LEFT_Y; - s_inputConfig.ctrlSensitivity[0] = 1.0f; - s_inputConfig.ctrlSensitivity[1] = 1.0f; - s_inputConfig.ctrlDeadzone[0] = 0.1f; - s_inputConfig.ctrlDeadzone[1] = 0.1f; - - // Mouse - s_inputConfig.mouseFlags = 0; - s_inputConfig.mouseMode = MMODE_LOOK; - s_inputConfig.mouseSensitivity[0] = 1.0f; - s_inputConfig.mouseSensitivity[1] = 1.0f; - - memset(s_actions, 0, sizeof(ActionState) * IA_COUNT); - addDefaultControlBinds(); - } - - bool inputMapping_serialize() - { - const char* path = TFE_Paths::getPath(PATH_USER_DOCUMENTS); - char fullPath[TFE_MAX_PATH]; - - sprintf(fullPath, "%s%s", path, c_inputRemappingName); - FileStream file; - if (!file.open(fullPath, Stream::MODE_WRITE)) - { - return false; - } - - file.writeBuffer(c_inputRemappingHdr, 4); - file.write(&c_inputRemappingVersion); - - file.write(&s_inputConfig.bindCount); - file.write(&s_inputConfig.bindCapacity); - file.writeBuffer(s_inputConfig.binds, sizeof(InputBinding), s_inputConfig.bindCount); - - file.write(&s_inputConfig.controllerFlags); - file.writeBuffer(s_inputConfig.axis, sizeof(Axis), AA_COUNT); - file.write(s_inputConfig.ctrlSensitivity, 2); - - // version: INPUT_ADD_DEADZONE - { - file.write(s_inputConfig.ctrlDeadzone, 2); - } - - file.write(&s_inputConfig.mouseFlags); - file.writeBuffer(&s_inputConfig.mouseMode, sizeof(MouseMode)); - file.write(s_inputConfig.mouseSensitivity, 2); - - file.close(); - return true; - } - - bool inputMapping_restore() - { - const char* path = TFE_Paths::getPath(PATH_USER_DOCUMENTS); - char fullPath[TFE_MAX_PATH]; - - sprintf(fullPath, "%s%s", path, c_inputRemappingName); - FileStream file; - if (!file.open(fullPath, Stream::MODE_READ)) - { - return false; - } - - char hdr[4]; - u32 version; - file.readBuffer(hdr, 4); - file.read(&version); - if (memcmp(hdr, c_inputRemappingHdr, 4) != 0) - { - file.close(); - return false; - } - - file.read(&s_inputConfig.bindCount); - file.read(&s_inputConfig.bindCapacity); - s_inputConfig.binds = (InputBinding*)realloc(s_inputConfig.binds, sizeof(InputBinding) * s_inputConfig.bindCapacity); - file.readBuffer(s_inputConfig.binds, sizeof(InputBinding), s_inputConfig.bindCount); - - file.read(&s_inputConfig.controllerFlags); - file.readBuffer(s_inputConfig.axis, sizeof(Axis), AA_COUNT); - file.read(s_inputConfig.ctrlSensitivity, 2); - - if (version >= INPUT_ADD_DEADZONE) - { - file.read(s_inputConfig.ctrlDeadzone, 2); - } - else - { - s_inputConfig.ctrlDeadzone[0] = 0.1f; - s_inputConfig.ctrlDeadzone[1] = 0.1f; - } - - file.read(&s_inputConfig.mouseFlags); - file.readBuffer(&s_inputConfig.mouseMode, sizeof(MouseMode)); - file.read(s_inputConfig.mouseSensitivity, 2); - - file.close(); - - if (version < INPUT_ADD_QUICKSAVE) - { - inputMapping_addBinding(&s_defaultKeyboardBinds[IAS_QUICK_SAVE]); - inputMapping_addBinding(&s_defaultKeyboardBinds[IAS_QUICK_LOAD]); - } - - return true; - } - - void inputMapping_addBinding(InputBinding* binding) - { - u32 index = s_inputConfig.bindCount; - s_inputConfig.bindCount++; - - if (s_inputConfig.bindCount > s_inputConfig.bindCapacity) - { - s_inputConfig.bindCapacity += IA_COUNT; - s_inputConfig.binds = (InputBinding*)realloc(s_inputConfig.binds, sizeof(InputBinding)*s_inputConfig.bindCapacity); - } - - s_inputConfig.binds[index] = *binding; - } - - void addDefaultControlBinds() - { - for (s32 i = 0; i < TFE_ARRAYSIZE(s_defaultKeyboardBinds); i++) - { - inputMapping_addBinding(&s_defaultKeyboardBinds[i]); - } -#ifndef TFE_ESPBOX - for (s32 i = 0; i < TFE_ARRAYSIZE(s_defaultControllerBinds); i++) - { - inputMapping_addBinding(&s_defaultControllerBinds[i]); - } -#endif - } - - void inputMapping_endFrame() - { - for (u32 i = 0; i < IA_COUNT; i++) - { - s_actions[i] = STATE_UP; - } - } - - bool inputMapping_isMovementAction(InputAction action) - { -#ifdef TFE_ESPBOX - if (action == IADF_USE) return true; -#endif - return action >= IADF_FORWARD && action <= IADF_LOOK_DN; - } - - void inputMapping_updateInput() - { - for (u32 i = 0; i < s_inputConfig.bindCount; i++) - { - InputBinding* bind = &s_inputConfig.binds[i]; - switch (bind->type) - { - case ITYPE_KEYBOARD: - { - const bool keyIsMod = (s32)bind->keyMod == (s32)bind->keyCode || bind->keyMod == KEYMOD_NONE; - const bool keyIsAlt = bind->keyCode == KEY_LALT || bind->keyCode == KEY_RALT; - if (TFE_Input::keyModDown(bind->keyMod, inputMapping_isMovementAction(bind->action)) || (keyIsMod && keyIsAlt)) - { - if (TFE_Input::keyPressed(bind->keyCode)) - { - s_actions[bind->action] = STATE_PRESSED; - } - else if (TFE_Input::keyDown(bind->keyCode) && s_actions[bind->action] != STATE_PRESSED) - { - s_actions[bind->action] = STATE_DOWN; - } - } - } break; - case ITYPE_MOUSE: - { - if (TFE_Input::keyModDown(bind->keyMod, true)) - { - if (TFE_Input::mousePressed(bind->mouseBtn)) - { - s_actions[bind->action] = STATE_PRESSED; - } - else if (TFE_Input::mouseDown(bind->mouseBtn) && s_actions[bind->action] != STATE_PRESSED) - { - s_actions[bind->action] = STATE_DOWN; - } - } - } break; - case ITYPE_MOUSEWHEEL: - { - s32 dx, dy; - TFE_Input::getMouseWheel(&dx, &dy); - if ((bind->mouseWheel == MOUSEWHEEL_LEFT && dx < 0) || - (bind->mouseWheel == MOUSEWHEEL_RIGHT && dx > 0) || - (bind->mouseWheel == MOUSEWHEEL_UP && dy > 0) || - (bind->mouseWheel == MOUSEWHEEL_DOWN && dy < 0)) - { - s_actions[bind->action] = STATE_PRESSED; - } - } break; - case ITYPE_CONTROLLER: - { - if (!(s_inputConfig.controllerFlags & CFLAG_ENABLE)) - { - break; - } - - if (TFE_Input::buttonPressed(bind->ctrlBtn)) - { - s_actions[bind->action] = STATE_PRESSED; - } - else if (TFE_Input::buttonDown(bind->ctrlBtn) && s_actions[bind->action] != STATE_PRESSED) - { - s_actions[bind->action] = STATE_DOWN; - } - } break; - case ITYPE_CONTROLLER_AXIS: - { - if (!(s_inputConfig.controllerFlags & CFLAG_ENABLE)) - { - break; - } - - if (TFE_Input::getAxis(bind->axis) > 0.5f) - { - s_actions[bind->action] = STATE_DOWN; - } - } break; - } - } -#ifdef TFE_ESPBOX - // strafe modifier - if (s_actions[IAS_SYSTEM_MENU]) - { - if (s_actions[IADF_TURN_LT]) - { - s_actions[IADF_STRAFE_LT] = s_actions[IADF_TURN_LT]; - s_actions[IADF_TURN_LT] = STATE_UP; - } - if (s_actions[IADF_TURN_RT]) - { - s_actions[IADF_STRAFE_RT] = s_actions[IADF_TURN_RT]; - s_actions[IADF_TURN_RT] = STATE_UP; - } - } -#endif - } - - void inputMapping_removeState(InputAction action) - { - s_actions[action] = STATE_UP; - } - - ActionState inputMapping_getActionState(InputAction action) - { - return s_actions[action]; - } - - void inputMapping_clearKeyBinding(KeyboardCode key) - { - // Search through bindings and clear any actions with this key. - for (u32 i = 0; i < s_inputConfig.bindCount; i++) - { - InputBinding* bind = &s_inputConfig.binds[i]; - if (bind->type == ITYPE_KEYBOARD && bind->keyCode == key) - { - inputMapping_removeState(bind->action); - return; - } - } - } - - f32 inputMapping_getAnalogAxis(AnalogAxis axis) - { - if (!(s_inputConfig.controllerFlags & CFLAG_ENABLE)) - { - return 0.0f; - } - - Axis mappedAxis = s_inputConfig.axis[axis]; - f32 axisValue = TFE_Input::getAxis(mappedAxis); - if (s_inputConfig.controllerFlags & (1 << (mappedAxis + 1))) - { - axisValue = -axisValue; - } - - const f32 sensitivity = s_inputConfig.ctrlSensitivity[mappedAxis < AXIS_RIGHT_X ? 0 : 1]; - f32 deadzone = s_inputConfig.ctrlDeadzone[mappedAxis < AXIS_RIGHT_X ? 0 : 1]; - if (fabsf(axisValue) <= deadzone) - { - axisValue = 0.0f; - } - else if (deadzone > FLT_EPSILON) - { - deadzone *= ((axisValue < 0.0f) ? -1.0f : 1.0f); - // sensitivity is adjusted by the new range, so larger deadzones don't decrease the maximum output. - axisValue = (axisValue - deadzone) * sensitivity / (1.0f - fabsf(deadzone)); - } - else - { - axisValue = axisValue * sensitivity; - } - - return axisValue; - } - - f32 inputMapping_getHorzMouseSensitivity() - { - return s_inputConfig.mouseSensitivity[0] * ((s_inputConfig.mouseFlags & MFLAG_INVERT_HORZ) ? -1.0f : 1.0f); - } - - f32 inputMapping_getVertMouseSensitivity() - { - return s_inputConfig.mouseSensitivity[1] * ((s_inputConfig.mouseFlags & MFLAG_INVERT_VERT) ? -1.0f : 1.0f); - } - - u32 inputMapping_getBindingsForAction(InputAction action, u32* indices, u32 maxIndices) - { - assert(indices); - u32 count = 0; - for (u32 i = 0; i < s_inputConfig.bindCount; i++) - { - if (s_inputConfig.binds[i].action == action) - { - indices[count++] = i; - if (count >= maxIndices) - { - return count; - } - } - } - return count; - } - - void inputMapping_removeBinding(u32 index) - { - for (u32 i = index; i < s_inputConfig.bindCount; i++) - { - s_inputConfig.binds[i] = s_inputConfig.binds[i + 1]; - } - s_inputConfig.bindCount--; - } - - InputBinding* inputMapping_getBindingByIndex(u32 index) - { - return &s_inputConfig.binds[index]; - } - - InputConfig* inputMapping_get() - { - return &s_inputConfig; - } -} // TFE_DarkForces \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Input/inputMapping.h b/components/darkforces/tfe/TFE_Input/inputMapping.h deleted file mode 100644 index 125f610c..00000000 --- a/components/darkforces/tfe/TFE_Input/inputMapping.h +++ /dev/null @@ -1,189 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Input Mapping for supported games. -////////////////////////////////////////////////////////////////////// -#include -#include -#include - -namespace TFE_Input -{ - enum InputAction - { - // System - IAS_CONSOLE = 0, - IAS_SYSTEM_MENU, - - // Dark Forces - // General - IADF_MENU_TOGGLE, - IADF_PDA_TOGGLE, - IADF_NIGHT_VISION_TOG, - IADF_CLEATS_TOGGLE, - IADF_GAS_MASK_TOGGLE, - IADF_HEAD_LAMP_TOGGLE, - IADF_HEADWAVE_TOGGLE, - IADF_HUD_TOGGLE, - IADF_HOLSTER_WEAPON, - IADF_AUTOMOUNT_TOGGLE, - IADF_CYCLEWPN_NEXT, - IADF_CYCLEWPN_PREV, - IADF_WPN_PREV, - IADF_PAUSE, - IADF_AUTOMAP, - IADF_DEC_SCREENSIZE, - IADF_INC_SCREENSIZE, - - // Automap - IADF_MAP_ZOOM_IN, - IADF_MAP_ZOOM_OUT, - IADF_MAP_ENABLE_SCROLL, - IADF_MAP_SCROLL_UP, - IADF_MAP_SCROLL_DN, - IADF_MAP_SCROLL_LT, - IADF_MAP_SCROLL_RT, - IADF_MAP_LAYER_UP, - IADF_MAP_LAYER_DN, - - // Player Controls - IADF_FORWARD, - IADF_BACKWARD, - IADF_STRAFE_LT, - IADF_STRAFE_RT, - IADF_TURN_LT, - IADF_TURN_RT, - IADF_LOOK_UP, - IADF_LOOK_DN, - IADF_CENTER_VIEW, - IADF_RUN, - IADF_SLOW, - IADF_CROUCH, - IADF_JUMP, - IADF_USE, - IADF_WEAPON_1, - IADF_WEAPON_2, - IADF_WEAPON_3, - IADF_WEAPON_4, - IADF_WEAPON_5, - IADF_WEAPON_6, - IADF_WEAPON_7, - IADF_WEAPON_8, - IADF_WEAPON_9, - IADF_WEAPON_10, - IADF_PRIMARY_FIRE, - IADF_SECONDARY_FIRE, - - // Saving - IAS_QUICK_SAVE, - IAS_QUICK_LOAD, - - IA_COUNT, - IAS_COUNT = IAS_SYSTEM_MENU + 1, - }; - - enum AnalogAxis - { - AA_LOOK_HORZ = 0, - AA_LOOK_VERT, - AA_STRAFE, - AA_MOVE, - AA_COUNT - }; - - enum InputType - { - ITYPE_KEYBOARD = 0, - ITYPE_MOUSE, - ITYPE_CONTROLLER, - ITYPE_CONTROLLER_AXIS, - ITYPE_MOUSEWHEEL, - ITYPE_COUNT - }; - - enum ActionState - { - STATE_UP = 0, - STATE_DOWN = 1, - STATE_PRESSED = 2, - STATE_ACTIVE = STATE_DOWN | STATE_PRESSED - }; - - struct InputBinding - { - InputAction action; - InputType type; - union - { - u32 code; - KeyboardCode keyCode; - MouseButton mouseBtn; - MouseWheel mouseWheel; - Button ctrlBtn; - Axis axis; - }; - KeyModifier keyMod = KEYMOD_NONE; - }; - - enum ControllerFlags - { - CFLAG_ENABLE = FLAG_BIT(0), - CFLAG_INVERT_LEFT_HORZ = FLAG_BIT(1), - CFLAG_INVERT_LEFT_VERT = FLAG_BIT(2), - CFLAG_INVERT_RIGHT_HORZ = FLAG_BIT(3), - CFLAG_INVERT_RIGHT_VERT = FLAG_BIT(4), - }; - - enum MouseFlags - { - MFLAG_INVERT_HORZ = FLAG_BIT(0), - MFLAG_INVERT_VERT = FLAG_BIT(1), - }; - - enum MouseMode - { - MMODE_NONE = 0, - MMODE_TURN, - MMODE_LOOK, - }; - - struct InputConfig - { - u32 bindCount; - u32 bindCapacity; - InputBinding* binds; - - // Controller - u32 controllerFlags; // see ControllerFlags. - Axis axis[AA_COUNT]; // axis mapping. - f32 ctrlSensitivity[2]; // left/right sensitivity. - f32 ctrlDeadzone[2]; // left/right sensitivity. - - // Mouse - u32 mouseFlags; // see MouseFlags. - MouseMode mouseMode; // see MouseMode. - f32 mouseSensitivity[2];// horizontal/vertical sensitivity. - }; - - void inputMapping_startup(); - void inputMapping_shutdown(); - void inputMapping_resetToDefaults(); - - bool inputMapping_serialize(); - bool inputMapping_restore(); - - void inputMapping_addBinding(InputBinding* binding); - void inputMapping_removeBinding(u32 index); - ActionState inputMapping_getActionState(InputAction action); - f32 inputMapping_getAnalogAxis(AnalogAxis axis); - void inputMapping_updateInput(); - void inputMapping_removeState(InputAction action); - void inputMapping_clearKeyBinding(KeyboardCode key); - void inputMapping_endFrame(); - - InputConfig* inputMapping_get(); - u32 inputMapping_getBindingsForAction(InputAction action, u32* indices, u32 maxIndices); - InputBinding* inputMapping_getBindingByIndex(u32 index); - - f32 inputMapping_getHorzMouseSensitivity(); - f32 inputMapping_getVertMouseSensitivity(); -} // TFE_Input \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Collision/collision.cpp b/components/darkforces/tfe/TFE_Jedi/Collision/collision.cpp deleted file mode 100644 index 01be2c2e..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Collision/collision.cpp +++ /dev/null @@ -1,1246 +0,0 @@ -#include "collision.h" -#include -#include -#include -#include -#include -#include -#include -// Merge player collision into collision -#include -using namespace TFE_DarkForces; - -// These will be moved over from player collision. -namespace TFE_DarkForces -{ - extern SecObject* s_collidedObj; - extern ColObject s_colObject; - extern ColObject s_colObj1; - extern RWall* s_colWallCollided; - extern fixed16_16 s_colSrcPosX; - extern fixed16_16 s_colSrcPosY; - extern fixed16_16 s_colSrcPosZ; - extern fixed16_16 s_colHeight; - extern fixed16_16 s_colDoubleRadius; - extern fixed16_16 s_colHeightBase; - extern fixed16_16 s_colRealFloorHeight; - extern fixed16_16 s_colRealCeilHeight; - extern fixed16_16 s_colBottom; - extern fixed16_16 s_colTop; - extern fixed16_16 s_colY1; - extern fixed16_16 s_colCurTop; - extern angle14_32 s_colResponseAngle; - extern vec2_fixed s_colResponsePos; - extern vec2_fixed s_colWallV0; - extern s32 s_collisionFrameSector; - - extern CollisionObjFunc s_objCollisionFunc; - extern CollisionProxFunc s_objCollisionProxFunc; -} - -namespace TFE_Jedi -{ - //////////////////////////////////////////////////////// - // Structures and Constants - //////////////////////////////////////////////////////// - struct ColPath - { - fixed16_16 x0; - fixed16_16 x1; - fixed16_16 z0; - fixed16_16 z1; - }; - - static const fixed16_16 c_maxCollisionDist = COL_INFINITY; - static const fixed16_16 c_minTraversableOpening = HALF_16; - - enum IntersectionResult - { - INTERSECT = 0xffffffff, - NO_INTERSECT = 0, - }; - - //////////////////////////////////////////////////////// - // Internal State - //////////////////////////////////////////////////////// - s32 s_collisionFrameWall; - JBool s_collision_wallHit = JFALSE; - u32 s_collision_excludeEntityFlags = 0; - static ColPath s_col_path; - - static fixed16_16 s_col_hitX; - static fixed16_16 s_col_hitDist; - static fixed16_16 s_col_hitZ; - static fixed16_16 s_col_ceilingHeight; - static fixed16_16 s_col_floorHeight; - - static vec2_fixed s_col_intersectPos; - static fixed16_16 s_col_intersectParam; - static fixed16_16 s_col_wallZ1; - static fixed16_16 s_col_intersectNum; - static fixed16_16 s_col_intersectNum2; - static fixed16_16 s_col_intersectDen; - - static fixed16_16 s_col_adjPathZ0; - static fixed16_16 s_col_adjPathX0; - static RWall* s_col_curWall; - static fixed16_16 s_col_pathDx; - static fixed16_16 s_col_pathDz; - static fixed16_16 s_col_adjPathX1; - static fixed16_16 s_col_intersect; - static fixed16_16 s_col_adjPathZ1; - static fixed16_16 s_col_wallDx; - static fixed16_16 s_col_wallDz; - - static fixed16_16 s_col_XOffset; - static fixed16_16 s_col_ZOffset; - - static fixed16_16 s_col_pathX0; - static fixed16_16 s_col_pathX1; - static fixed16_16 s_col_pathZ0; - static fixed16_16 s_col_pathZ1; - - static fixed16_16 s_col_wallX0; - static fixed16_16 s_col_wallX1; - static fixed16_16 s_col_wallZ0; - - // Object Collision - static fixed16_16 s_colObjOffsetX; - static fixed16_16 s_colObjOffsetZ; - static fixed16_16 s_colObjDirX; - static fixed16_16 s_colObjDirZ; - static fixed16_16 s_colObjMinY; - static fixed16_16 s_colObjMaxY; - static fixed16_16 s_colObjX0; - static fixed16_16 s_colObjX1; - static fixed16_16 s_colObjY0; - static fixed16_16 s_colObjY1; - static fixed16_16 s_colObjZ0; - static fixed16_16 s_colObjZ1; - static fixed16_16 s_colObjMove; - - static vec2_fixed s_colWallV0; - - static SecObject* s_colObjPrev; - static SecObject** s_colObjList; - static CollisionInterval* s_colObjInterval; - - static s32 s_colObjCount; - fixed16_16 s_colObjOverlap; - - //////////////////////////////////////////////////////// - // Forward Declarations - //////////////////////////////////////////////////////// - IntersectionResult pathIntersectsWall(ColPath* path, RWall* wall); - vec2_fixed* computeIntersectPos(); - SecObject* internal_getObjectCollision(); - - //////////////////////////////////////////////////////// - // API Implementation - //////////////////////////////////////////////////////// - void collision_getHitPoint(fixed16_16* x, fixed16_16* z) - { - *x = s_col_hitX; - *z = s_col_hitZ; - } - - fixed16_16 collision_getHitDistance() - { - return s_col_hitDist; - } - - RWall* collision_pathWallCollision(RSector* sector) - { - RWall* wall = sector->walls; - s32 count = sector->wallCount; - RWall* hitWall = nullptr; - s_col_hitDist = c_maxCollisionDist; - for (s32 i = 0; i < sector->wallCount; i++, wall++) - { - if (s_collisionFrameWall == wall->collisionFrame) - { - continue; - } - - // returns INTERSECT if s_col_path intersects wall, else returns NO_INTERSECT - IntersectionResult intersect = pathIntersectsWall(&s_col_path, wall); - if (intersect == INTERSECT) - { - vec2_fixed* pos = computeIntersectPos(); - if (pos->x != s_col_path.x0 || pos->z != s_col_path.z0) - { - fixed16_16 dx = s_col_path.x1 - s_col_path.x0; - fixed16_16 dz = s_col_path.z1 - s_col_path.z0; - - // Essentially a dot product with the (negative) wall normal, which given the wall direction (dir), normal = (-dir.z, dir.x), negative = (dir.z, -dir.x) - // So (dx, dz).(dir.z, -dir.x) = dx*dir.z - dz*dir.x - // If the path and the wall are parallel or facing opposite directions (i.e. the object is moving away), then there is no intersection. - if (mul16(dx, wall->wallDir.z) - mul16(dz, wall->wallDir.x) >= 0) - { - intersect = NO_INTERSECT; - } - } - if (intersect == INTERSECT) - { - fixed16_16 dist = distApprox(s_col_path.x0, s_col_path.z0, pos->x, pos->z); - if (dist < s_col_hitDist) - { - s_col_hitX = pos->x; - s_col_hitZ = pos->z; - s_col_hitDist = dist; - hitWall = wall; - } - } - } - } - if (hitWall) - { - hitWall->collisionFrame = s_collisionFrameWall; - RWall* hitMirror = hitWall->mirrorWall; - if (hitMirror) - { - hitMirror->collisionFrame = s_collisionFrameWall; - } - } - return hitWall; - } - - RSector* collision_tryMove(RSector* sector, fixed16_16 x0, fixed16_16 z0, fixed16_16 x1, fixed16_16 z1) - { - RSector* curSector = sector; - fixed16_16 ceilHeight, floorHeight; - fixed16_16 secHeight = curSector->secHeight; - if (secHeight < 0) - { - floorHeight = sector->floorHeight + secHeight; - if (floorHeight >= -COL_SEC_HEIGHT_OFFSET) - { - ceilHeight = curSector->ceilingHeight; - } - else - { - floorHeight = sector->floorHeight; - ceilHeight = sector->floorHeight + secHeight; - } - } - else - { - floorHeight = curSector->floorHeight + secHeight; - ceilHeight = curSector->ceilingHeight; - } - if (curSector->flags1 & SEC_FLAGS1_PIT) - { - floorHeight += SEC_SKY_HEIGHT; - } - if (curSector->flags1 & SEC_FLAGS1_EXTERIOR) - { - ceilHeight -= SEC_SKY_HEIGHT; - } - s_col_ceilingHeight = ceilHeight; - s_col_floorHeight = floorHeight; - - // Abort early if there is no movement. - fixed16_16 dx = x1 - x0; - fixed16_16 dz = z1 - z0; - if (dx == 0 && dz == 0) - { - return curSector; - } - - s_col_path.x0 = x0; - s_col_path.x1 = x1; - s_col_path.z0 = z0; - s_col_path.z1 = z1; - s_collisionFrameWall++; - - RWall* wall = collision_pathWallCollision(curSector); - fixed16_16 curFloorHeight = s_col_floorHeight; - if (!wall) - { - return curSector; - } - - while (wall) - { - RSector* nextSector = wall->nextSector; - if (!nextSector) - { - return nullptr; - } - else - { - fixed16_16 nextSecHeight = nextSector->secHeight; - if (nextSecHeight < 0) - { - floorHeight = nextSector->floorHeight + nextSecHeight; - if (floorHeight >= -COL_SEC_HEIGHT_OFFSET) - { - ceilHeight = nextSector->ceilingHeight; - } - else - { - floorHeight = nextSector->floorHeight; - ceilHeight = nextSector->floorHeight + nextSecHeight; - } - } - else - { - floorHeight = nextSector->floorHeight + nextSecHeight; - ceilHeight = nextSector->ceilingHeight; - } - - if (nextSector->flags1 & SEC_FLAGS1_PIT) - { - floorHeight += SEC_SKY_HEIGHT; - } - if (nextSector->flags1 & SEC_FLAGS1_EXTERIOR) - { - ceilHeight -= SEC_SKY_HEIGHT; - } - - if (ceilHeight <= s_col_ceilingHeight) - { - ceilHeight = s_col_ceilingHeight; - } - s_col_ceilingHeight = ceilHeight; - - if (curFloorHeight > floorHeight) - { - curFloorHeight = floorHeight; - } - s_col_floorHeight = curFloorHeight; - - wall = collision_pathWallCollision(nextSector); - } - curSector = nextSector; - } - return curSector; - } - - RWall* collision_wallCollisionFromPath(RSector* sector, fixed16_16 srcX, fixed16_16 srcZ, fixed16_16 dstX, fixed16_16 dstZ) - { - fixed16_16 dx = dstX - srcX; - fixed16_16 dz = dstZ - srcZ; - if (dx == 0 && dz == 0) - { - return nullptr; - } - - s_col_path.x0 = srcX; - s_col_path.x1 = dstX; - s_col_path.z1 = dstZ; - s_col_path.z0 = srcZ; - s_collisionFrameWall++; - - return collision_pathWallCollision(sector); - } - - RSector* collision_moveObj(SecObject* obj, fixed16_16 dx, fixed16_16 dz) - { - RSector* sector = obj->sector; - fixed16_16 x0 = obj->posWS.x; - fixed16_16 z0 = obj->posWS.z; - fixed16_16 x1 = x0 + dx; - fixed16_16 z1 = z0 + dz; - - RSector* newSector = collision_tryMove(sector, x0, z0, x1, z1); - if (newSector) - { - obj->posWS.x = x1; - obj->posWS.z = z1; - if (newSector != sector) - { - sector_addObject(newSector, obj); - } - } - return newSector; - } - - SecObject* collision_getObjectCollision(RSector* sector, CollisionInterval* interval, SecObject* prevObj) - { - if (!sector) { return nullptr; } - - //s_infCurSector = sector; - s_colObjPrev = prevObj; - - s_colObjX0 = interval->x0; - s_colObjX1 = interval->x1; - s_colObjZ0 = interval->z0; - s_colObjZ1 = interval->z1; - s_colObjInterval = interval; - s_colObjList = sector->objectList; - s_colObjCount = sector->objectCount; - s_colObjMove = interval->move; - s_colObjDirX = interval->dirX; - s_colObjDirZ = interval->dirZ; - - fixed16_16 y0 = interval->y0; - fixed16_16 y1 = interval->y1; - s_colObjMaxY = max(y0, y1); - s_colObjMinY = min(y0, y1); - s_colObjY0 = y0; - s_colObjY1 = y1; - - return internal_getObjectCollision(); - } - - void sector_calculateFloor(RSector* sector, fixed16_16 y, fixed16_16* floorHeight, fixed16_16* ceilHeight) - { - y -= COL_SEC_HEIGHT_OFFSET; // adjust the y value to handle second heights. - if (sector->secHeight < 0 && y > sector->floorHeight + sector->secHeight) - { - *floorHeight = sector->floorHeight; - *ceilHeight = sector->floorHeight + sector->secHeight; - } - else - { - *floorHeight = sector->floorHeight + sector->secHeight; - *ceilHeight = sector->ceilingHeight; - } - - if (sector->flags1 & SEC_FLAGS1_PIT) { *floorHeight += SEC_SKY_HEIGHT; } - if (sector->flags1 & SEC_FLAGS1_EXTERIOR) { *ceilHeight -= SEC_SKY_HEIGHT; } - } - - JBool collision_lineOfSight(RSector* sector0, RSector* sector1, vec3_fixed pos0, vec3_fixed pos1, u32 wallFlags3) - { - fixed16_16 len = distApprox(pos0.x, pos0.z, pos1.x, pos1.z); - fixed16_16 dy = pos1.y - pos0.y; - fixed16_16 slope = len ? div16(dy, len) : dy; - - RSector* sector = sector0; - RWall* hitWall = collision_wallCollisionFromPath(sector, pos0.x, pos0.z, pos1.x, pos1.z); - while (hitWall) - { - if (!hitWall->nextSector || (hitWall->flags3 & wallFlags3)) - { - return JFALSE; - } - - len = collision_getHitDistance(); - fixed16_16 y = pos0.y + mul16(len, slope); - - RSector* hitSector = hitWall->sector; - RSector* hitNextSector = hitWall->nextSector; - if (y < hitSector->ceilingHeight || y < hitNextSector->ceilingHeight) { return JFALSE; } - if (y > hitSector->floorHeight || y > hitNextSector->floorHeight) { return JFALSE; } - - sector = hitNextSector; - hitWall = collision_pathWallCollision(sector); - } - - return (sector == sector1) ? JTRUE : JFALSE; - } - - // Determines if an object with the correct entityFlag(s) is in range (radius) of (x,y,z) in sector and is not skipObj. - // Note only objects with a clear line-of-sight are accepted. - JBool collision_isAnyObjectInRange(RSector* sector, fixed16_16 radius, vec3_fixed origin, SecObject* skipObj, u32 entityFlags) - { - if (!sector) - { - return JFALSE; - } - - fixed16_16 x0 = origin.x - radius; - fixed16_16 y0 = origin.y - radius; - fixed16_16 z0 = origin.z - radius; - - fixed16_16 x1 = origin.x + radius; - fixed16_16 y1 = origin.y + radius; - fixed16_16 z1 = origin.z + radius; - - fixed16_16 secHeightThreshold = origin.y - COL_SEC_HEIGHT_OFFSET; - RSector* curSector = s_levelState.sectors; - - for (u32 i = 0; i < s_levelState.sectorCount; i++, curSector++) - { - /////////////////////////////////////////////// - // These tests should only happen once I think, - // unless x0, x1, z0, z1 change over time. - /////////////////////////////////////////////// - if (x0 > sector->boundsMax.x || x1 < sector->boundsMin.x || z0 > sector->boundsMax.z || z1 < sector->boundsMin.z) - { - continue; - } - - fixed16_16 floorHeight, ceilHeight; - sector_calculateFloor(sector, origin.y, &floorHeight, &ceilHeight); - if (floorHeight < y0 || ceilHeight > y1) - { - continue; - } - ///////////////////////////////////////////// - // End of checks to pull out of the loop. - ///////////////////////////////////////////// - - s32 objCapacity = curSector->objectCapacity; - s32 objCount = curSector->objectCount; - for (s32 objListIndex = 0, objIndex = 0; objIndex < objCount && objListIndex < objCapacity; objListIndex++) - { - SecObject* obj = curSector->objectList[objListIndex]; - if (!obj) { continue; } - - objIndex++; - if (skipObj && skipObj == obj) { continue; } - if (!(obj->entityFlags & entityFlags)) { continue; } - if (obj->posWS.x < x0 || obj->posWS.x > x1 || obj->posWS.z < z0 || obj->posWS.z > z1 || obj->posWS.y < y0 || obj->posWS.y > y1) - { - continue; - } - - RSector* curSector = sector; - RWall* hitWall = collision_wallCollisionFromPath(sector, origin.x, origin.z, obj->posWS.x, obj->posWS.z); - while (hitWall && curSector && curSector != obj->sector) - { - curSector = hitWall->nextSector; - if (curSector) - { - if (curSector->floorHeight - curSector->ceilingHeight < HALF_16) - { - break; - } - hitWall = collision_pathWallCollision(curSector); - } - } - - if (curSector == obj->sector) - { - return JTRUE; - } - } - } - return JFALSE; - } - - // Call the effectFunc() for each object within 'range' of point (x,y,z). This will only be called for objects in range and that have a valid collision path. - // Note the collision path is 3D (XYZ), in that it takes into account collision based on height. - void collision_effectObjectsInRange3D(RSector* startSector, fixed16_16 range, vec3_fixed origin, CollisionEffectFunc effectFunc, SecObject* excludeObj, u32 entityFlags) - { - const fixed16_16 x0 = origin.x - range; - const fixed16_16 y0 = origin.y - range; - const fixed16_16 z0 = origin.z - range; - - const fixed16_16 x1 = origin.x + range; - const fixed16_16 y1 = origin.y + range; - const fixed16_16 z1 = origin.z + range; - - const fixed16_16 secHeightThreshold = origin.y - COL_SEC_HEIGHT_OFFSET; - RSector* sector = s_levelState.sectors; - for (u32 i = 0; i < s_levelState.sectorCount; i++, sector++) - { - // Checks the start sector, should be pulled out of the loop. - if (x0 > startSector->boundsMax.x || x1 < startSector->boundsMin.x || z0 > startSector->boundsMax.z || z1 < startSector->boundsMin.z) - { - continue; - } - - fixed16_16 floor, ceil; - sector_calculateFloor(sector, origin.y, &floor, &ceil); - if (y0 > floor || y1 < ceil) { continue; } - // End of start sector check. - - for (s32 objIndex = 0, objListIndex = 0; objIndex < sector->objectCount && objListIndex < sector->objectCapacity; objListIndex++) - { - SecObject* obj = sector->objectList[objListIndex]; - if (!obj) { continue; } - objIndex++; - - if (excludeObj && excludeObj == obj) { continue; } - if (!(obj->entityFlags & entityFlags)) { continue; } - if (obj->posWS.x < x0 || obj->posWS.x > x1 || obj->posWS.z < z0 || obj->posWS.z > z1 || obj->posWS.y < y0 || obj->posWS.y > y1) - { - continue; - } - - JBool canHit = collision_lineOfSight(startSector, obj->sector, origin, obj->posWS, WF3_CANNOT_FIRE_THROUGH); - if (!canHit) - { - vec3_fixed topPos = { obj->posWS.x, obj->posWS.y - obj->worldHeight, obj->posWS.z }; - canHit = collision_lineOfSight(startSector, obj->sector, origin, topPos, WF3_CANNOT_FIRE_THROUGH); - } - // Finally the object can be hit, so call the effect function. - if (canHit) - { - effectFunc(obj); - } - } // Object Loop. - } // Sector loop. - } - - // Call the effectFunc() for each object within 'range' of point (x,y,z). This will only be called for objects in range and that have a valid collision path. - // Note the collision path is 2D (XZ) but cannot pass through sectors with a gap smaller than 0.5 units. - void collision_effectObjectsInRangeXZ(RSector* startSector, fixed16_16 range, vec3_fixed origin, CollisionEffectFunc effectFunc, SecObject* excludeObj, u32 entityFlags) - { - if (!startSector) - { - return; - } - - const fixed16_16 x0 = origin.x - range; - const fixed16_16 y0 = origin.y - range; - const fixed16_16 z0 = origin.z - range; - - const fixed16_16 x1 = origin.x + range; - const fixed16_16 y1 = origin.y + range; - const fixed16_16 z1 = origin.z + range; - - const fixed16_16 secHeightThreshold = origin.y - COL_SEC_HEIGHT_OFFSET; - RSector* sector = s_levelState.sectors; - for (u32 i = 0; i < s_levelState.sectorCount; i++, sector++) - { - // Checks the start sector, should be pulled out of the loop. - if (x0 > startSector->boundsMax.x || x1 < startSector->boundsMin.x || z0 > startSector->boundsMax.z || z1 < startSector->boundsMin.z) - { - continue; - } - fixed16_16 floor, ceil; - sector_calculateFloor(startSector, origin.y, &floor, &ceil); - if (y0 > floor || y1 < ceil) - { - continue; - } - // End of start sector check. - - for (s32 objIndex = 0, objListIndex = 0; objIndex < sector->objectCount && objListIndex < sector->objectCapacity; objListIndex++) - { - SecObject* obj = sector->objectList[objListIndex]; - if (!obj) { continue; } - objIndex++; - - if (excludeObj && excludeObj == obj) { continue; } - if (!(obj->entityFlags & entityFlags)) { continue; } - if (obj->posWS.x < x0 || obj->posWS.x > x1 || obj->posWS.z < z0 || obj->posWS.z > z1 || obj->posWS.y < y0 || obj->posWS.y > y1) - { - continue; - } - - fixed16_16 dx = obj->posWS.x - origin.x; - fixed16_16 dz = obj->posWS.z - origin.z; - RWall* hitWall = nullptr; - if (dx || dz) - { - s_col_path.x0 = origin.x; - s_col_path.z0 = origin.z; - s_col_path.x1 = obj->posWS.x; - s_col_path.z1 = obj->posWS.z; - s_collisionFrameWall++; - hitWall = collision_pathWallCollision(startSector); - } - - RSector* nextSector = startSector; - while (hitWall && nextSector && nextSector != obj->sector) - { - nextSector = hitWall->nextSector; - if (nextSector) - { - const fixed16_16 height = nextSector->floorHeight - nextSector->ceilingHeight; - if (height < c_minTraversableOpening) - { - break; - } - hitWall = collision_pathWallCollision(nextSector); - } - } - - // If there is a clear path from the source position to the object in range, call the specified function. - if (nextSector == obj->sector) - { - effectFunc(obj); - } - } // Object Loop. - } // Sector Loop. - } - - static RSector* s_hcolSector; - static vec3_fixed s_hcolDstPos; - static vec3_fixed s_hcolSrcPos; - static SecObject* s_hcolObj; - - void handleCollisionResponseSimple(fixed16_16 dirX, fixed16_16 dirZ, fixed16_16* moveX, fixed16_16* moveZ) - { - fixed16_16 proj = mul16(*moveX, dirX) + mul16(*moveZ, dirZ); - *moveX = mul16(proj, dirX); - *moveZ = mul16(proj, dirZ); - } - - // Returns JTRUE if there is no collision. - JBool handleCollision(CollisionInfo* colInfo) - { - SecObject* obj = colInfo->obj; - RWall* colWall = nullptr; - s32 b = 0; - SecObject* colObj = nullptr; - s_hcolSector = obj->sector; - RSector* curSector = s_hcolSector; - s_hcolSrcPos = obj->posWS; - - s_hcolObj = obj; - s_hcolDstPos.x = s_hcolSrcPos.x + colInfo->offsetX; - s_hcolDstPos.y = s_hcolSrcPos.y + colInfo->offsetY; - s_hcolDstPos.z = s_hcolSrcPos.z + colInfo->offsetZ; - - fixed16_16 top = s_hcolSrcPos.y - colInfo->height; - fixed16_16 bot = s_hcolSrcPos.y - colInfo->botOffset; - - colInfo->responseStep = JFALSE; - fixed16_16 yMax = (colInfo->flags & 1) ? (s_hcolSrcPos.y + COL_INFINITY) : (s_hcolSrcPos.y + colInfo->yPos); - colInfo->flags &= ~1; - - // Cross walls until the collision path hits something solid. - // Build a list of crossed walls in order to send INF events later. - // Note the number is based on the stack allocations, i.e. the next used offset is 0x80 and the size is 4 per element. - RWall* wallCrossList[32]; - RWall* wall = collision_wallCollisionFromPath(curSector, s_hcolSrcPos.x, s_hcolSrcPos.z, s_hcolDstPos.x, s_hcolDstPos.z); - s32 wallCrossCount = 0; - while (wall) - { - RSector* next = wall->nextSector; - if (next && !(wall->flags3 & WF3_SOLID_WALL)) - { - if ((s_hcolObj->entityFlags & ETFLAG_AI_ACTOR) && (wall->flags3 & WF3_PLAYER_WALK_ONLY)) - { - break; - } - - fixed16_16 ceilHeight, floorHeight; - sector_getObjFloorAndCeilHeight(next, s_hcolSrcPos.y, &floorHeight, &ceilHeight); - - if (floorHeight < bot || floorHeight > yMax || ceilHeight > top) - { - break; - } - - wallCrossList[wallCrossCount++] = wall; - wall = collision_pathWallCollision(next); - curSector = next; - } - else - { - break; - } - } - - // Collision above hit a solid wall. - if (wall) - { - colInfo->responseStep = JTRUE; - colInfo->responseDir.x = wall->wallDir.x; - colInfo->responseDir.z = wall->wallDir.z; - - vec2_fixed* w0 = wall->w0; - colInfo->responsePos.x = w0->x; - colInfo->responsePos.z = w0->z; - colInfo->responseAngle = wall->angle; - - s_hcolDstPos.x = s_hcolSrcPos.x; - s_hcolDstPos.z = s_hcolSrcPos.z; - - curSector = s_hcolSector; - colWall = wall; - } - else if (colInfo->width) - { - s_colDstPosX = s_hcolDstPos.x; - s_colDstPosY = s_hcolDstPos.y; - s_colDstPosZ = s_hcolDstPos.z; - s_colWidth = colInfo->width; - - s_colSrcPosX = s_hcolSrcPos.x; - s_colSrcPosY = s_hcolSrcPos.y; - s_colSrcPosZ = s_hcolSrcPos.z; - - s_colHeightBase = s_hcolObj->worldHeight; - s_colBottom = bot; - s_colTop = top; - s_colY1 = yMax; - - s_colWall0 = wall; - s_colObj1.wall = wall; - s_colHeight = colInfo->height; - if (s_hcolObj->entityFlags & ETFLAG_PLAYER) - { - s_colObject.obj = s_hcolObj; - } - else - { - s_colObject.wall = wall; - } - - if (!col_computeCollisionResponse(curSector, 0)) - { - colWall = s_colWall0; - colObj = s_collidedObj; - // Rewind the destination position to the start. - s_hcolDstPos.x = s_hcolSrcPos.x; - s_hcolDstPos.z = s_hcolSrcPos.z; - colInfo->responseStep = s_colResponseStep; - colInfo->responseDir = s_colResponseDir; - colInfo->responsePos = s_colResponsePos; - colInfo->responseAngle = s_colResponseAngle; - - curSector = s_hcolSector; - } - } - - if (curSector != s_hcolSector) - { - sector_addObject(curSector, s_hcolObj); - } - - // Update the object XZ position. - s_hcolObj->posWS.x = s_hcolDstPos.x; - s_hcolObj->posWS.z = s_hcolDstPos.z; - - // Determine the floor and ceiling height for the current sector based on the object position. - fixed16_16 floorHeight, ceilHeight; - sector_getObjFloorAndCeilHeight(s_hcolObj->sector, s_hcolSrcPos.y, &floorHeight, &ceilHeight); - - // Clip the y position to the floor and ceiling heights. - top = s_hcolDstPos.y - colInfo->height; - if (top <= ceilHeight) // is the top clipped by the ceiling? - { - // The object collides with the ceiling. - s_hcolDstPos.y = ceilHeight + colInfo->height; - } - else if (s_hcolDstPos.y > floorHeight) - { - // The object collides with the floor. - s_hcolDstPos.y = floorHeight; - } - s_hcolObj->posWS.y = s_hcolDstPos.y; - - // These values are probably filled in at 2346a6, 23474f, and/or 23487f - which need to be figured out first. - colInfo->wall = colWall; - colInfo->u24 = b; - colInfo->collidedObj = colObj; - if (colWall || b || colObj) - { - return JFALSE; - } - - // Go through all passable walls the object crossed and send cross line events. - for (; wallCrossCount; wallCrossCount--) - { - RWall* wall = wallCrossList[wallCrossCount - 1]; - inf_triggerWallEvent(wall, s_hcolObj, INF_EVENT_CROSS_LINE_FRONT); - - // Note: This is actually a bug... since inf_triggerWallEvent() automatically calls the event*2 on the backside - // This not only causes that to be called twice but calls INF_EVENT_ENTER_SECTOR on wall. - // This doesn't seem to hurt things but I doubt it was actually intended and lead to odd behaviors. - // This should not be called here (but it is in the original Dark Forces code). - if (wall->mirrorWall) - { - inf_triggerWallEvent(wall->mirrorWall, s_hcolObj, INF_EVENT_CROSS_LINE_BACK); - } - } - return JTRUE; - } - - //////////////////////////////////////////////////////// - // Internal - //////////////////////////////////////////////////////// - IntersectionResult pathIntersectsWall(ColPath* path, RWall* wall) - { - s_col_pathX0 = path->x0; - s_col_pathX1 = path->x1; - s_col_pathZ0 = path->z0; - s_col_pathZ1 = path->z1; - - vec2_fixed* v0 = wall->w0; - s_col_wallX0 = v0->x; - s_col_wallZ0 = v0->z; - - vec2_fixed* v1 = wall->w1; - s_col_wallX1 = v1->x; - s_col_wallZ1 = v1->z; - - s_col_curWall = wall; - s_col_pathDx = s_col_pathX1 - s_col_pathX0; - s_col_intersect = NO_INTERSECT; - s_col_wallDx = s_col_wallX0 - s_col_wallX1; - if (s_col_pathDx < 0) - { - s_col_adjPathX1 = s_col_pathX0; - s_col_adjPathX0 = s_col_pathX1; - } - else - { - s_col_adjPathX0 = s_col_pathX0; - s_col_adjPathX1 = s_col_pathX1; - } - if (s_col_wallDx > 0 && (s_col_adjPathX1 < s_col_wallX1 || s_col_wallX0 < s_col_adjPathX0)) - { - return NO_INTERSECT; - } - else if (s_col_wallDx <= 0 && (s_col_adjPathX1 < s_col_wallX0 || s_col_wallX1 < s_col_adjPathX0)) - { - return NO_INTERSECT; - } - - s_col_pathDz = s_col_pathZ1 - s_col_pathZ0; - s_col_wallDz = s_col_wallZ0 - s_col_wallZ1; - if (s_col_pathDz < 0) - { - s_col_adjPathZ1 = s_col_pathZ0; - s_col_adjPathZ0 = s_col_pathZ1; - } - else - { - s_col_adjPathZ0 = s_col_pathZ0; - s_col_adjPathZ1 = s_col_pathZ1; - } - - if (s_col_wallDz > 0 && s_col_adjPathZ1 < s_col_wallZ1) - { - return NO_INTERSECT; - } - if (s_col_wallZ0 < s_col_adjPathZ0 && (s_col_adjPathZ1 < s_col_wallZ0 || s_col_wallZ1 < s_col_adjPathZ0)) - { - return NO_INTERSECT; - } - - s_col_XOffset = s_col_pathX0 - s_col_wallX0; - s_col_ZOffset = s_col_pathZ0 - s_col_wallZ0; - s_col_intersectNum = mul16(s_col_wallDz, s_col_XOffset) - mul16(s_col_wallDx, s_col_ZOffset); - s_col_intersectDen = mul16(s_col_pathDz, s_col_wallDx) - mul16(s_col_pathDx, s_col_wallDz); - - if (s_col_intersectDen <= 0 && (s_col_intersectNum > 0 || s_col_intersectNum < s_col_intersectDen)) - { - return NO_INTERSECT; - } - else if (s_col_intersectDen > 0 && s_col_intersectDen > s_col_intersectNum) - { - return NO_INTERSECT; - } - - s_col_intersectNum2 = mul16(s_col_pathDx, s_col_ZOffset) - mul16(s_col_pathDz, s_col_XOffset); - if (s_col_intersectDen > 0 && s_col_intersectNum2 > s_col_intersectDen) - { - return NO_INTERSECT; - } - if (s_col_intersectNum2 > 0 || s_col_intersectNum2 < s_col_intersectDen) - { - return NO_INTERSECT; - } - if (s_col_intersectDen == 0) - { - return NO_INTERSECT; - } - - s_col_intersect = INTERSECT; - return INTERSECT; - } - - vec2_fixed* computeIntersectPos() - { - if (s_col_intersect == INTERSECT) - { - s_col_intersectParam = div16(s_col_intersectNum, s_col_intersectDen); - s_col_intersectPos.x = s_col_pathX0 + mul16(s_col_intersectParam, s_col_pathDx); - s_col_intersectPos.z = s_col_pathZ0 + mul16(s_col_intersectParam, s_col_pathDz); - } - else - { - s_col_intersectPos.x = 0; - s_col_intersectPos.z = 0; - } - return &s_col_intersectPos; - } - - // This seems to get the first collision hit, regardless if it is the closest. - // This means projectile/object collisions may get wonky with a high time interval (low framerate). - SecObject* internal_getObjectCollision() - { - for (; s_colObjCount > 0; s_colObjList++) - { - SecObject* obj = *s_colObjList; - if (!obj) { continue; } - - s_colObjCount--; - if (!obj->worldWidth || obj == s_colObjPrev) { continue; } - - if (!(obj->entityFlags & s_collision_excludeEntityFlags) && !(obj->entityFlags & ETFLAG_PICKUP)) - { - // Check height overlap. - if (obj->worldHeight >= 0 && (s_colObjMinY > obj->posWS.y || obj->posWS.y - obj->worldHeight > s_colObjMaxY)) - { - continue; - } - else if (obj->worldHeight < 0 && (obj->posWS.y > s_colObjMaxY || obj->posWS.y - obj->worldHeight < s_colObjMinY)) - { - // Since height < 0, this is the same as y + abs(height), i.e. this is hanging from the ceiling. - continue; - } - - s_colObjOffsetX = obj->posWS.x - s_colObjX0; - s_colObjOffsetZ = obj->posWS.z - s_colObjZ0; - s_colWallV0.x = mul16(s_colObjOffsetX, s_colObjDirZ) - mul16(s_colObjOffsetZ, s_colObjDirX); - if (TFE_Jedi::abs(s_colWallV0.x) > obj->worldWidth) { continue; } - - s_colWallV0.z = mul16(s_colObjOffsetX, s_colObjDirX) + mul16(s_colObjOffsetZ, s_colObjDirZ); - - fixed16_16 pathRadius = s_colObjMove + obj->worldWidth; - // the projectile hasn't move far enough to hit the object. - if (pathRadius < s_colWallV0.z) { continue; } - // the projectile is past the object far enough that it doesn't hit. - if (-obj->worldWidth > s_colWallV0.z) { continue; } - - s_colObjOverlap = s_colWallV0.z - obj->worldWidth; - return obj; - } - } - return nullptr; - } - - // Treat walls with flags3 that includes 'exclWallFlags3' as solid. - JBool collision_canHitObject(RSector* startSector, RSector* endSector, vec3_fixed p0, vec3_fixed p1, u32 exclWallFlags3) - { - s_collision_wallHit = JFALSE; - fixed16_16 approxDist = distApprox(p0.x, p0.z, p1.x, p1.z); - fixed16_16 dy = p1.y - p0.y; - fixed16_16 yStep = approxDist ? div16(dy, approxDist) : dy; - - RSector* sector = startSector; - RWall* hitWall = nullptr; - - // If there is no horizontal movement, there is no possible wall collision. - if (p1.x - p0.x != 0 || p1.z - p0.z != 0) - { - s_col_path.x0 = p0.x; - s_col_path.z0 = p0.z; - s_col_path.x1 = p1.x; - s_col_path.z1 = p1.z; - s_collisionFrameWall++; - hitWall = collision_pathWallCollision(sector); - } - while (hitWall) - { - RSector* nextSector = hitWall->nextSector; - if (!nextSector) - { - s_collision_wallHit = JTRUE; - return JFALSE; - } - if (hitWall->flags3 & exclWallFlags3) - { - return JFALSE; - } - fixed16_16 yHit = p0.y + mul16(s_col_hitDist, yStep); - RSector* hitSector = hitWall->sector; - if (yHit < hitSector->ceilingHeight || yHit < nextSector->ceilingHeight || yHit > hitSector->floorHeight || yHit > nextSector->floorHeight) - { - return JFALSE; - } - sector = nextSector; - hitWall = collision_pathWallCollision(nextSector); - } - return (sector == endSector) ? JTRUE : JFALSE; - } - - fixed16_16 computeYIntersect(const vec3_fixed p0, const vec3_fixed p1, f32 scaleXZ) - { - const f32 dx = fixed16ToFloat(p1.x - p0.x); - const f32 dy = fixed16ToFloat(p1.y - p0.y); - const f32 dz = fixed16ToFloat(p1.z - p0.z); - const f32 u = sqrtf(dx*dx + dz * dz) * scaleXZ; - return p0.y + floatToFixed16(u * dy); - } - - bool hitSign(RWall* hitWall, fixed16_16 paramPos, fixed16_16 yPos) - { - fixed16_16 baseHeight = 0; - fixed16_16 uOffset = 0; - switch (hitWall->drawFlags) - { - case WDF_MIDDLE: - { - baseHeight = hitWall->sector->floorHeight; - uOffset = hitWall->midOffset.x; - } break; - case WDF_TOP: - { - baseHeight = hitWall->nextSector->ceilingHeight; - uOffset = hitWall->topOffset.x; - } break; - case WDF_BOT: - case WDF_TOP_AND_BOT: - { - baseHeight = hitWall->sector->floorHeight; - uOffset = hitWall->botOffset.x; - } break; - } - - if (yPos) - { - fixed16_16 base = baseHeight + (hitWall->signOffset.z >> 3); - // base + 0.5 - fixed16_16 y0 = base + HALF_16; - // base - texHeight/8 - 0.5 - fixed16_16 y1 = base - ((*hitWall->signTex)->height << 13) - HALF_16; - if (y0 < yPos || y1 > yPos) - { - return false; - } - } - - if (paramPos) - { - fixed16_16 base = (hitWall->signOffset.x - uOffset) >> 3; - // base - 0.5 - fixed16_16 left = base - HALF_16; - // base + texWidth/8 + 0.5 - fixed16_16 right = base + ((*hitWall->signTex)->width << 13) + HALF_16; - if (paramPos < left || paramPos > right) - { - return false; - } - } - - return true; - } - - RayHitInfo collision_rayCast3d(RSector* sector, vec3_fixed p0, vec3_fixed p1, bool stopAtMidTex) - { - RayHitInfo outRayHit = { RHit_None, nullptr, nullptr }; - fixed16_16 ceilHeight, floorHeight; - - // Use existing code to raytrace through the scene. - RWall* wall = collision_wallCollisionFromPath(sector, p0.x, p0.z, p1.x, p1.z); - - // No walls are hit, so just test against the floor and ceiling in the current sector. - if (!wall) - { - fixed16_16 y0 = p0.y; - fixed16_16 y1 = p1.y; - floorHeight = sector->floorHeight; - ceilHeight = sector->ceilingHeight; - - fixed16_16 nextY = y1; - if (y1 >= floorHeight) - { - outRayHit.hit = RHit_Floor; - outRayHit.sector = sector; - } - else if (y1 <= ceilHeight) - { - outRayHit.hit = RHit_Ceiling; - outRayHit.sector = sector; - } - return outRayHit; - } - - // Compute the ray length and direction using floats to avoid overflow. - const vec2_float offset = { fixed16ToFloat(p1.x) - fixed16ToFloat(p0.x), - fixed16ToFloat(p1.z) - fixed16ToFloat(p0.z) }; - const f32 lenXZ = sqrtf(offset.x * offset.x + offset.z * offset.z); - - if (lenXZ < FLT_EPSILON) { return outRayHit; } - const f32 scaleXZ = 1.0f / lenXZ; - - // Trace through the sectors. - while (wall) - { - fixed16_16 bot, top; - if (wall->nextSector && (!(wall->flags1 & WF1_ADJ_MID_TEX) || !stopAtMidTex)) - { - // Determine the opening in the wall. - wall_getOpeningHeightRange(wall, &top, &bot); - - // Determine if the ray trivially passes through. - if (p0.y <= bot && p0.y >= top && p1.y <= bot && p1.y >= top) - { - sector = wall->nextSector; - wall = collision_pathWallCollision(sector); - continue; - } - } - else - { - // There is no opening in the wall. - bot = -SEC_SKY_HEIGHT; - top = SEC_SKY_HEIGHT; - } - - collision_getHitPoint(&p1.x, &p1.z); - - const fixed16_16 y = computeYIntersect(p0, p1, scaleXZ); - floorHeight = sector->floorHeight; - ceilHeight = sector->ceilingHeight; - - if (y >= floorHeight) - { - outRayHit.hit = RHit_Floor; - outRayHit.sector = sector; - break; - } - else if (y <= ceilHeight) - { - outRayHit.hit = RHit_Ceiling; - outRayHit.sector = sector; - break; - } - - // Check to see if it can pass through the opening. - if (y <= bot && y >= top) - { - sector = wall->nextSector; - wall = collision_pathWallCollision(sector); - } - // Wall Hit! - else - { - outRayHit.hit = RHit_WallMid; - if (wall->signTex && *wall->signTex) - { - fixed16_16 distFromW0 = vec2Length(wall->w0->x - p1.x, wall->w0->z - p1.z); - if (hitSign(wall, distFromW0, y)) - { - outRayHit.hit = RHit_WallSign; - outRayHit.sector = sector; - outRayHit.wall = wall; - break; - } - } - - if (wall->nextSector && wall->nextSector->ceilingHeight > sector->ceilingHeight && y < wall->nextSector->ceilingHeight) - { - outRayHit.hit = RHit_WallTop; - } - else if (wall->nextSector && wall->nextSector->floorHeight < sector->floorHeight && y > wall->nextSector->floorHeight) - { - outRayHit.hit = RHit_WallBot; - } - else if (wall->nextSector) // Is this a transparent mid texture? - { - outRayHit.hit = RHit_WallMid_Trans; - } - - outRayHit.sector = sector; - outRayHit.wall = wall; - break; - } - } - return outRayHit; - } - - JBool collision_propogateExplosion(RSector* sector) - { - message_sendToSector(sector, nullptr, INF_EVENT_EXPLOSION, MSG_TRIGGER); - return JTRUE; - } - - JBool inf_handleExplosion(RSector* sector, fixed16_16 x, fixed16_16 z, fixed16_16 range) - { - message_sendToSector(sector, nullptr, INF_EVENT_EXPLOSION, MSG_TRIGGER); - - s_colDstPosX = x; - s_colDstPosZ = z; - s_colWidth = range; - s_objCollisionFunc = collision_propogateExplosion; - s_objCollisionProxFunc = nullptr; - s_colDoubleRadius = range * 2; - s_collisionFrameSector += 2; - - return handleCollisionFunc(sector); - } -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Collision/collision.h b/components/darkforces/tfe/TFE_Jedi/Collision/collision.h deleted file mode 100644 index 6110424c..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Collision/collision.h +++ /dev/null @@ -1,125 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Collision System -// Classic Dark Forces (DOS) Jedi derived Collision system. This is -// the core collision system used by Dark Forces. -// -// Copyright note: -// While the project as a whole is licensed under GPL-2.0, some of the -// code under TFE_Collision/ was derived from reverse-engineered -// code from "Dark Forces" (DOS) which is copyrighted by LucasArts. -// -// I consider the reverse-engineering to be "Fair Use" - a means of -// supporting the games on other platforms and to improve support on -// existing platforms without claiming ownership of the games -// themselves or their IPs. -// -// That said using this code in a commercial project is risky without -// permission of the original copyright holders (LucasArts). -////////////////////////////////////////////////////////////////////// -#include -#include -#include - -struct RSector; -struct SecObject; -struct RWall; - -struct CollisionInterval -{ - fixed16_16 x0; - fixed16_16 x1; - fixed16_16 y0; - fixed16_16 y1; - fixed16_16 z0; - fixed16_16 z1; - fixed16_16 move; - fixed16_16 dirX; - fixed16_16 dirZ; -}; - -struct CollisionInfo -{ - SecObject* obj; - fixed16_16 offsetX; - fixed16_16 offsetY; - fixed16_16 offsetZ; - fixed16_16 botOffset; - fixed16_16 yPos; - fixed16_16 height; - s32 unused; - - RWall* wall; - s32 u24; - SecObject* collidedObj; - - fixed16_16 width; - u32 flags; - JBool responseStep; - vec2_fixed responseDir; - vec2_fixed responsePos; - angle14_32 responseAngle; -}; - -struct ColObject -{ - union - { - SecObject* obj; - RSector* sector; - RWall* wall; - void* ptr; - }; -}; - -enum RayHitType -{ - RHit_None = 0, - RHit_Floor, - RHit_Ceiling, - RHit_WallMid, - RHit_WallMid_Trans, - RHit_WallBot, - RHit_WallTop, - RHit_WallSign, -}; -struct RayHitInfo -{ - RayHitType hit; - RWall* wall; - RSector* sector; -}; - -typedef void(*CollisionEffectFunc)(SecObject*); - -#define COL_INFINITY FIXED(9999) -#define COL_SEC_HEIGHT_OFFSET FIXED(2) - -namespace TFE_Jedi -{ - void collision_getHitPoint(fixed16_16* x, fixed16_16* z); - fixed16_16 collision_getHitDistance(); - RSector* collision_tryMove(RSector* sector, fixed16_16 x0, fixed16_16 z0, fixed16_16 x1, fixed16_16 z1); - RSector* collision_moveObj(SecObject* obj, fixed16_16 dx, fixed16_16 dz); - RWall* collision_pathWallCollision(RSector* sector); - RWall* collision_wallCollisionFromPath(RSector* sector, fixed16_16 srcX, fixed16_16 srcZ, fixed16_16 dstX, fixed16_16 dstZ); - JBool collision_canHitObject(RSector* startSector, RSector* endSector, vec3_fixed p0, vec3_fixed p1, u32 exclWallFlags3); - - SecObject* collision_getObjectCollision(RSector* sector, CollisionInterval* interval, SecObject* prevObj); - JBool collision_isAnyObjectInRange(RSector* sector, fixed16_16 radius, vec3_fixed origin, SecObject* skipObj, u32 entityFlags); - - void collision_effectObjectsInRange3D(RSector* startSector, fixed16_16 range, vec3_fixed origin, CollisionEffectFunc effectFunc, SecObject* excludeObj, u32 entityFlags); - void collision_effectObjectsInRangeXZ(RSector* startSector, fixed16_16 range, vec3_fixed origin, CollisionEffectFunc effectFunc, SecObject* excludeObj, u32 entityFlags); - - JBool handleCollision(CollisionInfo* colInfo); - void handleCollisionResponseSimple(fixed16_16 dirX, fixed16_16 dirZ, fixed16_16* moveX, fixed16_16* moveZ); - - JBool inf_handleExplosion(RSector* sector, fixed16_16 x, fixed16_16 z, fixed16_16 range); - RayHitInfo collision_rayCast3d(RSector* sector, vec3_fixed p0, vec3_fixed p1, bool stopAtMidTex); - - // Variables - extern fixed16_16 s_colObjOverlap; - extern s32 s_collisionFrameWall; - extern JBool s_collision_wallHit; - extern u32 s_collision_excludeEntityFlags; -} diff --git a/components/darkforces/tfe/TFE_Jedi/IMuse/imConst.cpp b/components/darkforces/tfe/TFE_Jedi/IMuse/imConst.cpp deleted file mode 100644 index 3e8c4ca2..00000000 --- a/components/darkforces/tfe/TFE_Jedi/IMuse/imConst.cpp +++ /dev/null @@ -1,20 +0,0 @@ -#include "imConst.h" -#include "imuse.h" -#include -#include - -namespace TFE_Jedi -{ - // In the original code, there are two arrays of midi message size, but the values are exactly the same. - const u8 c_midiMsgSize[] = - { - 3, 3, 3, 3, 2, 2, 3, 1, - }; - const u32 c_channelMask[MIDI_CHANNEL_COUNT] = - { - FLAG_BIT( 0), FLAG_BIT( 1), FLAG_BIT( 2), FLAG_BIT( 3), - FLAG_BIT( 4), FLAG_BIT( 5), FLAG_BIT( 6), FLAG_BIT( 7), - FLAG_BIT( 8), FLAG_BIT( 9), FLAG_BIT(10), FLAG_BIT(11), - FLAG_BIT(12), FLAG_BIT(13), FLAG_BIT(14), FLAG_BIT(15) - }; -} // namespace TFE_Jedi diff --git a/components/darkforces/tfe/TFE_Jedi/IMuse/imConst.h b/components/darkforces/tfe/TFE_Jedi/IMuse/imConst.h deleted file mode 100644 index 3dacd386..00000000 --- a/components/darkforces/tfe/TFE_Jedi/IMuse/imConst.h +++ /dev/null @@ -1,99 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// iMuse System -// The IMuse system used by Dark Forces. -// -// Copyright note: -// While the project as a whole is licensed under GPL-2.0, some of the -// code under TFE_Jedi/ was derived from reverse-engineered -// code from "Dark Forces" (DOS) which is copyrighted by LucasArts. -// The original renderer is contained in RClassic_Fixed/ and the -// RClassic_Float/ and RClassic_GPU/ sub-renderers are derived from -// that code. -// -// I consider the reverse-engineering to be "Fair Use" - a means of -// supporting the games on other platforms and to improve support on -// existing platforms without claiming ownership of the games -// themselves or their IPs. -// -// That said using this code in a commercial project is risky without -// permission of the original copyright holders (LucasArts). -////////////////////////////////////////////////////////////////////// -#include -#include - -// Debug/Log Message Verbosity Settings. -#define IM_SHOW_DEBUG_MSG 0 // High frequency debug messages, these are only written out to the console or debug output. -#define IM_SHOW_LOG_MSG 0 // IMuse messages, usually the original DOS messages. A few new messages were added for TFE. -#define IM_SHOW_LOG_WARNING 1 // IMuse warnings, usually the original DOS messages. A few new warnings were added for TFE. -// IMuse errors are always enabled. They are usually the original DOS messages. A few new errors were added for TFE. - -enum iMuseConst -{ - imMaxVolume = 127, // Maximum allowed volume, correlated with imVolumeShift. - imMaxPriority = 127, - imPanCenter = 64, - imPanMax = 127, - imVolumeShift = 7, // Amount to shift when multiplying volumes. - imGetValue = -1, // Magic number to get values instead of set them. - imWildcard = -1, - imOutDrumChannel = 9, -}; - -// Time in iMuse is stored like the following: -// Where, generally, there are 480 ticks/beat and 4 beats/measure. -// --------------------------------------------------------- -// | 12-bits | 4-bits | 16-bits | -// --------------------------------------------------------- -// | offset=20-bits | offset=16-bits | offset=0 bits | -// --------------------------------------------------------- -// | Measure (0 - 999) | Beat (0 - 11) | Tick (0 - 479) | -// --------------------------------------------------------- - -// Get Time -#define ImTime_getTicks(t) ((t) & 0xffff) -#define ImTime_getBeat(t) (((t) >> 16) & 0xf) -#define ImTime_getBeatFixed(t) ((t) & 0xf0000) -#define ImTime_getMeasure(t) ((t) >> 20) - -// Set Time -#define ImTime_setTick(t) (t) -#define ImTime_setBeat(b) ((b)<<16) -#define ImTime_setMeasure(m) ((m)<<20) - -// Null sound define -#define IM_NULL_SOUNDID 0 - -// DEBUGGING & LOGGING -// These debug messages are very verbose so should be disabled in release builds. -// Lower frequency messages that are kept in release use logWrite() directly. -#if IM_SHOW_DEBUG_MSG - #define IM_DBG_MSG(str, ...) TFE_System::debugWrite("IMuse", str, __VA_ARGS__) -#else - #define IM_DBG_MSG(str, ...) -#endif - -// Original messages from DOS and a few new errors added for TFE. -// Note, when enabled, these write to the console and log file. Dark Forces disables -// output from these messages but I have preserved them in TFE for debugging. -// Also note for TFE - errors are always written, less important or expected errors are relegated to warnings. -#define IM_LOG_ERR(str, ...) TFE_System::logWrite(LOG_ERROR, "iMuse", str, __VA_ARGS__) -#if IM_SHOW_LOG_MSG - #define IM_LOG_MSG(str, ...) TFE_System::logWrite(LOG_MSG, "iMuse", str, __VA_ARGS__) -#else - #define IM_LOG_MSG(str, ...) -#endif - -#if IM_SHOW_LOG_WARNING -#define IM_LOG_WRN(str, ...) TFE_System::logWrite(LOG_WARNING, "iMuse", str, __VA_ARGS__) -#else -#define IM_LOG_WRN(str, ...) -#endif - -namespace TFE_Jedi -{ - typedef s64 ImSoundId; - - extern const u8 c_midiMsgSize[]; - extern const u32 c_channelMask[MIDI_CHANNEL_COUNT]; -} // namespace TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/IMuse/imDigitalSound.cpp b/components/darkforces/tfe/TFE_Jedi/IMuse/imDigitalSound.cpp deleted file mode 100644 index fce185b7..00000000 --- a/components/darkforces/tfe/TFE_Jedi/IMuse/imDigitalSound.cpp +++ /dev/null @@ -1,809 +0,0 @@ -#include "imuse.h" -#include "imDigitalSound.h" -#include "imDigitalVolumeTable.h" -#include "imSoundFader.h" -#include "imTrigger.h" -#include "imList.h" -#include -#include -#include -#include -#include -#include - -namespace TFE_Jedi -{ -#ifdef TFE_ESPBOX - #define MAX_SOUND_CHANNELS 8 -#else - #define MAX_SOUND_CHANNELS 16 -#endif - #define DEFAULT_SOUND_CHANNELS 8 - #define AUDIO_BUFFER_SIZE 512 - - #define AUDIO_LOCK() TFE_Audio::lock() - #define AUDIO_UNLOCK() TFE_Audio::unlock() - - //////////////////////////////////////////////////// - // Structures - //////////////////////////////////////////////////// - struct ImWaveData; - - struct ImWaveSound - { - ImWaveSound* prev; - ImWaveSound* next; - ImWaveData* data; - ImSoundId soundId; - - s32 marker; - s32 group; - s32 priority; - s32 baseVolume; - - s32 volume; - s32 pan; - s32 detune; - s32 transpose; - - s32 detuneTrans; - s32 mailbox; - }; - - struct ImWaveData - { - ImWaveSound* sound; - s32 offset; - s32 chunkSize; - s32 baseOffset; - s32 chunkIndex; - }; - - ///////////////////////////////////////////////////// - // Internal State - ///////////////////////////////////////////////////// - atomic_s32 s_digitalPause; - - static ImWaveSound* s_imWaveSoundList = nullptr; - static ImWaveSound s_imWaveSound[MAX_SOUND_CHANNELS]; - static ImWaveData s_imWaveData[MAX_SOUND_CHANNELS]; - static u8 s_imWaveChunkData[48]; - static s32 s_imWaveMixCount = DEFAULT_SOUND_CHANNELS; - static s32 s_imWaveNanosecsPerSample; - static iMuseInitData* s_imDigitalData; - - // In DOS these are 8-bit outputs since that is what the driver is accepting. - // For TFE, floating-point audio output is used, so these convert to floating-point. -#ifdef TFE_ESPBOX - static s8 s_audioNormalizationMem[MAX_SOUND_CHANNELS * 256 + 4]; -#else - static f32 s_audioNormalizationMem[MAX_SOUND_CHANNELS * 256 + 4]; -#endif - // Normalizes the sum of all audio playback (16-bit) to a [-1,1) floating point value. - // The mapping can be addressed with negative values (i.e. s_audioNormalization[-16]), which is why - // it is built this way. -#ifdef TFE_ESPBOX - static s8* s_audioNormalization = &s_audioNormalizationMem[MAX_SOUND_CHANNELS * 128 + 4]; - static s8* s_audioDriverOut; -#else - static f32* s_audioNormalization = &s_audioNormalizationMem[MAX_SOUND_CHANNELS * 128 + 4]; - - static f32* s_audioDriverOut; -#endif - static s16 s_audioOut[AUDIO_BUFFER_SIZE + IM_AUDIO_OVERSAMPLE]; // Add 2 stereo samples from the next frame for interpolation. - static s32 s_audioOutSize; - static u8* s_audioData; - - extern s32 ImWrapValue(s32 value, s32 a, s32 b); - extern s32 ImGetGroupVolume(s32 group); - extern u8* ImInternalGetSoundData(ImSoundId soundId); - - ImWaveData* ImGetWaveData(s32 index); - void ImFreeWaveSound(ImWaveSound* sound); - s32 ImComputeAudioNormalizationInit(iMuseInitData* initData); - s32 ImComputeAudioNormalization(s32 waveMixCount); - s32 ImSetWaveParamInternal(ImSoundId soundId, s32 param, s32 value); - s32 ImGetWaveParamIntern(ImSoundId soundId, s32 param); - s32 ImFreeWaveSoundByIdIntern(ImSoundId soundId); - s32 ImStartDigitalSoundIntern(ImSoundId soundId, s32 priority, s32 chunkIndex); - s32 audioPlaySoundFrame(ImWaveSound* sound); - s32 audioWriteToDriver(f32 systemVolume); - - /////////////////////////////////////////////////////////// - // API - /////////////////////////////////////////////////////////// - s32 ImInitializeDigitalAudio(iMuseInitData* initData) - { - IM_DBG_MSG("TRACKS module..."); - if (initData->waveMixCount <= 0 || initData->waveMixCount > 16) - { - IM_LOG_ERR("%s", "TR: waveMixCount NULL or too big, defaulting to 4..."); - initData->waveMixCount = 4; - } - s_imWaveMixCount = initData->waveMixCount; - s_digitalPause = 0; - s_imWaveSoundList = nullptr; - - if (initData->waveSpeed == IM_WAVE_11kHz) // <- this is the path taken by Dark Forces DOS - { - // Nanoseconds per second / wave speed in Hz - // 1,000,000,000 / 11,000 - s_imWaveNanosecsPerSample = 90909; - } - else // IM_WAVE_22kHz - { - // Nanoseconds per second / wave speed in Hz - // 1,000,000,000 / 22,000 - s_imWaveNanosecsPerSample = 45454; - } - - ImWaveSound* sound = s_imWaveSound; - for (s32 i = 0; i < s_imWaveMixCount; i++, sound++) - { - sound->prev = nullptr; - sound->next = nullptr; - ImWaveData* data = ImGetWaveData(i); - sound->data = data; - data->sound = sound; - sound->soundId = IM_NULL_SOUNDID; - } - - TFE_Audio::setAudioThreadCallback(ImUpdateWave); - - return ImComputeAudioNormalizationInit(initData); - } - - void ImTerminateDigitalAudio() - { - ImFreeAllWaveSounds(); - TFE_Audio::setAudioThreadCallback(); - s_imWaveSoundList = nullptr; - } - - s32 ImSetDigitalChannelCount(s32 count) - { - if (count < 0 || count > MAX_SOUND_CHANNELS) - { - return imArgErr; - } - ImFreeAllWaveSounds(); - - AUDIO_LOCK(); - { - s_imWaveMixCount = count; - ImWaveSound* sound = s_imWaveSound; - for (s32 i = 0; i < s_imWaveMixCount; i++, sound++) - { - sound->prev = nullptr; - sound->next = nullptr; - ImWaveData* data = ImGetWaveData(i); - sound->data = data; - data->sound = sound; - sound->soundId = IM_NULL_SOUNDID; - } - } - AUDIO_UNLOCK(); - - return ImComputeAudioNormalization(count); - } - - s32 ImSetWaveParam(ImSoundId soundId, s32 param, s32 value) - { - s32 res = ImSetWaveParamInternal(soundId, param, value); - return res; - } - - s32 ImGetWaveParam(ImSoundId soundId, s32 param) - { - return ImGetWaveParamIntern(soundId, param); - } - - s32 ImStartDigitalSound(ImSoundId soundId, s32 priority) - { - return ImStartDigitalSoundIntern(soundId, priority, 0); - } - - void ImUpdateWave(f32* buffer, u32 bufferSize, f32 systemVolume) - { - // Prepare buffers. -#ifdef TFE_ESPBOX - s_audioDriverOut = (s8*)buffer; -#else - s_audioDriverOut = buffer; -#endif - s_audioOutSize = bufferSize; - assert(bufferSize * 2 <= AUDIO_BUFFER_SIZE); - memset(s_audioOut, 0, (2*bufferSize + IM_AUDIO_OVERSAMPLE) * sizeof(s16)); - - // Write sounds to s_audioOut. - ImWaveSound* sound = s_imWaveSoundList; - while (sound) - { - ImWaveSound* next = sound->next; - audioPlaySoundFrame(sound); - sound = next; - } - - // Convert s_audioOut to "driver" buffer. - audioWriteToDriver(systemVolume); - } - - s32 ImPauseDigitalSound() - { - s_digitalPause = 1; - return imSuccess; - } - - s32 ImResumeDigitalSound() - { - s_digitalPause = 0; - return imSuccess; - } - - //////////////////////////////////// - // Internal - //////////////////////////////////// - ImWaveData* ImGetWaveData(s32 index) - { - assert(index < MAX_SOUND_CHANNELS); - return &s_imWaveData[index]; - } - - s32 ImComputeAudioNormalization(s32 waveMixCount) - { - s32 volumeMidPoint = 128; - s32 tableSize = waveMixCount << 7; - for (s32 i = 0; i < tableSize; i++) - { - // Results for count ~= 8: (i=0) 0.0, 1.5, 2.5, 3.4, 4.4, 5.2, 6.3, 7.2, ... 127.1 (i = 1023). - s32 volumeOffset = ((waveMixCount * 127 * i) << 8) / (waveMixCount * 127 + (waveMixCount - 1)*i) + 128; - volumeOffset >>= 8; - - // These values are 8-bit in DOS, but converted to floating point for TFE. -#ifdef TFE_ESPBOX - s_audioNormalization[i] = (volumeMidPoint + volumeOffset) - 128; - s_audioNormalization[-i - 1] = (volumeMidPoint - volumeOffset - 1) - 128; -#else - s_audioNormalization[i] = f32(volumeMidPoint + volumeOffset) / 128.0f - 1.0f; - s_audioNormalization[-i - 1] = f32(volumeMidPoint - volumeOffset - 1) / 128.0f - 1.0f; -#endif - } - return imSuccess; - } - - s32 ImComputeAudioNormalizationInit(iMuseInitData* initData) - { - s_imDigitalData = initData; - return ImComputeAudioNormalization(initData->waveMixCount); - } - - s32 ImSetWaveParamInternal(ImSoundId soundId, s32 param, s32 value) - { - ImWaveSound* sound = s_imWaveSoundList; - while (sound) - { - if (sound->soundId == soundId) - { - if (param == soundGroup) - { - if (value >= 16) - { - return imArgErr; - } - sound->volume = ((sound->baseVolume + 1) * ImGetGroupVolume(value)) >> 7; - sound->group = value; - return imSuccess; - } - else if (param == soundPriority) - { - if (value > 127) - { - return imArgErr; - } - sound->priority = value; - return imSuccess; - } - else if (param == soundVol) - { - if (value > 127) - { - return imArgErr; - } - sound->baseVolume = value; - sound->volume = ((sound->baseVolume + 1) * ImGetGroupVolume(sound->group)) >> 7; - return imSuccess; - } - else if (param == soundPan) - { - if (value > 127) - { - return imArgErr; - } - sound->pan = value; - return imSuccess; - } - else if (param == soundDetune) - { - if (value < -9216 || value > 9216) - { - return imArgErr; - } - sound->detune = value; - sound->detuneTrans = sound->detune + (sound->transpose << 8); - return imSuccess; - } - else if (param == soundTranspose) - { - if (value < -12 || value > 12) - { - return imArgErr; - } - sound->transpose = value ? ImWrapValue(sound->transpose + value, -12, 12) : 0; - sound->detuneTrans = sound->detune + (sound->transpose << 8); - return imSuccess; - } - else if (param == soundMailbox) - { - sound->mailbox = value; - return imSuccess; - } - // Invalid Parameter - IM_LOG_ERR("TrSetParam() couldn't set param %lu...", param); - return imArgErr; - } - sound = sound->next; - } - return imInvalidSound; - } - - s32 ImGetWaveParamIntern(ImSoundId soundId, s32 param) - { - s32 soundCount = 0; - ImWaveSound* sound = s_imWaveSoundList; - while (sound) - { - if (sound->soundId == soundId) - { - if (param == soundType) - { - return imFail; - } - else if (param == soundPlayCount) - { - soundCount++; - } - else if (param == soundMarker) - { - return sound->marker; - } - else if (param == soundGroup) - { - return sound->group; - } - else if (param == soundPriority) - { - return sound->priority; - } - else if (param == soundVol) - { - return sound->baseVolume; - } - else if (param == soundPan) - { - return sound->pan; - } - else if (param == soundDetune) - { - return sound->detune; - } - else if (param == soundTranspose) - { - return sound->transpose; - } - else if (param == soundMailbox) - { - return sound->mailbox; - } - else if (param == waveStreamFlag) - { - return sound->data ? 1 : 0; - } - else - { - return imArgErr; - } - } - sound = sound->next; - } - return (param == soundPlayCount) ? soundCount : imInvalidSound; - } - - ImWaveSound* ImAllocWaveSound(s32 priority) - { - ImWaveSound* sound = s_imWaveSound; - ImWaveSound* newSound = nullptr; - for (s32 i = 0; i < s_imWaveMixCount; i++, sound++) - { - if (!sound->soundId) - { - return sound; - } - } - - AUDIO_LOCK(); - IM_DBG_MSG("ERR: no spare tracks..."); - s32 minPriority = 127; - ImWaveSound* minPrioritySound = nullptr; - sound = s_imWaveSoundList; - while (sound) - { - if (sound->priority <= minPriority) - { - minPriority = sound->priority; - minPrioritySound = sound; - } - sound = sound->next; - } - - newSound = nullptr; - if (minPrioritySound) - { - if (priority >= minPriority) - { - ImFreeWaveSound(minPrioritySound); - newSound = minPrioritySound; - } - } - - AUDIO_UNLOCK(); - return newSound; - } - - u8* ImGetChunkSoundData(s32 chunkIndex, s32 rangeMin, s32 rangeMax) - { - IM_LOG_ERR("Digital Sound chunk index should be zero in Dark Forces, but is %d.", chunkIndex); - assert(0); - return nullptr; - } - - s32 ImSeekToNextChunk(ImWaveData* data) - { - while (1) - { - u8* chunkData = s_imWaveChunkData; - u8* sndData = nullptr; - - if (data->chunkIndex) - { - sndData = ImGetChunkSoundData(data->chunkIndex, 0, 48); - if (!sndData) - { - sndData = ImGetChunkSoundData(data->chunkIndex, 0, 1); - } - if (!sndData) - { - return imNotFound; - } - } - else // chunkIndex == 0 - { - ImWaveSound* sound = data->sound; - sndData = ImInternalGetSoundData(sound->soundId); - if (!sndData) - { - if (sound->mailbox == 0) - { - sound->mailbox = 8; - } - IM_LOG_ERR("%s", "null sound addr in SeekToNextChunk()..."); - return imFail; - } - } - - memcpy(chunkData, sndData + data->offset, 48); - u8 id = *chunkData; - chunkData++; - - if (id == 0) - { - return imFail; - } - else if (id == 1) // found the next useful chunk. - { - s32 chunkSize = (chunkData[0] | (chunkData[1] << 8) | (chunkData[2] << 16)) - 2; - chunkData += 5; - - data->chunkSize = chunkSize; - if (chunkSize > 220000) - { - ImWaveSound* sound = data->sound; - if (sound->mailbox == 0) - { - sound->mailbox = 9; - } - } - - data->offset += 6; - if (data->chunkIndex) - { - IM_LOG_ERR("data->chunkIndex should be 0 in Dark Forces, it is: %d.", data->chunkIndex); - assert(0); - } - return imSuccess; - } - else if (id == 4) - { - chunkData += 3; - ImSetSoundTrigger((ImSoundId)data->sound, chunkData); - data->offset += 6; - } - else if (id == 6) - { - data->baseOffset = data->offset; - data->offset += 6; - if (data->chunkIndex != 0) - { - IM_LOG_ERR("data->chunkIndex should be 0 in Dark Forces, it is: %d.", data->chunkIndex); - assert(0); - } - } - else if (id == 7) - { - data->offset = data->baseOffset; - if (data->chunkIndex != 0) - { - IM_LOG_ERR("data->chunkIndex should be 0 in Dark Forces, it is: %d.", data->chunkIndex); - assert(0); - } - } - else if (id == 'C') - { - if (chunkData[0] != 'r' || chunkData[1] != 'e' || chunkData[2] != 'a') - { - IM_LOG_ERR("ERR: Illegal chunk in sound %lu...", data->sound->soundId); - return imFail; - } - data->offset += 26; - if (data->chunkIndex) - { - IM_LOG_ERR("data->chunkIndex should be 0 in Dark Forces, it is: %d.", data->chunkIndex); - assert(0); - } - } - else - { - IM_LOG_ERR("ERR: Illegal chunk in sound %lu...", data->sound->soundId); - return imFail; - } - } - return imSuccess; - } - - s32 ImWaveSetupSoundData(ImWaveSound* sound, s32 chunkIndex) - { - ImWaveData* data = sound->data; - data->offset = 0; - data->chunkSize = 0; - data->baseOffset = 0; - - if (chunkIndex) - { - IM_LOG_ERR("data->chunkIndex should be 0 in Dark Forces, it is: %d.", chunkIndex); - assert(0); - } - - data->chunkIndex = 0; - return ImSeekToNextChunk(data); - } - - s32 ImStartDigitalSoundIntern(ImSoundId soundId, s32 priority, s32 chunkIndex) - { - priority = clamp(priority, 0, 127); - ImWaveSound* sound = ImAllocWaveSound(priority); - if (!sound) - { - return imFail; - } - - sound->soundId = soundId; - sound->marker = 0; - sound->group = 0; - sound->priority = priority; - sound->volume = 128; - sound->baseVolume = ImGetGroupVolume(0); - sound->pan = imPanCenter; - sound->detune = 0; - sound->transpose = 0; - sound->detuneTrans = 0; - sound->mailbox = 0; - if (ImWaveSetupSoundData(sound, chunkIndex) != imSuccess) - { - IM_LOG_ERR("Failed to setup wave player data - soundId: 0x%x, priority: %d", soundId, priority); - ImFreeWaveSound(sound); - return imFail; - } - - AUDIO_LOCK(); - { - IM_LIST_ADD(s_imWaveSoundList, sound); - } - AUDIO_UNLOCK(); - - return imSuccess; - } - - void ImFreeWaveSound(ImWaveSound* sound) - { - IM_LIST_REM(s_imWaveSoundList, sound); - ImClearSoundFaders(sound->soundId, -1); - ImClearTrigger(sound->soundId, -1, -1); - sound->soundId = IM_NULL_SOUNDID; - } - - s32 ImFreeWaveSoundById(ImSoundId soundId) - { - return ImFreeWaveSoundByIdIntern(soundId); - } - - s32 ImFreeAllWaveSounds() - { - AUDIO_LOCK(); - { - ImWaveSound* sound = s_imWaveSoundList; - while (sound) - { - ImWaveSound* next = sound->next; - ImFreeWaveSound(sound); - sound = next; - } - } - AUDIO_UNLOCK(); - return imSuccess; - } - - ImSoundId ImFindNextWaveSound(ImSoundId soundId) - { - ImSoundId nextSoundId = IM_NULL_SOUNDID; - ImWaveSound* sound = s_imWaveSoundList; - // Find the smallest ID that is greater than 'soundId' or NULL if soundId is the last one. - while (sound) - { - if (u64(sound->soundId) > u64(soundId)) - { - if (!nextSoundId || u64(sound->soundId) < u64(nextSoundId)) - { - nextSoundId = sound->soundId; - } - } - sound = sound->next; - } - return nextSoundId; - } - - // leftMapping: map left channel samples to final values based on volume and pan. - // rightMapping: map right channel samples to final values based on volume and pan. - void digitalAudioOutput_Stereo(s16* audioOut, const u8* sndData, const s8* leftMapping, const s8* rightMapping, s32 size) - { - for (s32 i = 0; i < size; i++, sndData++, audioOut+=2) - { - const u8 sample = *sndData; - audioOut[0] += (s16)leftMapping[sample]; - audioOut[1] += (s16)rightMapping[sample]; - } - } - - void audioProcessFrame(u8* audioFrame, s32 size, s32 outOffset, s32 vol, s32 pan) - { - s32 vTop = vol >> 3; - if (vol) - { - vTop++; - } - if (vTop >= 17) - { - vTop = 1; - } - - s32 panTop = (pan >> 3) - 8; - if (pan > imPanCenter) - { - panTop++; - } - - // Calculate where the in panVolume mapping channel to read from for each channel. - s32 leftVolume = s_audioPanVolumeTable[8 - panTop + vTop*17]; - s32 rightVolume = s_audioPanVolumeTable[8 + panTop + vTop*17]; - // Map [0,255] sample values to signed output values based on volume. - const s8* leftMapping = (s8*)&s_audioVolumeToSignedMapping[leftVolume << 8]; - const s8* rightMapping = (s8*)&s_audioVolumeToSignedMapping[rightVolume << 8]; - - digitalAudioOutput_Stereo(&s_audioOut[outOffset * 2], audioFrame, leftMapping, rightMapping, size); - } - - s32 audioPlaySoundFrame(ImWaveSound* sound) - { - ImWaveData* data = sound->data; - s32 bufferSize = s_audioOutSize; - s32 offset = 0; - s32 res = imSuccess; - while (bufferSize > 0) - { - res = imSuccess; - if (!data->chunkSize) - { - res = ImSeekToNextChunk(data); - if (res != imSuccess) - { - if (res == imFail) // Sound has finished playing. - { - ImFreeWaveSound(sound); - } - break; - } - } - - // Read additional samples, but only update the offset by the base number. - // This is required since the results might be interpolated on upsample. - const s32 baseReadSize = min(bufferSize, data->chunkSize); - const s32 readSize = min(bufferSize+IM_AUDIO_OVERSAMPLE, data->chunkSize); - s_audioData = ImInternalGetSoundData(sound->soundId) + data->offset; - audioProcessFrame(s_audioData, readSize, offset, sound->volume, sound->pan); - - offset += baseReadSize; - bufferSize -= baseReadSize; - data->offset += baseReadSize; - data->chunkSize -= baseReadSize; - } - return res; - } - - s32 audioWriteToDriver(f32 systemVolume) - { - if (!s_audioOut) - { - return imInvalidSound; - } - - s32 bufferSize = s_audioOutSize*2 + IM_AUDIO_OVERSAMPLE; - s16* audioOut = s_audioOut; -#ifdef TFE_ESPBOX - s8* driverOut = s_audioDriverOut; -#else - f32* driverOut = s_audioDriverOut; -#endif - for (s32 i = 0; i < bufferSize; i++, audioOut++, driverOut++) - { -#ifdef TFE_ESPBOX - *driverOut = s_audioNormalization[*audioOut]; - //*driverOut = sinf(((i/2) / 512.0f * 8.0f) * M_PI*2) * 127.0f; -#else - *driverOut = s_audioNormalization[*audioOut] * systemVolume; -#endif - } - return imSuccess; - } - - s32 ImFreeWaveSoundByIdIntern(ImSoundId soundId) - { - s32 result = imInvalidSound; - - AUDIO_LOCK(); - { - ImWaveSound* sound = s_imWaveSoundList; - while (sound) - { - ImWaveSound* next = sound->next; - if (sound->soundId == soundId) - { - ImFreeWaveSound(sound); - result = imSuccess; - } - sound = next; - } - } - AUDIO_UNLOCK(); - - return result; - } - -} // namespace TFE_Jedi diff --git a/components/darkforces/tfe/TFE_Jedi/IMuse/imDigitalSound.h b/components/darkforces/tfe/TFE_Jedi/IMuse/imDigitalSound.h deleted file mode 100644 index 454c3146..00000000 --- a/components/darkforces/tfe/TFE_Jedi/IMuse/imDigitalSound.h +++ /dev/null @@ -1,43 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// iMuse System -// The IMuse system used by Dark Forces. -// -// Copyright note: -// While the project as a whole is licensed under GPL-2.0, some of the -// code under TFE_Jedi/ was derived from reverse-engineered -// code from "Dark Forces" (DOS) which is copyrighted by LucasArts. -// The original renderer is contained in RClassic_Fixed/ and the -// RClassic_Float/ and RClassic_GPU/ sub-renderers are derived from -// that code. -// -// I consider the reverse-engineering to be "Fair Use" - a means of -// supporting the games on other platforms and to improve support on -// existing platforms without claiming ownership of the games -// themselves or their IPs. -// -// That said using this code in a commercial project is risky without -// permission of the original copyright holders (LucasArts). -////////////////////////////////////////////////////////////////////// -#include -#include "imuse.h" - -struct iMuseInitData; - -namespace TFE_Jedi -{ - s32 ImInitializeDigitalAudio(iMuseInitData* initData); - void ImTerminateDigitalAudio(); - - s32 ImSetWaveParam(ImSoundId soundId, s32 param, s32 value); - s32 ImGetWaveParam(ImSoundId soundId, s32 param); - s32 ImStartDigitalSound(ImSoundId soundId, s32 priority); - void ImUpdateWave(f32* buffer, u32 bufferSize, f32 systemVolume); - - s32 ImFreeWaveSoundById(ImSoundId soundId); - s32 ImFreeAllWaveSounds(); - ImSoundId ImFindNextWaveSound(ImSoundId soundId); - - s32 ImPauseDigitalSound(); - s32 ImResumeDigitalSound(); -} // namespace TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/IMuse/imDigitalVolumeTable.h b/components/darkforces/tfe/TFE_Jedi/IMuse/imDigitalVolumeTable.h deleted file mode 100644 index f1b15417..00000000 --- a/components/darkforces/tfe/TFE_Jedi/IMuse/imDigitalVolumeTable.h +++ /dev/null @@ -1,330 +0,0 @@ -#pragma once -#include - -// This is used to calculate the volume bucket (0 - 16) for a channel based on the pan and volume. -// The table is organized into volume rows: volOffset = volume[0, 16] * 17 -// Each row represents the stereo panning at the volume = [0, 16] -// So pan=16 means that the channel is at full volume and pan=0 means that the channel is at 0 volume. -// This is used as an offset into the s_audioVolumeToSignedMapping[] table below. -static const u8 s_audioPanVolumeTable[] = -{ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, - 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, - 0x00, 0x00, 0x01, 0x01, 0x02, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, - 0x00, 0x00, 0x01, 0x01, 0x02, 0x02, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, 0x05, 0x05, 0x05, 0x05, 0x05, - 0x00, 0x01, 0x01, 0x02, 0x02, 0x03, 0x03, 0x04, 0x04, 0x05, 0x05, 0x05, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x00, 0x01, 0x01, 0x02, 0x03, 0x03, 0x04, 0x04, 0x05, 0x05, 0x06, 0x06, 0x06, 0x07, 0x07, 0x07, 0x07, - 0x00, 0x01, 0x02, 0x02, 0x03, 0x04, 0x04, 0x05, 0x06, 0x06, 0x07, 0x07, 0x07, 0x08, 0x08, 0x08, 0x08, - 0x00, 0x01, 0x02, 0x03, 0x03, 0x04, 0x05, 0x06, 0x06, 0x07, 0x07, 0x08, 0x08, 0x09, 0x09, 0x09, 0x09, - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x06, 0x07, 0x08, 0x08, 0x09, 0x09, 0x0A, 0x0A, 0x0A, 0x0A, - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x09, 0x0A, 0x0A, 0x0B, 0x0B, 0x0B, 0x0B, - 0x00, 0x01, 0x02, 0x03, 0x05, 0x06, 0x07, 0x08, 0x08, 0x09, 0x0A, 0x0B, 0x0B, 0x0B, 0x0C, 0x0C, 0x0C, - 0x00, 0x01, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0B, 0x0C, 0x0C, 0x0D, 0x0D, 0x0D, - 0x00, 0x01, 0x03, 0x04, 0x05, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0C, 0x0D, 0x0D, 0x0E, 0x0E, 0x0E, - 0x00, 0x01, 0x03, 0x04, 0x06, 0x07, 0x08, 0x0A, 0x0B, 0x0C, 0x0C, 0x0D, 0x0E, 0x0E, 0x0F, 0x0F, 0x0F, - 0x00, 0x02, 0x03, 0x05, 0x06, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x0F, 0x10, 0x10, 0x10 -}; - -// Maps from unsigned 8-bit samples to signed 8-bit samples based on the volume. -// Note the valid volume range is [0, 16] -// Examples: -// s_audioVolumeToSignedMapping[0 << 8] maps [0,255] -> [ 0, 0] -// s_audioVolumeToSignedMapping[11 << 8] maps [0,255] -> [ -88, 87] -// s_audioVolumeToSignedMapping[16 << 8] maps [0,255] -> [-128, 127] -// TODO: This table seems to be a simple scaling, so this can be replaced by direct math on modern CPUs - -// This is basically code that will generate the table: -// for (vol = 0; vol <= 16; vol++) { table = mappingTable[vol<<8]; for (sample=0; sample<256; sample++) { table[sample] = (sample-128)*vol/16; } } -static const u8 s_audioVolumeToSignedMapping[17 * 256] = -{ - // 0 [0, 0] - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - // 1 [-7, 7] - 0xF9, 0xF9, 0xF9, 0xF9, 0xF9, 0xF9, 0xF9, 0xF9, 0xF9, 0xF9, 0xF9, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, - 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFB, 0xFB, 0xFB, - 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFC, - 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, - 0xFC, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, - 0xFD, 0xFD, 0xFD, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, - 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02, - 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x03, 0x03, - 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, - 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, - 0x04, 0x04, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, - 0x05, 0x05, 0x05, 0x05, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, - // 2 [-15, 15] - 0xF1, 0xF1, 0xF1, 0xF1, 0xF1, 0xF1, 0xF2, 0xF2, 0xF2, 0xF2, 0xF2, 0xF2, 0xF2, 0xF2, 0xF3, 0xF3, - 0xF3, 0xF3, 0xF3, 0xF3, 0xF3, 0xF3, 0xF3, 0xF4, 0xF4, 0xF4, 0xF4, 0xF4, 0xF4, 0xF4, 0xF4, 0xF5, - 0xF5, 0xF5, 0xF5, 0xF5, 0xF5, 0xF5, 0xF5, 0xF5, 0xF6, 0xF6, 0xF6, 0xF6, 0xF6, 0xF6, 0xF6, 0xF6, - 0xF7, 0xF7, 0xF7, 0xF7, 0xF7, 0xF7, 0xF7, 0xF7, 0xF7, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, - 0xF8, 0xF9, 0xF9, 0xF9, 0xF9, 0xF9, 0xF9, 0xF9, 0xF9, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, - 0xFA, 0xFA, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, - 0xFC, 0xFC, 0xFC, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, - 0xFE, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, - 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, - 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, - 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, - 0x09, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, - 0x0B, 0x0B, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, - 0x0D, 0x0D, 0x0D, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, - // 3 [-23, 23] - 0xE9, 0xE9, 0xE9, 0xE9, 0xEA, 0xEA, 0xEA, 0xEA, 0xEA, 0xEA, 0xEB, 0xEB, 0xEB, 0xEB, 0xEB, 0xEC, - 0xEC, 0xEC, 0xEC, 0xEC, 0xEC, 0xED, 0xED, 0xED, 0xED, 0xED, 0xEE, 0xEE, 0xEE, 0xEE, 0xEE, 0xEE, - 0xEF, 0xEF, 0xEF, 0xEF, 0xEF, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF1, 0xF1, 0xF1, 0xF1, 0xF1, - 0xF2, 0xF2, 0xF2, 0xF2, 0xF2, 0xF2, 0xF3, 0xF3, 0xF3, 0xF3, 0xF3, 0xF4, 0xF4, 0xF4, 0xF4, 0xF4, - 0xF4, 0xF5, 0xF5, 0xF5, 0xF5, 0xF5, 0xF5, 0xF6, 0xF6, 0xF6, 0xF6, 0xF6, 0xF7, 0xF7, 0xF7, 0xF7, - 0xF7, 0xF7, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF9, 0xF9, 0xF9, 0xF9, 0xF9, 0xF9, 0xFA, 0xFA, 0xFA, - 0xFA, 0xFA, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFD, 0xFD, 0xFD, - 0xFD, 0xFD, 0xFD, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02, 0x02, 0x03, 0x03, - 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, 0x04, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x08, 0x08, 0x08, 0x08, 0x08, 0x09, - 0x09, 0x09, 0x09, 0x09, 0x09, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, - 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, - 0x0E, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x11, 0x11, 0x11, 0x11, - 0x11, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x13, 0x13, 0x13, 0x13, 0x13, 0x14, 0x14, 0x14, 0x14, - 0x14, 0x14, 0x15, 0x15, 0x15, 0x15, 0x15, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x17, 0x17, 0x17, - // 4 [-31, 31] - 0xE1, 0xE1, 0xE1, 0xE1, 0xE2, 0xE2, 0xE2, 0xE2, 0xE3, 0xE3, 0xE3, 0xE3, 0xE4, 0xE4, 0xE4, 0xE4, - 0xE5, 0xE5, 0xE5, 0xE5, 0xE6, 0xE6, 0xE6, 0xE6, 0xE7, 0xE7, 0xE7, 0xE7, 0xE8, 0xE8, 0xE8, 0xE8, - 0xE9, 0xE9, 0xE9, 0xE9, 0xEA, 0xEA, 0xEA, 0xEA, 0xEB, 0xEB, 0xEB, 0xEB, 0xEB, 0xEC, 0xEC, 0xEC, - 0xEC, 0xED, 0xED, 0xED, 0xED, 0xEE, 0xEE, 0xEE, 0xEE, 0xEF, 0xEF, 0xEF, 0xEF, 0xF0, 0xF0, 0xF0, - 0xF0, 0xF1, 0xF1, 0xF1, 0xF1, 0xF2, 0xF2, 0xF2, 0xF2, 0xF3, 0xF3, 0xF3, 0xF3, 0xF4, 0xF4, 0xF4, - 0xF4, 0xF5, 0xF5, 0xF5, 0xF5, 0xF6, 0xF6, 0xF6, 0xF6, 0xF6, 0xF7, 0xF7, 0xF7, 0xF7, 0xF8, 0xF8, - 0xF8, 0xF8, 0xF9, 0xF9, 0xF9, 0xF9, 0xFA, 0xFA, 0xFA, 0xFA, 0xFB, 0xFB, 0xFB, 0xFB, 0xFC, 0xFC, - 0xFC, 0xFC, 0xFD, 0xFD, 0xFD, 0xFD, 0xFE, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, 0x04, - 0x04, 0x04, 0x04, 0x05, 0x05, 0x05, 0x05, 0x06, 0x06, 0x06, 0x06, 0x07, 0x07, 0x07, 0x07, 0x08, - 0x08, 0x08, 0x08, 0x09, 0x09, 0x09, 0x09, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0B, 0x0B, 0x0B, 0x0B, - 0x0C, 0x0C, 0x0C, 0x0C, 0x0D, 0x0D, 0x0D, 0x0D, 0x0E, 0x0E, 0x0E, 0x0E, 0x0F, 0x0F, 0x0F, 0x0F, - 0x10, 0x10, 0x10, 0x10, 0x11, 0x11, 0x11, 0x11, 0x12, 0x12, 0x12, 0x12, 0x13, 0x13, 0x13, 0x13, - 0x14, 0x14, 0x14, 0x14, 0x15, 0x15, 0x15, 0x15, 0x15, 0x16, 0x16, 0x16, 0x16, 0x17, 0x17, 0x17, - 0x17, 0x18, 0x18, 0x18, 0x18, 0x19, 0x19, 0x19, 0x19, 0x1A, 0x1A, 0x1A, 0x1A, 0x1B, 0x1B, 0x1B, - 0x1B, 0x1C, 0x1C, 0x1C, 0x1C, 0x1D, 0x1D, 0x1D, 0x1D, 0x1E, 0x1E, 0x1E, 0x1E, 0x1F, 0x1F, 0x1F, - // 5 [-39, 39] - 0xD9, 0xD9, 0xD9, 0xDA, 0xDA, 0xDA, 0xDB, 0xDB, 0xDB, 0xDB, 0xDC, 0xDC, 0xDC, 0xDD, 0xDD, 0xDD, - 0xDE, 0xDE, 0xDE, 0xDF, 0xDF, 0xDF, 0xDF, 0xE0, 0xE0, 0xE0, 0xE1, 0xE1, 0xE1, 0xE2, 0xE2, 0xE2, - 0xE3, 0xE3, 0xE3, 0xE3, 0xE4, 0xE4, 0xE4, 0xE5, 0xE5, 0xE5, 0xE6, 0xE6, 0xE6, 0xE7, 0xE7, 0xE7, - 0xE7, 0xE8, 0xE8, 0xE8, 0xE9, 0xE9, 0xE9, 0xEA, 0xEA, 0xEA, 0xEB, 0xEB, 0xEB, 0xEB, 0xEC, 0xEC, - 0xEC, 0xED, 0xED, 0xED, 0xEE, 0xEE, 0xEE, 0xEE, 0xEF, 0xEF, 0xEF, 0xF0, 0xF0, 0xF0, 0xF1, 0xF1, - 0xF1, 0xF2, 0xF2, 0xF2, 0xF2, 0xF3, 0xF3, 0xF3, 0xF4, 0xF4, 0xF4, 0xF5, 0xF5, 0xF5, 0xF6, 0xF6, - 0xF6, 0xF6, 0xF7, 0xF7, 0xF7, 0xF8, 0xF8, 0xF8, 0xF9, 0xF9, 0xF9, 0xFA, 0xFA, 0xFA, 0xFA, 0xFB, - 0xFB, 0xFB, 0xFC, 0xFC, 0xFC, 0xFD, 0xFD, 0xFD, 0xFE, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF, 0x00, - 0x00, 0x00, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x05, - 0x05, 0x05, 0x06, 0x06, 0x06, 0x06, 0x07, 0x07, 0x07, 0x08, 0x08, 0x08, 0x09, 0x09, 0x09, 0x0A, - 0x0A, 0x0A, 0x0A, 0x0B, 0x0B, 0x0B, 0x0C, 0x0C, 0x0C, 0x0D, 0x0D, 0x0D, 0x0E, 0x0E, 0x0E, 0x0E, - 0x0F, 0x0F, 0x0F, 0x10, 0x10, 0x10, 0x11, 0x11, 0x11, 0x12, 0x12, 0x12, 0x12, 0x13, 0x13, 0x13, - 0x14, 0x14, 0x14, 0x15, 0x15, 0x15, 0x15, 0x16, 0x16, 0x16, 0x17, 0x17, 0x17, 0x18, 0x18, 0x18, - 0x19, 0x19, 0x19, 0x19, 0x1A, 0x1A, 0x1A, 0x1B, 0x1B, 0x1B, 0x1C, 0x1C, 0x1C, 0x1D, 0x1D, 0x1D, - 0x1D, 0x1E, 0x1E, 0x1E, 0x1F, 0x1F, 0x1F, 0x20, 0x20, 0x20, 0x21, 0x21, 0x21, 0x21, 0x22, 0x22, - 0x22, 0x23, 0x23, 0x23, 0x24, 0x24, 0x24, 0x25, 0x25, 0x25, 0x25, 0x26, 0x26, 0x26, 0x27, 0x27, - // 6 [-47, 47] - 0xD1, 0xD1, 0xD1, 0xD2, 0xD2, 0xD2, 0xD3, 0xD3, 0xD4, 0xD4, 0xD4, 0xD5, 0xD5, 0xD5, 0xD6, 0xD6, - 0xD7, 0xD7, 0xD7, 0xD8, 0xD8, 0xD8, 0xD9, 0xD9, 0xDA, 0xDA, 0xDA, 0xDB, 0xDB, 0xDB, 0xDC, 0xDC, - 0xDC, 0xDD, 0xDD, 0xDE, 0xDE, 0xDE, 0xDF, 0xDF, 0xDF, 0xE0, 0xE0, 0xE1, 0xE1, 0xE1, 0xE2, 0xE2, - 0xE2, 0xE3, 0xE3, 0xE4, 0xE4, 0xE4, 0xE5, 0xE5, 0xE5, 0xE6, 0xE6, 0xE6, 0xE7, 0xE7, 0xE8, 0xE8, - 0xE8, 0xE9, 0xE9, 0xE9, 0xEA, 0xEA, 0xEB, 0xEB, 0xEB, 0xEC, 0xEC, 0xEC, 0xED, 0xED, 0xED, 0xEE, - 0xEE, 0xEF, 0xEF, 0xEF, 0xF0, 0xF0, 0xF0, 0xF1, 0xF1, 0xF2, 0xF2, 0xF2, 0xF3, 0xF3, 0xF3, 0xF4, - 0xF4, 0xF5, 0xF5, 0xF5, 0xF6, 0xF6, 0xF6, 0xF7, 0xF7, 0xF7, 0xF8, 0xF8, 0xF9, 0xF9, 0xF9, 0xFA, - 0xFA, 0xFA, 0xFB, 0xFB, 0xFC, 0xFC, 0xFC, 0xFD, 0xFD, 0xFD, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF, 0x00, - 0x00, 0x00, 0x01, 0x01, 0x01, 0x02, 0x02, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x05, 0x05, 0x06, - 0x06, 0x06, 0x07, 0x07, 0x07, 0x08, 0x08, 0x09, 0x09, 0x09, 0x0A, 0x0A, 0x0A, 0x0B, 0x0B, 0x0B, - 0x0C, 0x0C, 0x0D, 0x0D, 0x0D, 0x0E, 0x0E, 0x0E, 0x0F, 0x0F, 0x10, 0x10, 0x10, 0x11, 0x11, 0x11, - 0x12, 0x12, 0x13, 0x13, 0x13, 0x14, 0x14, 0x14, 0x15, 0x15, 0x15, 0x16, 0x16, 0x17, 0x17, 0x17, - 0x18, 0x18, 0x18, 0x19, 0x19, 0x1A, 0x1A, 0x1A, 0x1B, 0x1B, 0x1B, 0x1C, 0x1C, 0x1C, 0x1D, 0x1D, - 0x1E, 0x1E, 0x1E, 0x1F, 0x1F, 0x1F, 0x20, 0x20, 0x21, 0x21, 0x21, 0x22, 0x22, 0x22, 0x23, 0x23, - 0x24, 0x24, 0x24, 0x25, 0x25, 0x25, 0x26, 0x26, 0x26, 0x27, 0x27, 0x28, 0x28, 0x28, 0x29, 0x29, - 0x29, 0x2A, 0x2A, 0x2B, 0x2B, 0x2B, 0x2C, 0x2C, 0x2C, 0x2D, 0x2D, 0x2E, 0x2E, 0x2E, 0x2F, 0x2F, - // 7 [-55, 55] - 0xC9, 0xC9, 0xC9, 0xCA, 0xCA, 0xCB, 0xCB, 0xCC, 0xCC, 0xCC, 0xCD, 0xCD, 0xCE, 0xCE, 0xCF, 0xCF, - 0xCF, 0xD0, 0xD0, 0xD1, 0xD1, 0xD2, 0xD2, 0xD3, 0xD3, 0xD3, 0xD4, 0xD4, 0xD5, 0xD5, 0xD6, 0xD6, - 0xD6, 0xD7, 0xD7, 0xD8, 0xD8, 0xD9, 0xD9, 0xD9, 0xDA, 0xDA, 0xDB, 0xDB, 0xDC, 0xDC, 0xDC, 0xDD, - 0xDD, 0xDE, 0xDE, 0xDF, 0xDF, 0xE0, 0xE0, 0xE0, 0xE1, 0xE1, 0xE2, 0xE2, 0xE3, 0xE3, 0xE3, 0xE4, - 0xE4, 0xE5, 0xE5, 0xE6, 0xE6, 0xE6, 0xE7, 0xE7, 0xE8, 0xE8, 0xE9, 0xE9, 0xE9, 0xEA, 0xEA, 0xEB, - 0xEB, 0xEC, 0xEC, 0xED, 0xED, 0xED, 0xEE, 0xEE, 0xEF, 0xEF, 0xF0, 0xF0, 0xF0, 0xF1, 0xF1, 0xF2, - 0xF2, 0xF3, 0xF3, 0xF3, 0xF4, 0xF4, 0xF5, 0xF5, 0xF6, 0xF6, 0xF6, 0xF7, 0xF7, 0xF8, 0xF8, 0xF9, - 0xF9, 0xFA, 0xFA, 0xFA, 0xFB, 0xFB, 0xFC, 0xFC, 0xFD, 0xFD, 0xFD, 0xFE, 0xFE, 0xFF, 0xFF, 0x00, - 0x00, 0x00, 0x01, 0x01, 0x02, 0x02, 0x03, 0x03, 0x03, 0x04, 0x04, 0x05, 0x05, 0x06, 0x06, 0x06, - 0x07, 0x07, 0x08, 0x08, 0x09, 0x09, 0x0A, 0x0A, 0x0A, 0x0B, 0x0B, 0x0C, 0x0C, 0x0D, 0x0D, 0x0D, - 0x0E, 0x0E, 0x0F, 0x0F, 0x10, 0x10, 0x10, 0x11, 0x11, 0x12, 0x12, 0x13, 0x13, 0x13, 0x14, 0x14, - 0x15, 0x15, 0x16, 0x16, 0x17, 0x17, 0x17, 0x18, 0x18, 0x19, 0x19, 0x1A, 0x1A, 0x1A, 0x1B, 0x1B, - 0x1C, 0x1C, 0x1D, 0x1D, 0x1D, 0x1E, 0x1E, 0x1F, 0x1F, 0x20, 0x20, 0x20, 0x21, 0x21, 0x22, 0x22, - 0x23, 0x23, 0x24, 0x24, 0x24, 0x25, 0x25, 0x26, 0x26, 0x27, 0x27, 0x27, 0x28, 0x28, 0x29, 0x29, - 0x2A, 0x2A, 0x2A, 0x2B, 0x2B, 0x2C, 0x2C, 0x2D, 0x2D, 0x2D, 0x2E, 0x2E, 0x2F, 0x2F, 0x30, 0x30, - 0x31, 0x31, 0x31, 0x32, 0x32, 0x33, 0x33, 0x34, 0x34, 0x34, 0x35, 0x35, 0x36, 0x36, 0x37, 0x37, - // 8 [-63, 63] - 0xC1, 0xC1, 0xC1, 0xC2, 0xC2, 0xC3, 0xC3, 0xC4, 0xC4, 0xC5, 0xC5, 0xC6, 0xC6, 0xC7, 0xC7, 0xC8, - 0xC8, 0xC9, 0xC9, 0xCA, 0xCA, 0xCB, 0xCB, 0xCC, 0xCC, 0xCD, 0xCD, 0xCE, 0xCE, 0xCF, 0xCF, 0xD0, - 0xD0, 0xD1, 0xD1, 0xD2, 0xD2, 0xD3, 0xD3, 0xD4, 0xD4, 0xD5, 0xD5, 0xD6, 0xD6, 0xD7, 0xD7, 0xD8, - 0xD8, 0xD9, 0xD9, 0xDA, 0xDA, 0xDB, 0xDB, 0xDC, 0xDC, 0xDD, 0xDD, 0xDE, 0xDE, 0xDF, 0xDF, 0xE0, - 0xE0, 0xE1, 0xE1, 0xE2, 0xE2, 0xE3, 0xE3, 0xE4, 0xE4, 0xE5, 0xE5, 0xE6, 0xE6, 0xE7, 0xE7, 0xE8, - 0xE8, 0xE9, 0xE9, 0xEA, 0xEA, 0xEB, 0xEB, 0xEC, 0xEC, 0xED, 0xED, 0xEE, 0xEE, 0xEF, 0xEF, 0xF0, - 0xF0, 0xF1, 0xF1, 0xF2, 0xF2, 0xF3, 0xF3, 0xF4, 0xF4, 0xF5, 0xF5, 0xF6, 0xF6, 0xF7, 0xF7, 0xF8, - 0xF8, 0xF9, 0xF9, 0xFA, 0xFA, 0xFB, 0xFB, 0xFC, 0xFC, 0xFD, 0xFD, 0xFE, 0xFE, 0xFF, 0xFF, 0x00, - 0x00, 0x00, 0x01, 0x01, 0x02, 0x02, 0x03, 0x03, 0x04, 0x04, 0x05, 0x05, 0x06, 0x06, 0x07, 0x07, - 0x08, 0x08, 0x09, 0x09, 0x0A, 0x0A, 0x0B, 0x0B, 0x0C, 0x0C, 0x0D, 0x0D, 0x0E, 0x0E, 0x0F, 0x0F, - 0x10, 0x10, 0x11, 0x11, 0x12, 0x12, 0x13, 0x13, 0x14, 0x14, 0x15, 0x15, 0x16, 0x16, 0x17, 0x17, - 0x18, 0x18, 0x19, 0x19, 0x1A, 0x1A, 0x1B, 0x1B, 0x1C, 0x1C, 0x1D, 0x1D, 0x1E, 0x1E, 0x1F, 0x1F, - 0x20, 0x20, 0x21, 0x21, 0x22, 0x22, 0x23, 0x23, 0x24, 0x24, 0x25, 0x25, 0x26, 0x26, 0x27, 0x27, - 0x28, 0x28, 0x29, 0x29, 0x2A, 0x2A, 0x2B, 0x2B, 0x2C, 0x2C, 0x2D, 0x2D, 0x2E, 0x2E, 0x2F, 0x2F, - 0x30, 0x30, 0x31, 0x31, 0x32, 0x32, 0x33, 0x33, 0x34, 0x34, 0x35, 0x35, 0x36, 0x36, 0x37, 0x37, - 0x38, 0x38, 0x39, 0x39, 0x3A, 0x3A, 0x3B, 0x3B, 0x3C, 0x3C, 0x3D, 0x3D, 0x3E, 0x3E, 0x3F, 0x3F, - // 9 [-72, 71] - 0xB8, 0xB9, 0xBA, 0xBA, 0xBB, 0xBB, 0xBC, 0xBC, 0xBD, 0xBD, 0xBE, 0xBF, 0xBF, 0xC0, 0xC0, 0xC1, - 0xC1, 0xC2, 0xC3, 0xC3, 0xC4, 0xC4, 0xC5, 0xC5, 0xC6, 0xC6, 0xC7, 0xC8, 0xC8, 0xC9, 0xC9, 0xCA, - 0xCA, 0xCB, 0xCB, 0xCC, 0xCD, 0xCD, 0xCE, 0xCE, 0xCF, 0xCF, 0xD0, 0xD0, 0xD1, 0xD2, 0xD2, 0xD3, - 0xD3, 0xD4, 0xD4, 0xD5, 0xD6, 0xD6, 0xD7, 0xD7, 0xD8, 0xD8, 0xD9, 0xD9, 0xDA, 0xDB, 0xDB, 0xDC, - 0xDC, 0xDD, 0xDD, 0xDE, 0xDE, 0xDF, 0xE0, 0xE0, 0xE1, 0xE1, 0xE2, 0xE2, 0xE3, 0xE3, 0xE4, 0xE5, - 0xE5, 0xE6, 0xE6, 0xE7, 0xE7, 0xE8, 0xE9, 0xE9, 0xEA, 0xEA, 0xEB, 0xEB, 0xEC, 0xEC, 0xED, 0xEE, - 0xEE, 0xEF, 0xEF, 0xF0, 0xF0, 0xF1, 0xF1, 0xF2, 0xF3, 0xF3, 0xF4, 0xF4, 0xF5, 0xF5, 0xF6, 0xF6, - 0xF7, 0xF8, 0xF8, 0xF9, 0xF9, 0xFA, 0xFA, 0xFB, 0xFC, 0xFC, 0xFD, 0xFD, 0xFE, 0xFE, 0xFF, 0xFF, - 0x00, 0x01, 0x01, 0x02, 0x02, 0x03, 0x03, 0x04, 0x04, 0x05, 0x06, 0x06, 0x07, 0x07, 0x08, 0x08, - 0x09, 0x0A, 0x0A, 0x0B, 0x0B, 0x0C, 0x0C, 0x0D, 0x0D, 0x0E, 0x0F, 0x0F, 0x10, 0x10, 0x11, 0x11, - 0x12, 0x12, 0x13, 0x14, 0x14, 0x15, 0x15, 0x16, 0x16, 0x17, 0x17, 0x18, 0x19, 0x19, 0x1A, 0x1A, - 0x1B, 0x1B, 0x1C, 0x1D, 0x1D, 0x1E, 0x1E, 0x1F, 0x1F, 0x20, 0x20, 0x21, 0x22, 0x22, 0x23, 0x23, - 0x24, 0x24, 0x25, 0x25, 0x26, 0x27, 0x27, 0x28, 0x28, 0x29, 0x29, 0x2A, 0x2A, 0x2B, 0x2C, 0x2C, - 0x2D, 0x2D, 0x2E, 0x2E, 0x2F, 0x30, 0x30, 0x31, 0x31, 0x32, 0x32, 0x33, 0x33, 0x34, 0x35, 0x35, - 0x36, 0x36, 0x37, 0x37, 0x38, 0x38, 0x39, 0x3A, 0x3A, 0x3B, 0x3B, 0x3C, 0x3C, 0x3D, 0x3D, 0x3E, - 0x3F, 0x3F, 0x40, 0x40, 0x41, 0x41, 0x42, 0x43, 0x43, 0x44, 0x44, 0x45, 0x45, 0x46, 0x46, 0x47, - // 10 [-79, 79] - 0xB0, 0xB1, 0xB2, 0xB2, 0xB3, 0xB3, 0xB4, 0xB5, 0xB5, 0xB6, 0xB7, 0xB7, 0xB8, 0xB8, 0xB9, 0xBA, - 0xBA, 0xBB, 0xBC, 0xBC, 0xBD, 0xBD, 0xBE, 0xBF, 0xBF, 0xC0, 0xC1, 0xC1, 0xC2, 0xC2, 0xC3, 0xC4, - 0xC4, 0xC5, 0xC6, 0xC6, 0xC7, 0xC7, 0xC8, 0xC9, 0xC9, 0xCA, 0xCB, 0xCB, 0xCC, 0xCC, 0xCD, 0xCE, - 0xCE, 0xCF, 0xCF, 0xD0, 0xD1, 0xD1, 0xD2, 0xD3, 0xD3, 0xD4, 0xD4, 0xD5, 0xD6, 0xD6, 0xD7, 0xD8, - 0xD8, 0xD9, 0xD9, 0xDA, 0xDB, 0xDB, 0xDC, 0xDD, 0xDD, 0xDE, 0xDE, 0xDF, 0xE0, 0xE0, 0xE1, 0xE2, - 0xE2, 0xE3, 0xE3, 0xE4, 0xE5, 0xE5, 0xE6, 0xE6, 0xE7, 0xE8, 0xE8, 0xE9, 0xEA, 0xEA, 0xEB, 0xEB, - 0xEC, 0xED, 0xED, 0xEE, 0xEF, 0xEF, 0xF0, 0xF0, 0xF1, 0xF2, 0xF2, 0xF3, 0xF4, 0xF4, 0xF5, 0xF5, - 0xF6, 0xF7, 0xF7, 0xF8, 0xF9, 0xF9, 0xFA, 0xFA, 0xFB, 0xFC, 0xFC, 0xFD, 0xFE, 0xFE, 0xFF, 0xFF, - 0x00, 0x01, 0x01, 0x02, 0x02, 0x03, 0x04, 0x04, 0x05, 0x06, 0x06, 0x07, 0x07, 0x08, 0x09, 0x09, - 0x0A, 0x0B, 0x0B, 0x0C, 0x0C, 0x0D, 0x0E, 0x0E, 0x0F, 0x10, 0x10, 0x11, 0x11, 0x12, 0x13, 0x13, - 0x14, 0x15, 0x15, 0x16, 0x16, 0x17, 0x18, 0x18, 0x19, 0x1A, 0x1A, 0x1B, 0x1B, 0x1C, 0x1D, 0x1D, - 0x1E, 0x1E, 0x1F, 0x20, 0x20, 0x21, 0x22, 0x22, 0x23, 0x23, 0x24, 0x25, 0x25, 0x26, 0x27, 0x27, - 0x28, 0x28, 0x29, 0x2A, 0x2A, 0x2B, 0x2C, 0x2C, 0x2D, 0x2D, 0x2E, 0x2F, 0x2F, 0x30, 0x31, 0x31, - 0x32, 0x32, 0x33, 0x34, 0x34, 0x35, 0x35, 0x36, 0x37, 0x37, 0x38, 0x39, 0x39, 0x3A, 0x3A, 0x3B, - 0x3C, 0x3C, 0x3D, 0x3E, 0x3E, 0x3F, 0x3F, 0x40, 0x41, 0x41, 0x42, 0x43, 0x43, 0x44, 0x44, 0x45, - 0x46, 0x46, 0x47, 0x48, 0x48, 0x49, 0x49, 0x4A, 0x4B, 0x4B, 0x4C, 0x4D, 0x4D, 0x4E, 0x4E, 0x4F, - // 11 [-88, 87] - 0xA8, 0xA9, 0xAA, 0xAA, 0xAB, 0xAC, 0xAC, 0xAD, 0xAE, 0xAE, 0xAF, 0xB0, 0xB1, 0xB1, 0xB2, 0xB3, - 0xB3, 0xB4, 0xB5, 0xB5, 0xB6, 0xB7, 0xB7, 0xB8, 0xB9, 0xB9, 0xBA, 0xBB, 0xBB, 0xBC, 0xBD, 0xBE, - 0xBE, 0xBF, 0xC0, 0xC0, 0xC1, 0xC2, 0xC2, 0xC3, 0xC4, 0xC4, 0xC5, 0xC6, 0xC6, 0xC7, 0xC8, 0xC9, - 0xC9, 0xCA, 0xCB, 0xCB, 0xCC, 0xCD, 0xCD, 0xCE, 0xCF, 0xCF, 0xD0, 0xD1, 0xD1, 0xD2, 0xD3, 0xD3, - 0xD4, 0xD5, 0xD6, 0xD6, 0xD7, 0xD8, 0xD8, 0xD9, 0xDA, 0xDA, 0xDB, 0xDC, 0xDC, 0xDD, 0xDE, 0xDE, - 0xDF, 0xE0, 0xE0, 0xE1, 0xE2, 0xE3, 0xE3, 0xE4, 0xE5, 0xE5, 0xE6, 0xE7, 0xE7, 0xE8, 0xE9, 0xE9, - 0xEA, 0xEB, 0xEB, 0xEC, 0xED, 0xEE, 0xEE, 0xEF, 0xF0, 0xF0, 0xF1, 0xF2, 0xF2, 0xF3, 0xF4, 0xF4, - 0xF5, 0xF6, 0xF6, 0xF7, 0xF8, 0xF8, 0xF9, 0xFA, 0xFB, 0xFB, 0xFC, 0xFD, 0xFD, 0xFE, 0xFF, 0xFF, - 0x00, 0x01, 0x01, 0x02, 0x03, 0x03, 0x04, 0x05, 0x05, 0x06, 0x07, 0x08, 0x08, 0x09, 0x0A, 0x0A, - 0x0B, 0x0C, 0x0C, 0x0D, 0x0E, 0x0E, 0x0F, 0x10, 0x10, 0x11, 0x12, 0x12, 0x13, 0x14, 0x15, 0x15, - 0x16, 0x17, 0x17, 0x18, 0x19, 0x19, 0x1A, 0x1B, 0x1B, 0x1C, 0x1D, 0x1D, 0x1E, 0x1F, 0x20, 0x20, - 0x21, 0x22, 0x22, 0x23, 0x24, 0x24, 0x25, 0x26, 0x26, 0x27, 0x28, 0x28, 0x29, 0x2A, 0x2A, 0x2B, - 0x2C, 0x2D, 0x2D, 0x2E, 0x2F, 0x2F, 0x30, 0x31, 0x31, 0x32, 0x33, 0x33, 0x34, 0x35, 0x35, 0x36, - 0x37, 0x37, 0x38, 0x39, 0x3A, 0x3A, 0x3B, 0x3C, 0x3C, 0x3D, 0x3E, 0x3E, 0x3F, 0x40, 0x40, 0x41, - 0x42, 0x42, 0x43, 0x44, 0x45, 0x45, 0x46, 0x47, 0x47, 0x48, 0x49, 0x49, 0x4A, 0x4B, 0x4B, 0x4C, - 0x4D, 0x4D, 0x4E, 0x4F, 0x4F, 0x50, 0x51, 0x52, 0x52, 0x53, 0x54, 0x54, 0x55, 0x56, 0x56, 0x57, - // 12 [-96, 95] - 0xA0, 0xA1, 0xA2, 0xA2, 0xA3, 0xA4, 0xA5, 0xA5, 0xA6, 0xA7, 0xA8, 0xA8, 0xA9, 0xAA, 0xAB, 0xAB, - 0xAC, 0xAD, 0xAE, 0xAE, 0xAF, 0xB0, 0xB1, 0xB1, 0xB2, 0xB3, 0xB4, 0xB4, 0xB5, 0xB6, 0xB7, 0xB7, - 0xB8, 0xB9, 0xBA, 0xBA, 0xBB, 0xBC, 0xBD, 0xBD, 0xBE, 0xBF, 0xC0, 0xC0, 0xC1, 0xC2, 0xC3, 0xC3, - 0xC4, 0xC5, 0xC6, 0xC6, 0xC7, 0xC8, 0xC9, 0xC9, 0xCA, 0xCB, 0xCC, 0xCC, 0xCD, 0xCE, 0xCF, 0xCF, - 0xD0, 0xD1, 0xD2, 0xD2, 0xD3, 0xD4, 0xD5, 0xD5, 0xD6, 0xD7, 0xD8, 0xD8, 0xD9, 0xDA, 0xDB, 0xDB, - 0xDC, 0xDD, 0xDE, 0xDE, 0xDF, 0xE0, 0xE1, 0xE1, 0xE2, 0xE3, 0xE4, 0xE4, 0xE5, 0xE6, 0xE7, 0xE7, - 0xE8, 0xE9, 0xEA, 0xEA, 0xEB, 0xEC, 0xED, 0xED, 0xEE, 0xEF, 0xF0, 0xF0, 0xF1, 0xF2, 0xF3, 0xF3, - 0xF4, 0xF5, 0xF6, 0xF6, 0xF7, 0xF8, 0xF9, 0xF9, 0xFA, 0xFB, 0xFC, 0xFC, 0xFD, 0xFE, 0xFF, 0xFF, - 0x00, 0x01, 0x01, 0x02, 0x03, 0x04, 0x04, 0x05, 0x06, 0x07, 0x07, 0x08, 0x09, 0x0A, 0x0A, 0x0B, - 0x0C, 0x0D, 0x0D, 0x0E, 0x0F, 0x10, 0x10, 0x11, 0x12, 0x13, 0x13, 0x14, 0x15, 0x16, 0x16, 0x17, - 0x18, 0x19, 0x19, 0x1A, 0x1B, 0x1C, 0x1C, 0x1D, 0x1E, 0x1F, 0x1F, 0x20, 0x21, 0x22, 0x22, 0x23, - 0x24, 0x25, 0x25, 0x26, 0x27, 0x28, 0x28, 0x29, 0x2A, 0x2B, 0x2B, 0x2C, 0x2D, 0x2E, 0x2E, 0x2F, - 0x30, 0x31, 0x31, 0x32, 0x33, 0x34, 0x34, 0x35, 0x36, 0x37, 0x37, 0x38, 0x39, 0x3A, 0x3A, 0x3B, - 0x3C, 0x3D, 0x3D, 0x3E, 0x3F, 0x40, 0x40, 0x41, 0x42, 0x43, 0x43, 0x44, 0x45, 0x46, 0x46, 0x47, - 0x48, 0x49, 0x49, 0x4A, 0x4B, 0x4C, 0x4C, 0x4D, 0x4E, 0x4F, 0x4F, 0x50, 0x51, 0x52, 0x52, 0x53, - 0x54, 0x55, 0x55, 0x56, 0x57, 0x58, 0x58, 0x59, 0x5A, 0x5B, 0x5B, 0x5C, 0x5D, 0x5E, 0x5E, 0x5F, - // 13 [-104, 103] - 0x98, 0x99, 0x9A, 0x9B, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F, 0x9F, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA4, - 0xA5, 0xA6, 0xA7, 0xA8, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAC, 0xAD, 0xAE, 0xAF, 0xB0, 0xB1, 0xB1, - 0xB2, 0xB3, 0xB4, 0xB5, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBD, 0xBE, - 0xBF, 0xC0, 0xC1, 0xC2, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCA, 0xCB, - 0xCC, 0xCD, 0xCE, 0xCF, 0xCF, 0xD0, 0xD1, 0xD2, 0xD3, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD7, 0xD8, - 0xD9, 0xDA, 0xDB, 0xDC, 0xDC, 0xDD, 0xDE, 0xDF, 0xE0, 0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE4, 0xE5, - 0xE6, 0xE7, 0xE8, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xED, 0xEE, 0xEF, 0xF0, 0xF1, 0xF1, 0xF2, - 0xF3, 0xF4, 0xF5, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFE, 0xFF, - 0x00, 0x01, 0x02, 0x02, 0x03, 0x04, 0x05, 0x06, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0B, 0x0C, - 0x0D, 0x0E, 0x0F, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x18, 0x19, - 0x1A, 0x1B, 0x1C, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x20, 0x21, 0x22, 0x23, 0x24, 0x24, 0x25, 0x26, - 0x27, 0x28, 0x29, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x31, 0x32, 0x33, - 0x34, 0x35, 0x36, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3E, 0x3F, 0x40, - 0x41, 0x42, 0x43, 0x43, 0x44, 0x45, 0x46, 0x47, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4B, 0x4C, 0x4D, - 0x4E, 0x4F, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x54, 0x55, 0x56, 0x57, 0x58, 0x58, 0x59, 0x5A, - 0x5B, 0x5C, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x61, 0x62, 0x63, 0x64, 0x65, 0x65, 0x66, 0x67, - // 14 [-112, 111] - 0x90, 0x91, 0x92, 0x93, 0x94, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0x9B, 0x9B, 0x9C, 0x9D, - 0x9E, 0x9F, 0xA0, 0xA1, 0xA2, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xA9, 0xAA, 0xAB, - 0xAC, 0xAD, 0xAE, 0xAF, 0xB0, 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB7, 0xB8, 0xB9, - 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBE, 0xBF, 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC5, 0xC6, 0xC7, - 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0, 0xD1, 0xD2, 0xD3, 0xD3, 0xD4, 0xD5, - 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF, 0xE0, 0xE1, 0xE1, 0xE2, 0xE3, - 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF, 0xEF, 0xF0, 0xF1, - 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFD, 0xFE, 0xFF, - 0x00, 0x01, 0x02, 0x03, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0A, 0x0B, 0x0C, 0x0D, - 0x0E, 0x0F, 0x10, 0x11, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x18, 0x19, 0x1A, 0x1B, - 0x1C, 0x1D, 0x1E, 0x1F, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x26, 0x27, 0x28, 0x29, - 0x2A, 0x2B, 0x2C, 0x2D, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x34, 0x35, 0x36, 0x37, - 0x38, 0x39, 0x3A, 0x3B, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x42, 0x43, 0x44, 0x45, - 0x46, 0x47, 0x48, 0x49, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x50, 0x51, 0x52, 0x53, - 0x54, 0x55, 0x56, 0x57, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5E, 0x5F, 0x60, 0x61, - 0x62, 0x63, 0x64, 0x65, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6C, 0x6D, 0x6E, 0x6F, - // 15 [-120, 119] = x * 15/16 - 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F, 0x90, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, - 0x97, 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F, 0x9F, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, - 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAE, 0xAF, 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, - 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBD, 0xBE, 0xBF, 0xC0, 0xC1, 0xC2, 0xC3, - 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0, 0xD1, 0xD2, - 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF, 0xE0, 0xE1, - 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF, 0xF0, - 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF, - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, - 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, - 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, - 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, - 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, - 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, - 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, - 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, - // 16 [-128, 127] - 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F, - 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F, - 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF, - 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF, - 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, - 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF, - 0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF, - 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF, - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, - 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, - 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, - 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, - 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, - 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, - 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, - 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F, -}; \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/IMuse/imList.cpp b/components/darkforces/tfe/TFE_Jedi/IMuse/imList.cpp deleted file mode 100644 index 3aaab1a4..00000000 --- a/components/darkforces/tfe/TFE_Jedi/IMuse/imList.cpp +++ /dev/null @@ -1,62 +0,0 @@ -#include "imList.h" -#include "imuse.h" -#include - -namespace TFE_Jedi -{ - s32 ImListAdd(ImList** list, ImList* item) - { - if (!item || item->next || item->prev) - { - IM_LOG_ERR("%s", "List arg err when adding"); - return imArgErr; - } - - ImList* next = *list; - item->next = next; - if (next) - { - next->prev = item; - } - item->prev = nullptr; - - *list = item; - return imSuccess; - } - - s32 ImListRemove(ImList** list, ImList* item) - { - ImList* curItem = *list; - if (!item || !curItem) - { - IM_LOG_ERR("%s", "List arg err when removing."); - return imArgErr; - } - while (curItem && item != curItem) - { - curItem = curItem->next; - } - if (!curItem) - { - IM_LOG_ERR("%s", "Item not on list."); - return imNotFound; - } - - if (item->next) - { - item->next->prev = item->prev; - } - if (item->prev) - { - item->prev->next = item->next; - } - else - { - *list = item->next; - } - item->next = nullptr; - item->prev = nullptr; - - return imSuccess; - } -} // namespace TFE_Jedi diff --git a/components/darkforces/tfe/TFE_Jedi/IMuse/imList.h b/components/darkforces/tfe/TFE_Jedi/IMuse/imList.h deleted file mode 100644 index ff8a38e7..00000000 --- a/components/darkforces/tfe/TFE_Jedi/IMuse/imList.h +++ /dev/null @@ -1,36 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// iMuse System -// The IMuse system used by Dark Forces. -// -// Copyright note: -// While the project as a whole is licensed under GPL-2.0, some of the -// code under TFE_Jedi/ was derived from reverse-engineered -// code from "Dark Forces" (DOS) which is copyrighted by LucasArts. -// The original renderer is contained in RClassic_Fixed/ and the -// RClassic_Float/ and RClassic_GPU/ sub-renderers are derived from -// that code. -// -// I consider the reverse-engineering to be "Fair Use" - a means of -// supporting the games on other platforms and to improve support on -// existing platforms without claiming ownership of the games -// themselves or their IPs. -// -// That said using this code in a commercial project is risky without -// permission of the original copyright holders (LucasArts). -////////////////////////////////////////////////////////////////////// -#include - -namespace TFE_Jedi -{ - struct ImList - { - ImList* prev; - ImList* next; - }; - #define IM_LIST_ADD(list, item) ImListAdd((ImList**)&list, (ImList*)item) - #define IM_LIST_REM(list, item) ImListRemove((ImList**)&list, (ImList*)item) - - s32 ImListRemove(ImList** list, ImList* item); - s32 ImListAdd(ImList** list, ImList* item); -} // namespace TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/IMuse/imMidiCmd.cpp b/components/darkforces/tfe/TFE_Jedi/IMuse/imMidiCmd.cpp deleted file mode 100644 index 89a3a6fa..00000000 --- a/components/darkforces/tfe/TFE_Jedi/IMuse/imMidiCmd.cpp +++ /dev/null @@ -1,195 +0,0 @@ -#include "imMidiCmd.h" -#include "imMidiPlayer.h" -#include "imuse.h" -#include "imTrigger.h" -#include "imList.h" -#include "midiData.h" -#include -#include -#include -#include -#include - -namespace TFE_Jedi -{ - extern s32 ImJumpMidiInternal(ImPlayerData* data, s32 chunk, s32 measure, s32 beat, s32 tick, s32 sustain); - - #define MIDI_FUNC(f) (MidiEventFunc)f - void ImCheckForTrackEnd(ImPlayerData* playerData, u8* data); - void ImMidiSystemFunc(ImPlayerData* playerData, u8* chunkData); - void ImMidiPressure(ImMidiPlayer* player, u8 channel, u8 arg1, u8 arg2); - - // Midi functions for each message type - see ImMidiMessageIndex{} above. - MidiCmdFuncUnion s_jumpMidiCmdFunc[IM_MID_COUNT] = - { - MIDI_FUNC(nullptr), // IM_MID_NOTE_OFF - MIDI_FUNC(nullptr), // IM_MID_NOTE_ON - MIDI_FUNC(nullptr), // IM_MID_KEY_PRESSURE - MIDI_FUNC(nullptr), // IM_MID_CONTROL_CHANGE - MIDI_FUNC(nullptr), // IM_MID_PROGRAM_CHANGE - MIDI_FUNC(nullptr), // IM_MID_CHANNEL_PRESSURE - MIDI_FUNC(nullptr), // IM_MID_PITCH_BEND - MIDI_FUNC(nullptr), // IM_MID_SYS_FUNC - MIDI_FUNC(ImMidiEvent), // IM_MID_EVENT - }; - MidiCmdFuncUnion s_jumpMidiSustainOpenCmdFunc[IM_MID_COUNT] = - { - MIDI_FUNC(ImMidiJumpSustainOpen_NoteOff),// IM_MID_NOTE_OFF - MIDI_FUNC(ImMidiJumpSustainOpen_NoteOn), // IM_MID_NOTE_ON - MIDI_FUNC(nullptr), // IM_MID_KEY_PRESSURE - MIDI_FUNC(nullptr), // IM_MID_CONTROL_CHANGE - MIDI_FUNC(nullptr), // IM_MID_PROGRAM_CHANGE - MIDI_FUNC(nullptr), // IM_MID_CHANNEL_PRESSURE - MIDI_FUNC(nullptr), // IM_MID_PITCH_BEND - MIDI_FUNC(nullptr), // IM_MID_SYS_FUNC - MIDI_FUNC(ImCheckForTrackEnd) // IM_MID_EVENT - }; - MidiCmdFuncUnion s_jumpMidiSustainCmdFunc[IM_MID_COUNT] = - { - MIDI_FUNC(nullptr), // IM_MID_NOTE_OFF - MIDI_FUNC(ImMidiJumpSustain_NoteOn), // IM_MID_NOTE_ON - MIDI_FUNC(nullptr), // IM_MID_KEY_PRESSURE - MIDI_FUNC(nullptr), // IM_MID_CONTROL_CHANGE - MIDI_FUNC(nullptr), // IM_MID_PROGRAM_CHANGE - MIDI_FUNC(nullptr), // IM_MID_CHANNEL_PRESSURE - MIDI_FUNC(nullptr), // IM_MID_PITCH_BEND - MIDI_FUNC(nullptr), // IM_MID_SYS_FUNC - MIDI_FUNC(ImCheckForTrackEnd) // IM_MID_EVENT - }; - MidiCmdFuncUnion s_midiCmdFunc[IM_MID_COUNT] = - { - MIDI_FUNC(ImMidiNoteOff), // IM_MID_NOTE_OFF - MIDI_FUNC(ImMidiNoteOn), // IM_MID_NOTE_ON - MIDI_FUNC(ImMidiPressure), // IM_MID_KEY_PRESSURE - MIDI_FUNC(ImMidiCommand), // IM_MID_CONTROL_CHANGE - MIDI_FUNC(ImMidiProgramChange), // IM_MID_PROGRAM_CHANGE - MIDI_FUNC(ImMidiPressure), // IM_MID_CHANNEL_PRESSURE - MIDI_FUNC(ImMidiPitchBend), // IM_MID_PITCH_BEND - MIDI_FUNC(ImMidiSystemFunc), // IM_MID_SYS_FUNC - MIDI_FUNC(ImMidiEvent), // IM_MID_EVENT - }; - - void ImCheckForTrackEnd(ImPlayerData* playerData, u8* data) - { - if (data[0] == META_END_OF_TRACK) - { - s_midiTrackEnd = 1; - } - } - - s32 ImUpdateHook(s32* hook, u8 newValue) - { - if (newValue) - { - if ((s32)newValue != (*hook)) - { - return imFail; - } - IM_DBG_MSG("Set Hook = 0, Hook = %d, New Value = %d", *hook, newValue); - *hook = 0; - return imSuccess; - } - - if ((*hook) == 0x80) - { - IM_DBG_MSG("Hook = %d", newValue); - *hook = (s32)newValue; - return imFail; - } - - return imSuccess; - } - - void ImMidiSystemFunc(ImPlayerData* playerData, u8* chunkData) - { - if (*chunkData != 0xf0) - { - return; - } - - u8* data = chunkData + 1; - if (data[0] > 0x7f || data[1] != 0x7d) - { - return; - } - data += 2; - - u8 value = *data; - data++; - if (value == 0) - { - // Set Marker - ImMidiPlayer* player = playerData->player; - u8 marker = *data; - player->marker = marker; - - IM_DBG_MSG("Set Marker: %d", marker); - ImSetSoundTrigger(player->soundId, (void*)data); - } - else if (value == 1) - { - value = *data; - data++; - - ImMidiPlayer* player = playerData->player; - if (ImUpdateHook(&player->hook, value) == imSuccess) - { - IM_DBG_MSG("JMP(I) h:%d", value); - ImJumpMidiInternal(playerData, data[0], (data[1] << 7) | data[2], data[3], (data[4] << 7) | data[5], data[6]); - } - else - { - IM_DBG_MSG("JMP(I) Skipped - h:%d", value); - } - } - else if (value == 3) - { - ImMidiPlayer* player = playerData->player; - IM_DBG_MSG("Marker: 0x80"); - player->marker = 0x80; - ImSetSoundTrigger(player->soundId, (void*)data); - } - else - { - IM_LOG_ERR("%s", "mp got bad sysex msg..."); - } - } - - void ImMidiPressure(ImMidiPlayer* player, u8 channel, u8 arg1, u8 arg2) - { - // Not used by Dark Forces. - IM_LOG_ERR("%s", "ImMidiPressure() unimplemented."); - assert(0); - } - - ////////////////////////////////////////////// - // Low-level Midi Commands - ////////////////////////////////////////////// - void ImNoteOff(s32 channelId, s32 instrId) - { - TFE_MidiPlayer::sendMessageDirect(MID_NOTE_OFF | channelId, instrId); - } - - void ImNoteOn(s32 channelId, s32 instrId, s32 velocity) - { - TFE_MidiPlayer::sendMessageDirect(MID_NOTE_ON | channelId, instrId, velocity); - } - - void ImControlChange(s32 channelId, MidiController ctrl, s32 value) - { - TFE_MidiPlayer::sendMessageDirect(MID_CONTROL_CHANGE | channelId, ctrl, value); - } - - void ImProgramChange(u8 channel, u8 msg) - { - TFE_MidiPlayer::sendMessageDirect(MID_PROGRAM_CHANGE | channel, msg); - } - - // For Pan, "Fine" resolution is 14-bit where 8192 (0x2000) is center - MID_PAN_LSB - // Most devices use coarse adjustment instead (7 bits, 64 is center) - MID_PAN_MSB - void ImSetPanFine(s32 channel, s32 pan) - { - // General Midi uses MID_PAN_MSB, so this is a no-op. - } - -} // namespace TFE_Jedi diff --git a/components/darkforces/tfe/TFE_Jedi/IMuse/imMidiCmd.h b/components/darkforces/tfe/TFE_Jedi/IMuse/imMidiCmd.h deleted file mode 100644 index d8bca187..00000000 --- a/components/darkforces/tfe/TFE_Jedi/IMuse/imMidiCmd.h +++ /dev/null @@ -1,75 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// iMuse System -// The IMuse system used by Dark Forces. -// -// Copyright note: -// While the project as a whole is licensed under GPL-2.0, some of the -// code under TFE_Jedi/ was derived from reverse-engineered -// code from "Dark Forces" (DOS) which is copyrighted by LucasArts. -// The original renderer is contained in RClassic_Fixed/ and the -// RClassic_Float/ and RClassic_GPU/ sub-renderers are derived from -// that code. -// -// I consider the reverse-engineering to be "Fair Use" - a means of -// supporting the games on other platforms and to improve support on -// existing platforms without claiming ownership of the games -// themselves or their IPs. -// -// That said using this code in a commercial project is risky without -// permission of the original copyright holders (LucasArts). -////////////////////////////////////////////////////////////////////// -#include -#include -#include "imConst.h" - -namespace TFE_Jedi -{ - struct ImPlayerData; - struct ImMidiPlayer; - - enum ImMidiMessageIndex - { - IM_MID_NOTE_OFF = 0, - IM_MID_NOTE_ON = 1, - IM_MID_KEY_PRESSURE = 2, - IM_MID_CONTROL_CHANGE = 3, - IM_MID_PROGRAM_CHANGE = 4, - IM_MID_CHANNEL_PRESSURE = 5, - IM_MID_PITCH_BEND = 6, - IM_MID_SYS_FUNC = 7, - IM_MID_EVENT = 8, - IM_MID_COUNT = 9, - }; - - typedef void(*MidiEventFunc)(ImPlayerData* playerData, u8* chunkData); - typedef void(*MidiCmdFunc)(ImMidiPlayer* player, u8 channel, u8 arg1, u8 arg2); - union MidiCmdFuncUnion - { - MidiEventFunc evtFunc; - MidiCmdFunc cmdFunc; - }; - - extern MidiCmdFuncUnion s_jumpMidiCmdFunc[IM_MID_COUNT]; - extern MidiCmdFuncUnion s_jumpMidiSustainOpenCmdFunc[IM_MID_COUNT]; - extern MidiCmdFuncUnion s_jumpMidiSustainCmdFunc[IM_MID_COUNT]; - extern MidiCmdFuncUnion s_midiCmdFunc[IM_MID_COUNT]; - - // Low level midi commands. - void ImNoteOff(s32 channelId, s32 instrId); - void ImNoteOn(s32 channelId, s32 instrId, s32 velocity); - void ImControlChange(s32 channelId, MidiController ctrl, s32 value); - void ImProgramChange(u8 channel, u8 msg); - void ImSetPanFine(s32 channel, s32 pan); - - // TODO: These are currently defined in imuse.cpp, move them over. - extern void ImMidiJumpSustainOpen_NoteOff(ImMidiPlayer* player, u8 channelId, u8 arg1, u8 arg2); - extern void ImMidiJumpSustainOpen_NoteOn(ImMidiPlayer* player, u8 channelId, u8 arg1, u8 arg2); - extern void ImMidiJumpSustain_NoteOn(ImMidiPlayer* player, u8 channelId, u8 arg1, u8 arg2); - extern void ImMidiCommand(ImMidiPlayer* player, s32 channelIndex, s32 midiCmd, s32 value); - extern void ImMidiNoteOff(ImMidiPlayer* player, u8 channel, u8 arg1, u8 arg2); - extern void ImMidiNoteOn(ImMidiPlayer* player, u8 channel, u8 arg1, u8 arg2); - extern void ImMidiProgramChange(ImMidiPlayer* player, u8 channel, u8 arg1, u8 arg2); - extern void ImMidiPitchBend(ImMidiPlayer* player, u8 channel, u8 arg1, u8 arg2); - extern void ImMidiEvent(ImPlayerData* playerData, u8* chunkData); -} // namespace TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/IMuse/imMidiPlayer.cpp b/components/darkforces/tfe/TFE_Jedi/IMuse/imMidiPlayer.cpp deleted file mode 100644 index 14e356d3..00000000 --- a/components/darkforces/tfe/TFE_Jedi/IMuse/imMidiPlayer.cpp +++ /dev/null @@ -1,203 +0,0 @@ -#include "imMidiPlayer.h" -#include "imuse.h" -#include "imList.h" -#include "imSoundFader.h" -#include "imTrigger.h" -#include "midiData.h" -#include -#include -#include -#include -#include - -namespace TFE_Jedi -{ - // TODO: Fix these externs. - extern void ImMidiSetupParts(); - - ImSustainedSound* s_imActiveSustainedSounds = nullptr; - ImSustainedSound* s_imFreeSustainedSounds = nullptr; - ImSustainedSound s_sustainedSounds[24]; - ImMidiPlayer* s_midiPlayerList = nullptr; - s32 s_midiTrackEnd = 0; - s32 s_imEndOfTrack = 0; - - void ImSetEndOfTrack(); - - // Advance the current sound to the next tick. - void ImAdvanceMidi(ImPlayerData* playerData, u8* sndData, MidiCmdFuncUnion* midiCmdFunc) - { - s_imEndOfTrack = 0; - s32 tick = playerData->curTick; - s32 nextTick = playerData->nextTick; - u8* chunkData = sndData + playerData->chunkOffset + playerData->chunkPtr; - IM_DBG_MSG("t: %03d.%02d.%03d -> %03d.%02d.%03d", ImTime_getMeasure(tick), ImTime_getBeat(tick), ImTime_getTicks(tick), - ImTime_getMeasure(nextTick), ImTime_getBeat(nextTick), ImTime_getTicks(nextTick)); - - while (tick < nextTick) - { - u8 data = chunkData[0]; - if (data < MID_EXCLUSIVE_START) - { - if (data & 0x80) - { - u8 msgType = (data & 0x70) >> 4; - u8 channel = data & 0x0f; - if (midiCmdFunc[msgType].cmdFunc) - { - midiCmdFunc[msgType].cmdFunc(playerData->player, channel, chunkData[1], chunkData[2]); - } - chunkData += c_midiMsgSize[msgType]; - } - else - { - IM_LOG_ERR("Invalid midi message: %u", data); - assert(0); - } - } - else - { - u8 msgType = 0; - if (data == MID_EXCLUSIVE_START) - { - msgType = IM_MID_SYS_FUNC; - } - else - { - if (data != 0xff) - { - IM_LOG_ERR("sq unknown msg type 0x%x...", data); - ImReleaseMidiPlayer(playerData->player); - assert(0); - return; - } - msgType = IM_MID_EVENT; - chunkData++; - } - if (midiCmdFunc[msgType].evtFunc) - { - midiCmdFunc[msgType].evtFunc(playerData, chunkData); - } - - // This steps past the current chunk, if we don't know what a chunk is, it should be skipped. - chunkData++; - chunkData += midi_getVariableLengthValue(&chunkData); - } - - // If we have reached the end, then we are done for now. - if (s_imEndOfTrack) - { - return; - } - - u32 dt = midi_getVariableLengthValue(&chunkData); - tick += dt; - if ((tick & 0xffff) >= playerData->ticksPerBeat) - { - tick = ImFixupSoundTick(playerData, tick); - } - } - playerData->curTick = tick; - u8* chunkBase = sndData + playerData->chunkOffset; - playerData->chunkPtr = s32(chunkData - chunkBase); - } - - s32 ImFixupSoundTick(ImPlayerData* data, s32 value) - { - while (ImTime_getTicks(value) >= data->ticksPerBeat) - { - value = value - data->ticksPerBeat + ImTime_setBeat(1); - // This needs to be here so that we don't overflow the number of beats (15). - while (ImTime_getBeatFixed(value) >= data->beatsPerMeasure) - { - value = value - data->beatsPerMeasure + ImTime_setMeasure(1); - } - } - // Just in case. - while (ImTime_getBeatFixed(value) >= data->beatsPerMeasure) - { - value = value - data->beatsPerMeasure + ImTime_setMeasure(1); - } - return value; - } - - void ImRemoveInstrumentSound(ImMidiPlayer* player) - { - ImSustainedSound* sustainedSound = s_imActiveSustainedSounds; - while (sustainedSound) - { - ImSustainedSound* next = sustainedSound->next; - if (player == sustainedSound->midiPlayer) - { - ImMidiNoteOff(sustainedSound->midiPlayer, sustainedSound->channelId, sustainedSound->instrumentId, 0); - IM_LIST_REM(s_imActiveSustainedSounds, sustainedSound); - IM_LIST_ADD(s_imFreeSustainedSounds, sustainedSound); - } - sustainedSound = next; - } - } - - void ImFreeMidiChannel(ImMidiChannel* channelData) - { - if (channelData) - { - const u32 channelMask = c_channelMask[channelData->channelId]; - channelData->sustain = 0; - for (s32 i = 0; i < MIDI_INSTRUMENT_COUNT; i++) - { - u32 instrMask = channelData->instrumentMask[i]; - if (channelData->instrumentMask[i] & channelMask) - { - ImNoteOff(channelData->channelId, i); - channelData->instrumentMask[i] &= ~channelMask; - } - else if (channelData->instrumentMask2[i] & channelMask) - { - ImNoteOff(channelData->channelId, i); - channelData->instrumentMask2[i] &= ~channelMask; - } - } - } - } - - void ImResetMidiOutChannel(ImMidiOutChannel* channel) - { - ImMidiChannel* data = channel->data; - if (data) - { - ImFreeMidiChannel(data); - data->player = nullptr; - data->channel = nullptr; - channel->data = nullptr; - } - } - - void ImReleaseMidiPlayer(ImMidiPlayer* player) - { - s32 res = IM_LIST_REM(s_midiPlayerList, player); - ImClearSoundFaders(player->soundId, -1); - ImClearTrigger(player->soundId, -1, -1); - ImRemoveInstrumentSound(player); - ImSetEndOfTrack(); - - for (s32 i = 0; i < MIDI_CHANNEL_COUNT; i++) - { - ImMidiOutChannel* channel = &player->channels[i]; - ImResetMidiOutChannel(channel); - } - - player->soundId = IM_NULL_SOUNDID; - if (player->sharedPart) - { - player->sharedPart->sharedPartId = 0; - player->sharedPart->sharedPart = nullptr; - player->sharedPart = nullptr; - } - ImMidiSetupParts(); - } - - void ImSetEndOfTrack() - { - s_imEndOfTrack = 1; - } -} // namespace TFE_Jedi diff --git a/components/darkforces/tfe/TFE_Jedi/IMuse/imMidiPlayer.h b/components/darkforces/tfe/TFE_Jedi/IMuse/imMidiPlayer.h deleted file mode 100644 index de4cda65..00000000 --- a/components/darkforces/tfe/TFE_Jedi/IMuse/imMidiPlayer.h +++ /dev/null @@ -1,153 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// iMuse System -// The IMuse system used by Dark Forces. -// -// Copyright note: -// While the project as a whole is licensed under GPL-2.0, some of the -// code under TFE_Jedi/ was derived from reverse-engineered -// code from "Dark Forces" (DOS) which is copyrighted by LucasArts. -// The original renderer is contained in RClassic_Fixed/ and the -// RClassic_Float/ and RClassic_GPU/ sub-renderers are derived from -// that code. -// -// I consider the reverse-engineering to be "Fair Use" - a means of -// supporting the games on other platforms and to improve support on -// existing platforms without claiming ownership of the games -// themselves or their IPs. -// -// That said using this code in a commercial project is risky without -// permission of the original copyright holders (LucasArts). -////////////////////////////////////////////////////////////////////// -#include -#include "imConst.h" -#include "imMidiCmd.h" - -namespace TFE_Jedi -{ - struct ImMidiPlayer; - struct ImMidiOutChannel; - struct ImMidiChannel; - - struct ImSustainedSound - { - ImSustainedSound* prev; - ImSustainedSound* next; - ImMidiPlayer* midiPlayer; - s32 instrumentId; - s32 channelId; - s32 curTick; - s32 curTickFixed; - }; - - struct ImMidiChannel - { - ImMidiPlayer* player; - ImMidiOutChannel* channel; - ImMidiChannel* sharedMidiChannel; - s32 channelId; - - s32 pgm; - s32 priority; - s32 noteReq; - s32 volume; - - s32 pan; - s32 modulation; - s32 finalPan; - s32 sustain; - - u32* instrumentMask; - u32* instrumentMask2; - ImMidiPlayer* sharedPart; - ImMidiOutChannel* sharedChannel; - ImMidiChannel* prevChannel; - s32 sharedId; - - s32 sharedPgm; - s32 sharedPriority; - s32 sharedNoteReq; - s32 sharedVolume; - - s32 sharedPan; - s32 sharedModulation; - s32 sharedFinalPan; - s32 sharedSustain; - - u32* sharedInstrumentMask; - u32* sharedInstrumentMask2; - }; - - struct ImMidiOutChannel - { - ImMidiChannel* data; - s32 partStatus; - s32 partPgm; - s32 partTrim; - s32 partPriority; - s32 priority; - s32 partNoteReq; - s32 partVolume; - s32 groupVolume; - s32 partPan; - s32 modulation; - s32 sustain; - s32 pitchBend; - s32 outChannelCount; - s32 pan; - }; - - struct ImPlayerData - { - ImMidiPlayer* player; - ImSoundId soundId; - s32 seqIndex; - s32 chunkOffset; - s32 nextTick; // Next tick - s32 curTick; // Current tick - s32 chunkPtr; - s32 ticksPerBeat; - s32 beatsPerMeasure; - s32 tickAccum; // Fixed-point tick accumulator, preserves the fractional part of the tick to avoid time being lost. - s32 tempo; - s32 step; - s32 speed; - s32 stepFixed; - }; - - struct ImMidiPlayer - { - ImMidiPlayer* prev; - ImMidiPlayer* next; - ImPlayerData* data; - ImMidiPlayer* sharedPart; - ImSoundId sharedPartId; - ImSoundId soundId; - s32 marker; - s32 group; - s32 priority; - s32 volume; - s32 groupVolume; - s32 pan; - s32 detune; - s32 transpose; - s32 mailbox; - s32 hook; - - ImMidiOutChannel channels[MIDI_CHANNEL_COUNT]; - }; - - extern s32 s_imEndOfTrack; - extern s32 s_midiTrackEnd; - extern ImSustainedSound* s_imActiveSustainedSounds; - extern ImSustainedSound* s_imFreeSustainedSounds; - extern ImSustainedSound s_sustainedSounds[24]; - extern ImMidiPlayer* s_midiPlayerList; - - extern s32 ImFixupSoundTick(ImPlayerData* data, s32 value); - extern void ImAdvanceMidi(ImPlayerData* playerData, u8* sndData, MidiCmdFuncUnion* midiCmdFunc); - extern void ImReleaseMidiPlayer(ImMidiPlayer* player); - extern void ImResetMidiOutChannel(ImMidiOutChannel* channel); - extern void ImFreeMidiChannel(ImMidiChannel* channelData); - extern void ImRemoveInstrumentSound(ImMidiPlayer* player); -} // namespace TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/IMuse/imOpCodes.h b/components/darkforces/tfe/TFE_Jedi/IMuse/imOpCodes.h deleted file mode 100644 index a40af0df..00000000 --- a/components/darkforces/tfe/TFE_Jedi/IMuse/imOpCodes.h +++ /dev/null @@ -1,59 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// iMuse System -// The IMuse system used by Dark Forces. -// -// Copyright note: -// While the project as a whole is licensed under GPL-2.0, some of the -// code under TFE_Jedi/ was derived from reverse-engineered -// code from "Dark Forces" (DOS) which is copyrighted by LucasArts. -// The original renderer is contained in RClassic_Fixed/ and the -// RClassic_Float/ and RClassic_GPU/ sub-renderers are derived from -// that code. -// -// I consider the reverse-engineering to be "Fair Use" - a means of -// supporting the games on other platforms and to improve support on -// existing platforms without claiming ownership of the games -// themselves or their IPs. -// -// That said using this code in a commercial project is risky without -// permission of the original copyright holders (LucasArts). -////////////////////////////////////////////////////////////////////// -#include - -enum ImOpCode -{ - imInitialize = 0x0000, - imTerminate = 0x0001, - imPrintf = 0x0002, - imPause = 0x0003, - imResume = 0x0004, - imSave = 0x0005, - imRestore = 0x0006, - imSetGroupVol = 0x0007, - imStartSound = 0x0008, - imStopSound = 0x0009, - imStopAllSounds = 0x000A, - imGetNextSound = 0x000B, - imSetParam = 0x000C, - imGetParam = 0x000D, - imFadeParam = 0x000E, - imSetHook = 0x000F, - imGetHook = 0x0010, - imSetTrigger = 0x0011, - imCheckTrigger = 0x0012, - imClearTrigger = 0x0013, - imDeferCommand = 0x0014, - - imJumpMidi = 0x0015, - imScanMidi = 0x0016, - imSendMidiMsg = 0x0017, - imShareParts = 0x0018, - - imStartStream = 0x0019, - imSwitchStream = 0x001A, - imProcessStreams = 0x001B, - imQueryNextStream = 0x001C, - - imUndefined = 0x001D -}; \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/IMuse/imSoundFader.cpp b/components/darkforces/tfe/TFE_Jedi/IMuse/imSoundFader.cpp deleted file mode 100644 index ce7d3050..00000000 --- a/components/darkforces/tfe/TFE_Jedi/IMuse/imSoundFader.cpp +++ /dev/null @@ -1,182 +0,0 @@ -#include "imuse.h" -#include "imSoundFader.h" -#include -#include -#include - -namespace TFE_Jedi -{ - //////////////////////////////////////////////////// - // Structures - //////////////////////////////////////////////////// - struct ImSoundFader - { - s32 active; - ImSoundId soundId; - iMuseParameter param; - s32 curValue; - s32 timeRem; - s32 fadeTime; - s32 signedStep; - s32 unsignedStep; - s32 errAccum; - s32 stepDir; - }; - - ///////////////////////////////////////////////////// - // Internal State - ///////////////////////////////////////////////////// - static s32 s_imFadersActive = 0; - static ImSoundFader s_soundFaders[MIDI_CHANNEL_COUNT]; - - /////////////////////////////////////////////////////////// - // API - /////////////////////////////////////////////////////////// - void ImUpdateSoundFaders() - { - ImSoundFader* fader = s_soundFaders; - if (s_imFadersActive) - { - s_imFadersActive = 0; - for (s32 i = 0; i < 16; i++, fader++) - { - if (fader->active) - { - s_imFadersActive = 1; - fader->timeRem--; - if (fader->timeRem == 0) - { - fader->active = 0; - } - - s32 nextValue = fader->curValue + fader->signedStep; - fader->errAccum += fader->unsignedStep; - if (fader->errAccum >= fader->fadeTime) - { - fader->errAccum -= fader->fadeTime; - nextValue += fader->stepDir; - } - - if (nextValue != fader->curValue) - { - fader->curValue = nextValue; - // Only update the parameter on the '0' ticks - i.e. once every 6 'frames'. - // Note this should always hit on the last frame ('0') - so fades should always work. - if ((fader->timeRem % 6) == 0) - { - if (fader->param == soundVol && nextValue == 0) - { - ImStopSound(fader->soundId); - } - else - { - ImSetParam(fader->soundId, fader->param, nextValue); - } - } - } - } - } - } - } - - s32 ImClearAllSoundFaders() - { - for (s32 i = 0; i < MIDI_CHANNEL_COUNT; i++) - { - s_soundFaders[i].active = 0; - } - s_imFadersActive = 0; - return imSuccess; - } - - void ImClearSoundFaders(ImSoundId soundId, s32 param) - { - ImSoundFader* fader = s_soundFaders; - for (s32 i = 0; i < MIDI_CHANNEL_COUNT; i++, fader++) - { - if (fader->active) - { - if (soundId != fader->soundId) { continue; } - - if (iMuseParameter(param) == fader->param || param == -1) - { - fader->active = 0; - } - } - } - } - - // soundID is the sound (digital or midi) to adjust. - // param is of type 'iMuseParameter' - // value is the target value for the parameter (such as volume). - // time is the amount of time this should take, 0 for instant changes (negative values are invalid). - // time is in "iMuse frames" = 1/60th of a sec. per frame. - s32 ImFadeParam(ImSoundId soundId, s32 param, s32 value, s32 time) - { - // Check that the sound and time are valid. - if (!soundId || time < 0) - { - return imArgErr; - } - // Check to see if the parameter is fadable. - if (param != soundPriority && param != soundVol && param != soundPan && param != soundDetune && param != midiSpeed && (param & 0xff00) != midiPartTrim) - { - return imArgErr; - } - - // Clear any matching sound faders. - ImClearSoundFaders(soundId, param); - - // If the 'time' is 0, the effect should happen instantly. - if (time == 0) - { - if (param == soundVol && value == 0) - { - ImStopSound(soundId); - } - else - { - ImSetParam(soundId, param, value); - } - return imSuccess; - } - - // Otherwise find a free fader and set it up. - ImSoundFader* fader = s_soundFaders; - for (s32 i = 0; i < MIDI_CHANNEL_COUNT; i++, fader++) - { - if (!fader->active) - { - fader->soundId = soundId; - fader->param = iMuseParameter(param); - fader->curValue = ImGetParam(soundId, param); - fader->fadeTime = time; - fader->timeRem = time; - - s32 valueChange = value - fader->curValue; - fader->signedStep = valueChange / time; - - s32 stepDir = 1; - s32 absValueChange = valueChange; - if (valueChange < 0) - { - stepDir = -1; - absValueChange = -valueChange; - } - fader->stepDir = stepDir; - // Adsolute value, change over time. - fader->unsignedStep = absValueChange / time; - - fader->errAccum = 0; - fader->active = 1; - s_imFadersActive = 1; - return imSuccess; - } - } - - // If we get here, no free fader was found, so return an error. - IM_LOG_WRN("fd unable to alloc fade.", NULL); - return imAllocErr; - } - -} // namespace TFE_Jedi diff --git a/components/darkforces/tfe/TFE_Jedi/IMuse/imSoundFader.h b/components/darkforces/tfe/TFE_Jedi/IMuse/imSoundFader.h deleted file mode 100644 index 2b564c2f..00000000 --- a/components/darkforces/tfe/TFE_Jedi/IMuse/imSoundFader.h +++ /dev/null @@ -1,30 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// iMuse System -// The IMuse system used by Dark Forces. -// -// Copyright note: -// While the project as a whole is licensed under GPL-2.0, some of the -// code under TFE_Jedi/ was derived from reverse-engineered -// code from "Dark Forces" (DOS) which is copyrighted by LucasArts. -// The original renderer is contained in RClassic_Fixed/ and the -// RClassic_Float/ and RClassic_GPU/ sub-renderers are derived from -// that code. -// -// I consider the reverse-engineering to be "Fair Use" - a means of -// supporting the games on other platforms and to improve support on -// existing platforms without claiming ownership of the games -// themselves or their IPs. -// -// That said using this code in a commercial project is risky without -// permission of the original copyright holders (LucasArts). -////////////////////////////////////////////////////////////////////// -#include - -namespace TFE_Jedi -{ - void ImUpdateSoundFaders(); - s32 ImClearAllSoundFaders(); - void ImClearSoundFaders(ImSoundId soundId, s32 param); - s32 ImFadeParam(ImSoundId soundId, s32 param, s32 value, s32 time); -} // namespace TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/IMuse/imTrigger.cpp b/components/darkforces/tfe/TFE_Jedi/IMuse/imTrigger.cpp deleted file mode 100644 index b59d80a8..00000000 --- a/components/darkforces/tfe/TFE_Jedi/IMuse/imTrigger.cpp +++ /dev/null @@ -1,230 +0,0 @@ -#include "imuse.h" -#include "imSoundFader.h" -#include -#include -#include - -namespace TFE_Jedi -{ - //////////////////////////////////////////////////// - // Structures - //////////////////////////////////////////////////// - struct ImTrigger - { - ImSoundId soundId; - s32 marker; - iptr opcode; // opcode is sometimes used to pass pointers. - s64 args[10]; - }; - - struct ImDeferCmd - { - s32 time; - iptr opcode; - s64 args[10]; - }; - - typedef void(*ImTriggerCmdFunc)(char*); - - enum ImTriggerConst - { - ImMaxDeferredCmd = 8, - }; - - ///////////////////////////////////////////////////// - // Internal State - ///////////////////////////////////////////////////// - static ImTrigger s_triggers[MIDI_CHANNEL_COUNT]; - static ImDeferCmd s_deferCmd[ImMaxDeferredCmd]; - static s32 s_imDeferredCmds = 0; - - void ImHandleDeferredCommand(ImDeferCmd* cmd); - void ImTriggerExecute(ImTrigger* trigger, void* marker); - - /////////////////////////////////////////////////////////// - // API - /////////////////////////////////////////////////////////// - s32 ImSetTrigger(ImSoundId soundId, s32 marker, iptr opcode) - { - if (!soundId) { return imArgErr; } - - ImTrigger* trigger = s_triggers; - for (s32 i = 0; i < MIDI_CHANNEL_COUNT; i++, trigger++) - { - if (!trigger->soundId) - { - trigger->soundId = soundId; - trigger->marker = marker; - trigger->opcode = opcode; - - // The code beyond this point handles variable parameters - but this isn't used in Dark Forces. - // It blindly copies 10 arguments from the stack and stores them in trigger->args[] - return imSuccess; - } - } - IM_LOG_WRN("tr unable to alloc trigger.", NULL); - return imAllocErr; - } - - // Returns the number of matching triggers. - s32 ImCheckTrigger(ImSoundId soundId, s32 marker, iptr opcode) - { - ImTrigger* trigger = s_triggers; - s32 count = 0; - for (s32 i = 0; i < MIDI_CHANNEL_COUNT; i++, trigger++) - { - if (trigger->soundId) - { - if ((soundId == imWildcard || soundId == trigger->soundId) && - (marker == imWildcard || marker == trigger->marker) && - (opcode == imWildcard || opcode == trigger->opcode)) - { - count++; - } - } - } - return count; - } - - s32 ImClearTrigger(ImSoundId soundId, s32 marker, iptr opcode) - { - ImTrigger* trigger = s_triggers; - for (s32 i = 0; i < MIDI_CHANNEL_COUNT; i++, trigger++) - { - // Only clear set triggers and match Sound ID - if (trigger->soundId && (soundId == imWildcard || soundId == trigger->soundId)) - { - // Match marker and opcode. - if ((marker == imWildcard || marker == trigger->marker) && - (opcode == imWildcard || opcode == trigger->opcode)) - { - trigger->soundId = IM_NULL_SOUNDID; - } - } - } - return imSuccess; - } - - s32 ImClearTriggersAndCmds() - { - for (s32 i = 0; i < MIDI_CHANNEL_COUNT; i++) - { - s_triggers[i].soundId = IM_NULL_SOUNDID; - } - for (s32 i = 0; i < ImMaxDeferredCmd; i++) - { - s_deferCmd[i].time = 0; - } - s_imDeferredCmds = 0; - return imSuccess; - } - - // The original function can take a variable number of arguments, but it is used exactly once in Dark Forces, - // so I simplified it. - s32 ImDeferCommand(s32 time, iptr opcode, s64 arg1) - { - ImDeferCmd* cmd = s_deferCmd; - if (time == 0) - { - return imArgErr; - } - - for (s32 i = 0; i < ImMaxDeferredCmd; i++, cmd++) - { - if (cmd->time == 0) - { - cmd->opcode = opcode; - cmd->time = time; - - // This copies variable arguments into cmd->args[], for Dark Forces, only a single argument is used. - cmd->args[0] = arg1; - s_imDeferredCmds = 1; - return imSuccess; - } - } - - IM_LOG_WRN("tr unable to alloc deferred cmd.", NULL); - return imAllocErr; - } - - void ImHandleDeferredCommands() - { - ImDeferCmd* cmd = s_deferCmd; - if (s_imDeferredCmds) - { - s_imDeferredCmds = 0; - for (s32 i = 0; i < ImMaxDeferredCmd; i++, cmd++) - { - if (cmd->time) - { - s_imDeferredCmds = 1; - cmd->time--; - if (cmd->time == 0) - { - ImHandleDeferredCommand(cmd); - } - } - } - } - } - - void ImSetSoundTrigger(ImSoundId soundId, void* marker) - { - // Look for triggers with matching soundId. - ImTrigger* trigger = s_triggers; - for (s32 i = 0; i < MIDI_CHANNEL_COUNT; i++, trigger++) - { - ImSoundId triggerSndId = trigger->soundId; - // Trigger is null or doesn't match. - if (!triggerSndId || triggerSndId != soundId) - { - continue; - } - if (trigger->marker) - { - // trigger->marker is never non-zero when running Dark Forces. - IM_LOG_ERR("%s", "trigger->marker should always be 0 in Dark Forces."); - assert(0); - } - // Execute the matching trigger. - ImTriggerExecute(trigger, marker); - } - } - - //////////////////////////////////// - // Internal - //////////////////////////////////// - void ImHandleDeferredCommand(ImDeferCmd* cmd) - { - // In Dark Forces, only stop sound is used, basically to deal stopping a sound after an iMuse transition. - // In the original code, this calls the dispatch function and pushes all 10 arguments. - // A non-dispatch version can be created here with a simple case statement. - if (cmd->opcode == imStopSound) - { - ImStopSound(cmd->args[0]); - } - else - { - IM_LOG_ERR("%s", "Unimplemented deferred command."); - assert(0); - } - } - - void ImTriggerExecute(ImTrigger* trigger, void* marker) - { - trigger->soundId = IM_NULL_SOUNDID; - if (trigger->opcode < imUndefined) - { - // This is not used by Dark Forces. - // In the original code, this passed in all 10 parameters. - // ImProcessCommand(trigger->opcode, *arg0, *arg1, *arg2); - IM_LOG_ERR("%s", "Unimplemented trigger opcode."); - assert(0); - } - else - { - ImTriggerCmdFunc(trigger->opcode)((char*)marker); - } - } - -} // namespace TFE_Jedi diff --git a/components/darkforces/tfe/TFE_Jedi/IMuse/imTrigger.h b/components/darkforces/tfe/TFE_Jedi/IMuse/imTrigger.h deleted file mode 100644 index ef6beeb4..00000000 --- a/components/darkforces/tfe/TFE_Jedi/IMuse/imTrigger.h +++ /dev/null @@ -1,35 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// iMuse System -// The IMuse system used by Dark Forces. -// -// Copyright note: -// While the project as a whole is licensed under GPL-2.0, some of the -// code under TFE_Jedi/ was derived from reverse-engineered -// code from "Dark Forces" (DOS) which is copyrighted by LucasArts. -// The original renderer is contained in RClassic_Fixed/ and the -// RClassic_Float/ and RClassic_GPU/ sub-renderers are derived from -// that code. -// -// I consider the reverse-engineering to be "Fair Use" - a means of -// supporting the games on other platforms and to improve support on -// existing platforms without claiming ownership of the games -// themselves or their IPs. -// -// That said using this code in a commercial project is risky without -// permission of the original copyright holders (LucasArts). -////////////////////////////////////////////////////////////////////// -#include -#include "imuse.h" - -namespace TFE_Jedi -{ - s32 ImSetTrigger(ImSoundId soundId, s32 marker, iptr opcode); - s32 ImCheckTrigger(ImSoundId soundId, s32 marker, iptr opcode); - s32 ImClearTrigger(ImSoundId soundId, s32 marker, iptr opcode); - s32 ImClearTriggersAndCmds(); - - s32 ImDeferCommand(s32 time, iptr opcode, s64 arg1); - void ImHandleDeferredCommands(); - void ImSetSoundTrigger(ImSoundId soundId, void* marker); -} // namespace TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/IMuse/imuse.cpp b/components/darkforces/tfe/TFE_Jedi/IMuse/imuse.cpp deleted file mode 100644 index 49e5b38b..00000000 --- a/components/darkforces/tfe/TFE_Jedi/IMuse/imuse.cpp +++ /dev/null @@ -1,2502 +0,0 @@ -#include "imuse.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "imList.h" -#include "imTrigger.h" -#include "imSoundFader.h" -#include "imMidiPlayer.h" -#include "imDigitalSound.h" -#include "midiData.h" - -namespace TFE_Jedi -{ - #define IM_MAX_SOUNDS 32 - #define IM_MIDI_FILE_COUNT 6 - #define IM_MIDI_PLAYER_COUNT 2 - #define imuse_alloc(size) TFE_Memory::region_alloc(s_memRegion, size) - #define imuse_realloc(ptr, size) TFE_Memory::region_realloc(s_memRegion, ptr, size) - #define imuse_free(ptr) TFE_Memory::region_free(s_memRegion, ptr) - - //////////////////////////////////////////////////// - // Structures - //////////////////////////////////////////////////// - struct ImSound - { - ImSound* prev; - ImSound* next; - ImSoundId id; - char name[10]; - // 14-bytes unused by Dark Forces/iMuse in struct, removed in TFE. - s32 refCount; - }; - - struct ImResource - { - u32 resType; - char name[8]; - - ImResource* next; - s32 type; - s32 id; - - s32 flags; - s32 volume; - - s32 var1; - s32 var2; - u8* varptr; - u8* varhdl; - - u8* data; - }; - - ///////////////////////////////////////////////////// - // Forward Declarations - ///////////////////////////////////////////////////// - void ImUpdate(); - void ImUpdateMidi(); - void ImUpdateSustainedNotes(); - - void ImAdvanceMidiPlayer(ImPlayerData* playerData); - void ImJumpSustain(ImMidiPlayer* player, u8* sndData, ImPlayerData* playerPrevData, ImPlayerData* playerNextData); - void ImMidiGetInstruments(ImMidiPlayer* player, u32* soundMidiInstrumentMask, s32* midiInstrumentCount); - s32 ImMidiGetTickDelta(ImPlayerData* playerData, u32 prevTick, u32 tick); - void ImMidiProcessSustain(ImPlayerData* playerData, u8* sndData, MidiCmdFuncUnion* midiCmdFunc, ImMidiPlayer* player); - - void ImPrintMidiState(); - s32 ImJumpMidiInternal(ImPlayerData* data, s32 chunk, s32 measure, s32 beat, s32 tick, s32 sustain); - s32 ImPauseMidi(); - s32 ImResumeMidi(); - s32 ImHandleChannelGroupVolume(); - s32 ImGetGroupVolume(s32 group); - void ImHandleChannelVolumeChange(ImMidiPlayer* player, ImMidiOutChannel* channel); - void ImMidiSetupParts(); - void ImAssignMidiChannel(ImMidiPlayer* player, ImMidiOutChannel* channel, ImMidiChannel* midiChannel); - u8* ImGetSoundData(ImSoundId id); - u8* ImInternalGetSoundData(ImSoundId soundId); - ImMidiChannel* ImGetFreeMidiChannel(); - ImMidiPlayer* ImGetFreePlayer(s32 priority); - s32 ImStartMidiPlayerInternal(ImPlayerData* data, ImSoundId soundId); - s32 ImSetupMidiPlayer(ImSoundId soundId, s32 priority); - s32 ImFreeMidiPlayer(ImSoundId soundId); - s32 ImReleaseAllPlayers(); - s32 ImGetSoundType(ImSoundId soundId); - s32 ImSetMidiParam(ImSoundId soundId, s32 param, s32 value); - s32 ImGetMidiTimeParam(ImPlayerData* data, s32 param); - s32 ImGetMidiParam(ImSoundId soundId, s32 param); - s32 ImGetPendingSoundCount(ImSoundId soundId); - s32 ImWrapValue(s32 value, s32 a, s32 b); - void ImHandleChannelPriorityChange(ImMidiPlayer* player, ImMidiOutChannel* channel); - ImSoundId ImFindNextMidiSound(ImSoundId soundId); - ImMidiPlayer* ImGetMidiPlayer(ImSoundId soundId); - s32 ImSetHookMidi(ImSoundId soundId, s32 value); - s32 ImSetSequence(ImPlayerData* data, u8* sndData, s32 seqIndex); - - void ImMidiLock(); - void ImMidiUnlock(); - s32 ImGetDeltaTime(); - s32 ImMidiSetSpeed(ImPlayerData* data, u32 value); - void ImSetTempo(ImPlayerData* data, u32 tempo); - void ImSetMidiTicksPerBeat(ImPlayerData* data, s32 ticksPerBeat, s32 beatsPerMeasure);; - - ImSoundId ImOpenMidi(const char* name); - s32 ImCloseMidi(char* name); - s32 ImMidiCall(s32 index, s32 id, s32 arg1, s32 arg2, s32 arg3); - - // Midi channel commands - void ImMidiChannelSetVolume(ImMidiChannel* midiChannel, s32 volume); - void ImHandleChannelDetuneChange(ImMidiPlayer* player, ImMidiOutChannel* channel); - void ImHandleChannelPitchBend(ImMidiPlayer* player, s32 channelIndex, s32 fractValue, s32 intValue); - void ImMidiChannelSetPgm(ImMidiChannel* midiChannel, s32 pgm); - void ImMidiChannelSetPriority(ImMidiChannel* midiChannel, s32 priority); - void ImMidiChannelSetPartNoteReq(ImMidiChannel* midiChannel, s32 noteReq); - void ImMidiChannelSetPan(ImMidiChannel* midiChannel, s32 pan); - void ImMidiChannelSetModulation(ImMidiChannel* midiChannel, s32 modulation); - void ImHandleChannelPan(ImMidiChannel* midiChannel, s32 pan); - void ImSetChannelSustain(ImMidiChannel* midiChannel, s32 sustain); - - void ImMidiStopAllNotes(ImMidiPlayer* player); - - void ImHandleNoteOff(ImMidiChannel* midiChannel, s32 instrumentId); - void ImHandleNoteOn(ImMidiChannel* channel, s32 instrumentId, s32 velocity); - void ImMidi_DrumOut_NoteOn(s32 priority, s32 partNoteReq, s32 volume, s32 instrumentId, s32 velocity); - - // Initialization - s32 ImSetupFilesModule(iMuseInitData* initData); - s32 ImInitializeGroupVolume(); - s32 ImInitializeSlots(iMuseInitData* initData); - s32 ImInitializeSustain(); - s32 ImInitializePlayers(); - s32 ImInitializeMidiEngine(iMuseInitData* initData); - s32 ImInitializeInterrupt(iMuseInitData* initData); - - ///////////////////////////////////////////////////// - // Internal State - ///////////////////////////////////////////////////// - // These need to be updated across threads. - atomic_s32 s_imPause; - atomic_s32 s_midiPaused; - atomic_s32 s_midiLock; - - static iMuseInitData s_imInitData = { 0, IM_WAVE_11kHz, 8, 6944 }; - - // TODO: Split modules into files. - // Files module. - static iMuseInitData* s_imFilesData; - - const char* c_midi = "MIDI"; - const char* c_crea = "Crea"; - static s32 s_iMuseTimestepMicrosec = 6944; - - static MemoryRegion* s_memRegion = nullptr; - static s32 s_iMuseTimeInMicrosec = 0; - static s32 s_iMuseTimeLong = 0; - static s32 s_iMuseSystemTime = 0; - - static ImMidiChannel s_midiChannels[MIDI_CHANNEL_COUNT - 1]; - static s32 s_midiFrame = 0; - static s32 s_trackTicksRemaining; - static s32 s_midiTickDelta; - static bool s_imEnableMusic = true; - - static ImMidiPlayer s_midiPlayers[IM_MIDI_PLAYER_COUNT]; - static ImPlayerData s_playerData[IM_MIDI_PLAYER_COUNT]; - static ImPlayerData s_imSoundNextState; - static ImPlayerData s_imSoundPrevState; - static s32 s_midiDriverNotReady = 1; - - static s32 s_groupVolume[groupMaxCount] = { 0 }; - static s32 s_soundGroupVolume[groupMaxCount] = - { - imMaxVolume, imMaxVolume, imMaxVolume, imMaxVolume, - imMaxVolume, imMaxVolume, imMaxVolume, imMaxVolume, - imMaxVolume, imMaxVolume, imMaxVolume, imMaxVolume, - imMaxVolume, imMaxVolume, imMaxVolume, imMaxVolume, - }; - - static u32 s_midiSustainChannelMask[MIDI_CHANNEL_COUNT] = { 0 }; - static u32 s_midiInstrumentChannelMask[MIDI_INSTRUMENT_COUNT]; - static u32 s_midiInstrumentChannelMask1[MIDI_INSTRUMENT_COUNT]; - static u32 s_midiInstrumentChannelMask3[MIDI_INSTRUMENT_COUNT]; - static u32 s_midiInstrumentChannelMaskShared[MIDI_INSTRUMENT_COUNT]; - static u32 s_curMidiInstrumentMask[MIDI_INSTRUMENT_COUNT]; - static s32 s_curInstrumentCount; - - static ImSound s_sounds[IM_MAX_SOUNDS]; - static ImSound* s_soundList = nullptr; - - static s32 s_ImDrumOutCh_priority; - static s32 s_ImDrumOutCh_partNoteReq; - static s32 s_ImDrumOutCh_volume; - - // Midi files loaded. - static u32 s_midiFileCount = 0; - static u8* s_midiFiles[IM_MIDI_FILE_COUNT]; - - static ImResourceCallback s_resourceCallback = nullptr; - - /////////////////////////////////////////////////////////// - // Main API - // ----------------------------------------------------- - // This includes both high level functions and low level - // Note: - // The original DOS code wrapped calls to an internal - // dispatch function which is removed for TFE, calling - // the functions directly instead. - /////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////// - // High level functions - //////////////////////////////////////////////////// - s32 ImSetMasterVol(s32 vol) - { - ImSetGroupVol(groupMaster, vol); - return imSuccess; - } - - s32 ImGetMasterVol(void) - { - return ImGetGroupVolume(groupMaster); - } - - s32 ImSetMusicVol(s32 vol) - { - ImSetGroupVol(groupMusic, vol); - return imSuccess; - } - - s32 ImGetMusicVol(void) - { - return ImGetGroupVolume(groupMusic); - } - - s32 ImSetSfxVol(s32 vol) - { - ImSetGroupVol(groupSfx, vol); - return imSuccess; - } - - s32 ImGetSfxVol(void) - { - return ImGetGroupVolume(groupSfx); - } - - s32 ImSetVoiceVol(s32 vol) - { - ImSetGroupVol(groupVoice, vol); - return imSuccess; - } - - s32 ImGetVoiceVol(void) - { - return ImGetGroupVolume(groupVoice); - } - - s32 ImStartSfx(ImSoundId soundId, s32 priority) - { - if (ImStartSound(soundId, priority) == imSuccess) - { - return ImSetParam(soundId, soundGroup, groupSfx); - } - return imFail; - } - - s32 ImStartVoice(ImSoundId soundId, s32 priority) - { - if (ImStartSound(soundId, priority) == imSuccess) - { - return ImSetParam(soundId, soundGroup, groupVoice); - } - return imFail; - } - - s32 ImStartMusic(ImSoundId soundId, s32 priority) - { - // Not used in Dark Forces. - assert(0); - return imNotImplemented; - } - - void ImUnloadAll(void) - { - for (s32 n = 0; n < 10; n++) - { - ImSound* sound = &s_sounds[n]; - if (sound->id) - { - ImCloseMidi(sound->name); - } - } - } - - // Called ImLoadSound() in the original code, but it only loads midi. - ImSoundId ImLoadMidi(const char *name) - { - if (!s_imEnableMusic || !name || !name[0]) - { - return imFail; - } - - ImSoundId soundId = ImFindMidi(name); - if (soundId) - { - ImSound* sound = s_soundList; - while (sound) - { - if (sound->id == soundId) - { - sound->refCount++; - return soundId; - } - sound = sound->next; - } - } - - for (s32 n = 0; n < 10; n++) - { - ImSound* sound = &s_sounds[n]; - if (!sound->id) - { - if (strlen(name) >= 17) - { - IM_LOG_ERR("Name too long: %s", name); - return imFail; - } - soundId = ImOpenMidi(name); - if (!soundId) - { - IM_LOG_ERR("%s", "Host couldn't load sound"); - return imFail; - } - - strcpy(sound->name, name); - sound->id = soundId; - sound->refCount = 1; - IM_LIST_ADD(s_soundList, sound); - return soundId; - } - } - - IM_LOG_ERR("%s", "Sound List FULL!"); - return imFail; - } - - //////////////////////////////////////////////////// - // Low level functions - //////////////////////////////////////////////////// - s32 ImInitialize(MemoryRegion* memRegion) - { - ////////////////////////////////////////////////////////////////////////////////////////// - // Notes: - // * In DOS, a memory region is setup for iMuse (the descriptor setup), for TFE this - // is replicated by using the passed in memory region. - // * Initialize Debug skipped since it is a no-op for Dark Forces due to settings. - // * The host interrupt handler is NULL for Dark Forces. - // * Memory descriptors and PIC/PIT setup are skipped since they are DOS specific. - // * Init data is hardcoded to Dark Forces values and reduced to relevant fields. - ////////////////////////////////////////////////////////////////////////////////////////// - s_memRegion = memRegion; - - s_iMuseTimeInMicrosec = 0; - s_iMuseTimeLong = 0; - IM_LOG_MSG("Initializing...COMMANDS module..."); - - if (ImSetupFilesModule(&s_imInitData) == imSuccess) - { - if (ImInitializeGroupVolume() != imSuccess) { return imFail; } - if (ImClearAllSoundFaders() != imSuccess) { return imFail; } - if (ImClearTriggersAndCmds() != imSuccess) { return imFail; } - if (ImInitializeMidiEngine(&s_imInitData) != imSuccess) { return imFail; } - if (ImInitializeDigitalAudio(&s_imInitData) != imSuccess) { return imFail; } - if (ImInitializeInterrupt(&s_imInitData) != imSuccess) { return imFail; } - - s_imPause = 0; - IM_LOG_MSG("Initialization complete..."); - } - return imSuccess; - } - - s32 ImTerminate(void) - { - ImStopAllSounds(); - ImUnloadAll(); - ImTerminateDigitalAudio(); - TFE_MidiPlayer::midiClearCallback(); - TFE_MidiPlayer::setMaximumNoteLength(); - - s_iMuseTimeInMicrosec = 0; - s_iMuseTimeLong = 0; - s_iMuseSystemTime = 0; - s_midiFrame = 0; - s_trackTicksRemaining = 0; - s_midiTickDelta = 0; - s_soundList = nullptr; - s_midiFileCount = 0; - s_resourceCallback = nullptr; - - return imSuccess; - } - - s32 ImSetResourceCallback(ImResourceCallback callback) - { - s_resourceCallback = callback; - return imSuccess; - } - - s32 ImPause(void) - { - s32 res = imSuccess; - if (!s_imPause) - { - res = ImPauseMidi(); - res |= ImPauseDigitalSound(); - } - s_imPause++; - s32 pause = s_imPause; - return (res == imSuccess) ? pause : res; - } - - s32 ImResume(void) - { - s32 res = imSuccess; - if (s_imPause == 1) - { - res = ImResumeMidi(); - res |= ImResumeDigitalSound(); - } - if (s_imPause) - { - s_imPause--; - } - s32 pause = s_imPause; - return (res == imSuccess) ? pause : res; - } - - s32 ImSetGroupVol(s32 group, s32 volume) - { - if (group >= groupMaxCount || volume > imMaxVolume) - { - return imArgErr; - } - else if (volume == imGetValue) - { - return s_groupVolume[group]; - } - - s32 groupVolume = s_groupVolume[group]; - if (group == groupMaster) - { - s_groupVolume[groupMaster] = volume; - s_soundGroupVolume[groupMaster] = 0; - for (s32 i = 1; i < groupMaxCount; i++) - { - s_soundGroupVolume[i] = ((s_groupVolume[i] + 1) * volume) >> imVolumeShift; - } - } - else - { - s_groupVolume[group] = volume; - s_soundGroupVolume[group] = ((s_groupVolume[groupMaster] + 1) * volume) >> imVolumeShift; - } - ImHandleChannelGroupVolume(); - - return groupVolume; - } - - s32 ImStartSound(ImSoundId soundId, s32 priority) - { - u8* data = ImInternalGetSoundData(soundId); - if (!data) - { - IM_LOG_ERR("%s", "null sound addr in StartSound()"); - return imFail; - } - - s32 i = 0; - for (; i < 4; i++) - { - if (data[i] != c_midi[i]) - { - break; - } - } - if (i == 4) // Midi - { - return ImSetupMidiPlayer(soundId, priority); - } - else // Digital Sound - { - const u8* creative = (u8*)c_crea; - for (i = 0; i < 4; i++) - { - if (data[i] != creative[i]) - { - return imFail; - } - } - return ImStartDigitalSound(soundId, priority); - } - return imSuccess; - } - - s32 ImStopSound(ImSoundId soundId) - { - s32 type = ImGetSoundType(soundId); - if (type == typeMidi) - { - return ImFreeMidiPlayer(soundId); - } - else if (type == typeWave) - { - return ImFreeWaveSoundById(soundId); - } - return imFail; - } - - s32 ImStopAllSounds(void) - { - s32 res = ImClearAllSoundFaders(); - res |= ImClearTriggersAndCmds(); - res |= ImReleaseAllPlayers(); - res |= ImFreeAllWaveSounds(); - - TFE_MidiPlayer::stopMidiSound(); - return res; - } - - ImSoundId ImGetNextSound(ImSoundId soundId) - { - ImSoundId nextMidiId = ImFindNextMidiSound(soundId); - ImSoundId nextWaveId = ImFindNextWaveSound(soundId); - if (nextMidiId == 0 || (nextWaveId && u64(nextMidiId) >= u64(nextWaveId))) - { - return nextWaveId; - } - return nextMidiId; - } - - s32 ImSetParam(ImSoundId soundId, s32 param, s32 value) - { - iMuseSoundType type = (iMuseSoundType)ImGetSoundType(soundId); - if (type == typeMidi) - { - return ImSetMidiParam(soundId, param, value); - } - else if (type == typeWave) - { - return ImSetWaveParam(soundId, param, value); - } - return imFail; - } - - s32 ImGetParam(ImSoundId soundId, s32 param) - { - iMuseSoundType type = (iMuseSoundType)ImGetSoundType(soundId); - if (param == soundType) - { - return type; - } - else if (param == soundPendCount) - { - return ImGetPendingSoundCount(soundId); - } - else if (type == typeMidi) - { - return ImGetMidiParam(soundId, param); - } - else if (type == typeWave) - { - return ImGetWaveParam(soundId, param); - } - else if (param == soundPlayCount) - { - // This is zero here, since there is no valid type - - // so no sounds are that type are playing. - return 0; - } - return imFail; - } - - s32 ImSetHook(ImSoundId soundId, s32 value) - { - iMuseSoundType type = (iMuseSoundType)ImGetSoundType(soundId); - if (type == typeMidi) - { - return ImSetHookMidi(soundId, value); - } - else if (type == typeWave) - { - // IM_TODO - } - return imFail; - } - - s32 ImGetHook(ImSoundId soundId) - { - // Not called from Dark Forces. - return imSuccess; - } - - s32 ImJumpMidi(ImSoundId soundId, s32 chunk, s32 measure, s32 beat, s32 tick, s32 sustain) - { - ImMidiPlayer* player = ImGetMidiPlayer(soundId); - if (!player) { return imInvalidSound; } - - IM_DBG_MSG("JMP(C)"); - return ImJumpMidiInternal(player->data, chunk, measure, beat, tick, sustain); - } - - s32 ImSendMidiMsg(ImSoundId soundId, s32 arg1, s32 arg2, s32 arg3) - { - // Not called by Dark Forces. - IM_DBG_MSG("MSG [s 0x%x, a1 0x%x, a2 0x%x, a3 0x%x]", soundId, arg1, arg2, arg3); - assert(0); - return imNotImplemented; - } - - s32 ImShareParts(ImSoundId sound1, ImSoundId sound2) - { - ImMidiPlayer* player1 = ImGetMidiPlayer(sound1); - ImMidiPlayer* player2 = ImGetMidiPlayer(sound2); - if (!player1 || player1->sharedPart || !player2 || player2->sharedPart) - { - return imFail; - } - - player1->sharedPart = player2; - player2->sharedPart = player1; - player1->sharedPartId = sound2; - player2->sharedPartId = sound1; - ImMidiSetupParts(); - return imSuccess; - } - - /////////////////////////////////////////////////////////// - // Internal "main loop" - /////////////////////////////////////////////////////////// - // Main update entry point which is called at a fixed rate (see ImGetDeltaTime). - // This is responsible for updating the midi players and updating digital audio playback. - void ImUpdate() - { - const s32 dtInMicrosec = ImGetDeltaTime(); - - // Update Midi and Audio - ImUpdateMidi(); - if (s_imPause) - { - return; - } - - // Update faders and deferred commands that update at a rate of 60 fps. - s_iMuseTimeInMicrosec += dtInMicrosec; - while (s_iMuseTimeInMicrosec >= 16667) - { - s_iMuseTimeInMicrosec -= 16667; - s32 prevTime = s_iMuseSystemTime; - s_iMuseSystemTime++; // increment the system time every 1/60th of a second. - - ImUpdateSoundFaders(); - ImHandleDeferredCommands(); - } - - // Update Group Volumes every 6 "frames". - s_iMuseTimeLong += dtInMicrosec; - while (s_iMuseTimeLong >= 100000) // ~6 frames @ 60Hz - { - s_iMuseTimeLong -= 100000; - - s32 musicVolume = ImSetGroupVol(groupMusic, imGetValue); - ImSoundId soundId = IM_NULL_SOUNDID; - do - { - soundId = ImGetNextSound(soundId); - if (soundId) - { - if (ImGetParam(soundId, soundGroup) == groupVoice) - { - musicVolume = (musicVolume * 82) >> imVolumeShift; - break; - } - } - } while (soundId); - - s32 dippedMusicVolume = ImSetGroupVol(groupDippedMusic, imGetValue); - if (dippedMusicVolume > musicVolume) - { - dippedMusicVolume -= 6; - if (dippedMusicVolume <= musicVolume) - { - dippedMusicVolume = musicVolume; - } - ImSetGroupVol(groupDippedMusic, dippedMusicVolume); - } - else if (dippedMusicVolume != musicVolume) - { - dippedMusicVolume += 3; - if (dippedMusicVolume >= musicVolume) - { - dippedMusicVolume = musicVolume; - } - ImSetGroupVol(groupDippedMusic, dippedMusicVolume); - } - } - } - - void ImUpdateMidi() - { - if (s_midiLock) - { - return; - } - - ImMidiLock(); - s_midiFrame++; - if (s_midiFrame > 75) // Prints the iMuse state every 75 "frames". - { - s_midiFrame = 0; - ImPrintMidiState(); - } - if (!s_midiPaused) // Update the midi state and instruments. - { - ImMidiPlayer* player = s_midiPlayerList; - while (player) - { - ImAdvanceMidiPlayer(player->data); - player = player->next; - } - ImUpdateSustainedNotes(); - } - ImMidiUnlock(); - } - - /////////////////////////////////////////////////////////// - // Internal Implementation - /////////////////////////////////////////////////////////// - void ImPrintMidiState() - { - // Compiled out in the original code. - // TODO: Replace with TFE debug data. - } - - s32 ImJumpMidiInternal(ImPlayerData* data, s32 chunk, s32 measure, s32 beat, s32 tick, s32 sustain) - { - u8* sndData = ImInternalGetSoundData(data->soundId); - if (!sndData) { return imInvalidSound; } - - measure--; - beat--; - chunk--; - if (measure >= 1000 || beat >= 12 || tick >= 480) - { - return imArgErr; - } - - ImMidiLock(); - memcpy(&s_imSoundPrevState, data, sizeof(ImPlayerData)); - memcpy(&s_imSoundNextState, data, sizeof(ImPlayerData)); - - IM_DBG_MSG("JMP c:%d t:%03d.%02d.%03d -> c:%d t:%03d.%02d.%03d [s:%d]", s_imSoundNextState.seqIndex, ImTime_getMeasure(data->nextTick), ImTime_getBeat(data->nextTick), ImTime_getTicks(data->nextTick), chunk, measure, beat, tick, sustain); - u32 nextTick = ImFixupSoundTick(data, ImTime_setMeasure(measure) + ImTime_setBeat(beat) + ImTime_setTick(tick)); - // If we either change chunks or jump backwards, the sequence needs to be setup/reset. - if (chunk != s_imSoundNextState.seqIndex || nextTick < (u32)s_imSoundNextState.nextTick) - { - if (ImSetSequence(&s_imSoundNextState, sndData, chunk)) - { - IM_LOG_ERR("%s", "sq jump to invalid chunk."); - ImMidiUnlock(); - return imFail; - } - } - s_imSoundNextState.nextTick = nextTick; - ImAdvanceMidi(&s_imSoundNextState, sndData, s_jumpMidiCmdFunc); - if (s_imEndOfTrack) - { - IM_LOG_WRN("sq jump to invalid ms:bt:tk...", NULL); - ImMidiUnlock(); - return imFail; - } - - if (sustain) - { - // Loop through the channels. - for (s32 c = 0; c < MIDI_CHANNEL_COUNT; c++) - { - ImMidiCommand(data->player, c, MID_SUSTAIN_SWITCH, 0); - ImMidiCommand(data->player, c, MID_MODULATIONWHEEL_MSB, 0); - ImHandleChannelPitchBend(data->player, c, 0, imPanCenter); - } - ImJumpSustain(data->player, sndData, &s_imSoundPrevState, &s_imSoundNextState); - } - else - { - ImMidiStopAllNotes(data->player); - } - - memcpy(data, &s_imSoundNextState, sizeof(ImPlayerData)); - s_imEndOfTrack = 1; - ImMidiUnlock(); - - return imSuccess; - } - - void ImUpdateSustainedNotes() - { - ImSustainedSound* sustainedSound = s_imActiveSustainedSounds; - while (sustainedSound) - { - ImSustainedSound* next = sustainedSound->next; - ImMidiPlayer* player = sustainedSound->midiPlayer; - ImPlayerData* data = player->data; - - sustainedSound->curTickFixed += data->stepFixed; - sustainedSound->curTick -= floor16(sustainedSound->curTickFixed); - sustainedSound->curTickFixed = fract16(sustainedSound->curTickFixed); - - if (sustainedSound->curTick < 0) - { - ImMidiNoteOff(sustainedSound->midiPlayer, sustainedSound->channelId, sustainedSound->instrumentId, 0); - IM_LIST_REM(s_imActiveSustainedSounds, sustainedSound); - IM_LIST_ADD(s_imFreeSustainedSounds, sustainedSound); - } - sustainedSound = next; - } - } - - s32 ImPauseMidi() - { - s_midiPaused = 1; - return imSuccess; - } - - s32 ImResumeMidi() - { - s_midiPaused = 0; - return imSuccess; - } - - s32 ImHandleChannelGroupVolume() - { - ImMidiPlayer* player = s_midiPlayerList; - while (player) - { - s32 sndVol = player->volume + 1; - s32 groupVol = ImGetGroupVolume(player->group); - player->groupVolume = (sndVol * groupVol) >> imVolumeShift; - - for (s32 i = 0; i < MIDI_CHANNEL_COUNT; i++) - { - ImMidiOutChannel* channel = &player->channels[i]; - ImHandleChannelVolumeChange(player, channel); - } - player = player->next; - } - return imSuccess; - } - - s32 ImGetGroupVolume(s32 group) - { - if (group >= groupMaxCount) - { - return imArgErr; - } - return s_soundGroupVolume[group]; - } - - void ImHandleChannelVolumeChange(ImMidiPlayer* player, ImMidiOutChannel* channel) - { - if (!channel->outChannelCount) - { - // This should never be hit. - IM_LOG_ERR("%s", "Sound channel has 0 output channels."); - } - s32 partTrim = channel->partTrim + 1; - s32 partVolume = channel->partVolume + 1; - channel->groupVolume = (partVolume * partTrim * player->groupVolume) >> (2*imVolumeShift); - - // These checks seem redundant. If groupVolume is != 0, then by definition partTrim and partVolume are != 0. - if (!player->groupVolume || !channel->partTrim || !channel->partVolume) - { - if (!channel->data) { return; } - ImResetMidiOutChannel(channel); - } - else if (channel->data) // has volume. - { - ImMidiChannelSetVolume(channel->data, channel->groupVolume); - } - ImMidiSetupParts(); - } - - void ImMidiSetupParts() - { - ImMidiPlayer* player = s_midiPlayerList; - ImMidiPlayer* newPlayer = nullptr; - ImMidiPlayer* prevPlayer = nullptr; - ImMidiOutChannel* newChannel = nullptr; - ImMidiOutChannel* prevChannel = nullptr; - s32 cont = 0; - - while (player) - { - ImMidiPlayer* sharedPart = player->sharedPart; - for (s32 m = 0; m < MIDI_CHANNEL_COUNT; m++) - { - ImMidiOutChannel* channel = &player->channels[m]; - ImMidiOutChannel* sharedChannel = sharedPart ? &sharedPart->channels[m] : nullptr; - - if (sharedChannel && sharedChannel->partStatus) - { - if (channel->data && !sharedChannel->data) - { - if (sharedPart->groupVolume && sharedChannel->partTrim && sharedChannel->partVolume) - { - ImAssignMidiChannel(sharedPart, sharedChannel, channel->data); - } - } - else if (!channel->data && sharedChannel->data && channel->partStatus && player->groupVolume && - channel->partTrim && channel->partVolume) - { - ImAssignMidiChannel(player, channel, sharedChannel->data->sharedMidiChannel); - } - } - - if (channel->data) - { - if (sharedChannel && sharedChannel->data) - { - if (sharedChannel->priority > channel->priority) { continue; } - } - if (prevChannel) - { - if (channel->priority > prevChannel->priority) { continue; } - } - prevPlayer = player; - prevChannel = channel; - cont = 1; - } - else if (channel->partStatus && player->groupVolume && channel->partTrim && channel->partVolume) - { - if (!newChannel || channel->priority > newChannel->priority) - { - newPlayer = player; - newChannel = channel; - cont = 0; - } - } - } - player = player->next; - - // This will only start once all of the players has been exhausted. - if (newChannel && !player) - { - ImMidiChannel* midiChannel = ImGetFreeMidiChannel(); - if (!midiChannel) - { - s32 newPriority = newChannel->priority; - s32 prevPriority = prevChannel->priority; - if (newPriority <= prevPriority && (prevPriority != newPriority || !cont || newPlayer == prevPlayer)) - { - return; - } - - // The new channel has higher priority, so reset the previous and reassign. - ImMidiChannel* prev = prevChannel->data; - ImResetMidiOutChannel(prev->channel); - - ImMidiChannel* shared = prev->sharedMidiChannel; - if (shared && shared->channel) - { - ImResetMidiOutChannel(shared->channel); - } - midiChannel = prev; - } - ImAssignMidiChannel(newPlayer, newChannel, midiChannel); - - player = s_midiPlayerList; - newPlayer = nullptr; - prevPlayer = nullptr; - newChannel = nullptr; - prevChannel = nullptr; - } - } - } - - ImMidiChannel* ImGetFreeMidiChannel() - { - for (s32 i = 0; i < MIDI_CHANNEL_COUNT - 1; i++) - { - if (!s_midiChannels[i].player && !s_midiChannels[i].sharedPart) - { - return &s_midiChannels[i]; - } - } - return nullptr; - } - - void ImAssignMidiChannel(ImMidiPlayer* player, ImMidiOutChannel* channel, ImMidiChannel* midiChannel) - { - if (!channel || !midiChannel) - { - return; - } - - channel->data = midiChannel; - midiChannel->player = player; - midiChannel->channel = channel; - - ImMidiChannelSetPgm(midiChannel, channel->partPgm); - ImMidiChannelSetPriority(midiChannel, channel->priority); - ImMidiChannelSetPartNoteReq(midiChannel, channel->partNoteReq); - ImMidiChannelSetVolume(midiChannel, channel->groupVolume); - ImMidiChannelSetPan(midiChannel, channel->partPan); - ImMidiChannelSetModulation(midiChannel, channel->modulation); - ImHandleChannelPan(midiChannel, channel->pan); - ImSetChannelSustain(midiChannel, channel->sustain); - } - - u8* ImGetSoundData(ImSoundId id) - { - if (id & imMidiFlag) - { - const ImSoundId index = id & imMidiMask; - assert(index < IM_MIDI_FILE_COUNT); - return index < IM_MIDI_FILE_COUNT ? s_midiFiles[index] : nullptr; - } - else - { - u8* data = nullptr; - if (s_resourceCallback) - { - data = s_resourceCallback(id); - } - else - { - // Cast ImSoundId as a pointer. - ImResource* res = (ImResource*)id; - data = res->data; - } - return data; - } - return nullptr; - } - - s32 ImInternal_SoundValid(ImSoundId soundId) - { - // Since soundId can be a pointer, we can't use the original imValidMask since the pointer may be 64-bit. - // if (soundId && soundId < imValidMask) - if (soundId) - { - return 1; - } - return 0; - } - - u8* ImInternalGetSoundData(ImSoundId soundId) - { - if (ImInternal_SoundValid(soundId)) - { - return ImGetSoundData(soundId); - } - return nullptr; - } - - ImMidiPlayer* ImGetFreePlayer(s32 priority) - { - ImMidiPlayer* midiPlayer = s_midiPlayers; - for (s32 i = 0; i < 2; i++, midiPlayer++) - { - if (!midiPlayer->soundId) - { - return midiPlayer; - } - } - IM_LOG_WRN("no spare players", NULL); - return nullptr; - } - - s32 ImStartMidiPlayerInternal(ImPlayerData* data, ImSoundId soundId) - { - u8* sndData = ImInternalGetSoundData(soundId); - if (!sndData) - { - return imInvalidSound; - } - - data->soundId = soundId; - data->tickAccum = 0; - ImSetTempo(data, 500000); // microseconds per beat, 500000 = 120 beats per minute - ImMidiSetSpeed(data, 128); - ImSetMidiTicksPerBeat(data, 480, 4); - return ImSetSequence(data, sndData, 0); - } - - ImSoundId ImFindMidi(const char* name) - { - ImSound* sound = s_soundList; - while (sound) - { - if (!strcasecmp(name, sound->name) && sound->refCount) - { - return sound->id; - } - sound = sound->next; - } - return IM_NULL_SOUNDID; - } - - ImSoundId loadMidiFile(char* midiFile) - { - FilePath filePath; - if (!TFE_Paths::getFilePath(midiFile, &filePath)) - { - IM_LOG_ERR("Cannot find midi file '%s'.", midiFile); - return IM_NULL_SOUNDID; - } - FileStream file; - if (!file.open(&filePath, Stream::MODE_READ)) - { - IM_LOG_ERR("Cannot open midi file '%s'.", midiFile); - return IM_NULL_SOUNDID; - } - assert(s_midiFileCount < IM_MIDI_FILE_COUNT); - - size_t len = file.getSize(); - s_midiFiles[s_midiFileCount] = (u8*)imuse_alloc(len); - file.readBuffer(s_midiFiles[s_midiFileCount], u32(len)); - file.close(); - - ImSoundId id = ImSoundId(s_midiFileCount | imMidiFlag); - s_midiFileCount++; - return id; - } - - ImSoundId ImOpenMidi(const char* name) - { - char filename[32]; - strcpy(filename, name); - strcat(filename, ".gmd"); - return loadMidiFile(filename); - } - - s32 ImCloseMidi(char* name) - { - ImSound* sound = s_soundList; - while (sound) - { - if (!strcasecmp(sound->name, name) && sound->refCount) - { - sound->refCount--; - // The ref count seems to be ignored here. - { - const ImSoundId index = sound->id & imMidiMask; - assert(index < IM_MIDI_FILE_COUNT); - if (index < IM_MIDI_FILE_COUNT) - { - imuse_free(s_midiFiles[index]); - s_midiFiles[index] = nullptr; - s_midiFileCount--; - } - - sound->id = IM_NULL_SOUNDID; - sound->refCount = 0; - - IM_LIST_REM(s_soundList, sound); - } - break; - } - sound = sound->next; - } - return imSuccess; - } - - s32 ImSetupMidiPlayer(ImSoundId soundId, s32 priority) - { - s32 clampedPriority = clamp(priority, 0, imMaxPriority); - ImMidiPlayer* player = ImGetFreePlayer(clampedPriority); - if (!player) - { - return imAllocErr; - } - - player->sharedPart = nullptr; - player->sharedPartId = 0; - player->marker = -1; - player->group = groupMusic; - player->priority = clampedPriority; - player->volume = imMaxVolume; - player->groupVolume = ImGetGroupVolume(player->group); - player->pan = imPanCenter; - - player->detune = 0; - player->transpose = 0; - player->mailbox = 0; - IM_DBG_MSG("Init: Hook = 0"); - player->hook = 0; - - for (s32 i = 0; i < MIDI_CHANNEL_COUNT; i++) - { - ImMidiOutChannel* channel = &player->channels[i]; - - channel->data = nullptr; - channel->partStatus = 0; - channel->partPgm = 128; - channel->partTrim = imMaxVolume; - channel->partPriority = 0; - channel->priority = player->priority; - channel->partNoteReq = 1; - channel->partVolume = imMaxVolume; - channel->groupVolume = player->groupVolume; - channel->partPan = imPanCenter; - channel->modulation = 0; - channel->sustain = 0; - channel->pitchBend = 0; - channel->outChannelCount = 2; - channel->pan = 0; - } - - ImPlayerData* playerData = player->data; - if (ImStartMidiPlayerInternal(playerData, soundId)) - { - return imFail; - } - - player->soundId = soundId; - IM_LIST_ADD(s_midiPlayerList, player); - return imSuccess; - } - - s32 ImFreeMidiPlayer(ImSoundId soundId) - { - ImMidiPlayer* player = ImGetMidiPlayer(soundId); - if (player) - { - ImReleaseMidiPlayer(player); - // This should be null - but the original code handles duplicates. - do - { - player = ImGetMidiPlayer(soundId); - if (player) - { - ImReleaseMidiPlayer(player); - } - } while (player); - return imSuccess; - } - return imFail; - } - - s32 ImReleaseAllPlayers() - { - ImMidiPlayer* player = nullptr; - do - { - player = s_midiPlayerList; - if (player) - { - ImReleaseMidiPlayer(player); - } - } while (player); - return imSuccess; - } - - s32 ImGetSoundType(ImSoundId soundId) - { - ImSoundId foundId = IM_NULL_SOUNDID; - // First check midi sounds. - do - { - foundId = ImFindNextMidiSound(foundId); - if (foundId && foundId == soundId) - { - return typeMidi; - } - } while (foundId); - - // Then check for wave sounds. - foundId = IM_NULL_SOUNDID; - do - { - foundId = ImFindNextWaveSound(foundId); - if (foundId && foundId == soundId) - { - return typeWave; - } - } while (foundId); - - // The sound doesn't exist. - return imFail; - } - - void ImHandleChannelPriorityChange(ImMidiPlayer* player, ImMidiOutChannel* channel) - { - channel->priority = min(channel->partPriority + player->priority, 127); - if (channel->data) - { - ImMidiChannelSetPriority(channel->data, channel->priority); - } - } - - s32 ImWrapValue(s32 value, s32 a, s32 b) - { - while (value < a) - { - value += 12; - } - while (value > b) - { - value -= 12; - } - return value; - } - - s32 ImSetMidiParam(ImSoundId soundId, s32 param, s32 value) - { - ImMidiPlayer* player = ImGetMidiPlayer(soundId); - if (!player) - { - return imInvalidSound; - } - - s32 midiChannel = param & 0x00ff; - iMuseParameter imParam = iMuseParameter(param & 0xff00); - ImMidiOutChannel* channels = player->channels; - - if (imParam == soundGroup) - { - if (value >= groupMaxCount) { return imArgErr; } - - player->group = value; - s32 playerVol = player->volume + 1; - s32 groupVol = ImGetGroupVolume(value); - player->groupVolume = (playerVol * groupVol) >> 7; - - for (s32 m = 0; m < MIDI_CHANNEL_COUNT; m++) - { - ImHandleChannelVolumeChange(player, &channels[m]); - } - } - else if (imParam == soundPriority && value <= imMaxPriority) - { - player->priority = value; - for (s32 m = 0; m < MIDI_CHANNEL_COUNT; m++) - { - ImHandleChannelPriorityChange(player, &channels[m]); - } - } - else if (imParam == soundVol && value <= imMaxVolume) - { - player->volume = value; - s32 groupVol = ImGetGroupVolume(player->group); - player->groupVolume = ((value + 1) * groupVol) >> imVolumeShift; - - for (s32 m = 0; m < MIDI_CHANNEL_COUNT; m++) - { - ImHandleChannelVolumeChange(player, &channels[m]); - } - } - else if (imParam == soundPan && value <= imPanMax) - { - player->pan = value; - for (s32 m = 0; m < MIDI_CHANNEL_COUNT; m++) - { - s32 pan = clamp(channels[m].partPan + value - imPanCenter, 0, imPanMax); - ImMidiChannelSetPan(channels[m].data, pan); - } - } - else if (imParam == soundDetune) - { - if (value < -9216 || value > 9216) { return imArgErr; } - player->detune = value; - for (s32 m = 0; m < MIDI_CHANNEL_COUNT; m++) - { - ImHandleChannelDetuneChange(player, &channels[m]); - } - } - else if (imParam == soundTranspose) - { - if (value < -12 || value > 12) { return imArgErr; } - player->transpose = (value == 0) ? 0 : ImWrapValue(value + player->transpose, -12, 12); - - for (s32 m = 0; m < MIDI_CHANNEL_COUNT; m++) - { - ImHandleChannelDetuneChange(player, &channels[m]); - } - } - else if (imParam == soundMailbox) - { - player->mailbox = value; - } - else if (imParam == midiSpeed) - { - return ImMidiSetSpeed(player->data, value); - } - else if (imParam == midiPartTrim) - { - if (midiChannel >= MIDI_CHANNEL_COUNT || value > imMaxVolume) { return imArgErr; } - - channels[midiChannel].partTrim = value; - ImHandleChannelVolumeChange(player, &channels[midiChannel]); - } - else - { - IM_LOG_WRN("PlSetParam() couldn't set param %lu.", param); - return imArgErr; - } - - return imSuccess; - } - - s32 ImGetMidiTimeParam(ImPlayerData* data, s32 param) - { - if (param == midiChunk) - { - return data->seqIndex + 1; - } - else if (param == midiMeasure) - { - return ImTime_getMeasure(data->nextTick) + 1; - } - else if (param == midiBeat) - { - return ImTime_getBeat(data->nextTick) + 1; - } - else if (param == midiTick) - { - return ImTime_getTicks(data->nextTick); - } - else if (param == midiSpeed) - { - return data->speed; - } - return imArgErr; - } - - s32 ImGetMidiParam(ImSoundId soundId, s32 param) - { - s32 playCount = 0; - ImMidiPlayer* player = s_midiPlayerList; - while (player) - { - if (player->soundId == soundId) - { - s32 midiChannel = param & 0x00ff; - iMuseParameter imParam = iMuseParameter(param & 0xff00); - ImMidiOutChannel* channel = &player->channels[midiChannel]; - - switch (imParam) - { - case soundPlayCount: - { - playCount++; - } break; - case soundPendCount: - { - return imFail; - } break; - case soundMarker: - { - return player->marker; - } break; - case soundGroup: - { - return player->group; - } break; - case soundPriority: - { - return player->priority; - } break; - case soundVol: - { - return player->volume; - } break; - case soundPan: - { - return player->pan; - } break; - case soundDetune: - { - return player->detune; - } break; - case soundTranspose: - { - return player->transpose; - } break; - case soundMailbox: - { - return player->mailbox; - } break; - case midiChunk: - case midiMeasure: - case midiBeat: - case midiTick: - case midiSpeed: - { - return ImGetMidiTimeParam(player->data, param); - } break; - case midiPartTrim: - { - return channel->partTrim; - } break; - case midiPartStatus: - { - return channel->partStatus ? 1 : 0; - } break; - case midiPartPriority: - { - return channel->partPriority; - } break; - case midiPartNoteReq: - { - return channel->partNoteReq; - } break; - case midiPartVol: - { - return channel->partVolume; - } break; - case midiPartPan: - { - return channel->partPan; - } break; - case midiPartPgm: - { - return channel->partPgm; - } break; - default: - { - return imArgErr; - } - }; - } - player = player->next; - } - if (param == soundPlayCount) - { - return playCount; - } - - return imInvalidSound; - } - - s32 ImGetPendingSoundCount(ImSoundId soundId) - { - // Not called by Dark Forces. - assert(0); - return 0; - } - - // Search a list for the smallest non-zero value that is atleast minValue. - ImSoundId ImFindNextMidiSound(ImSoundId soundId) - { - ImSoundId value = IM_NULL_SOUNDID; - ImMidiPlayer* player = s_midiPlayerList; - while (player) - { - if (u64(soundId) < u64(player->soundId)) - { - if (!value || u64(value) > u64(player->soundId)) - { - value = player->soundId; - } - } - player = player->next; - } - return value; - } - - ImMidiPlayer* ImGetMidiPlayer(ImSoundId soundId) - { - ImMidiPlayer* player = s_midiPlayerList; - while (player) - { - if (player->soundId == soundId) - { - break; - } - player = player->next; - } - return player; - } - - s32 ImSetHookMidi(ImSoundId soundId, s32 value) - { - if (value > 0x80) - { - return imArgErr; - } - ImMidiPlayer* player = ImGetMidiPlayer(soundId); - if (!player) - { - return imInvalidSound; - } - IM_DBG_MSG("Hook = %d", value); - player->hook = value; - return imSuccess; - } - - void ImMidiLock() - { - s_midiLock++; - } - - void ImMidiUnlock() - { - if (s_midiLock) - { - s_midiLock--; - } - } - - // Gets the deltatime in microseconds (i.e. 1,000 ms / 1 microsec). - s32 ImGetDeltaTime() - { - return s_iMuseTimestepMicrosec; - } - - s32 ImMidiSetSpeed(ImPlayerData* data, u32 value) - { - if (value > 255) - { - return imArgErr; - } - - ImMidiLock(); - data->speed = value; - data->stepFixed = (value * data->step) >> 7; - ImMidiUnlock(); - return imSuccess; - } - - void ImSetTempo(ImPlayerData* data, u32 tempo) - { - s32 ticks = ImGetDeltaTime() * 480; - data->tempo = tempo; - - // Keep reducing the tick scale? until it is less than one? - // This also reduces the tempo as well. - while (1) - { - if (!(ticks & 0xffff0000)) - { - if (!(tempo & 0xffff0000)) - { - break; - } - ticks >>= 1; - tempo >>= 1; - } - else - { - ticks >>= 1; - tempo >>= 1; - } - } - - data->step = intToFixed16(ticks) / tempo; - ImMidiSetSpeed(data, data->speed); - } - - void ImSetMidiTicksPerBeat(ImPlayerData* data, s32 ticksPerBeat, s32 beatsPerMeasure) - { - ImMidiLock(); - data->ticksPerBeat = ticksPerBeat; - data->beatsPerMeasure = intToFixed16(beatsPerMeasure); - ImMidiUnlock(); - } - - s32 ImSetSequence(ImPlayerData* data, u8* sndData, s32 seqIndex) - { - u8* chunk = midi_gotoHeader(sndData, "MTrk", seqIndex); - if (!chunk) - { - IM_LOG_ERR("Sq couldn't find chunk %d", seqIndex + 1); - return imFail; - } - - // Skip the header and size to the data. - u8* chunkData = &chunk[8]; - data->seqIndex = seqIndex; - // offset of the chunk data from the base sound data. - data->chunkOffset = s32(chunkData - sndData); - - u32 dt = midi_getVariableLengthValue(&chunkData); - data->curTick = ImFixupSoundTick(data, dt); - data->nextTick = 0; - data->chunkPtr = s32(chunkData - (sndData + data->chunkOffset)); - return imSuccess; - } - - // This gets called at a fixed rate, where each step = 'stepFixed' ticks. - void ImAdvanceMidiPlayer(ImPlayerData* playerData) - { - playerData->tickAccum += playerData->stepFixed; - playerData->nextTick += floor16(playerData->tickAccum); - // Keep the fractional part. - playerData->tickAccum = fract16(playerData->tickAccum); - - if ((playerData->nextTick & 0xffff) >= playerData->ticksPerBeat) - { - playerData->nextTick = ImFixupSoundTick(playerData, playerData->nextTick); - } - if (playerData->curTick < playerData->nextTick) - { - u8* sndData = ImInternalGetSoundData(playerData->soundId); - if (sndData) - { - ImAdvanceMidi(playerData, sndData, s_midiCmdFunc); - return; - } - IM_LOG_ERR("%s", "sq int handler got null addr"); - assert(0); - // TODO: ERROR handling - } - } - - void ImMidiGetInstruments(ImMidiPlayer* player, u32* soundMidiInstrumentMask, s32* midiInstrumentCount) - { - *midiInstrumentCount = 0; - - // Build a mask for all active midi channels. - u32 channelMask = 0; - for (s32 i = 0; i < MIDI_CHANNEL_COUNT - 1; i++) - { - ImMidiChannel* midiChannel = &s_midiChannels[i]; - if (player == midiChannel->player) - { - channelMask |= c_channelMask[midiChannel->channelId]; - } - } - - // Given the instrument channel mask and active channels, - // count the number of instruments playing. - for (s32 i = 0; i < MIDI_INSTRUMENT_COUNT; i++) - { - u32 value = s_midiInstrumentChannelMask[i] & channelMask; - soundMidiInstrumentMask[i] = value; - // Count the number of channels currently playing the instrument. - // This is counting the bits. - while (value) - { - (*midiInstrumentCount) += (value & 1); - value >>= 1; - } - } - - // Build a mask for all shared midi channels. - channelMask = 0; - for (s32 i = 0; i < MIDI_CHANNEL_COUNT - 1; i++) - { - ImMidiChannel* midiChannel = &s_midiChannels[i]; - if (player == midiChannel->sharedPart) - { - channelMask |= c_channelMask[midiChannel->sharedId]; - } - } - - // Given the instrument channel mask and shared channels, - // count the number of instruments playing. - for (s32 i = 0; i < MIDI_INSTRUMENT_COUNT; i++) - { - u32 value = s_midiInstrumentChannelMaskShared[i] & channelMask; - soundMidiInstrumentMask[i] |= value; - - while (value) - { - (*midiInstrumentCount) += (value & 1); - value >>= 1; - } - } - } - - s32 ImMidiGetTickDelta(ImPlayerData* playerData, u32 prevTick, u32 tick) - { - const u32 ticksPerMeasure = playerData->ticksPerBeat * playerData->beatsPerMeasure; - - // Compute the previous midi tick. - u32 prevMeasure = ImTime_getMeasure(prevTick); - u32 prevMeasureTick = mul16(prevMeasure, ticksPerMeasure); - - u32 prevBeat = ImTime_getBeat(prevTick); - u32 prevBeatTick = prevBeat * playerData->ticksPerBeat; - u32 prevMidiTick = prevMeasureTick + prevBeatTick + ImTime_getTicks(prevTick); - - // Compute the current midi tick. - u32 curMeasure = ImTime_getMeasure(tick); - u32 curMeasureTick = mul16(curMeasure, ticksPerMeasure); - - u32 curBeat = ImTime_getBeat(tick); - u32 curBeatTick = curBeat * playerData->ticksPerBeat; - u32 curMidiTick = curMeasureTick + curBeatTick + ImTime_getTicks(tick); - - return curMidiTick - prevMidiTick; - } - - void ImMidiProcessSustain(ImPlayerData* playerData, u8* sndData, MidiCmdFuncUnion* midiCmdFunc, ImMidiPlayer* player) - { - s_midiTrackEnd = 0; - - u8* data = sndData + playerData->chunkOffset + playerData->chunkPtr; - s_midiTickDelta = ImMidiGetTickDelta(playerData, playerData->curTick, playerData->nextTick); - - while (!s_midiTrackEnd) - { - u8 value = data[0]; - u8 msgFuncIndex; - if (value < 0xf0 && (value & 0x80)) - { - u8 msgType = (value & 0x70) >> 4; - u8 channel = (value & 0x0f); - if (midiCmdFunc[msgType].cmdFunc) - { - midiCmdFunc[msgType].cmdFunc(player, channel, data[1], data[2]); - } - data += c_midiMsgSize[msgType]; - } - else - { - if (value == MID_EXCLUSIVE_START) - { - msgFuncIndex = IM_MID_SYS_FUNC; - } - else - { - if (value != 0xff) - { - IM_LOG_ERR("su unknown msg type 0x%x.", value); - return; - } - msgFuncIndex = IM_MID_EVENT; - data++; - } - if (midiCmdFunc[msgFuncIndex].evtFunc) - { - midiCmdFunc[msgFuncIndex].evtFunc(playerData, data); - } - data++; - data += midi_getVariableLengthValue(&data); - } - // Length of message in "ticks" - s_midiTickDelta += midi_getVariableLengthValue(&data); - } - } - - void ImJumpSustain(ImMidiPlayer* player, u8* sndData, ImPlayerData* playerPrevData, ImPlayerData* playerNextData) - { - for (s32 i = 0; i < MIDI_CHANNEL_COUNT; i++) - { - ImMidiChannel* channel = player->channels[i].data; - s_midiSustainChannelMask[i] = (channel) ? (1u << u32(channel->channelId)) : 0; - } - - // Remove active sustained from the midi instrument list, these should already be tracked. - ImMidiGetInstruments(player, s_curMidiInstrumentMask, &s_curInstrumentCount); - ImSustainedSound* sustainedSound = s_imActiveSustainedSounds; - while (sustainedSound && s_curInstrumentCount) - { - if (sustainedSound->midiPlayer == player) - { - u32 instrMask = s_curMidiInstrumentMask[sustainedSound->instrumentId]; - u32 channelMask = s_midiSustainChannelMask[sustainedSound->channelId]; - if (channelMask & instrMask) - { - s_curMidiInstrumentMask[sustainedSound->instrumentId] &= ~channelMask; - s_curInstrumentCount--; - } - } - sustainedSound = sustainedSound->next; - } - - if (s_curInstrumentCount) - { - // Capture future "note off" events and add them to the active sounds. - // These sounds will continue to play during the transition. - ImMidiProcessSustain(playerPrevData, sndData, s_jumpMidiSustainOpenCmdFunc, player); - - // Make sure all "note off" events have been captured. If uncaptured notes still exist, we have to turn them off manually. - if (s_curInstrumentCount) - { - IM_LOG_WRN("su couldn't find all note-offs...", NULL); - for (s32 i = 0; i < MIDI_INSTRUMENT_COUNT; i++) - { - if (!s_curMidiInstrumentMask[i]) { continue; } - for (s32 c = 0; c < MIDI_CHANNEL_COUNT; c++) - { - if (s_curMidiInstrumentMask[i] & s_midiSustainChannelMask[c]) - { - IM_LOG_WRN("missing note %d on chan %d...", i, c); - ImMidiNoteOff(player, c, i, 0); - s_curInstrumentCount--; - } - } - } - assert(s_curInstrumentCount == 0); - } - } - - // Go through active sounds and calculate the time remaining for the sustain. - s_trackTicksRemaining = 0; - sustainedSound = s_imActiveSustainedSounds; - while (sustainedSound) - { - s_trackTicksRemaining = max(s_trackTicksRemaining, sustainedSound->curTick); - sustainedSound = sustainedSound->next; - } - // Get the current instruments again. - ImMidiGetInstruments(player, s_curMidiInstrumentMask, &s_curInstrumentCount); - ImMidiProcessSustain(playerNextData, sndData, s_jumpMidiSustainCmdFunc, player); - } - - //////////////////////////////////////// - // Midi Commands - //////////////////////////////////////// - void ImMidiChannelSetPgm(ImMidiChannel* midiChannel, s32 pgm) - { - if (midiChannel && pgm != midiChannel->pgm) - { - midiChannel->sharedMidiChannel->pgm = pgm; - midiChannel->pgm = pgm; - ImProgramChange(midiChannel->channelId, pgm); - } - } - - void ImMidiChannelSetPriority(ImMidiChannel* midiChannel, s32 priority) - { - if (midiChannel && priority != midiChannel->priority) - { - midiChannel->sharedMidiChannel->priority = priority; - midiChannel->priority = priority; - ImControlChange(midiChannel->channelId, MID_GPC3_MSB, priority); - } - } - - void ImMidiChannelSetPartNoteReq(ImMidiChannel* midiChannel, s32 noteReq) - { - if (midiChannel && noteReq != midiChannel->noteReq) - { - midiChannel->sharedMidiChannel->noteReq = noteReq; - midiChannel->noteReq = noteReq; - ImControlChange(midiChannel->channelId, MID_GPC2_MSB, noteReq); - } - } - - void ImMidiChannelSetPan(ImMidiChannel* midiChannel, s32 pan) - { - if (midiChannel && pan != midiChannel->pan) - { - midiChannel->sharedMidiChannel->pan = pan; - midiChannel->pan = pan; - ImControlChange(midiChannel->channelId, MID_PAN_MSB, pan); - } - } - - void ImMidiChannelSetModulation(ImMidiChannel* midiChannel, s32 modulation) - { - if (midiChannel && modulation != midiChannel->modulation) - { - midiChannel->sharedMidiChannel->modulation = modulation; - midiChannel->modulation = modulation; - ImControlChange(midiChannel->channelId, MID_MODULATIONWHEEL_MSB, modulation); - } - } - - void ImHandleChannelPan(ImMidiChannel* midiChannel, s32 pan) - { - if (midiChannel && pan != midiChannel->finalPan) - { - midiChannel->sharedMidiChannel->finalPan = pan; - midiChannel->finalPan = pan; - ImSetPanFine(midiChannel->channelId, 2*pan + 8192); - } - } - - void ImSetChannelSustain(ImMidiChannel* midiChannel, s32 sustain) - { - if (midiChannel) - { - midiChannel->sustain = sustain; - if (!sustain) - { - const u32 channelMask = c_channelMask[midiChannel->channelId]; - for (s32 i = 0; i < MIDI_INSTRUMENT_COUNT; i++) - { - if (midiChannel->instrumentMask2[i] & channelMask) - { - midiChannel->instrumentMask2[i] &= ~channelMask; - ImNoteOff(midiChannel->channelId, i); - } - } - } - } - } - - void ImMidiChannelSetVolume(ImMidiChannel* midiChannel, s32 volume) - { - if (midiChannel && volume != midiChannel->volume) - { - midiChannel->sharedMidiChannel->volume = volume; - midiChannel->volume = volume; - ImControlChange(midiChannel->channelId, MID_VOLUME_MSB, volume); - } - } - - void ImHandleChannelDetuneChange(ImMidiPlayer* player, ImMidiOutChannel* channel) - { - channel->pan = (player->transpose << 8) + player->detune + channel->pitchBend; - ImMidiChannel* data = channel->data; - if (data) - { - ImHandleChannelPan(data, channel->pan); - } - } - - void ImHandleChannelPitchBend(ImMidiPlayer* player, s32 channelIndex, s32 fractValue, s32 intValue) - { - ImMidiOutChannel* channel = &player->channels[channelIndex]; - s32 pitchBend = ((intValue << 7) | fractValue) - (imPanCenter << 7); - if (channel->outChannelCount) - { - channel->pan = (channel->outChannelCount * pitchBend) >> 5; // range -256, 256 - ImHandleChannelDetuneChange(player, channel); - } - } - - /////////////////////////////////// - // Midi Call Functions - /////////////////////////////////// - s32 ImMidiCall(s32 index, s32 id, s32 arg1, s32 arg2, s32 arg3) - { - // This is used to interface with the midi driver in DOS. - // In TFE, midi commands are sent directly to the low-level midi system. - return imSuccess; - } - - ////////////////////////////////// - // Midi Advance Functions - ////////////////////////////////// - void ImMidiJumpSustainOpen_NoteOff(ImMidiPlayer* player, u8 channelId, u8 arg1, u8 arg2) - { - const u8 instrumentId = arg1; - const u32 channelMask = s_midiSustainChannelMask[channelId]; - if (s_curMidiInstrumentMask[instrumentId] & channelMask) - { - s_curMidiInstrumentMask[instrumentId] &= ~channelMask; - s_curInstrumentCount--; - if (s_curInstrumentCount == 0) - { - s_midiTrackEnd = 1; - } - ImSustainedSound* sound = s_imFreeSustainedSounds; - if (!sound) - { - IM_LOG_ERR("%s", "su unable to alloc Sustain..."); - return; - } - IM_LIST_REM(s_imFreeSustainedSounds, sound); - IM_LIST_ADD(s_imActiveSustainedSounds, sound); - - sound->midiPlayer = player; - sound->instrumentId = instrumentId; - sound->channelId = channelId; - sound->curTick = s_midiTickDelta; - sound->curTickFixed = 0; - } - } - - void ImMidiJumpSustainOpen_NoteOn(ImMidiPlayer* player, u8 channelId, u8 arg1, u8 arg2) - { - const u8 instrumentId = arg1; - const u8 velocity = arg2; - if (velocity == 0) - { - ImMidiJumpSustainOpen_NoteOff(player, channelId, instrumentId, 0); - } - } - - void ImMidiJumpSustain_NoteOn(ImMidiPlayer* player, u8 channelId, u8 arg1, u8 arg2) - { - const s32 instrumentId = arg1; - const u32 channelMask = s_midiSustainChannelMask[channelId]; - if (s_midiTickDelta > s_trackTicksRemaining) - { - s_midiTrackEnd = 1; - } - else if (s_curMidiInstrumentMask[instrumentId] & channelMask) - { - s_curMidiInstrumentMask[instrumentId] &= ~channelMask; - ImSustainedSound* sustainedSound = s_imActiveSustainedSounds; - while (sustainedSound) - { - s32 delta = s_midiTickDelta - 10; - if (sustainedSound->midiPlayer == player && sustainedSound->instrumentId == instrumentId && sustainedSound->channelId == channelId && - delta <= sustainedSound->curTick) - { - sustainedSound->curTick = delta; - break; - } - sustainedSound = sustainedSound->next; - } - } - } - - void ImMidiStopAllNotes(ImMidiPlayer* player) - { - for (s32 i = 0; i < MIDI_CHANNEL_COUNT; i++) - { - ImMidiCommand(player, i, MID_ALL_NOTES_OFF, 0); - } - } - - void ImMidiCommand(ImMidiPlayer* player, s32 channelIndex, s32 midiCmd, s32 value) - { - ImMidiOutChannel* channel = &player->channels[channelIndex]; - - if (midiCmd == MID_MODULATIONWHEEL_MSB) - { - channel->modulation = value; - if (channel->data) - { - ImMidiChannelSetModulation(channel->data, value); - } - } - else if (midiCmd == MID_VOLUME_MSB) - { - channel->partVolume = value; - ImHandleChannelVolumeChange(player, channel); - } - else if (midiCmd == MID_PAN_MSB) - { - channel->partPan = value; - if (channel->data) - { - s32 pan = clamp(value + player->pan - imPanCenter, 0, imPanMax); - ImMidiChannelSetPan(channel->data, pan); - } - } - else if (midiCmd == MID_GPC1_MSB) - { - if (value < 12) - { - //channel->outChannelCount = value; - ImMidiPitchBend(player, channelIndex, 0, imPanCenter); - } - } - else if (midiCmd == MID_GPC2_MSB) - { - channel->partNoteReq = value; - if (channel->data) - { - ImMidiChannelSetPartNoteReq(channel->data, value); - } - } - else if (midiCmd == MID_GPC3_MSB) - { - channel->partPriority = value; - ImHandleChannelPriorityChange(player, channel); - ImMidiSetupParts(); - } - else if (midiCmd == MID_SUSTAIN_SWITCH) - { - channel->sustain = value; - if (channel->data) - { - ImSetChannelSustain(channel->data, value); - } - } - else if (midiCmd == MID_ALL_NOTES_OFF) - { - channel->sustain = 0; - if (channel->data) - { - ImFreeMidiChannel(channel->data); - } - } - } - - void ImMidiNoteOff(ImMidiPlayer* player, u8 channelId, u8 arg1, u8 arg2) - { - s32 instrumentId = arg1; - ImMidiOutChannel* channel = &player->channels[channelId]; - if (channel->partStatus) - { - if (channel->data) - { - ImHandleNoteOff(channel->data, instrumentId); - } - } - else - { - ImNoteOff(imOutDrumChannel, instrumentId); - } - } - - void ImMidiNoteOn(ImMidiPlayer* player, u8 channelId, u8 arg1, u8 arg2) - { - s32 instrumentId = arg1; - s32 velocity = arg2; - ImMidiOutChannel* channel = &player->channels[channelId]; - if (!velocity) - { - ImMidiNoteOff(player, channelId, instrumentId, 0); - } - else if (channel->partStatus) - { - if (channel->data) - { - ImHandleNoteOn(channel->data, instrumentId, velocity); - } - } - else - { - ImMidi_DrumOut_NoteOn(channel->priority, channel->partNoteReq, channel->groupVolume, instrumentId, velocity); - } - } - - void ImMidiProgramChange(ImMidiPlayer* player, u8 channelId, u8 arg1, u8 arg2) - { - const s32 pgm = arg1; - ImMidiOutChannel* channel = &player->channels[channelId]; - channel->partPgm = pgm; - if (!channel->partStatus) - { - channel->partStatus = 1; - ImMidiSetupParts(); - } - else if (channel->data) - { - ImMidiChannelSetPgm(channel->data, pgm); - } - } - - void ImMidiPitchBend(ImMidiPlayer* player, u8 channelId, u8 arg1, u8 arg2) - { - const s32 pitchBendFract = arg1; - const s32 pitchBendInt = arg2; - - ImMidiOutChannel* channel = &player->channels[channelId]; - s32 pitchBend = ((pitchBendInt << 7) | pitchBendFract) - (imPanCenter << 7); - s32 channelCount = channel->outChannelCount; - - // There should always be channels. - if (channelCount) - { - channel->pitchBend = (pitchBend * channelCount) >> 5; - ImHandleChannelDetuneChange(player, channel); - } - } - - void ImMidiEvent(ImPlayerData* playerData, u8* chunkData) - { - u8* data = chunkData; - MetaType metaType = MetaType(*data); - // Skip past the metaType and length. - data += 2; - - if (metaType == META_END_OF_TRACK) - { - s_imEndOfTrack = 1; - } - else if (metaType == META_TEMPO) - { - u32 tempo = (data[0] << 16) | (data[1] << 8) | data[2]; - ImSetTempo(playerData, tempo); - } - else if (metaType == META_TIME_SIG) - { - ImSetMidiTicksPerBeat(playerData, 960 >> (data[1] - 1), data[0]); - } - } - - void ImHandleNoteOn(ImMidiChannel* channel, s32 instrumentId, s32 velocity) - { - if (!channel) { return; } - - u32 channelMask = c_channelMask[channel->channelId]; - if (channel->instrumentMask[instrumentId] & channelMask) - { - ImNoteOff(channel->channelId, instrumentId); - } - else - { - if (channel->instrumentMask2[instrumentId] & channelMask) - { - channel->instrumentMask2[instrumentId] &= ~channelMask; - ImNoteOff(channel->channelId, instrumentId); - } - } - - channel->instrumentMask[instrumentId] |= channelMask; - ImNoteOn(channel->channelId, instrumentId, velocity); - } - - void ImMidi_DrumOut_NoteOn(s32 priority, s32 partNoteReq, s32 volume, s32 instrumentId, s32 velocity) - { - if (s_ImDrumOutCh_priority != priority) - { - s_ImDrumOutCh_priority = priority; - ImControlChange(imOutDrumChannel, MID_GPC3_MSB, priority); - } - if (s_ImDrumOutCh_partNoteReq != partNoteReq) - { - s_ImDrumOutCh_partNoteReq = partNoteReq; - ImControlChange(imOutDrumChannel, MID_GPC2_MSB, partNoteReq); - } - if (s_ImDrumOutCh_volume != volume) - { - s_ImDrumOutCh_volume = volume; - ImControlChange(imOutDrumChannel, MID_VOLUME_MSB, volume); - } - ImNoteOn(imOutDrumChannel, instrumentId, velocity); - } - - void ImHandleNoteOff(ImMidiChannel* midiChannel, s32 instrumentId) - { - if (midiChannel) - { - const u32 channelMask = c_channelMask[midiChannel->channelId]; - if (midiChannel->instrumentMask[instrumentId] & channelMask) - { - midiChannel->instrumentMask[instrumentId] &= ~channelMask; - if (!midiChannel->sustain) - { - ImNoteOff(midiChannel->channelId, instrumentId); - } - } - } - } - - /////////////////////////////////////////////////////////// - // Initialization Functions - /////////////////////////////////////////////////////////// - s32 ImSetupFilesModule(iMuseInitData* initData) - { - IM_LOG_MSG("FILES module..."); - s_imFilesData = initData; - return s_imFilesData ? imSuccess : imFail; - } - - s32 ImInitializeGroupVolume() - { - for (s32 i = 0; i < MIDI_CHANNEL_COUNT; i++) - { - s_groupVolume[i] = imMaxVolume; - s_soundGroupVolume[i] = imMaxVolume; - } - return imSuccess; - } - - // TFE: Used to reinitialize Midi when devices are changed. - s32 ImReintializeMidi() - { - for (s32 i = 0; i < MIDI_INSTRUMENT_COUNT; i++) - { - s_midiInstrumentChannelMask[i] = 0; - s_midiInstrumentChannelMaskShared[i] = 0; - s_midiInstrumentChannelMask1[i] = 0; - s_midiInstrumentChannelMask3[i] = 0; - } - for (s32 i = 0; i < MIDI_CHANNEL_COUNT - 1; i++) - { - ImMidiChannel* channel = &s_midiChannels[i]; - channel->player = nullptr; - channel->channel = nullptr; - - // There are two channels embedded in the structure that point to each other. - channel->sharedMidiChannel = (ImMidiChannel*)&channel->sharedPart; - // Initialize values. - channel->channelId = (i < imOutDrumChannel) ? i : i + 1; - channel->pgm = 0; - channel->priority = 0; - channel->noteReq = 0; - channel->volume = imMaxVolume; - channel->pan = imPanCenter; - channel->modulation = 0; - channel->finalPan = 0; - channel->sustain = 0; - channel->instrumentMask = s_midiInstrumentChannelMask; - channel->instrumentMask2 = s_midiInstrumentChannelMask1; - - ImMidiChannel* sharedChannel = (ImMidiChannel*)&channel->sharedPart; - sharedChannel->player = nullptr; - sharedChannel->channel = nullptr; - sharedChannel->sharedMidiChannel = channel; - sharedChannel->channelId = (i < imOutDrumChannel) ? i : i + 1; - sharedChannel->pgm = 0; - sharedChannel->priority = 0; - sharedChannel->noteReq = 0; - sharedChannel->volume = imMaxVolume; - sharedChannel->pan = imPanCenter; - sharedChannel->modulation = 0; - sharedChannel->finalPan = 0; - sharedChannel->sustain = 0; - sharedChannel->instrumentMask = s_midiInstrumentChannelMaskShared; - sharedChannel->instrumentMask2 = s_midiInstrumentChannelMask3; - - ImProgramChange(sharedChannel->channelId, sharedChannel->pgm); - ImControlChange(sharedChannel->channelId, MID_GPC3_MSB, sharedChannel->priority); - ImControlChange(sharedChannel->channelId, MID_GPC2_MSB, sharedChannel->noteReq); - ImControlChange(sharedChannel->channelId, MID_VOLUME_MSB, sharedChannel->volume); - ImControlChange(sharedChannel->channelId, MID_PAN_MSB, sharedChannel->pan); - ImControlChange(sharedChannel->channelId, MID_MODULATIONWHEEL_MSB, sharedChannel->modulation); - ImSetPanFine(sharedChannel->channelId, sharedChannel->finalPan * 2 + 8192); - } - // Channel 15 maps to 9 and only uses 3 parameters. - s_ImDrumOutCh_priority = 0; - s_ImDrumOutCh_partNoteReq = 1; - s_ImDrumOutCh_volume = imMaxVolume; - ImControlChange(imOutDrumChannel, MID_GPC3_MSB, s_ImDrumOutCh_priority); - ImControlChange(imOutDrumChannel, MID_GPC2_MSB, s_ImDrumOutCh_partNoteReq); - ImControlChange(imOutDrumChannel, MID_VOLUME_MSB, s_ImDrumOutCh_volume); - return imSuccess; - } - - s32 ImInitializeSlots(iMuseInitData* initData) - { - IM_LOG_MSG("SLOTS module..."); - - ImMidiCall(0, 0, 0, 0, 0); - s_midiDriverNotReady = 0; - return ImReintializeMidi(); - } - - s32 ImInitializeSustain() - { - IM_LOG_MSG("SUSTAIN module..."); - s_imFreeSustainedSounds = nullptr; - s_imActiveSustainedSounds = nullptr; - - ImSustainedSound* sound = s_sustainedSounds; - for (s32 i = 0; i < 24; i++, sound++) - { - sound->prev = nullptr; - sound->next = nullptr; - IM_LIST_ADD(s_imFreeSustainedSounds, sound); - } - return imSuccess; - } - - s32 ImInitializePlayers() - { - IM_LOG_MSG("PLAYERS module..."); - ImMidiPlayer* player = s_midiPlayers; - s_midiPlayerList = nullptr; - s_soundList = nullptr; - for (s32 i = 0; i < IM_MIDI_PLAYER_COUNT; i++, player++) - { - player->prev = nullptr; - player->next = nullptr; - - ImPlayerData* data = &s_playerData[i]; - player->data = data; - data->player = player; - player->soundId = 0; - } - return imSuccess; - } - - s32 ImInitializeMidiEngine(iMuseInitData* initData) - { - IM_LOG_MSG("MIDI engine...."); - if (ImInitializeSlots(initData) != imSuccess) - { - IM_LOG_ERR("%s", "SL: MIDI driver init failed..."); - return imFail; - } - if (ImInitializeSustain() != imSuccess) - { - IM_LOG_ERR("%s", "SL: MIDI driver init failed..."); - return imFail; - } - if (ImInitializePlayers() != imSuccess) - { - IM_LOG_ERR("%s", "SL: MIDI driver init failed..."); - return imFail; - } - - s_midiPaused = 0; - s_midiLock = 0; - return imSuccess; - } - - s32 ImInitializeInterrupt(iMuseInitData* initData) - { - // This function has been simplified compared to DOS, since TFE does not use - // interrupt handlers. - if (initData->imuseIntUsecCount) - { - s_iMuseTimestepMicrosec = initData->imuseIntUsecCount; - } - - // In the original code, the interrupt is setup here, TFE uses a thread to simulate this. - const f64 timeStep = TFE_System::microsecondsToSeconds((f64)s_iMuseTimestepMicrosec) / TFE_System::c_gameTimeScale; - TFE_MidiPlayer::midiSetCallback(ImUpdate, timeStep); - TFE_MidiPlayer::setMaximumNoteLength(8.0f); - - return imSuccess; - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/IMuse/imuse.h b/components/darkforces/tfe/TFE_Jedi/IMuse/imuse.h deleted file mode 100644 index c7bcefe6..00000000 --- a/components/darkforces/tfe/TFE_Jedi/IMuse/imuse.h +++ /dev/null @@ -1,168 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// iMuse System -// The IMuse system used by Dark Forces. -// -// Copyright note: -// While the project as a whole is licensed under GPL-2.0, some of the -// code under TFE_Jedi/ was derived from reverse-engineered -// code from "Dark Forces" (DOS) which is copyrighted by LucasArts. -// The original renderer is contained in RClassic_Fixed/ and the -// RClassic_Float/ and RClassic_GPU/ sub-renderers are derived from -// that code. -// -// I consider the reverse-engineering to be "Fair Use" - a means of -// supporting the games on other platforms and to improve support on -// existing platforms without claiming ownership of the games -// themselves or their IPs. -// -// That said using this code in a commercial project is risky without -// permission of the original copyright holders (LucasArts). -////////////////////////////////////////////////////////////////////// -#include -#include "imOpCodes.h" -#include "imConst.h" - -struct MemoryRegion; - -enum ImWaveSpeed -{ - IM_WAVE_11kHz = 0, - IM_WAVE_22kHz = 1, -}; - -struct iMuseInitData -{ - u32 systemTime = 0; // iMuse 60Hz timer clock - ImWaveSpeed waveSpeed = IM_WAVE_11kHz; // 0 = 11KHz, 1 = 22KHz - s32 waveMixCount = 8; // set 0 to 16 mixer channels - u32 imuseIntUsecCount = 6944; // iMuse interrupt freq -}; - -typedef u8*(*ImResourceCallback)(s64); - -// Used by ImSetParam() and ImGetParam(). -enum iMuseParameter -{ - // empty low byte allows bit field for MIDI channel - soundType = 0x0000, // see next enum - soundPlayCount = 0x0100, // iterations playing - soundPendCount = 0x0200, // iterations pending - soundMarker = 0x0300, // last marker seen - soundGroup = 0x0400, // group volume select - soundPriority = 0x0500, // priority - soundVol = 0x0600, // volume - soundPan = 0x0700, // pan - soundDetune = 0x0800, // absolute detune - soundTranspose = 0x0900, // relative transpose - soundMailbox = 0x0A00, // general purpose - midiChunk = 0x0B00, // midifile chunk - midiMeasure = 0x0C00, // measure - midiBeat = 0x0D00, // beat - midiTick = 0x0E00, // tick 0-479 - midiSpeed = 0x0F00, // speed - midiPartTrim = 0x1100, // part trim - midiPartStatus = 0x1200, // see bit fields below - midiPartPriority = 0x1300, // set by MIDI ch msg - midiPartNoteReq = 0x1400, - midiPartVol = 0x1500, - midiPartPan = 0x1600, - midiPartPgm = 0x1700, - waveStreamFlag = 0x1800 // set if wave streamed -}; - -enum iMuseGroup -{ - groupMaster = 0, // master - groupSfx = 1, // sound effects - groupVoice = 2, // voice - groupMusic = 3, // music - groupDippedMusic = 4, // auto dip music - groupMaxCount = 16 -}; - -enum iMuseSoundType: u64 // Force enum to unsigned (C++ 11) -{ - typeMidi = 1u, - typeWave = 2u, - imMidiFlag = 0x8000000000000000u, - imMidiMask = 0x7fffffffffffffffu, - imValidMask = 0xfff00000u, -}; - -enum iMuseErrorCode -{ - imSuccess = 0, - imFail = -1, - imNotImplemented = -2, - imNotFound = -3, - imInvalidSound = -4, - imArgErr = -5, - imAllocErr = -6, - imIllegalErr = -7 -}; - -#ifdef TFE_ESPBOX -#define IM_AUDIO_OVERSAMPLE 0 -#else -#define IM_AUDIO_OVERSAMPLE 2 -#endif - -namespace TFE_Jedi -{ - //////////////////////////////////////////////////// - // High level functions - //////////////////////////////////////////////////// - extern s32 ImSetMasterVol(s32 vol); - extern s32 ImGetMasterVol(void); - - extern s32 ImSetMusicVol(s32 vol); - extern s32 ImGetMusicVol(void); - - extern s32 ImSetSfxVol(s32 vol); - extern s32 ImGetSfxVol(void); - - extern s32 ImSetVoiceVol(s32 vol); - extern s32 ImGetVoiceVol(void); - - extern s32 ImStartSfx(ImSoundId soundId, s32 priority); - extern s32 ImStartVoice(ImSoundId soundId, s32 priority); - extern s32 ImStartMusic(ImSoundId soundId, s32 priority); - - extern void ImUnloadAll(void); - extern ImSoundId ImLoadMidi(const char *name); - extern ImSoundId ImFindMidi(const char* name); - - //////////////////////////////////////////////////// - // TFE - //////////////////////////////////////////////////// - s32 ImSetDigitalChannelCount(s32 count); - s32 ImReintializeMidi(); - - //////////////////////////////////////////////////// - // Low level functions - //////////////////////////////////////////////////// - extern s32 ImInitialize(MemoryRegion* memRegion); - extern s32 ImTerminate(void); - extern s32 ImSetResourceCallback(ImResourceCallback callback); - extern s32 ImPause(void); - extern s32 ImResume(void); - extern s32 ImSetGroupVol(s32 group, s32 vol); - extern s32 ImStartSound(ImSoundId soundId, s32 priority); - extern s32 ImStopSound(ImSoundId soundId); - extern s32 ImStopAllSounds(void); - extern ImSoundId ImGetNextSound(ImSoundId soundId); - extern s32 ImSetParam(ImSoundId soundId, s32 param, s32 value); - extern s32 ImGetParam(ImSoundId soundId, s32 param); - extern s32 ImFadeParam(ImSoundId soundId, s32 param, s32 value, s32 time); - extern s32 ImSetHook(ImSoundId soundId, s32 value); - extern s32 ImGetHook(ImSoundId soundId); - extern s32 ImSetTrigger(ImSoundId soundId, s32 marker, iptr opcode); // Modified based on actual usage to simplify - extern s32 ImCheckTrigger(ImSoundId soundId, s32 marker, iptr opcode); - extern s32 ImClearTrigger(ImSoundId soundId, s32 marker, iptr opcode); - extern s32 ImDeferCommand(s32 time, iptr opcode, s64 sound); // Modified based on actual usage to simplify - - extern s32 ImJumpMidi(ImSoundId soundId, s32 chunk, s32 measure, s32 beat, s32 tick, s32 sustain); - extern s32 ImSendMidiMsg(ImSoundId soundId, s32 arg1, s32 arg2, s32 arg3); - extern s32 ImShareParts(ImSoundId sound1, ImSoundId sound2); -} // namespace TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/IMuse/midiData.cpp b/components/darkforces/tfe/TFE_Jedi/IMuse/midiData.cpp deleted file mode 100644 index b534d54b..00000000 --- a/components/darkforces/tfe/TFE_Jedi/IMuse/midiData.cpp +++ /dev/null @@ -1,66 +0,0 @@ -#include "imuse.h" -#include "midiData.h" -#include -#include -#include - -namespace TFE_Jedi -{ - u32 midi_getChunkSize(u8* data) - { - u8* curData = data; - u32 v0 = curData[0] << 8; curData++; - u32 v1 = (curData[0] | v0) << 8; curData++; - u32 v2 = (curData[0] | v1) << 8; curData++; - u32 v3 = curData[0] | v2; - - return data[3] | (data[2] << 8) | (data[1] << 16) | (data[0] << 24); - } - - u8* midi_gotoHeader(u8* data, const char* header, s32 hdrIndex) - { - if (data) - { - data += 4; - u32 size = midi_getChunkSize(data); - u32 curIndex = 0; - data += 4; - while (curIndex < size) - { - s32 hdrNotMatch = 0; - for (s32 i = 0; i < 4; i++, curIndex++) - { - if (data[curIndex] != header[i]) - { - hdrNotMatch = 1; - } - } - if (!hdrNotMatch) // Match - { - if (hdrIndex == 0) - { - // returns the pointer starting at the beginning of the header. - return data + curIndex - 4; - } - hdrIndex--; - } - curIndex += midi_getChunkSize(data + curIndex) + 4; - } - } - return nullptr; - } - - u32 midi_getVariableLengthValue(u8** chunkData) - { - u32 value = 0u; - for (u32 i = 0; i < 4; i++) - { - const u8 partial = (*chunkData)[0]; - (*chunkData)++; - - value = (value << 7u) | (partial & 0x7f); - if (!(partial & 0x80)) { break; } - } - return value; - } -} // namespace TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/IMuse/midiData.h b/components/darkforces/tfe/TFE_Jedi/IMuse/midiData.h deleted file mode 100644 index 2b817052..00000000 --- a/components/darkforces/tfe/TFE_Jedi/IMuse/midiData.h +++ /dev/null @@ -1,30 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// iMuse System -// The IMuse system used by Dark Forces. -// -// Copyright note: -// While the project as a whole is licensed under GPL-2.0, some of the -// code under TFE_Jedi/ was derived from reverse-engineered -// code from "Dark Forces" (DOS) which is copyrighted by LucasArts. -// The original renderer is contained in RClassic_Fixed/ and the -// RClassic_Float/ and RClassic_GPU/ sub-renderers are derived from -// that code. -// -// I consider the reverse-engineering to be "Fair Use" - a means of -// supporting the games on other platforms and to improve support on -// existing platforms without claiming ownership of the games -// themselves or their IPs. -// -// That said using this code in a commercial project is risky without -// permission of the original copyright holders (LucasArts). -////////////////////////////////////////////////////////////////////// -#include -#include "imuse.h" - -namespace TFE_Jedi -{ - u32 midi_getChunkSize(u8* data); - u8* midi_gotoHeader(u8* data, const char* header, s32 hdrIndex); - u32 midi_getVariableLengthValue(u8** chunkData); -} // namespace TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/InfSystem/infElevatorUpdateFunc.h b/components/darkforces/tfe/TFE_Jedi/InfSystem/infElevatorUpdateFunc.h deleted file mode 100644 index 0748faac..00000000 --- a/components/darkforces/tfe/TFE_Jedi/InfSystem/infElevatorUpdateFunc.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Elevator update function forward declarations. -////////////////////////////////////////////////////////////////////// -namespace TFE_Jedi -{ - typedef fixed16_16(*InfUpdateFunc)(InfElevator* elev, fixed16_16 delta); - fixed16_16 infUpdate_moveHeights(InfElevator* elev, fixed16_16 delta); - fixed16_16 infUpdate_moveWall(InfElevator* elev, fixed16_16 delta); - fixed16_16 infUpdate_rotateWall(InfElevator* elev, fixed16_16 delta); - fixed16_16 infUpdate_scrollWall(InfElevator* elev, fixed16_16 delta); - fixed16_16 infUpdate_scrollFlat(InfElevator* elev, fixed16_16 delta); - fixed16_16 infUpdate_changeAmbient(InfElevator* elev, fixed16_16 delta); - fixed16_16 infUpdate_changeWallLight(InfElevator* elev, fixed16_16 delta); -} diff --git a/components/darkforces/tfe/TFE_Jedi/InfSystem/infPublicTypes.h b/components/darkforces/tfe/TFE_Jedi/InfSystem/infPublicTypes.h deleted file mode 100644 index a60b142e..00000000 --- a/components/darkforces/tfe/TFE_Jedi/InfSystem/infPublicTypes.h +++ /dev/null @@ -1,99 +0,0 @@ -#pragma once -#include -#include -#include - -// Core elevator types. -enum InfElevatorType -{ - IELEV_MOVE_CEILING = 0, - IELEV_MOVE_FLOOR, - IELEV_MOVE_OFFSET, - IELEV_MOVE_WALL, - IELEV_ROTATE_WALL, - IELEV_SCROLL_WALL, - IELEV_SCROLL_FLOOR, - IELEV_SCROLL_CEILING, - IELEV_CHANGE_LIGHT, - IELEV_MOVE_FC, - IELEV_CHANGE_WALL_LIGHT, - IELEV_COUNT, -}; - -// "Special" elevators are "high level" elevators that map to the core -// 11 types (see InfElevatorType) but have special settings and/or -// automatically add stops to make commonly used patterns easier to setup. -enum InfSpecialElevator -{ - IELEV_SP_BASIC = 0, - IELEV_SP_BASIC_AUTO, - // Both of these are unimplemented in the final game. - IELEV_SP_UNIMPLEMENTED, - IELEV_SP_MID, - // Back to implemented types. - IELEV_SP_INV = 4, - IELEV_SP_DOOR, - IELEV_SP_DOOR_INV, - IELEV_SP_DOOR_MID, - IELEV_SP_MORPH_SPIN1, - IELEV_SP_MORPH_SPIN2, - IELEV_SP_MORPH_MOVE1, - IELEV_SP_MORPH_MOVE2, - IELEV_SP_EXPLOSIVE_WALL, - IELEV_SP_COUNT -}; - -enum InfEventMask -{ - INF_EVENT_CROSS_LINE_FRONT = FLAG_BIT(0), - INF_EVENT_CROSS_LINE_BACK = FLAG_BIT(1), - INF_EVENT_ENTER_SECTOR = FLAG_BIT(2), - INF_EVENT_LEAVE_SECTOR = FLAG_BIT(3), - INF_EVENT_NUDGE_FRONT = FLAG_BIT(4), // Front of line or inside sector. - INF_EVENT_NUDGE_BACK = FLAG_BIT(5), // Back of line or outside sector. - INF_EVENT_EXPLOSION = FLAG_BIT(6), - INF_EVENT_UNUSED1 = FLAG_BIT(7), // Unused slot. - INF_EVENT_SHOOT_LINE = FLAG_BIT(8), // Shoot or punch line. - INF_EVENT_LAND = FLAG_BIT(9), // Land on floor - INF_EVENT_UNUSED2 = FLAG_BIT(10), - INF_EVENT_UNUSED3 = FLAG_BIT(11), - INF_EVENT_INTERNAL = FLAG_BIT(31), // Internal Event - INF_EVENT_NONE = 0, - INF_EVENT_ANY = 0xffffffff -}; - -enum LinkType -{ - LTYPE_SECTOR = 0, - LTYPE_TRIGGER, - LTYPE_TELEPORT, -}; - -struct Allocator; -namespace TFE_Jedi -{ - typedef void(*InfFreeFunc)(void*); - - struct InfElevator; - struct InfTrigger; - struct Teleport; - - struct InfLink - { - LinkType type; // Sector or Trigger - Task* task; // Either the Elevator or Trigger msg func. - union - { - InfElevator* elev; // The actual INF item. - InfTrigger* trigger; - Teleport* teleport; - void* target; - }; - u32 eventMask; // The event mask which helps determine if a link can be activated. - u32 entityMask; // The entity mask (as above). - Allocator* parent; // The parent list of links. - InfFreeFunc freeFunc; // The function to use to free the link. - // TFE: - s32 serializeIndex; // An index used to fix up pointers after all of the data is loaded. - }; -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/InfSystem/infState.cpp b/components/darkforces/tfe/TFE_Jedi/InfSystem/infState.cpp deleted file mode 100644 index f3521bd6..00000000 --- a/components/darkforces/tfe/TFE_Jedi/InfSystem/infState.cpp +++ /dev/null @@ -1,863 +0,0 @@ -#include "infState.h" -#include "infTypesInternal.h" -#include "infSystem.h" -#include -#include -#include -#include -#include -#include - -using namespace TFE_DarkForces; - -namespace TFE_Jedi -{ - enum InfStateVersion : u32 - { - InfState_InitVersion = 1, - InfState_CurVersion = InfState_InitVersion, - }; - - // INF State - InfSerializableState s_infSerState = { }; - InfState s_infState = { }; - - ///////////////////////////////////////////// - // Forward Declarations - ///////////////////////////////////////////// - void inf_serializeStop(Stream* stream, Stop* stop); - void inf_serializeSlave(Stream* stream, Slave* slave); - void inf_serializeLink(Stream* stream, InfLink* link, Allocator* parent); - void inf_serializeFixupLinks(); - - void inf_computeElevValuePointer(InfElevator* elev); - extern void inf_deleteElevator(InfElevator* elev); - extern void inf_deleteTrigger(InfTrigger* trigger); - - ///////////////////////////////////////////// - // Implementation - ///////////////////////////////////////////// - void inf_clearState() - { - s_infSerState = { 0 }; - s_infState = { 0 }; - } - - void inf_serializeElevator(Stream* stream, InfElevator* elev) - { - SERIALIZE(InfState_InitVersion, elev->deleted, 0); - if (elev->deleted) - { - if (serialization_getMode() == SMODE_READ) - { - memset(elev, 0, sizeof(InfElevator)); - elev->deleted = JTRUE; - } - return; - } - - const vec2_fixed def = { 0 }; - if (serialization_getMode() == SMODE_READ) - { - elev->deleted = JFALSE; - elev->self = elev; - } - - RSector* sector = elev->sector; - SERIALIZE(InfState_InitVersion, elev->type, IELEV_COUNT); - SERIALIZE(InfState_InitVersion, elev->trigMove, TRIGMOVE_HOLD); - serialization_serializeSectorPtr(stream, InfState_InitVersion, sector); - if (serialization_getMode() == SMODE_READ) - { - elev->sector = sector; - } - - SERIALIZE(InfState_InitVersion, elev->key, KEY_NONE); - SERIALIZE(InfState_InitVersion, elev->fixedStep, 0); - SERIALIZE(InfState_InitVersion, elev->nextTick, 0); - SERIALIZE(InfState_InitVersion, elev->timer, 0); - - // Matching sector link. - InfLink* elevLink = nullptr; - if (serialization_getMode() == SMODE_WRITE) - { - if (sector && sector->infLink) - { - allocator_saveIter(sector->infLink); - InfLink* link = (InfLink*)allocator_getHead(sector->infLink); - while (link) - { - if (link->type == LTYPE_SECTOR && link->elev == elev) - { - elevLink = link; - break; - } - link = (InfLink*)allocator_getNext(sector->infLink); - } - allocator_restoreIter(sector->infLink); - } - RSector* linkSector = elevLink ? sector : nullptr; - serialization_serializeSectorPtr(stream, InfState_InitVersion, linkSector); - } - else - { - RSector* linkSector; - serialization_serializeSectorPtr(stream, InfState_InitVersion, linkSector); - if (linkSector) - { - assert(linkSector == sector); - if (!linkSector->infLink) - { - linkSector->infLink = allocator_create(sizeof(InfLink)); - } - elevLink = (InfLink*)allocator_newItem(linkSector->infLink); - } - } - if (elevLink) - { - inf_serializeLink(stream, elevLink, sector->infLink); - } - - // Serialize the current stop allocator position. - s32 stopPos, stopPrev; - if (serialization_getMode() == SMODE_WRITE) - { - stopPos = allocator_getCurPos(elev->stops); - stopPrev = allocator_getPrevPos(elev->stops); - } - SERIALIZE(InfState_InitVersion, stopPos, -1); - SERIALIZE(InfState_InitVersion, stopPrev, -1); - - // Stops - s32 stopCount; - if (serialization_getMode() == SMODE_WRITE) - { - allocator_saveIter(elev->stops); - stopCount = allocator_getCount(elev->stops); - assert(!elev->stops || stopCount); - - SERIALIZE(InfState_InitVersion, stopCount, 0); - Stop* stop = (Stop*)allocator_getHead(elev->stops); - while (stop) - { - inf_serializeStop(stream, stop); - stop = (Stop*)allocator_getNext(elev->stops); - } - allocator_restoreIter(elev->stops); - } - else - { - SERIALIZE(InfState_InitVersion, stopCount, 0); - elev->stops = stopCount ? allocator_create(sizeof(Stop)) : nullptr; - for (s32 s = 0; s < stopCount; s++) - { - Stop* stop = (Stop*)allocator_newItem(elev->stops); - inf_serializeStop(stream, stop); - } - - // Set stop position. - if (stopPos >= 0) - { - assert(stopCount); - allocator_setPos(elev->stops, stopPos); - } - if (stopPrev >= 0) - { - assert(stopCount); - allocator_setPrevPos(elev->stops, stopPrev); - } - } - - // Slaves - s32 slaveCount; - if (serialization_getMode() == SMODE_WRITE) - { - allocator_saveIter(elev->slaves); - slaveCount = allocator_getCount(elev->slaves); - SERIALIZE(InfState_InitVersion, slaveCount, 0); - Slave* slave = (Slave*)allocator_getHead(elev->slaves); - while (slave) - { - inf_serializeSlave(stream, slave); - slave = (Slave*)allocator_getNext(elev->slaves); - } - allocator_restoreIter(elev->slaves); - } - else - { - SERIALIZE(InfState_InitVersion, slaveCount, 0); - elev->slaves = allocator_create(sizeof(Slave)); - for (s32 s = 0; s < slaveCount; s++) - { - Slave* slave = (Slave*)allocator_newItem(elev->slaves); - inf_serializeSlave(stream, slave); - } - } - - // Next Stop - s32 stopIndex; - if (serialization_getMode() == SMODE_WRITE) - { - stopIndex = elev->nextStop ? elev->nextStop->index : -1; - } - SERIALIZE(InfState_InitVersion, stopIndex, -1); - if (serialization_getMode() == SMODE_READ) - { - elev->nextStop = (stopIndex < 0) ? nullptr : (Stop*)allocator_getByIndex(elev->stops, stopIndex); - } - - SERIALIZE(InfState_InitVersion, elev->speed, 0); - SERIALIZE(InfState_InitVersion, elev->iValue, 0); - SERIALIZE(InfState_InitVersion, elev->dirOrCenter, def); - SERIALIZE(InfState_InitVersion, elev->flags, 0); - // Compute the elev->value pointer. - if (serialization_getMode() == SMODE_READ) - { - inf_computeElevValuePointer(elev); - } - - serialization_serializeDfSound(stream, InfState_InitVersion, &elev->sound0); - serialization_serializeDfSound(stream, InfState_InitVersion, &elev->sound1); - serialization_serializeDfSound(stream, InfState_InitVersion, &elev->sound2); - - if (serialization_getMode() == SMODE_READ) - { - // elev->loopingSoundID is not serialized, the sound will resume on the next update. - elev->loopingSoundID = NULL_SOUND; - } - - SERIALIZE(InfState_InitVersion, elev->updateFlags, 0); - SERIALIZE(InfState_InitVersion, elev->prevValue, 0); - } - - void inf_serializeTeleport(Stream* stream, Teleport* teleport) - { - const vec3_fixed def = { 0 }; - - serialization_serializeSectorPtr(stream, InfState_InitVersion, teleport->sector); - serialization_serializeSectorPtr(stream, InfState_InitVersion, teleport->target); - SERIALIZE(InfState_InitVersion, teleport->type, TELEPORT_BASIC); - SERIALIZE(InfState_InitVersion, teleport->dstPosition, def); - SERIALIZE_BUF(InfState_InitVersion, teleport->dstAngle, 3 * sizeof(angle14_16)); - - // Matching sector link. - InfLink* teleportLink = nullptr; - RSector* sector = teleport->sector; - RSector* linkSector = nullptr; - if (serialization_getMode() == SMODE_WRITE) - { - if (sector->infLink) - { - allocator_saveIter(sector->infLink); - InfLink* link = (InfLink*)allocator_getHead(sector->infLink); - while (link) - { - if (link->type == LTYPE_TELEPORT && link->teleport == teleport) - { - teleportLink = link; - linkSector = sector; - break; - } - link = (InfLink*)allocator_getNext(sector->infLink); - } - allocator_restoreIter(sector->infLink); - } - serialization_serializeSectorPtr(stream, InfState_InitVersion, linkSector); - if (linkSector) - { - inf_serializeLink(stream, teleportLink, linkSector->infLink); - } - } - else // SMODE_READ - { - RSector* linkSector; - serialization_serializeSectorPtr(stream, InfState_InitVersion, linkSector); - if (linkSector) - { - if (!linkSector->infLink) - { - linkSector->infLink = allocator_create(sizeof(InfLink)); - } - Allocator* parent = linkSector->infLink; - InfLink* link = (InfLink*)allocator_newItem(parent); - inf_serializeLink(stream, link, parent); - } - } - } - - void inf_serializeTarget(Stream* stream, TriggerTarget* target) - { - RSector* targetSector = nullptr; - s32 wallIndex = -1; - if (serialization_getMode() == SMODE_WRITE) - { - if (target->sector) - { - targetSector = target->sector; - } - else if (target->wall && target->wall->sector) - { - targetSector = target->wall->sector; - } - if (target->wall) - { - wallIndex = target->wall->id; - } - } - serialization_serializeSectorPtr(stream, InfState_InitVersion, targetSector); - SERIALIZE(InfState_InitVersion, wallIndex, -1); - if (serialization_getMode() == SMODE_READ) - { - target->sector = nullptr; - target->wall = nullptr; - if (wallIndex >= 0 && targetSector) - { - target->wall = &targetSector->walls[wallIndex]; - } - else if (targetSector) - { - target->sector = targetSector; - } - } - SERIALIZE(InfState_InitVersion, target->eventMask, 0); - } - - void inf_serializeTrigger(Stream* stream, InfTrigger* trigger) - { - SERIALIZE(InfState_InitVersion, trigger->deleted, 0); - if (trigger->deleted) - { - if (serialization_getMode() == SMODE_READ) - { - memset(trigger, 0, sizeof(InfTrigger)); - trigger->deleted = JTRUE; - } - return; - } - SERIALIZE(InfState_InitVersion, trigger->type, ITRIGGER_WALL); - - // Inf Link - s32 parentWallIndex = -1; - RSector* parentSector = nullptr; - if (serialization_getMode() == SMODE_WRITE) - { - if (trigger->type == ITRIGGER_SECTOR) - { - parentSector = (RSector*)trigger->parent; - assert(parentSector && parentSector->id == parentSector->index); - } - else - { - RWall* wall = (RWall*)trigger->parent; - parentSector = wall->sector; - parentWallIndex = wall->id; - assert(parentSector && parentSector->id == parentSector->index && parentWallIndex >= 0 && parentWallIndex < parentSector->wallCount); - } - } - serialization_serializeSectorPtr(stream, InfState_InitVersion, parentSector); - SERIALIZE(InfState_InitVersion, parentWallIndex, -1); - if (serialization_getMode() == SMODE_READ) - { - assert(parentSector && parentSector->id == parentSector->index); - trigger->parent = (trigger->type == ITRIGGER_SECTOR) ? (void*)parentSector : (void*)&parentSector->walls[parentWallIndex]; - } - InfLink* link = nullptr; - Allocator* parent = nullptr; - RWall* triggerWall = nullptr; - if (serialization_getMode() == SMODE_WRITE) - { - link = trigger->link; - assert(link->type == LTYPE_TRIGGER); - } - else // SMODE_READ - { - if (trigger->type == ITRIGGER_SECTOR && parentSector) - { - if (!parentSector->infLink) - { - parentSector->infLink = allocator_create(sizeof(InfLink)); - } - parent = parentSector->infLink; - link = (InfLink*)allocator_newItem(parentSector->infLink); - } - else if (parentSector && parentWallIndex >= 0) - { - RWall* wall = &parentSector->walls[parentWallIndex]; - if (!wall->infLink) - { - wall->infLink = allocator_create(sizeof(InfLink)); - } - parent = wall->infLink; - triggerWall = wall; - link = (InfLink*)allocator_newItem(wall->infLink); - } - trigger->link = link; - } - inf_serializeLink(stream, trigger->link, parent); - - // Animated Texture - serialization_serializeAnimatedTexturePtr(stream, InfState_InitVersion, trigger->animTex); - - // targets - if (serialization_getMode() == SMODE_WRITE) - { - allocator_saveIter(trigger->targets); - s32 targetCount = allocator_getCount(trigger->targets); - SERIALIZE(InfState_InitVersion, targetCount, 0); - TriggerTarget* target = (TriggerTarget*)allocator_getHead(trigger->targets); - while (target) - { - inf_serializeTarget(stream, target); - target = (TriggerTarget*)allocator_getNext(trigger->targets); - } - allocator_restoreIter(trigger->targets); - } - else // SMODE_READ - { - s32 targetCount; - SERIALIZE(InfState_InitVersion, targetCount, 0); - trigger->targets = allocator_create(sizeof(TriggerTarget)); - for (s32 i = 0; i < targetCount; i++) - { - TriggerTarget* target = (TriggerTarget*)allocator_newItem(trigger->targets); - inf_serializeTarget(stream, target); - } - } - - SERIALIZE(InfState_InitVersion, trigger->cmd, MSG_RUN_TASK); - SERIALIZE(InfState_InitVersion, trigger->event, 0); - SERIALIZE(InfState_InitVersion, trigger->arg0, 0); - SERIALIZE(InfState_InitVersion, trigger->arg1, 0); - SERIALIZE(InfState_InitVersion, trigger->master, 0); - - // trigger->tex - s32 frameIndex = -1; - if (serialization_getMode() == SMODE_WRITE) - { - AnimatedTexture* animTex = trigger->animTex; - if (trigger->tex && animTex) - { - // Which frame is it currently on? - for (s32 f = 0; f < animTex->count; f++) - { - if (trigger->tex == animTex->frameList[f]) - { - frameIndex = f; - break; - } - } - assert(frameIndex >= 0); - } - } - SERIALIZE(InfState_InitVersion, frameIndex, -1); - if (serialization_getMode() == SMODE_READ) - { - if (frameIndex >= 0) - { - AnimatedTexture* animTex = trigger->animTex; - if (animTex) - { - assert(frameIndex < animTex->count); - trigger->tex = animTex->frameList[frameIndex]; - if (triggerWall) - { - triggerWall->signTex = &trigger->tex; - } - } - } - else - { - assert(!trigger->animTex); - trigger->animTex = nullptr; - } - } - - serialization_serializeDfSound(stream, InfState_InitVersion, &trigger->soundId); - SERIALIZE(InfState_InitVersion, trigger->state, 0); - SERIALIZE(InfState_InitVersion, trigger->textId, 0); - } - - void inf_serialize(Stream* stream) - { - SERIALIZE_VERSION(InfState_CurVersion); - - s32 elevCount, teleCount, trigCount; - if (serialization_getMode() == SMODE_WRITE) - { - elevCount = allocator_getCount(s_infSerState.infElevators); - teleCount = allocator_getCount(s_infSerState.infTeleports); - trigCount = allocator_getCount(s_infSerState.infTriggers); - } - // Counts. - SERIALIZE(InfState_InitVersion, s_infSerState.activeTriggerCount, 0); - SERIALIZE(InfState_InitVersion, elevCount, 0); - SERIALIZE(InfState_InitVersion, teleCount, 0); - SERIALIZE(InfState_InitVersion, trigCount, 0); - - // Elevators. - const vec2_fixed def = { 0 }; - if (serialization_getMode() == SMODE_WRITE) - { - allocator_saveIter(s_infSerState.infElevators); - InfElevator* elev = (InfElevator*)allocator_getHead(s_infSerState.infElevators); - while (elev) - { - inf_serializeElevator(stream, elev); - elev = (InfElevator*)allocator_getNext(s_infSerState.infElevators); - } - allocator_restoreIter(s_infSerState.infElevators); - } - else // Read - { - for (s32 i = 0; i < elevCount; i++) - { - InfElevator* elev = (InfElevator*)allocator_newItem(s_infSerState.infElevators); - inf_serializeElevator(stream, elev); - } - } - - // Teleports - if (serialization_getMode() == SMODE_WRITE) - { - allocator_saveIter(s_infSerState.infTeleports); - Teleport* teleport = (Teleport*)allocator_getHead(s_infSerState.infTeleports); - while (teleport) - { - inf_serializeTeleport(stream, teleport); - teleport = (Teleport*)allocator_getNext(s_infSerState.infTeleports); - } - allocator_restoreIter(s_infSerState.infTeleports); - } - else // SMODE_READ - { - for (s32 i = 0; i < teleCount; i++) - { - Teleport* teleport = (Teleport*)allocator_newItem(s_infSerState.infTeleports); - inf_serializeTeleport(stream, teleport); - } - } - - // Triggers - if (serialization_getMode() == SMODE_WRITE) - { - allocator_saveIter(s_infSerState.infTriggers); - InfTrigger* trigger = (InfTrigger*)allocator_getHead(s_infSerState.infTriggers); - while (trigger) - { - inf_serializeTrigger(stream, trigger); - trigger = (InfTrigger*)allocator_getNext(s_infSerState.infTriggers); - } - allocator_restoreIter(s_infSerState.infTriggers); - } - else // SMODE_READ - { - for (s32 i = 0; i < trigCount; i++) - { - InfTrigger* trigger = (InfTrigger*)allocator_newItem(s_infSerState.infTriggers); - inf_serializeTrigger(stream, trigger); - } - } - - // Fixup - if (serialization_getMode() == SMODE_READ) - { - inf_serializeFixupLinks(); - } - } - - ///////////////////////////////////////////// - // Internal - Serialize - ///////////////////////////////////////////// - void inf_serializeMessage(Stream* stream, InfMessage* msg) - { - RSector* sector = nullptr; - s32 wallIndex = -1; - if (serialization_getMode() == SMODE_WRITE) - { - if (msg->sector) - { - sector = msg->sector; - } - else if (msg->wall) - { - sector = msg->wall->sector; - } - wallIndex = (msg->wall) ? msg->wall->id : -1; - } - // It is possible for both wallIndex and sectorIndex to be null. - serialization_serializeSectorPtr(stream, InfState_InitVersion, sector); - SERIALIZE(InfState_InitVersion, wallIndex, -1); - if (serialization_getMode() == SMODE_READ) - { - msg->wall = nullptr; - msg->sector = nullptr; - if (wallIndex >= 0) - { - msg->wall = sector ? §or->walls[wallIndex] : nullptr; - } - else - { - msg->sector = sector; - } - } - - SERIALIZE(InfState_InitVersion, msg->msgType, MSG_COUNT); - SERIALIZE(InfState_InitVersion, msg->event, 0); - SERIALIZE(InfState_InitVersion, msg->arg1, 0); - SERIALIZE(InfState_InitVersion, msg->arg2, 0); - } - - void inf_serializeAdjoin(Stream* stream, Stop* stop, AdjoinCmd* adjCmd) - { - serialization_serializeSectorPtr(stream, InfState_InitVersion, adjCmd->sector0); - serialization_serializeSectorPtr(stream, InfState_InitVersion, adjCmd->sector1); - - if (serialization_getMode() == SMODE_WRITE) - { - s32 id0 = adjCmd->wall0 ? adjCmd->wall0->id : -1; - s32 id1 = adjCmd->wall1 ? adjCmd->wall1->id : -1; - SERIALIZE(InfState_InitVersion, id0, 0); - SERIALIZE(InfState_InitVersion, id1, 0); - } - else // SMODE_READ - { - s32 wall0Id, wall1Id; - SERIALIZE(InfState_InitVersion, wall0Id, 0); - SERIALIZE(InfState_InitVersion, wall1Id, 0); - adjCmd->wall0 = wall0Id >= 0 ? &adjCmd->sector0->walls[wall0Id] : nullptr; - adjCmd->wall1 = wall1Id >= 0 ? &adjCmd->sector1->walls[wall1Id] : nullptr; - } - } - - void inf_serializeStop(Stream* stream, Stop* stop) - { - SERIALIZE(InfState_InitVersion, stop->value, 0); - SERIALIZE(InfState_InitVersion, stop->delay, 0); - - // Messages - s32 msgCount; - if (serialization_getMode() == SMODE_WRITE) - { - msgCount = allocator_getCount(stop->messages); - } - SERIALIZE(InfState_InitVersion, msgCount, 0); - if (serialization_getMode() == SMODE_WRITE) - { - allocator_saveIter(stop->messages); - InfMessage* msg = (InfMessage*)allocator_getHead(stop->messages); - while (msg) - { - inf_serializeMessage(stream, msg); - msg = (InfMessage*)allocator_getNext(stop->messages); - } - allocator_restoreIter(stop->messages); - } - else // SMODE_READ - { - stop->messages = allocator_create(sizeof(InfMessage)); - for (s32 m = 0; m < msgCount; m++) - { - InfMessage* msg = (InfMessage*)allocator_newItem(stop->messages); - inf_serializeMessage(stream, msg); - } - } - - // Adjoin Commands - s32 adjCount; - if (serialization_getMode() == SMODE_WRITE) - { - adjCount = allocator_getCount(stop->adjoinCmds); - } - SERIALIZE(InfState_InitVersion, adjCount, 0); - if (serialization_getMode() == SMODE_WRITE) - { - allocator_saveIter(stop->adjoinCmds); - AdjoinCmd* adjCmd = (AdjoinCmd*)allocator_getHead(stop->adjoinCmds); - while (adjCmd) - { - inf_serializeAdjoin(stream, stop, adjCmd); - adjCmd = (AdjoinCmd*)allocator_getNext(stop->adjoinCmds); - } - allocator_restoreIter(stop->adjoinCmds); - } - else // SMODE_READ - { - stop->adjoinCmds = allocator_create(sizeof(AdjoinCmd)); - for (s32 a = 0; a < adjCount; a++) - { - AdjoinCmd* adjCmd = (AdjoinCmd*)allocator_newItem(stop->adjoinCmds); - inf_serializeAdjoin(stream, stop, adjCmd); - } - } - - serialization_serializeDfSound(stream, InfState_InitVersion, &stop->pageId); - SERIALIZE(InfState_InitVersion, stop->floorTexSecId, -1); - SERIALIZE(InfState_InitVersion, stop->ceilTexSecId, -1); - SERIALIZE(InfState_InitVersion, stop->index, -1); - - if (serialization_getMode() == SMODE_READ) - { - stop->floorTex = nullptr; - stop->ceilTex = nullptr; - if (stop->floorTexSecId >= 0) - { - stop->floorTex = s_levelState.sectors[stop->floorTexSecId].floorTex; - } - if (stop->ceilTexSecId >= 0) - { - stop->ceilTex = s_levelState.sectors[stop->ceilTexSecId].ceilTex; - } - } - } - - void inf_serializeSlave(Stream* stream, Slave* slave) - { - serialization_serializeSectorPtr(stream, InfState_InitVersion, slave->sector); - SERIALIZE(InfState_InitVersion, slave->value, 0); - } - - void inf_serializeFixupLink(InfLink* link) - { - const s32 index = link->serializeIndex; - switch (link->type) - { - case LTYPE_SECTOR: - { - link->elev = (InfElevator*)allocator_getByIndex(s_infSerState.infElevators, index); - } break; - case LTYPE_TRIGGER: - { - link->trigger = (InfTrigger*)allocator_getByIndex(s_infSerState.infTriggers, index); - } break; - case LTYPE_TELEPORT: - { - link->teleport = (Teleport*)allocator_getByIndex(s_infSerState.infTeleports, index); - } break; - } - } - - void inf_serializeFixupLinks() - { - RSector* sector = s_levelState.sectors; - for (u32 s = 0; s < s_levelState.sectorCount; s++, sector++) - { - allocator_saveIter(sector->infLink); - InfLink* link = (InfLink*)allocator_getHead(sector->infLink); - while (link) - { - inf_serializeFixupLink(link); - link = (InfLink*)allocator_getNext(sector->infLink); - } - allocator_restoreIter(sector->infLink); - - s32 wallCount = sector->wallCount; - RWall* wall = sector->walls; - for (s32 w = 0; w < wallCount; w++, wall++) - { - allocator_saveIter(wall->infLink); - link = (InfLink*)allocator_getHead(wall->infLink); - while (link) - { - inf_serializeFixupLink(link); - link = (InfLink*)allocator_getNext(wall->infLink); - } - allocator_restoreIter(wall->infLink); - } - } - } - - void inf_serializeLink(Stream* stream, InfLink* link, Allocator* parent) - { - SERIALIZE(InfState_InitVersion, link->type, LTYPE_SECTOR); - // Task function is derived from the type. - s32 index = -1; - if (serialization_getMode() == SMODE_WRITE) - { - switch (link->type) - { - case LTYPE_SECTOR: - { - index = allocator_getIndex(s_infSerState.infElevators, link->elev); - } break; - case LTYPE_TRIGGER: - { - index = allocator_getIndex(s_infSerState.infTriggers, link->trigger); - } break; - case LTYPE_TELEPORT: - { - index = allocator_getIndex(s_infSerState.infTeleports, link->teleport); - } break; - } - } - SERIALIZE(InfState_InitVersion, index, -1); - if (serialization_getMode() == SMODE_READ) - { - link->serializeIndex = index; - switch (link->type) - { - case LTYPE_SECTOR: - { - link->elev = nullptr; - link->task = s_infState.infElevTask; - link->freeFunc = (InfFreeFunc)inf_deleteElevator; - } break; - case LTYPE_TRIGGER: - { - link->trigger = nullptr; - link->task = s_infState.infTriggerTask; - link->freeFunc = (InfFreeFunc)inf_deleteTrigger; - } break; - case LTYPE_TELEPORT: - { - link->teleport = nullptr; - link->task = s_infState.teleportTask; - link->freeFunc = nullptr; - } break; - } - } - - SERIALIZE(InfState_InitVersion, link->eventMask, 0); - SERIALIZE(InfState_InitVersion, link->entityMask, 0); - - if (serialization_getMode() == SMODE_READ) - { - link->parent = parent; - } - } - - - ///////////////////////////////////////////// - // Internal - Deserialize - ///////////////////////////////////////////// - void inf_computeElevValuePointer(InfElevator* elev) - { - RSector* sector = elev->sector; - switch (elev->type) - { - case IELEV_MOVE_CEILING: - elev->value = §or->ceilingHeight; - break; - case IELEV_MOVE_FLOOR: - case IELEV_MOVE_FC: - elev->value = §or->floorHeight; - break; - case IELEV_MOVE_OFFSET: - elev->value = §or->secHeight; - break; - case IELEV_CHANGE_LIGHT: - elev->value = §or->ambient; - break; - case IELEV_MOVE_WALL: - case IELEV_ROTATE_WALL: - case IELEV_SCROLL_WALL: - case IELEV_SCROLL_FLOOR: - case IELEV_SCROLL_CEILING: - case IELEV_CHANGE_WALL_LIGHT: - elev->value = &elev->iValue; - break; - default: - // It shouldn't reach here. - assert(0); - }; - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/InfSystem/infState.h b/components/darkforces/tfe/TFE_Jedi/InfSystem/infState.h deleted file mode 100644 index 99b61f71..00000000 --- a/components/darkforces/tfe/TFE_Jedi/InfSystem/infState.h +++ /dev/null @@ -1,35 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// INF System State -// Internal to the INF system. -// Note - this file should *only* be included by internal cpp files. -////////////////////////////////////////////////////////////////////// -#include "infPublicTypes.h" -#include -#include -#include - -namespace TFE_Jedi -{ - struct Stop; - - // State that should be serialized for quick-saves. - struct InfSerializableState - { - s32 activeTriggerCount = 0; - Allocator* infElevators = nullptr; - Allocator* infTeleports = nullptr; - Allocator* infTriggers = nullptr; - }; - extern InfSerializableState s_infSerState; - - // General state that should be cleared on reset but does not need to be serialized. - struct InfState - { - Task* infElevTask = nullptr; - Task* infTriggerTask = nullptr; - Task* teleportTask = nullptr; - Stop* nextStop = nullptr; - }; - extern InfState s_infState; -} diff --git a/components/darkforces/tfe/TFE_Jedi/InfSystem/infSystem.cpp b/components/darkforces/tfe/TFE_Jedi/InfSystem/infSystem.cpp deleted file mode 100644 index 6ddf9971..00000000 --- a/components/darkforces/tfe/TFE_Jedi/InfSystem/infSystem.cpp +++ /dev/null @@ -1,3672 +0,0 @@ -#include - -#include "infSystem.h" -#include "infState.h" -#include "message.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -// TODO: This will make adding Outlaws harder, fix the abstraction. -#include -#include -#include "infTypesInternal.h" -// Include update functions -#include "infElevatorUpdateFunc.h" - -using namespace TFE_Jedi; -using namespace TFE_DarkForces; - -namespace TFE_Jedi -{ - enum InfConstants - { - MAX_INF_ITEMS = 512, - DELAY_SLEEP = 0xffffffff, - }; - - const fixed16_16 c_verticalElevCrushThres = 0x3000; // 0x4000 in the original code, reduced to account for higher framerate. - const fixed16_16 c_verticalElevCrushThres2 = 0x1000; - - typedef union { RSector* sector; RWall* wall; } InfTriggerObject; - - // Long lived state - this is setup during game initialization and then left alone. - SoundSourceId s_moveCeilSound0 = NULL_SOUND; - SoundSourceId s_moveCeilSound1 = NULL_SOUND; - SoundSourceId s_moveCeilSound2 = NULL_SOUND; - SoundSourceId s_moveFloorSound0 = NULL_SOUND; - SoundSourceId s_moveFloorSound1 = NULL_SOUND; - SoundSourceId s_moveFloorSound2 = NULL_SOUND; - SoundSourceId s_doorSound = NULL_SOUND; - SoundSourceId s_needKeySoundId = NULL_SOUND; - SoundSourceId s_switchDefaultSndId = NULL_SOUND; - - // Temporary state that does not need to be cleared or serialized. - static std::vector s_buffer; - static char s_infArg0[256]; - static char s_infArg1[256]; - static char s_infArg2[256]; - static char s_infArg3[256]; - static char s_infArg4[256]; - static char s_infArgExtra[256]; - - // DOS hack... this is required since elevators with an invalid delay use the previous valid delay. - static Tick s_prevStopDelay = 0; - - // Forward Declarations. - void inf_elevatorTaskFunc(MessageType msg); - void inf_telelporterTaskFunc(MessageType msg); - void inf_triggerTaskFunc(MessageType msg); - - void infElevatorMsgFunc(MessageType msgType); - void infTriggerMsgFunc(MessageType msgType); - void inf_handleTriggerMsg(InfTrigger* trigger); - - void inf_deleteElevator(InfElevator* elev); - void inf_deleteTrigger(InfTrigger* trigger); - JBool updateElevator(InfElevator* elev); - void elevHandleStopDelay(InfElevator* elev); - Stop* inf_advanceStops(Allocator* stops, s32 absoluteStop, s32 relativeStop); - bool inf_parseElevatorCommand(s32 argCount, KEYWORD action, Allocator* linkAlloc, bool seqEnd, InfElevator*& elev, s32& initStopIndex, InfLink*& link); - void inf_parseMessage(MessageType* type, u32* arg1, u32* arg2, u32* evt, const char* infArg0, const char* infArg1, const char* infArg2, bool elevator = false); - void inf_setWallBits(RWall* wall); - void inf_clearWallBits(RWall* wall); - - InfTrigger* inf_createTrigger(TriggerType type, InfTriggerObject obj); - - void inf_stopAdjoinCommands(Stop* stop); - void inf_stopHandleMessages(MessageType msg); - void inf_handleMsgLights(); - void inf_elevatorStart(InfElevator* elev); - vec3_fixed inf_getElevSoundPos(InfElevator* elev); - - void inf_teleporterTaskLocal(MessageType msg); - void inf_elevatorTaskLocal(MessageType msg); - void inf_triggerTaskLocal(MessageType msg); - - ///////////////////////////////////////////////////// - // API - ///////////////////////////////////////////////////// - - // No need to do the conversion ourselves like the DOS code did. - s32 strToInt(const char* str) - { - char* endPtr; - return strtol(str, &endPtr, 10); - } - - u32 strToUInt(const char* str) - { - char* endPtr; - return strtoul(str, &endPtr, 10); - } - - void inf_createElevatorTask() - { - s_infSerState.infElevators = allocator_create(sizeof(InfElevator)); - s_infState.infElevTask = createSubTask("elevator", inf_elevatorTaskFunc, inf_elevatorTaskLocal); - } - - void inf_createTeleportTask() - { - s_infState.teleportTask = createSubTask("teleporter", inf_telelporterTaskFunc, inf_teleporterTaskLocal); - task_setNextTick(s_infState.teleportTask, TASK_SLEEP); - s_infSerState.infTeleports = allocator_create(sizeof(Teleport)); - } - - void inf_createTriggerTask() - { - s_infState.infTriggerTask = createSubTask("trigger", inf_triggerTaskFunc, inf_triggerTaskLocal); - s_infSerState.activeTriggerCount = 0; - // TFE: create a trigger allocator to make tracking easier. - s_infSerState.infTriggers = allocator_create(sizeof(InfTrigger)); - } - - InfLink* allocateLink(Allocator* infLinks, InfElevator* elev) - { - InfLink* link = (InfLink*)allocator_newItem(infLinks); - link->type = LTYPE_SECTOR; - link->entityMask = INF_ENTITY_PLAYER; - link->eventMask = INF_EVENT_NONE; - link->freeFunc = nullptr; - link->elev = elev; - link->parent = infLinks; - link->task = s_infState.infElevTask; - - return link; - } - - InfLink* inf_addElevatorToSector(InfElevator* elev, RSector* sector) - { - if (!sector->infLink) - { - sector->infLink = allocator_create(sizeof(InfLink)); - } - return allocateLink(sector->infLink, elev); - } - - Stop* allocateStop(Allocator* stops) - { - s32 index = allocator_getCount(stops); - - Stop* stop = (Stop*)allocator_newItem(stops); - stop->value = 0; - stop->delay = TICKS(4); // 4 seconds. - stop->messages = 0; - stop->adjoinCmds = 0; - stop->pageId = 0; - stop->floorTex = nullptr; - stop->ceilTex = nullptr; - stop->floorTexSecId = -1; - stop->ceilTexSecId = -1; - stop->index = index; - - return stop; - } - - Stop* allocateStop(InfElevator* elev) - { - if (!elev->stops) - { - elev->stops = allocator_create(sizeof(Stop)); - } - return allocateStop(elev->stops); - } - - void inf_gotoInitialStop(InfElevator* elev, s32 stopIndex) - { - if (!elev || !elev->stops) - { - if (elev) { elev->nextTick = s_curTick; } - return; - } - - Stop* stop = (Stop*)allocator_getByIndex(elev->stops, stopIndex); - if (!stop) { return; } - - elev->nextStop = stop; - fixed16_16 speed = elev->speed; - elev->speed = 0; - - fixed16_16 dt = s_deltaTime; - fixed16_16 fixedStep = elev->fixedStep; - elev->fixedStep = 0; - if (!s_deltaTime) - { - s_deltaTime = ONE_16; - } - updateElevator(elev); - - elev->fixedStep = fixedStep; - elev->speed = speed; - - Stop* next = elev->nextStop; - Tick delay = next->delay; - - if (delay == IDELAY_TERMINATE) - { - inf_deleteElevator(elev); - elev = nullptr; - return; - } - else if (delay == IDELAY_HOLD) - { - elev->nextTick = DELAY_SLEEP; - } - else - { - elev->nextTick = s_curTick + next->delay; - } - - // Setup the next stop. - elev->nextStop = inf_advanceStops(elev->stops, 0, 1); - } - - InfElevator* inf_allocateElevItem(RSector* sector, InfElevatorType type) - { - InfElevator* elev = (InfElevator*)allocator_newItem(s_infSerState.infElevators); - elev->trigMove = TRIGMOVE_HOLD; - elev->key = KEY_NONE; - elev->fixedStep = 0; - elev->timer = 0xffffffff; - elev->stops = nullptr; - elev->slaves = nullptr; - elev->nextStop = nullptr; - elev->value = nullptr; - elev->iValue = 0; - elev->prevValue = 0; - elev->dirOrCenter.x = 0; - elev->dirOrCenter.z = 0; - elev->flags = 0; - elev->loopingSoundID = NULL_SOUND; - elev->deleted = JFALSE; - - elev->type = type; - elev->self = elev; - elev->sector = sector; - elev->updateFlags = ELEV_MASTER_ON; - elev->sound0 = NULL_SOUND; - elev->sound1 = NULL_SOUND; - elev->sound2 = NULL_SOUND; - - switch (type) - { - case IELEV_MOVE_CEILING: - elev->speed = FIXED(8); - elev->trigMove = TRIGMOVE_LAST; - elev->value = §or->ceilingHeight; - elev->sound0 = s_moveCeilSound0; - elev->sound1 = s_moveCeilSound1; - elev->sound2 = s_moveCeilSound2; - break; - case IELEV_MOVE_FLOOR: - case IELEV_MOVE_FC: - elev->speed = FIXED(8); - elev->trigMove = TRIGMOVE_CONT; - elev->value = §or->floorHeight; - elev->sound0 = s_moveFloorSound0; - elev->sound1 = s_moveFloorSound1; - elev->sound2 = s_moveFloorSound2; - break; - case IELEV_MOVE_OFFSET: - elev->speed = FIXED(8); - elev->trigMove = TRIGMOVE_CONT; - elev->value = §or->secHeight; - elev->sound0 = s_moveFloorSound0; - elev->sound1 = s_moveFloorSound1; - elev->sound2 = s_moveFloorSound2; - break; - case IELEV_MOVE_WALL: - elev->speed = FIXED(15); - elev->trigMove = TRIGMOVE_CONT; - elev->value = &elev->iValue; - sinCosFixed(0, &elev->dirOrCenter.x, &elev->dirOrCenter.z); - elev->sound0 = s_moveCeilSound0; - elev->sound1 = s_moveCeilSound1; - elev->sound2 = s_moveCeilSound2; - break; - case IELEV_ROTATE_WALL: - elev->speed = FIXED(1024); - elev->trigMove = TRIGMOVE_CONT; - elev->value = &elev->iValue; - elev->sound0 = s_moveCeilSound0; - elev->sound1 = s_moveCeilSound1; - elev->sound2 = s_moveCeilSound2; - break; - case IELEV_SCROLL_WALL: - elev->speed = FIXED(4); - elev->value = &elev->iValue; - elev->trigMove = TRIGMOVE_CONT; - break; - case IELEV_SCROLL_FLOOR: - elev->speed = FIXED(4); - elev->value = &elev->iValue; - elev->trigMove = TRIGMOVE_CONT; - elev->flags = INF_EFLAG_MOVE_FLOOR | INF_EFLAG_MOVE_SECHT; - sinCosFixed(0, &elev->dirOrCenter.x, &elev->dirOrCenter.z); - break; - case IELEV_SCROLL_CEILING: - elev->speed = FIXED(4); - elev->value = &elev->iValue; - elev->trigMove = TRIGMOVE_CONT; - elev->flags = INF_EFLAG_MOVE_CEIL; - sinCosFixed(0, &elev->dirOrCenter.x, &elev->dirOrCenter.z); - break; - case IELEV_CHANGE_LIGHT: - elev->speed = FIXED(32); - elev->value = §or->ambient; - break; - case IELEV_CHANGE_WALL_LIGHT: - elev->speed = FIXED(32); - elev->value = &elev->iValue; - break; - }; - - return elev; - } - - InfElevator* inf_allocateSpecialElevator(RSector* sector, InfSpecialElevator type) - { - if (type >= IELEV_SP_COUNT) - { - return nullptr; - } - - InfElevator* elev = nullptr; - InfLink* link = nullptr; - switch (type) - { - case IELEV_SP_BASIC: - { - elev = inf_allocateElevItem(sector, IELEV_MOVE_FLOOR); - link = inf_addElevatorToSector(elev, sector); - - elev->trigMove = TRIGMOVE_CONT; - elev->speed = FIXED(8); - link->entityMask = INF_ENTITY_PLAYER | INF_ENTITY_SMART_OBJ; - link->eventMask = INF_EVENT_UNUSED2 | INF_EVENT_UNUSED3 | INF_EVENT_NUDGE_BACK | INF_EVENT_NUDGE_FRONT | INF_EVENT_ENTER_SECTOR; - } break; - case IELEV_SP_BASIC_AUTO: - { - elev = inf_allocateElevItem(sector, IELEV_MOVE_FLOOR); - link = inf_addElevatorToSector(elev, sector); - - fixed16_16 maxFloor = -COL_INFINITY; - fixed16_16 minFloor = COL_INFINITY; - s32 wallCount = sector->wallCount; - RWall* wall = sector->walls; - for (s32 i = 0; i < wallCount; i++, wall++) - { - RSector* nextSector = wall->nextSector; - if (nextSector) - { - maxFloor = max(maxFloor, nextSector->floorHeight); - minFloor = min(minFloor, nextSector->floorHeight); - } - } - - fixed16_16 floorHeight = sector->floorHeight; - if (minFloor == floorHeight) - { - std::swap(maxFloor, minFloor); - } - Stop* stop0 = allocateStop(elev); - stop0->value = maxFloor; - stop0->index = 0; - - // Add another stop. - Stop* stop1 = allocateStop(elev); - stop1->value = minFloor; - stop1->index = 1; - - elev->speed = FIXED(8); - elev->trigMove = TRIGMOVE_CONT; - stop1->delay = IDELAY_HOLD; - link->entityMask = INF_ENTITY_PLAYER | INF_ENTITY_SMART_OBJ; - link->eventMask = INF_EVENT_UNUSED2 | INF_EVENT_UNUSED3 | INF_EVENT_NUDGE_BACK | INF_EVENT_NUDGE_FRONT | INF_EVENT_ENTER_SECTOR; - } break; - case IELEV_SP_UNIMPLEMENTED: - case IELEV_SP_MID: - // Unimplemented in the DOS code (or implementation removed). - break; - case IELEV_SP_INV: - { - elev = inf_allocateElevItem(sector, IELEV_MOVE_CEILING); - link = inf_addElevatorToSector(elev, sector); - - elev->trigMove = TRIGMOVE_CONT; - elev->speed = FIXED(8); - link->entityMask = INF_ENTITY_PLAYER | INF_ENTITY_SMART_OBJ; - link->eventMask = INF_EVENT_UNUSED2 | INF_EVENT_UNUSED3 | INF_EVENT_NUDGE_BACK | INF_EVENT_NUDGE_FRONT | INF_EVENT_ENTER_SECTOR; - } break; - case IELEV_SP_DOOR: - { - elev = inf_allocateElevItem(sector, IELEV_MOVE_CEILING); - link = inf_addElevatorToSector(elev, sector); - - Stop* stop0 = allocateStop(elev); - stop0->value = sector->floorHeight; - stop0->delay = IDELAY_HOLD; - stop0->index = 0; - - Stop* stop1 = allocateStop(elev); - stop1->value = sector->ceilingHeight; - stop1->index = 1; - - elev->trigMove = TRIGMOVE_LAST; - elev->sound1 = NULL_SOUND; - elev->sound2 = NULL_SOUND; - elev->sound0 = s_doorSound; - - elev->speed = FIXED(30); - link->entityMask = INF_ENTITY_PLAYER | INF_ENTITY_SMART_OBJ; - link->eventMask = INF_EVENT_UNUSED2 | INF_EVENT_UNUSED3 | INF_EVENT_NUDGE_BACK | INF_EVENT_NUDGE_FRONT; - } break; - case IELEV_SP_DOOR_INV: - { - elev = inf_allocateElevItem(sector, IELEV_MOVE_FLOOR); - link = inf_addElevatorToSector(elev, sector); - - Stop* stop0 = allocateStop(elev); - Stop* stop1 = allocateStop(elev); - stop0->value = sector->ceilingHeight; - stop0->delay = IDELAY_HOLD; - stop0->index = 0; - stop1->value = sector->floorHeight; - stop1->index = 1; - - elev->trigMove = TRIGMOVE_LAST; - elev->speed = FIXED(15); - link->entityMask = INF_ENTITY_PLAYER | INF_ENTITY_SMART_OBJ; - link->eventMask = INF_EVENT_UNUSED2 | INF_EVENT_UNUSED3 | INF_EVENT_NUDGE_BACK | INF_EVENT_NUDGE_FRONT; - } break; - case IELEV_SP_DOOR_MID: - { - fixed16_16 halfHeight = TFE_Jedi::abs(sector->ceilingHeight - sector->floorHeight) >> 1; - fixed16_16 middle = sector->floorHeight - halfHeight; - - // Upper Part - elev = inf_allocateElevItem(sector, IELEV_MOVE_CEILING); - link = inf_addElevatorToSector(elev, sector); - - Stop* stop0 = allocateStop(elev); - stop0->value = middle; - stop0->delay = IDELAY_HOLD; - stop0->index = 0; - - Stop* stop1 = allocateStop(elev); - stop1->value = sector->ceilingHeight; - stop1->index = 1; - inf_gotoInitialStop(elev, 0); - - elev->trigMove = TRIGMOVE_LAST; - elev->speed = FIXED(15); - link->entityMask = INF_ENTITY_PLAYER | INF_ENTITY_SMART_OBJ; - link->eventMask = INF_EVENT_UNUSED2 | INF_EVENT_UNUSED3 | INF_EVENT_NUDGE_BACK | INF_EVENT_NUDGE_FRONT; - - // Lower Part - elev = inf_allocateElevItem(sector, IELEV_MOVE_FLOOR); - link = inf_addElevatorToSector(elev, sector); - - stop0 = allocateStop(elev); - stop0->value = middle; - stop0->delay = IDELAY_HOLD; - stop0->index = 0; - - stop1 = allocateStop(elev); - stop1->value = sector->floorHeight; - stop1->index = 1; - - elev->trigMove = TRIGMOVE_LAST; - elev->speed = FIXED(15); - link->entityMask = INF_ENTITY_PLAYER | INF_ENTITY_SMART_OBJ; - link->eventMask = INF_EVENT_UNUSED2 | INF_EVENT_UNUSED3 | INF_EVENT_NUDGE_BACK | INF_EVENT_NUDGE_FRONT; - } break; - case IELEV_SP_MORPH_SPIN1: - { - elev = inf_allocateElevItem(sector, IELEV_ROTATE_WALL); - link = inf_addElevatorToSector(elev, sector); - link->entityMask = INF_ENTITY_PLAYER | INF_ENTITY_SMART_OBJ; - link->eventMask = INF_EVENT_ANY; - } break; - case IELEV_SP_MORPH_SPIN2: - { - elev = inf_allocateElevItem(sector, IELEV_ROTATE_WALL); - link = inf_addElevatorToSector(elev, sector); - link->entityMask = INF_ENTITY_PLAYER | INF_ENTITY_SMART_OBJ; - link->eventMask = INF_EVENT_ANY; - // This makes the objects move with the sector. - elev->flags = INF_EFLAG_MOVE_FLOOR | INF_EFLAG_MOVE_SECHT | INF_EFLAG_MOVE_CEIL; - } break; - case IELEV_SP_MORPH_MOVE1: - { - elev = inf_allocateElevItem(sector, IELEV_MOVE_WALL); - link = inf_addElevatorToSector(elev, sector); - link->entityMask = INF_ENTITY_PLAYER | INF_ENTITY_SMART_OBJ; - link->eventMask = INF_EVENT_ANY; - } break; - case IELEV_SP_MORPH_MOVE2: - { - elev = inf_allocateElevItem(sector, IELEV_MOVE_WALL); - link = inf_addElevatorToSector(elev, sector); - link->entityMask = INF_ENTITY_PLAYER | INF_ENTITY_SMART_OBJ; - link->eventMask = INF_EVENT_ANY; - // This makes the objects move with the sector. - elev->flags = INF_EFLAG_MOVE_FLOOR | INF_EFLAG_MOVE_SECHT | INF_EFLAG_MOVE_CEIL; - } break; - case IELEV_SP_EXPLOSIVE_WALL: - { - elev = inf_allocateElevItem(sector, IELEV_MOVE_CEILING); - link = inf_addElevatorToSector(elev, sector); - - Stop* stop0 = allocateStop(elev); - Stop* stop1 = allocateStop(elev); - - stop0->value = sector->floorHeight; - stop0->delay = IDELAY_HOLD; - stop0->index = 0; - - stop1->value = sector->ceilingHeight; - stop1->delay = IDELAY_TERMINATE; - stop1->index = 1; - - elev->trigMove = TRIGMOVE_LAST; - elev->speed = 0; - elev->sound0 = NULL_SOUND; - elev->sound1 = NULL_SOUND; - elev->sound2 = NULL_SOUND; - - link->entityMask = INF_ENTITY_ANY; - link->eventMask = INF_EVENT_EXPLOSION; - } break; - }; - - link->freeFunc = (InfFreeFunc)inf_deleteElevator; - if (elev) - { - inf_gotoInitialStop(elev, 0); - } - return elev; - } - - Stop* inf_addStop(InfElevator* elev, s32 value) - { - Allocator* stops = elev->stops; - if (!elev->stops) - { - elev->stops = allocator_create(sizeof(Stop)); - stops = elev->stops; - } - s32 index = allocator_getCount(stops); - Stop* stop = allocateStop(stops); - stop->value = value; - - return stop; - } - - void inf_setStopDelay(Stop* stop, u32 delay) - { - stop->delay = delay; - } - - void inf_getMessageTarget(const char* arg, RSector** sector, RWall** targetWall) - { - KEYWORD key = getKeywordIndex(arg); - if (key == KW_SYSTEM) - { - *sector = nullptr; - *targetWall = nullptr; - return; - } - - RSector* msgSector = nullptr; - RWall* wall = nullptr; - s32 wallIndex = -1; - - // There should be a variant of strstr() that returns a non-constant pointer, but in Visual Studio it is always constant. - char* parenOpen = (char*)strstr(arg, "("); - // This message targets a wall rather than a whole sector. - if (parenOpen) - { - *parenOpen = 0; - parenOpen++; - - char* parenClose = (char*)strstr(arg, ")"); - // This should never be true and this doesn't seem to be hit at runtime. - // I wonder if this was meant to be { char* parenClose = (char*)strstr(parenOpen, ")"); } - which would make more sense. - // Or it could have been check *before* the location at ")" was set to 0 above. - if (parenClose) - { - *parenClose = 0; - } - // Finally parse the integer and set the wall index. - wallIndex = strToInt(parenOpen); - } - - MessageAddress* msgAddr = message_getAddress(arg); - if (msgAddr) - { - msgSector = msgAddr->sector; - if (wallIndex != -1) // >= 0 would be safer, but the original code specifically checks against -1. - { - // Sets wall and removes sector. - if (wallIndex < msgSector->wallCount) - { - wall = &msgSector->walls[wallIndex]; - } - // Note that even if the wall index is invalid, msgSector is nulled out. - msgSector = nullptr; - } - } - - *sector = msgSector; - *targetWall = wall; - } - - Stop* inf_getStopByIndex(InfElevator* elev, s32 index) - { - Stop* stop = nullptr; - if (elev->stops) - { - stop = (Stop*)allocator_getHead(elev->stops); - while (index--) - { - stop = (Stop*)allocator_getNext(elev->stops); - } - } - return stop; - } - - void inf_addSlave(InfElevator* elev, fixed16_16 value, RSector* sector) - { - if (!elev->slaves) - { - elev->slaves = allocator_create(sizeof(Slave)); - } - Slave* slave = (Slave*)allocator_newItem(elev->slaves); - slave->sector = sector; - slave->value = value; - } - - void inf_setDirFromAngle(InfElevator* elev, angle14_32 angle) - { - sinCosFixed(angle, &elev->dirOrCenter.x, &elev->dirOrCenter.z); - } - - TriggerTarget* inf_addTriggerTarget(InfTrigger* trigger, RSector* targetSector, RWall* targetWall, u32 eventMask) - { - TriggerTarget* target = (TriggerTarget*)allocator_newItem(trigger->targets); - target->sector = targetSector; - target->wall = targetWall; - target->eventMask = eventMask; - - return target; - } - - Teleport* inf_createTeleport(TeleportType type, RSector* sector) - { - Teleport* teleport = (Teleport*)allocator_newItem(s_infSerState.infTeleports); - teleport->dstAngle[0] = 0; - teleport->dstAngle[1] = 0; - teleport->dstAngle[2] = 0; - teleport->sector = sector; - teleport->type = type; - teleport->target = nullptr; - - if (!sector->infLink) - { - sector->infLink = allocator_create(sizeof(InfLink)); - } - - InfLink* link = (InfLink*)allocator_newItem(sector->infLink); - link->type = LTYPE_TELEPORT; - link->entityMask = INF_ENTITY_ANY; - link->eventMask = INF_EVENT_ENTER_SECTOR; - link->teleport = teleport; - link->task = s_infState.teleportTask; - link->parent = sector->infLink; - - return teleport; - } - - void inf_setTeleportTarget(Teleport* teleport, RSector* sector) - { - teleport->target = sector; - } - - void inf_setTeleportDestPosition(Teleport* teleport, fixed16_16 x, fixed16_16 y, fixed16_16 z) - { - teleport->dstPosition.x = x; - teleport->dstPosition.y = y; - teleport->dstPosition.z = z; - } - - void inf_setTeleportDestAngle(Teleport* teleport, angle14_16 pitch, angle14_16 yaw, angle14_16 roll) - { - teleport->dstAngle[0] = pitch; - teleport->dstAngle[1] = yaw; - teleport->dstAngle[2] = roll; - } - - // Return true if "SEQEND" found. - bool parseElevator(TFE_Parser& parser, size_t& bufferPos, const char* itemName) - { - const char* line; - - MessageAddress* msgAddr = message_getAddress(itemName); - // This means the level is most likely broken. But better to write an error and return than crash. - if (!msgAddr) - { - parser.readLine(bufferPos); - return false; - } - - RSector* sector = msgAddr->sector; - assert(sector); - KEYWORD itemSubclass = getKeywordIndex(s_infArg1); - - InfElevator* elev = nullptr; - InfLink* link = nullptr; - Allocator* linkAlloc = nullptr; - - // Special classes - these map to the 11 core elevator types but have special defaults and/or automatically setup stops. - if (itemSubclass <= KW_MORPH_MOVE2) - { - InfSpecialElevator type; - switch (itemSubclass) - { - case KW_BASIC: - type = IELEV_SP_BASIC; - break; - case KW_BASIC_AUTO: - type = IELEV_SP_BASIC_AUTO; - break; - case KW_ENCLOSED: - // Unused. - return false; - break; - case KW_INV: - type = IELEV_SP_INV; - break; - case KW_MID: - type = IELEV_SP_MID; - break; - case KW_DOOR: - type = IELEV_SP_DOOR; - break; - case KW_DOOR_INV: - type = IELEV_SP_DOOR_INV; - break; - case KW_DOOR_MID: - type = IELEV_SP_DOOR_MID; - break; - case KW_MORPH_SPIN1: - type = IELEV_SP_MORPH_SPIN1; - break; - case KW_MORPH_SPIN2: - type = IELEV_SP_MORPH_SPIN2; - break; - case KW_MORPH_MOVE1: - type = IELEV_SP_MORPH_MOVE1; - break; - case KW_MORPH_MOVE2: - type = IELEV_SP_MORPH_MOVE2; - break; - default: - // Invalid type. - return false; - }; - // index is mapped to a type internally. - elev = inf_allocateSpecialElevator(sector, type); - - linkAlloc = sector->infLink; - link = (InfLink*)allocator_getTail(linkAlloc); - elev = link->elev; - } - // One of the core 11 types. - else - { - InfElevatorType type; - switch (itemSubclass) - { - case KW_MOVE_CEILING: - type = IELEV_MOVE_CEILING; - break; - case KW_MOVE_FLOOR: - type = IELEV_MOVE_FLOOR; - break; - case KW_MOVE_FC: - type = IELEV_MOVE_FC; - break; - case KW_MOVE_OFFSET: - type = IELEV_MOVE_OFFSET; - break; - case KW_MOVE_WALL: - type = IELEV_MOVE_WALL; - break; - case KW_ROTATE_WALL: - type = IELEV_ROTATE_WALL; - break; - case KW_SCROLL_WALL: - type = IELEV_SCROLL_WALL; - break; - case KW_SCROLL_FLOOR: - type = IELEV_SCROLL_FLOOR; - break; - case KW_SCROLL_CEILING: - type = IELEV_SCROLL_CEILING; - break; - case KW_CHANGE_LIGHT: - type = IELEV_CHANGE_LIGHT; - break; - case KW_CHANGE_WALL_LIGHT: - type = IELEV_CHANGE_WALL_LIGHT; - break; - default: - // Invalid type. - return false; - } - - elev = inf_allocateElevItem(sector, type); - link = inf_addElevatorToSector(elev, sector); - linkAlloc = sector->infLink; - } - - s32 initStopIndex = 0; - bool seqEnd = false; - while (!seqEnd) - { - line = parser.readLine(bufferPos); - if (!line) { break; } - // There is another class in this sequence, so finish the current class by setting up the initial stop. - if (strstr(line, "CLASS")) - { - inf_gotoInitialStop(elev, initStopIndex); - break; - } - - char id[256]; - s32 argCount = sscanf(line, " %s %s %s %s %s %s %s", id, s_infArg0, s_infArg1, s_infArg2, s_infArg3, s_infArg4, s_infArgExtra); - KEYWORD action = getKeywordIndex(id); - if (action == KW_UNKNOWN) - { - TFE_System::logWrite(LOG_WARNING, "INF", "Unknown elevator command - '%s'.", id); - } - seqEnd = inf_parseElevatorCommand(argCount, action, linkAlloc, seqEnd, elev, initStopIndex, link); - } // while (!seqEnd) - - return seqEnd; - } - - // Return true if "SEQEND" found. - bool parseSectorTrigger(TFE_Parser& parser, size_t& bufferPos, s32 argCount, const char* itemName) - { - MessageAddress* msgAddr = message_getAddress(itemName); - if (!msgAddr) - { - parser.readLine(bufferPos); - return false; - } - RSector* sector = msgAddr->sector; - - // The original code is a bit strange here. - // Since this is a sector trigger, all of the different types behave exactly the same, though there are multiple - // conditionals to get to that result. - // This code simplifies this. - InfTriggerObject obj; obj.sector = sector; - InfTrigger* trigger = sector ? inf_createTrigger(ITRIGGER_SECTOR, obj) : nullptr; - - // Loop through trigger parameters. - const char* line; - bool seqEnd = false; - while (!seqEnd) - { - line = parser.readLine(bufferPos); - // There is another class in this sequence, so we are done with the trigger. - if (!line || strstr(line, "CLASS")) - { - break; - } - - char id[256]; - argCount = sscanf(line, " %s %s %s %s %s", id, s_infArg0, s_infArg1, s_infArg2, s_infArg3); - KEYWORD itemId = getKeywordIndex(id); - assert(itemId != KW_UNKNOWN); - - // Continue reading, but the information cannot be filled in properly. - if (!sector) - { - assert(0); - if (itemId == KW_SEQEND) - { - seqEnd = true; - break; - } - continue; - } - - switch (itemId) - { - case KW_CLIENT: - { - RWall* targetWall; - RSector* targetSector; - inf_getMessageTarget(s_infArg0, &targetSector, &targetWall); - TriggerTarget* target = inf_addTriggerTarget(trigger, targetSector, targetWall, INF_EVENT_ANY); - if (argCount > 2) - { - target->eventMask = strToUInt(s_infArg1); - } - } break; - case KW_MASTER: - { - trigger->master = JFALSE; - } break; - case KW_TEXT: - { - if (s_infArg0[0] >= '0' && s_infArg0[0] <= '9') - { - trigger->textId = strToUInt(s_infArg0); - } - } break; - case KW_MESSAGE: - { - inf_parseMessage(&trigger->cmd, &trigger->arg0, &trigger->arg1, nullptr, s_infArg0, s_infArg1, s_infArg2); - } break; - case KW_EVENT_MASK: - { - if (s_infArg0[0] == '*') - { - trigger->link->eventMask = INF_EVENT_ANY; - } - else - { - trigger->link->eventMask = strToUInt(s_infArg0); - } - } break; - case KW_ENTITY_MASK: - case KW_OBJECT_MASK: - { - if (s_infArg0[0] == '*') - { - trigger->link->entityMask = INF_ENTITY_ANY; - } - else - { - trigger->link->entityMask = strToUInt(s_infArg0); - } - } break; - case KW_EVENT: - { - trigger->event = strToUInt(s_infArg0); - } break; - case KW_SEQEND: - { - // The sequence for this item has completed (no more classes). - seqEnd = true; - } break; - } - } - - return seqEnd; - } - - // Return true if "SEQEND" found. - bool parseTeleport(TFE_Parser& parser, size_t& bufferPos, const char* itemName) - { - MessageAddress* msgAddr = message_getAddress(itemName); - if (!msgAddr) - { - parser.readLine(bufferPos); - return false; - } - - RSector* sector = msgAddr->sector; - - KEYWORD type = getKeywordIndex(s_infArg1); - Teleport* teleport = nullptr; - if (type == KW_BASIC) - { - teleport = inf_createTeleport(TELEPORT_BASIC, sector); - } - else if (type == KW_CHUTE) - { - teleport = inf_createTeleport(TELEPORT_CHUTE, sector); - } - - // Loop through trigger parameters. - const char* line; - bool seqEnd = false; - while (!seqEnd) - { - line = parser.readLine(bufferPos); - // There is another class in this sequence, so we are done with the trigger. - if (!line || strstr(line, "CLASS")) - { - break; - } - - char name[256]; - sscanf(line, " %s %s %s %s %s", name, s_infArg0, s_infArg1, s_infArg2, s_infArg3); - KEYWORD kw = getKeywordIndex(name); - - if (kw == KW_TARGET) - { - msgAddr = message_getAddress(s_infArg0); - inf_setTeleportTarget(teleport, msgAddr->sector); - } - else if (kw == KW_MOVE) - { - char* endPtr; - fixed16_16 dstPosX = floatToFixed16(strtof(s_infArg0, &endPtr)); - fixed16_16 dstPosY = floatToFixed16(strtof(s_infArg1, &endPtr)); - fixed16_16 dstPosZ = floatToFixed16(strtof(s_infArg2, &endPtr)); - angle14_16 yaw = floatToAngle(strtof(s_infArg3, &endPtr)); - - inf_setTeleportDestPosition(teleport, dstPosX, dstPosY, dstPosZ); - inf_setTeleportDestAngle(teleport, 0, yaw, 0); - } - else if (kw == KW_SEQEND) - { - seqEnd = true; - break; - } - } - - return seqEnd; - } - - // Return true if "SEQEND" found. - bool parseLineTrigger(TFE_Parser& parser, size_t& bufferPos, s32 argCount, const char* name, s32 num) - { - KEYWORD typeId = getKeywordIndex(s_infArg0); - assert(typeId != KW_UNKNOWN); - - MessageAddress* msgAddr = message_getAddress(name); - if (!msgAddr) - { - parser.readLine(bufferPos); - return false; - } - - RSector* sector = msgAddr->sector; - RWall* wall = §or->walls[num]; - - InfTriggerObject obj; - InfTrigger* trigger = nullptr; - if (argCount > 2) - { - KEYWORD subTypeId = getKeywordIndex(s_infArg1); - switch (subTypeId) - { - case KW_SWITCH1: - { - obj.wall = wall; - trigger = inf_createTrigger(ITRIGGER_SWITCH1, obj); - } break; - case KW_TOGGLE: - { - obj.wall = wall; - trigger = inf_createTrigger(ITRIGGER_TOGGLE, obj); - } break; - case KW_SINGLE: - { - obj.wall = wall; - trigger = inf_createTrigger(ITRIGGER_SINGLE, obj); - } break; - case KW_STANDARD: - { - obj.wall = wall; - trigger = inf_createTrigger(ITRIGGER_WALL, obj); - } break; - default: - { - obj.wall = wall; - trigger = inf_createTrigger(ITRIGGER_WALL, obj); - } - } - } - else - { - obj.wall = wall; - trigger = inf_createTrigger(ITRIGGER_WALL, obj); - } - - // Trigger parameters - const char* line; - bool seqEnd = false; - while (!seqEnd) - { - line = parser.readLine(bufferPos); - if (!line || strstr(line, "CLASS")) - { - break; - } - - char id[256]; - argCount = sscanf(line, " %s %s %s %s %s", id, s_infArg0, s_infArg1, s_infArg2, s_infArg3); - KEYWORD itemId = getKeywordIndex(id); - if (itemId == KW_UNKNOWN) - { - TFE_System::logWrite(LOG_WARNING, "INF", "Unknown trigger parameter - '%s'.", id); - } - - switch (itemId) - { - case KW_SEQEND: - { - seqEnd = true; - } break; - case KW_CLIENT: - { - RWall* targetWall; - RSector* targetSector; - inf_getMessageTarget(s_infArg0, &targetSector, &targetWall); - - TriggerTarget* target = inf_addTriggerTarget(trigger, targetSector, targetWall, INF_EVENT_ANY); - if (argCount > 2) - { - target->eventMask = strToUInt(s_infArg1); - } - } break; - case KW_EVENT_MASK: - { - if (s_infArg0[0] == '*') - { - trigger->link->eventMask = INF_EVENT_ANY; - } - else - { - trigger->link->eventMask = strToUInt(s_infArg0); - } - } break; - case KW_MASTER: - { - trigger->master = JFALSE; - } break; - case KW_TEXT: - { - if (s_infArg0[0] >= '0' && s_infArg0[0] <= '9') - { - trigger->textId = strToUInt(s_infArg0); - } - } break; - case KW_ENTITY_MASK: - case KW_OBJECT_MASK: - { - if (s_infArg0[0] == '*') - { - trigger->link->entityMask = INF_ENTITY_ANY; - } - else - { - trigger->link->entityMask = strToUInt(s_infArg0); - } - } break; - case KW_EVENT: - { - trigger->event = strToUInt(s_infArg0); - } break; - case KW_SOUND_COLON: - { - SoundSourceId soundSourceId = NULL_SOUND; - // Not ascii - if (s_infArg0[0] < '0' || s_infArg0[0] > '9') - { - soundSourceId = sound_load(s_infArg0, SOUND_PRIORITY_LOW3); - } - trigger->soundId = soundSourceId; - } break; - case KW_MESSAGE: - { - inf_parseMessage(&trigger->cmd, &trigger->arg0, &trigger->arg1, nullptr, s_infArg0, s_infArg1, s_infArg2); - } break; - } // switch (itemId) - } // while (!seqEnd) - - return seqEnd; - } - - // For now load the INF data directly. - // Move back to asset later. - JBool inf_load(const char* levelName) - { - char levelPath[TFE_MAX_PATH]; - strcpy(levelPath, levelName); - strcat(levelPath, ".INF"); - - FilePath filePath; - if (!TFE_Paths::getFilePath(levelPath, &filePath)) - { - TFE_System::logWrite(LOG_ERROR, "level_loadINF", "Cannot find level INF '%s'.", levelPath); - return JFALSE; - } - FileStream file; - if (!file.open(&filePath, Stream::MODE_READ)) - { - TFE_System::logWrite(LOG_ERROR, "level_loadINF", "Cannot open level INF '%s'.", levelPath); - return JFALSE; - } - TFE_Parser parser; - size_t bufferPos = 0; -#ifdef TFE_ESPBOX - // Parse through a small window of the (still open) file instead of reading - // the whole file into memory. - if (!parser.initFromFile(&file)) { return JFALSE; } -#else - size_t len = file.getSize(); - s_buffer.resize(len); - file.readBuffer(s_buffer.data(), u32(len)); - file.close(); - parser.init(s_buffer.data(), s_buffer.size()); -#endif - parser.enableBlockComments(); - parser.addCommentString("//"); - parser.convertToUpperCase(true); - - const char* line; - line = parser.readLine(bufferPos); - - // Keep looping until the version is found. - while (strncasecmp(line, "INF", 3) != 0 && line) - { - line = parser.readLine(bufferPos); - } - if (!line) - { - TFE_System::logWrite(LOG_ERROR, "level_loadINF", "Cannot find INF version."); - return JFALSE; - } - - f32 version; - if (sscanf(line, "INF %f", &version) != 1) - { - TFE_System::logWrite(LOG_ERROR, "level_loadINF", "Cannot read INF version."); - return JFALSE; - } - if (version != 1.0f) - { - TFE_System::logWrite(LOG_ERROR, "level_loadINF", "Incorrect INF version %f, should be 1.0.", version); - return JFALSE; - } - - // Keep looping until ITEMS is found. - s32 itemCount = 0; - while (1) - { - line = parser.readLine(bufferPos); - if (!line) - { - TFE_System::logWrite(LOG_ERROR, "level_loadINF", "Cannot find ITEMS in INF: '%s'.", levelName); - return JFALSE; - } - - if (sscanf(line, "ITEMS %d", &itemCount) == 1) - { - break; - } - } - - // Verify that we are under or are ignoring the limit. - if (!TFE_Settings::getGameSettings()->df_ignoreInfLimit) - { - if (itemCount > MAX_INF_ITEMS) - { - TFE_System::logWrite(LOG_WARNING, "level_loadINF", "Too many INF items - skipping extra items."); - itemCount = MAX_INF_ITEMS; - } - } - - // Then loop through all of the items and parse their classes. - s32 wallNum = 0; - for (s32 i = 0; i < itemCount; i++) - { - line = parser.readLine(bufferPos); - if (!line) - { - TFE_System::logWrite(LOG_WARNING, "level_loadINF", "Hit the end of INF '%s' before parsing all items: %d/%d", levelName, i, itemCount); - return JTRUE; - } - - char item[256], name[256]; - while (sscanf(line, " ITEM: %s NAME: %s NUM: %d", item, name, &wallNum) < 1) - { - line = parser.readLine(bufferPos); - if (!line) - { - TFE_System::logWrite(LOG_WARNING, "level_loadINF", "Hit the end of INF '%s' before parsing all items: %d/%d", levelName, i, itemCount); - return JTRUE; - } - continue; - } - - KEYWORD itemType = getKeywordIndex(item); - switch (itemType) - { - case KW_LEVEL: - { - line = parser.readLine(bufferPos); - if (line && strstr(line, "SEQ")) - { - while (line = parser.readLine(bufferPos)) - { - char itemName[256]; - s32 argCount = sscanf(line, " %s %s %s %s %s %s %s", itemName, s_infArg0, s_infArg1, s_infArg2, s_infArg3, s_infArgExtra, s_infArgExtra); - KEYWORD levelItem = getKeywordIndex(itemName); - switch (levelItem) - { - case KW_SEQEND: - break; - case KW_AMB_SOUND: - { - level_addSound(s_infArg0, u32(atof(s_infArg1) * 145.65f), atoi(s_infArg2)); - continue; - } - } - break; - } - } - } break; - case KW_SECTOR: - { - line = parser.readLine(bufferPos); - if (!line || !strstr(line, "SEQ")) - { - continue; - } - - line = parser.readLine(bufferPos); - // Loop until seqend since an INF item may have multiple classes. - while (1) - { - if (!line || !strstr(line, "CLASS")) - { - break; - } - - char id[256]; - s32 argCount = sscanf(line, " %s %s %s %s %s %s %s", id, s_infArg0, s_infArg1, s_infArg2, s_infArg3, s_infArg4, s_infArgExtra); - KEYWORD itemClass = getKeywordIndex(s_infArg0); - assert(itemClass != KW_UNKNOWN); - - if (itemClass == KW_ELEVATOR) - { - if (parseElevator(parser, bufferPos, name)) - { - break; - } - } - else if (itemClass == KW_TRIGGER) - { - if (parseSectorTrigger(parser, bufferPos, argCount, name)) - { - break; - } - } - else if (itemClass == KW_TELEPORTER) - { - if (parseTeleport(parser, bufferPos, name)) - { - break; - } - } - else - { - // Invalid item class. - line = parser.readLine(bufferPos); - } - } - } break; - case KW_LINE: - { - line = parser.readLine(bufferPos); - if (!line || !strstr(line, "SEQ")) - { - continue; - } - - line = parser.readLine(bufferPos); - // Loop until seqend since an INF item may have multiple classes. - while (1) - { - if (!line || !strstr(line, "CLASS")) - { - break; - } - - char id[256]; - s32 argCount = sscanf(line, " %s %s %s %s %s", id, s_infArg0, s_infArg1, s_infArg2, s_infArg3); - if (parseLineTrigger(parser, bufferPos, argCount, name, wallNum)) - { - break; - } - } // while (!seqEnd) - outer (Line Classes). - } break; - } - } // for (s32 i = 0; i < itemCount; i++) - - return JTRUE; - } - - // Sounds - void inf_loadSounds() - { - // Default sounds. - s_moveCeilSound0 = sound_load("door2-1.voc", SOUND_PRIORITY_LOW3); - s_moveCeilSound1 = sound_load("door2-2.voc", SOUND_PRIORITY_LOW3); - s_moveCeilSound2 = sound_load("door2-3.voc", SOUND_PRIORITY_LOW3); - s_moveFloorSound0 = sound_load("elev2-1.voc", SOUND_PRIORITY_LOW3); - s_moveFloorSound1 = sound_load("elev2-2.voc", SOUND_PRIORITY_LOW3); - s_moveFloorSound2 = sound_load("elev2-3.voc", SOUND_PRIORITY_LOW3); - s_doorSound = sound_load("door.voc", SOUND_PRIORITY_LOW3); - s_needKeySoundId = sound_load("locked-1.voc", SOUND_PRIORITY_LOW3); - s_switchDefaultSndId = sound_load("switch3.voc", SOUND_PRIORITY_HIGH1); - // Precache common sounds - sound_load("door1-1.voc", SOUND_PRIORITY_LOW3); - sound_load("door1-2.voc", SOUND_PRIORITY_LOW3); - sound_load("door1-3.voc", SOUND_PRIORITY_LOW3); - sound_load("elev1-1.voc", SOUND_PRIORITY_LOW3); - sound_load("elev1-2.voc", SOUND_PRIORITY_LOW3); - sound_load("elev1-3.voc", SOUND_PRIORITY_LOW3); - sound_load("elev3-1.voc", SOUND_PRIORITY_LOW3); - sound_load("elev3-2.voc", SOUND_PRIORITY_LOW3); - sound_load("elev3-3.voc", SOUND_PRIORITY_LOW3); - } - - void inf_elevatorTaskLocal(MessageType msg) - { - infElevatorMsgFunc(msg); - } - - void inf_startElevator(InfElevator* elev) - { - if (!(elev->updateFlags & ELEV_MOVING)) - { - // Figure out the source position for the sound effect. - vec3_fixed sndPos = inf_getElevSoundPos(elev); - - // Play the startup sound effect if the elevator is not already at the next stop. - Stop* nextStop = elev->nextStop; - // Play the initial sound as the elevator starts moving. - if (nextStop && *elev->value != nextStop->value) - { - sound_playCued(elev->sound0, sndPos); - } - - // Update the next time, so this will move on the next update. - elev->nextTick = s_curTick; - - // Flag the elevator as moving. - elev->updateFlags |= ELEV_MOVING; - } - } - - void inf_elevatorVolume(InfElevator* elev) - { - if (elev->updateFlags & ELEV_MOVING) - { - // Figure out the source position for the sound effect. - vec3_fixed sndPos = inf_getElevSoundPos(elev); - - // Start up the sound effect, track it since it is looping. - elev->loopingSoundID = sound_maintain(elev->loopingSoundID, elev->sound1, sndPos); - } - } - - // Per frame update. - void inf_elevatorTaskFunc(MessageType msg) - { - struct LocalContext - { - InfElevator* elev; - Stop* nextStop; - s32 elevDeleted; - - }; - task_begin_ctx; - - while (msg != MSG_FREE_TASK) - { - if (msg != MSG_RUN_TASK) // General elevator message, just pass it along. - { - infElevatorMsgFunc(msg); - } - else // id == MSG_RUN_TASK - { - taskCtx->elev = (InfElevator*)allocator_getHead(s_infSerState.infElevators); - while (taskCtx->elev) - { - if (taskCtx->elev->deleted) - { - taskCtx->elev = (InfElevator*)allocator_getNext(s_infSerState.infElevators); - continue; - } - - taskCtx->elevDeleted = 0; - if ((taskCtx->elev->updateFlags & ELEV_MASTER_ON) && taskCtx->elev->nextTick < s_curTick) - { - // If not already moving, get started. - if (!(taskCtx->elev->updateFlags & ELEV_MOVING) && !taskCtx->elevDeleted) - { - inf_startElevator(taskCtx->elev); - } - inf_elevatorVolume(taskCtx->elev); - - if (updateElevator(taskCtx->elev)) - { - // The elevator has reached the next stop. - elevHandleStopDelay(taskCtx->elev); - - taskCtx->nextStop = taskCtx->elev->nextStop; - if (taskCtx->elev->updateFlags & ELEV_CRUSH) - { - taskCtx->elev->nextTick = s_curTick + TICKS_PER_SECOND; // this will pause the elevator for one second. - taskCtx->elev->updateFlags &= ~ELEV_CRUSH; // remove the crush flag. - } - else - { - u32 delay = taskCtx->nextStop->delay; - if (delay == IDELAY_HOLD) - { - taskCtx->elev->nextTick = DELAY_SLEEP; - } - else if (delay == IDELAY_COMPLETE || delay == IDELAY_TERMINATE) - { - // delete the elevator, we're done here. - inf_deleteElevator(taskCtx->elev); - taskCtx->elevDeleted = 1; - if (delay == IDELAY_COMPLETE) - { - agent_levelComplete(); - agent_createLevelEndTask(); - } - } - else // Timed - { - taskCtx->elev->nextTick = s_curTick + taskCtx->nextStop->delay; - } - } - - // Process stop messages if the elevator has not been deleted. - if (!taskCtx->elevDeleted) - { - // Messages - s_infState.nextStop = taskCtx->nextStop; - task_callTaskFunc(inf_stopHandleMessages); - - task_localBlockBegin; - // Adjoin Commands. - inf_stopAdjoinCommands(taskCtx->nextStop); - - // Floor texture change. - TextureData** floorTex = taskCtx->nextStop->floorTex; - if (floorTex) - { - RSector* sector = taskCtx->elev->sector; - sector->floorTex = floorTex; - } - - // Ceiling texture change. - TextureData** ceilTex = taskCtx->nextStop->ceilTex; - if (ceilTex) - { - RSector* sector = taskCtx->elev->sector; - sector->ceilTex = ceilTex; - } - - // Page (special 2D sound effect that plays, such as voice overs). - SoundSourceId pageId = taskCtx->nextStop->pageId; - if (pageId) - { - sound_play(pageId); - } - - // Advance to the next stop. - taskCtx->elev->nextStop = inf_advanceStops(taskCtx->elev->stops, 0, 1); - task_localBlockEnd; - } // (!elevDeleted) - } - } // ((elev->updateFlags & ELEV_MASTER_ON) && elev->nextTick < s_curTick) - - // Next elevator. - taskCtx->elev = (InfElevator*)allocator_getNext(s_infSerState.infElevators); - } // while (elev) - } // id == 0 (main elevator update loop) - task_yield(TASK_NO_DELAY); - } // while (id != -1) - - task_end; - } - - void inf_teleporterTaskLocal(MessageType msg) - { - if (msg == MSG_TRIGGER && s_msgEvent == INF_EVENT_ENTER_SECTOR) - { - task_makeActive(s_infState.teleportTask); - } - else - { - // TODO(Core Game Loop Release) - } - } - - void inf_telelporterTaskFunc(MessageType msg) - { - struct LocalContext - { - Tick delay; - }; - task_begin_ctx; - - while (msg != MSG_FREE_TASK) - { - taskCtx->delay = TASK_SLEEP; - - if (msg != MSG_RUN_TASK) - { - inf_teleporterTaskLocal(msg); - taskCtx->delay = TASK_NO_DELAY; - } - else - { - Teleport* teleport = (Teleport*)allocator_getHead(s_infSerState.infTeleports); - while (teleport) - { - RSector* sector = teleport->sector; - s32 objCount = sector->objectCount; - SecObject** objList = sector->objectList; - - for (s32 i = 0; i < objCount; objList++) - { - SecObject* obj = *objList; - if (obj) - { - i++; - taskCtx->delay = TASK_NO_DELAY; - TeleportType type = teleport->type; - if (type <= TELEPORT_BASIC) - { - // So dstPosition is actually an absolute position. - obj->posWS = teleport->dstPosition; - obj->pitch = teleport->dstAngle[0]; - obj->yaw = teleport->dstAngle[1]; - obj->roll = teleport->dstAngle[2]; - sector_addObject(teleport->target, obj); - } - else if (type == TELEPORT_CHUTE) - { - sector = teleport->sector; - fixed16_16 floorThreshold = sector->floorHeight - HALF_16; - // if the object is lower than 0.5 units above the floor. - if (floorThreshold < obj->posWS.y) - { - sector_addObject(teleport->target, obj); - } - } - - if (obj->entityFlags & ETFLAG_PLAYER) - { - // automap_setLayer(obj->sector->layer); - } - } // if (obj) - } // for (s32 i = 0; i < objCount; objList++) - teleport = (Teleport*)allocator_getNext(s_infSerState.infTeleports); - } // while (teleport) - } - - task_yield(taskCtx->delay); - } // while (id != -1) - task_end; - } - - void inf_triggerTaskLocal(MessageType msg) - { - InfTrigger* trigger = (InfTrigger*)s_msgTarget; - if (trigger->deleted) { return; } - - switch (msg) - { - case MSG_FREE: - { - inf_deleteTrigger(trigger); - } break; - case MSG_TRIGGER: - { - inf_handleTriggerMsg(trigger); - } break; - case MSG_MASTER_OFF: - { - trigger->master = JFALSE; - } break; - case MSG_MASTER_ON: - { - trigger->master = JTRUE; - } break; - case MSG_DONE: - { - if (trigger->type == ITRIGGER_SWITCH1) - { - AnimatedTexture* animTex = trigger->animTex; - // If the trigger is still in its original state, nothing to do. - if (animTex) - { - trigger->state = 0; - trigger->tex = animTex->frameList[0]; - } - trigger->master = JTRUE; - } - } break; - } - } - - void inf_triggerTaskFunc(MessageType msg) - { - task_begin; - // Wait until explicitly called. - task_yield(TASK_SLEEP); - - while (msg != MSG_FREE_TASK) - { - inf_triggerTaskLocal(msg); - task_yield(TASK_SLEEP); - } - - task_end; - } - - // Send messages so that entities and the player can interact with the INF system. - // If msgType = MSG_SET/CLEAR_BITS the msg is processed directly for this wall OR - // this iterates through the valid links and calls their msgFunc. - void inf_wallSendMessage(RWall* wall, SecObject* entity, u32 evt, MessageType msgType) - { - if (msgType == MSG_SET_BITS) - { - inf_setWallBits(wall); - } - else if (msgType == MSG_CLEAR_BITS) - { - inf_clearWallBits(wall); - } - else - { - inf_sendLinkMessages(wall->infLink, entity, evt, msgType); - } - } - - // Sends a message to a wall at a specific position (parametric along wall + height). - // This is used so that switches are only activated if directly hit. - void inf_wallSendMessageAtPos(RWall* hitWall, SecObject* obj, u32 evt, fixed16_16 paramPos, fixed16_16 yPos) - { - if (hitWall->signTex && *hitWall->signTex) - { - fixed16_16 baseHeight = 0; - fixed16_16 uOffset = 0; - switch (hitWall->drawFlags) - { - case WDF_MIDDLE: - { - baseHeight = hitWall->sector->floorHeight; - uOffset = hitWall->midOffset.x; - } break; - case WDF_TOP: - { - baseHeight = hitWall->nextSector->ceilingHeight; - uOffset = hitWall->topOffset.x; - } break; - case WDF_BOT: - case WDF_TOP_AND_BOT: - { - baseHeight = hitWall->sector->floorHeight; - uOffset = hitWall->botOffset.x; - } break; - } - - if (yPos) - { - fixed16_16 base = baseHeight + (hitWall->signOffset.z >> 3); - // base + 0.5 - fixed16_16 y0 = base + HALF_16; - // base - texHeight/8 - 0.5 - fixed16_16 y1 = base - ((*hitWall->signTex)->height << 13) - HALF_16; - if (y0 < yPos || y1 > yPos) - { - return; - } - } - - if (paramPos) - { - fixed16_16 base = (hitWall->signOffset.x - uOffset) >> 3; - // base - 0.5 - fixed16_16 left = base - HALF_16; - // base + texWidth/8 + 0.5 - fixed16_16 right = base + ((*hitWall->signTex)->width << 13) + HALF_16; - if (paramPos < left || paramPos > right) - { - return; - } - } - } - - inf_wallSendMessage(hitWall, obj, evt, MSG_TRIGGER); - } - - void inf_wallAndMirrorSendMessageAtPos(RWall* hitWall, SecObject* obj, u32 evt, fixed16_16 paramPos, fixed16_16 yPos) - { - inf_wallSendMessageAtPos(hitWall, obj, evt, paramPos, yPos); - if (hitWall->mirrorWall) - { - // evt*2 is the next event. This is obviously incorrect for shooting the wall, but the land event shouldn't be used for a line - // so it doesn't seem to be an issue... - inf_wallSendMessageAtPos(hitWall->mirrorWall, obj, evt * 2, paramPos, yPos); // eax, edx, ebx, ecx, stack. - } - } - - void inf_triggerWallEvent(RWall* wall, SecObject* obj, u32 event) - { - inf_wallSendMessage(wall, obj, event, MSG_TRIGGER); - - RWall* mirror = wall->mirrorWall; - if (mirror) - { - // Opposite event. - u32 backsideEvent = event * 2; - inf_wallSendMessage(mirror, obj, backsideEvent, MSG_TRIGGER); - } - } - - ///////////////////////////////////////////////////// - // Internal - ///////////////////////////////////////////////////// - void inf_parseMessage(MessageType* type, u32* arg1, u32* arg2, u32* evt, const char* infArg0, const char* infArg1, const char* infArg2, bool elevator) - { - const KEYWORD msgId = getKeywordIndex(infArg0); - - switch (msgId) - { - case KW_NEXT_STOP: - *type = MSG_NEXT_STOP; - break; - case KW_PREV_STOP: - *type = MSG_PREV_STOP; - break; - case KW_GOTO_STOP: - *type = MSG_GOTO_STOP; - *arg1 = strToUInt(infArg1); - if (evt) { *evt = INF_EVENT_NONE; } - break; - case KW_MASTER_ON: - *type = MSG_MASTER_ON; - break; - case KW_MASTER_OFF: - *type = MSG_MASTER_OFF; - break; - case KW_SET_BITS: - *type = MSG_SET_BITS; - *arg1 = strToUInt(infArg1); - *arg2 = strToUInt(infArg2); - if (evt) { *evt = INF_EVENT_NONE; } - break; - case KW_CLEAR_BITS: - *type = MSG_CLEAR_BITS; - *arg1 = strToUInt(infArg1); - *arg2 = strToUInt(infArg2); - if (evt) { *evt = INF_EVENT_NONE; } - break; - case KW_COMPLETE: - *type = MSG_COMPLETE; - *arg1 = strToUInt(infArg1); - if (evt) { *evt = INF_EVENT_NONE; } - break; - case KW_LIGHTS: - *type = MSG_LIGHTS; - break; - case KW_M_TRIGGER: - default: - if (elevator) - { - // Elevators can use a few additional message types, but these are treated as M_TRIGGER for either trigger type. - switch (msgId) - { - case KW_DONE: - *type = MSG_DONE; - break; - case KW_WAKEUP: - *type = MSG_WAKEUP; - break; - default: - *type = MSG_TRIGGER; - } - } - else // Trigger - { - *type = MSG_TRIGGER; - } - } - } - - bool inf_parseElevatorCommand(s32 argCount, KEYWORD action, Allocator* linkAlloc, bool seqEnd, InfElevator*& elev, s32& initStopIndex, InfLink*& link) - { - char* endPtr; - MessageAddress* msgAddr; - - switch (action) - { - case KW_START: - { - initStopIndex = strToInt(s_infArg0); - } break; - case KW_STOP: - { - fixed16_16 stopValue; - // Calculate the stop value. - if (s_infArg0[0] == '@') // Relative Value - { - f32 value = strtof(&s_infArg0[1], &endPtr); - stopValue = floatToFixed16(value); - - if (elev->type == IELEV_MOVE_CEILING || elev->type == IELEV_MOVE_FLOOR || elev->type == IELEV_MOVE_FC) - { - RSector* sector = elev->sector; - stopValue = sector->floorHeight - stopValue; - } - else if (elev->type == IELEV_ROTATE_WALL) - { - // This is a bug (in the original code): - // This will always evaluate to 0 because strtof('@') = 0 - value = strtof(s_infArg0, &endPtr); - stopValue = floatToAngle(value); - stopValue = floatToFixed16(f32(stopValue)); - } - } - else if ((s_infArg0[0] >= '0' && s_infArg0[0] <= '9') || s_infArg0[0] == '-' || s_infArg0[0] == '.') // Numeric Value - { - f32 value = strtof(s_infArg0, &endPtr); - stopValue = floatToFixed16(value); - - if (elev->type == IELEV_MOVE_CEILING || elev->type == IELEV_MOVE_FLOOR || elev->type == IELEV_MOVE_FC) - { - // Elevators that move the floor and/or ceiling need to be converted from +Y up to -Y up. - stopValue = -stopValue; - } - else if (elev->type == IELEV_ROTATE_WALL) - { - // Rotation stop values need to be converted to angles. - value = strtof(s_infArg0, &endPtr); - stopValue = floatToAngle(value); - stopValue = floatToFixed16(f32(stopValue)); - } - } - else // Value from named sector. - { - msgAddr = message_getAddress(s_infArg0); - RSector* sector = msgAddr->sector; - stopValue = sector->floorHeight; - } - - Stop* stop = inf_addStop(elev, stopValue); - if (argCount < 3) - { - return seqEnd; - } - - // Delay is optional, if not specified each elevator has its own default. - Tick delay; - // Numeric - if ((s_infArg1[0] >= '0' && s_infArg1[0] <= '9') || s_infArg1[0] == '-' || s_infArg1[0] == '.') - { - f32 value = strtof(s_infArg1, &endPtr); - // Convert from seconds to ticks. - delay = Tick(SECONDS_TO_TICKS_ROUNDED * value); - } - else if (strcasecmp(s_infArg1, "HOLD") == 0) - { - delay = IDELAY_HOLD; - } - else if (strcasecmp(s_infArg1, "TERMINATE") == 0) - { - delay = IDELAY_TERMINATE; - } - else if (strcasecmp(s_infArg1, "COMPLETE") == 0) - { - delay = IDELAY_COMPLETE; - } - else - { - delay = s_prevStopDelay; - } - s_prevStopDelay = delay; - - inf_setStopDelay(stop, delay); - } break; - case KW_SPEED: - { - if (elev->type == IELEV_ROTATE_WALL) - { - f32 value = strtof(s_infArg0, &endPtr); - // 360 degrees is split into 16384 angular units. - // Speed is in angular units. - s32 speed = floatToAngle(value); - // Then speed is converted to a fixed point value, essentially 14.16 fixed point. - elev->speed = intToFixed16(speed & 0xffff); - } - else - { - f32 value = strtof(s_infArg0, &endPtr); - elev->speed = floatToFixed16(value); - } - } break; - case KW_MASTER: - { - // KW_MASTER (this seems to always turn master off) - elev->updateFlags &= ~ELEV_MASTER_ON; - } break; - case KW_ANGLE: - { - f32 value = strtof(s_infArg0, &endPtr); - s32 angle = floatToAngle(value); - inf_setDirFromAngle(elev, angle); - } break; - case KW_ADJOIN: - { - s32 stopId = strToInt(s_infArg0); - Stop* stop = inf_getStopByIndex(elev, stopId); - if (stop) - { - if (!stop->adjoinCmds) - { - stop->adjoinCmds = allocator_create(sizeof(AdjoinCmd)); - } - AdjoinCmd* adjoinCmd = (AdjoinCmd*)allocator_newItem(stop->adjoinCmds); - MessageAddress* msgAddr0 = message_getAddress(s_infArg1); - MessageAddress* msgAddr1 = message_getAddress(s_infArg3); - RSector* sector0 = msgAddr0->sector; - RSector* sector1 = msgAddr1->sector; - - s32 wallIndex0 = strToInt(s_infArg2); - s32 wallIndex1 = strToInt(s_infArg4); - - // DT 4 bug with adjoin commands - handle invalid wall indices. - adjoinCmd->wall0 = (sector0 && wallIndex0 >= 0 && wallIndex0 < sector0->wallCount) ? §or0->walls[wallIndex0] : nullptr; - adjoinCmd->wall1 = (sector1 && wallIndex1 >= 0 && wallIndex1 < sector1->wallCount) ? §or1->walls[wallIndex1] : nullptr; - adjoinCmd->sector0 = sector0; - adjoinCmd->sector1 = sector1; - } - } break; - case KW_TEXTURE: - { - s32 stopId = strToInt(s_infArg0); - Stop* stop = inf_getStopByIndex(elev, stopId); - if (stop) - { - msgAddr = message_getAddress(s_infArg2); - RSector* sector = msgAddr->sector; - if (s_infArg1[0] == 'C' || s_infArg1[0] == 'c') - { - stop->ceilTex = sector->ceilTex; - stop->ceilTexSecId = sector->index; - } - else - { - stop->floorTex = sector->floorTex; - stop->floorTexSecId = sector->index; - } - } - } break; - case KW_SLAVE: - { - MessageAddress* msgAddr = message_getAddress(s_infArg0); - s32 slaveValue = 0; - if (argCount > 2) - { - f32 value = strtof(s_infArg1, &endPtr); - slaveValue = floatToAngle(value); - } - inf_addSlave(elev, slaveValue, msgAddr->sector); - } break; - case KW_MESSAGE: - { - s32 stopId = strToInt(s_infArg0); - Stop* stop = inf_getStopByIndex(elev, stopId); - if (stop) - { - if (!stop->messages) - { - stop->messages = allocator_create(sizeof(InfMessage)); - } - - InfMessage* msg = (InfMessage*)allocator_newItem(stop->messages); - RSector* targetSector; - RWall* targetWall; - inf_getMessageTarget(s_infArg1, &targetSector, &targetWall); - msg->sector = targetSector; - msg->wall = targetWall; - - msg->msgType = MSG_TRIGGER; - msg->event = INF_EVENT_NONE; - if (argCount >= 5) - { - msg->event = strToUInt(s_infArg3); - } - - if (argCount > 3) - { - inf_parseMessage(&msg->msgType, &msg->arg1, &msg->arg2, &msg->event, s_infArg2, s_infArg3, s_infArg4, true); - } - } - } break; - case KW_EVENT_MASK: - { - if (s_infArg0[0] == '*') - { - link->eventMask = INF_EVENT_ANY; // everything - } - else - { - link->eventMask = strToUInt(s_infArg0); // specified - } - } break; - case KW_ENTITY_MASK: - case KW_OBJECT_MASK: - { - // Entity_mask and Object_mask are buggy for elevators... - if (s_infArg0[0] == '*') - { - // This looks like a bug, this should be eventMask but is entityMask in the code... - link->entityMask = INF_ENTITY_ANY; - } - else - { - link->eventMask = strToUInt(s_infArg0); - } - } break; - case KW_CENTER: - { - f32 centerX = strtof(s_infArg0, &endPtr); - f32 centerZ = strtof(s_infArg1, &endPtr); - elev->dirOrCenter.x = floatToFixed16(centerX); - elev->dirOrCenter.z = floatToFixed16(centerZ); - } break; - case KW_KEY_COLON: - { - KEYWORD key = getKeywordIndex(s_infArg0); - if (key == KW_RED) - { - elev->key = KEY_RED; - } - else if (key == KW_YELLOW) - { - elev->key = KEY_YELLOW; - } - else if (key == KW_BLUE) - { - elev->key = KEY_BLUE; - } - } break; - // This entry is required for special cases, like IELEV_SP_DOOR_MID, where multiple elevators are created at once. - // This way, we can modify the first created elevator as well as the last. - // It allows allows us to modify previous classes... but this isn't recommended. - case KW_ADDON: - { - s32 index = strToInt(s_infArg0); - link = (InfLink*)allocator_getByIndex(linkAlloc, index); - elev = link->elev; - } break; - case KW_FLAGS: - { - elev->flags = strToUInt(s_infArg0); - } break; - case KW_SOUND_COLON: - { - SoundSourceId soundSourceId = 0; - if (s_infArg1[0] >= '0' && s_infArg1[0] <= '9') - { - // Any numeric value means "no sound." - soundSourceId = NULL_SOUND; - } - else - { - soundSourceId = sound_load(s_infArg1, SOUND_PRIORITY_LOW3); - } - - // Determine which elevator sound to assign soundId to. - s32 soundIdx = strToInt(s_infArg0); - if (soundIdx == 1) - { - elev->sound0 = soundSourceId; - } - else if (soundIdx == 2) - { - elev->sound1 = soundSourceId; - } - else if (soundIdx == 3) - { - elev->sound2 = soundSourceId; - } - } break; - case KW_PAGE: - { - SoundSourceId soundSourceId = sound_load(s_infArg1, SOUND_PRIORITY_HIGH5); - sound_setBaseVolume(soundSourceId, 127); - - s32 index = strToInt(s_infArg0); - Stop* stop = inf_getStopByIndex(elev, index); - if (stop) { stop->pageId = soundSourceId; } - } break; - case KW_SEQEND: - { - // The sequence for this item has completed (no more classes). - // Finish the current class by setting up the initial stop. - inf_gotoInitialStop(elev, initStopIndex); - seqEnd = true; - } break; - } - - return seqEnd; - } - - void inf_setWallBits(RWall* wall) - { - u32 flagsIndex = s_msgArg1; - u32 bits = s_msgArg2; - if (flagsIndex == 1) - { - wall->flags1 |= bits; - - // If there is a mirror, also set some of the bits there. - RWall* mirror = wall->mirrorWall; - if (mirror) - { - const u32 allowedMirrorFlags = (WF1_HIDE_ON_MAP | WF1_SHOW_NORMAL_ON_MAP | WF1_DAMAGE_WALL | WF1_SHOW_AS_LEDGE_ON_MAP | WF1_SHOW_AS_DOOR_ON_MAP); - mirror->flags1 |= (bits & allowedMirrorFlags); - } - } - else if (flagsIndex == 2) - { - wall->flags2 |= bits; - } - // It looks like if mirror is set for flags2, it also sets them for 3... - else if (flagsIndex == 3) - { - wall->flags3 |= bits; - - // If there is a mirror, also set some of the bits there. - RWall* mirror = wall->mirrorWall; - if (mirror) - { - const u32 allowedMirrorFlags = (WF3_ALWAYS_WALK | WF3_CANNOT_FIRE_THROUGH | WF3_PLAYER_WALK_ONLY | WF3_SOLID_WALL); - mirror->flags3 |= (bits & allowedMirrorFlags); - } - } - } - - void inf_clearWallBits(RWall* wall) - { - u32 flagsIndex = s_msgArg1; - u32 bits = s_msgArg2; - if (flagsIndex == 1) - { - wall->flags1 &= ~bits; - - // If there is a mirror, also clear some of the bits there. - RWall* mirror = wall->mirrorWall; - if (mirror) - { - const u32 allowedMirrorFlags = WF1_HIDE_ON_MAP | WF1_SHOW_NORMAL_ON_MAP | WF1_DAMAGE_WALL | WF1_SHOW_AS_LEDGE_ON_MAP | WF1_SHOW_AS_DOOR_ON_MAP; - mirror->flags1 &= ~(bits & allowedMirrorFlags); - } - } - else if (flagsIndex == 2) - { - wall->flags2 &= ~bits; - } - else if (flagsIndex == 3) - { - wall->flags3 &= ~bits; - - // If there is a mirror, also set some of the bits there. - RWall* mirror = wall->mirrorWall; - if (mirror) - { - const u32 allowedMirrorFlags = (WF3_ALWAYS_WALK | WF3_CANNOT_FIRE_THROUGH | WF3_PLAYER_WALK_ONLY | WF3_SOLID_WALL); - mirror->flags3 &= ~(bits & allowedMirrorFlags); - } - } - } - - // Send messages for each link in the infLink list. - // This is the same code for walls and sectors. - void inf_sendLinkMessages(Allocator* infLink, SecObject* entity, u32 evt, MessageType msgType) - { - if (!infLink) { return; } - - InfLink* link = (InfLink*)allocator_getHead(infLink); - while (link) - { - // Fire off the link task if the event and entity match the requirements. - if ((evt == INF_EVENT_NONE || evt == INF_EVENT_ANY || (link->eventMask & evt)) && (!entity || (link->entityMask & entity->entityFlags)) && link->task) - { - s_msgEntity = entity; - s_msgTarget = link->target; - s_msgEvent = evt; - - // Handle recursion gracefully. - void* iter = allocator_getIter(infLink); - { - allocator_addRef(infLink); - task_runLocal(link->task, msgType); - allocator_release(infLink); - } - allocator_setIter(infLink, iter); - } - link = (InfLink*)allocator_getNext(infLink); - } - } - - // Update an elevator. - // Returns JTRUE if the elevator has reached the next stop, else JFALSE. - JBool updateElevator(InfElevator* elev) - { - fixed16_16* value = elev->value; - Stop* nextStop = elev->nextStop; - - fixed16_16 pos = *value; - fixed16_16 targetPos = pos; - if (nextStop) - { - targetPos = nextStop->value; - } - - // The elevator has reached the next stop. - if (pos == targetPos && nextStop) - { - return JTRUE; - } - - InfElevatorType type = elev->type; - InfUpdateFunc updateFunc = nullptr; - switch (type) - { - case IELEV_MOVE_CEILING: - case IELEV_MOVE_FLOOR: - case IELEV_MOVE_OFFSET: - case IELEV_MOVE_FC: - updateFunc = infUpdate_moveHeights; - break; - case IELEV_MOVE_WALL: - updateFunc = infUpdate_moveWall; - break; - case IELEV_ROTATE_WALL: - updateFunc = infUpdate_rotateWall; - break; - case IELEV_SCROLL_WALL: - updateFunc = infUpdate_scrollWall; - break; - case IELEV_SCROLL_FLOOR: - case IELEV_SCROLL_CEILING: - updateFunc = infUpdate_scrollFlat; - break; - case IELEV_CHANGE_LIGHT: - updateFunc = infUpdate_changeAmbient; - break; - case IELEV_CHANGE_WALL_LIGHT: - updateFunc = infUpdate_changeWallLight; - break; - } - - fixed16_16 dt = s_deltaTime; - fixed16_16 frameDelta = 0; - if (!nextStop) - { - // If there are no stops, then the elevator keeps going forever... - // Useful for scrolling textures, constantly spinning gears, etc. - frameDelta = mul16(elev->speed, dt); - } - else - { - fixed16_16 delta = targetPos - pos; - frameDelta = delta; - if (elev->speed) - { - if (!elev->fixedStep) - { - fixed16_16 move = mul16(elev->speed, dt); - frameDelta = delta > move ? move : delta < -move ? -move : delta; - } - else - { - // This is a little strange, this could lead to framerate based speeds... - frameDelta = elev->speed; - } - } - } - - if (updateFunc) - { - pos = updateFunc(elev, frameDelta); - } - else - { - // If there is no update function, just increment the value based and move on. - *elev->value += frameDelta; - pos = *elev->value; - } - - // Returns JTRUE if the elevator has reached the next stop, otherwise returns JFALSE. - return (targetPos == pos && elev->nextStop) ? JTRUE : JFALSE; - } - - void inf_elevatorStart(InfElevator* elev) - { - if (!(elev->updateFlags & ELEV_MOVING)) - { - if (elev->nextStop && *elev->value != elev->nextStop->value) - { - vec3_fixed pos = inf_getElevSoundPos(elev); - sound_playCued(elev->sound0, pos); - } - elev->nextTick = s_curTick; - elev->updateFlags |= ELEV_MOVING; - } - } - - void inf_elevHandleTriggerMsg(InfElevator* elev, u32 evt) - { - switch (elev->trigMove) - { - case TRIGMOVE_CONT: - { - inf_elevatorStart(elev); - } break; - case TRIGMOVE_LAST: - { - // Goto the last stop. - elev->nextStop = inf_advanceStops(elev->stops, -1, 0); - if (*elev->value != elev->nextStop->value) - { - inf_elevatorStart(elev); - } - } break; - case TRIGMOVE_PREV: - { - if (elev->nextTick < s_curTick) - { - elev->nextStop = inf_advanceStops(elev->stops, 0, -1); - } - elev->nextStop = inf_advanceStops(elev->stops, 0, -1); - inf_elevatorStart(elev); - } break; - case TRIGMOVE_NEXT: - default: - { - if (elev->nextTick < s_curTick) - { - elev->nextStop = inf_advanceStops(elev->stops, 0, 1); - } - inf_elevatorStart(elev); - } - } - - // Handle the explosion event. - if (evt == INF_EVENT_EXPLOSION) - { - RSector* sector = elev->sector; - RWall* wall = sector->walls; - for (s32 i = 0; i < sector->wallCount; i++, wall++) - { - wall->flags1 &= ~(WF1_HIDE_ON_MAP | WF1_SHOW_NORMAL_ON_MAP); - } - } - } - - void inf_handleTriggerMsg(InfTrigger* trigger) - { - if (!trigger->master) - { - return; - } - - // Play trigger sound. - sound_play(trigger->soundId); - - // Trigger targets (clients). - TriggerTarget* target = (TriggerTarget*)allocator_getHead(trigger->targets); - u32 event = s_msgEvent; - while (target) - { - if (target->eventMask & event) - { - s_msgArg1 = trigger->arg0; - s_msgArg2 = trigger->arg1; - - if (target->wall) - { - inf_wallSendMessage(target->wall, nullptr, trigger->event, trigger->cmd); - } - else if (target->sector) - { - message_sendToSector(target->sector, nullptr, trigger->event, trigger->cmd); - } - else // the target is a trigger, recursively call the msg func. - { - infTriggerMsgFunc(trigger->cmd); - } - } - target = (TriggerTarget*)allocator_getNext(trigger->targets); - } - - // Send "TEXT" message. - if (trigger->textId) - { - hud_sendTextMessage(trigger->textId); - } - - // Update the trigger state (including switch textures). - TriggerType type = trigger->type; - switch (type) - { - case ITRIGGER_TOGGLE: - { - AnimatedTexture* animTex = trigger->animTex; - if (animTex) - { - trigger->state++; - if (trigger->state >= animTex->count) - { - trigger->state = 0; - } - trigger->tex = animTex->frameList[trigger->state]; - } - } break; - case ITRIGGER_SINGLE: - { - AnimatedTexture* animTex = trigger->animTex; - if (animTex) - { - if (animTex->count) - { - trigger->state = 1; - } - trigger->tex = animTex->frameList[trigger->state]; - // Single can only be triggered once. - trigger->master = JFALSE; - } - } break; - case ITRIGGER_SWITCH1: - { - AnimatedTexture* animTex = trigger->animTex; - if (animTex) - { - if (animTex->count) - { - trigger->state = 1; - } - trigger->tex = animTex->frameList[trigger->state]; - } - // Switch1 can only be triggered once until it recieves the "DONE" message. - trigger->master = JFALSE; - } break; - } - } - - void infElevatorMessageInternal(MessageType msgType) - { - u32 event = s_msgEvent; - InfElevator* elev = (InfElevator*)s_msgTarget; - if (elev->deleted) { return; } - - SecObject* entity = (SecObject*)s_msgEntity; - RSector* sector = elev->sector; - u32 arg1 = s_msgArg1; - - if (entity && (entity->entityFlags&ETFLAG_SMART_OBJ)) - { - if (sector->flags1 & SEC_FLAGS1_NO_SMART_OBJ) - { - return; - } - else if (!(sector->flags1 & SEC_FLAGS1_SMART_OBJ) && !(elev->flags & INF_EFLAG_DOOR)) - { - return; - } - } - - // Master On message. - if (msgType == MSG_MASTER_ON) - { - // Turn master on. - elev->updateFlags |= ELEV_MASTER_ON; - return; - } - if (!(elev->updateFlags & ELEV_MASTER_ON)) - { - return; - } - - // For other messages, make sure the correct key is held. - if (event != INF_EVENT_INTERNAL) - { - // Non-smart entities cannot use this because it requires a key. - if (entity && (entity->entityFlags & ETFLAG_SMART_OBJ) && elev->key != KEY_NONE) - { - return; - } - - // Does the player have the key? - KeyItem key = elev->key; - if (key == KEY_RED && !s_playerInfo.itemRedKey) - { - // "You need the red key." - hud_sendTextMessage(6); - sound_play(s_needKeySoundId); - return; - } - else if (key == KEY_YELLOW && !s_playerInfo.itemYellowKey) - { - // "You need the yellow key." - hud_sendTextMessage(7); - sound_play(s_needKeySoundId); - return; - } - else if (key == KEY_BLUE && !s_playerInfo.itemBlueKey) - { - // "You need the blue key." - hud_sendTextMessage(8); - sound_play(s_needKeySoundId); - return; - } - } - - // Other messages. - switch (msgType) - { - case MSG_TRIGGER: - { - inf_elevHandleTriggerMsg(elev, event); - } break; - case MSG_NEXT_STOP: - { - // This will not fire if the elevator is in the HOLD or delay state. - // This is because nextStop should already be set in that case, so firing it again - // will cause the elevator to skip a stop. - if (elev->nextTick < s_curTick) - { - elev->nextStop = inf_advanceStops(elev->stops, 0, 1); - } - inf_startElevator(elev); - } break; - case MSG_PREV_STOP: - { - // If the elevator is in the HOLD state (i.e. the next time is in the future), go ahead and move back an additional time. - // Why? Since nextStop is the next stop, this sets nextStop to the *current* stop. - if (elev->nextTick > s_curTick) - { - // What this does is move the nextStop back to the "current" stop, so when calling inf_advanceStops() a second time we don't wind up - // back where we started. - elev->nextStop = inf_advanceStops(elev->stops, 0, -1); - } - // Back to the previous stop (see the note above on why this can happen twice). - elev->nextStop = inf_advanceStops(elev->stops, 0, -1); - inf_startElevator(elev); - } break; - case MSG_GOTO_STOP: - if (elev->stops) - { - Stop* stop = inf_advanceStops(elev->stops, arg1, 0); - if (stop->value != *elev->value) - { - elev->nextStop = stop; - inf_startElevator(elev); - - // ... and then stop which - which always happens because updateFlags is or will be set to moving - // and then stops the looping sound if it is playing and then play the stop sound. - // So in some cases you will get the start sound and the stop sound and then the start sound again slightly later. - // This seems like buggy behavior... but I'm going to leave it alone for now. - if (elev->updateFlags & ELEV_MOVING) - { - vec3_fixed pos = inf_getElevSoundPos(elev); - sound_stop(elev->loopingSoundID); - elev->loopingSoundID = NULL_SOUND; - - sound_playCued(elev->sound2, pos); - elev->updateFlags &= ~ELEV_MOVING; - } - } - } break; - case MSG_CRUSH: - { - RSector* sector = elev->sector; - if (!(sector->flags1 & SEC_FLAGS1_CRUSHING)) - { - if (elev->trigMove <= TRIGMOVE_CONT) - { - // This will go to the previous stop. - elev->nextStop = inf_advanceStops(elev->stops, 0, -1); - elev->updateFlags |= ELEV_CRUSH; - } - else // TRIGMOVE_LAST or TRIGMOVE_NEXT or TRIGMOVE_PREV - { - // This will get the last stop. - elev->nextStop = inf_advanceStops(elev->stops, -1, 0); - elev->updateFlags |= ELEV_CRUSH; - } - elev->nextTick = 0; - } - } break; - case MSG_MASTER_OFF: - { - // Disable the elevator. - elev->updateFlags &= ~ELEV_MASTER_ON; - - // Handle the case when the elevator is moving and needs to stop. - if (elev->updateFlags & ELEV_MOVING) - { - // Get the sound position. - vec3_fixed pos = inf_getElevSoundPos(elev); - - // Stop the looping sound and then play the stopping sound. - sound_stop(elev->loopingSoundID); - elev->loopingSoundID = NULL_SOUND; - // Play the stop one shot. - sound_playCued(elev->sound2, pos); - - // Remove the "moving" flag. - elev->updateFlags &= ~ELEV_MOVING; - } - } break; - case MSG_COMPLETE: - { - // Fill in the goal specified by 'arg1' - assert(arg1 < NUM_COMPLETE); - s_levelState.complete[0][arg1] = JTRUE; - // Move the elevator to the stop specified by 'arg1' if it is NOT holding. - if (elev->nextTick < s_curTick) - { - elev->nextStop = inf_advanceStops(elev->stops, arg1, 0); - } - // Play the sound effect, update the flags, update the next update time if NOT moving. - inf_elevatorStart(elev); - } break; - } - } - - void infElevatorMsgFunc(MessageType msgType) - { - if (msgType == MSG_FREE) - { - inf_deleteElevator((InfElevator*)s_msgTarget); - return; - } - infElevatorMessageInternal(msgType); - } - - void infTriggerMsgFunc(MessageType msgType) - { - InfTrigger* trigger = (InfTrigger*)s_msgTarget; - if (trigger->deleted) { return; } - - switch (msgType) - { - case MSG_FREE: - { - inf_deleteTrigger(trigger); - } break; - case MSG_TRIGGER: - { - inf_handleTriggerMsg(trigger); - } break; - case MSG_MASTER_OFF: - { - trigger->master = JFALSE; - } break; - case MSG_DONE: - { - if (trigger->type == ITRIGGER_SWITCH1) - { - AnimatedTexture* animTex = trigger->animTex; - if (animTex) - { - trigger->state = 0; - trigger->tex = animTex->frameList[0]; - } - // reactivate the trigger. - trigger->master = JTRUE; - } - } break; - case MSG_MASTER_ON: - { - trigger->master = JTRUE; - } break; - } - } - - void elevHandleStopDelay(InfElevator* elev) - { - Stop* nextStop = elev->nextStop; - if ((elev->updateFlags & ELEV_MOVING) && nextStop->delay) - { - // Get the position to play the stop sound. - vec3_fixed pos = inf_getElevSoundPos(elev); - - // Stop the looping middle sound and then play the stop sound. - sound_stop(elev->loopingSoundID); - elev->loopingSoundID = NULL_SOUND; - // Play the stop one shot. - sound_playCued(elev->sound2, pos); - } - // If there is a delay, then the elevator is not moving. - if (nextStop->delay) - { - elev->updateFlags &= ~ELEV_MOVING; - } - else - { - elev->updateFlags |= ELEV_MOVING; - } - } - - Stop* inf_advanceStops(Allocator* stops, s32 absoluteStop, s32 relativeStop) - { - Stop* stop = nullptr; - // advance to a future stop - if (relativeStop > 0) - { - for (; relativeStop > 0; relativeStop--) - { - stop = (Stop*)allocator_getNext(stops); - // Loop around. - if (!stop) - { - stop = (Stop*)allocator_getHead(stops); - } - } - } - // advance to a previous stop - else if (relativeStop < 0) - { - relativeStop = -relativeStop; - for (; relativeStop > 0; relativeStop--) - { - stop = (Stop*)allocator_getPrev(stops); - // Loop around. - if (!stop) - { - stop = (Stop*)allocator_getTail(stops); - } - } - } - // relativeStop == 0 - else if (absoluteStop >= 0) - { - // Loop from head instead of the current stop. - stop = (Stop*)allocator_getHead(stops); - for (; absoluteStop > 0; absoluteStop--) - { - stop = (Stop*)allocator_getNext(stops); - if (!stop) - { - stop = (Stop*)allocator_getHead(stops); - } - } - } - // relativeStop == 0 && absoluteStop < 0 -- this basically will send us to the last stop. - else - { - stop = (Stop*)allocator_getTail_noIterUpdate(stops); - } - - return stop; - } - - void inf_deleteSectorElevatorLink(RSector* sector, InfElevator* elev) - { - InfLink* link = (InfLink*)allocator_getHead(sector->infLink); - while (link) - { - if (elev == link->elev) - { - allocator_deleteItem(sector->infLink, link); - break; - } - link = (InfLink*)allocator_getNext(sector->infLink); - } - } - - void inf_deleteElevator(InfElevator* elev) - { - assert(!elev->deleted); - if (elev->slaves) - { - allocator_free(elev->slaves); - elev->slaves = nullptr; - } - // Free the stops. - if (elev->stops) - { - Stop* stop = (Stop*)allocator_getHead(elev->stops); - while (stop) - { - if (stop->messages) - { - allocator_free(stop->messages); - } - if (stop->adjoinCmds) - { - allocator_free(stop->adjoinCmds); - } - stop = (Stop*)allocator_getNext(elev->stops); - } - allocator_free(elev->stops); - elev->stops = nullptr; - } - inf_deleteSectorElevatorLink(elev->sector, elev); - elev->deleted = JTRUE; - //allocator_deleteItem(s_infSerState.infElevators, elev); - } - - void inf_deleteTrigger(InfTrigger* trigger) - { - assert(!trigger->deleted); - - InfLink* link = trigger->link; - allocator_deleteItem(link->parent, link); - allocator_free(trigger->targets); - level_free(trigger->text); - trigger->targets = nullptr; - trigger->text = nullptr; - - // level_free(trigger); - trigger->deleted = JTRUE; - - s_infSerState.activeTriggerCount--; - if (s_infSerState.activeTriggerCount == 0) - { - task_free(s_infState.infTriggerTask); - } - } - - void inf_stopAdjoinCommands(Stop* stop) - { - Allocator* adjoinCmds = stop->adjoinCmds; - if (adjoinCmds) - { - AdjoinCmd* cmd = (AdjoinCmd*)allocator_getHead(adjoinCmds); - while (cmd) - { - RWall* wall0 = cmd->wall0; - RWall* wall1 = cmd->wall1; - RSector* sector0 = cmd->sector0; - RSector* sector1 = cmd->sector1; - - // TFE: Handle mods with invalid adjoin wall IDs. - if (wall0) - { - wall0->nextSector = sector1; - wall0->mirrorWall = wall1; - wall0->mirror = wall0->mirrorWall ? wall0->mirrorWall->id : -1; - } - if (wall1) - { - wall1->nextSector = sector0; - wall1->mirrorWall = wall0; - wall1->mirror = wall1->mirrorWall ? wall1->mirrorWall->id : -1; - } - - sector_setupWallDrawFlags(sector0); - sector_setupWallDrawFlags(sector1); - - cmd = (AdjoinCmd*)allocator_getNext(adjoinCmds); - } - } - } - - // Returns JTRUE if the object is sitting on a moving floor or second height. - JBool inf_isOnMovingFloor(SecObject* obj, InfElevator* elev, RSector* sector) - { - const fixed16_16 secHeight = sector->floorHeight + sector->secHeight; - if ((obj->posWS.y == sector->floorHeight && (elev->flags&INF_EFLAG_MOVE_FLOOR)) || (obj->posWS.y == secHeight && (elev->flags&INF_EFLAG_MOVE_SECHT))) - { - return JTRUE; - } - return JFALSE; - } - - void inf_getMovingElevatorVelocity(InfElevator* elev, vec3_fixed* vel, fixed16_16* angularSpeed) - { - vel->x = 0; - vel->y = 0; - vel->z = 0; - *angularSpeed = 0; - - if (elev->updateFlags & ELEV_MOVING) - { - fixed16_16 speed = 1; - if (elev->nextStop) - { - speed = elev->nextStop->value - *elev->value; - } - if (speed == 0) { return; } - - speed = (speed >= 0) ? elev->speed : -elev->speed; - if (elev->type == IELEV_MOVE_WALL || elev->type == IELEV_SCROLL_FLOOR || elev->type == IELEV_SCROLL_CEILING) - { - vel->x = mul16(speed, elev->dirOrCenter.x); - vel->z = mul16(speed, elev->dirOrCenter.z); - } - } - } - - void inf_sendSectorMessage(RSector* sector, MessageType msgType) - { - switch (msgType) - { - case MSG_WAKEUP: - { - s32 objCount = sector->objectCount; - s32 objCapacity = sector->objectCapacity; - SecObject** objList = sector->objectList; - - for (s32 i = 0; i < objCount && i < objCapacity; objList++) - { - SecObject* obj = *objList; - if (obj) - { - if (obj->entityFlags & ETFLAG_CAN_WAKE) - { - message_sendToObj(obj, MSG_WAKEUP, nullptr); - } - i++; - } - } - } - // MSG_WAKEUP drops through to MSG_MASTER_ON/MSG_MASTER_OFF - case MSG_MASTER_ON: - case MSG_MASTER_OFF: - { - s32 objCount = sector->objectCount; - s32 objCapacity = sector->objectCapacity; - SecObject** objList = sector->objectList; - - for (s32 i = 0; i < objCount && i < objCapacity; objList++) - { - SecObject* obj = *objList; - if (obj) - { - if (obj->entityFlags & ETFLAG_CAN_DISABLE) - { - message_sendToObj(obj, msgType, nullptr); - } - i++; - } - } - } break; - case MSG_SET_BITS: - { - u32 flagsIndex = s_msgArg1; - u32 bits = s_msgArg2; - - if (flagsIndex == 1) - { - sector->flags1 |= bits; - } - else if (flagsIndex == 2) - { - sector->flags2 |= bits; - } - else if (flagsIndex == 3) - { - sector->flags3 |= bits; - } - } break; - case MSG_CLEAR_BITS: - { - u32 flagsIndex = s_msgArg1; - u32 bits = s_msgArg2; - - if (flagsIndex == 1) - { - sector->flags1 &= ~bits; - } - else if (flagsIndex == 2) - { - sector->flags2 &= ~bits; - } - else if (flagsIndex == 3) - { - sector->flags3 &= ~bits; - } - } break; - }; - } - - void inf_stopHandleMessages(MessageType msg) - { - struct LocalContext - { - Allocator* msgList; - Allocator* infLink; - InfMessage* msg; - RSector* sector; - InfLink* link; - }; - task_begin_ctx; - - taskCtx->msgList = s_infState.nextStop->messages; - taskCtx->msg = (InfMessage*)allocator_getHead(taskCtx->msgList); - while (taskCtx->msg) - { - s_msgArg1 = taskCtx->msg->arg1; - s_msgArg2 = taskCtx->msg->arg2; - if (taskCtx->msg->wall) - { - inf_wallSendMessage(taskCtx->msg->wall, nullptr, taskCtx->msg->event, taskCtx->msg->msgType); - } - else if (taskCtx->msg->sector) - { - taskCtx->sector = taskCtx->msg->sector; - taskCtx->infLink = taskCtx->sector->infLink; - if (taskCtx->infLink) - { - taskCtx->link = (InfLink*)allocator_getHead(taskCtx->infLink); - while (taskCtx->link) - { - if (taskCtx->link->task && (taskCtx->msg->event == INF_EVENT_NONE || taskCtx->msg->event == INF_EVENT_ANY || (taskCtx->link->eventMask & taskCtx->msg->event))) - { - allocator_addRef(taskCtx->msgList); - - inf_sendSectorMessage(taskCtx->sector, taskCtx->msg->msgType); - - s_msgTarget = taskCtx->link->target; - s_msgEntity = nullptr; - s_msgArg1 = taskCtx->msg->arg1; - s_msgArg2 = taskCtx->msg->arg2; - s_msgEvent = taskCtx->msg->event; - task_runLocal(taskCtx->link->task, taskCtx->msg->msgType); - - if (msg != MSG_RUN_TASK) - { - infElevatorMessageInternal(msg); - task_yield(TASK_NO_DELAY); - } - - allocator_release(taskCtx->msgList); - } - taskCtx->link = (InfLink*)allocator_getNext(taskCtx->infLink); - } - } - else // infLink - { - message_sendToSector(taskCtx->sector, nullptr, taskCtx->msg->event, taskCtx->msg->msgType); - } - } - else // world - { - // In the original game, this will call a specific function based on the type - // But the only type is MSG_LIGHTS - if (taskCtx->msg->msgType == MSG_LIGHTS) - { - inf_handleMsgLights(); - } - } - - taskCtx->msg = (InfMessage*)allocator_getNext(taskCtx->msgList); - } // while (msg) - - task_end; - } - - void inf_handleMsgLights() - { - RSector* sector = s_levelState.sectors; - for (u32 i = 0; i < s_levelState.sectorCount; i++, sector++) - { - fixed16_16 newAmbient = intToFixed16(sector->flags3); - if (newAmbient != sector->ambient) - { - sector->dirtyFlags |= SDF_AMBIENT; - } - - // Store the old value in flags3 so the lights can be toggled. - sector->flags3 = floor16(sector->ambient); - sector->ambient = newAmbient; - } - } - - vec3_fixed inf_getElevSoundPos(InfElevator* elev) - { - vec3_fixed pos = { 0 }; - RSector* sector = elev ? elev->sector : nullptr; - if (!sector) { return pos; } - - // Figure out the source position for the sound effect. - pos.y = sector->secHeight + sector->floorHeight; - if (elev->type != IELEV_ROTATE_WALL) - { - // First vertex position. - vec2_fixed* vtx = (vec2_fixed*)sector->verticesWS; - if (vtx) - { - pos.x = vtx->x; - pos.z = vtx->z; - } - } - else - { - // Rotation center. - pos.x = elev->dirOrCenter.x; - pos.z = elev->dirOrCenter.z; - } - - return pos; - } - - /////////////////////////////////////////// - // Trigger creation and setup - /////////////////////////////////////////// - // Creates a trigger and adds a link to the sector or wall where it is located. - // For example, if a player "nudges" a wall, then all of the wall's links will be - // cycled through, calling the "msgFunc" on each to determine what happens, which than - // sends the message to the appropriate "InfTrigger" or "InfElevator" - InfTrigger* inf_createTrigger(TriggerType type, InfTriggerObject obj) - { - InfTrigger* trigger = (InfTrigger*)allocator_newItem(s_infSerState.infTriggers); - memset(trigger, 0, sizeof(InfTrigger)); - s_infSerState.activeTriggerCount++; - - InfLink* link = nullptr; - trigger->soundId = NULL_SOUND; - trigger->targets = allocator_create(sizeof(TriggerTarget)); - - void* parent = nullptr; - switch (type) - { - case ITRIGGER_WALL: - { - RWall* wall = obj.wall; - if (!wall->infLink) - { - wall->infLink = allocator_create(sizeof(InfLink)); - } - link = (InfLink*)allocator_newItem(wall->infLink); - link->type = LTYPE_TRIGGER; - link->entityMask = INF_ENTITY_PLAYER; - link->eventMask = INF_EVENT_ANY; - link->trigger = trigger; - link->task = s_infState.infTriggerTask; - link->parent = wall->infLink; - // TFE - parent = wall; - } break; - case ITRIGGER_SECTOR: - { - RSector* sector = obj.sector; - if (!sector->infLink) - { - sector->infLink = allocator_create(sizeof(InfLink)); - } - link = (InfLink*)allocator_newItem(sector->infLink); - link->type = LTYPE_TRIGGER; - link->entityMask = INF_ENTITY_PLAYER; - link->eventMask = INF_EVENT_ANY; - link->trigger = trigger; - link->task = s_infState.infTriggerTask; - link->parent = sector->infLink; - // TFE - parent = sector; - } break; - case ITRIGGER_SWITCH1: - case ITRIGGER_TOGGLE: - case ITRIGGER_SINGLE: - { - RWall* wall = obj.wall; - trigger->soundId = s_switchDefaultSndId; - if (!wall->infLink) - { - wall->infLink = allocator_create(sizeof(InfLink)); - } - link = (InfLink*)allocator_newItem(wall->infLink); - link->type = LTYPE_TRIGGER; - link->entityMask = INF_ENTITY_PLAYER; - link->eventMask = INF_EVENT_ANY; - link->task = s_infState.infTriggerTask; - link->trigger = trigger; - link->parent = wall->infLink; - trigger->animTex = nullptr; - - // Handle trigger sign texture. - TextureData** signTex = wall->signTex; - if (signTex && (*signTex)->uvWidth == BM_ANIMATED_TEXTURE) - { - // In this case, image points to the AnimatedTexture rather than the actual image. - AnimatedTexture* animTex = (AnimatedTexture*)(*signTex)->image; - trigger->animTex = animTex; - trigger->tex = animTex->frameList[0]; - wall->signTex = &trigger->tex; - // Removes "cross line" events - link->eventMask &= ~(INF_EVENT_CROSS_LINE_FRONT | INF_EVENT_CROSS_LINE_BACK); - } - - // TFE - parent = wall; - } break; - } - trigger->cmd = MSG_TRIGGER; - trigger->event = 0; - trigger->arg1 = 0; - trigger->timer = -1; - trigger->time = 21; - trigger->master = JTRUE; - trigger->state = 0; - trigger->text = nullptr; - trigger->textId = 0; - trigger->link = link; - trigger->type = type; - trigger->parent = parent; - if (link) - { - link->freeFunc = (InfFreeFunc)inf_deleteTrigger; - } - - return trigger; - } - - /////////////////////////////////////////////////// - // Elevator Update Functions - /////////////////////////////////////////////////// - fixed16_16 infUpdate_moveHeights(InfElevator* elev, fixed16_16 delta) - { - RSector* sector = elev->sector; - fixed16_16 secHeightDelta = 0; - fixed16_16 ceilDelta = 0; - fixed16_16 floorDelta = 0; - - switch (elev->type) - { - case IELEV_MOVE_CEILING: - ceilDelta = delta; - break; - case IELEV_MOVE_FLOOR: - floorDelta = delta; - break; - case IELEV_MOVE_OFFSET: - secHeightDelta = delta; - break; - case IELEV_MOVE_FC: - floorDelta = delta; - ceilDelta = delta; - break; - } - - fixed16_16 maxObjHeight = sector_getMaxObjectHeight(sector); - if (maxObjHeight) - { - maxObjHeight += c_verticalElevCrushThres; - if (secHeightDelta) - { - fixed16_16 offsetHeight = sector->floorHeight + sector->secHeight; - fixed16_16 maxObjHeightAbove = 0; - fixed16_16 maxObjectHeightBelow = 0; - - // Remove dead objects. - sector_removeCorpses(sector); - - s32 objCount = sector->objectCount; - SecObject** objList = sector->objectList; - for (; objCount > 0; objList++) - { - SecObject* obj = *objList; - if (!obj) { continue; } - - objCount--; - fixed16_16 objHeight = obj->worldHeight + ONE_16; - if (obj->posWS.y > offsetHeight) // Object is below the second height - { - maxObjectHeightBelow = max(maxObjectHeightBelow, objHeight); - } - else // Object is on or above the second height - { - maxObjHeightAbove = max(maxObjHeightAbove, objHeight); - } - } - - // The new second height after adjustment (only second height so far). - offsetHeight += secHeightDelta; - // Difference between the base floor height and the adjusted second height. - fixed16_16 floorDelta = sector->floorHeight - (offsetHeight + ONE_16); - // Difference betwen the adjusted second height and the ceiling. - fixed16_16 ceilDelta = offsetHeight - sector->ceilingHeight; - if (floorDelta < maxObjectHeightBelow || ceilDelta < maxObjHeightAbove) - { - // If there are objects in the way, set the next stop as the previous. - elev->nextStop = inf_advanceStops(elev->stops, 0, -1); - secHeightDelta = 0; - } - } - else - { - fixed16_16 floorHeight = sector->floorHeight + floorDelta; - fixed16_16 ceilHeight = sector->ceilingHeight + ceilDelta; - fixed16_16 spaceAvail = floorHeight - ceilHeight; - if (spaceAvail < maxObjHeight) - { - // Remove dead objects. - sector_removeCorpses(sector); - - // See if there is anything else in the way. - maxObjHeight = sector_getMaxObjectHeight(sector); - if (maxObjHeight) - { - maxObjHeight += c_verticalElevCrushThres2; - - // If the height between floor and ceiling is too small for the tallest object AND - // If the floor is moving up or the ceiling is moving down and this is NOT a crushing sector. - if (spaceAvail < maxObjHeight && (floorDelta < 0 || ceilDelta > 0) && !(sector->flags1 & SEC_FLAGS1_CRUSHING)) - { - elev->nextStop = inf_advanceStops(elev->stops, 0, -1); - floorDelta = 0; - secHeightDelta = 0; - ceilDelta = 0; - } - } - } - } - } - - if (floorDelta) - { - sector_adjustTextureWallOffsets_Floor(sector, floorDelta); - sector_adjustTextureMirrorOffsets_Floor(sector, floorDelta); - } - sector_adjustHeights(sector, floorDelta, ceilDelta, secHeightDelta); - - // Apply adjustments to "slave" sectors. - Slave* child = (Slave*)allocator_getHead(elev->slaves); - while (child) - { - if (floorDelta) - { - sector_adjustTextureWallOffsets_Floor(child->sector, floorDelta); - sector_adjustTextureMirrorOffsets_Floor(child->sector, floorDelta); - } - sector_adjustHeights(child->sector, floorDelta, ceilDelta, secHeightDelta); - child = (Slave*)allocator_getNext(elev->slaves); - } - return *elev->value; - } - - fixed16_16 infUpdate_moveWall(InfElevator* elev, fixed16_16 delta) - { - // First attempt to move walls in the sector. - if (!sector_moveWalls(elev->sector, delta, elev->dirOrCenter.x, elev->dirOrCenter.z, elev->flags)) - { - return elev->iValue; - } - - // If successful move its slaves. - Slave* child = (Slave*)allocator_getHead(elev->slaves); - while (child) - { - sector_moveWalls(child->sector, delta, elev->dirOrCenter.x, elev->dirOrCenter.z, elev->flags); - child = (Slave*)allocator_getNext(elev->slaves); - } - - // Finally update the elevator value. - elev->iValue += delta; - return elev->iValue; - } - - fixed16_16 infUpdate_rotateWall(InfElevator* elev, fixed16_16 delta) - { - RSector* sector = elev->sector; - sector->dirtyFlags |= SDF_VERTICES; - - JBool halfStep = JFALSE; - if (abs(delta) < ONE_16) - { - // This is a minor hack to allow slow moving rotating sectors to work at up to 144Hz. - // Basically it allows slowly rotating elevators to work at 2x the framerate by rounding in halves - yielding similar - // behavior to vanilla. - fixed16_16 d2 = delta * 2; - d2 = (d2 > 0) ? fixed16_16((d2 + HALF_16) & 0xffff0000) : -fixed16_16((HALF_16 - d2) & 0xffff0000); - delta = d2 / 2; - halfStep = JTRUE; - } - else - { - // This is the DOS code. - delta = (delta > 0) ? fixed16_16((delta + HALF_16) & 0xffff0000) : -fixed16_16((HALF_16 - delta) & 0xffff0000); - } - - const fixed16_16 angle = elev->iValue + delta; - const fixed16_16 centerX = elev->dirOrCenter.x; - const fixed16_16 centerZ = elev->dirOrCenter.z; - const angle14_32 angleInt = floor16(angle); - if (!sector_canRotateWalls(sector, angleInt, centerX, centerZ)) - { - return elev->iValue; - } - - Slave* child = (Slave*)allocator_getHead(elev->slaves); - while (child) - { - // The value in slave can be used as an angular offset. - if (!sector_canRotateWalls(child->sector, child->value + angleInt, centerX, centerZ)) - { - return elev->iValue; - } - child = (Slave*)allocator_getNext(elev->slaves); - } - sector_rotateWalls(elev->sector, centerX, centerZ, angleInt, elev->flags); - - // The original DOS code was deltaInt = floor16(delta); - // But this code allows for half steps to be taken when needed at high framerates without modifying the - // original behavior in other cases. - const angle14_32 deltaInt = halfStep ? (angleInt - elev->prevValue) : floor16(delta); - sector_rotateObjects(elev->sector, deltaInt, centerX, centerZ, elev->flags); - - child = (Slave*)allocator_getHead(elev->slaves); - while (child) - { - sector_rotateWalls(child->sector, centerX, centerZ, angleInt + child->value, elev->flags); - sector_rotateObjects(child->sector, deltaInt, centerX, centerZ, elev->flags); - child = (Slave*)allocator_getNext(elev->slaves); - } - elev->prevValue = angleInt; - elev->iValue = angle; - return elev->iValue; - } - - fixed16_16 infUpdate_scrollWall(InfElevator* elev, fixed16_16 delta) - { - elev->iValue += delta; - fixed16_16 deltaX = mul16(delta, elev->dirOrCenter.x); - fixed16_16 deltaZ = mul16(delta, elev->dirOrCenter.z); - sector_scrollWalls(elev->sector, deltaX, deltaZ); - - Slave* child = (Slave*)allocator_getHead(elev->slaves); - while (child) - { - sector_scrollWalls(child->sector, deltaX, deltaZ); - child = (Slave*)allocator_getNext(elev->slaves); - } - return elev->iValue; - } - - fixed16_16 infUpdate_scrollFlat(InfElevator* elev, fixed16_16 delta) - { - elev->iValue += delta; - fixed16_16 deltaX = mul16(delta, elev->dirOrCenter.x); - fixed16_16 deltaZ = mul16(delta, elev->dirOrCenter.z); - - RSector* sector = elev->sector; - sector->dirtyFlags |= SDF_FLAT_OFFSETS; - if (elev->type == IELEV_SCROLL_FLOOR) - { - sector->floorOffset.x += deltaX; - sector->floorOffset.z += deltaZ; - } - else if (elev->type == IELEV_SCROLL_CEILING) - { - sector->ceilOffset.x += deltaX; - sector->ceilOffset.z += deltaZ; - } - - Slave* child = (Slave*)allocator_getHead(elev->slaves); - while (child) - { - sector = child->sector; - sector->dirtyFlags |= SDF_FLAT_OFFSETS; - if (elev->type == IELEV_SCROLL_FLOOR) - { - sector->floorOffset.x += deltaX; - sector->floorOffset.z += deltaZ; - } - else if (elev->type == IELEV_SCROLL_CEILING) - { - sector->ceilOffset.x += deltaX; - sector->ceilOffset.z += deltaZ; - } - child = (Slave*)allocator_getNext(elev->slaves); - } - - return elev->iValue; - } - - fixed16_16 infUpdate_changeAmbient(InfElevator* elev, fixed16_16 delta) - { - RSector* sector = elev->sector; - sector->ambient += delta; - sector->dirtyFlags |= SDF_AMBIENT; - - Slave* child = (Slave*)allocator_getHead(elev->slaves); - while (child) - { - child->sector->ambient += delta; - child->sector->dirtyFlags |= SDF_AMBIENT; - child = (Slave*)allocator_getNext(elev->slaves); - } - return sector->ambient; - } - - fixed16_16 infUpdate_changeWallLight(InfElevator* elev, fixed16_16 delta) - { - elev->iValue += delta; - sector_changeWallLight(elev->sector, delta); - - Slave* child = (Slave*)allocator_getHead(elev->slaves); - while (child) - { - sector_changeWallLight(child->sector, delta); - child = (Slave*)allocator_getNext(elev->slaves); - } - return elev->iValue; - } - - JBool sector_isDoor(RSector* sector) - { - if (!sector) { return JFALSE; } - - if (sector->flags1 & SEC_FLAGS1_DOOR) - { - return JTRUE; - } - else - { - InfLink* link = (InfLink*)allocator_getHead(sector->infLink); - if (link && link->type == LTYPE_SECTOR) - { - InfElevator* elev = link->elev; - InfElevatorType type = elev->type; - if (type == IELEV_MOVE_CEILING || type == IELEV_MOVE_FLOOR || type == IELEV_MOVE_WALL || type == IELEV_ROTATE_WALL || type == IELEV_MOVE_FC) - { - return JTRUE; - } - } - } - return JFALSE; - } -} - -#ifdef TFE_ESPBOX -// The file read scratch buffer keeps the capacity of the largest file loaded; -// release it when the game is shut down (called from the platform glue). -void espbox_free_inf_scratch() -{ - std::vector().swap(TFE_Jedi::s_buffer); -} -#endif diff --git a/components/darkforces/tfe/TFE_Jedi/InfSystem/infSystem.h b/components/darkforces/tfe/TFE_Jedi/InfSystem/infSystem.h deleted file mode 100644 index cd404dfe..00000000 --- a/components/darkforces/tfe/TFE_Jedi/InfSystem/infSystem.h +++ /dev/null @@ -1,87 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// INF System -// Classic Dark Forces (DOS) Jedi derived INF system. The INF System -// is a "script-like" system that controls level interactivity, -// level animation, and tracks completion. -// -// Copyright note: -// While the project as a whole is licensed under GPL-2.0, some of the -// code under TFE_Jedi/InfSystem/ was derived from reverse-engineered -// code from "Dark Forces" (DOS) which is copyrighted by LucasArts. -// -// I consider the reverse-engineering to be "Fair Use" - a means of -// supporting the games on other platforms and to improve support on -// existing platforms without claiming ownership of the games -// themselves or their IPs. -// -// That said using this code in a commercial project is risky without -// permission of the original copyright holders (LucasArts). -////////////////////////////////////////////////////////////////////// -#include "infPublicTypes.h" -#include -#include - -struct RWall; -struct RSector; -struct SecObject; - -namespace TFE_Jedi -{ - // Setup - void inf_createElevatorTask(); - void inf_createTeleportTask(); - void inf_createTriggerTask(); - - // Serialization & State - void inf_clearState(); - void inf_serialize(Stream* stream); - - // ** Runtime API ** - // Messages are the way entities and the player interact with the INF system during gameplay. - - // Send a message to a specific wall or line, such as when "nudging" a switch or crossing a line. - // wall: message target. - // entity: entity involved (such as the player) or nullptr. - // evt: event(s) (see InfEventMask in "infPublicTypes.h" such as INF_EVENT_CROSS_LINE_FRONT). - // msgType: message type (such as IMSG_TRIGGER). - void inf_wallSendMessage(RWall* wall, SecObject* entity, u32 evt, MessageType msgType); - - // Send a message to a specific wall or line at a specific location on the wall. This is used for projectiles hitting switches. - // This always sends the "IMSG_TRIGGER" message. - // wall: message target. - // entity: entity involved (such as the player) or nullptr. - // evt: event(s) (see InfEventMask in "infPublicTypes.h" such as INF_EVENT_CROSS_LINE_FRONT). - // paramPos: the parametric horizontal position on the line from [0, length]. - // yPos: the y position. - void inf_wallSendMessageAtPos(RWall* wall, SecObject* entity, u32 evt, TFE_Jedi::fixed16_16 paramPos, TFE_Jedi::fixed16_16 yPos); - void inf_wallAndMirrorSendMessageAtPos(RWall* wall, SecObject* entity, u32 evt, TFE_Jedi::fixed16_16 paramPos, TFE_Jedi::fixed16_16 yPos); - void inf_triggerWallEvent(RWall* wall, SecObject* obj, u32 event); - - // Returns JTRUE if the object is sitting on a moving floor or second height. - JBool inf_isOnMovingFloor(SecObject* obj, InfElevator* elev, RSector* sector); - - // Get the moving elevator velocity. - void inf_getMovingElevatorVelocity(InfElevator* elev, vec3_fixed* vel, fixed16_16* speed); - - // ** Loadtime API ** - // These functions are used at load-time to setup special elevators based on sector flags or load - // the level INF. - - // Used when loading levels. - struct InfElevator; - - // For now load the INF data directly. - // Move back to the asset system later. - JBool inf_load(const char* levelName); - - // Sounds - void inf_loadSounds(); - - InfElevator* inf_allocateSpecialElevator(RSector* sector, InfSpecialElevator type); - InfElevator* inf_allocateElevItem(RSector* sector, InfElevatorType type); - void inf_sendSectorMessage(RSector* sector, MessageType msgType); - void inf_sendLinkMessages(Allocator* infLink, SecObject* entity, u32 evt, MessageType msgType); - - JBool sector_isDoor(RSector* sector); -} diff --git a/components/darkforces/tfe/TFE_Jedi/InfSystem/infTypesInternal.h b/components/darkforces/tfe/TFE_Jedi/InfSystem/infTypesInternal.h deleted file mode 100644 index 9446b4c5..00000000 --- a/components/darkforces/tfe/TFE_Jedi/InfSystem/infTypesInternal.h +++ /dev/null @@ -1,202 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include "infPublicTypes.h" - -struct TextureData; -struct AnimatedTexture; -struct Allocator; - -namespace TFE_Jedi -{ - struct InfLink; - - // How an elevator moves if triggered. - enum ElevTrigMove - { - TRIGMOVE_HOLD = -1, // The elevator is holding, so the trigger message has no effect. - TRIGMOVE_CONT = 0, // Continue to the next stop if NOT already moving. - TRIGMOVE_LAST = 1, // Set next (target) stop to the last stop whether moving or not. - TRIGMOVE_NEXT = 2, // Set next (target) stop to the next stop if NOT waiting for a timed delay. - TRIGMOVE_PREV = 3, // Set next (target) stop to the prev stop if waiting for a timed delay or goes back 2 stops if NOT waiting for a timed delay. - }; - - enum ElevUpdateFlags - { - ELEV_MOVING = FLAG_BIT(0), // elevator should be moving. - ELEV_MASTER_ON = FLAG_BIT(1), // master on - ELEV_CRUSH = FLAG_BIT(2), // the elevator is moving in reverse. - }; - - enum InfDelay - { - // IDELAY_SECONDS < IDELAY_COMPLETE - IDELAY_HOLD = 0xffffffff, - IDELAY_TERMINATE = 0xfffffffe, - IDELAY_COMPLETE = 0xfffffffd, - }; - - enum TriggerType - { - ITRIGGER_WALL = 0, - ITRIGGER_SECTOR, - ITRIGGER_SWITCH1, - ITRIGGER_TOGGLE, - ITRIGGER_SINGLE - }; - - enum InfEntityMask - { - INF_ENTITY_ENEMY = FLAG_BIT(0), - INF_ENTITY_WEAPON = FLAG_BIT(3), - INF_ENTITY_SMART_OBJ = FLAG_BIT(11), - INF_ENTITY_PLAYER = FLAG_BIT(31), - INF_ENTITY_ANY = 0xffffffffu - }; - - enum InfElevatorFlags - { - INF_EFLAG_MOVE_FLOOR = FLAG_BIT(0), // Move on floor. - INF_EFLAG_MOVE_SECHT = FLAG_BIT(1), // Move on second height. - INF_EFLAG_MOVE_CEIL = FLAG_BIT(2), // Move on ceiling (head has to be close enough?) - INF_EFLAG_DOOR = FLAG_BIT(3), // This is a door auto-created from the sector flag. - // New TFE Flags - TODO: Implement them. - INF_EFLAG_ROTATE_FLOOR = FLAG_BIT(4), // Rotate the floor if the sector rotates. - INF_EFLAG_ROTATE_CEIL = FLAG_BIT(5), // Rotate the ceiling if the sector rotates. - }; - - enum KeyItem - { - KEY_NONE = 0, - KEY_RED = 23, - KEY_YELLOW = 24, - KEY_BLUE = 25, - }; - - enum TeleportType - { - TELEPORT_BASIC = 0, - TELEPORT_CHUTE = 1 - }; - - struct Teleport - { - RSector* sector; - RSector* target; - TeleportType type; - - vec3_fixed dstPosition; - angle14_16 dstAngle[3]; - }; - - struct TriggerTarget - { - RSector* sector; - RWall* wall; - u32 eventMask; - }; - - struct InfTrigger - { - TriggerType type; - InfLink* link; - AnimatedTexture* animTex; - Allocator* targets; - MessageType cmd; - u32 event; - u32 arg0; - u32 arg1; - - // Unused - // Some of these values are set, such as timer and time but are not referenced. - s32 arg2; - s32 arg3; - s32 arg4; - s32 arg5; - - s32 timer; - s32 time; - // End Unused - - JBool master; - TextureData* tex; - SoundSourceId soundId; - s32 state; - char* text; // This is also unreferenced - probably debug code. - u32 textId; - - // TFE - JBool deleted; - void* parent; - }; - - struct InfMessage - { - RSector* sector; - RWall* wall; - MessageType msgType; - u32 event; - u32 arg1; - u32 arg2; - }; - - struct Slave - { - RSector* sector; - s32 value; - }; - - struct AdjoinCmd - { - RWall* wall0; - RWall* wall1; - RSector* sector0; - RSector* sector1; - }; - - struct Stop - { - fixed16_16 value; - Tick delay; // delay in 'ticks' (see TICKS_PER_SECOND in TFE_DarkForces/time.h) - Allocator* messages; - Allocator* adjoinCmds; - SoundSourceId pageId; - TextureData** floorTex; - TextureData** ceilTex; - - // TFE: - s32 floorTexSecId = -1; - s32 ceilTexSecId = -1; - s32 index = -1; - }; - - struct InfElevator - { - InfElevator* self; - InfElevatorType type; - ElevTrigMove trigMove; - RSector* sector; - KeyItem key; - s32 fixedStep; - Tick nextTick; - Tick timer; - Allocator* stops; - Allocator* slaves; - Stop* nextStop; - fixed16_16 speed; - fixed16_16* value; - fixed16_16 iValue; - vec2_fixed dirOrCenter; - u32 flags; - SoundSourceId sound0; - SoundSourceId sound1; - SoundSourceId sound2; - SoundEffectId loopingSoundID; - s32 updateFlags; - // TFE - fixed16_16 prevValue; - JBool deleted; - }; -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/InfSystem/message.cpp b/components/darkforces/tfe/TFE_Jedi/InfSystem/message.cpp deleted file mode 100644 index 12921efe..00000000 --- a/components/darkforces/tfe/TFE_Jedi/InfSystem/message.cpp +++ /dev/null @@ -1,100 +0,0 @@ -#include - -#include "message.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace TFE_Jedi -{ - Allocator* s_messageAddr = nullptr; - void* s_msgEntity; - void* s_msgTarget; - u32 s_msgArg1; - u32 s_msgArg2; - u32 s_msgEvent; - - void message_free() - { - s_messageAddr = nullptr; - } - - void message_addAddress(const char* name, s32 param0, s32 param1, RSector* sector) - { - if (!s_messageAddr) - { - s_messageAddr = allocator_create(sizeof(MessageAddress)); - } - MessageAddress* msgAddr = (MessageAddress*)allocator_newItem(s_messageAddr); - - assert(strlen(name) <= 16); - strncpy(msgAddr->name, name, 16); - - msgAddr->param0 = param0; - msgAddr->param1 = param1; - msgAddr->sector = sector; - } - - MessageAddress* message_getAddress(const char* name) - { - MessageAddress* msgAddr = (MessageAddress*)allocator_getHead(s_messageAddr); - while (msgAddr) - { - if (strncasecmp(name, msgAddr->name, 16) == 0) - { - return msgAddr; - } - msgAddr = (MessageAddress*)allocator_getNext(s_messageAddr); - } - - TFE_System::logWrite(LOG_ERROR, "INF", "Message_GetAddress: ADDRESS NOT FOUND: %s", name); - return nullptr; - } - - void message_sendToObj(SecObject* obj, MessageType msgType, MessageFunc func) - { - Logic** logicList = (Logic**)allocator_getHead((Allocator*)obj->logic); - while (logicList) - { - Logic* logic = *logicList; - s_msgTarget = logic; - { - if (logic->task == task_getCurrent() && func) - { - //s_taskId = msgType; - func(msgType, logic); - //s_taskId = 0; - } - else if (task_hasLocalMsgFunc(logic->task)) - { - task_runLocal(logic->task, msgType); - } - else - { - task_runAndReturn(logic->task, msgType); - } - } - logicList = (Logic**)allocator_getNext((Allocator*)obj->logic); - } - } - - // Send messages so that entities and the player can interact with the INF system. - // If msgType = MSG_SET/CLEAR_BITS, MSG_MASTER_ON/OFF, MSG_WAKEUP it is processed directly for this sector AND - // this iterates through the valid links and calls their msgFunc. - void message_sendToSector(RSector* sector, SecObject* entity, u32 evt, MessageType msgType) - { - // Was: inf_sendSectorMessage() - // Changed: inf_sendSectorMessageInternal() -> inf_sendSectorMessage() - inf_sendSectorMessage(sector, msgType); - inf_sendLinkMessages(sector->infLink, entity, evt, msgType); - } -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/InfSystem/message.h b/components/darkforces/tfe/TFE_Jedi/InfSystem/message.h deleted file mode 100644 index 8bf29e6f..00000000 --- a/components/darkforces/tfe/TFE_Jedi/InfSystem/message.h +++ /dev/null @@ -1,69 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Message Address is the way named sectors are flagged during load -// in order to be looked up by the INF system. -////////////////////////////////////////////////////////////////////// - -#include -#include -#include -#include -#include - -enum MessageType -{ - MSG_FREE_TASK = -1, - MSG_RUN_TASK = 0, - MSG_FREE = 1, - MSG_SWITCH_WPN = 2, - MSG_START_FIRING = 4, - MSG_STOP_FIRING = 5, - MSG_HOLSTER = 6, - MSG_TRIGGER = 7, - MSG_NEXT_STOP = 8, - MSG_PREV_STOP = 9, - MSG_GOTO_STOP = 11, - MSG_CRUSH = 12, - MSG_SEQ_COMPLETE = 20, - MSG_DONE = 21, - MSG_DAMAGE = 22, - MSG_EXPLOSION = 23, - MSG_PICKUP = 24, - MSG_WAKEUP = 25, - MSG_TERMINAL_VEL = 26, - MSG_MASTER_ON = 29, - MSG_MASTER_OFF = 30, - MSG_SET_BITS = 31, - MSG_CLEAR_BITS = 32, - MSG_COMPLETE = 33, - MSG_LIGHTS = 34, - MSG_COUNT -}; - -typedef void(*MessageFunc)(MessageType, void*); -struct MessageAddress -{ - char name[16]; - s32 param0; - s32 param1; - RSector* sector; -}; - -namespace TFE_Jedi -{ - // Add and retrieve addresses, this way named sectors can be accessed without looping through the entire set. - void message_addAddress(const char* name, s32 param0, s32 param1, RSector* sector); - MessageAddress* message_getAddress(const char* name); - void message_free(); - - // Send a message to either an object or sector. - void message_sendToObj(SecObject* obj, MessageType msgType, MessageFunc func); - void message_sendToSector(RSector* sector, SecObject* entity, u32 evt, MessageType msgType); - - // Optional message values - set these before calling message_XXX() and read inside the message function. - extern void* s_msgEntity; - extern void* s_msgTarget; - extern u32 s_msgArg1; - extern u32 s_msgArg2; - extern u32 s_msgEvent; -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Level/level.cpp b/components/darkforces/tfe/TFE_Jedi/Level/level.cpp deleted file mode 100644 index 1942e1d8..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Level/level.cpp +++ /dev/null @@ -1,1036 +0,0 @@ -#include -#include - -#include "level.h" -#include "levelData.h" -#ifdef TFE_ESPBOX -#include "esp_platform.h" -#endif -#include "rwall.h" -#include "rtexture.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -// TODO: Fix game dependency? -#include - -namespace TFE_DarkForces -{ - extern u8 s_levelPalette[]; - extern u8 s_basePalette[]; - extern JBool s_palModified; -} -using namespace TFE_DarkForces; - -#ifdef TFE_ESPBOX -void espbox_free_rtexture_scratch(); -void espbox_free_sprite_scratch(); -void espbox_free_level_scratch(); -void espbox_free_inf_scratch(); -void espbox_free_model_scratch(); -#endif - -namespace TFE_Jedi -{ - enum - { - DF_LEVEL_VERSION_MAJOR = 2, - DF_LEVEL_VERSION_MINOR = 1, - }; - - // Temp State. - static s32 s_dataIndex; - static char s_readBuffer[256]; - static std::vector s_buffer; - - JBool level_loadGeometry(const char* levelName); - JBool level_loadObjects(const char* levelName, u8 difficulty); - JBool level_loadGoals(const char* levelName); - - JBool level_load(const char* levelName, u8 difficulty) - { - if (!levelName) { return JFALSE; } -#ifdef TFE_ESPBOX - // Memory diagnostics: what is still allocated when a level starts loading. - printf("[DarkForces] memory before loading '%s':\n", levelName); - TFE_Memory::printPoolSummary(); - TFE_Memory::printRegionCallers(); -#endif - - // Clear just in case. - for (s32 i = 0; i < NUM_COMPLETE; i++) - { - s_levelState.completeNum[COMPL_TRIG][i] = -1; - s_levelState.completeNum[COMPL_ITEM][i] = -1; - - s_levelState.complete[COMPL_TRIG][i] = JFALSE; - s_levelState.complete[COMPL_ITEM][i] = JFALSE; - } - - if (!level_loadGeometry(levelName)) { return JFALSE; } - level_loadObjects(levelName, difficulty); - inf_load(levelName); -#ifdef TFE_ESPBOX - // The loaders' scratch read buffers (~0.8MB) are not needed while playing. - espbox_free_rtexture_scratch(); - espbox_free_sprite_scratch(); - espbox_free_level_scratch(); - espbox_free_inf_scratch(); - espbox_free_model_scratch(); -#endif - level_loadGoals(levelName); - - return JTRUE; - } - - void level_loadPalette() - { - // Palette *IS* loaded from the level file. - FilePath filePath; - if (TFE_Paths::getFilePath(s_levelState.levelPaletteName, &filePath)) - { - FileStream::readContents(&filePath, s_levelPalette, 768); - } - else if (TFE_Paths::getFilePath("default.pal", &filePath)) - { - FileStream::readContents(&filePath, s_levelPalette, 768); - } - // The "base palette" is adjusted by the hud colors, which is why it is a copy. - memcpy(s_basePalette, s_levelPalette, 768); - s_palModified = JTRUE; - } - - JBool level_loadGeometry(const char* levelName) - { - s_levelState.secretCount = 0; - s_dataIndex = 0; - s_levelState.minLayer = INT_MAX; - s_levelState.maxLayer = INT_MIN; - message_free(); - - char levelPath[TFE_MAX_PATH]; - strcpy(levelPath, levelName); - strcat(levelPath, ".LEV"); - - FilePath filePath; - if (!TFE_Paths::getFilePath(levelPath, &filePath)) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGeometry", "Cannot find level geometry '%s'.", levelName); - return false; - } - FileStream file; - if (!file.open(&filePath, Stream::MODE_READ)) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGeometry", "Cannot open level geometry '%s'.", levelName); - return false; - } - TFE_Parser parser; - size_t bufferPos = 0; -#ifdef TFE_ESPBOX - // Parse through a small window of the (still open) file instead of reading - // the whole file into memory. - if (!parser.initFromFile(&file)) { return JFALSE; } -#else - size_t len = file.getSize(); - s_buffer.resize(len); - file.readBuffer(s_buffer.data(), u32(len)); - file.close(); - parser.init(s_buffer.data(), s_buffer.size()); -#endif - parser.addCommentString("#"); - parser.convertToUpperCase(true); - - // Only use the parser "read line" functionality and otherwise read in the same was as the DOS code. - const char* line; - line = parser.readLine(bufferPos); - s32 versionMajor, versionMinor; - if (sscanf(line, " LEV %d.%d", &versionMajor, &versionMinor) != 2) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGeometry", "Cannot read version."); - return false; - } - if (versionMajor != DF_LEVEL_VERSION_MAJOR || versionMinor != DF_LEVEL_VERSION_MINOR) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGeometry", "Invalid level version %d.%d.", versionMajor, versionMinor); - return false; - } - - line = parser.readLine(bufferPos); - if (sscanf(line, " LEVELNAME %s", s_readBuffer) != 1) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGeometry", "Cannot read level name."); - return false; - } - - // This gets read here just to be overwritten later... so just ignore for now. - line = parser.readLine(bufferPos); - if (sscanf(line, " PALETTE %s", s_levelState.levelPaletteName) != 1) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGeometry", "Cannot read palette name."); - return false; - } - - level_loadPalette(); - - // Another value that is ignored. - line = parser.readLine(bufferPos); - if (sscanf(line, " MUSIC %s", s_readBuffer) != 1) - { - TFE_System::logWrite(LOG_WARNING, "level_loadGeometry", "Cannot read music name."); - } - else - { - line = parser.readLine(bufferPos); - } - - // Sky Parallax. - f32 parallax0, parallax1; - if (sscanf(line, " PARALLAX %f %f", ¶llax0, ¶llax1) != 2) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGeometry", "Cannot read parallax values."); - return false; - } - s_levelState.parallax0 = floatToFixed16(parallax0); - s_levelState.parallax1 = floatToFixed16(parallax1); - - // Number of textures used by the level. - line = parser.readLine(bufferPos); - if (sscanf(line, " TEXTURES %d", &s_levelState.textureCount) != 1) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGeometry", "Cannot read texture count."); - return false; - } - s_levelState.textures = (TextureData**)level_alloc(2 * s_levelState.textureCount * sizeof(TextureData**)); - memset(s_levelState.textures, 0, 2 * s_levelState.textureCount * sizeof(TextureData**)); - - // Load Textures. - TextureData** texture = s_levelState.textures; - TextureData** texBase = s_levelState.textures + s_levelState.textureCount; - for (s32 i = 0; i < s_levelState.textureCount; i++, texture++, texBase++) - { - line = parser.readLine(bufferPos); - char textureName[256]; - if (sscanf(line, " TEXTURE: %s ", textureName) != 1) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGeometry", "Cannot read texture name."); - *texture = bitmap_load("default.bm", 1); - } - else if (strcasecmp(textureName, "") == 0) - { - *texture = nullptr; - } - else - { - TextureData* tex = bitmap_load(textureName, 1); - if (!tex) - { - TFE_System::logWrite(LOG_WARNING, "level_loadGeometry", "Could not open '%s', using 'default.bm' instead.", textureName); - tex = bitmap_load("default.bm", 1); - if (!tex) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGeometry", "'default.bm' is not a valid BM file!"); - assert(0); - return false; - } - } - *texture = tex; - // This version never gets modified, so serialization is simpler. - *texBase = tex; - - // Setup an animated texture. - if (tex->uvWidth == BM_ANIMATED_TEXTURE) - { - bitmap_setupAnimatedTexture(texture, i); - } - } - } - - // Load Sectors. - line = parser.readLine(bufferPos); - if (sscanf(line, "NUMSECTORS %d", &s_levelState.sectorCount) != 1) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGeometry", "Cannot read sector count."); - return false; - } - - s_levelState.sectors = (RSector*)level_alloc(sizeof(RSector) * s_levelState.sectorCount); - memset(s_levelState.sectors, 0, sizeof(RSector) * s_levelState.sectorCount); - for (u32 i = 0; i < s_levelState.sectorCount; i++) - { - RSector* sector = &s_levelState.sectors[i]; - sector_clear(sector); - sector->index = i; - - // Sector ID and Name - line = parser.readLine(bufferPos); - if (sscanf(line, " SECTOR %d", §or->id) != 1) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGeometry", "Cannot read sector id."); - return false; - } - - // Allow names to have '#' in them. - line = parser.readLine(bufferPos, false, true); - // Sectors missing a name are valid but do not get "addresses" - and thus cannot be - // used by the INF system (except in the case of doors and exploding walls, see the flags section below). - char name[256]; - if (sscanf(line, " NAME %s", name) == 1) - { - // Add the sector "address" for later use by the INF system. - message_addAddress(name, 0, 0, sector); - - // Track special elevators. - if (!strcasecmp(name, "complete")) - { - s_levelState.completeSector = sector; - } - else if (!strcasecmp(name, "boss")) - { - s_levelState.bossSector = sector; - } - else if (!strcasecmp(name, "mohc")) - { - s_levelState.mohcSector = sector; - } - } - - // Lighting - line = parser.readLine(bufferPos); - s32 ambient; - if (sscanf(line, " AMBIENT %d", &ambient) != 1) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGeometry", "Cannot read sector ambient."); - return false; - } - sector->ambient = intToFixed16(ambient); - - // Floor Texture & Offset - line = parser.readLine(bufferPos); - s32 index, tmp; - f32 offsetX, offsetZ; - if (sscanf(line, " FLOOR TEXTURE %d %f %f %d", &index, &offsetX, &offsetZ, &tmp) != 4) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGeometry", "Cannot read floor texture."); - return false; - } - - sector->floorTex = nullptr; - if (index != -1) - { - sector->floorTex = &s_levelState.textures[index]; - } - sector->floorOffset.x = floatToFixed16(offsetX); - sector->floorOffset.z = floatToFixed16(offsetZ); - - // Floor Altitude - line = parser.readLine(bufferPos); - f32 alt; - if (sscanf(line, " FLOOR ALTITUDE %f", &alt) != 1) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGeometry", "Cannot read floor altitude."); - return false; - } - sector->floorHeight = floatToFixed16(alt); - - // Ceiling Texture & Offset - line = parser.readLine(bufferPos); - if (sscanf(line, " CEILING TEXTURE %d %f %f %d", &index, &offsetX, &offsetZ, &tmp) != 4) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGeometry", "Cannot read ceiling texture."); - return false; - } - sector->ceilTex = nullptr; - if (index != -1) - { - sector->ceilTex = &s_levelState.textures[index]; - } - sector->ceilOffset.x = floatToFixed16(offsetX); - sector->ceilOffset.z = floatToFixed16(offsetZ); - - // Ceiling Altitude - line = parser.readLine(bufferPos); - if (sscanf(line, " CEILING ALTITUDE %f", &alt) != 1) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGeometry", "Cannot read ceiling altitude."); - return false; - } - sector->ceilingHeight = floatToFixed16(alt); - - // Second Altitude - line = parser.readLine(bufferPos); - if (sscanf(line, " SECOND ALTITUDE %f", &alt) != 1) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGeometry", "Cannot read second altitude."); - return false; - } - sector->secHeight = floatToFixed16(alt); - - // Sector flags - line = parser.readLine(bufferPos); - if (sscanf(line, " FLAGS %d %d %d", §or->flags1, §or->flags2, §or->flags3) != 3) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGeometry", "Cannot read sector flags."); - return false; - } - // Create a door if needed. - if (sector->flags1 & SEC_FLAGS1_DOOR) - { - InfElevator* elev = inf_allocateSpecialElevator(sector, IELEV_SP_DOOR); - if (elev) { elev->flags |= INF_EFLAG_DOOR; } - } - // Create an exploding wall if needed. - if (sector->flags1 & SEC_FLAGS1_EXP_WALL) - { - inf_allocateSpecialElevator(sector, IELEV_SP_EXPLOSIVE_WALL); - } - // Add secrets. - if (sector->flags1 & SEC_FLAGS1_SECRET) - { - s_levelState.secretCount++; - } - - // Layer - line = parser.readLine(bufferPos); - if (sscanf(line, " LAYER %d", §or->layer) != 1) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGeometry", "Cannot read sector layer."); - return false; - } - s_levelState.minLayer = min(s_levelState.minLayer, sector->layer); - s_levelState.maxLayer = max(s_levelState.maxLayer, sector->layer); - - // Vertices - line = parser.readLine(bufferPos); - s32 vertexCount; - if (sscanf(line, " VERTICES %d", &vertexCount) != 1) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGeometry", "Cannot read sector vertices."); - return false; - } - const size_t vtxSize = vertexCount * sizeof(vec2_fixed); - sector->verticesWS = (vec2_fixed*)level_alloc(vtxSize); - sector->verticesVS = (vec2_fixed*)level_alloc(vtxSize); - sector->vertexCount = vertexCount; - - for (s32 v = 0; v < vertexCount; v++) - { - line = parser.readLine(bufferPos); - - f32 x, z; - sscanf(line, " X: %f Z: %f ", &x, &z); - sector->verticesWS[v].x = floatToFixed16(x); - sector->verticesWS[v].z = floatToFixed16(z); - } - - // Walls - line = parser.readLine(bufferPos); - s32 wallCount; - if (sscanf(line, " WALLS %d", &wallCount) != 1) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGeometry", "Cannot read sector walls."); - return false; - } - sector->walls = (RWall*)level_alloc(wallCount * sizeof(RWall)); - sector->wallCount = wallCount; - - for (s32 w = 0; w < wallCount; w++) - { - s32 light, flags3, flags2, flags1, walk, mirror, adjoin; - s32 signTex, unused; - s32 botTex, topTex, midTex, right, left; - f32 signOffsetZ, signOffsetX; - f32 botOffsetZ, botOffsetX; - f32 topOffsetZ, topOffsetX; - f32 midOffsetZ, midOffsetX; - - line = parser.readLine(bufferPos); - if (sscanf(line, " WALL LEFT: %d RIGHT: %d MID: %d %f %f %d TOP: %d %f %f %d BOT: %d %f %f %d SIGN: %d %f %f ADJOIN: %d MIRROR: %d WALK: %d FLAGS: %d %d %d LIGHT: %d", - &left, &right, &midTex, &midOffsetX, &midOffsetZ, &unused, &topTex, &topOffsetX, &topOffsetZ, &unused, &botTex, &botOffsetX, &botOffsetZ, &unused, - &signTex, &signOffsetX, &signOffsetZ, &adjoin, &mirror, &walk, &flags1, &flags2, &flags3, &light) != 24) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGeometry", "Cannot read wall."); - return false; - } - - RWall* wall = §or->walls[w]; - wall->id = w; - wall->sector = sector; - wall->mirrorWall = nullptr; - wall->seen = JFALSE; - wall->flags1 = flags1; - wall->flags2 = flags2; - wall->flags3 = flags3; - - vec2_fixed* leftVtxWS = §or->verticesWS[left]; - vec2_fixed* rightVtxWS = §or->verticesWS[right]; - wall->w0 = leftVtxWS; - wall->w1 = rightVtxWS; - wall->v0 = §or->verticesVS[left]; - wall->v1 = §or->verticesVS[right]; - // Store the original position 0 in the wall since it is used by the sector rotation INF. - wall->worldPos0.x = leftVtxWS->x; - wall->worldPos0.z = leftVtxWS->z; - - wall->nextSector = nullptr; - wall->mirror = -1; - if (adjoin != -1) - { - wall->nextSector = &s_levelState.sectors[adjoin]; - if (mirror == -1) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGeometry", "Adjoining wall missing mirror."); - } - wall->mirror = mirror; - } - - wall->infLink = nullptr; - wall->collisionFrame = 0; - wall->drawFrame = 0; - wall->drawFlags = 0; - wall->wallLight = intToFixed16(light); - - wall->midTex = nullptr; - if (midTex != -1) - { - wall->midTex = &s_levelState.textures[midTex]; - wall->midOffset.x = floatToFixed16(midOffsetX) * 8; - wall->midOffset.z = floatToFixed16(midOffsetZ) * 8; - } - - wall->topTex = nullptr; - if (topTex != -1) - { - wall->topTex = &s_levelState.textures[topTex]; - wall->topOffset.x = floatToFixed16(topOffsetX) * 8; - wall->topOffset.z = floatToFixed16(topOffsetZ) * 8; - } - - wall->botTex = nullptr; - if (botTex != -1) - { - wall->botTex = &s_levelState.textures[botTex]; - wall->botOffset.x = floatToFixed16(botOffsetX) * 8; - wall->botOffset.z = floatToFixed16(botOffsetZ) * 8; - } - - wall->signTex = nullptr; - if (signTex != -1) - { - wall->signTex = &s_levelState.textures[signTex]; - wall->signOffset.x = floatToFixed16(signOffsetX) * 8; - wall->signOffset.z = floatToFixed16(signOffsetZ) * 8; - } - - fixed16_16 dx = rightVtxWS->x - leftVtxWS->x; - fixed16_16 dz = rightVtxWS->z - leftVtxWS->z; - wall->angle = vec2ToAngle(dx, dz); - wall->length = vec2Length(dx, dz); - wall_computeDirectionVector(wall); - wall->texelLength = wall->length * 8; - } - } - - // Process sectors after load. - RSector* sector = s_levelState.sectors; - for (u32 i = 0; i < s_levelState.sectorCount; i++, sector++) - { - RWall* wall = sector->walls; - for (s32 w = 0; w < sector->wallCount; w++, wall++) - { - RSector* nextSector = wall->nextSector; - if (nextSector) - { - RWall* mirror = &nextSector->walls[wall->mirror]; - wall->mirrorWall = mirror; - // Both sides of a mirror should have the same lower flags3 (such as walkability). - wall->flags3 |= (mirror->flags3 & 0x0f); - mirror->flags3 |= (wall->flags3 & 0x0f); - } - } - sector_setupWallDrawFlags(sector); - sector_adjustHeights(sector, 0, 0, 0); - sector_computeBounds(sector); - // TFE: Added to support non-fixed-point rendering. - sector->dirtyFlags = SDF_ALL; - } - - // Setup the control sector. - s_levelState.controlSector->id = s_levelState.sectorCount; - s_levelState.controlSector->index = s_levelState.controlSector->id; - - return true; - } - - void level_freeAllAssets() - { - TFE_Sprite_Jedi::freeLevelData(); - TFE_Model_Jedi::freeLevelData(); - } - - JBool level_isGoalComplete(s32 goalIndex) - { - for (s32 i = 0; i < NUM_COMPLETE; i++) - { - if (s_levelState.completeNum[COMPL_TRIG][i] == goalIndex) - { - return s_levelState.complete[COMPL_TRIG][i]; - } - - if (s_levelState.completeNum[COMPL_ITEM][i] == goalIndex) - { - return s_levelState.complete[COMPL_ITEM][i]; - } - } - return JFALSE; - } - - JBool level_loadGoals(const char* levelName) - { - char levelPath[TFE_MAX_PATH]; - strcpy(levelPath, levelName); - strcat(levelPath, ".GOL"); - - FilePath filePath; - FileStream file; - if (!TFE_Paths::getFilePath(levelPath, &filePath)) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGoals", "Cannot find level goals '%s'.", levelName); - return JFALSE; - } - if (!file.open(&filePath, Stream::MODE_READ)) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGoals", "Cannot open level goals '%s'.", levelName); - return JFALSE; - } - - TFE_Parser parser; - size_t bufferPos = 0; -#ifdef TFE_ESPBOX - // Parse through a small window of the (still open) file instead of reading - // the whole file into memory. - if (!parser.initFromFile(&file)) { return JFALSE; } -#else - size_t len = file.getSize(); - s_buffer.resize(len); - file.readBuffer(s_buffer.data(), u32(len)); - file.close(); - parser.init(s_buffer.data(), s_buffer.size()); -#endif - parser.enableBlockComments(); - parser.addCommentString("//"); - parser.addCommentString("#"); - - const char* line; - line = parser.readLine(bufferPos); - s32 versionMajor, versionMinor; - if (sscanf(line, "GOL %d.%d", &versionMajor, &versionMinor) != 2) - { - TFE_System::logWrite(LOG_ERROR, "level_loadGeometry", "Cannot parse version for Goal file '%s'.", levelName); - return false; - } - - line = parser.readLine(bufferPos); - while (line) - { - s32 goalNum, typeNum; - char type[32]; - if (sscanf(line, " GOAL: %d %s %d", &goalNum, type, &typeNum) == 3) - { - if (typeNum < 0 || typeNum >= NUM_COMPLETE) - { - TFE_System::logWrite(LOG_ERROR, "Goals", "Bad item or trigger number in .GOL file"); - } - - if (typeNum >= 0 && typeNum < NUM_COMPLETE) - { - if (strcasecmp(type, "ITEM:") == 0) - { - s_levelState.completeNum[COMPL_ITEM][typeNum] = goalNum; - } - else if (strcasecmp(type, "TRIG:") == 0) - { - s_levelState.completeNum[COMPL_TRIG][typeNum] = goalNum; - } - } - } - - line = parser.readLine(bufferPos); - } - file.close(); - - return JTRUE; - } - - void ambientSoundTaskFunc(MessageType msg) - { - task_begin; - while (msg != MSG_FREE_TASK) - { - task_localBlockBegin; - AmbientSound* ambientSound = (AmbientSound*)allocator_getHead(s_levelState.ambientSounds); - while (ambientSound) - { - ambientSound->instanceId = sound_maintain(ambientSound->instanceId, ambientSound->soundId, ambientSound->pos); - ambientSound = (AmbientSound*)allocator_getNext(s_levelState.ambientSounds); - } - task_localBlockEnd; - task_yield(72); // half a second. - } - task_end; - } - - void level_addAmbientSound(SoundSourceId soundId, vec3_fixed pos) - { - if (!s_levelState.ambientSounds) - { - s_levelState.ambientSounds = allocator_create(sizeof(AmbientSound)); - s_levelIntState.ambientSoundTask = createSubTask("AmbientSound", ambientSoundTaskFunc); - } - AmbientSound* ambientSound = (AmbientSound*)allocator_newItem(s_levelState.ambientSounds); - ambientSound->soundId = soundId; - ambientSound->instanceId = 0; - ambientSound->pos = pos; - } - - void level_addSound(const char* name, u32 freq, s32 priority) - { - // TODO - } - - JBool level_loadObjects(const char* levelName, u8 difficulty) - { - char levelPath[TFE_MAX_PATH]; - strcpy(levelPath, levelName); - strcat(levelPath, ".O"); - - s32 curDiff = s32(difficulty) + 1; - - FilePath filePath; - if (!TFE_Paths::getFilePath(levelPath, &filePath)) - { - TFE_System::logWrite(LOG_ERROR, "Level Load", "Cannot find level objects '%s'.", levelName); - return false; - } - FileStream file; - if (!file.open(&filePath, Stream::MODE_READ)) - { - TFE_System::logWrite(LOG_ERROR, "Level Load", "Cannot open level objects '%s'.", levelName); - return false; - } - - TFE_Parser parser; - size_t bufferPos = 0; -#ifdef TFE_ESPBOX - // Parse through a small window of the (still open) file instead of reading - // the whole file into memory. - if (!parser.initFromFile(&file)) { return JFALSE; } -#else - size_t len = file.getSize(); - s_buffer.resize(len); - file.readBuffer(s_buffer.data(), u32(len)); - file.close(); - parser.init(s_buffer.data(), s_buffer.size()); -#endif - parser.enableBlockComments(); - parser.addCommentString("//"); - parser.addCommentString("#"); - parser.convertToUpperCase(true); - - // Only use the parser "read line" functionality and otherwise read in the same was as the DOS code. - const char* line; - line = parser.readLine(bufferPos); - s32 versionMajor, versionMinor; - if (sscanf(line, "O %d.%d", &versionMajor, &versionMinor) != 2) - { - TFE_System::logWrite(LOG_ERROR, "Level Load", "Cannot parse version for Object file '%s'.", levelName); - return false; - } - - while (line = parser.readLine(bufferPos)) - { - if (sscanf(line, "PODS %d", &s_levelIntState.podCount) == 1) - { - s_levelIntState.pods = (JediModel**)level_alloc(sizeof(JediModel*)*s_levelIntState.podCount); - for (s32 p = 0; p < s_levelIntState.podCount; p++) - { - line = parser.readLine(bufferPos); - s_levelIntState.pods[p] = nullptr; - - if (line) - { - char podName[32]; - if (sscanf(line, " POD: %s", podName) == 1) - { - s_levelIntState.pods[p] = TFE_Model_Jedi::get(podName); - if (!s_levelIntState.pods[p]) - { - s_levelIntState.pods[p] = TFE_Model_Jedi::get("default.3do"); - } - } - else - { - TFE_System::logWrite(LOG_WARNING, "Level Load", "Unknown line in pod list '%s' - skipping.", line); - } - } - } - } - else if (sscanf(line, "SPRS %d", &s_levelIntState.spriteCount) == 1) - { - s_levelIntState.sprites = (JediWax**)level_alloc(sizeof(JediWax*)*s_levelIntState.spriteCount); - for (s32 s = 0; s < s_levelIntState.spriteCount; s++) - { - line = parser.readLine(bufferPos); - s_levelIntState.sprites[s] = nullptr; - - if (line) - { - char name[32]; - if (sscanf(line, " SPR: %s ", name) == 1) - { - s_levelIntState.sprites[s] = TFE_Sprite_Jedi::getWax(name); - if (!s_levelIntState.sprites[s]) - { - s_levelIntState.sprites[s] = TFE_Sprite_Jedi::getWax("default.wax"); - } - } - else - { - TFE_System::logWrite(LOG_WARNING, "Level Load", "Unknown line in sprite list '%s' - skipping.", line); - } - } - } - } - else if (sscanf(line, "FMES %d", &s_levelIntState.fmeCount) == 1) - { - s_levelIntState.frames = (JediFrame**)level_alloc(sizeof(JediFrame*)*s_levelIntState.fmeCount); - for (s32 f = 0; f < s_levelIntState.fmeCount; f++) - { - line = parser.readLine(bufferPos); - s_levelIntState.frames[f] = nullptr; - - if (line) - { - char name[32]; - if (sscanf(line, " FME: %s ", name) == 1) - { - s_levelIntState.frames[f] = TFE_Sprite_Jedi::getFrame(name); - if (!s_levelIntState.frames[f]) - { - s_levelIntState.frames[f] = TFE_Sprite_Jedi::getFrame("default.fme"); - } - } - else - { - TFE_System::logWrite(LOG_WARNING, "Level Load", "Unknown line in fme list '%s' - skipping.", line); - } - } - } - } - else if (sscanf(line, "SOUNDS %d", &s_levelIntState.soundCount) == 1) - { - s_levelIntState.soundIds = (SoundSourceId*)level_alloc(sizeof(SoundSourceId)*s_levelIntState.soundCount); - for (s32 s = 0; s < s_levelIntState.soundCount; s++) - { - line = parser.readLine(bufferPos); - s_levelIntState.soundIds[s] = NULL_SOUND; - - if (line) - { - char name[32]; - if (sscanf(line, " SOUND: %s ", name) == 1) - { - s_levelIntState.soundIds[s] = sound_load(name, SOUND_PRIORITY_LOW2); - } - else - { - TFE_System::logWrite(LOG_WARNING, "Level Load", "Unknown line in sound list '%s' - skipping.", line); - } - } - } - } - else if (sscanf(line, "OBJECTS %d", &s_levelIntState.objectCount) == 1) - { - s32 count = s_levelIntState.objectCount; - JBool readNextLine = JTRUE; - for (s32 objIndex = 0; objIndex < count;) - { - if (readNextLine) - { - line = parser.readLine(bufferPos); - if (!line) { break; } - } - else - { - readNextLine = JTRUE; - } - - s32 objDiff = 0; - f32 x, y, z, pch, yaw, rol; - char objClass[32]; - - if (sscanf(line, " CLASS: %s DATA: %d X: %f Y: %f Z: %f PCH: %f YAW: %f ROL: %f DIFF: %d", objClass, &s_dataIndex, &x, &y, &z, &pch, &yaw, &rol, &objDiff) > 5) - { - objIndex++; - // objDiff >= 0: This difficulty and all greater. - // objDiff < 0: Less than this difficulty. - if ((objDiff >= 0 && curDiff < objDiff) || (objDiff < 0 && curDiff > TFE_Jedi::abs(objDiff))) - { - continue; - } - - vec3_fixed posWS; - posWS.x = floatToFixed16(x); - posWS.y = floatToFixed16(y); - posWS.z = floatToFixed16(z); - - // The DOS code allocated the object, tried to find the sector it is in and than frees the object - // if it doesn't fit. - // Instead TFE just reads the values and only allocates the object if it has a valid sector. - RSector* sector = sector_which3D(posWS.x, posWS.y, posWS.z); - if (!sector) - { - continue; - } - - SecObject* obj = allocateObject(); - obj->posWS = posWS; - obj->pitch = floatDegreesToFixed(pch); - obj->yaw = floatDegreesToFixed(yaw); - obj->roll = floatDegreesToFixed(rol); - - KEYWORD classType = getKeywordIndex(objClass); - switch (classType) - { - case KW_3D: - { - sector_addObject(sector, obj); - obj3d_setData(obj, s_levelIntState.pods[s_dataIndex]); - obj3d_computeTransform(obj); - } break; - case KW_SPRITE: - { - sector_addObject(sector, obj); - sprite_setData(obj, s_levelIntState.sprites[s_dataIndex]); - } break; - case KW_FRAME: - { - sector_addObject(sector, obj); - frame_setData(obj, s_levelIntState.frames[s_dataIndex]); - } break; - case KW_SPIRIT: - { - sector_addObject(sector, obj); - spirit_setData(obj); - } break; - case KW_SOUND: - { - level_addAmbientSound(s_levelIntState.soundIds[s_dataIndex], obj->posWS); - freeObject(obj); - obj = nullptr; - } break; - case KW_SAFE: - { - if (!s_levelState.safeLoc) - { - s_levelState.safeLoc = allocator_create(sizeof(Safe)); - } - Safe* safe = (Safe*)allocator_newItem(s_levelState.safeLoc); - safe->sector = sector; - safe->x = obj->posWS.x; - safe->z = obj->posWS.z; - safe->yaw = obj->yaw; - sector->flags1 |= SEC_FLAGS1_SAFESECTOR; - - freeObject(obj); - obj = nullptr; - } break; - default: - { - freeObject(obj); - obj = nullptr; - TFE_System::logWrite(LOG_ERROR, "Level Load", "Invalid Object Class: %d - Skipping Object.", classType); - continue; - } - } - - if (obj) - { - readNextLine = object_parseSeq(obj, &parser, &bufferPos); - if (obj->entityFlags & ETFLAG_PLAYER) - { - if (!s_levelState.safeLoc) - { - s_levelState.safeLoc = allocator_create(sizeof(Safe)); - } - Safe* safe = (Safe*)allocator_newItem(s_levelState.safeLoc); - safe->sector = obj->sector; - safe->x = obj->posWS.x; - safe->z = obj->posWS.z; - safe->yaw = obj->yaw; - sector->flags1 |= SEC_FLAGS1_SAFESECTOR; - } - } - } - } - } - } - - return JTRUE; - } - - Safe* level_getSafeFromSector(RSector* sector) - { - Safe* safe = (Safe*)allocator_getHead(s_levelState.safeLoc); - while (safe) - { - if (safe->sector == sector) - { - return safe; - } - safe = (Safe*)allocator_getNext(s_levelState.safeLoc); - } - return nullptr; - } - - void getSkyParallax(fixed16_16* parallax0, fixed16_16* parallax1) - { - *parallax0 = s_levelState.parallax0; - *parallax1 = s_levelState.parallax1; - } - - void setSkyParallax(fixed16_16 parallax0, fixed16_16 parallax1) - { - s_levelState.parallax0 = parallax0; - s_levelState.parallax1 = parallax1; - } - - void setObjPos_AddToSector(SecObject* obj, s32 x, s32 y, s32 z, RSector* sector) - { - obj->posWS.x = x; - obj->posWS.y = y; - obj->posWS.z = z; - sector_addObject(sector, obj); - } -} - -#ifdef TFE_ESPBOX -// The file read scratch buffer keeps the capacity of the largest file loaded; -// release it when the game is shut down (called from the platform glue). -void espbox_free_level_scratch() -{ - std::vector().swap(TFE_Jedi::s_buffer); -} -#endif diff --git a/components/darkforces/tfe/TFE_Jedi/Level/level.h b/components/darkforces/tfe/TFE_Jedi/Level/level.h deleted file mode 100644 index 68c5e487..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Level/level.h +++ /dev/null @@ -1,59 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Level -// Classic Dark Forces (DOS) Jedi derived Level structures and shared -// functionality used by systems such as collision detection, -// rendering, and INF. -// -// Copyright note: -// While the project as a whole is licensed under GPL-2.0, some of the -// code under TFE_Jedi/Level/ was derived from reverse-engineered -// code from "Dark Forces" (DOS) which is copyrighted by LucasArts. -// -// I consider the reverse-engineering to be "Fair Use" - a means of -// supporting the games on other platforms and to improve support on -// existing platforms without claiming ownership of the games -// themselves or their IPs. -// -// That said using this code in a commercial project is risky without -// permission of the original copyright holders (LucasArts). -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include -#include -#include "rsector.h" - -struct Safe -{ - RSector* sector; - fixed16_16 x; - fixed16_16 z; - s16 yaw; - s16 pad; -}; - -namespace TFE_Jedi -{ - JBool level_load(const char* levelName, u8 difficulty); - void level_clearData(); - void level_freeAllAssets(); - - void level_serialize(Stream* stream); - - void setObjPos_AddToSector(SecObject* obj, s32 x, s32 y, s32 z, RSector* sector); - void getSkyParallax(fixed16_16* parallax0, fixed16_16* parallax1); - void setSkyParallax(fixed16_16 parallax0, fixed16_16 parallax1); - - Safe* level_getSafeFromSector(RSector* sector); - JBool level_isGoalComplete(s32 goalIndex); - - void level_addSound(const char* name, u32 freq, s32 priority); - void level_loadPalette(); - - void level_updateSecretPercent(); - - void ambientSoundTaskFunc(MessageType msg); -} diff --git a/components/darkforces/tfe/TFE_Jedi/Level/levelData.cpp b/components/darkforces/tfe/TFE_Jedi/Level/levelData.cpp deleted file mode 100644 index 19f8999a..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Level/levelData.cpp +++ /dev/null @@ -1,478 +0,0 @@ -#include -#include - -#include "levelData.h" -#include "rsector.h" -#include "rwall.h" -#include "robjData.h" -#include -#include -#include -#include - -// TODO: coupling between Dark Forces and Jedi. -using namespace TFE_DarkForces; -#include - -namespace TFE_DarkForces -{ - extern s32 s_secretsFound; - extern s32 s_secretsPercent; -} - -namespace TFE_Jedi -{ - enum LevelStateVersion : u32 - { - LevelState_InitVersion = 1, - LevelState_CurVersion = LevelState_InitVersion, - }; - enum LevelTextureType : u32 - { - LEVTEX_TYPE_TEX = 1, - LEVTEX_TYPE_ANM = 2, - }; - - LevelState s_levelState = {}; - LevelInternalState s_levelIntState = {}; - - void level_serializeSector(Stream* stream, RSector* sector); - void level_serializeSafe(Stream* stream, Safe* safe); - void level_serializeAmbientSound(Stream* stream, AmbientSound* sound); - void level_serializeWall(Stream* stream, RWall* wall, RSector* sector); - void level_serializeTextureList(Stream* stream); - - ///////////////////////////////////////////// - // Implementation - ///////////////////////////////////////////// - void level_clearData() - { - s_levelState = { 0 }; - s_levelIntState = { 0 }; - - s_levelState.controlSector = (RSector*)level_alloc(sizeof(RSector)); - sector_clear(s_levelState.controlSector); - - objData_clear(); - } - - void level_serializeFixupMirrors() - { - RSector* sector = s_levelState.sectors; - for (u32 s = 0; s < s_levelState.sectorCount; s++, sector++) - { - s32 wallCount = sector->wallCount; - RWall* wall = sector->walls; - for (s32 w = 0; w < wallCount; w++, wall++) - { - if (wall->nextSector && wall->mirror >= 0) - { - wall->mirrorWall = &wall->nextSector->walls[wall->mirror]; - } - } - } - } - - void level_serializePalette(Stream* stream) - { - u8 length = 0; - if (serialization_getMode() == SMODE_WRITE) - { - length = (u8)strlen(s_levelState.levelPaletteName); - } - SERIALIZE(SaveVersionInit, length, 0); - SERIALIZE_BUF(SaveVersionInit, s_levelState.levelPaletteName, length); - s_levelState.levelPaletteName[length] = 0; - - if (serialization_getMode() == SMODE_READ) - { - level_loadPalette(); - } - } - - void level_updateSecretPercent() - { - if (s_levelState.secretCount) - { - // 100.0 * found / count - fixed16_16 percentage = mul16(FIXED(100), div16(intToFixed16(s_secretsFound), intToFixed16(s_levelState.secretCount))); - s_secretsPercent = floor16(percentage); - } - else - { - s_secretsPercent = 100; - } - s_secretsPercent = max(0, min(100, s_secretsPercent)); - } - - void level_serialize(Stream* stream) - { - bool debug = serialization_getMode() == SMODE_WRITE; - - if (serialization_getMode() == SMODE_READ) - { - level_clearData(); - } - SERIALIZE_VERSION(LevelState_CurVersion); - - SERIALIZE(LevelState_InitVersion, s_levelState.minLayer, 0); - SERIALIZE(LevelState_InitVersion, s_levelState.maxLayer, 0); - SERIALIZE(LevelState_InitVersion, s_levelState.secretCount, 0); - SERIALIZE(LevelState_InitVersion, s_levelState.sectorCount, 0); - SERIALIZE(LevelState_InitVersion, s_levelState.parallax0, 0); - SERIALIZE(LevelState_InitVersion, s_levelState.parallax1, 0); - SERIALIZE(LevelState_InitVersion, TFE_DarkForces::s_secretsFound, 0); - - SERIALIZE_BUF(LevelState_InitVersion, s_levelState.complete, sizeof(JBool) * 2 * NUM_COMPLETE); - SERIALIZE_BUF(LevelState_InitVersion, s_levelState.completeNum, sizeof(s32) * 2 * NUM_COMPLETE); - - ///////////////////////////////////// - // Serialize asset names - ///////////////////////////////////// - level_serializePalette(stream); - bitmap_serializeLevelTextures(stream); - TFE_Sprite_Jedi::sprite_serializeSpritesAndFrames(stream); - TFE_Model_Jedi::serializeModels(stream); - - // This is needed because level textures are pointers to the list itself, rather than the texture. - level_serializeTextureList(stream); - - if (serialization_getMode() == SMODE_READ) - { - s_levelState.sectors = (RSector*)level_alloc(sizeof(RSector) * s_levelState.sectorCount); - s_levelState.controlSector->id = s_levelState.sectorCount; - s_levelState.controlSector->index = s_levelState.controlSector->id; - - level_updateSecretPercent(); - } - RSector* sector = s_levelState.sectors; - for (u32 s = 0; s < s_levelState.sectorCount; s++, sector++) - { - level_serializeSector(stream, sector); - } - - serialization_serializeSectorPtr(stream, LevelState_InitVersion, s_levelState.bossSector); - serialization_serializeSectorPtr(stream, LevelState_InitVersion, s_levelState.mohcSector); - serialization_serializeSectorPtr(stream, LevelState_InitVersion, s_levelState.completeSector); - - // The control sector is just a dummy sector, no need to save anything. - // Sound emitter isn't actually used. - - if (serialization_getMode() == SMODE_WRITE) - { - allocator_saveIter(s_levelState.safeLoc); - s32 safeCount = allocator_getCount(s_levelState.safeLoc); - SERIALIZE(LevelState_InitVersion, safeCount, 0); - Safe* safe = (Safe*)allocator_getHead(s_levelState.safeLoc); - while (safe) - { - level_serializeSafe(stream, safe); - safe = (Safe*)allocator_getNext(s_levelState.safeLoc); - } - allocator_restoreIter(s_levelState.safeLoc); - - allocator_saveIter(s_levelState.ambientSounds); - s32 ambientSoundCount = allocator_getCount(s_levelState.ambientSounds); - SERIALIZE(LevelState_InitVersion, ambientSoundCount, 0); - AmbientSound* sound = (AmbientSound*)allocator_getHead(s_levelState.ambientSounds); - while (sound) - { - level_serializeAmbientSound(stream, sound); - sound = (AmbientSound*)allocator_getNext(s_levelState.ambientSounds); - } - allocator_restoreIter(s_levelState.ambientSounds); - } - else - { - s32 safeCount; - SERIALIZE(LevelState_InitVersion, safeCount, 0); - s_levelState.safeLoc = nullptr; - if (safeCount) - { - s_levelState.safeLoc = allocator_create(sizeof(Safe)); - for (s32 s = 0; s < safeCount; s++) - { - Safe* safe = (Safe*)allocator_newItem(s_levelState.safeLoc); - level_serializeSafe(stream, safe); - } - } - - s32 ambientSoundCount; - SERIALIZE(LevelState_InitVersion, ambientSoundCount, 0); - s_levelState.ambientSounds = nullptr; - if (ambientSoundCount) - { - s_levelState.ambientSounds = allocator_create(sizeof(AmbientSound)); - for (s32 s = 0; s < ambientSoundCount; s++) - { - AmbientSound* sound = (AmbientSound*)allocator_newItem(s_levelState.ambientSounds); - level_serializeAmbientSound(stream, sound); - } - if (!s_levelIntState.ambientSoundTask) - { - s_levelIntState.ambientSoundTask = createSubTask("AmbientSound", ambientSoundTaskFunc); - } - } - - level_serializeFixupMirrors(); - } - - // Serialize objects. - objData_serialize(stream); - } - - ///////////////////////////////////////////// - // Internal - Serialize - ///////////////////////////////////////////// - void level_serializeTextureList(Stream* stream) - { - const bool read = serialization_getMode() == SMODE_READ; - - SERIALIZE(LevelState_InitVersion, s_levelState.textureCount, 0); - if (read) - { - s_levelState.textures = (TextureData**)level_alloc(2 * s_levelState.textureCount * sizeof(TextureData**)); - } - TextureData** textures = s_levelState.textures; - TextureData** texBase = textures + s_levelState.textureCount; - for (s32 i = 0; i < s_levelState.textureCount; i++) - { - serialization_serializeTexturePtr(stream, LevelState_InitVersion, texBase[i]); - // texBase[] remains unmodified for serialization, whereas textures[] can be modified with animated textures. - if (read) - { - textures[i] = texBase[i]; - } - if (read && s_levelState.textures[i] && s_levelState.textures[i]->uvWidth == BM_ANIMATED_TEXTURE) - { - bitmap_setupAnimatedTexture(&s_levelState.textures[i], i); - } - } - } - - void level_serializeTexturePointer(Stream* stream, TextureData**& texData) - { - u32 texIndex = 0u; - if (serialization_getMode() == SMODE_WRITE && texData && *texData) - { - std::ptrdiff_t offset = (std::ptrdiff_t(texData) - std::ptrdiff_t(s_levelState.textures)) / (std::ptrdiff_t)sizeof(TextureData**); - if ((*texData)->animIndex >= 0) - { - const u8 frameIndex = (*texData)->frameIdx < 0 ? 0xfff : (u8)(*texData)->frameIdx; - texIndex = LEVTEX_TYPE_ANM | (frameIndex << 4) | ((u32)(*texData)->animIndex << 12u); - } - else - { - if (offset >= 0 && offset < s_levelState.textureCount) - { - texIndex = LEVTEX_TYPE_TEX | ((u32)offset << 12u); - } - assert(texIndex && s_levelState.textures[offset] == *texData); - } - } - SERIALIZE(LevelState_InitVersion, texIndex, 0u); - - if (serialization_getMode() == SMODE_READ) - { - s32 index = texIndex >> 12; - s32 frameIdx = (texIndex >> 4) & 255; - if (frameIdx == 0xff) { frameIdx = -1; } - - assert(index >= 0 && index < s_levelState.textureCount); - texData = (texIndex == 0) ? nullptr : &s_levelState.textures[index]; - if (texData && *texData) - { - if ((texIndex & 3) == LEVTEX_TYPE_ANM && frameIdx >= 0) - { - AnimatedTexture* anim = (AnimatedTexture*)(*texData)->animPtr; - if (anim) - { - (*texData) = anim->frameList[frameIdx]; - } - } - (*texData)->animIndex = ((texIndex & 3) == LEVTEX_TYPE_ANM) ? index : -1; - (*texData)->frameIdx = frameIdx; - } - } - } - - void level_serializeSector(Stream* stream, RSector* sector) - { - if (serialization_getMode() == SMODE_READ) - { - sector->self = sector; - } - SERIALIZE(LevelState_InitVersion, sector->id, 0); - SERIALIZE(LevelState_InitVersion, sector->index, 0); - SERIALIZE(LevelState_InitVersion, sector->prevDrawFrame, 0); - SERIALIZE(LevelState_InitVersion, sector->prevDrawFrame2, 0); - - SERIALIZE(LevelState_InitVersion, sector->vertexCount, 0); - const size_t vtxSize = sector->vertexCount * sizeof(vec2_fixed); - if (serialization_getMode() == SMODE_READ) - { - sector->verticesWS = (vec2_fixed*)level_alloc(vtxSize); - sector->verticesVS = (vec2_fixed*)level_alloc(vtxSize); - } - SERIALIZE_BUF(LevelState_InitVersion, sector->verticesWS, u32(vtxSize)); - // view space vertices don't need to be serialized. - - SERIALIZE(LevelState_InitVersion, sector->wallCount, 0); - if (serialization_getMode() == SMODE_READ) - { - sector->walls = (RWall*)level_alloc(sector->wallCount * sizeof(RWall)); - } - RWall* wall = sector->walls; - for (s32 w = 0; w < sector->wallCount; w++, wall++) - { - level_serializeWall(stream, wall, sector); - } - - SERIALIZE(LevelState_InitVersion, sector->floorHeight, 0); - SERIALIZE(LevelState_InitVersion, sector->ceilingHeight, 0); - SERIALIZE(LevelState_InitVersion, sector->secHeight, 0); - SERIALIZE(LevelState_InitVersion, sector->ambient, 0); - - SERIALIZE(LevelState_InitVersion, sector->colFloorHeight, 0); - SERIALIZE(LevelState_InitVersion, sector->colCeilHeight, 0); - SERIALIZE(LevelState_InitVersion, sector->colSecHeight, 0); - SERIALIZE(LevelState_InitVersion, sector->colSecCeilHeight, 0); - - // infLink will be set when the INF system is serialized. - if (serialization_getMode() == SMODE_READ) - { - sector->infLink = nullptr; - } - - level_serializeTexturePointer(stream, sector->floorTex); - level_serializeTexturePointer(stream, sector->ceilTex); - - const vec2_fixed def = { 0,0 }; - SERIALIZE(LevelState_InitVersion, sector->floorOffset, def); - SERIALIZE(LevelState_InitVersion, sector->ceilOffset, def); - - // Objects are handled seperately and added to the sector later, so just initialize the object data. - if (serialization_getMode() == SMODE_READ) - { - sector->objectCount = 0; - sector->objectCapacity = 0; - sector->objectList = nullptr; - } - - SERIALIZE(LevelState_InitVersion, sector->collisionFrame, 0); - SERIALIZE(LevelState_InitVersion, sector->startWall, 0); - SERIALIZE(LevelState_InitVersion, sector->drawWallCnt, 0); - SERIALIZE(LevelState_InitVersion, sector->flags1, 0); - SERIALIZE(LevelState_InitVersion, sector->flags2, 0); - SERIALIZE(LevelState_InitVersion, sector->flags3, 0); - SERIALIZE(LevelState_InitVersion, sector->layer, 0); - SERIALIZE(LevelState_InitVersion, sector->boundsMin, def); - SERIALIZE(LevelState_InitVersion, sector->boundsMax, def); - - // dirty flags will be set on deserialization. - if (serialization_getMode() == SMODE_READ) - { - sector->dirtyFlags = SDF_ALL; - } - } - - void level_serializeSafe(Stream* stream, Safe* safe) - { - serialization_serializeSectorPtr(stream, LevelState_InitVersion, safe->sector); - SERIALIZE(LevelState_InitVersion, safe->x, 0); - SERIALIZE(LevelState_InitVersion, safe->z, 0); - SERIALIZE(LevelState_InitVersion, safe->yaw, 0); - SERIALIZE(LevelState_InitVersion, safe->pad, 0); // for padding. - } - - void level_serializeAmbientSound(Stream* stream, AmbientSound* sound) - { - serialization_serializeDfSound(stream, LevelState_InitVersion, &sound->soundId); - if (serialization_getMode() == SMODE_READ) - { - sound->instanceId = 0; - } - const vec3_fixed def = { 0,0,0 }; - SERIALIZE(LevelState_InitVersion, sound->pos, def); - } - - void level_serializeWall(Stream* stream, RWall* wall, RSector* sector) - { - SERIALIZE(LevelState_InitVersion, wall->id, 0); - SERIALIZE(LevelState_InitVersion, wall->seen, 0); - SERIALIZE(LevelState_InitVersion, wall->visible, 0); - - serialization_serializeSectorPtr(stream, LevelState_InitVersion, wall->sector); - serialization_serializeSectorPtr(stream, LevelState_InitVersion, wall->nextSector); - - // mirrorWall will be computed from mirror. - SERIALIZE(LevelState_InitVersion, wall->drawFlags, 0); - SERIALIZE(LevelState_InitVersion, wall->mirror, -1); - if (serialization_getMode() == SMODE_READ) - { - wall->mirrorWall = nullptr; - // Fix-up next sector if needed. - if (wall->mirror < 0 && wall->nextSector) - { - TFE_System::logWrite(LOG_WARNING, "LevelData", - "Wall %d of sector %d has 'nextSector = %d' but no 'mirror' - clearing out the next sector.", wall->id, sector->id, wall->nextSector->id); - wall->nextSector = nullptr; - } - } - - // worldspace vertices. - s32 i0, i1; - if (serialization_getMode() == SMODE_WRITE) - { - i0 = PTR_INDEX_S32(wall->w0, sector->verticesWS, sizeof(vec2_fixed)); - i1 = PTR_INDEX_S32(wall->w1, sector->verticesWS, sizeof(vec2_fixed)); - SERIALIZE(LevelState_InitVersion, i0, 0); - SERIALIZE(LevelState_InitVersion, i1, 0); - // viewspace vertices need not be saved. - } - else - { - SERIALIZE(LevelState_InitVersion, i0, 0); - SERIALIZE(LevelState_InitVersion, i1, 0); - wall->w0 = §or->verticesWS[i0]; - wall->w1 = §or->verticesWS[i1]; - wall->v0 = §or->verticesVS[i0]; - wall->v1 = §or->verticesVS[i1]; - } - - level_serializeTexturePointer(stream, wall->topTex); - level_serializeTexturePointer(stream, wall->midTex); - level_serializeTexturePointer(stream, wall->botTex); - level_serializeTexturePointer(stream, wall->signTex); - - SERIALIZE(LevelState_InitVersion, wall->texelLength, 0); - SERIALIZE(LevelState_InitVersion, wall->topTexelHeight, 0); - SERIALIZE(LevelState_InitVersion, wall->midTexelHeight, 0); - SERIALIZE(LevelState_InitVersion, wall->botTexelHeight, 0); - - const vec2_fixed def = { 0, 0 }; - SERIALIZE(LevelState_InitVersion, wall->topOffset, def); - SERIALIZE(LevelState_InitVersion, wall->midOffset, def); - SERIALIZE(LevelState_InitVersion, wall->botOffset, def); - SERIALIZE(LevelState_InitVersion, wall->signOffset, def); - - SERIALIZE(LevelState_InitVersion, wall->wallDir, def); - SERIALIZE(LevelState_InitVersion, wall->length, 0); - SERIALIZE(LevelState_InitVersion, wall->collisionFrame, 0); - SERIALIZE(LevelState_InitVersion, wall->drawFrame, 0); - - // infLink will be filled in when serializing the INF system. - if (serialization_getMode() == SMODE_READ) - { - wall->infLink = nullptr; - } - - SERIALIZE(LevelState_InitVersion, wall->flags1, 0); - SERIALIZE(LevelState_InitVersion, wall->flags2, 0); - SERIALIZE(LevelState_InitVersion, wall->flags3, 0); - - SERIALIZE(LevelState_InitVersion, wall->worldPos0, def); - SERIALIZE(LevelState_InitVersion, wall->wallLight, 0); - SERIALIZE(LevelState_InitVersion, wall->angle, 0); - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Level/levelData.h b/components/darkforces/tfe/TFE_Jedi/Level/levelData.h deleted file mode 100644 index 0ff97aa4..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Level/levelData.h +++ /dev/null @@ -1,105 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Level -// Classic Dark Forces (DOS) Jedi derived Level structures and shared -// functionality used by systems such as collision detection, -// rendering, and INF. -// -// Copyright note: -// While the project as a whole is licensed under GPL-2.0, some of the -// code under TFE_Jedi/Level/ was derived from reverse-engineered -// code from "Dark Forces" (DOS) which is copyrighted by LucasArts. -// -// I consider the reverse-engineering to be "Fair Use" - a means of -// supporting the games on other platforms and to improve support on -// existing platforms without claiming ownership of the games -// themselves or their IPs. -// -// That said using this code in a commercial project is risky without -// permission of the original copyright holders (LucasArts). -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include -#include -#include -#include "rsector.h" - -struct Task; - -namespace TFE_Jedi -{ - enum GoalConstants - { - COMPL_TRIG = 0, - COMPL_ITEM = 1, - NUM_COMPLETE = 10, - }; - - struct AmbientSound - { - SoundSourceId soundId; - SoundEffectId instanceId; - vec3_fixed pos; - }; - - // Serializable State. - struct LevelState - { - // Level Data. - s32 minLayer = 0; - s32 maxLayer = 0; - s32 secretCount = 0; - u32 sectorCount = 0; - s32 textureCount = 0; - fixed16_16 parallax0 = 0; - fixed16_16 parallax1 = 0; - RSector* sectors = nullptr; - - // Goals - JBool complete[2][NUM_COMPLETE] = { JFALSE }; - s32 completeNum[2][NUM_COMPLETE] = { 0 }; - - // Texture list - TextureData** textures = nullptr; - - // Gameplay sector pointers. - RSector* bossSector = nullptr; - RSector* mohcSector = nullptr; - RSector* controlSector = nullptr; - RSector* completeSector = nullptr; - - // Special level objects. - Allocator* soundEmitters = nullptr; - Allocator* safeLoc = nullptr; - Allocator* ambientSounds = nullptr; - - // TFE - char levelPaletteName[256]; - }; - - // State that should be reset. - struct LevelInternalState - { - s32 podCount = 0; - s32 spriteCount = 0; - s32 fmeCount = 0; - s32 soundCount = 0; - s32 objectCount = 0; - - JediModel** pods = nullptr; - JediWax** sprites = nullptr; - JediFrame** frames = nullptr; - SoundSourceId* soundIds = nullptr; - - Task* ambientSoundTask = nullptr; - Task* soundEmitterTask = nullptr; - }; - - // Serializable level state. - extern LevelState s_levelState; - // Internal level state. - extern LevelInternalState s_levelIntState; -} diff --git a/components/darkforces/tfe/TFE_Jedi/Level/levelTextures.cpp b/components/darkforces/tfe/TFE_Jedi/Level/levelTextures.cpp deleted file mode 100644 index f4e35d1d..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Level/levelTextures.cpp +++ /dev/null @@ -1,103 +0,0 @@ -#include -#include - -#include "level.h" -#include "levelTextures.h" -#include "rwall.h" -#include "rtexture.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace TFE_Jedi -{ - bool level_getLevelTextures(TextureInfoList& textures, AssetPool pool) - { - s32 textureCount = 0; - TextureData** levelTextures = bitmap_getTextures(&textureCount, pool); - for (s32 i = 0; i < textureCount; i++) - { - TextureInfo texInfo = {}; - if (levelTextures[i] && levelTextures[i]->uvWidth != BM_ANIMATED_TEXTURE) - { - texInfo.type = TEXINFO_DF_TEXTURE_DATA; - texInfo.texData = levelTextures[i]; - textures.push_back(texInfo); - } - } - - // Insert animated textures. - if (pool == POOL_LEVEL) - { - Allocator* animTextures = bitmap_getAnimatedTextures(); - AnimatedTexture* animTex = (AnimatedTexture*)allocator_getHead(animTextures); - while (animTex) - { - TextureInfo texInfo = {}; - - texInfo.type = TEXINFO_DF_ANIM_TEX; - texInfo.animTex = animTex; - textures.push_back(texInfo); - animTex = (AnimatedTexture*)allocator_getNext(animTextures); - } - } - - return !textures.empty(); - } - - bool level_getObjectTextures(TextureInfoList& textures, AssetPool pool) - { - // Insert sprite frames. - const std::vector& waxList = TFE_Sprite_Jedi::getWaxList(pool); - const size_t waxCount = waxList.size(); - JediWax*const* wax = waxList.data(); - for (size_t i = 0; i < waxCount; i++) - { - for (s32 animId = 0; animId < wax[i]->animCount; animId++) - { - WaxAnim* anim = WAX_AnimPtr(wax[i], animId); - if (!anim) { continue; } - for (s32 v = 0; v < WAX_MAX_VIEWS; v++) - { - WaxView* view = WAX_ViewPtr(wax[i], anim, v); - if (!view) { continue; } - for (s32 f = 0; f < anim->frameCount; f++) - { - TextureInfo texInfo = {}; - texInfo.type = TEXINFO_DF_WAX_CELL; - texInfo.frame = WAX_FramePtr(wax[i], view, f); - texInfo.basePtr = wax[i]; - textures.push_back(texInfo); - } - } - } - } - - // Insert frames. - const std::vector& frameList = TFE_Sprite_Jedi::getFrameList(pool); - const size_t frameCount = frameList.size(); - JediFrame*const* frame = frameList.data(); - for (size_t i = 0; i < frameCount; i++) - { - TextureInfo texInfo = {}; - texInfo.type = TEXINFO_DF_WAX_CELL; - texInfo.frame = frame[i]; - texInfo.basePtr = frame[i]; - textures.push_back(texInfo); - } - - return !textures.empty(); - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Level/levelTextures.h b/components/darkforces/tfe/TFE_Jedi/Level/levelTextures.h deleted file mode 100644 index 3bced882..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Level/levelTextures.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Level -// Functionality to get level geometry and object textures for use by -// the GPU renderer(s). -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include -#include -#include "rsector.h" - -namespace TFE_Jedi -{ - bool level_getLevelTextures(TextureInfoList& textures, AssetPool pool); - bool level_getObjectTextures(TextureInfoList& textures, AssetPool pool); -} diff --git a/components/darkforces/tfe/TFE_Jedi/Level/rfont.cpp b/components/darkforces/tfe/TFE_Jedi/Level/rfont.cpp deleted file mode 100644 index c15c13c6..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Level/rfont.cpp +++ /dev/null @@ -1,103 +0,0 @@ -#include - -#include "rfont.h" -#include "rtexture.h" -#include -#include -#include - -namespace TFE_Jedi -{ - enum FontConstants - { - FNT_VERSION = 0x15, - }; - - s32 font_getStringLength(Font* font, const char *str) - { - if (!font) { return 0; } - - char c = *str; - s32 len = 0; - while (c) - { - if (c <= 32) - { - len += font->width; - } - else - { - s32 index = s32(c) - s32(font->minChar); - len += font->glyphs[index].width + font->horzSpacing; - } - str++; - c = *str; - } - return len; - } - - Font* font_load(FilePath* filePath) - { - FileStream file; - if (!file.open(filePath, Stream::MODE_READ)) - { - TFE_System::logWrite(LOG_ERROR, "Font", "Failed to open font."); - return nullptr; - } - - char hdr[4]; - file.readBuffer(hdr, 3); - hdr[3] = 0; - if (strncmp(hdr, "FNT", 3)) - { - file.close(); - TFE_System::logWrite(LOG_ERROR, "Font", "Invalid font header - '%s'", hdr); - return nullptr; - } - - u8 version; - file.read(&version); - if (version != FNT_VERSION) - { - file.close(); - TFE_System::logWrite(LOG_ERROR, "Font", "Invalid font version: %d, should be %d", version, FNT_VERSION); - return nullptr; - } - - Font* font = (Font*)game_alloc(sizeof(Font)); - file.read(&font->vertSpacing); - file.read(&font->horzSpacing); - file.read(&font->width); - file.read(&font->height); - file.read(&font->minChar); - file.read(&font->maxChar); - - // Unused space. - u8 buffer[22]; - file.readBuffer(buffer, 22); - - s32 glyphCount = s32(font->maxChar) - s32(font->minChar) + 1; - font->glyphs = (TextureData*)game_alloc(sizeof(TextureData) * glyphCount); - memset(font->glyphs, 0, sizeof(TextureData) * glyphCount); - - TextureData* glyph = font->glyphs; - for (s32 i = 0; i < glyphCount; i++, glyph++) - { - u8 width; - file.read(&width); - - s32 pixelCount = width * font->vertSpacing; - glyph->image = (u8*)game_alloc(pixelCount); - file.readBuffer(glyph->image, pixelCount); - - glyph->width = width; - glyph->height = font->vertSpacing; - glyph->dataSize = pixelCount; - glyph->flags = 9; - glyph->compressed = 0; - } - file.close(); - - return font; - } -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Level/rfont.h b/components/darkforces/tfe/TFE_Jedi/Level/rfont.h deleted file mode 100644 index 3b8d4299..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Level/rfont.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include - -struct Font -{ - TextureData* glyphs; - u8 minChar; - u8 maxChar; - u8 vertSpacing; - u8 horzSpacing; - u8 width; - u8 height; - u8 pad[2]; -}; - -namespace TFE_Jedi -{ - Font* font_load(FilePath* filePath); - s32 font_getStringLength(Font* font, const char *str); -} diff --git a/components/darkforces/tfe/TFE_Jedi/Level/robjData.cpp b/components/darkforces/tfe/TFE_Jedi/Level/robjData.cpp deleted file mode 100644 index d01813dd..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Level/robjData.cpp +++ /dev/null @@ -1,262 +0,0 @@ -#include "robjData.h" -#include "robject.h" -#include "level.h" -#include -#include -#include -#include -#include -#include -#include -#include - -// Required for serialization. -namespace TFE_DarkForces -{ - extern void logic_serialize(Logic*& logic, Stream* stream); -} - -namespace TFE_Jedi -{ - // Serialization - Keep a global list of objects... - struct SectorObjectData - { - ChunkedArray* objectList = nullptr; - }; - static SectorObjectData s_objData = {}; - - void objData_clear() - { - s_objData = {}; - } - - SecObject* objData_allocFromArray() - { - if (!s_objData.objectList) - { - s_objData.objectList = TFE_Memory::createChunkedArray(sizeof(SecObject), 256, 1, s_levelRegion); - } - return (SecObject*)TFE_Memory::allocFromChunkedArray(s_objData.objectList); - } - - void objData_freeToArray(SecObject* obj) - { - if (obj && s_objData.objectList) - { - obj->self = nullptr; - TFE_Memory::freeToChunkedArray(s_objData.objectList, obj); - } - } - - void objData_serializeObject(SecObject* obj, Stream* stream) - { - if (serialization_getMode() == SMODE_READ) - { - obj->self = obj; - } - else - { - assert(obj && obj->sector && obj->sector->id == obj->sector->index); - } - - const vec3_fixed def = { 0 }; - SERIALIZE(ObjState_InitVersion, obj->type, ObjectType::OBJ_TYPE_SPIRIT); - SERIALIZE(ObjState_InitVersion, obj->entityFlags, 0); - SERIALIZE(ObjState_InitVersion, obj->posWS, def); - // obj->posVS is derived at runtime. - - SERIALIZE(ObjState_InitVersion, obj->worldWidth, -1); - SERIALIZE(ObjState_InitVersion, obj->worldHeight, -1); - if (obj->type == OBJ_TYPE_3D) - { - SERIALIZE_BUF(ObjState_InitVersion, obj->transform, TFE_ARRAYSIZE(obj->transform) * sizeof(fixed16_16)); - } - else if (serialization_getMode() == SMODE_READ) - { - memset(obj->transform, 0, TFE_ARRAYSIZE(obj->transform) * sizeof(fixed16_16)); - } - - // Handle object render data - if (obj->type == OBJ_TYPE_SPRITE) - { - serialization_serializeWaxPtr(stream, ObjState_InitVersion, obj->wax); - } - else if (obj->type == OBJ_TYPE_3D) - { - serialization_serialize3doPtr(stream, ObjState_InitVersion, obj->model); - } - else if (obj->type == OBJ_TYPE_FRAME) - { - serialization_serializeFramePtr(stream, ObjState_InitVersion, obj->fme); - } - else if (serialization_getMode() == SMODE_READ) - { - obj->ptr = nullptr; - } - - SERIALIZE(ObjState_InitVersion, obj->frame, 0); - SERIALIZE(ObjState_InitVersion, obj->anim, 0); - serialization_serializeSectorPtr(stream, ObjState_InitVersion, obj->sector); - assert(obj && obj->sector && obj->sector->id == obj->sector->index); - - SERIALIZE(ObjState_InitVersion, obj->flags, 0); - SERIALIZE(ObjState_InitVersion, obj->pitch, 0); - SERIALIZE(ObjState_InitVersion, obj->yaw, 0); - SERIALIZE(ObjState_InitVersion, obj->roll, 0); - - // obj->index will be reset once the object is re-added to its sector. - if (serialization_getMode() == SMODE_READ) - { - obj->index = -1; - } - - SERIALIZE(ObjState_InitVersion, obj->serializeIndex, 0); - } - - SecObject* objData_getObjectBySerializationId(u32 id) - { - SecObject* obj = (SecObject*)TFE_Memory::chunkedArrayGet(s_objData.objectList, id); - // The object may have been deleted later. - return (obj && obj->serializeIndex == id) ? obj : nullptr; - } - - SecObject* objData_getObjectBySerializationId_NoValidation(u32 id) - { - return (SecObject*)TFE_Memory::chunkedArrayGet(s_objData.objectList, id); - } - - void objData_serialize(Stream* stream) - { - SERIALIZE_VERSION(ObjState_CurVersion); - - u32 writeCount = 0; - if (serialization_getMode() == SMODE_WRITE) - { - ChunkedArray* list = s_objData.objectList; - if (!list || TFE_Memory::chunkedArraySize(list) < 1) - { - // No objects, so just write out 0 for the count. - SERIALIZE(ObjState_InitVersion, writeCount, 0); - return; - } - - // Assign IDs - const u32 size = TFE_Memory::chunkedArraySize(list); - for (u32 i = 0; i < size; i++) - { - SecObject* obj = (SecObject*)TFE_Memory::chunkedArrayGet(list, i); - - // Skip deleted objects. - if (!obj->self) { continue; } - obj->serializeIndex = writeCount; // So downstream serialization passes have an object ID to use. - writeCount++; - } - SERIALIZE(ObjState_InitVersion, writeCount, 0); - - // Write objects. - for (u32 i = 0; i < size; i++) - { - SecObject* obj = (SecObject*)TFE_Memory::chunkedArrayGet(list, i); - - // Skip deleted objects. - if (!obj->self) { continue; } - // Write the object to the stream. - objData_serializeObject(obj, stream); - - u32 logicCount = allocator_getCount((Allocator*)obj->logic); - SERIALIZE(ObjState_InitVersion, logicCount, 0); - if (!logicCount) { continue; } - - allocator_saveIter((Allocator*)obj->logic); - Logic** logicList = (Logic**)allocator_getHead((Allocator*)obj->logic); - while (logicList) - { - Logic* logic = *logicList; - if (logic) - { - TFE_DarkForces::logic_serialize(logic, obj, stream); - } - else - { - s32 invalidLogic = -1; - SERIALIZE(ObjState_InitVersion, invalidLogic, -1); - } - logicList = (Logic**)allocator_getNext((Allocator*)obj->logic); - } - allocator_restoreIter((Allocator*)obj->logic); - } - } - else if (serialization_getMode() == SMODE_READ) - { - SERIALIZE(ObjState_InitVersion, writeCount, 0); - if (!s_objData.objectList) - { - const u32 initChunkCount = max(u32(1), u32((writeCount + 255u) >> 8u)); - s_objData.objectList = TFE_Memory::createChunkedArray(sizeof(SecObject), 256, initChunkCount, s_levelRegion); - } - else - { - TFE_Memory::chunkedArrayClear(s_objData.objectList); - } - - for (u32 i = 0; i < writeCount; i++) - { - SecObject* obj = (SecObject*)TFE_Memory::allocFromChunkedArray(s_objData.objectList); - objData_serializeObject(obj, stream); - - if (obj->sector) - { - sector_addObjectDirect(obj->sector, obj); - } - else - { - TFE_System::logWrite(LOG_ERROR, "Game Load", "Object [%d] has no sector.", i); - } - - u32 logicCount; - SERIALIZE(ObjState_InitVersion, logicCount, 0); - obj->logic = nullptr; - obj->projectileLogic = nullptr; - if (!logicCount) { continue; } - - obj->logic = allocator_create(sizeof(Logic**)); - for (u32 l = 0; l < logicCount; l++) - { - Logic* logic = nullptr; - TFE_DarkForces::logic_serialize(logic, obj, stream); - if (!logic) { continue; } - - Logic** logicItem = (Logic**)allocator_newItem((Allocator*)obj->logic); - logic->parent = logicItem; - logic->obj = obj; - *logicItem = logic; - - // Handle projectiles. - if (logic->type == LOGIC_PROJECTILE) - { - obj->projectileLogic = logic; - } - } - } - - // Fix-up generator references. - for (u32 i = 0; i < writeCount; i++) - { - SecObject* obj = (SecObject*)TFE_Memory::chunkedArrayGet(s_objData.objectList, i); - - allocator_saveIter((Allocator*)obj->logic); - Logic** logicPtr = (Logic**)allocator_getHead((Allocator*)obj->logic); - while (logicPtr) - { - Logic* logic = *logicPtr; - if (logic->type == LOGIC_GENERATOR) - { - TFE_DarkForces::generatorLogic_fixup(logic); - } - logicPtr = (Logic**)allocator_getNext((Allocator*)obj->logic); - } - allocator_restoreIter((Allocator*)obj->logic); - } - } - } -} // namespace TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Level/robjData.h b/components/darkforces/tfe/TFE_Jedi/Level/robjData.h deleted file mode 100644 index 1726aec6..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Level/robjData.h +++ /dev/null @@ -1,124 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include - -using namespace TFE_Jedi; - -struct JediModel; -struct RSector; - -enum ObjectType -{ - OBJ_TYPE_SPIRIT = 0, - OBJ_TYPE_SPRITE = 1, - OBJ_TYPE_3D = 2, - OBJ_TYPE_FRAME = 3, -}; - -enum ObjectFlags -{ - OBJ_FLAG_NONE = 0, - OBJ_FLAG_AIM = FLAG_BIT(0), // An object that can be aimed at. - OBJ_FLAG_EYE = FLAG_BIT(1), // Eye - OBJ_FLAG_NEEDS_TRANSFORM = FLAG_BIT(2), // Object needs to be transformed and rendered. - OBJ_FLAG_FULLBRIGHT = FLAG_BIT(3), // Rendered as fullbright (not lit). - OBJ_FLAG_MOVABLE = FLAG_BIT(4), // Object is movable. - OBJ_FLAG_BOSS = FLAG_BIT(5), // Boss enemy. - OBJ_FLAG_MISSION = FLAG_BIT(6), -}; - -enum EntityTypeFlags -{ - ETFLAG_AI_ACTOR = FLAG_BIT(0), // AI Actor - moves and acts on its own. - ETFLAG_HAS_GRAVITY = FLAG_BIT(1), // This entity is effected by gravity. - ETFLAG_FLYING = FLAG_BIT(2), // This entity is flying (can change Y height). - ETFLAG_PROJECTILE = FLAG_BIT(3), // The entity is a projectile. - ETFLAG_CAN_WAKE = FLAG_BIT(6), // An inactive object or animation waiting to be "woken up" - such as Vues waiting to play. - ETFLAG_PICKUP = FLAG_BIT(7), // An item pickup. - ETFLAG_SCENERY = FLAG_BIT(8), // Set for scenery. - ETFLAG_CORPSE = FLAG_BIT(9), // Corpse - ETFLAG_CAN_DISABLE = FLAG_BIT(10), // An object that can be enabled or disabled by INF. - ETFLAG_SMART_OBJ = FLAG_BIT(11), // An object that can manipulate the level, such as opening doors. - ETFLAG_REMOTE = FLAG_BIT(12), // Unknown, used by AI. - ETFLAG_LANDMINE = FLAG_BIT(13), // Specifically set if a pre-placed landmine. - ETFLAG_KEEP_CORPSE = FLAG_BIT(14), // Do not free this corpse. - ETFLAG_GENERAL_MOHC = FLAG_BIT(15), // Used by AI. - ETFLAG_LANDMINE_WPN = FLAG_BIT(16), // A landmine weapon - i.e. player placed landmines. - ETFLAG_PLAYER = FLAG_BIT(31), // This is the player object. - - ETFLAG_NONE = 0, -}; - -enum ObjStateVersion : u32 -{ - ObjState_InitVersion = 1, - ObjState_FlyModeAdded = 2, - ObjState_VueSmoothing = 3, - ObjState_CurVersion = ObjState_VueSmoothing, -}; - -#define SPRITE_SCALE_FIXED FIXED(10) - -struct SecObject -{ - SecObject* self; - ObjectType type; - u32 entityFlags; // see EntityTypeFlags above. - void* projectileLogic; // projectile logic. - - // Position - vec3_fixed posWS; - vec3_fixed posVS; - - // World Size - fixed16_16 worldWidth; - fixed16_16 worldHeight; - - // 3x3 transformation matrix. - fixed16_16 transform[9]; - - // Rendering data. - union - { - JediModel* model; - Wax* wax; - WaxFrame* fme; - void* ptr; - }; - s32 frame; - s32 anim; - RSector* sector; - void* logic; - - // See ObjectFlags above. - u32 flags; - - // Orientation. - angle14_16 pitch; - angle14_16 yaw; - angle14_16 roll; - // index in containing sector object list. - s16 index; - - // TFE - u32 serializeIndex; -}; - -namespace TFE_Jedi -{ - void objData_clear(); - SecObject* objData_allocFromArray(); - void objData_freeToArray(SecObject* obj); - - void objData_serialize(Stream* stream); - - // Used for downstream serialization, to get the object from the serialized object ID. - SecObject* objData_getObjectBySerializationId(u32 id); - SecObject* objData_getObjectBySerializationId_NoValidation(u32 id); -} diff --git a/components/darkforces/tfe/TFE_Jedi/Level/robject.cpp b/components/darkforces/tfe/TFE_Jedi/Level/robject.cpp deleted file mode 100644 index 942acd25..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Level/robject.cpp +++ /dev/null @@ -1,166 +0,0 @@ -#include "robject.h" -#include "level.h" -#include -#include -#include -#include -#include - -namespace TFE_Jedi -{ - JBool s_freeObjLock = JFALSE; - - void computeTransform3x3(fixed16_16* transform, angle14_32 yaw, angle14_32 pitch, angle14_32 roll); - - SecObject* allocateObject() - { - SecObject* obj = objData_allocFromArray(); - obj->yaw = 0; - obj->pitch = 0; - obj->roll = 0; - obj->frame = 0; - obj->anim = 0; - obj->worldWidth = -1; - obj->worldHeight = -1; - obj->ptr = nullptr; - obj->sector = nullptr; - obj->logic = nullptr; - obj->projectileLogic = nullptr; - obj->type = OBJ_TYPE_SPIRIT; - obj->entityFlags = ETFLAG_NONE; - obj->flags = OBJ_FLAG_NEEDS_TRANSFORM | OBJ_FLAG_MOVABLE; - obj->self = obj; - obj->serializeIndex = 0; - return obj; - } - - void freeObject(SecObject* obj) - { - s_freeObjLock = JTRUE; - // Free Logics - Logic** head = (Logic**)allocator_getHead((Allocator*)obj->logic); - while (head) - { - Logic* logic = *head; - if (logic->cleanupFunc) - { - logic->cleanupFunc(logic); - } - - head = (Logic**)allocator_getNext((Allocator*)obj->logic); - } - - allocator_free((Allocator*)obj->logic); - sector_removeObject(obj); - objData_freeToArray(obj); - - s_freeObjLock = JFALSE; - } - - void obj3d_setData(SecObject* obj, JediModel* pod) - { - obj->model = pod; - obj->type = OBJ_TYPE_3D; - obj->flags |= OBJ_FLAG_NEEDS_TRANSFORM; - if (obj->worldWidth == -1) // the initial value. - { - obj->worldWidth = 0; - } - if (obj->worldHeight == -1) - { - obj->worldHeight = 0; - } - } - - void obj3d_computeTransform(SecObject* obj) - { - computeTransform3x3(obj->transform, obj->yaw, obj->pitch, obj->roll); - } - - void spirit_setData(SecObject* obj) - { - obj->ptr = nullptr; - obj->type = OBJ_TYPE_SPIRIT; - if (obj->worldWidth == -1) - { - obj->worldWidth = 0; - } - if (obj->worldHeight == -1) - { - obj->worldHeight = 0; - } - } - - void sprite_setData(SecObject* obj, JediWax* data) - { - obj->wax = data; - obj->type = OBJ_TYPE_SPRITE; - obj->flags |= OBJ_FLAG_NEEDS_TRANSFORM; - - if (data) - { - WaxAnim* anim = WAX_AnimPtr(data, 0); - WaxView* view = WAX_ViewPtr(data, anim, 0); - WaxFrame* frame = WAX_FramePtr(data, view, 0); - WaxCell* cell = WAX_CellPtr(data, frame); - - if (obj->worldWidth == -1) - { - const fixed16_16 width = intToFixed16(TFE_Jedi::abs(cell->sizeX)/2); - obj->worldWidth = div16(mul16(data->xScale, width), SPRITE_SCALE_FIXED); - } - if (obj->worldHeight == -1) - { - const fixed16_16 height = intToFixed16(TFE_Jedi::abs(cell->sizeY)); - obj->worldHeight = div16(mul16(data->yScale, height), SPRITE_SCALE_FIXED); - } - } - } - - void frame_setData(SecObject* obj, WaxFrame* data) - { - obj->fme = data; - obj->type = OBJ_TYPE_FRAME; - obj->flags |= OBJ_FLAG_NEEDS_TRANSFORM; - WaxCell* cell = data ? WAX_CellPtr(data, data) : nullptr; - - if (obj->worldWidth == -1 && cell) - { - const fixed16_16 width = intToFixed16(TFE_Jedi::abs(cell->sizeX)/2); - obj->worldWidth = div16(width, SPRITE_SCALE_FIXED); - } - if (obj->worldHeight == -1 && cell) - { - const fixed16_16 height = intToFixed16(TFE_Jedi::abs(cell->sizeY)); - obj->worldHeight = div16(height, SPRITE_SCALE_FIXED); - } - } - - ///////////////////////////////// - // Internal - void computeTransform3x3(fixed16_16* transform, angle14_32 yaw, angle14_32 pitch, angle14_32 roll) - { - fixed16_16 sinYaw, cosYaw; - fixed16_16 sinPch, cosPch; - fixed16_16 sinRol, cosRol; - - sinCosFixed(yaw, &sinYaw, &cosYaw); - sinCosFixed(pitch, &sinPch, &cosPch); - sinCosFixed(roll, &sinRol, &cosRol); - - fixed16_16 sRol_sPitch = mul16(sinRol, sinPch); - fixed16_16 cRol_sPitch = mul16(cosRol, sinPch); - - transform[0] = mul16(cosRol, cosYaw) + mul16(sRol_sPitch, sinYaw); - transform[1] = -mul16(sinRol, cosYaw) + mul16(cRol_sPitch, sinYaw); - transform[2] = mul16(cosPch, sinYaw); - - transform[3] = mul16(cosPch, sinRol); - transform[4] = mul16(cosRol, cosPch); - transform[5] = -sinPch; - - transform[6] = -mul16(cosRol, sinYaw) + mul16(sRol_sPitch, cosYaw); - transform[7] = mul16(sinRol, sinYaw) + mul16(cRol_sPitch, cosYaw); - transform[8] = mul16(cosPch, cosYaw); - } -} // namespace TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Level/robject.h b/components/darkforces/tfe/TFE_Jedi/Level/robject.h deleted file mode 100644 index 47fbdebb..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Level/robject.h +++ /dev/null @@ -1,35 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include "robjData.h" - -using namespace TFE_Jedi; - -struct JediModel; -struct RSector; - -namespace TFE_Jedi -{ - SecObject* allocateObject(); - void freeObject(SecObject* obj); - - // Spirits - void spirit_setData(SecObject* obj); - - // 3D objects - void obj3d_setData(SecObject* obj, JediModel* pod); - void obj3d_computeTransform(SecObject* obj); - - // Sprites - void sprite_setData(SecObject* obj, JediWax* data); - - // Frames - void frame_setData(SecObject* obj, WaxFrame* data); - - extern JBool s_freeObjLock; -} diff --git a/components/darkforces/tfe/TFE_Jedi/Level/roffscreenBuffer.cpp b/components/darkforces/tfe/TFE_Jedi/Level/roffscreenBuffer.cpp deleted file mode 100644 index 4749cdab..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Level/roffscreenBuffer.cpp +++ /dev/null @@ -1,128 +0,0 @@ -#include - -#include "roffscreenBuffer.h" -#include -#include - -namespace TFE_Jedi -{ - static u8 s_workBuffer[256]; - #define system_alloc(x) malloc(x) - #define system_free(x) free(x) - - OffScreenBuffer* createOffScreenBuffer(s32 width, s32 height, u32 flags) - { - OffScreenBuffer* buffer = (OffScreenBuffer*)game_alloc(sizeof(OffScreenBuffer)); - s32 size = width * height; - - buffer->width = width; - buffer->height = height; - buffer->flags = flags; - buffer->size = size; - // This needs to go through the system allocator since it can be very large. - buffer->image = (u8*)system_alloc(size); - - return buffer; - } - - void freeOffScreenBuffer(OffScreenBuffer* buffer) - { - if (!buffer) { return; } - system_free(buffer->image); - game_free(buffer); - } - - void offscreenBuffer_clearImage(OffScreenBuffer* buffer, u8 clear_color) - { - memset(buffer->image, clear_color, buffer->size); - } - - void offscreenBuffer_drawTexture(OffScreenBuffer* buffer, TextureData* tex, s32 x, s32 y) - { - if (!buffer || !tex) { return; } - - s32 x0 = x, y0 = y; - // Early out if the texture does not overlap with the buffer. - if (x0 >= buffer->width || x0 + tex->width < 0 || y0 >= buffer->height || y0 + tex->height < 0) - { - return; - } - - s32 x1 = x0 + tex->width - 1; - s32 y1 = y0 + tex->height - 1; - // Clip the texture rect to the offscreen buffer. - s32 xDiff = 0; - s32 yDiff = 0; - if (y0 < 0) - { - y0 = 0; - } - if (y1 >= buffer->height) - { - yDiff = y1 - buffer->height + 1; - y1 = buffer->height - 1; - } - - if (x0 < 0) - { - x0 = 0; - xDiff = -x0; - } - if (x1 >= buffer->width) - { - x1 = buffer->width - 1; - } - - s32 height = y1 - y0 + 1; - if (height <= 0) - { - return; - } - - assert(x0 >= 0 && x1 < buffer->width && x0 <= x1); - assert(y0 >= 0 && y1 < buffer->height && y0 <= y1); - if (tex->flags & OPACITY_TRANS) - { - if (tex->compressed) - { - // TODO - this doesn't seem to be used, so do it later... - assert(0); - } - - for (s32 xi = x0; xi <= x1; xi++) - { - s32 srcX = xi - x0 + xDiff; - s32 xOffset = srcX * tex->height; - u8* srcImage = tex->image + xOffset + yDiff; - - for (s32 yi = y1; yi >= y0; yi--, srcImage++) - { - if (*srcImage) - { - buffer->image[yi*buffer->width + xi] = *srcImage; - } - } - } - } - else - { - if (tex->compressed) - { - // TODO - this doesn't seem to be used, so do it later... - assert(0); - } - - for (s32 xi = x0; xi <= x1; xi++) - { - s32 srcX = xi - x0 + xDiff; - s32 xOffset = srcX * tex->height; - u8* srcImage = tex->image + xOffset + yDiff; - - for (s32 yi = y1; yi >= y0; yi--, srcImage++) - { - buffer->image[yi*buffer->width + xi] = *srcImage; - } - } - } - } -} // TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Level/roffscreenBuffer.h b/components/darkforces/tfe/TFE_Jedi/Level/roffscreenBuffer.h deleted file mode 100644 index 85d33013..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Level/roffscreenBuffer.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include "rtexture.h" - -struct OffScreenBuffer -{ - u8* image; - s32 width; - s32 height; - s32 size; - u32 flags; -}; - -enum OffScreenBufferFlags -{ - OBF_NONE = 0, - OBF_TRANS = FLAG_BIT(0), // transparent element. -}; - -namespace TFE_Jedi -{ - OffScreenBuffer* createOffScreenBuffer(s32 width, s32 height, u32 flags); - void freeOffScreenBuffer(OffScreenBuffer* buffer); - void offscreenBuffer_clearImage(OffScreenBuffer* buffer, u8 clear_color); - - // Draw texture 'tex' to the offscreen buffer 'buffer' at position (x, y). - void offscreenBuffer_drawTexture(OffScreenBuffer* buffer, TextureData* tex, s32 x, s32 y); -} // TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Level/rsector.cpp b/components/darkforces/tfe/TFE_Jedi/Level/rsector.cpp deleted file mode 100644 index 5f630012..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Level/rsector.cpp +++ /dev/null @@ -1,1306 +0,0 @@ -#include -#include - -#include "rsector.h" -#include "rwall.h" -#include "robject.h" -#include "level.h" -#include "levelData.h" -#include -#include -#include -#include -#include -#include -#include -// TODO: Find a better way to handle this. -#include - -namespace TFE_DarkForces -{ - extern u32 s_playerDying; -} - -using namespace TFE_DarkForces; - -namespace TFE_Jedi -{ - // Internal Forward Declarations - void sector_computeWallDirAndLength(RWall* wall); - void sector_moveWallVertex(RWall* wall, fixed16_16 offsetX, fixed16_16 offsetZ); - JBool sector_objOverlapsWall(RWall* wall, SecObject* obj, s32* objSide); - JBool sector_canWallMove(RWall* wall, fixed16_16 offsetX, fixed16_16 offsetZ); - void sector_moveObjects(RSector* sector, u32 flags, fixed16_16 offsetX, fixed16_16 offsetZ); - - f32 isLeft(Vec2f p0, Vec2f p1, Vec2f p2); - - ///////////////////////////////////////////////// - // API Implementation - ///////////////////////////////////////////////// - void sector_clear(RSector* sector) - { - sector->vertexCount = 0; - sector->wallCount = 0; - sector->objectCount = 0; - sector->secHeight = 0; - sector->collisionFrame = 0; - sector->id = 0; - sector->prevDrawFrame = 0; - sector->infLink = 0; - sector->objectCapacity = 0; - sector->verticesWS = nullptr; - sector->verticesVS = nullptr; - sector->self = sector; - } - - void sector_setupWallDrawFlags(RSector* sector) - { - RWall* wall = sector->walls; - for (s32 w = 0; w < sector->wallCount; w++, wall++) - { - wall->drawFlags = WDF_MIDDLE; - if (wall->nextSector) - { - RSector* wSector = wall->sector; - fixed16_16 wFloorHeight = wSector->floorHeight; - fixed16_16 wCeilHeight = wSector->ceilingHeight; - - RWall* mirror = wall->mirrorWall; - RSector* mSector = mirror->sector; - fixed16_16 mFloorHeight = mSector->floorHeight; - fixed16_16 mCeilHeight = mSector->ceilingHeight; - assert(mSector == wall->nextSector); - - //wall->drawFlags = WDF_MIDDLE; - mirror->drawFlags = WDF_MIDDLE; - - if (wCeilHeight < mCeilHeight) - { - wall->drawFlags |= WDF_TOP; - } - if (wFloorHeight > mFloorHeight) - { - wall->drawFlags |= WDF_BOT; - } - if (mCeilHeight < wCeilHeight) - { - mirror->drawFlags |= WDF_TOP; - } - if (mFloorHeight > wFloorHeight) - { - mirror->drawFlags |= WDF_BOT; - } - wall_computeTexelHeights(wall->mirrorWall); - } - wall_computeTexelHeights(wall); - } - } - - void sector_adjustHeights(RSector* sector, fixed16_16 floorOffset, fixed16_16 ceilOffset, fixed16_16 secondHeightOffset) - { - sector->dirtyFlags |= SDF_HEIGHTS; - - // Adjust objects. - if (sector->objectCount) - { - fixed16_16 heightOffset = secondHeightOffset + floorOffset; - for (s32 i = 0; i < sector->objectCapacity; i++) - { - SecObject* obj = sector->objectList[i]; - if (!obj) { continue; } - - if (obj->posWS.y == sector->floorHeight) - { - obj->posWS.y += floorOffset; - if (obj->entityFlags & ETFLAG_PLAYER) - { - s_playerYPos += floorOffset; - } - } - - if (obj->posWS.y == sector->ceilingHeight) - { - obj->posWS.y += ceilOffset; - if (obj->entityFlags & ETFLAG_PLAYER) - { - // Why not ceilingOffset? - s_playerYPos += floorOffset; - } - } - - fixed16_16 secHeight = sector->floorHeight + sector->secHeight; - if (obj->posWS.y == secHeight) - { - obj->posWS.y += heightOffset; - if (obj->entityFlags & ETFLAG_PLAYER) - { - // Dark Forces Bug: - // The original code was `s_playerYPos += floorOffset;` here instead, which made second-height based elevators - // jittery in DOS. This change makes the elevators smooth (such as move_offset). - s_playerYPos += heightOffset; - } - } - } - } - // Adjust sector heights. - sector->ceilingHeight += ceilOffset; - sector->floorHeight += floorOffset; - sector->secHeight += secondHeightOffset; - - // Update wall data. - s32 wallCount = sector->wallCount; - RWall* wall = sector->walls; - for (s32 w = 0; w < wallCount; w++, wall++) - { - if (wall->nextSector) - { - wall_setupAdjoinDrawFlags(wall); - wall_computeTexelHeights(wall->mirrorWall); - } - wall_computeTexelHeights(wall); - } - - // Update collision data. - fixed16_16 floorHeight = sector->floorHeight; - if (sector->flags1 & SEC_FLAGS1_PIT) - { - floorHeight += SEC_SKY_HEIGHT; - } - fixed16_16 ceilHeight = sector->ceilingHeight; - if (sector->flags1 & SEC_FLAGS1_EXTERIOR) - { - ceilHeight -= SEC_SKY_HEIGHT; - } - fixed16_16 secHeight = sector->floorHeight + sector->secHeight; - if (sector->secHeight >= 0 && floorHeight > secHeight) - { - secHeight = floorHeight; - } - - sector->colFloorHeight = floorHeight; - sector->colCeilHeight = ceilHeight; - sector->colSecHeight = secHeight; - sector->colSecCeilHeight = ceilHeight; - } - - void sector_computeBounds(RSector* sector) - { - RWall* wall = sector->walls; - vec2_fixed* w0 = wall->w0; - fixed16_16 maxX = w0->x; - fixed16_16 maxZ = w0->z; - fixed16_16 minX = maxX; - fixed16_16 minZ = maxZ; - - wall++; - for (s32 i = 1; i < sector->wallCount; i++, wall++) - { - w0 = wall->w0; - - minX = min(minX, w0->x); - minZ = min(minZ, w0->z); - - maxX = max(maxX, w0->x); - maxZ = max(maxZ, w0->z); - } - - sector->boundsMin.x = minX; - sector->boundsMax.x = maxX; - sector->boundsMin.z = minZ; - sector->boundsMax.z = maxZ; - } - - fixed16_16 sector_getMaxObjectHeight(RSector* sector) - { - s32 maxObjHeight = 0; - SecObject** objectList = sector->objectList; - for (s32 count = sector->objectCount; count > 0; objectList++) - { - SecObject* obj = *objectList; - if (obj) - { - maxObjHeight = max(maxObjHeight, obj->worldHeight + ONE_16); - count--; - } - } - return maxObjHeight; - } - - JBool sector_moveWalls(RSector* sector, fixed16_16 delta, fixed16_16 dirX, fixed16_16 dirZ, u32 flags) - { - fixed16_16 offsetX = mul16(delta, dirX); - fixed16_16 offsetZ = mul16(delta, dirZ); - - JBool sectorBlocked = JFALSE; - s32 wallCount = sector->wallCount; - RWall* wall = sector->walls; - for (s32 i = 0; i < wallCount && !sectorBlocked; i++, wall++) - { - if (wall->flags1 & WF1_WALL_MORPHS) - { - sectorBlocked |= sector_canWallMove(wall, offsetX, offsetZ); - - RWall* mirror = wall->mirrorWall; - if (mirror && (mirror->flags1 & WF1_WALL_MORPHS)) - { - sectorBlocked |= sector_canWallMove(mirror, offsetX, offsetZ); - } - } - } - - if (!sectorBlocked) - { - sector->dirtyFlags |= SDF_VERTICES; - - wall = sector->walls; - for (s32 i = 0; i < wallCount; i++, wall++) - { - if (wall->flags1 & WF1_WALL_MORPHS) - { - sector_moveWallVertex(wall, offsetX, offsetZ); - RWall* mirror = wall->mirrorWall; - if (mirror && (mirror->flags1 & WF1_WALL_MORPHS)) - { - mirror->sector->dirtyFlags |= SDF_VERTICES; - sector_moveWallVertex(mirror, offsetX, offsetZ); - } - } - } - sector_moveObjects(sector, flags, offsetX, offsetZ); - sector_computeBounds(sector); - } - - return ~sectorBlocked; - } - - void sector_changeWallLight(RSector* sector, fixed16_16 delta) - { - RWall* wall = sector->walls; - s32 wallCount = sector->wallCount; - - sector->dirtyFlags |= SDF_AMBIENT; - for (s32 i = 0; i < wallCount; i++, wall++) - { - if (wall->flags1 & WF1_CHANGE_WALL_LIGHT) - { - wall->wallLight += delta; - } - } - } - - void sector_scrollWalls(RSector* sector, fixed16_16 offsetX, fixed16_16 offsetZ) - { - RWall* wall = sector->walls; - s32 wallCount = sector->wallCount; - sector->dirtyFlags |= SDF_WALL_OFFSETS; - - const u32 scrollFlags = WF1_SCROLL_SIGN_TEX | WF1_SCROLL_BOT_TEX | WF1_SCROLL_MID_TEX | WF1_SCROLL_TOP_TEX; - for (s32 i = 0; i < wallCount; i++, wall++) - { - if (wall->flags1 & scrollFlags) - { - if (wall->flags1 & WF1_SCROLL_TOP_TEX) - { - wall->topOffset.x += offsetX; - wall->topOffset.z += offsetZ; - } - if (wall->flags1 & WF1_SCROLL_MID_TEX) - { - wall->midOffset.x += offsetX; - wall->midOffset.z += offsetZ; - } - if (wall->flags1 & WF1_SCROLL_BOT_TEX) - { - wall->botOffset.x += offsetX; - wall->botOffset.z += offsetZ; - } - if (wall->flags1 & WF1_SCROLL_SIGN_TEX) - { - wall->signOffset.x += offsetX; - wall->signOffset.z += offsetZ; - } - } - } - } - - void sector_adjustTextureWallOffsets_Floor(RSector* sector, fixed16_16 floorDelta) - { - sector->dirtyFlags |= SDF_WALL_OFFSETS; - - RWall* wall = sector->walls; - s32 wallCount = sector->wallCount; - for (s32 i = 0; i < wallCount; i++, wall++) - { - fixed16_16 textureOffset = floorDelta * 8; - if (wall->flags1 & WF1_TEX_ANCHORED) - { - if (wall->nextSector) - { - wall->botOffset.z -= textureOffset; - } - else - { - wall->midOffset.z -= textureOffset; - } - } - if (wall->flags1 & WF1_SIGN_ANCHORED) - { - wall->signOffset.z -= textureOffset; - } - } - } - - void sector_adjustTextureMirrorOffsets_Floor(RSector* sector, fixed16_16 floorDelta) - { - RWall* wall = sector->walls; - s32 wallCount = sector->wallCount; - for (s32 i = 0; i < wallCount; i++, wall++) - { - RWall* mirror = wall->mirrorWall; - if (mirror) - { - mirror->sector->dirtyFlags |= SDF_WALL_OFFSETS; - - fixed16_16 textureOffset = -floorDelta * 8; - if (mirror->flags1 & WF1_TEX_ANCHORED) - { - if (mirror->nextSector) - { - mirror->botOffset.z -= textureOffset; - } - else - { - mirror->midOffset.z -= textureOffset; - } - } - if (mirror->flags1 & WF1_SIGN_ANCHORED) - { - mirror->signOffset.z -= textureOffset; - } - } - } - } - - void sector_growObjectList(RSector* sector) - { - s32 objectCapacity = sector->objectCapacity; - if (sector->objectCount >= objectCapacity) - { - SecObject** list; - if (!objectCapacity) - { - list = (SecObject**)level_alloc(sizeof(SecObject*) * 5); - sector->objectList = list; - } - else - { - sector->objectList = (SecObject**)level_realloc(sector->objectList, sizeof(SecObject*) * (objectCapacity + 5)); - list = sector->objectList + objectCapacity; - } - memset(list, 0, sizeof(SecObject*) * 5); - sector->objectCapacity += 5; - } - } - - void sector_addObjectToList(RSector* sector, SecObject* obj) - { - // Then add the object to the first free slot. - // Note that this scheme is optimized for deletion rather than addition. - SecObject** list = sector->objectList; - for (s32 i = 0; i < sector->objectCapacity; i++, list++) - { - if (!(*list)) - { - *list = obj; - obj->index = i; - obj->sector = sector; - sector->objectCount++; - break; - } - } - } - - // Skips some of the checks and does not send messages. - // Used for serialization. - void sector_addObjectDirect(RSector* sector, SecObject* obj) - { - sector->dirtyFlags |= SDF_CHANGE_OBJ; - - // The sector containing the player has a special flag. - if (obj->entityFlags & ETFLAG_PLAYER) - { - sector->flags1 |= SEC_FLAGS1_PLAYER; - } - - // Grow the object list if necessary. - sector_growObjectList(sector); - - // Then add the object to the first free slot. - sector_addObjectToList(sector, obj); - } - - void sector_addObject(RSector* sector, SecObject* obj) - { - if (sector != obj->sector) - { - sector->dirtyFlags |= SDF_CHANGE_OBJ; - - // Remove the object from its current sector (if it has one). - if (obj->sector) - { - sector_removeObject(obj); - } - - // The sector containing the player has a special flag. - if (!((obj->entityFlags & ETFLAG_PLAYER) && s_playerDying)) - { - message_sendToSector(sector, obj, INF_EVENT_ENTER_SECTOR, MSG_TRIGGER); - } - if (obj->entityFlags & ETFLAG_PLAYER) - { - sector->flags1 |= SEC_FLAGS1_PLAYER; - } - - // Grow the object list if necessary. - sector_growObjectList(sector); - - // Then add the object to the first free slot. - sector_addObjectToList(sector, obj); - } - } - - void sector_removeObject(SecObject* obj) - { - if (!obj || !obj->sector) { return; } - - RSector* sector = obj->sector; - obj->sector = nullptr; - sector->dirtyFlags |= SDF_CHANGE_OBJ; - - // Remove the object from the object list. - SecObject** objList = sector->objectList; - objList[obj->index] = nullptr; - sector->objectCount--; - - if (!((obj->entityFlags & ETFLAG_PLAYER) && s_playerDying)) - { - message_sendToSector(sector, obj, INF_EVENT_LEAVE_SECTOR, MSG_TRIGGER); - } - if (obj->entityFlags & ETFLAG_PLAYER) - { - sector->flags1 &= ~SEC_FLAGS1_PLAYER; - } - } - - void sector_changeGlobalLightLevel() - { - RSector* sector = s_levelState.sectors; - for (u32 i = 0; i < s_levelState.sectorCount; i++, sector++) - { - fixed16_16 newLightLevel = intToFixed16(sector->flags3); - sector->flags3 = floor16(sector->ambient); - sector->ambient = newLightLevel; - } - } - - RSector* sector_which3D(fixed16_16 dx, fixed16_16 dy, fixed16_16 dz) - { - fixed16_16 ix = dx; - fixed16_16 iz = dz; - fixed16_16 y = dy; - - RSector* sector = s_levelState.sectors; - RSector* foundSector = nullptr; - s32 sectorUnitArea = 0; - s32 prevSectorUnitArea = INT_MAX; - - for (u32 i = 0; i < s_levelState.sectorCount; i++, sector++) - { - if (y >= sector->ceilingHeight && y <= sector->floorHeight) - { - const fixed16_16 sectorMaxX = sector->boundsMax.x; - const fixed16_16 sectorMinX = sector->boundsMin.x; - const fixed16_16 sectorMaxZ = sector->boundsMax.z; - const fixed16_16 sectorMinZ = sector->boundsMin.z; - - const s32 dxInt = floor16(sectorMaxX - sectorMinX) + 1; - const s32 dzInt = floor16(sectorMaxZ - sectorMinZ) + 1; - sectorUnitArea = dzInt * dxInt; - - s32 insideBounds = 0; - if (ix >= sectorMinX && ix <= sectorMaxX && iz >= sectorMinZ && iz <= sectorMaxZ) - { - // pick the containing sector with the smallest area. - if (sectorUnitArea < prevSectorUnitArea && sector_pointInsideDF(sector, ix, iz)) - { - prevSectorUnitArea = sectorUnitArea; - foundSector = sector; - } - } - } - } - - return foundSector; - } - - RSector* sector_which3D_Map(fixed16_16 dx, fixed16_16 dz, s32 layer) - { - fixed16_16 ix = dx; - fixed16_16 iz = dz; - - RSector* sector = s_levelState.sectors; - RSector* foundSector = nullptr; - s32 sectorUnitArea = 0; - s32 prevSectorUnitArea = INT_MAX; - - for (u32 i = 0; i < s_levelState.sectorCount; i++, sector++) - { - if (sector->layer == layer) - { - const fixed16_16 sectorMaxX = sector->boundsMax.x; - const fixed16_16 sectorMinX = sector->boundsMin.x; - const fixed16_16 sectorMaxZ = sector->boundsMax.z; - const fixed16_16 sectorMinZ = sector->boundsMin.z; - - const s32 dxInt = floor16(sectorMaxX - sectorMinX) + 1; - const s32 dzInt = floor16(sectorMaxZ - sectorMinZ) + 1; - sectorUnitArea = dzInt * dxInt; - - s32 insideBounds = 0; - if (ix >= sectorMinX && ix <= sectorMaxX && iz >= sectorMinZ && iz <= sectorMaxZ) - { - // pick the containing sector with the smallest area. - if (sectorUnitArea < prevSectorUnitArea && sector_pointInsideDF(sector, ix, iz)) - { - prevSectorUnitArea = sectorUnitArea; - foundSector = sector; - } - } - } - } - - return foundSector; - } - - enum PointSegSide - { - PS_INSIDE = -1, - PS_ON_LINE = 0, - PS_OUTSIDE = 1 - }; - - PointSegSide lineSegmentSide(fixed16_16 x, fixed16_16 z, fixed16_16 x0, fixed16_16 z0, fixed16_16 x1, fixed16_16 z1) - { - fixed16_16 dx = x0 - x1; - fixed16_16 dz = z0 - z1; - if (dx == 0) - { - if (dz > 0) - { - if (z < z1 || z > z0 || x > x0) { return PS_INSIDE; } - } - else - { - if (z < z0 || z > z1 || x > x0) { return PS_INSIDE; } - } - return (x == x0) ? PS_ON_LINE : PS_OUTSIDE; - } - else if (dz == 0) - { - if (z != z0) - { - // I believe this should be -1 or +1 depending on if z is less than or greater than z0. - // Otherwise flat lines always give the same answer. - return PS_INSIDE; - } - if (dx > 0) - { - return (x > x0) ? PS_INSIDE : (x < x1) ? PS_OUTSIDE : PS_ON_LINE; - } - return (x > x1) ? PS_INSIDE : (x < x0) ? PS_OUTSIDE : PS_ON_LINE; - } - else if (dx > 0) - { - if (x > x0) { return PS_INSIDE; } - - x -= x1; - if (dz > 0) - { - if (z < z1 || z > z0) { return PS_INSIDE; } - z -= z1; - } - else - { - if (z < z0 || z > z1) { return PS_INSIDE; } - dz = -dz; - z1 -= z; - z = z1; - } - } - else // dx <= 0 - { - if (x > x1) { return PS_INSIDE; } - - x -= x0; - dx = -dx; - if (dz > 0) - { - if (z < z1 || z > z0) { return PS_INSIDE; } - z0 -= z; - z = z0; - } - else // dz <= 0 - { - if (z < z0 || z > z1) { return PS_INSIDE; } - dz = -dz; - z -= z0; - } - } - fixed16_16 zDx = mul16(z, dx); - fixed16_16 xDz = mul16(x, dz); - if (xDz == zDx) - { - return PS_ON_LINE; - } - return (xDz > zDx) ? PS_INSIDE : PS_OUTSIDE; - } - - // The original DF algorithm. - JBool sector_pointInsideDF(RSector* sector, fixed16_16 x, fixed16_16 z) - { - const fixed16_16 xFrac = fract16(x); - const fixed16_16 zFrac = fract16(z); - const s32 xInt = floor16(x); - const s32 zInt = floor16(z); - const s32 wallCount = sector->wallCount; - - RWall* wall = sector->walls; - RWall* last = §or->walls[wallCount - 1]; - vec2_fixed* w1 = last->w1; - vec2_fixed* w0 = last->w0; - fixed16_16 dzLast = w1->z - w0->z; - s32 crossings = 0; - - for (s32 w = 0; w < wallCount; w++, wall++) - { - w0 = wall->w0; - w1 = wall->w1; - - fixed16_16 x0 = w0->x; - fixed16_16 x1 = w1->x; - fixed16_16 z0 = w0->z; - fixed16_16 z1 = w1->z; - fixed16_16 dz = z1 - z0; - - if (dz != 0) - { - if (z == z0 && x == x0) - { - TFE_System::logWrite(LOG_ERROR, "Sector", "Sector_Which3D: Object at (%d.%d, %d.%d) lies on a vertex of Sector #%d", xInt, xFrac, zInt, zFrac, sector->id); - return JTRUE; - } - else if (z != z0) - { - if (z != z1) - { - PointSegSide side = lineSegmentSide(x, z, x0, z0, x1, z1); - if (side == PS_OUTSIDE) - { - crossings++; - } - else if (side == PS_ON_LINE) - { - TFE_System::logWrite(LOG_ERROR, "Sector", "Sector_Which3D: Object at (%d.%d, %d.%d) lies on wall of Sector #%d", xInt, xFrac, zInt, zFrac, sector->id); - return JTRUE; - } - } - dzLast = dz; - } - else if (x != x0) - { - if (x < x0) - { - fixed16_16 dzSignMatches = dz ^ dzLast; // dzSignMatches >= 0 if dz and dz0 have the same sign. - if (dzSignMatches >= 0 || dzLast == 0) // the signs match OR dz or dz0 are positive OR dz0 EQUALS 0. - { - crossings++; - } - } - dzLast = dz; - } - } - else if (lineSegmentSide(x, z, x0, z0, x1, z1) == PS_ON_LINE) - { - TFE_System::logWrite(LOG_ERROR, "Sector", "Sector_Which3D: Object at (%d.%d, %d.%d) lies on wall of Sector #%d", xInt, xFrac, zInt, zFrac, sector->id); - return JTRUE; - } - } - - return (crossings & 1) ? JTRUE : JFALSE; - } - - // Uses the "Winding Number" test for a point in polygon. - // The point is considered inside if the winding number is greater than 0. - // Note that this is different than DF's "crossing" algorithm. - bool sector_pointInside(RSector* sector, fixed16_16 x, fixed16_16 z) - { - RWall* wall = sector->walls; - s32 wallCount = sector->wallCount; - s32 wn = 0; - - const Vec2f point = { fixed16ToFloat(x), fixed16ToFloat(z) }; - for (s32 w = 0; w < wallCount; w++, wall++) - { - vec2_fixed* w1 = wall->w0; - vec2_fixed* w0 = wall->w1; - - Vec2f p0 = { fixed16ToFloat(w0->x), fixed16ToFloat(w0->z) }; - Vec2f p1 = { fixed16ToFloat(w1->x), fixed16ToFloat(w1->z) }; - - if (p0.z <= z) - { - // Upward crossing, if the point is left of the edge than it intersects. - if (p1.z > z && isLeft(p0, p1, point) > 0) - { - wn++; - } - } - else - { - // Downward crossing, if point is right of the edge it intersects. - if (p1.z <= z && isLeft(p0, p1, point) < 0) - { - wn--; - } - } - } - - // The point is only outside if the winding number is less than or equal to 0. - return wn > 0; - } - - JBool sector_rotatingWallCollidesWithPlayer(RWall* wall, fixed16_16 cosAngle, fixed16_16 sinAngle, fixed16_16 centerX, fixed16_16 centerZ) - { - fixed16_16 objSide0; - SecObject* player = s_playerObject; - sector_objOverlapsWall(wall, player, &objSide0); - - fixed16_16 localX = wall->worldPos0.x - centerX; - fixed16_16 localZ = wall->worldPos0.z - centerZ; - - fixed16_16 dirX = wall->wallDir.x; - fixed16_16 dirZ = wall->wallDir.z; - fixed16_16 prevX = wall->w0->x; - fixed16_16 prevZ = wall->w0->z; - - wall->w0->x = mul16(localX, cosAngle) - mul16(localZ, sinAngle) + centerX; - wall->w0->z = mul16(localX, sinAngle) + mul16(localZ, cosAngle) + centerZ; - - vec2_fixed* w0 = wall->w0; - vec2_fixed* w1 = wall->w1; - fixed16_16 dx = w1->x - w0->x; - fixed16_16 dz = w1->z - w0->z; - computeDirAndLength(dx, dz, &wall->wallDir.x, &wall->wallDir.z); - - s32 objSide1; - JBool overlap1 = sector_objOverlapsWall(wall, player, &objSide1); - - // Restore - wall->wallDir.x = dirX; - wall->wallDir.z = dirZ; - wall->w0->x = prevX; - wall->w0->z = prevZ; - - // Test the results. - if (overlap1 || ((objSide0 & objSide1) && (objSide0 != objSide1))) { return JTRUE; } - return JFALSE; - } - - void sector_removeCorpses(RSector* sector) - { - SecObject* obj = nullptr; - s32 objectCount = sector->objectCount; - - s32 freeCount = 0; - SecObject* freeList[128]; - - for (s32 i = 0, idx = 0; i < objectCount && idx < sector->objectCapacity; idx++) - { - SecObject* obj = sector->objectList[idx]; - if (obj) - { - i++; - - JBool canRemove = (obj->entityFlags & ETFLAG_CORPSE) != 0; - canRemove |= ((obj->entityFlags & ETFLAG_PICKUP) && !(obj->flags & OBJ_FLAG_MISSION)); - - const u32 projType = (obj->projectileLogic) ? ((TFE_DarkForces::ProjectileLogic*)obj->projectileLogic)->type : (0); - const JBool isLandMine = projType == PROJ_LAND_MINE || projType == PROJ_LAND_MINE_PROX || projType == PROJ_LAND_MINE_PLACED; - canRemove |= ((obj->entityFlags & ETFLAG_PROJECTILE) && isLandMine); - - if (canRemove && freeCount < 128) - { - freeList[freeCount++] = obj; - } - } - } - - for (s32 i = 0; i < freeCount; i++) - { - freeObject(freeList[i]); - } - } - - // Returns JTRUE if the walls can rotate. - JBool sector_canRotateWalls(RSector* sector, angle14_32 angle, fixed16_16 centerX, fixed16_16 centerZ) - { - fixed16_16 cosAngle, sinAngle; - sinCosFixed(angle, &sinAngle, &cosAngle); - - // Loop through the walls and determine if the player is in the sector of any affected wall. - s32 wallCount = sector->wallCount; - RWall* wall = sector->walls; - JBool playerCollides = JFALSE; - for (s32 i = 0; i < sector->wallCount; i++, wall++) - { - if (wall->flags1 & WF1_WALL_MORPHS) - { - if (wall->sector->flags1 & SEC_FLAGS1_PLAYER) - { - playerCollides = JTRUE; - break; - } - RWall* mirror = wall->mirrorWall; - if (mirror && (mirror->flags1 & WF1_WALL_MORPHS)) - { - if (mirror->sector->flags1 & SEC_FLAGS1_PLAYER) - { - playerCollides = JTRUE; - break; - } - } - } - } - - if (playerCollides) // really this says that the player *might* collide and then gets definite here. - { - playerCollides = JFALSE; - wallCount = sector->wallCount; - wall = sector->walls; - - for (s32 i = 0; i < wallCount; i++, wall++) - { - if (wall->flags1 & WF1_WALL_MORPHS) - { - playerCollides |= sector_rotatingWallCollidesWithPlayer(wall, cosAngle, sinAngle, centerX, centerZ); - RWall* mirror = wall->mirrorWall; - if (mirror && (mirror->flags1 & WF1_WALL_MORPHS)) - { - playerCollides |= sector_rotatingWallCollidesWithPlayer(mirror, cosAngle, sinAngle, centerX, centerZ); - } - } - } - } - return playerCollides ? JFALSE : JTRUE; - } - - void sector_rotateWall(RWall* wall, fixed16_16 cosAngle, fixed16_16 sinAngle, fixed16_16 centerX, fixed16_16 centerZ) - { - fixed16_16 x0 = wall->worldPos0.x - centerX; - fixed16_16 z0 = wall->worldPos0.z - centerZ; - wall->w0->x = mul16(x0, cosAngle) - mul16(z0, sinAngle) + centerX; - wall->w0->z = mul16(x0, sinAngle) + mul16(z0, cosAngle) + centerZ; - - vec2_fixed* w1 = wall->w1; - vec2_fixed* w0 = wall->w0; - fixed16_16 dx = w1->x - w0->x; - fixed16_16 dz = w1->z - w0->z; - wall->length = computeDirAndLength(dx, dz, &wall->wallDir.x, &wall->wallDir.z); - wall->angle = vec2ToAngle(dx, dz); - - RSector* sector = wall->sector; - if (sector->flags1 & SEC_FLAGS1_PLAYER) - { - s_playerSecMoved = JTRUE; - } - - RWall* prevWall; - if (wall->id == 0) - { - prevWall = wall + (sector->wallCount - 1); - } - else - { - prevWall = wall - 1; - } - - w0 = prevWall->w0; - w1 = prevWall->w1; - dx = w1->x - w0->x; - dz = w1->z - w0->z; - prevWall->length = computeDirAndLength(dx, dz, &prevWall->wallDir.x, &prevWall->wallDir.z); - prevWall->angle = vec2ToAngle(dx, dz); - - sector = prevWall->sector; - if (sector->flags1 & SEC_FLAGS1_PLAYER) - { - s_playerSecMoved = JTRUE; - } - } - - void sector_rotateWalls(RSector* sector, fixed16_16 centerX, fixed16_16 centerZ, angle14_32 angle, u32 rotateFlags) - { - s32 cosAngle, sinAngle; - sinCosFixed(angle, &sinAngle, &cosAngle); - - sector->dirtyFlags |= SDF_WALL_SHAPE; - // TODO: (TFE) Handle rotateFlags for floor and ceiling texture rotation. - - s32 wallCount = sector->wallCount; - RWall* wall = sector->walls; - for (s32 i = 0; i < wallCount; i++, wall++) - { - if (wall->flags1 & WF1_WALL_MORPHS) - { - sector_rotateWall(wall, cosAngle, sinAngle, centerX, centerZ); - - RWall* mirror = wall->mirrorWall; - if (mirror && (mirror->flags1 & WF1_WALL_MORPHS)) - { - mirror->sector->dirtyFlags |= SDF_WALL_SHAPE; - sector_rotateWall(mirror, cosAngle, sinAngle, centerX, centerZ); - } - } - } - sector_computeBounds(sector); - sector->dirtyFlags |= SDF_WALL_SHAPE; - } - - void sector_rotateObj(SecObject* obj, angle14_32 deltaAngle, fixed16_16 cosdAngle, fixed16_16 sindAngle, fixed16_16 centerX, fixed16_16 centerZ) - { - if (obj->flags & OBJ_FLAG_MOVABLE) - { - if (obj->entityFlags & ETFLAG_PLAYER) - { - s_playerYaw -= deltaAngle; - } - else - { - obj->yaw -= deltaAngle; - } - - fixed16_16 relX = obj->posWS.x - centerX; - fixed16_16 relZ = obj->posWS.z - centerZ; - - fixed16_16 offsetY = 0; - fixed16_16 offsetX = mul16(relX, cosdAngle) - mul16(relZ, sindAngle) + centerX - obj->posWS.x; - fixed16_16 offsetZ = mul16(relX, sindAngle) + mul16(relZ, cosdAngle) + centerZ - obj->posWS.z; - - fixed16_16 height = obj->worldHeight + HALF_16; - - CollisionInfo info = - { - obj, - offsetX, offsetY, offsetZ, - 0, COL_INFINITY, height, 0, - 0, 0, 0, // to be filled in later. - obj->worldWidth, - }; - handleCollision(&info); - - // Collision reponse with a single iteration. - if (info.responseStep && info.wall) - { - handleCollisionResponseSimple(info.responseDir.x, info.responseDir.z, &info.offsetX, &info.offsetZ); - handleCollision(&info); - } - - RSector* finalSector = sector_which3D(obj->posWS.x, obj->posWS.y, obj->posWS.z); - if (finalSector) - { - // Adds the object to the new sector and removes it from the previous. - sector_addObject(finalSector, obj); - } - if (obj->type == OBJ_TYPE_3D) - { - obj3d_computeTransform(obj); - } - } - } - - void sector_rotateObjects(RSector* sector, angle14_32 deltaAngle, fixed16_16 centerX, fixed16_16 centerZ, u32 flags) - { - fixed16_16 cosdAngle, sindAngle; - sinCosFixed(deltaAngle, &sindAngle, &cosdAngle); - JBool moveCeil = JFALSE; - JBool moveSecHgt = JFALSE; - JBool moveFloor = JFALSE; - if (flags & INF_EFLAG_MOVE_FLOOR) - { - moveFloor = JTRUE; - } - if (flags & INF_EFLAG_MOVE_SECHT) - { - moveSecHgt = JTRUE; - } - if (flags & INF_EFLAG_MOVE_CEIL) - { - moveCeil = JTRUE; - } - - SecObject** objList = sector->objectList; - s32 objCount = sector->objectCount; - for (s32 i = 0; i < objCount; i++, objList++) - { - SecObject* obj = *objList; - while (!obj) - { - objList++; - obj = *objList; - } - // The first 3 conditionals can be collapsed since the resulting values are the same. - if ((moveFloor && obj->posWS.y == sector->floorHeight) || - (moveSecHgt && sector->secHeight && sector->floorHeight + sector->secHeight == obj->posWS.y) || - (moveCeil && sector->ceilingHeight == obj->posWS.y)) - { - sector_rotateObj(obj, deltaAngle, cosdAngle, sindAngle, centerX, centerZ); - } - } - } - - ////////////////////////////////////////////////////////// - // Internal - ////////////////////////////////////////////////////////// - void sector_computeWallDirAndLength(RWall* wall) - { - vec2_fixed* w0 = wall->w0; - vec2_fixed* w1 = wall->w1; - fixed16_16 dx = w1->x - w0->x; - fixed16_16 dz = w1->z - w0->z; - wall->length = computeDirAndLength(dx, dz, &wall->wallDir.x, &wall->wallDir.z); - wall->angle = vec2ToAngle(dx, dz); - } - - void sector_moveWallVertex(RWall* wall, fixed16_16 offsetX, fixed16_16 offsetZ) - { - // Offset vertex 0. - wall->w0->x += offsetX; - wall->w0->z += offsetZ; - // Update the wall direction and length. - sector_computeWallDirAndLength(wall); - - // Set the appropriate game value if the player is inside the sector. - RSector* sector = wall->sector; - if (sector->flags1 & SEC_FLAGS1_PLAYER) - { - s_playerSecMoved = JTRUE; - } - - // Update the previous wall, since it would have changed as well. - RWall* prevWall = nullptr; - if (wall->id == 0) - { - s32 last = sector->wallCount - 1; - prevWall = §or->walls[last]; - } - else - { - prevWall = wall - 1; - } - // Compute the wall direction and length of the previous wall. - sector_computeWallDirAndLength(prevWall); - - // Set the appropriate game value if the player is inside the sector. - sector = prevWall->sector; - if (sector->flags1 & SEC_FLAGS1_PLAYER) - { - s_playerSecMoved = JTRUE; - } - } - - // returns 0 if the object does NOT overlap, otherwise non-zero. - // objSide: 0 = no overlap, -1/+1 front or behind. - JBool sector_objOverlapsWall(RWall* wall, SecObject* obj, s32* objSide) - { - *objSide = 0; - RSector* next = wall->nextSector; - if (next) - { - RSector* sector = wall->sector; - if (sector->floorHeight >= obj->posWS.y) - { - fixed16_16 objTop = obj->posWS.y - obj->worldHeight; - if (sector->ceilingHeight < objTop) - { - return JFALSE; - } - } - } - - const fixed16_16 threeQuartWidth = obj->worldWidth/2 + obj->worldWidth/4; - - vec2_fixed* w0 = wall->w0; - // Given a 2D direction: Dx, Dz; the perpendicular (normal) = -Dz, Dx - fixed16_16 nrmX = wall->wallDir.z; - fixed16_16 nrmZ = wall->wallDir.x; - fixed16_16 len = wall->length; - fixed16_16 dx = obj->posWS.x - w0->x; - fixed16_16 dz = obj->posWS.z - w0->z; - - fixed16_16 proj = mul16(dx, nrmZ) + mul16(dz, nrmX); - fixed16_16 minSepDist = threeQuartWidth * 2 + len; // 1.5 * width + length - if (u32(proj + threeQuartWidth) <= u32(minSepDist)) - { - fixed16_16 perpDist = mul16(dx, nrmX) - mul16(dz, nrmZ); - s32 side = (perpDist >= 0) ? 1 : -1; - - *objSide = side; - if (abs(perpDist) <= threeQuartWidth) - { - return JTRUE; - } - } - return JFALSE; - } - - // returns 0 if the wall is free to move, else non-zero. - JBool sector_canWallMove(RWall* wall, fixed16_16 offsetX, fixed16_16 offsetZ) - { - // Test the initial position, the code assumes there is no collision at this point. - s32 objSide0 = 0; - sector_objOverlapsWall(wall, s_playerObject, &objSide0); - - vec2_fixed* w0 = wall->w0; - fixed16_16 x0 = w0->x; - fixed16_16 z0 = w0->z; - w0->x += offsetX; - w0->z += offsetZ; - - // Then move the wall and test the new position. - s32 objSide1 = 0; - JBool col = sector_objOverlapsWall(wall, s_playerObject, &objSide1); - - // Restore the wall. - w0->x = x0; - w0->z = z0; - - if (col || ((objSide0 & objSide1) && (objSide0 != objSide1))) { return JTRUE; } - return JFALSE; - } - - void sector_getFloorAndCeilHeight(RSector* sector, fixed16_16* floorHeight, fixed16_16* ceilHeight) - { - *floorHeight = sector->floorHeight; - *ceilHeight = sector->ceilingHeight; - - if (sector->flags1 & SEC_FLAGS1_PIT) - { - *floorHeight += SEC_SKY_HEIGHT; - } - if (sector->flags1 & SEC_FLAGS1_EXTERIOR) - { - *ceilHeight -= SEC_SKY_HEIGHT; - } - } - - void sector_getObjFloorAndCeilHeight(RSector* sector, fixed16_16 y, fixed16_16* floorHeight, fixed16_16* ceilHeight) - { - fixed16_16 secHeight = sector->secHeight; - fixed16_16 bottom = y - COL_SEC_HEIGHT_OFFSET; - if (secHeight < 0) - { - fixed16_16 height = sector->floorHeight + sector->secHeight; - if (bottom <= height) - { - *floorHeight = height; - *ceilHeight = sector->ceilingHeight; - } - else - { - *floorHeight = sector->floorHeight; - *ceilHeight = height; - } - } - else // secHeight >= 0 - { - *floorHeight = sector->floorHeight + sector->secHeight; - *ceilHeight = sector->ceilingHeight; - } - if (sector->flags1 & SEC_FLAGS1_PIT) - { - *floorHeight += SEC_SKY_HEIGHT; - } - if (sector->flags1 & SEC_FLAGS1_EXTERIOR) - { - *ceilHeight -= SEC_SKY_HEIGHT; - } - } - - void sector_moveObject(SecObject* obj, fixed16_16 offsetX, fixed16_16 offsetZ) - { - if (obj->flags & OBJ_FLAG_MOVABLE) - { - s32 height = obj->worldHeight + HALF_16; - CollisionInfo info = - { - obj, - offsetX, 0, offsetZ, - 0, COL_INFINITY, height, 0, - 0, 0, 0, // to be filled in later. - obj->worldWidth, - }; - handleCollision(&info); - - if (info.responseStep && info.wall) - { - handleCollisionResponseSimple(info.responseDir.x, info.responseDir.z, &info.offsetX, &info.offsetZ); - handleCollision(&info); - } - - RSector* newSector = sector_which3D(obj->posWS.x, obj->posWS.y, obj->posWS.z); - if (newSector) - { - if (newSector != obj->sector && (obj->entityFlags & (ETFLAG_CORPSE | ETFLAG_PICKUP))) - { - obj->posWS.y = newSector->colSecHeight; - } - sector_addObject(newSector, obj); - } - } - } - - void sector_moveObjects(RSector* sector, u32 flags, fixed16_16 offsetX, fixed16_16 offsetZ) - { - JBool ceiling = (flags & INF_EFLAG_MOVE_CEIL)!=0 ? JTRUE : JFALSE; - JBool offset = (flags & INF_EFLAG_MOVE_SECHT)!=0 ? JTRUE : JFALSE; - JBool floor = (flags & INF_EFLAG_MOVE_FLOOR)!=0 ? JTRUE : JFALSE; - - SecObject** objList = sector->objectList; - for (s32 i = 0, idx = 0; i < sector->objectCount && idx < sector->objectCapacity; idx++) - { - SecObject* obj = objList[idx]; - if (obj) - { - i++; - if ((obj->flags & OBJ_FLAG_MOVABLE) && (obj->entityFlags != ETFLAG_PLAYER)) - { - if ((floor && obj->posWS.y == sector->floorHeight) || - (offset && sector->secHeight && sector->floorHeight + sector->secHeight == obj->posWS.y) || - (ceiling && obj->posWS.y == sector->ceilingHeight)) - { - sector_moveObject(obj, offsetX, offsetZ); - } - } - } - } - } - - // Tests if a point (p2) is to the left, on or right of an infinite line (p0 -> p1). - // Return: >0 p2 is on the left of the line. - // =0 p2 is on the line. - // <0 p2 is on the right of the line. - f32 isLeft(Vec2f p0, Vec2f p1, Vec2f p2) - { - return (p1.x - p0.x) * (p2.z - p0.z) - (p2.x - p0.x) * (p1.z - p0.z); - } -} // namespace TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Level/rsector.h b/components/darkforces/tfe/TFE_Jedi/Level/rsector.h deleted file mode 100644 index 9b5be47a..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Level/rsector.h +++ /dev/null @@ -1,170 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Sector -////////////////////////////////////////////////////////////////////// -#include -#include -#include - -using namespace TFE_Jedi; - -struct Allocator; -struct TextureData; - -struct RWall; -struct SecObject; - -enum SectorFlags1 -{ - SEC_FLAGS1_EXTERIOR = FLAG_BIT(0), - SEC_FLAGS1_DOOR = FLAG_BIT(1), - SEC_FLAGS1_MAG_SEAL = FLAG_BIT(2), - SEC_FLAGS1_EXT_ADJ = FLAG_BIT(3), - SEC_FLAGS1_ICE_FLOOR = FLAG_BIT(4), - SEC_FLAGS1_SNOW_FLOOR = FLAG_BIT(5), - SEC_FLAGS1_EXP_WALL = FLAG_BIT(6), - SEC_FLAGS1_PIT = FLAG_BIT(7), - SEC_FLAGS1_EXT_FLOOR_ADJ = FLAG_BIT(8), - SEC_FLAGS1_CRUSHING = FLAG_BIT(9), - SEC_FLAGS1_NOWALL_DRAW = FLAG_BIT(10), - SEC_FLAGS1_LOW_DAMAGE = FLAG_BIT(11), - SEC_FLAGS1_HIGH_DAMAGE = FLAG_BIT(12), - SEC_FLAGS1_NO_SMART_OBJ = FLAG_BIT(13), - SEC_FLAGS1_SMART_OBJ = FLAG_BIT(14), - SEC_FLAGS1_SUBSECTOR = FLAG_BIT(15), - SEC_FLAGS1_SAFESECTOR = FLAG_BIT(16), - SEC_FLAGS1_RENDERED = FLAG_BIT(17), - SEC_FLAGS1_PLAYER = FLAG_BIT(18), - SEC_FLAGS1_SECRET = FLAG_BIT(19), -}; - -// Added for TFE to support floating point and GPU sub-renderers. -// Floating point or GPU based sector data should be cached and only parts updated based -// on these flags. -enum SectorDirtyFlags -{ - SDF_NONE = 0, - // Texture Offsets - SDF_WALL_OFFSETS = FLAG_BIT(0), - SDF_FLAT_OFFSETS = FLAG_BIT(1), - // Geometry - SDF_VERTICES = FLAG_BIT(2), - SDF_HEIGHTS = FLAG_BIT(3), - SDF_WALL_SHAPE = FLAG_BIT(4), - // Lighting - SDF_AMBIENT = FLAG_BIT(5), - // Objects - SDF_CHANGE_OBJ = FLAG_BIT(6), - // Initial setup. - SDF_INIT_SETUP = FLAG_BIT(7), - // Wall change flags. - SDF_WALL_CHANGE = (SDF_INIT_SETUP | SDF_WALL_OFFSETS | SDF_WALL_SHAPE | SDF_HEIGHTS), - // Everything. - SDF_ALL = 0xffffffff -}; - -enum SectorConstants -{ - SEC_SKY_HEIGHT = FIXED(100), -}; - -struct RSector -{ - RSector* self; - s32 id; - s32 index; // 'index' was added for TFE to help with sector caching, since id is not necessarily match the index. - s32 prevDrawFrame; // previous frame that this sector was drawn/updated. - s32 prevDrawFrame2; // previous frame drawn (again...) - - // Vertices. - s32 vertexCount; // number of vertices. - vec2_fixed* verticesWS; // world space and view space XZ vertex positions. - vec2_fixed* verticesVS; - - // Walls. - s32 wallCount; // number of walls. - RWall* walls; // wall list. - - // Render heights. - fixed16_16 floorHeight; // floor height (Y); -Y up, larger = lower. - fixed16_16 ceilingHeight; // ceiling height (Y); -Y up, smaller = higher. - fixed16_16 secHeight; // second height; equals floor height if second height in the data = 0. - fixed16_16 ambient; // sector ambient in fixed point in the range of [0.0, MAX_LIGHT_LEVEL] - - // Collision heights. - fixed16_16 colFloorHeight; - fixed16_16 colCeilHeight; - fixed16_16 colSecHeight; - fixed16_16 colSecCeilHeight; - - // INF - Allocator* infLink; - - // Textures - TextureData** floorTex; - TextureData** ceilTex; - - // Texture offsets - vec2_fixed floorOffset; - vec2_fixed ceilOffset; - - // Objects - s32 objectCount; - SecObject** objectList; - s32 objectCapacity; - - // Collision tracking. - s32 collisionFrame; - - // Rendering wall segment tracking. - s32 startWall; // wall segment start index for rendering - s32 drawWallCnt; // wall segment draw count for rendering - - // Flags & Layer. - u32 flags1; // sector flags. - u32 flags2; - u32 flags3; - s32 layer; - - // Bounds - vec2_fixed boundsMin; - vec2_fixed boundsMax; - - // Added for TFE, to support floating point and GPU sub-renderers. - u32 dirtyFlags; -}; - -namespace TFE_Jedi -{ - void sector_clear(RSector* sector); - void sector_setupWallDrawFlags(RSector* sector); - void sector_adjustHeights(RSector* sector, fixed16_16 floorOffset, fixed16_16 ceilOffset, fixed16_16 secondHeightOffset); - void sector_computeBounds(RSector* sector); - - fixed16_16 sector_getMaxObjectHeight(RSector* sector); - JBool sector_moveWalls(RSector* sector, fixed16_16 delta, fixed16_16 dirX, fixed16_16 dirZ, u32 flags); - void sector_changeWallLight(RSector* sector, fixed16_16 delta); - void sector_scrollWalls(RSector* sector, fixed16_16 offsetX, fixed16_16 offsetZ); - - void sector_adjustTextureWallOffsets_Floor(RSector* sector, fixed16_16 floorDelta); - void sector_adjustTextureMirrorOffsets_Floor(RSector* sector, fixed16_16 floorDelta); - - void sector_addObject(RSector* sector, SecObject* obj); - void sector_addObjectDirect(RSector* sector, SecObject* obj); - void sector_removeObject(SecObject* obj); - - RSector* sector_which3D(fixed16_16 dx, fixed16_16 dy, fixed16_16 dz); - RSector* sector_which3D_Map(fixed16_16 dx, fixed16_16 dz, s32 layer); - bool sector_pointInside(RSector* sector, fixed16_16 x, fixed16_16 z); - JBool sector_pointInsideDF(RSector* sector, fixed16_16 x, fixed16_16 z); - - void sector_getFloorAndCeilHeight(RSector* sector, fixed16_16* floorHeight, fixed16_16* ceilHeight); - void sector_getObjFloorAndCeilHeight(RSector* sector, fixed16_16 y, fixed16_16* floorHeight, fixed16_16* ceilHeight); - - void sector_changeGlobalLightLevel(); - void sector_removeCorpses(RSector* sector); - - JBool sector_canRotateWalls(RSector* sector, angle14_32 angle, fixed16_16 centerX, fixed16_16 centerZ); - void sector_rotateWalls(RSector* sector, fixed16_16 centerX, fixed16_16 centerZ, angle14_32 angle, u32 rotateFlags); - void sector_rotateObjects(RSector* sector, angle14_32 deltaAngle, fixed16_16 centerX, fixed16_16 centerZ, u32 flags); -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Level/rtexture.cpp b/components/darkforces/tfe/TFE_Jedi/Level/rtexture.cpp deleted file mode 100644 index 8179a177..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Level/rtexture.cpp +++ /dev/null @@ -1,717 +0,0 @@ -#include - -#include "rtexture.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace TFE_DarkForces; -using namespace TFE_Memory; - -namespace TFE_Jedi -{ - enum - { - DF_BM_VERSION = 30, - DF_ANIM_ID = 2, - }; - - struct LevelTexture - { - std::string name; - TextureData* texture; - }; - typedef std::vector TextureList; - typedef std::unordered_map TextureTable; - - struct TextureState - { - Allocator* textureAnimAlloc = nullptr; - Task* textureAnimTask = nullptr; - MemoryRegion* memoryRegion = nullptr; - s32 animTexIndex = 0; - }; - static TextureState s_texState = {}; - static std::vector s_buffer; - static std::vector s_tempTextureList; - - static TextureList s_textureList[POOL_COUNT]; - static TextureTable s_textureTable[POOL_COUNT]; - - void decompressColumn_Type1(const u8* src, u8* dst, s32 pixelCount); - void decompressColumn_Type2(const u8* src, u8* dst, s32 pixelCount); - void textureAnimationTaskFunc(MessageType msg); - - u8 readByte(const u8*& data) - { - u8 res = *data; - data++; - return res; - } - - s16 readShort(const u8*& data) - { - s16 res = *((s16*)data); - data += 2; - return TFE_Endian::le16_to_cpu(res); - } - - u16 readUShort(const u8*& data) - { - u16 res = *((u16*)data); - data += 2; - return TFE_Endian::le16_to_cpu(res); - } - - s32 readInt(const u8*& data) - { - s32 res = *((s32*)data); - data += 4; - return TFE_Endian::le32_to_cpu(res); - } - - void bitmap_setupAnimationTask() - { - s_texState.textureAnimTask = createSubTask("texture animation", textureAnimationTaskFunc); - s_texState.textureAnimAlloc = allocator_create(sizeof(AnimatedTexture)); - s_texState.animTexIndex = 0; - } - - Allocator* bitmap_getAnimTextureAlloc() - { - return s_texState.textureAnimAlloc; - } - - MemoryRegion* bitmap_getAllocator() - { - return s_texState.memoryRegion; - } - - void bitmap_setAllocator(MemoryRegion* allocator) - { - s_texState.memoryRegion = allocator; - } - - // Added for TFE to clear out per-level texture data. - void bitmap_clearLevelData() - { - s_textureList[POOL_LEVEL].clear(); - s_textureTable[POOL_LEVEL].clear(); - } - - void bitmap_clearAll() - { - s_texState = {}; - for (s32 p = 0; p < POOL_COUNT; p++) - { - s_textureList[p].clear(); - s_textureTable[p].clear(); - } - } - - bool bitmap_getTextureIndex(TextureData* tex, s32* index, AssetPool* pool) - { - for (s32 p = 0; p < POOL_COUNT; p++) - { - s32 count = (s32)s_textureList[p].size(); - const LevelTexture* srcList = s_textureList[p].data(); - for (s32 i = 0; i < count; i++) - { - if (srcList[i].texture == tex) - { - *index = i; - *pool = AssetPool(p); - return true; - } - } - } - return false; - } - - TextureData* bitmap_getTextureByIndex(s32 index, AssetPool pool) - { - return s_textureList[pool][index].texture; - } - - const char* bitmap_getTextureName(s32 index, AssetPool pool) - { - return s_textureList[pool][index].name.c_str(); - } - - // Serialize only level textures. - void bitmap_serializeLevelTextures(Stream* stream) - { - s32 count = 0; - LevelTexture* list = nullptr; - if (serialization_getMode() == SMODE_WRITE) - { - count = (s32)s_textureList[POOL_LEVEL].size(); - } - SERIALIZE(SaveVersionInit, count, 0); - if (serialization_getMode() == SMODE_READ) - { - s_textureList[POOL_LEVEL].resize(count); - s_textureTable[POOL_LEVEL].clear(); - } - list = s_textureList[POOL_LEVEL].data(); - - for (s32 i = 0; i < count; i++, list++) - { - // Assume names are less than 256 characters. - u8 length = 0; - if (serialization_getMode() == SMODE_WRITE) - { - length = (u8)list->name.length(); - } - SERIALIZE(SaveVersionInit, length, 0); - if (serialization_getMode() == SMODE_READ) - { - list->name.resize(length); - } - SERIALIZE_BUF(SaveVersionInit, &list->name[0], length); - - // If reading, we need to load the texture now. - if (serialization_getMode() == SMODE_READ) - { - const char* name = list->name.c_str(); - list->texture = bitmap_load(name, 1, POOL_LEVEL, false); - s_textureTable[POOL_LEVEL][name] = i; - } - } - } - - TextureData** bitmap_getTextures(s32* textureCount, AssetPool pool) - { - assert(textureCount); - s32 count = (s32)s_textureList[pool].size(); - s_tempTextureList.resize(count); - TextureData** list = s_tempTextureList.data(); - const LevelTexture* srcList = s_textureList[pool].data(); - for (s32 i = 0; i < count; i++) - { - list[i] = srcList[i].texture; - } - *textureCount = count; - return list; - } - - TextureData* bitmap_load(const char* name, u32 decompress, AssetPool pool, bool addToCache) - { - // TFE: Keep track of per-level texture state for serialization. - // This is also useful for handling per-level GPU texture mirrors. - TextureTable::iterator iTex = s_textureTable[pool].find(name); - if (iTex != s_textureTable[pool].end()) - { - return s_textureList[pool][iTex->second].texture; - } - - FilePath filepath; - if (!TFE_Paths::getFilePath(name, &filepath)) - { - return nullptr; - } - - FileStream file; - if (!file.open(&filepath, Stream::MODE_READ)) - { - return nullptr; - } - - size_t size = file.getSize(); - s_buffer.resize(size); - file.readBuffer(s_buffer.data(), (u32)size); - file.close(); - - TextureData* texture = (TextureData*)region_alloc(s_texState.memoryRegion, sizeof(TextureData)); - const u8* data = s_buffer.data(); - const u8* fheader = data; - data += 3; - - if (strncmp((char*)fheader, "BM ", 3)) - { - TFE_System::logWrite(LOG_ERROR, "bitmap_load", "File '%s' is not a valid BM file.", filepath); - return nullptr; - } - - u8 version = readByte(data); - if (version != DF_BM_VERSION) - { - TFE_System::logWrite(LOG_ERROR, "bitmap_load", "File '%s' has invalid BM version '%u'.", filepath, version); - return nullptr; - } - - texture->width = readUShort(data); - texture->height = readUShort(data); - texture->uvWidth = readShort(data); - texture->uvHeight = readShort(data); - texture->flags = readByte(data); - texture->logSizeY = readByte(data); - texture->compressed = readByte(data); - texture->animSetup = 0; - // value is ignored. - data++; - - if (texture->compressed) - { - s32 inSize = readInt(data); - // values are ignored. - data += 12; - - if (decompress & 1) - { - texture->dataSize = texture->width * texture->height; - texture->image = (u8*)region_alloc(s_texState.memoryRegion, texture->dataSize); - - const u8* inBuffer = data; - data += inSize; - - const u32* columns = (u32*)data; - data += sizeof(u32) * texture->width; - - if (texture->compressed == 1) - { - u8* dst = texture->image; - for (s32 i = 0; i < texture->width; i++, dst += texture->height) - { - const u8* src = &inBuffer[TFE_Endian::le32_to_cpu(columns[i])]; - decompressColumn_Type1(src, dst, texture->height); - } - } - else if (texture->compressed == 2) - { - u8* dst = texture->image; - for (s32 i = 0; i < texture->width; i++, dst += texture->height) - { - const u8* src = &inBuffer[TFE_Endian::le32_to_cpu(columns[i])]; - decompressColumn_Type2(src, dst, texture->height); - } - } - texture->compressed = 0; - texture->columns = nullptr; - } - else - { - texture->dataSize = inSize; - texture->image = (u8*)region_alloc(s_texState.memoryRegion, texture->dataSize); - memcpy(texture->image, data, texture->dataSize); - data += texture->dataSize; - - texture->columns = (u32*)region_alloc(s_texState.memoryRegion, texture->width * sizeof(u32)); - memcpy(texture->columns, data, texture->width * sizeof(u32)); - data += texture->width * sizeof(u32); - } - } - else - { - texture->dataSize = texture->width * texture->height; - // Datasize, ignored. - data += 4; - texture->columns = nullptr; - - // Padding, ignored. - data += 12; - - // Allocate and read the BM image. - texture->image = (u8*)region_alloc(s_texState.memoryRegion, texture->dataSize); - memcpy(texture->image, data, texture->dataSize); - data += texture->dataSize; - } - - // Add the texture to the level texture cache if appropriate. - if (addToCache) - { - s32 index = (s32)s_textureList[pool].size(); - s_textureList[pool].push_back({ name, texture }); - s_textureTable[pool][name] = index; - } - - texture->animIndex = -1; - texture->frameIdx = -1; - texture->animPtr = nullptr; - - return texture; - } - - TextureData* bitmap_loadFromMemory(const u8* data, size_t size, u32 decompress) - { - TextureData* texture = (TextureData*)malloc(sizeof(TextureData)); - const u8* fheader = data; - data += 3; - - if (strncmp((char*)fheader, "BM ", 3)) - { - TFE_System::logWrite(LOG_ERROR, "bitmap_load", "Load From Memory - invalid data."); - return nullptr; - } - - u8 version = readByte(data); - if (version != DF_BM_VERSION) - { - TFE_System::logWrite(LOG_ERROR, "bitmap_load", "Load From Memory - invalid BM version '%u'.", version); - return nullptr; - } - - texture->width = readUShort(data); - texture->height = readUShort(data); - texture->uvWidth = readShort(data); - texture->uvHeight = readShort(data); - texture->flags = readByte(data); - texture->logSizeY = readByte(data); - texture->compressed = readByte(data); - texture->animSetup = 0; - // value is ignored. - data++; - - if (texture->compressed) - { - s32 inSize = readInt(data); - // values are ignored. - data += 12; - - if (decompress & 1) - { - texture->dataSize = texture->width * texture->height; - texture->image = (u8*)malloc(texture->dataSize); - - const u8* inBuffer = data; - data += inSize; - - const u32* columns = (u32*)data; - data += sizeof(u32) * texture->width; - - if (texture->compressed == 1) - { - u8* dst = texture->image; - for (s32 i = 0; i < texture->width; i++, dst += texture->height) - { - const u8* src = &inBuffer[columns[i]]; - decompressColumn_Type1(src, dst, texture->height); - } - } - else if (texture->compressed == 2) - { - u8* dst = texture->image; - for (s32 i = 0; i < texture->width; i++, dst += texture->height) - { - const u8* src = &inBuffer[columns[i]]; - decompressColumn_Type2(src, dst, texture->height); - } - } - texture->compressed = 0; - texture->columns = nullptr; - } - else - { - texture->dataSize = inSize; - texture->image = (u8*)malloc(texture->dataSize); - memcpy(texture->image, data, texture->dataSize); - data += texture->dataSize; - - texture->columns = (u32*)malloc(texture->width * sizeof(u32)); - if (texture->columns) - { - memcpy(texture->columns, data, texture->width * sizeof(u32)); - } - data += texture->width * sizeof(u32); - } - } - else - { - texture->dataSize = texture->width * texture->height; - // Datasize, ignored. - data += 4; - texture->columns = nullptr; - - // Padding, ignored. - data += 12; - - // Allocate and read the BM image. - texture->image = (u8*)malloc(texture->dataSize); - if (texture->image) - { - memcpy(texture->image, data, texture->dataSize); - } - data += texture->dataSize; - } - - return texture; - } - - Allocator* bitmap_getAnimatedTextures() - { - return s_texState.textureAnimAlloc; - } - - AnimatedTexture* bitmap_createAnimatedTexture(TextureData** texture, s32 index, u8& frameRate) - { - TextureData* tex = *texture; - frameRate = tex->image[0]; - u8 animatedId = tex->image[1]; - - // if animatedId != DF_ANIM_ID, then this is not a properly setup animated texture. - if (animatedId != DF_ANIM_ID) - { - TFE_System::logWrite(LOG_WARNING, "bitmap_setupAnimatedTexture", "Invalid animatedId %u, should be %u.", animatedId, DF_ANIM_ID); - tex->uvWidth = 0; - return nullptr; - } - - // In the original DOS code, this is directly set to pointers. But since TFE is compiled as 64-bit, pointers are not the correct size. - const u32* textureOffsets = (u32*)(tex->image + 2); - AnimatedTexture* anim = (AnimatedTexture*)allocator_newItem(s_texState.textureAnimAlloc); - - // 64 bit pointers are larger than the offsets, so we have to allocate more space (for now). - anim->frame = 0; - anim->count = tex->uvHeight; // frame count is packed into uvHeight. - anim->texPtr = texture; // pointer to the texture pointer, allowing us to update that pointer later. - anim->baseFrame = tex; - anim->baseData = tex->image; - anim->frameList = (TextureData**)level_alloc(sizeof(TextureData**) * anim->count); - // Allocate frame memory here since load-in-place does not work because structure size changes. - TextureData* outFrames = (TextureData*)level_alloc(sizeof(TextureData) * anim->count); - assert(anim->frameList); - - const u8* base = tex->image + 2; - for (s32 i = 0; i < anim->count; i++) - { - const TextureData* frame = (TextureData*)(base + TFE_Endian::le32_to_cpu(textureOffsets[i])); - outFrames[i] = *frame; - outFrames[i].width = TFE_Endian::le16_to_cpu(outFrames[i].width); - outFrames[i].height = TFE_Endian::le16_to_cpu(outFrames[i].height); - outFrames[i].uvWidth = TFE_Endian::le16_to_cpu(outFrames[i].uvWidth); - outFrames[i].uvHeight = TFE_Endian::le16_to_cpu(outFrames[i].uvHeight); - - // Somehow this doesn't crash in DOS... - if (outFrames[i].width >= 16384 || outFrames[i].height >= 16384) - { - outFrames[i] = outFrames[0]; - } - - // Allocate an image buffer since everything no longer fits nicely. - outFrames[i].image = (u8*)level_alloc(outFrames[i].width * outFrames[i].height); - memcpy(outFrames[i].image, (u8*)frame + 0x1c, outFrames[i].width * outFrames[i].height); - - // We have to make sure the structure offsets line up with DOS... - outFrames[i].flags = *((u8*)frame + 0x18); - outFrames[i].compressed = *((u8*)frame + 0x19); - outFrames[i].animIndex = index; - outFrames[i].frameIdx = i; - outFrames[i].animPtr = anim; - outFrames[i].animSetup = 1; - outFrames[i].columns = nullptr; - - anim->frameList[i] = &outFrames[i]; - } - return anim; - } - - bool bitmap_setupAnimatedTexture(TextureData** texture, s32 index) - { - if ((*texture)->animSetup) - { - // If it is already animated, then setup. - AnimatedTexture* anim = (AnimatedTexture*)(*texture)->animPtr; - if (anim && anim->count) - { - *texture = anim->frameList[0]; - } - return true; - } - (*texture)->animSetup = 1; - - u8 frameRate; - AnimatedTexture* anim = bitmap_createAnimatedTexture(texture, index, frameRate); - if (!anim) { return false; } - - TextureData* tex = *texture; - - if (frameRate) - { - anim->delay = time_frameRateToDelay(u32(frameRate)); // Delay is in "ticks." - anim->nextTick = 0; - *texture = anim->frameList[0]; - } - else - { - // Hold indefinitely. - anim->nextTick = 0xffffffff; - // The "image" is really the animation. - tex->image = (u8*)anim; - tex->animIndex = index; - tex->frameIdx = -1; - tex->animPtr = nullptr; // This is set to NULL since it is handled in the INF serialization. - } - s_texState.animTexIndex++; - return true; - } - - void bitmap_write(const char* filePath, u16 width, u16 height, u8* image, u8 flags) - { - const u32 pixelCount = u32(width) * u32(height); - - FileStream bmFile; - if (bmFile.open(filePath, Stream::MODE_WRITE)) - { - char fheader[3] = { 'B', 'M', ' ' }; - bmFile.writeBuffer(fheader, 3); - - u8 version = DF_BM_VERSION; - bmFile.write(&version); - - u8 logSizeY = TFE_Math::log2(height); - u8 compressed = 0; - u8 unused = 0; - bmFile.write(&width); - bmFile.write(&height); - bmFile.write(&width); // uvWidth - bmFile.write(&height); // uvHeight - bmFile.write(&flags); - bmFile.write(&logSizeY); - bmFile.write(&compressed); - bmFile.write(&unused); - bmFile.write(&pixelCount); // dataSize - - u8 padding[12] = { 0 }; - bmFile.writeBuffer(padding, 12); - - // Image data. - bmFile.writeBuffer(image, pixelCount); - bmFile.close(); - } - } - - void bitmap_writeOpaque(const char* filePath, u16 width, u16 height, u8* image) - { - bitmap_write(filePath, width, height, image, 0); - } - - void bitmap_writeTransparent(const char* filePath, u16 width, u16 height, u8* image) - { - bitmap_write(filePath, width, height, image, OPACITY_TRANS); - } - - // Per frame animated texture update. - void textureAnimationTaskFunc(MessageType msg) - { - task_begin; - while (msg != MSG_FREE_TASK) - { - // No persistent state is required. - { - AnimatedTexture* animTex = (AnimatedTexture*)allocator_getHead(s_texState.textureAnimAlloc); - while (animTex) - { - if (animTex->nextTick < s_curTick) - { - if (animTex->nextTick == 0) - { - animTex->nextTick = s_curTick; - } - - animTex->frame++; - if (animTex->frame >= animTex->count) - { - animTex->frame = 0; - } - - *animTex->texPtr = animTex->frameList[animTex->frame]; - animTex->nextTick += animTex->delay; - } - animTex = (AnimatedTexture*)allocator_getNext(s_texState.textureAnimAlloc); - } - } - task_yield(TASK_NO_DELAY); - } - task_end; - } - - // Type 1: RLE with runs of solid colors. Costs 2 bytes per solid-color run. - void decompressColumn_Type1(const u8* src, u8* dst, s32 pixelCount) - { - while (pixelCount) - { - const u8 value = *src; - src++; - - if (value & 0x80) - { - const u8 color = *src; - src++; - - const u32 count = value & 0x7f; - // store packed at dst - for (u32 i = 0; i < count; i++, dst++) - { - *dst = color; - } - pixelCount -= count; - } - else - { - const u32 count = value; - // store packed at dst - for (u32 i = 0; i < count; i++, dst++, src++) - { - *dst = *src; - } - pixelCount -= count; - } - } - } - - // Type 2: RLE with runs of transparent texels (useful for sprites). Costs 1 byte per transparent run. - void decompressColumn_Type2(const u8* src, u8* dst, s32 pixelCount) - { - while (pixelCount) - { - const u8 value = *src; - src++; - - if (value & 0x80) - { - const u32 count = value & 0x7f; - // store 0 at dst - memset(dst, 0, count); - dst += count; - pixelCount -= count; - } - else - { - const u32 count = value; - // store packed at dst - for (u32 i = 0; i < count; i++, dst++, src++) - { - *dst = *src; - } - pixelCount -= count; - } - } - } -} -#ifdef TFE_ESPBOX -// The file read scratch buffer keeps the capacity of the largest file loaded; -// release it when the game is shut down (called from the platform glue). -void espbox_free_rtexture_scratch() -{ - std::vector().swap(TFE_Jedi::s_buffer); -} -#endif - -#ifdef TFE_ESPBOX -// Shutdown only: release this file's cached container storage so nothing is -// left in the 4MB ROM block when the session ends (see esp_alloc.cpp). -void espbox_release_rtexture_caches() -{ - std::vector().swap(TFE_Jedi::s_tempTextureList); - for (auto& list : TFE_Jedi::s_textureList) { TFE_Jedi::TextureList().swap(list); } - for (auto& table : TFE_Jedi::s_textureTable) { TFE_Jedi::TextureTable().swap(table); } -} -#endif diff --git a/components/darkforces/tfe/TFE_Jedi/Level/rtexture.h b/components/darkforces/tfe/TFE_Jedi/Level/rtexture.h deleted file mode 100644 index f65095b1..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Level/rtexture.h +++ /dev/null @@ -1,114 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include - -struct BM_Header -{ - s16 width; - s16 height; - s16 uvWidth; - s16 uvHeight; - u8 flags; - u8 logSizeY; - s16 compressed; - s32 dataSize; - u8 pad[12]; -}; - -enum OpacityFlags -{ - OPACITY_TRANS = FLAG_BIT(3), -}; - -// was BM_SubHeader -#pragma pack(push) -#pragma pack(1) -struct TextureData -{ - u16 width; // if = 1 then multiple BM in the file - u16 height; // EXCEPT if SizeY also = 1, in which case - // it is a 1x1 BM - s16 uvWidth; // portion of texture actually used - s16 uvHeight; // portion of texture actually used - - u32 dataSize; // Data size for compressed BM - // excluding header and columns starts table - // If not compressed, DataSize is unused - - u8 logSizeY; // logSizeY = log2(SizeY) - // logSizeY = 0 for weapons - u8 animSetup; // Added for TFE, a flag indicating that the animated texture has already been setup. - u16 textureId; // Added for TFE, replaces u8 pad1[3]; - - u8* image; // Image data. - u32* columns; // columns will be NULL except when compressed. - - // 4 bytes - u8 flags; - u8 compressed; // 0 = not compressed, 1 = compressed (RLE), 2 = compressed (RLE0) - u8 pad3[2]; - - // TFE - s32 animIndex = -1; - s32 frameIdx = 0; - void* animPtr = nullptr; -}; -#pragma pack(pop) - -// Animated texture object. -struct AnimatedTexture -{ - s32 count; // the number of things to iterate through. - s32 frame; // the current iteration index. - Tick delay; // the delay between iterations, in ticks. - Tick nextTick; // the next time this iterates. - TextureData** frameList; // the list of things to cycle through. - TextureData** texPtr; // iterates through a list every N seconds/ticks. - TextureData* baseFrame; // - u8* baseData; // -}; - -enum -{ - BM_ANIMATED_TEXTURE = -2, -}; - -struct MemoryRegion; - -namespace TFE_Jedi -{ - void bitmap_setupAnimationTask(); - - void bitmap_setAllocator(MemoryRegion* allocator); - MemoryRegion* bitmap_getAllocator(); - void bitmap_clearLevelData(); - void bitmap_clearAll(); - - // levelTexture bool was added for TFE to make serializing texture state easier. - // if levelTexture is false, then textures are not serialized and not cleared at level end. - TextureData* bitmap_load(const char* name, u32 decompress, AssetPool pool = POOL_LEVEL, bool addToCache = true); - bool bitmap_setupAnimatedTexture(TextureData** texture, s32 index); - - Allocator* bitmap_getAnimatedTextures(); - TextureData** bitmap_getTextures(s32* textureCount, AssetPool pool); - - bool bitmap_getTextureIndex(TextureData* tex, s32* index, AssetPool* pool); - TextureData* bitmap_getTextureByIndex(s32 index, AssetPool pool); - const char* bitmap_getTextureName(s32 index, AssetPool pool); - - // Used for tools. - TextureData* bitmap_loadFromMemory(const u8* data, size_t size, u32 decompress); - Allocator* bitmap_getAnimTextureAlloc(); - - // Serialization. - void bitmap_serializeLevelTextures(Stream* stream); - - void bitmap_writeOpaque(const char* filePath, u16 width, u16 height, u8* image); - void bitmap_writeTransparent(const char* filePath, u16 width, u16 height, u8* image); -} diff --git a/components/darkforces/tfe/TFE_Jedi/Level/rwall.cpp b/components/darkforces/tfe/TFE_Jedi/Level/rwall.cpp deleted file mode 100644 index 5e96fc4b..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Level/rwall.cpp +++ /dev/null @@ -1,162 +0,0 @@ -#include "rwall.h" -#include "rsector.h" -#include - -namespace TFE_Jedi -{ - void wall_setupAdjoinDrawFlags(RWall* wall) - { - if (wall->nextSector) - { - RSector* sector = wall->sector; - RWall* mirror = wall->mirrorWall; - fixed16_16 wFloorHeight = sector->floorHeight; - fixed16_16 wCeilHeight = sector->ceilingHeight; - - RSector* nextSector = mirror->sector; - fixed16_16 mFloorHeight = nextSector->floorHeight; - fixed16_16 mCeilHeight = nextSector->ceilingHeight; - wall->drawFlags = 0; - mirror->drawFlags = 0; - - if (wCeilHeight < mCeilHeight) - { - wall->drawFlags |= WDF_TOP; - } - if (wFloorHeight > mFloorHeight) - { - wall->drawFlags |= WDF_BOT; - } - if (mCeilHeight < wCeilHeight) - { - mirror->drawFlags |= WDF_TOP; - } - if (mFloorHeight > wFloorHeight) - { - mirror->drawFlags |= WDF_BOT; - } - } - } - - void wall_computeTexelHeights(RWall* wall) - { - wall->sector->dirtyFlags |= SDF_HEIGHTS; - - if (wall->nextSector) - { - if (wall->drawFlags & WDF_TOP) - { - RSector* next = wall->nextSector; - RSector* cur = wall->sector; - wall->topTexelHeight = (next->ceilingHeight - cur->ceilingHeight) << 3; - } - if (wall->drawFlags & WDF_BOT) - { - RSector* cur = wall->sector; - RSector* next = wall->nextSector; - wall->botTexelHeight = (cur->floorHeight - next->floorHeight) << 3; - } - - if (wall->midTex) - { - if (!(wall->drawFlags & WDF_BOT) && !(wall->drawFlags & WDF_TOP)) - { - RSector* midSector = wall->sector; - fixed16_16 midFloorHeight = wall->sector->floorHeight; - wall->midTexelHeight = (midFloorHeight - midSector->ceilingHeight) << 3; - } - else if (!(wall->drawFlags & WDF_BOT)) - { - RSector* midSector = wall->nextSector; - fixed16_16 midFloorHeight = wall->sector->floorHeight; - wall->midTexelHeight = (midFloorHeight - midSector->ceilingHeight) << 3; - } - else if (!(wall->drawFlags & WDF_TOP)) - { - RSector* midSector = wall->sector; - fixed16_16 midFloorHeight = wall->nextSector->floorHeight; - wall->midTexelHeight = (midFloorHeight - midSector->ceilingHeight) << 3; - } - else // WDF_TOP_AND_BOT - { - RSector* midSector = wall->nextSector; - fixed16_16 midFloorHeight = wall->nextSector->floorHeight; - wall->midTexelHeight = (midFloorHeight - midSector->ceilingHeight) << 3; - } - } - } - else - { - RSector* midSector = wall->sector; - fixed16_16 midFloorHeight = midSector->floorHeight; - wall->midTexelHeight = (midFloorHeight - midSector->ceilingHeight) << 3; - } - } - - fixed16_16 wall_computeDirectionVector(RWall* wall) - { - wall->sector->dirtyFlags |= SDF_WALL_SHAPE; - - // Calculate dx and dz - fixed16_16 dx = wall->w1->x - wall->w0->x; - fixed16_16 dz = wall->w1->z - wall->w0->z; - - // The original DOS code converts to floating point here to compute the length but - // switches back to fixed point for the divide. - // Convert to floating point - f32 fdx = fixed16ToFloat(dx); - f32 fdz = fixed16ToFloat(dz); - // Compute the squared distance in floating point. - f32 lenSq = fdx * fdx + fdz * fdz; - f32 len = sqrtf(lenSq); - fixed16_16 lenFixed = floatToFixed16(len); - - if (lenFixed) - { - wall->wallDir.x = div16(dx, lenFixed); - wall->wallDir.z = div16(dz, lenFixed); - } - else - { - wall->wallDir.x = 0; - wall->wallDir.z = 0; - } - return lenFixed; - } - - void wall_getOpeningHeightRange(RWall* wall, fixed16_16* topRes, fixed16_16* botRes) - { - fixed16_16 curCeilHeight; - fixed16_16 curFloorHeight; - RSector* curSector = wall->sector; - RSector* nextSector = wall->nextSector; - sector_getFloorAndCeilHeight(curSector, &curFloorHeight, &curCeilHeight); - - fixed16_16 nextCeilHeight; - fixed16_16 nextFloorHeight; - sector_getFloorAndCeilHeight(nextSector, &nextFloorHeight, &nextCeilHeight); - - if (nextSector) // <- This check is too late... - { - // There is an upper wall since the current ceiling is higher than the next. - fixed16_16 top = curCeilHeight; - if (curCeilHeight <= nextCeilHeight) - { - top = nextCeilHeight; - } - *topRes = top; - - fixed16_16 bot = curFloorHeight; - if (curFloorHeight >= nextFloorHeight) - { - bot = nextFloorHeight; - } - *botRes = bot; - } - else - { - *topRes = COL_INFINITY; - *botRes = -COL_INFINITY; - } - } -} // namespace TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Level/rwall.h b/components/darkforces/tfe/TFE_Jedi/Level/rwall.h deleted file mode 100644 index ff19916a..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Level/rwall.h +++ /dev/null @@ -1,126 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include - -using namespace TFE_Jedi; - -struct TextureData; -struct Allocator; -struct RSector; - -enum WallDrawFlags -{ - WDF_MIDDLE = 0, - WDF_TOP = 1, - WDF_BOT = 2, - WDF_TOP_AND_BOT = 3, -}; - -enum WallFlags1 -{ - WF1_ADJ_MID_TEX = FLAG_BIT(0), // the mid texture is rendered even with adjoin (maskwall) - WF1_ILLUM_SIGN = FLAG_BIT(1), // render a sign. - WF1_FLIP_HORIZ = FLAG_BIT(2), // flip texture horizontally. - WF1_CHANGE_WALL_LIGHT = FLAG_BIT(3), // elevator can change wall light - WF1_TEX_ANCHORED = FLAG_BIT(4), - WF1_WALL_MORPHS = FLAG_BIT(5), - WF1_SCROLL_TOP_TEX = FLAG_BIT(6), // elevator can scroll various textures - WF1_SCROLL_MID_TEX = FLAG_BIT(7), - WF1_SCROLL_BOT_TEX = FLAG_BIT(8), - WF1_SCROLL_SIGN_TEX = FLAG_BIT(9), - WF1_HIDE_ON_MAP = FLAG_BIT(10), - WF1_SHOW_NORMAL_ON_MAP = FLAG_BIT(11), - WF1_SIGN_ANCHORED = FLAG_BIT(12), - WF1_DAMAGE_WALL = FLAG_BIT(13), // wall damages player - WF1_SHOW_AS_LEDGE_ON_MAP = FLAG_BIT(14), - WF1_SHOW_AS_DOOR_ON_MAP = FLAG_BIT(15), -}; - -// WallFlags2 used internally. - -enum WallFlags3 -{ - WF3_ALWAYS_WALK = FLAG_BIT(0), - WF3_SOLID_WALL = FLAG_BIT(1), - WF3_PLAYER_WALK_ONLY = FLAG_BIT(2), // players can walk through but not enemies. - WF3_CANNOT_FIRE_THROUGH = FLAG_BIT(3), // cannot fire through the wall. -}; - -struct RWall -{ - s32 id; - JBool seen; - s32 visible; - RSector* sector; - RSector* nextSector; - RWall* mirrorWall; - s32 drawFlags; // see WallDrawFlags - s32 mirror; // original mirror id. - - // Vertices (worldspace) - vec2_fixed* w0; - vec2_fixed* w1; - - // Vertices (viewspace). - vec2_fixed* v0; - vec2_fixed* v1; - - // Textures - pointer-to-pointer so that pointers can be changed by texture animation. - TextureData** topTex; - TextureData** midTex; - TextureData** botTex; - TextureData** signTex; - - // Wall length in texels. - fixed16_16 texelLength; - - // Wall heights in texels. - fixed16_16 topTexelHeight; - fixed16_16 midTexelHeight; - fixed16_16 botTexelHeight; - - // Texture Offsets - vec2_fixed topOffset; - vec2_fixed midOffset; - vec2_fixed botOffset; - vec2_fixed signOffset; - - // Direction and length. - vec2_fixed wallDir; - fixed16_16 length; - // Collision frame, to avoid checking a wall multiple times in the same collision query. - s32 collisionFrame; - - // Update Frame - s32 drawFrame; - - // INF - Allocator* infLink; - - // Flags - u32 flags1; - u32 flags2; - u32 flags3; - - // Original position 0, used for rotating walls. - vec2_fixed worldPos0; - - // Lighting - fixed16_16 wallLight; - - // Wall angle. - angle14_32 angle; -}; - -namespace TFE_Jedi -{ - void wall_setupAdjoinDrawFlags(RWall* wall); - void wall_computeTexelHeights(RWall* wall); - fixed16_16 wall_computeDirectionVector(RWall* wall); - - void wall_getOpeningHeightRange(RWall* wall, fixed16_16* topRes, fixed16_16* botRes); -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Math/core_math.cpp b/components/darkforces/tfe/TFE_Jedi/Math/core_math.cpp deleted file mode 100644 index 626e82c9..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Math/core_math.cpp +++ /dev/null @@ -1,296 +0,0 @@ -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// - -#include -#include -#include "core_math.h" - -namespace TFE_Jedi -{ - static s32 s_negArcCos; - - ///////////////////////////////////////////// - // Fixed point - ///////////////////////////////////////////// - void computeTransformFromAngles_Fixed(angle14_32 yaw, angle14_32 pitch, angle14_32 roll, fixed16_16* transform) - { - fixed16_16 sinYaw, cosYaw; - fixed16_16 sinPch, cosPch; - fixed16_16 sinRol, cosRol; - sinCosFixed(yaw, &sinYaw, &cosYaw); - sinCosFixed(pitch, &sinPch, &cosPch); - sinCosFixed(roll, &sinRol, &cosRol); - - transform[0] = mul16(cosYaw, cosRol); - transform[1] = mul16(cosPch, sinRol) + mul16(mul16(sinPch, sinYaw), cosPch); - transform[2] = mul16(sinPch, sinRol) - mul16(mul16(cosPch, sinYaw), cosRol); - - transform[3] = -mul16(cosYaw, sinRol); - transform[4] = mul16(cosPch, cosRol) - mul16(mul16(sinPch, sinYaw), sinRol); - transform[5] = mul16(sinPch, cosRol) + mul16(mul16(cosPch, sinYaw), sinRol); - - transform[6] = sinYaw; - transform[7] = -mul16(sinPch, cosYaw); - transform[8] = mul16(cosPch, cosYaw); - } - - void normalizeVec3(vec3_fixed* vIn, vec3_fixed* vOut) - { - fixed16_16 distSq = mul16(vIn->x, vIn->x) + mul16(vIn->y, vIn->y) + mul16(vIn->z, vIn->z); - fixed16_16 dist = fixedSqrt(distSq); - - if (dist > 0) - { - vOut->x = div16(vIn->x, dist); - vOut->y = div16(vIn->y, dist); - vOut->z = div16(vIn->z, dist); - } - else - { - vOut->x = 0; - vOut->y = 0; - vOut->z = 0; - } - } - - void rotateVectorM3x3(vec3_fixed* inVec, vec3_fixed* outVec, s32* mtx) - { - outVec->x = mul16(inVec->x, mtx[0]) + mul16(inVec->y, mtx[3]) + mul16(inVec->z, mtx[6]); - outVec->y = mul16(inVec->x, mtx[1]) + mul16(inVec->y, mtx[4]) + mul16(inVec->z, mtx[7]); - outVec->z = mul16(inVec->x, mtx[2]) + mul16(inVec->y, mtx[5]) + mul16(inVec->z, mtx[8]); - } - - angle14_32 vec2ToAngle(fixed16_16 dx, fixed16_16 dz) - { - if (dx == 0 && dz == 0) - { - return 0; - } - - const s32 signsDiff = (signV2A(dx) != signV2A(dz)) ? 1 : 0; - // Splits the view into 4 quadrants, 0 - 3: - // 1 | 0 - // ----- - // 2 | 3 - const s32 quadrant = (dz < 0 ? 2 : 0) + signsDiff; - - // Further splits the quadrants into sub-quadrants: - // \2|1/ - // 3\|/0 - //---*--- - // 4/|\7 - // /5|6\ - // - dx = abs(dx); - dz = abs(dz); - const s32 subquadrant = quadrant * 2 + ((dx < dz) ? (1 - signsDiff) : signsDiff); - - // true in sub-quadrants: 0, 3, 4, 7; where dz tends towards 0. - if ((subquadrant - 1) & 2) - { - // The original code did the "3 xor" trick to swap dx and dz. - std::swap(dx, dz); - } - - // next compute |dx| / |dz|, which will be a value from 0.0 to 1.0 - fixed16_16 dXdZ = div16(dx, dz); - if (subquadrant & 1) - { - // invert the ratio in sub-quadrants 1, 3, 5, 7 to maintain the correct direction. - dXdZ = ONE_16 - dXdZ; - } - - // subquadrantF is based on the sub-quadrant, essentially fixed16(subquadrant) - // which has a range of 0 to 7.0 (see above). - const fixed16_16 subquadrantF = intToFixed16(subquadrant); - // angle = (int(2.0 - (zF + dXdZ)) * 2048) & 16383 - // this flips the angle so that straight up (dx = 0, dz > 0) is 0, right is 90, down is 180. - const angle14_32 angle = (2 * ONE_16 - (subquadrantF + dXdZ)) >> 5; - // the final angle will be in the range of 0 - 16383 - return angle & ANGLE_MASK; - } - - fixed16_16 computeDirAndLength(fixed16_16 dx, fixed16_16 dz, fixed16_16* dirX, fixed16_16* dirZ) - { - fixed16_16 dist = vec2Length(dx, dz); - - if (dist) - { - *dirX = clamp(div16(dx, dist), -ONE_16, ONE_16); - *dirZ = clamp(div16(dz, dist), -ONE_16, ONE_16); - } - else - { - *dirX = 0; - *dirZ = 0; - } - - return dist; - } - - angle14_32 getAngleDifference(angle14_32 angle0, angle14_32 angle1) - { - angle0 &= ANGLE_MASK; - angle1 &= ANGLE_MASK; - - angle14_32 dAngle = angle1 - angle0; - if (abs(dAngle) <= 8191) // less than 180 degrees - { - return dAngle; - } - // Otherwise we have to compute the "shortest arc". - if (dAngle >= 0) - { - return dAngle - ANGLE_MAX - 1; - } - // dAngle < 0 - return dAngle + ANGLE_MAX; - } - - void mulMatrix3x3(fixed16_16* mtx0, fixed16_16* mtx1, fixed16_16* mtxOut) - { - mtxOut[0] = mul16(mtx0[0], mtx1[0]) + mul16(mtx0[3], mtx1[3]) + mul16(mtx0[6], mtx1[6]); - mtxOut[3] = mul16(mtx0[0], mtx1[1]) + mul16(mtx0[3], mtx1[4]) + mul16(mtx0[6], mtx1[7]); - mtxOut[6] = mul16(mtx0[0], mtx1[2]) + mul16(mtx0[3], mtx1[5]) + mul16(mtx0[6], mtx1[8]); - - mtxOut[1] = mul16(mtx0[1], mtx1[0]) + mul16(mtx0[4], mtx1[3]) + mul16(mtx0[7], mtx1[6]); - mtxOut[4] = mul16(mtx0[1], mtx1[1]) + mul16(mtx0[4], mtx1[4]) + mul16(mtx0[7], mtx1[7]); - mtxOut[7] = mul16(mtx0[1], mtx1[2]) + mul16(mtx0[4], mtx1[5]) + mul16(mtx0[7], mtx1[8]); - - mtxOut[2] = mul16(mtx0[2], mtx1[0]) + mul16(mtx0[5], mtx1[3]) + mul16(mtx0[8], mtx1[6]); - mtxOut[5] = mul16(mtx0[2], mtx1[1]) + mul16(mtx0[5], mtx1[4]) + mul16(mtx0[8], mtx1[7]); - mtxOut[8] = mul16(mtx0[2], mtx1[2]) + mul16(mtx0[5], mtx1[5]) + mul16(mtx0[8], mtx1[8]); - } - - angle14_32 arcCosFixed(fixed16_16 sinAngle, angle14_32 angle) - { - const fixed16_16* cosTable = s_cosTable; - if (sinAngle >= 0) - { - s_negArcCos = 0; - } - else - { - s_negArcCos = 1; - sinAngle = -angle; - } - s32 i = 0; - for (; i < 4095; i++, cosTable++) - { - if (sinAngle >= *cosTable) - { - break; - } - } - - angle14_32 resAngle = 4095 - i; - if (s_negArcCos) - { - resAngle += 8192; - } - return resAngle; - } - - ///////////////////////////////////////////// - // Floating point - ///////////////////////////////////////////// - void computeTransformFromAngles_Float(f32 yaw, f32 pitch, f32 roll, f32* transform) - { - f32 sinYaw, cosYaw; - f32 sinPch, cosPch; - f32 sinRol, cosRol; - sinCosFlt(yaw, &sinYaw, &cosYaw); - sinCosFlt(pitch, &sinPch, &cosPch); - sinCosFlt(roll, &sinRol, &cosRol); - - transform[0] = cosYaw * cosRol; - transform[1] = cosPch * sinRol + sinPch * sinYaw*cosPch; - transform[2] = sinPch * sinRol - cosPch * sinYaw*cosRol; - - transform[3] = -cosYaw * sinRol; - transform[4] = cosPch * cosRol - sinPch * sinYaw*sinRol; - transform[5] = sinPch * cosRol + cosPch * sinYaw*sinRol; - - transform[6] = sinYaw; - transform[7] = -sinPch * cosYaw; - transform[8] = cosPch * cosYaw; - } - - void normalizeVec3(vec3_float* vIn, vec3_float* vOut) - { - f32 distSq = vIn->x*vIn->x + vIn->y*vIn->y + vIn->z*vIn->z; - f32 dist = sqrtf(distSq); - - if (dist > FLT_EPSILON) - { - f32 scale = 1.0f / dist; - vOut->x = vIn->x * scale; - vOut->y = vIn->y * scale; - vOut->z = vIn->z * scale; - } - else - { - vOut->x = 0; - vOut->y = 0; - vOut->z = 0; - } - } - - void rotateVectorM3x3(vec3_float* inVec, vec3_float* outVec, f32* mtx) - { - outVec->x = inVec->x*mtx[0] + inVec->y*mtx[3] + inVec->z*mtx[6]; - outVec->y = inVec->x*mtx[1] + inVec->y*mtx[4] + inVec->z*mtx[7]; - outVec->z = inVec->x*mtx[2] + inVec->y*mtx[5] + inVec->z*mtx[8]; - } - - s32 vec2ToAngle(f32 dx, f32 dz) - { - if (dx == 0.0f && dz == 0.0f) - { - return 0; - } - - const s32 signsDiff = (signV2A(dx) != signV2A(dz)) ? 1 : 0; - // Splits the view into 4 quadrants, 0 - 3: - // 1 | 0 - // ----- - // 2 | 3 - const s32 quadrant = (dz < 0.0f ? 2 : 0) + signsDiff; - - // Further splits the quadrants into sub-quadrants: - // \2|1/ - // 3\|/0 - //---*--- - // 4/|\7 - // /5|6\ - // - dx = fabsf(dx); - dz = fabsf(dz); - const s32 subquadrant = quadrant * 2 + ((dx < dz) ? (1 - signsDiff) : signsDiff); - - // true in sub-quadrants: 0, 3, 4, 7; where dz tends towards 0. - if ((subquadrant - 1) & 2) - { - // The original code did the "3 xor" trick to swap dx and dz. - std::swap(dx, dz); - } - - // next compute |dx| / |dz|, which will be a value from 0.0 to 1.0 - f32 dXdZ = dx / dz; - if (subquadrant & 1) - { - // invert the ratio in sub-quadrants 1, 3, 5, 7 to maintain the correct direction. - dXdZ = 1.0f - dXdZ; - } - - // subquadrantF is based on the sub-quadrant, essentially fixed16(subquadrant) - // which has a range of 0 to 7.0 (see above). - const f32 subquadrantF = f32(subquadrant); - // this flips the angle so that straight up (dx = 0, dz > 0) is 0, right is 90, down is 180. - const f32 angle = 2.0f - (subquadrantF + dXdZ); - // the final angle will be in the range of 0 - 16383 - return s32(angle * 2048.0f) & ANGLE_MASK; - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Math/core_math.h b/components/darkforces/tfe/TFE_Jedi/Math/core_math.h deleted file mode 100644 index 0693f33e..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Math/core_math.h +++ /dev/null @@ -1,357 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include "fixedPoint.h" -#include "cosTable.h" - -namespace TFE_Jedi -{ - struct vec2_fixed - { - fixed16_16 x, z; - }; - - struct vec3_fixed - { - fixed16_16 x, y, z; - }; - - struct vec2_float - { - f32 x, z; - }; - - struct vec3_float - { - f32 x, y, z; - }; - - // Int/Fixed Point - inline s32 abs(s32 x) - { - return x < 0 ? -x : x; - } - - inline s32 min(s32 a, s32 b) - { - return a < b ? a : b; - } - - inline s32 max(s32 a, s32 b) - { - return a > b ? a : b; - } - - inline u32 min(u32 a, u32 b) - { - return a < b ? a : b; - } - - inline u32 max(u32 a, u32 b) - { - return a > b ? a : b; - } - - inline s32 clamp(s32 x, s32 a, s32 b) - { - return min(max(x, a), b); - } - - inline void swap(s32& a, s32& b) - { - s32 tmp = a; - a = b; - b = tmp; - } - - inline s32 sign(s32 x) - { - return x < 0 ? -1 : 1; - } - - inline s32 signZero(s32 x) - { - if (x == 0) { return 0; } - return x < 0 ? -1 : 1; - } - - inline s32 signV2A(s32 x) { return (x < 0 ? 1 : 0); } - - inline fixed16_16 dotFixed(vec3_fixed v0, vec3_fixed v1) { return mul16(v0.x, v1.x) + mul16(v0.y, v1.y) + mul16(v0.z, v1.z); } - - inline fixed16_16 dot(const vec3_fixed* v0, const vec3_fixed* v1) - { - return mul16(v0->x, v1->x) + mul16(v0->y, v1->y) + mul16(v0->z, v1->z); - } - - void normalizeVec3(vec3_fixed* vIn, vec3_fixed* vOut); - void rotateVectorM3x3(vec3_fixed* inVec, vec3_fixed* outVec, s32* mtx); - - inline fixed16_16 tanFixed(angle14_32 angle) - { - angle &= ANGLE_MASK; - if (angle < 8192) - { - return s_tanTable[angle]; - } - return s_tanTable[angle - 8192]; - } - - inline void sinCosFixed(angle14_32 angle, fixed16_16* sinValue, fixed16_16* cosValue) - { - angle &= ANGLE_MASK; - if (!(angle & 0x1000)) - { - if (!(angle & 0x2000)) // Quadrant 1 - { - assert(angle < 4096); - *sinValue = s_cosTable[4096 - angle]; - *cosValue = s_cosTable[angle]; - } - else // Quadrant 3 - { - assert(angle >= 8192 && angle < 12288); - *sinValue = -s_cosTable[12288 - angle]; - *cosValue = -s_cosTable[angle - 8192]; - } - } - else - { - if (!(angle & 0x2000)) // Quadrant 2 - { - assert(angle >= 4096 && angle < 8192); - *sinValue = s_cosTable[angle - 4096]; - *cosValue = -s_cosTable[8192 - angle]; - } - else // Quadrant 4 - { - assert(angle >= 12288 && angle < 16384); - *sinValue = -s_cosTable[angle - 12288]; - *cosValue = s_cosTable[16384 - angle]; - } - } - } - - angle14_32 arcCosFixed(fixed16_16 sinAngle, angle14_32 angle); - - inline fixed16_16 sinFixed(angle14_32 angle) - { - angle &= ANGLE_MASK; - if (!(angle & 0x1000)) - { - if (!(angle & 0x2000)) // Quadrant 1 - { - return s_cosTable[4096 - angle]; - } - else // Quadrant 3 - { - return -s_cosTable[12288 - angle]; - } - } - if (!(angle & 0x2000)) // Quadrant 2 - { - return s_cosTable[angle - 4096]; - } - // Quadrant 4 - return -s_cosTable[angle - 12288]; - } - - inline fixed16_16 cosFixed(angle14_32 angle) - { - angle &= ANGLE_MASK; - if (!(angle & 0x1000)) - { - if (!(angle & 0x2000)) // Quadrant 1 - { - return s_cosTable[angle]; // cos(angle) - } - else // Quadrant 3 - { - return -s_cosTable[angle - 8192]; - } - } - if (!(angle & 0x2000)) // Quadrant 2 - { - return -s_cosTable[8192 - angle]; - } - // Quadrant 4 - return s_cosTable[16384 - angle]; - } - - inline fixed16_16 vec2Length(fixed16_16 dx, fixed16_16 dz) - { - // Trade precision to avoid overflow. - dx = (dx + ((dx < 0) ? -1 : 0)) >> 1; - dz = (dz + ((dz < 0) ? -1 : 0)) >> 1; - return fixedSqrt(mul16(dx, dx) + mul16(dz, dz)) << 1; - } - - inline fixed16_16 vec3Length(fixed16_16 dx, fixed16_16 dy, fixed16_16 dz) - { - // Trade precision to avoid overflow. - dx = (dx + ((dx < 0) ? -1 : 0)) >> 1; - dy = (dy + ((dy < 0) ? -1 : 0)) >> 1; - dz = (dz + ((dz < 0) ? -1 : 0)) >> 1; - return fixedSqrt(mul16(dx, dx) + mul16(dy, dy) + mul16(dz, dz)) << 1; - } - - inline fixed16_16 fixedSquaredDistance(vec3_fixed a, vec3_fixed b) - { - fixed16_16 dx = b.x - a.x; - fixed16_16 dy = b.y - a.y; - fixed16_16 dz = b.z - a.z; - - // distSq overflows if dist > 181 units. - return mul16(dx, dx) + mul16(dy, dy) + mul16(dz, dz); - } - - inline fixed16_16 fixedDistance(vec3_fixed a, vec3_fixed b) - { - fixed16_16 dx = b.x - a.x; - fixed16_16 dy = b.y - a.y; - fixed16_16 dz = b.z - a.z; - - return vec3Length(dx, dy, dz); - } - - fixed16_16 computeDirAndLength(fixed16_16 dx, fixed16_16 dz, fixed16_16* dirX, fixed16_16* dirZ); - - void computeTransformFromAngles_Fixed(angle14_32 yaw, angle14_32 pitch, angle14_32 roll, fixed16_16* transform); - - // Returns an DF angle, where 360 degrees = 16384 angular units (~45.5 units / degree). - angle14_32 vec2ToAngle(fixed16_16 dx, fixed16_16 dz); - - // This is an approximate distance between points. - // It is basically manhattan distance - smallest component / 2 - // dist = |dx| + |dz| - min(|dx|, |dz|)/2 - inline fixed16_16 distApprox(fixed16_16 x0, fixed16_16 z0, fixed16_16 x1, fixed16_16 z1) - { - fixed16_16 dx = abs(x1 - x0); - fixed16_16 dz = abs(z1 - z0); - return dx + dz - (min(dx, dz) >> 1); - } - - angle14_32 getAngleDifference(angle14_32 angle0, angle14_32 angle1); - void mulMatrix3x3(fixed16_16* mtx0, fixed16_16* mtx1, fixed16_16* mtxOut); - - // Float - inline f32 abs(f32 x) - { - return x < 0 ? -x : x; - } - - inline f32 min(f32 a, f32 b) - { - return a < b ? a : b; - } - - inline f32 max(f32 a, f32 b) - { - return a > b ? a : b; - } - - inline f64 min(f64 a, f64 b) - { - return a < b ? a : b; - } - - inline f64 max(f64 a, f64 b) - { - return a > b ? a : b; - } - - inline f32 clamp(f32 x, f32 a, f32 b) - { - return min(max(x, a), b); - } - - inline s32 roundFloat(f32 x) - { - return s32(x + 0.5f); - } - - inline s32 floorFloat(f32 x) - { - return (s32)floorf(x); - } - - inline s32 sign(f32 x) - { - return x < 0.0f ? -1 : 1; - } - - inline s32 signZero(f32 x) - { - if (x == 0.0f) { return 0; } - return x < 0.0f ? -1 : 1; - } - - inline s32 signV2A(f32 x) { return (x < 0.0f ? 1 : 0); } - - inline f32 dotFloat(vec3_float v0, vec3_float v1) { return v0.x*v1.x + v0.y*v1.y + v0.z*v1.z; } - - inline f32 dot(const vec3_float* v0, const vec3_float* v1) - { - return v0->x*v1->x + v0->y*v1->y + v0->z*v1->z; - } - - void normalizeVec3(vec3_float* vIn, vec3_float* vOut); - void rotateVectorM3x3(vec3_float* inVec, vec3_float* outVec, f32* mtx); - - // Returns an DF angle, where 360 degrees = 16384 angular units (~45.5 units / degree). - s32 vec2ToAngle(f32 dx, f32 dz); - - inline f32 tanFlt(f32 angle) - { - const f32 scale = 2.0f * PI / 16384.0f; - return tanf(scale * angle); - } - - inline void sinCosFlt(f32 angle, f32* sinValue, f32* cosValue) - { - const f32 scale = 2.0f * PI / 16384.0f; - *sinValue = sinf(scale * angle); - *cosValue = cosf(scale * angle); - } - - inline f32 sinFlt(f32 angle) - { - const f32 scale = 2.0f * PI / 16384.0f; - return sinf(scale * angle); - } - - void computeTransformFromAngles_Float(f32 yaw, f32 pitch, f32 roll, f32* transform); - - inline u32 previousPowerOf2(u32 x) - { - if (x == 0) { return 0; } - - x |= (x >> 1); - x |= (x >> 2); - x |= (x >> 4); - x |= (x >> 8); - x |= (x >> 16); - return x - (x >> 1); - } - - // Size_t -#ifndef TFE_ESPBOX // size_t == u32 on the Amiga and the ESP32 - inline size_t min(size_t a, size_t b) - { - return a < b ? a : b; - } - - inline size_t max(size_t a, size_t b) - { - return a > b ? a : b; - } -#endif - - inline size_t clamp(size_t x, size_t a, size_t b) - { - return min(max(x, a), b); - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Math/cosTable.cpp b/components/darkforces/tfe/TFE_Jedi/Math/cosTable.cpp deleted file mode 100644 index 3197702e..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Math/cosTable.cpp +++ /dev/null @@ -1,9232 +0,0 @@ -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include "cosTable.h" - -namespace TFE_Jedi -{ - // The cosine table from Dark Forces. - const fixed16_16 s_cosTable[] = - { - 0x00010000, 0x0000FFFF, 0x0000FFFF, 0x0000FFFF, - 0x0000FFFF, 0x0000FFFF, 0x0000FFFF, 0x0000FFFF, - 0x0000FFFF, 0x0000FFFF, 0x0000FFFF, 0x0000FFFF, - 0x0000FFFF, 0x0000FFFF, 0x0000FFFF, 0x0000FFFE, - 0x0000FFFE, 0x0000FFFE, 0x0000FFFE, 0x0000FFFE, - 0x0000FFFE, 0x0000FFFD, 0x0000FFFD, 0x0000FFFD, - 0x0000FFFD, 0x0000FFFC, 0x0000FFFC, 0x0000FFFC, - 0x0000FFFC, 0x0000FFFB, 0x0000FFFB, 0x0000FFFB, - 0x0000FFFB, 0x0000FFFA, 0x0000FFFA, 0x0000FFFA, - 0x0000FFF9, 0x0000FFF9, 0x0000FFF9, 0x0000FFF8, - 0x0000FFF8, 0x0000FFF7, 0x0000FFF7, 0x0000FFF7, - 0x0000FFF6, 0x0000FFF6, 0x0000FFF5, 0x0000FFF5, - 0x0000FFF4, 0x0000FFF4, 0x0000FFF3, 0x0000FFF3, - 0x0000FFF2, 0x0000FFF2, 0x0000FFF1, 0x0000FFF1, - 0x0000FFF0, 0x0000FFF0, 0x0000FFEF, 0x0000FFEF, - 0x0000FFEE, 0x0000FFEE, 0x0000FFED, 0x0000FFEC, - 0x0000FFEC, 0x0000FFEB, 0x0000FFEB, 0x0000FFEA, - 0x0000FFE9, 0x0000FFE9, 0x0000FFE8, 0x0000FFE7, - 0x0000FFE7, 0x0000FFE6, 0x0000FFE5, 0x0000FFE4, - 0x0000FFE4, 0x0000FFE3, 0x0000FFE2, 0x0000FFE1, - 0x0000FFE1, 0x0000FFE0, 0x0000FFDF, 0x0000FFDE, - 0x0000FFDD, 0x0000FFDD, 0x0000FFDC, 0x0000FFDB, - 0x0000FFDA, 0x0000FFD9, 0x0000FFD8, 0x0000FFD8, - 0x0000FFD7, 0x0000FFD6, 0x0000FFD5, 0x0000FFD4, - 0x0000FFD3, 0x0000FFD2, 0x0000FFD1, 0x0000FFD0, - 0x0000FFCF, 0x0000FFCE, 0x0000FFCD, 0x0000FFCC, - 0x0000FFCB, 0x0000FFCA, 0x0000FFC9, 0x0000FFC8, - 0x0000FFC7, 0x0000FFC6, 0x0000FFC5, 0x0000FFC4, - 0x0000FFC3, 0x0000FFC2, 0x0000FFC1, 0x0000FFC0, - 0x0000FFBF, 0x0000FFBE, 0x0000FFBC, 0x0000FFBB, - 0x0000FFBA, 0x0000FFB9, 0x0000FFB8, 0x0000FFB7, - 0x0000FFB5, 0x0000FFB4, 0x0000FFB3, 0x0000FFB2, - 0x0000FFB1, 0x0000FFAF, 0x0000FFAE, 0x0000FFAD, - 0x0000FFAC, 0x0000FFAA, 0x0000FFA9, 0x0000FFA8, - 0x0000FFA6, 0x0000FFA5, 0x0000FFA4, 0x0000FFA2, - 0x0000FFA1, 0x0000FFA0, 0x0000FF9E, 0x0000FF9D, - 0x0000FF9C, 0x0000FF9A, 0x0000FF99, 0x0000FF97, - 0x0000FF96, 0x0000FF95, 0x0000FF93, 0x0000FF92, - 0x0000FF90, 0x0000FF8F, 0x0000FF8D, 0x0000FF8C, - 0x0000FF8A, 0x0000FF89, 0x0000FF87, 0x0000FF86, - 0x0000FF84, 0x0000FF83, 0x0000FF81, 0x0000FF80, - 0x0000FF7E, 0x0000FF7C, 0x0000FF7B, 0x0000FF79, - 0x0000FF78, 0x0000FF76, 0x0000FF74, 0x0000FF73, - 0x0000FF71, 0x0000FF6F, 0x0000FF6E, 0x0000FF6C, - 0x0000FF6A, 0x0000FF69, 0x0000FF67, 0x0000FF65, - 0x0000FF63, 0x0000FF62, 0x0000FF60, 0x0000FF5E, - 0x0000FF5C, 0x0000FF5B, 0x0000FF59, 0x0000FF57, - 0x0000FF55, 0x0000FF53, 0x0000FF52, 0x0000FF50, - 0x0000FF4E, 0x0000FF4C, 0x0000FF4A, 0x0000FF48, - 0x0000FF46, 0x0000FF45, 0x0000FF43, 0x0000FF41, - 0x0000FF3F, 0x0000FF3D, 0x0000FF3B, 0x0000FF39, - 0x0000FF37, 0x0000FF35, 0x0000FF33, 0x0000FF31, - 0x0000FF2F, 0x0000FF2D, 0x0000FF2B, 0x0000FF29, - 0x0000FF27, 0x0000FF25, 0x0000FF23, 0x0000FF21, - 0x0000FF1F, 0x0000FF1D, 0x0000FF1B, 0x0000FF19, - 0x0000FF16, 0x0000FF14, 0x0000FF12, 0x0000FF10, - 0x0000FF0E, 0x0000FF0C, 0x0000FF0A, 0x0000FF07, - 0x0000FF05, 0x0000FF03, 0x0000FF01, 0x0000FEFF, - 0x0000FEFC, 0x0000FEFA, 0x0000FEF8, 0x0000FEF6, - 0x0000FEF3, 0x0000FEF1, 0x0000FEEF, 0x0000FEEC, - 0x0000FEEA, 0x0000FEE8, 0x0000FEE5, 0x0000FEE3, - 0x0000FEE1, 0x0000FEDE, 0x0000FEDC, 0x0000FEDA, - 0x0000FED7, 0x0000FED5, 0x0000FED3, 0x0000FED0, - 0x0000FECE, 0x0000FECB, 0x0000FEC9, 0x0000FEC6, - 0x0000FEC4, 0x0000FEC1, 0x0000FEBF, 0x0000FEBC, - 0x0000FEBA, 0x0000FEB7, 0x0000FEB5, 0x0000FEB2, - 0x0000FEB0, 0x0000FEAD, 0x0000FEAB, 0x0000FEA8, - 0x0000FEA6, 0x0000FEA3, 0x0000FEA0, 0x0000FE9E, - 0x0000FE9B, 0x0000FE99, 0x0000FE96, 0x0000FE93, - 0x0000FE91, 0x0000FE8E, 0x0000FE8B, 0x0000FE89, - 0x0000FE86, 0x0000FE83, 0x0000FE81, 0x0000FE7E, - 0x0000FE7B, 0x0000FE78, 0x0000FE76, 0x0000FE73, - 0x0000FE70, 0x0000FE6D, 0x0000FE6B, 0x0000FE68, - 0x0000FE65, 0x0000FE62, 0x0000FE5F, 0x0000FE5D, - 0x0000FE5A, 0x0000FE57, 0x0000FE54, 0x0000FE51, - 0x0000FE4E, 0x0000FE4B, 0x0000FE48, 0x0000FE46, - 0x0000FE43, 0x0000FE40, 0x0000FE3D, 0x0000FE3A, - 0x0000FE37, 0x0000FE34, 0x0000FE31, 0x0000FE2E, - 0x0000FE2B, 0x0000FE28, 0x0000FE25, 0x0000FE22, - 0x0000FE1F, 0x0000FE1C, 0x0000FE19, 0x0000FE16, - 0x0000FE13, 0x0000FE10, 0x0000FE0C, 0x0000FE09, - 0x0000FE06, 0x0000FE03, 0x0000FE00, 0x0000FDFD, - 0x0000FDFA, 0x0000FDF7, 0x0000FDF3, 0x0000FDF0, - 0x0000FDED, 0x0000FDEA, 0x0000FDE7, 0x0000FDE3, - 0x0000FDE0, 0x0000FDDD, 0x0000FDDA, 0x0000FDD6, - 0x0000FDD3, 0x0000FDD0, 0x0000FDCD, 0x0000FDC9, - 0x0000FDC6, 0x0000FDC3, 0x0000FDBF, 0x0000FDBC, - 0x0000FDB9, 0x0000FDB5, 0x0000FDB2, 0x0000FDAF, - 0x0000FDAB, 0x0000FDA8, 0x0000FDA5, 0x0000FDA1, - 0x0000FD9E, 0x0000FD9A, 0x0000FD97, 0x0000FD93, - 0x0000FD90, 0x0000FD8C, 0x0000FD89, 0x0000FD86, - 0x0000FD82, 0x0000FD7F, 0x0000FD7B, 0x0000FD77, - 0x0000FD74, 0x0000FD70, 0x0000FD6D, 0x0000FD69, - 0x0000FD66, 0x0000FD62, 0x0000FD5F, 0x0000FD5B, - 0x0000FD57, 0x0000FD54, 0x0000FD50, 0x0000FD4C, - 0x0000FD49, 0x0000FD45, 0x0000FD42, 0x0000FD3E, - 0x0000FD3A, 0x0000FD36, 0x0000FD33, 0x0000FD2F, - 0x0000FD2B, 0x0000FD28, 0x0000FD24, 0x0000FD20, - 0x0000FD1C, 0x0000FD19, 0x0000FD15, 0x0000FD11, - 0x0000FD0D, 0x0000FD09, 0x0000FD06, 0x0000FD02, - 0x0000FCFE, 0x0000FCFA, 0x0000FCF6, 0x0000FCF2, - 0x0000FCEF, 0x0000FCEB, 0x0000FCE7, 0x0000FCE3, - 0x0000FCDF, 0x0000FCDB, 0x0000FCD7, 0x0000FCD3, - 0x0000FCCF, 0x0000FCCB, 0x0000FCC7, 0x0000FCC3, - 0x0000FCBF, 0x0000FCBB, 0x0000FCB7, 0x0000FCB3, - 0x0000FCAF, 0x0000FCAB, 0x0000FCA7, 0x0000FCA3, - 0x0000FC9F, 0x0000FC9B, 0x0000FC97, 0x0000FC93, - 0x0000FC8F, 0x0000FC8B, 0x0000FC86, 0x0000FC82, - 0x0000FC7E, 0x0000FC7A, 0x0000FC76, 0x0000FC72, - 0x0000FC6E, 0x0000FC69, 0x0000FC65, 0x0000FC61, - 0x0000FC5D, 0x0000FC58, 0x0000FC54, 0x0000FC50, - 0x0000FC4C, 0x0000FC48, 0x0000FC43, 0x0000FC3F, - 0x0000FC3B, 0x0000FC36, 0x0000FC32, 0x0000FC2E, - 0x0000FC29, 0x0000FC25, 0x0000FC21, 0x0000FC1C, - 0x0000FC18, 0x0000FC14, 0x0000FC0F, 0x0000FC0B, - 0x0000FC06, 0x0000FC02, 0x0000FBFE, 0x0000FBF9, - 0x0000FBF5, 0x0000FBF0, 0x0000FBEC, 0x0000FBE7, - 0x0000FBE3, 0x0000FBDE, 0x0000FBDA, 0x0000FBD5, - 0x0000FBD1, 0x0000FBCC, 0x0000FBC8, 0x0000FBC3, - 0x0000FBBF, 0x0000FBBA, 0x0000FBB5, 0x0000FBB1, - 0x0000FBAC, 0x0000FBA8, 0x0000FBA3, 0x0000FB9E, - 0x0000FB9A, 0x0000FB95, 0x0000FB91, 0x0000FB8C, - 0x0000FB87, 0x0000FB83, 0x0000FB7E, 0x0000FB79, - 0x0000FB74, 0x0000FB70, 0x0000FB6B, 0x0000FB66, - 0x0000FB61, 0x0000FB5D, 0x0000FB58, 0x0000FB53, - 0x0000FB4E, 0x0000FB4A, 0x0000FB45, 0x0000FB40, - 0x0000FB3B, 0x0000FB36, 0x0000FB31, 0x0000FB2D, - 0x0000FB28, 0x0000FB23, 0x0000FB1E, 0x0000FB19, - 0x0000FB14, 0x0000FB0F, 0x0000FB0A, 0x0000FB05, - 0x0000FB01, 0x0000FAFC, 0x0000FAF7, 0x0000FAF2, - 0x0000FAED, 0x0000FAE8, 0x0000FAE3, 0x0000FADE, - 0x0000FAD9, 0x0000FAD4, 0x0000FACF, 0x0000FACA, - 0x0000FAC5, 0x0000FAC0, 0x0000FABA, 0x0000FAB5, - 0x0000FAB0, 0x0000FAAB, 0x0000FAA6, 0x0000FAA1, - 0x0000FA9C, 0x0000FA97, 0x0000FA92, 0x0000FA8C, - 0x0000FA87, 0x0000FA82, 0x0000FA7D, 0x0000FA78, - 0x0000FA73, 0x0000FA6D, 0x0000FA68, 0x0000FA63, - 0x0000FA5E, 0x0000FA58, 0x0000FA53, 0x0000FA4E, - 0x0000FA49, 0x0000FA43, 0x0000FA3E, 0x0000FA39, - 0x0000FA33, 0x0000FA2E, 0x0000FA29, 0x0000FA23, - 0x0000FA1E, 0x0000FA19, 0x0000FA13, 0x0000FA0E, - 0x0000FA09, 0x0000FA03, 0x0000F9FE, 0x0000F9F8, - 0x0000F9F3, 0x0000F9ED, 0x0000F9E8, 0x0000F9E3, - 0x0000F9DD, 0x0000F9D8, 0x0000F9D2, 0x0000F9CD, - 0x0000F9C7, 0x0000F9C2, 0x0000F9BC, 0x0000F9B7, - 0x0000F9B1, 0x0000F9AB, 0x0000F9A6, 0x0000F9A0, - 0x0000F99B, 0x0000F995, 0x0000F990, 0x0000F98A, - 0x0000F984, 0x0000F97F, 0x0000F979, 0x0000F973, - 0x0000F96E, 0x0000F968, 0x0000F962, 0x0000F95D, - 0x0000F957, 0x0000F951, 0x0000F94C, 0x0000F946, - 0x0000F940, 0x0000F93B, 0x0000F935, 0x0000F92F, - 0x0000F929, 0x0000F923, 0x0000F91E, 0x0000F918, - 0x0000F912, 0x0000F90C, 0x0000F906, 0x0000F901, - 0x0000F8FB, 0x0000F8F5, 0x0000F8EF, 0x0000F8E9, - 0x0000F8E3, 0x0000F8DD, 0x0000F8D8, 0x0000F8D2, - 0x0000F8CC, 0x0000F8C6, 0x0000F8C0, 0x0000F8BA, - 0x0000F8B4, 0x0000F8AE, 0x0000F8A8, 0x0000F8A2, - 0x0000F89C, 0x0000F896, 0x0000F890, 0x0000F88A, - 0x0000F884, 0x0000F87E, 0x0000F878, 0x0000F872, - 0x0000F86C, 0x0000F866, 0x0000F860, 0x0000F85A, - 0x0000F853, 0x0000F84D, 0x0000F847, 0x0000F841, - 0x0000F83B, 0x0000F835, 0x0000F82F, 0x0000F828, - 0x0000F822, 0x0000F81C, 0x0000F816, 0x0000F810, - 0x0000F80A, 0x0000F803, 0x0000F7FD, 0x0000F7F7, - 0x0000F7F1, 0x0000F7EA, 0x0000F7E4, 0x0000F7DE, - 0x0000F7D7, 0x0000F7D1, 0x0000F7CB, 0x0000F7C5, - 0x0000F7BE, 0x0000F7B8, 0x0000F7B2, 0x0000F7AB, - 0x0000F7A5, 0x0000F79E, 0x0000F798, 0x0000F792, - 0x0000F78B, 0x0000F785, 0x0000F77E, 0x0000F778, - 0x0000F772, 0x0000F76B, 0x0000F765, 0x0000F75E, - 0x0000F758, 0x0000F751, 0x0000F74B, 0x0000F744, - 0x0000F73E, 0x0000F737, 0x0000F731, 0x0000F72A, - 0x0000F724, 0x0000F71D, 0x0000F716, 0x0000F710, - 0x0000F709, 0x0000F703, 0x0000F6FC, 0x0000F6F5, - 0x0000F6EF, 0x0000F6E8, 0x0000F6E2, 0x0000F6DB, - 0x0000F6D4, 0x0000F6CE, 0x0000F6C7, 0x0000F6C0, - 0x0000F6BA, 0x0000F6B3, 0x0000F6AC, 0x0000F6A5, - 0x0000F69F, 0x0000F698, 0x0000F691, 0x0000F68A, - 0x0000F684, 0x0000F67D, 0x0000F676, 0x0000F66F, - 0x0000F668, 0x0000F662, 0x0000F65B, 0x0000F654, - 0x0000F64D, 0x0000F646, 0x0000F63F, 0x0000F638, - 0x0000F632, 0x0000F62B, 0x0000F624, 0x0000F61D, - 0x0000F616, 0x0000F60F, 0x0000F608, 0x0000F601, - 0x0000F5FA, 0x0000F5F3, 0x0000F5EC, 0x0000F5E5, - 0x0000F5DE, 0x0000F5D7, 0x0000F5D0, 0x0000F5C9, - 0x0000F5C2, 0x0000F5BB, 0x0000F5B4, 0x0000F5AD, - 0x0000F5A6, 0x0000F59F, 0x0000F598, 0x0000F591, - 0x0000F58A, 0x0000F582, 0x0000F57B, 0x0000F574, - 0x0000F56D, 0x0000F566, 0x0000F55F, 0x0000F558, - 0x0000F550, 0x0000F549, 0x0000F542, 0x0000F53B, - 0x0000F534, 0x0000F52C, 0x0000F525, 0x0000F51E, - 0x0000F517, 0x0000F50F, 0x0000F508, 0x0000F501, - 0x0000F4FA, 0x0000F4F2, 0x0000F4EB, 0x0000F4E4, - 0x0000F4DC, 0x0000F4D5, 0x0000F4CE, 0x0000F4C6, - 0x0000F4BF, 0x0000F4B8, 0x0000F4B0, 0x0000F4A9, - 0x0000F4A1, 0x0000F49A, 0x0000F492, 0x0000F48B, - 0x0000F484, 0x0000F47C, 0x0000F475, 0x0000F46D, - 0x0000F466, 0x0000F45E, 0x0000F457, 0x0000F44F, - 0x0000F448, 0x0000F440, 0x0000F439, 0x0000F431, - 0x0000F42A, 0x0000F422, 0x0000F41B, 0x0000F413, - 0x0000F40B, 0x0000F404, 0x0000F3FC, 0x0000F3F5, - 0x0000F3ED, 0x0000F3E5, 0x0000F3DE, 0x0000F3D6, - 0x0000F3CE, 0x0000F3C7, 0x0000F3BF, 0x0000F3B7, - 0x0000F3B0, 0x0000F3A8, 0x0000F3A0, 0x0000F398, - 0x0000F391, 0x0000F389, 0x0000F381, 0x0000F379, - 0x0000F372, 0x0000F36A, 0x0000F362, 0x0000F35A, - 0x0000F353, 0x0000F34B, 0x0000F343, 0x0000F33B, - 0x0000F333, 0x0000F32B, 0x0000F324, 0x0000F31C, - 0x0000F314, 0x0000F30C, 0x0000F304, 0x0000F2FC, - 0x0000F2F4, 0x0000F2EC, 0x0000F2E4, 0x0000F2DC, - 0x0000F2D4, 0x0000F2CC, 0x0000F2C4, 0x0000F2BD, - 0x0000F2B5, 0x0000F2AD, 0x0000F2A5, 0x0000F29C, - 0x0000F294, 0x0000F28C, 0x0000F284, 0x0000F27C, - 0x0000F274, 0x0000F26C, 0x0000F264, 0x0000F25C, - 0x0000F254, 0x0000F24C, 0x0000F244, 0x0000F23C, - 0x0000F233, 0x0000F22B, 0x0000F223, 0x0000F21B, - 0x0000F213, 0x0000F20B, 0x0000F202, 0x0000F1FA, - 0x0000F1F2, 0x0000F1EA, 0x0000F1E2, 0x0000F1D9, - 0x0000F1D1, 0x0000F1C9, 0x0000F1C1, 0x0000F1B8, - 0x0000F1B0, 0x0000F1A8, 0x0000F19F, 0x0000F197, - 0x0000F18F, 0x0000F187, 0x0000F17E, 0x0000F176, - 0x0000F16D, 0x0000F165, 0x0000F15D, 0x0000F154, - 0x0000F14C, 0x0000F144, 0x0000F13B, 0x0000F133, - 0x0000F12A, 0x0000F122, 0x0000F119, 0x0000F111, - 0x0000F109, 0x0000F100, 0x0000F0F8, 0x0000F0EF, - 0x0000F0E7, 0x0000F0DE, 0x0000F0D6, 0x0000F0CD, - 0x0000F0C5, 0x0000F0BC, 0x0000F0B3, 0x0000F0AB, - 0x0000F0A2, 0x0000F09A, 0x0000F091, 0x0000F089, - 0x0000F080, 0x0000F077, 0x0000F06F, 0x0000F066, - 0x0000F05D, 0x0000F055, 0x0000F04C, 0x0000F043, - 0x0000F03B, 0x0000F032, 0x0000F029, 0x0000F021, - 0x0000F018, 0x0000F00F, 0x0000F006, 0x0000EFFE, - 0x0000EFF5, 0x0000EFEC, 0x0000EFE3, 0x0000EFDB, - 0x0000EFD2, 0x0000EFC9, 0x0000EFC0, 0x0000EFB7, - 0x0000EFAF, 0x0000EFA6, 0x0000EF9D, 0x0000EF94, - 0x0000EF8B, 0x0000EF82, 0x0000EF79, 0x0000EF71, - 0x0000EF68, 0x0000EF5F, 0x0000EF56, 0x0000EF4D, - 0x0000EF44, 0x0000EF3B, 0x0000EF32, 0x0000EF29, - 0x0000EF20, 0x0000EF17, 0x0000EF0E, 0x0000EF05, - 0x0000EEFC, 0x0000EEF3, 0x0000EEEA, 0x0000EEE1, - 0x0000EED8, 0x0000EECF, 0x0000EEC6, 0x0000EEBD, - 0x0000EEB4, 0x0000EEAB, 0x0000EEA2, 0x0000EE99, - 0x0000EE8F, 0x0000EE86, 0x0000EE7D, 0x0000EE74, - 0x0000EE6B, 0x0000EE62, 0x0000EE59, 0x0000EE4F, - 0x0000EE46, 0x0000EE3D, 0x0000EE34, 0x0000EE2B, - 0x0000EE21, 0x0000EE18, 0x0000EE0F, 0x0000EE06, - 0x0000EDFC, 0x0000EDF3, 0x0000EDEA, 0x0000EDE1, - 0x0000EDD7, 0x0000EDCE, 0x0000EDC5, 0x0000EDBB, - 0x0000EDB2, 0x0000EDA9, 0x0000ED9F, 0x0000ED96, - 0x0000ED8D, 0x0000ED83, 0x0000ED7A, 0x0000ED71, - 0x0000ED67, 0x0000ED5E, 0x0000ED54, 0x0000ED4B, - 0x0000ED41, 0x0000ED38, 0x0000ED2F, 0x0000ED25, - 0x0000ED1C, 0x0000ED12, 0x0000ED09, 0x0000ECFF, - 0x0000ECF6, 0x0000ECEC, 0x0000ECE3, 0x0000ECD9, - 0x0000ECD0, 0x0000ECC6, 0x0000ECBC, 0x0000ECB3, - 0x0000ECA9, 0x0000ECA0, 0x0000EC96, 0x0000EC8C, - 0x0000EC83, 0x0000EC79, 0x0000EC70, 0x0000EC66, - 0x0000EC5C, 0x0000EC53, 0x0000EC49, 0x0000EC3F, - 0x0000EC36, 0x0000EC2C, 0x0000EC22, 0x0000EC19, - 0x0000EC0F, 0x0000EC05, 0x0000EBFB, 0x0000EBF2, - 0x0000EBE8, 0x0000EBDE, 0x0000EBD4, 0x0000EBCB, - 0x0000EBC1, 0x0000EBB7, 0x0000EBAD, 0x0000EBA3, - 0x0000EB99, 0x0000EB90, 0x0000EB86, 0x0000EB7C, - 0x0000EB72, 0x0000EB68, 0x0000EB5E, 0x0000EB54, - 0x0000EB4B, 0x0000EB41, 0x0000EB37, 0x0000EB2D, - 0x0000EB23, 0x0000EB19, 0x0000EB0F, 0x0000EB05, - 0x0000EAFB, 0x0000EAF1, 0x0000EAE7, 0x0000EADD, - 0x0000EAD3, 0x0000EAC9, 0x0000EABF, 0x0000EAB5, - 0x0000EAAB, 0x0000EAA1, 0x0000EA97, 0x0000EA8D, - 0x0000EA83, 0x0000EA79, 0x0000EA6F, 0x0000EA64, - 0x0000EA5A, 0x0000EA50, 0x0000EA46, 0x0000EA3C, - 0x0000EA32, 0x0000EA28, 0x0000EA1E, 0x0000EA13, - 0x0000EA09, 0x0000E9FF, 0x0000E9F5, 0x0000E9EB, - 0x0000E9E0, 0x0000E9D6, 0x0000E9CC, 0x0000E9C2, - 0x0000E9B7, 0x0000E9AD, 0x0000E9A3, 0x0000E999, - 0x0000E98E, 0x0000E984, 0x0000E97A, 0x0000E96F, - 0x0000E965, 0x0000E95B, 0x0000E950, 0x0000E946, - 0x0000E93C, 0x0000E931, 0x0000E927, 0x0000E91D, - 0x0000E912, 0x0000E908, 0x0000E8FD, 0x0000E8F3, - 0x0000E8E9, 0x0000E8DE, 0x0000E8D4, 0x0000E8C9, - 0x0000E8BF, 0x0000E8B4, 0x0000E8AA, 0x0000E89F, - 0x0000E895, 0x0000E88A, 0x0000E880, 0x0000E875, - 0x0000E86B, 0x0000E860, 0x0000E856, 0x0000E84B, - 0x0000E841, 0x0000E836, 0x0000E82B, 0x0000E821, - 0x0000E816, 0x0000E80C, 0x0000E801, 0x0000E7F6, - 0x0000E7EC, 0x0000E7E1, 0x0000E7D6, 0x0000E7CC, - 0x0000E7C1, 0x0000E7B6, 0x0000E7AC, 0x0000E7A1, - 0x0000E796, 0x0000E78C, 0x0000E781, 0x0000E776, - 0x0000E76B, 0x0000E761, 0x0000E756, 0x0000E74B, - 0x0000E740, 0x0000E736, 0x0000E72B, 0x0000E720, - 0x0000E715, 0x0000E70A, 0x0000E6FF, 0x0000E6F5, - 0x0000E6EA, 0x0000E6DF, 0x0000E6D4, 0x0000E6C9, - 0x0000E6BE, 0x0000E6B3, 0x0000E6A9, 0x0000E69E, - 0x0000E693, 0x0000E688, 0x0000E67D, 0x0000E672, - 0x0000E667, 0x0000E65C, 0x0000E651, 0x0000E646, - 0x0000E63B, 0x0000E630, 0x0000E625, 0x0000E61A, - 0x0000E60F, 0x0000E604, 0x0000E5F9, 0x0000E5EE, - 0x0000E5E3, 0x0000E5D8, 0x0000E5CD, 0x0000E5C2, - 0x0000E5B7, 0x0000E5AB, 0x0000E5A0, 0x0000E595, - 0x0000E58A, 0x0000E57F, 0x0000E574, 0x0000E569, - 0x0000E55E, 0x0000E552, 0x0000E547, 0x0000E53C, - 0x0000E531, 0x0000E526, 0x0000E51A, 0x0000E50F, - 0x0000E504, 0x0000E4F9, 0x0000E4ED, 0x0000E4E2, - 0x0000E4D7, 0x0000E4CC, 0x0000E4C0, 0x0000E4B5, - 0x0000E4AA, 0x0000E49F, 0x0000E493, 0x0000E488, - 0x0000E47D, 0x0000E471, 0x0000E466, 0x0000E45B, - 0x0000E44F, 0x0000E444, 0x0000E438, 0x0000E42D, - 0x0000E422, 0x0000E416, 0x0000E40B, 0x0000E3FF, - 0x0000E3F4, 0x0000E3E9, 0x0000E3DD, 0x0000E3D2, - 0x0000E3C6, 0x0000E3BB, 0x0000E3AF, 0x0000E3A4, - 0x0000E398, 0x0000E38D, 0x0000E381, 0x0000E376, - 0x0000E36A, 0x0000E35F, 0x0000E353, 0x0000E347, - 0x0000E33C, 0x0000E330, 0x0000E325, 0x0000E319, - 0x0000E30D, 0x0000E302, 0x0000E2F6, 0x0000E2EB, - 0x0000E2DF, 0x0000E2D3, 0x0000E2C8, 0x0000E2BC, - 0x0000E2B0, 0x0000E2A5, 0x0000E299, 0x0000E28D, - 0x0000E282, 0x0000E276, 0x0000E26A, 0x0000E25E, - 0x0000E253, 0x0000E247, 0x0000E23B, 0x0000E22F, - 0x0000E224, 0x0000E218, 0x0000E20C, 0x0000E200, - 0x0000E1F4, 0x0000E1E9, 0x0000E1DD, 0x0000E1D1, - 0x0000E1C5, 0x0000E1B9, 0x0000E1AD, 0x0000E1A2, - 0x0000E196, 0x0000E18A, 0x0000E17E, 0x0000E172, - 0x0000E166, 0x0000E15A, 0x0000E14E, 0x0000E142, - 0x0000E136, 0x0000E12A, 0x0000E11E, 0x0000E112, - 0x0000E106, 0x0000E0FA, 0x0000E0EE, 0x0000E0E2, - 0x0000E0D6, 0x0000E0CA, 0x0000E0BE, 0x0000E0B2, - 0x0000E0A6, 0x0000E09A, 0x0000E08E, 0x0000E082, - 0x0000E076, 0x0000E06A, 0x0000E05E, 0x0000E052, - 0x0000E046, 0x0000E03A, 0x0000E02D, 0x0000E021, - 0x0000E015, 0x0000E009, 0x0000DFFD, 0x0000DFF1, - 0x0000DFE4, 0x0000DFD8, 0x0000DFCC, 0x0000DFC0, - 0x0000DFB4, 0x0000DFA7, 0x0000DF9B, 0x0000DF8F, - 0x0000DF83, 0x0000DF76, 0x0000DF6A, 0x0000DF5E, - 0x0000DF52, 0x0000DF45, 0x0000DF39, 0x0000DF2D, - 0x0000DF20, 0x0000DF14, 0x0000DF08, 0x0000DEFB, - 0x0000DEEF, 0x0000DEE3, 0x0000DED6, 0x0000DECA, - 0x0000DEBE, 0x0000DEB1, 0x0000DEA5, 0x0000DE98, - 0x0000DE8C, 0x0000DE7F, 0x0000DE73, 0x0000DE67, - 0x0000DE5A, 0x0000DE4E, 0x0000DE41, 0x0000DE35, - 0x0000DE28, 0x0000DE1C, 0x0000DE0F, 0x0000DE03, - 0x0000DDF6, 0x0000DDEA, 0x0000DDDD, 0x0000DDD1, - 0x0000DDC4, 0x0000DDB8, 0x0000DDAB, 0x0000DD9E, - 0x0000DD92, 0x0000DD85, 0x0000DD79, 0x0000DD6C, - 0x0000DD5F, 0x0000DD53, 0x0000DD46, 0x0000DD39, - 0x0000DD2D, 0x0000DD20, 0x0000DD13, 0x0000DD07, - 0x0000DCFA, 0x0000DCED, 0x0000DCE1, 0x0000DCD4, - 0x0000DCC7, 0x0000DCBB, 0x0000DCAE, 0x0000DCA1, - 0x0000DC94, 0x0000DC88, 0x0000DC7B, 0x0000DC6E, - 0x0000DC61, 0x0000DC54, 0x0000DC48, 0x0000DC3B, - 0x0000DC2E, 0x0000DC21, 0x0000DC14, 0x0000DC08, - 0x0000DBFB, 0x0000DBEE, 0x0000DBE1, 0x0000DBD4, - 0x0000DBC7, 0x0000DBBA, 0x0000DBAD, 0x0000DBA1, - 0x0000DB94, 0x0000DB87, 0x0000DB7A, 0x0000DB6D, - 0x0000DB60, 0x0000DB53, 0x0000DB46, 0x0000DB39, - 0x0000DB2C, 0x0000DB1F, 0x0000DB12, 0x0000DB05, - 0x0000DAF8, 0x0000DAEB, 0x0000DADE, 0x0000DAD1, - 0x0000DAC4, 0x0000DAB7, 0x0000DAAA, 0x0000DA9D, - 0x0000DA90, 0x0000DA82, 0x0000DA75, 0x0000DA68, - 0x0000DA5B, 0x0000DA4E, 0x0000DA41, 0x0000DA34, - 0x0000DA27, 0x0000DA19, 0x0000DA0C, 0x0000D9FF, - 0x0000D9F2, 0x0000D9E5, 0x0000D9D8, 0x0000D9CA, - 0x0000D9BD, 0x0000D9B0, 0x0000D9A3, 0x0000D995, - 0x0000D988, 0x0000D97B, 0x0000D96E, 0x0000D960, - 0x0000D953, 0x0000D946, 0x0000D939, 0x0000D92B, - 0x0000D91E, 0x0000D911, 0x0000D903, 0x0000D8F6, - 0x0000D8E9, 0x0000D8DB, 0x0000D8CE, 0x0000D8C1, - 0x0000D8B3, 0x0000D8A6, 0x0000D898, 0x0000D88B, - 0x0000D87E, 0x0000D870, 0x0000D863, 0x0000D855, - 0x0000D848, 0x0000D83A, 0x0000D82D, 0x0000D81F, - 0x0000D812, 0x0000D804, 0x0000D7F7, 0x0000D7E9, - 0x0000D7DC, 0x0000D7CE, 0x0000D7C1, 0x0000D7B3, - 0x0000D7A6, 0x0000D798, 0x0000D78B, 0x0000D77D, - 0x0000D770, 0x0000D762, 0x0000D754, 0x0000D747, - 0x0000D739, 0x0000D72C, 0x0000D71E, 0x0000D710, - 0x0000D703, 0x0000D6F5, 0x0000D6E7, 0x0000D6DA, - 0x0000D6CC, 0x0000D6BE, 0x0000D6B1, 0x0000D6A3, - 0x0000D695, 0x0000D688, 0x0000D67A, 0x0000D66C, - 0x0000D65F, 0x0000D651, 0x0000D643, 0x0000D635, - 0x0000D627, 0x0000D61A, 0x0000D60C, 0x0000D5FE, - 0x0000D5F0, 0x0000D5E3, 0x0000D5D5, 0x0000D5C7, - 0x0000D5B9, 0x0000D5AB, 0x0000D59D, 0x0000D590, - 0x0000D582, 0x0000D574, 0x0000D566, 0x0000D558, - 0x0000D54A, 0x0000D53C, 0x0000D52E, 0x0000D520, - 0x0000D512, 0x0000D505, 0x0000D4F7, 0x0000D4E9, - 0x0000D4DB, 0x0000D4CD, 0x0000D4BF, 0x0000D4B1, - 0x0000D4A3, 0x0000D495, 0x0000D487, 0x0000D479, - 0x0000D46B, 0x0000D45D, 0x0000D44F, 0x0000D441, - 0x0000D433, 0x0000D424, 0x0000D416, 0x0000D408, - 0x0000D3FA, 0x0000D3EC, 0x0000D3DE, 0x0000D3D0, - 0x0000D3C2, 0x0000D3B4, 0x0000D3A6, 0x0000D397, - 0x0000D389, 0x0000D37B, 0x0000D36D, 0x0000D35F, - 0x0000D351, 0x0000D342, 0x0000D334, 0x0000D326, - 0x0000D318, 0x0000D30A, 0x0000D2FB, 0x0000D2ED, - 0x0000D2DF, 0x0000D2D1, 0x0000D2C2, 0x0000D2B4, - 0x0000D2A6, 0x0000D297, 0x0000D289, 0x0000D27B, - 0x0000D26D, 0x0000D25E, 0x0000D250, 0x0000D242, - 0x0000D233, 0x0000D225, 0x0000D217, 0x0000D208, - 0x0000D1FA, 0x0000D1EB, 0x0000D1DD, 0x0000D1CF, - 0x0000D1C0, 0x0000D1B2, 0x0000D1A3, 0x0000D195, - 0x0000D187, 0x0000D178, 0x0000D16A, 0x0000D15B, - 0x0000D14D, 0x0000D13E, 0x0000D130, 0x0000D121, - 0x0000D113, 0x0000D104, 0x0000D0F6, 0x0000D0E7, - 0x0000D0D9, 0x0000D0CA, 0x0000D0BC, 0x0000D0AD, - 0x0000D09F, 0x0000D090, 0x0000D081, 0x0000D073, - 0x0000D064, 0x0000D056, 0x0000D047, 0x0000D038, - 0x0000D02A, 0x0000D01B, 0x0000D00C, 0x0000CFFE, - 0x0000CFEF, 0x0000CFE0, 0x0000CFD2, 0x0000CFC3, - 0x0000CFB4, 0x0000CFA6, 0x0000CF97, 0x0000CF88, - 0x0000CF7A, 0x0000CF6B, 0x0000CF5C, 0x0000CF4D, - 0x0000CF3F, 0x0000CF30, 0x0000CF21, 0x0000CF12, - 0x0000CF04, 0x0000CEF5, 0x0000CEE6, 0x0000CED7, - 0x0000CEC8, 0x0000CEBA, 0x0000CEAB, 0x0000CE9C, - 0x0000CE8D, 0x0000CE7E, 0x0000CE6F, 0x0000CE60, - 0x0000CE52, 0x0000CE43, 0x0000CE34, 0x0000CE25, - 0x0000CE16, 0x0000CE07, 0x0000CDF8, 0x0000CDE9, - 0x0000CDDA, 0x0000CDCB, 0x0000CDBC, 0x0000CDAD, - 0x0000CD9F, 0x0000CD90, 0x0000CD81, 0x0000CD72, - 0x0000CD63, 0x0000CD54, 0x0000CD45, 0x0000CD36, - 0x0000CD26, 0x0000CD17, 0x0000CD08, 0x0000CCF9, - 0x0000CCEA, 0x0000CCDB, 0x0000CCCC, 0x0000CCBD, - 0x0000CCAE, 0x0000CC9F, 0x0000CC90, 0x0000CC81, - 0x0000CC72, 0x0000CC62, 0x0000CC53, 0x0000CC44, - 0x0000CC35, 0x0000CC26, 0x0000CC17, 0x0000CC07, - 0x0000CBF8, 0x0000CBE9, 0x0000CBDA, 0x0000CBCB, - 0x0000CBBB, 0x0000CBAC, 0x0000CB9D, 0x0000CB8E, - 0x0000CB7F, 0x0000CB6F, 0x0000CB60, 0x0000CB51, - 0x0000CB41, 0x0000CB32, 0x0000CB23, 0x0000CB14, - 0x0000CB04, 0x0000CAF5, 0x0000CAE6, 0x0000CAD6, - 0x0000CAC7, 0x0000CAB8, 0x0000CAA8, 0x0000CA99, - 0x0000CA8A, 0x0000CA7A, 0x0000CA6B, 0x0000CA5B, - 0x0000CA4C, 0x0000CA3D, 0x0000CA2D, 0x0000CA1E, - 0x0000CA0E, 0x0000C9FF, 0x0000C9EF, 0x0000C9E0, - 0x0000C9D1, 0x0000C9C1, 0x0000C9B2, 0x0000C9A2, - 0x0000C993, 0x0000C983, 0x0000C974, 0x0000C964, - 0x0000C955, 0x0000C945, 0x0000C936, 0x0000C926, - 0x0000C916, 0x0000C907, 0x0000C8F7, 0x0000C8E8, - 0x0000C8D8, 0x0000C8C9, 0x0000C8B9, 0x0000C8A9, - 0x0000C89A, 0x0000C88A, 0x0000C87B, 0x0000C86B, - 0x0000C85B, 0x0000C84C, 0x0000C83C, 0x0000C82C, - 0x0000C81D, 0x0000C80D, 0x0000C7FD, 0x0000C7EE, - 0x0000C7DE, 0x0000C7CE, 0x0000C7BE, 0x0000C7AF, - 0x0000C79F, 0x0000C78F, 0x0000C780, 0x0000C770, - 0x0000C760, 0x0000C750, 0x0000C740, 0x0000C731, - 0x0000C721, 0x0000C711, 0x0000C701, 0x0000C6F1, - 0x0000C6E2, 0x0000C6D2, 0x0000C6C2, 0x0000C6B2, - 0x0000C6A2, 0x0000C692, 0x0000C683, 0x0000C673, - 0x0000C663, 0x0000C653, 0x0000C643, 0x0000C633, - 0x0000C623, 0x0000C613, 0x0000C603, 0x0000C5F3, - 0x0000C5E4, 0x0000C5D4, 0x0000C5C4, 0x0000C5B4, - 0x0000C5A4, 0x0000C594, 0x0000C584, 0x0000C574, - 0x0000C564, 0x0000C554, 0x0000C544, 0x0000C534, - 0x0000C524, 0x0000C514, 0x0000C504, 0x0000C4F4, - 0x0000C4E3, 0x0000C4D3, 0x0000C4C3, 0x0000C4B3, - 0x0000C4A3, 0x0000C493, 0x0000C483, 0x0000C473, - 0x0000C463, 0x0000C453, 0x0000C442, 0x0000C432, - 0x0000C422, 0x0000C412, 0x0000C402, 0x0000C3F2, - 0x0000C3E1, 0x0000C3D1, 0x0000C3C1, 0x0000C3B1, - 0x0000C3A1, 0x0000C390, 0x0000C380, 0x0000C370, - 0x0000C360, 0x0000C350, 0x0000C33F, 0x0000C32F, - 0x0000C31F, 0x0000C30F, 0x0000C2FE, 0x0000C2EE, - 0x0000C2DE, 0x0000C2CD, 0x0000C2BD, 0x0000C2AD, - 0x0000C29C, 0x0000C28C, 0x0000C27C, 0x0000C26B, - 0x0000C25B, 0x0000C24B, 0x0000C23A, 0x0000C22A, - 0x0000C21A, 0x0000C209, 0x0000C1F9, 0x0000C1E8, - 0x0000C1D8, 0x0000C1C8, 0x0000C1B7, 0x0000C1A7, - 0x0000C196, 0x0000C186, 0x0000C175, 0x0000C165, - 0x0000C154, 0x0000C144, 0x0000C133, 0x0000C123, - 0x0000C112, 0x0000C102, 0x0000C0F1, 0x0000C0E1, - 0x0000C0D0, 0x0000C0C0, 0x0000C0AF, 0x0000C09F, - 0x0000C08E, 0x0000C07E, 0x0000C06D, 0x0000C05C, - 0x0000C04C, 0x0000C03B, 0x0000C02B, 0x0000C01A, - 0x0000C009, 0x0000BFF9, 0x0000BFE8, 0x0000BFD8, - 0x0000BFC7, 0x0000BFB6, 0x0000BFA6, 0x0000BF95, - 0x0000BF84, 0x0000BF74, 0x0000BF63, 0x0000BF52, - 0x0000BF41, 0x0000BF31, 0x0000BF20, 0x0000BF0F, - 0x0000BEFF, 0x0000BEEE, 0x0000BEDD, 0x0000BECC, - 0x0000BEBC, 0x0000BEAB, 0x0000BE9A, 0x0000BE89, - 0x0000BE78, 0x0000BE68, 0x0000BE57, 0x0000BE46, - 0x0000BE35, 0x0000BE24, 0x0000BE14, 0x0000BE03, - 0x0000BDF2, 0x0000BDE1, 0x0000BDD0, 0x0000BDBF, - 0x0000BDAE, 0x0000BD9E, 0x0000BD8D, 0x0000BD7C, - 0x0000BD6B, 0x0000BD5A, 0x0000BD49, 0x0000BD38, - 0x0000BD27, 0x0000BD16, 0x0000BD05, 0x0000BCF4, - 0x0000BCE3, 0x0000BCD2, 0x0000BCC1, 0x0000BCB0, - 0x0000BCA0, 0x0000BC8F, 0x0000BC7E, 0x0000BC6C, - 0x0000BC5B, 0x0000BC4A, 0x0000BC39, 0x0000BC28, - 0x0000BC17, 0x0000BC06, 0x0000BBF5, 0x0000BBE4, - 0x0000BBD3, 0x0000BBC2, 0x0000BBB1, 0x0000BBA0, - 0x0000BB8F, 0x0000BB7E, 0x0000BB6C, 0x0000BB5B, - 0x0000BB4A, 0x0000BB39, 0x0000BB28, 0x0000BB17, - 0x0000BB06, 0x0000BAF4, 0x0000BAE3, 0x0000BAD2, - 0x0000BAC1, 0x0000BAB0, 0x0000BA9F, 0x0000BA8D, - 0x0000BA7C, 0x0000BA6B, 0x0000BA5A, 0x0000BA48, - 0x0000BA37, 0x0000BA26, 0x0000BA15, 0x0000BA03, - 0x0000B9F2, 0x0000B9E1, 0x0000B9D0, 0x0000B9BE, - 0x0000B9AD, 0x0000B99C, 0x0000B98A, 0x0000B979, - 0x0000B968, 0x0000B956, 0x0000B945, 0x0000B934, - 0x0000B922, 0x0000B911, 0x0000B900, 0x0000B8EE, - 0x0000B8DD, 0x0000B8CB, 0x0000B8BA, 0x0000B8A9, - 0x0000B897, 0x0000B886, 0x0000B874, 0x0000B863, - 0x0000B852, 0x0000B840, 0x0000B82F, 0x0000B81D, - 0x0000B80C, 0x0000B7FA, 0x0000B7E9, 0x0000B7D7, - 0x0000B7C6, 0x0000B7B4, 0x0000B7A3, 0x0000B791, - 0x0000B780, 0x0000B76E, 0x0000B75D, 0x0000B74B, - 0x0000B73A, 0x0000B728, 0x0000B717, 0x0000B705, - 0x0000B6F3, 0x0000B6E2, 0x0000B6D0, 0x0000B6BF, - 0x0000B6AD, 0x0000B69B, 0x0000B68A, 0x0000B678, - 0x0000B667, 0x0000B655, 0x0000B643, 0x0000B632, - 0x0000B620, 0x0000B60E, 0x0000B5FD, 0x0000B5EB, - 0x0000B5D9, 0x0000B5C8, 0x0000B5B6, 0x0000B5A4, - 0x0000B592, 0x0000B581, 0x0000B56F, 0x0000B55D, - 0x0000B54B, 0x0000B53A, 0x0000B528, 0x0000B516, - 0x0000B504, 0x0000B4F3, 0x0000B4E1, 0x0000B4CF, - 0x0000B4BD, 0x0000B4AB, 0x0000B49A, 0x0000B488, - 0x0000B476, 0x0000B464, 0x0000B452, 0x0000B441, - 0x0000B42F, 0x0000B41D, 0x0000B40B, 0x0000B3F9, - 0x0000B3E7, 0x0000B3D5, 0x0000B3C3, 0x0000B3B2, - 0x0000B3A0, 0x0000B38E, 0x0000B37C, 0x0000B36A, - 0x0000B358, 0x0000B346, 0x0000B334, 0x0000B322, - 0x0000B310, 0x0000B2FE, 0x0000B2EC, 0x0000B2DA, - 0x0000B2C8, 0x0000B2B6, 0x0000B2A4, 0x0000B292, - 0x0000B280, 0x0000B26E, 0x0000B25C, 0x0000B24A, - 0x0000B238, 0x0000B226, 0x0000B214, 0x0000B202, - 0x0000B1F0, 0x0000B1DE, 0x0000B1CC, 0x0000B1BA, - 0x0000B1A8, 0x0000B196, 0x0000B183, 0x0000B171, - 0x0000B15F, 0x0000B14D, 0x0000B13B, 0x0000B129, - 0x0000B117, 0x0000B104, 0x0000B0F2, 0x0000B0E0, - 0x0000B0CE, 0x0000B0BC, 0x0000B0AA, 0x0000B097, - 0x0000B085, 0x0000B073, 0x0000B061, 0x0000B04F, - 0x0000B03C, 0x0000B02A, 0x0000B018, 0x0000B006, - 0x0000AFF3, 0x0000AFE1, 0x0000AFCF, 0x0000AFBD, - 0x0000AFAA, 0x0000AF98, 0x0000AF86, 0x0000AF73, - 0x0000AF61, 0x0000AF4F, 0x0000AF3D, 0x0000AF2A, - 0x0000AF18, 0x0000AF06, 0x0000AEF3, 0x0000AEE1, - 0x0000AECE, 0x0000AEBC, 0x0000AEAA, 0x0000AE97, - 0x0000AE85, 0x0000AE73, 0x0000AE60, 0x0000AE4E, - 0x0000AE3B, 0x0000AE29, 0x0000AE17, 0x0000AE04, - 0x0000ADF2, 0x0000ADDF, 0x0000ADCD, 0x0000ADBA, - 0x0000ADA8, 0x0000AD95, 0x0000AD83, 0x0000AD70, - 0x0000AD5E, 0x0000AD4B, 0x0000AD39, 0x0000AD26, - 0x0000AD14, 0x0000AD01, 0x0000ACEF, 0x0000ACDC, - 0x0000ACCA, 0x0000ACB7, 0x0000ACA5, 0x0000AC92, - 0x0000AC80, 0x0000AC6D, 0x0000AC5A, 0x0000AC48, - 0x0000AC35, 0x0000AC23, 0x0000AC10, 0x0000ABFD, - 0x0000ABEB, 0x0000ABD8, 0x0000ABC6, 0x0000ABB3, - 0x0000ABA0, 0x0000AB8E, 0x0000AB7B, 0x0000AB68, - 0x0000AB56, 0x0000AB43, 0x0000AB30, 0x0000AB1E, - 0x0000AB0B, 0x0000AAF8, 0x0000AAE5, 0x0000AAD3, - 0x0000AAC0, 0x0000AAAD, 0x0000AA9B, 0x0000AA88, - 0x0000AA75, 0x0000AA62, 0x0000AA50, 0x0000AA3D, - 0x0000AA2A, 0x0000AA17, 0x0000AA04, 0x0000A9F2, - 0x0000A9DF, 0x0000A9CC, 0x0000A9B9, 0x0000A9A6, - 0x0000A994, 0x0000A981, 0x0000A96E, 0x0000A95B, - 0x0000A948, 0x0000A935, 0x0000A922, 0x0000A910, - 0x0000A8FD, 0x0000A8EA, 0x0000A8D7, 0x0000A8C4, - 0x0000A8B1, 0x0000A89E, 0x0000A88B, 0x0000A878, - 0x0000A866, 0x0000A853, 0x0000A840, 0x0000A82D, - 0x0000A81A, 0x0000A807, 0x0000A7F4, 0x0000A7E1, - 0x0000A7CE, 0x0000A7BB, 0x0000A7A8, 0x0000A795, - 0x0000A782, 0x0000A76F, 0x0000A75C, 0x0000A749, - 0x0000A736, 0x0000A723, 0x0000A710, 0x0000A6FD, - 0x0000A6EA, 0x0000A6D7, 0x0000A6C4, 0x0000A6B0, - 0x0000A69D, 0x0000A68A, 0x0000A677, 0x0000A664, - 0x0000A651, 0x0000A63E, 0x0000A62B, 0x0000A618, - 0x0000A605, 0x0000A5F1, 0x0000A5DE, 0x0000A5CB, - 0x0000A5B8, 0x0000A5A5, 0x0000A592, 0x0000A57E, - 0x0000A56B, 0x0000A558, 0x0000A545, 0x0000A532, - 0x0000A51F, 0x0000A50B, 0x0000A4F8, 0x0000A4E5, - 0x0000A4D2, 0x0000A4BE, 0x0000A4AB, 0x0000A498, - 0x0000A485, 0x0000A471, 0x0000A45E, 0x0000A44B, - 0x0000A438, 0x0000A424, 0x0000A411, 0x0000A3FE, - 0x0000A3EA, 0x0000A3D7, 0x0000A3C4, 0x0000A3B0, - 0x0000A39D, 0x0000A38A, 0x0000A376, 0x0000A363, - 0x0000A350, 0x0000A33C, 0x0000A329, 0x0000A316, - 0x0000A302, 0x0000A2EF, 0x0000A2DC, 0x0000A2C8, - 0x0000A2B5, 0x0000A2A1, 0x0000A28E, 0x0000A27B, - 0x0000A267, 0x0000A254, 0x0000A240, 0x0000A22D, - 0x0000A219, 0x0000A206, 0x0000A1F2, 0x0000A1DF, - 0x0000A1CB, 0x0000A1B8, 0x0000A1A5, 0x0000A191, - 0x0000A17E, 0x0000A16A, 0x0000A156, 0x0000A143, - 0x0000A12F, 0x0000A11C, 0x0000A108, 0x0000A0F5, - 0x0000A0E1, 0x0000A0CE, 0x0000A0BA, 0x0000A0A7, - 0x0000A093, 0x0000A07F, 0x0000A06C, 0x0000A058, - 0x0000A045, 0x0000A031, 0x0000A01E, 0x0000A00A, - 0x00009FF6, 0x00009FE3, 0x00009FCF, 0x00009FBB, - 0x00009FA8, 0x00009F94, 0x00009F80, 0x00009F6D, - 0x00009F59, 0x00009F45, 0x00009F32, 0x00009F1E, - 0x00009F0A, 0x00009EF7, 0x00009EE3, 0x00009ECF, - 0x00009EBC, 0x00009EA8, 0x00009E94, 0x00009E80, - 0x00009E6D, 0x00009E59, 0x00009E45, 0x00009E31, - 0x00009E1E, 0x00009E0A, 0x00009DF6, 0x00009DE2, - 0x00009DCF, 0x00009DBB, 0x00009DA7, 0x00009D93, - 0x00009D7F, 0x00009D6B, 0x00009D58, 0x00009D44, - 0x00009D30, 0x00009D1C, 0x00009D08, 0x00009CF4, - 0x00009CE1, 0x00009CCD, 0x00009CB9, 0x00009CA5, - 0x00009C91, 0x00009C7D, 0x00009C69, 0x00009C55, - 0x00009C42, 0x00009C2E, 0x00009C1A, 0x00009C06, - 0x00009BF2, 0x00009BDE, 0x00009BCA, 0x00009BB6, - 0x00009BA2, 0x00009B8E, 0x00009B7A, 0x00009B66, - 0x00009B52, 0x00009B3E, 0x00009B2A, 0x00009B16, - 0x00009B02, 0x00009AEE, 0x00009ADA, 0x00009AC6, - 0x00009AB2, 0x00009A9E, 0x00009A8A, 0x00009A76, - 0x00009A62, 0x00009A4E, 0x00009A3A, 0x00009A26, - 0x00009A12, 0x000099FE, 0x000099EA, 0x000099D6, - 0x000099C1, 0x000099AD, 0x00009999, 0x00009985, - 0x00009971, 0x0000995D, 0x00009949, 0x00009935, - 0x00009921, 0x0000990C, 0x000098F8, 0x000098E4, - 0x000098D0, 0x000098BC, 0x000098A8, 0x00009893, - 0x0000987F, 0x0000986B, 0x00009857, 0x00009843, - 0x0000982E, 0x0000981A, 0x00009806, 0x000097F2, - 0x000097DE, 0x000097C9, 0x000097B5, 0x000097A1, - 0x0000978D, 0x00009778, 0x00009764, 0x00009750, - 0x0000973C, 0x00009727, 0x00009713, 0x000096FF, - 0x000096EA, 0x000096D6, 0x000096C2, 0x000096AD, - 0x00009699, 0x00009685, 0x00009670, 0x0000965C, - 0x00009648, 0x00009633, 0x0000961F, 0x0000960B, - 0x000095F6, 0x000095E2, 0x000095CE, 0x000095B9, - 0x000095A5, 0x00009590, 0x0000957C, 0x00009568, - 0x00009553, 0x0000953F, 0x0000952A, 0x00009516, - 0x00009502, 0x000094ED, 0x000094D9, 0x000094C4, - 0x000094B0, 0x0000949B, 0x00009487, 0x00009472, - 0x0000945E, 0x00009449, 0x00009435, 0x00009420, - 0x0000940C, 0x000093F7, 0x000093E3, 0x000093CE, - 0x000093BA, 0x000093A5, 0x00009391, 0x0000937C, - 0x00009368, 0x00009353, 0x0000933F, 0x0000932A, - 0x00009315, 0x00009301, 0x000092EC, 0x000092D8, - 0x000092C3, 0x000092AE, 0x0000929A, 0x00009285, - 0x00009271, 0x0000925C, 0x00009247, 0x00009233, - 0x0000921E, 0x0000920A, 0x000091F5, 0x000091E0, - 0x000091CC, 0x000091B7, 0x000091A2, 0x0000918E, - 0x00009179, 0x00009164, 0x00009150, 0x0000913B, - 0x00009126, 0x00009111, 0x000090FD, 0x000090E8, - 0x000090D3, 0x000090BF, 0x000090AA, 0x00009095, - 0x00009080, 0x0000906C, 0x00009057, 0x00009042, - 0x0000902D, 0x00009019, 0x00009004, 0x00008FEF, - 0x00008FDA, 0x00008FC5, 0x00008FB1, 0x00008F9C, - 0x00008F87, 0x00008F72, 0x00008F5D, 0x00008F49, - 0x00008F34, 0x00008F1F, 0x00008F0A, 0x00008EF5, - 0x00008EE0, 0x00008ECB, 0x00008EB7, 0x00008EA2, - 0x00008E8D, 0x00008E78, 0x00008E63, 0x00008E4E, - 0x00008E39, 0x00008E24, 0x00008E10, 0x00008DFB, - 0x00008DE6, 0x00008DD1, 0x00008DBC, 0x00008DA7, - 0x00008D92, 0x00008D7D, 0x00008D68, 0x00008D53, - 0x00008D3E, 0x00008D29, 0x00008D14, 0x00008CFF, - 0x00008CEA, 0x00008CD5, 0x00008CC0, 0x00008CAB, - 0x00008C96, 0x00008C81, 0x00008C6C, 0x00008C57, - 0x00008C42, 0x00008C2D, 0x00008C18, 0x00008C03, - 0x00008BEE, 0x00008BD9, 0x00008BC4, 0x00008BAF, - 0x00008B9A, 0x00008B85, 0x00008B70, 0x00008B5B, - 0x00008B46, 0x00008B31, 0x00008B1B, 0x00008B06, - 0x00008AF1, 0x00008ADC, 0x00008AC7, 0x00008AB2, - 0x00008A9D, 0x00008A88, 0x00008A72, 0x00008A5D, - 0x00008A48, 0x00008A33, 0x00008A1E, 0x00008A09, - 0x000089F4, 0x000089DE, 0x000089C9, 0x000089B4, - 0x0000899F, 0x0000898A, 0x00008974, 0x0000895F, - 0x0000894A, 0x00008935, 0x00008920, 0x0000890A, - 0x000088F5, 0x000088E0, 0x000088CB, 0x000088B5, - 0x000088A0, 0x0000888B, 0x00008876, 0x00008860, - 0x0000884B, 0x00008836, 0x00008820, 0x0000880B, - 0x000087F6, 0x000087E1, 0x000087CB, 0x000087B6, - 0x000087A1, 0x0000878B, 0x00008776, 0x00008761, - 0x0000874B, 0x00008736, 0x00008721, 0x0000870B, - 0x000086F6, 0x000086E1, 0x000086CB, 0x000086B6, - 0x000086A1, 0x0000868B, 0x00008676, 0x00008660, - 0x0000864B, 0x00008636, 0x00008620, 0x0000860B, - 0x000085F5, 0x000085E0, 0x000085CB, 0x000085B5, - 0x000085A0, 0x0000858A, 0x00008575, 0x0000855F, - 0x0000854A, 0x00008534, 0x0000851F, 0x00008509, - 0x000084F4, 0x000084DF, 0x000084C9, 0x000084B4, - 0x0000849E, 0x00008489, 0x00008473, 0x0000845E, - 0x00008448, 0x00008433, 0x0000841D, 0x00008407, - 0x000083F2, 0x000083DC, 0x000083C7, 0x000083B1, - 0x0000839C, 0x00008386, 0x00008371, 0x0000835B, - 0x00008345, 0x00008330, 0x0000831A, 0x00008305, - 0x000082EF, 0x000082DA, 0x000082C4, 0x000082AE, - 0x00008299, 0x00008283, 0x0000826D, 0x00008258, - 0x00008242, 0x0000822D, 0x00008217, 0x00008201, - 0x000081EC, 0x000081D6, 0x000081C0, 0x000081AB, - 0x00008195, 0x0000817F, 0x0000816A, 0x00008154, - 0x0000813E, 0x00008128, 0x00008113, 0x000080FD, - 0x000080E7, 0x000080D2, 0x000080BC, 0x000080A6, - 0x00008090, 0x0000807B, 0x00008065, 0x0000804F, - 0x0000803A, 0x00008024, 0x0000800E, 0x00007FF8, - 0x00007FE2, 0x00007FCD, 0x00007FB7, 0x00007FA1, - 0x00007F8B, 0x00007F76, 0x00007F60, 0x00007F4A, - 0x00007F34, 0x00007F1E, 0x00007F09, 0x00007EF3, - 0x00007EDD, 0x00007EC7, 0x00007EB1, 0x00007E9B, - 0x00007E85, 0x00007E70, 0x00007E5A, 0x00007E44, - 0x00007E2E, 0x00007E18, 0x00007E02, 0x00007DEC, - 0x00007DD7, 0x00007DC1, 0x00007DAB, 0x00007D95, - 0x00007D7F, 0x00007D69, 0x00007D53, 0x00007D3D, - 0x00007D27, 0x00007D11, 0x00007CFB, 0x00007CE6, - 0x00007CD0, 0x00007CBA, 0x00007CA4, 0x00007C8E, - 0x00007C78, 0x00007C62, 0x00007C4C, 0x00007C36, - 0x00007C20, 0x00007C0A, 0x00007BF4, 0x00007BDE, - 0x00007BC8, 0x00007BB2, 0x00007B9C, 0x00007B86, - 0x00007B70, 0x00007B5A, 0x00007B44, 0x00007B2E, - 0x00007B18, 0x00007B02, 0x00007AEC, 0x00007AD6, - 0x00007AC0, 0x00007AAA, 0x00007A93, 0x00007A7D, - 0x00007A67, 0x00007A51, 0x00007A3B, 0x00007A25, - 0x00007A0F, 0x000079F9, 0x000079E3, 0x000079CD, - 0x000079B7, 0x000079A0, 0x0000798A, 0x00007974, - 0x0000795E, 0x00007948, 0x00007932, 0x0000791C, - 0x00007906, 0x000078EF, 0x000078D9, 0x000078C3, - 0x000078AD, 0x00007897, 0x00007881, 0x0000786A, - 0x00007854, 0x0000783E, 0x00007828, 0x00007812, - 0x000077FB, 0x000077E5, 0x000077CF, 0x000077B9, - 0x000077A3, 0x0000778C, 0x00007776, 0x00007760, - 0x0000774A, 0x00007733, 0x0000771D, 0x00007707, - 0x000076F1, 0x000076DA, 0x000076C4, 0x000076AE, - 0x00007698, 0x00007681, 0x0000766B, 0x00007655, - 0x0000763F, 0x00007628, 0x00007612, 0x000075FC, - 0x000075E5, 0x000075CF, 0x000075B9, 0x000075A2, - 0x0000758C, 0x00007576, 0x0000755F, 0x00007549, - 0x00007533, 0x0000751C, 0x00007506, 0x000074F0, - 0x000074D9, 0x000074C3, 0x000074AD, 0x00007496, - 0x00007480, 0x00007469, 0x00007453, 0x0000743D, - 0x00007426, 0x00007410, 0x000073F9, 0x000073E3, - 0x000073CD, 0x000073B6, 0x000073A0, 0x00007389, - 0x00007373, 0x0000735D, 0x00007346, 0x00007330, - 0x00007319, 0x00007303, 0x000072EC, 0x000072D6, - 0x000072BF, 0x000072A9, 0x00007292, 0x0000727C, - 0x00007265, 0x0000724F, 0x00007239, 0x00007222, - 0x0000720C, 0x000071F5, 0x000071DF, 0x000071C8, - 0x000071B1, 0x0000719B, 0x00007184, 0x0000716E, - 0x00007157, 0x00007141, 0x0000712A, 0x00007114, - 0x000070FD, 0x000070E7, 0x000070D0, 0x000070BA, - 0x000070A3, 0x0000708C, 0x00007076, 0x0000705F, - 0x00007049, 0x00007032, 0x0000701B, 0x00007005, - 0x00006FEE, 0x00006FD8, 0x00006FC1, 0x00006FAA, - 0x00006F94, 0x00006F7D, 0x00006F67, 0x00006F50, - 0x00006F39, 0x00006F23, 0x00006F0C, 0x00006EF5, - 0x00006EDF, 0x00006EC8, 0x00006EB1, 0x00006E9B, - 0x00006E84, 0x00006E6D, 0x00006E57, 0x00006E40, - 0x00006E29, 0x00006E13, 0x00006DFC, 0x00006DE5, - 0x00006DCF, 0x00006DB8, 0x00006DA1, 0x00006D8A, - 0x00006D74, 0x00006D5D, 0x00006D46, 0x00006D30, - 0x00006D19, 0x00006D02, 0x00006CEB, 0x00006CD5, - 0x00006CBE, 0x00006CA7, 0x00006C90, 0x00006C7A, - 0x00006C63, 0x00006C4C, 0x00006C35, 0x00006C1E, - 0x00006C08, 0x00006BF1, 0x00006BDA, 0x00006BC3, - 0x00006BAD, 0x00006B96, 0x00006B7F, 0x00006B68, - 0x00006B51, 0x00006B3A, 0x00006B24, 0x00006B0D, - 0x00006AF6, 0x00006ADF, 0x00006AC8, 0x00006AB1, - 0x00006A9B, 0x00006A84, 0x00006A6D, 0x00006A56, - 0x00006A3F, 0x00006A28, 0x00006A11, 0x000069FB, - 0x000069E4, 0x000069CD, 0x000069B6, 0x0000699F, - 0x00006988, 0x00006971, 0x0000695A, 0x00006943, - 0x0000692D, 0x00006916, 0x000068FF, 0x000068E8, - 0x000068D1, 0x000068BA, 0x000068A3, 0x0000688C, - 0x00006875, 0x0000685E, 0x00006847, 0x00006830, - 0x00006819, 0x00006802, 0x000067EB, 0x000067D4, - 0x000067BD, 0x000067A6, 0x0000678F, 0x00006778, - 0x00006761, 0x0000674A, 0x00006733, 0x0000671C, - 0x00006705, 0x000066EE, 0x000066D7, 0x000066C0, - 0x000066A9, 0x00006692, 0x0000667B, 0x00006664, - 0x0000664D, 0x00006636, 0x0000661F, 0x00006608, - 0x000065F1, 0x000065DA, 0x000065C3, 0x000065AC, - 0x00006595, 0x0000657E, 0x00006567, 0x00006550, - 0x00006539, 0x00006521, 0x0000650A, 0x000064F3, - 0x000064DC, 0x000064C5, 0x000064AE, 0x00006497, - 0x00006480, 0x00006469, 0x00006451, 0x0000643A, - 0x00006423, 0x0000640C, 0x000063F5, 0x000063DE, - 0x000063C7, 0x000063B0, 0x00006398, 0x00006381, - 0x0000636A, 0x00006353, 0x0000633C, 0x00006325, - 0x0000630D, 0x000062F6, 0x000062DF, 0x000062C8, - 0x000062B1, 0x00006299, 0x00006282, 0x0000626B, - 0x00006254, 0x0000623D, 0x00006225, 0x0000620E, - 0x000061F7, 0x000061E0, 0x000061C9, 0x000061B1, - 0x0000619A, 0x00006183, 0x0000616C, 0x00006154, - 0x0000613D, 0x00006126, 0x0000610F, 0x000060F7, - 0x000060E0, 0x000060C9, 0x000060B2, 0x0000609A, - 0x00006083, 0x0000606C, 0x00006054, 0x0000603D, - 0x00006026, 0x0000600F, 0x00005FF7, 0x00005FE0, - 0x00005FC9, 0x00005FB1, 0x00005F9A, 0x00005F83, - 0x00005F6B, 0x00005F54, 0x00005F3D, 0x00005F25, - 0x00005F0E, 0x00005EF7, 0x00005EDF, 0x00005EC8, - 0x00005EB1, 0x00005E99, 0x00005E82, 0x00005E6B, - 0x00005E53, 0x00005E3C, 0x00005E25, 0x00005E0D, - 0x00005DF6, 0x00005DDE, 0x00005DC7, 0x00005DB0, - 0x00005D98, 0x00005D81, 0x00005D6A, 0x00005D52, - 0x00005D3B, 0x00005D23, 0x00005D0C, 0x00005CF4, - 0x00005CDD, 0x00005CC6, 0x00005CAE, 0x00005C97, - 0x00005C7F, 0x00005C68, 0x00005C50, 0x00005C39, - 0x00005C22, 0x00005C0A, 0x00005BF3, 0x00005BDB, - 0x00005BC4, 0x00005BAC, 0x00005B95, 0x00005B7D, - 0x00005B66, 0x00005B4E, 0x00005B37, 0x00005B1F, - 0x00005B08, 0x00005AF0, 0x00005AD9, 0x00005AC1, - 0x00005AAA, 0x00005A92, 0x00005A7B, 0x00005A63, - 0x00005A4C, 0x00005A34, 0x00005A1D, 0x00005A05, - 0x000059EE, 0x000059D6, 0x000059BF, 0x000059A7, - 0x00005990, 0x00005978, 0x00005961, 0x00005949, - 0x00005931, 0x0000591A, 0x00005902, 0x000058EB, - 0x000058D3, 0x000058BC, 0x000058A4, 0x0000588C, - 0x00005875, 0x0000585D, 0x00005846, 0x0000582E, - 0x00005817, 0x000057FF, 0x000057E7, 0x000057D0, - 0x000057B8, 0x000057A0, 0x00005789, 0x00005771, - 0x0000575A, 0x00005742, 0x0000572A, 0x00005713, - 0x000056FB, 0x000056E3, 0x000056CC, 0x000056B4, - 0x0000569D, 0x00005685, 0x0000566D, 0x00005656, - 0x0000563E, 0x00005626, 0x0000560F, 0x000055F7, - 0x000055DF, 0x000055C8, 0x000055B0, 0x00005598, - 0x00005580, 0x00005569, 0x00005551, 0x00005539, - 0x00005522, 0x0000550A, 0x000054F2, 0x000054DB, - 0x000054C3, 0x000054AB, 0x00005493, 0x0000547C, - 0x00005464, 0x0000544C, 0x00005435, 0x0000541D, - 0x00005405, 0x000053ED, 0x000053D6, 0x000053BE, - 0x000053A6, 0x0000538E, 0x00005377, 0x0000535F, - 0x00005347, 0x0000532F, 0x00005317, 0x00005300, - 0x000052E8, 0x000052D0, 0x000052B8, 0x000052A1, - 0x00005289, 0x00005271, 0x00005259, 0x00005241, - 0x0000522A, 0x00005212, 0x000051FA, 0x000051E2, - 0x000051CA, 0x000051B3, 0x0000519B, 0x00005183, - 0x0000516B, 0x00005153, 0x0000513B, 0x00005124, - 0x0000510C, 0x000050F4, 0x000050DC, 0x000050C4, - 0x000050AC, 0x00005095, 0x0000507D, 0x00005065, - 0x0000504D, 0x00005035, 0x0000501D, 0x00005005, - 0x00004FED, 0x00004FD6, 0x00004FBE, 0x00004FA6, - 0x00004F8E, 0x00004F76, 0x00004F5E, 0x00004F46, - 0x00004F2E, 0x00004F16, 0x00004EFF, 0x00004EE7, - 0x00004ECF, 0x00004EB7, 0x00004E9F, 0x00004E87, - 0x00004E6F, 0x00004E57, 0x00004E3F, 0x00004E27, - 0x00004E0F, 0x00004DF7, 0x00004DDF, 0x00004DC8, - 0x00004DB0, 0x00004D98, 0x00004D80, 0x00004D68, - 0x00004D50, 0x00004D38, 0x00004D20, 0x00004D08, - 0x00004CF0, 0x00004CD8, 0x00004CC0, 0x00004CA8, - 0x00004C90, 0x00004C78, 0x00004C60, 0x00004C48, - 0x00004C30, 0x00004C18, 0x00004C00, 0x00004BE8, - 0x00004BD0, 0x00004BB8, 0x00004BA0, 0x00004B88, - 0x00004B70, 0x00004B58, 0x00004B40, 0x00004B28, - 0x00004B10, 0x00004AF8, 0x00004AE0, 0x00004AC8, - 0x00004AB0, 0x00004A98, 0x00004A80, 0x00004A68, - 0x00004A50, 0x00004A38, 0x00004A1F, 0x00004A07, - 0x000049EF, 0x000049D7, 0x000049BF, 0x000049A7, - 0x0000498F, 0x00004977, 0x0000495F, 0x00004947, - 0x0000492F, 0x00004917, 0x000048FF, 0x000048E7, - 0x000048CE, 0x000048B6, 0x0000489E, 0x00004886, - 0x0000486E, 0x00004856, 0x0000483E, 0x00004826, - 0x0000480E, 0x000047F5, 0x000047DD, 0x000047C5, - 0x000047AD, 0x00004795, 0x0000477D, 0x00004765, - 0x0000474D, 0x00004734, 0x0000471C, 0x00004704, - 0x000046EC, 0x000046D4, 0x000046BC, 0x000046A4, - 0x0000468B, 0x00004673, 0x0000465B, 0x00004643, - 0x0000462B, 0x00004613, 0x000045FA, 0x000045E2, - 0x000045CA, 0x000045B2, 0x0000459A, 0x00004581, - 0x00004569, 0x00004551, 0x00004539, 0x00004521, - 0x00004508, 0x000044F0, 0x000044D8, 0x000044C0, - 0x000044A8, 0x0000448F, 0x00004477, 0x0000445F, - 0x00004447, 0x0000442F, 0x00004416, 0x000043FE, - 0x000043E6, 0x000043CE, 0x000043B5, 0x0000439D, - 0x00004385, 0x0000436D, 0x00004354, 0x0000433C, - 0x00004324, 0x0000430C, 0x000042F3, 0x000042DB, - 0x000042C3, 0x000042AB, 0x00004292, 0x0000427A, - 0x00004262, 0x0000424A, 0x00004231, 0x00004219, - 0x00004201, 0x000041E8, 0x000041D0, 0x000041B8, - 0x000041A0, 0x00004187, 0x0000416F, 0x00004157, - 0x0000413E, 0x00004126, 0x0000410E, 0x000040F5, - 0x000040DD, 0x000040C5, 0x000040AC, 0x00004094, - 0x0000407C, 0x00004064, 0x0000404B, 0x00004033, - 0x0000401B, 0x00004002, 0x00003FEA, 0x00003FD2, - 0x00003FB9, 0x00003FA1, 0x00003F89, 0x00003F70, - 0x00003F58, 0x00003F3F, 0x00003F27, 0x00003F0F, - 0x00003EF6, 0x00003EDE, 0x00003EC6, 0x00003EAD, - 0x00003E95, 0x00003E7D, 0x00003E64, 0x00003E4C, - 0x00003E33, 0x00003E1B, 0x00003E03, 0x00003DEA, - 0x00003DD2, 0x00003DBA, 0x00003DA1, 0x00003D89, - 0x00003D70, 0x00003D58, 0x00003D40, 0x00003D27, - 0x00003D0F, 0x00003CF6, 0x00003CDE, 0x00003CC5, - 0x00003CAD, 0x00003C95, 0x00003C7C, 0x00003C64, - 0x00003C4B, 0x00003C33, 0x00003C1B, 0x00003C02, - 0x00003BEA, 0x00003BD1, 0x00003BB9, 0x00003BA0, - 0x00003B88, 0x00003B6F, 0x00003B57, 0x00003B3F, - 0x00003B26, 0x00003B0E, 0x00003AF5, 0x00003ADD, - 0x00003AC4, 0x00003AAC, 0x00003A93, 0x00003A7B, - 0x00003A62, 0x00003A4A, 0x00003A31, 0x00003A19, - 0x00003A01, 0x000039E8, 0x000039D0, 0x000039B7, - 0x0000399F, 0x00003986, 0x0000396E, 0x00003955, - 0x0000393D, 0x00003924, 0x0000390C, 0x000038F3, - 0x000038DB, 0x000038C2, 0x000038AA, 0x00003891, - 0x00003879, 0x00003860, 0x00003848, 0x0000382F, - 0x00003816, 0x000037FE, 0x000037E5, 0x000037CD, - 0x000037B4, 0x0000379C, 0x00003783, 0x0000376B, - 0x00003752, 0x0000373A, 0x00003721, 0x00003709, - 0x000036F0, 0x000036D8, 0x000036BF, 0x000036A6, - 0x0000368E, 0x00003675, 0x0000365D, 0x00003644, - 0x0000362C, 0x00003613, 0x000035FB, 0x000035E2, - 0x000035C9, 0x000035B1, 0x00003598, 0x00003580, - 0x00003567, 0x0000354E, 0x00003536, 0x0000351D, - 0x00003505, 0x000034EC, 0x000034D4, 0x000034BB, - 0x000034A2, 0x0000348A, 0x00003471, 0x00003459, - 0x00003440, 0x00003427, 0x0000340F, 0x000033F6, - 0x000033DE, 0x000033C5, 0x000033AC, 0x00003394, - 0x0000337B, 0x00003362, 0x0000334A, 0x00003331, - 0x00003319, 0x00003300, 0x000032E7, 0x000032CF, - 0x000032B6, 0x0000329D, 0x00003285, 0x0000326C, - 0x00003254, 0x0000323B, 0x00003222, 0x0000320A, - 0x000031F1, 0x000031D8, 0x000031C0, 0x000031A7, - 0x0000318E, 0x00003176, 0x0000315D, 0x00003144, - 0x0000312C, 0x00003113, 0x000030FA, 0x000030E2, - 0x000030C9, 0x000030B0, 0x00003098, 0x0000307F, - 0x00003066, 0x0000304E, 0x00003035, 0x0000301C, - 0x00003004, 0x00002FEB, 0x00002FD2, 0x00002FB9, - 0x00002FA1, 0x00002F88, 0x00002F6F, 0x00002F57, - 0x00002F3E, 0x00002F25, 0x00002F0D, 0x00002EF4, - 0x00002EDB, 0x00002EC2, 0x00002EAA, 0x00002E91, - 0x00002E78, 0x00002E60, 0x00002E47, 0x00002E2E, - 0x00002E15, 0x00002DFD, 0x00002DE4, 0x00002DCB, - 0x00002DB3, 0x00002D9A, 0x00002D81, 0x00002D68, - 0x00002D50, 0x00002D37, 0x00002D1E, 0x00002D05, - 0x00002CED, 0x00002CD4, 0x00002CBB, 0x00002CA2, - 0x00002C8A, 0x00002C71, 0x00002C58, 0x00002C3F, - 0x00002C27, 0x00002C0E, 0x00002BF5, 0x00002BDC, - 0x00002BC4, 0x00002BAB, 0x00002B92, 0x00002B79, - 0x00002B61, 0x00002B48, 0x00002B2F, 0x00002B16, - 0x00002AFD, 0x00002AE5, 0x00002ACC, 0x00002AB3, - 0x00002A9A, 0x00002A82, 0x00002A69, 0x00002A50, - 0x00002A37, 0x00002A1E, 0x00002A06, 0x000029ED, - 0x000029D4, 0x000029BB, 0x000029A2, 0x0000298A, - 0x00002971, 0x00002958, 0x0000293F, 0x00002926, - 0x0000290E, 0x000028F5, 0x000028DC, 0x000028C3, - 0x000028AA, 0x00002892, 0x00002879, 0x00002860, - 0x00002847, 0x0000282E, 0x00002815, 0x000027FD, - 0x000027E4, 0x000027CB, 0x000027B2, 0x00002799, - 0x00002781, 0x00002768, 0x0000274F, 0x00002736, - 0x0000271D, 0x00002704, 0x000026EC, 0x000026D3, - 0x000026BA, 0x000026A1, 0x00002688, 0x0000266F, - 0x00002656, 0x0000263E, 0x00002625, 0x0000260C, - 0x000025F3, 0x000025DA, 0x000025C1, 0x000025A8, - 0x00002590, 0x00002577, 0x0000255E, 0x00002545, - 0x0000252C, 0x00002513, 0x000024FA, 0x000024E2, - 0x000024C9, 0x000024B0, 0x00002497, 0x0000247E, - 0x00002465, 0x0000244C, 0x00002433, 0x0000241B, - 0x00002402, 0x000023E9, 0x000023D0, 0x000023B7, - 0x0000239E, 0x00002385, 0x0000236C, 0x00002353, - 0x0000233B, 0x00002322, 0x00002309, 0x000022F0, - 0x000022D7, 0x000022BE, 0x000022A5, 0x0000228C, - 0x00002273, 0x0000225A, 0x00002242, 0x00002229, - 0x00002210, 0x000021F7, 0x000021DE, 0x000021C5, - 0x000021AC, 0x00002193, 0x0000217A, 0x00002161, - 0x00002148, 0x0000212F, 0x00002117, 0x000020FE, - 0x000020E5, 0x000020CC, 0x000020B3, 0x0000209A, - 0x00002081, 0x00002068, 0x0000204F, 0x00002036, - 0x0000201D, 0x00002004, 0x00001FEB, 0x00001FD2, - 0x00001FBA, 0x00001FA1, 0x00001F88, 0x00001F6F, - 0x00001F56, 0x00001F3D, 0x00001F24, 0x00001F0B, - 0x00001EF2, 0x00001ED9, 0x00001EC0, 0x00001EA7, - 0x00001E8E, 0x00001E75, 0x00001E5C, 0x00001E43, - 0x00001E2A, 0x00001E11, 0x00001DF8, 0x00001DDF, - 0x00001DC7, 0x00001DAE, 0x00001D95, 0x00001D7C, - 0x00001D63, 0x00001D4A, 0x00001D31, 0x00001D18, - 0x00001CFF, 0x00001CE6, 0x00001CCD, 0x00001CB4, - 0x00001C9B, 0x00001C82, 0x00001C69, 0x00001C50, - 0x00001C37, 0x00001C1E, 0x00001C05, 0x00001BEC, - 0x00001BD3, 0x00001BBA, 0x00001BA1, 0x00001B88, - 0x00001B6F, 0x00001B56, 0x00001B3D, 0x00001B24, - 0x00001B0B, 0x00001AF2, 0x00001AD9, 0x00001AC0, - 0x00001AA7, 0x00001A8E, 0x00001A75, 0x00001A5C, - 0x00001A43, 0x00001A2A, 0x00001A11, 0x000019F8, - 0x000019DF, 0x000019C6, 0x000019AD, 0x00001994, - 0x0000197B, 0x00001962, 0x00001949, 0x00001930, - 0x00001917, 0x000018FE, 0x000018E5, 0x000018CC, - 0x000018B3, 0x0000189A, 0x00001881, 0x00001868, - 0x0000184F, 0x00001836, 0x0000181D, 0x00001804, - 0x000017EB, 0x000017D2, 0x000017B9, 0x000017A0, - 0x00001787, 0x0000176E, 0x00001755, 0x0000173C, - 0x00001723, 0x0000170A, 0x000016F1, 0x000016D8, - 0x000016BF, 0x000016A6, 0x0000168D, 0x00001673, - 0x0000165A, 0x00001641, 0x00001628, 0x0000160F, - 0x000015F6, 0x000015DD, 0x000015C4, 0x000015AB, - 0x00001592, 0x00001579, 0x00001560, 0x00001547, - 0x0000152E, 0x00001515, 0x000014FC, 0x000014E3, - 0x000014CA, 0x000014B1, 0x00001498, 0x0000147F, - 0x00001466, 0x0000144C, 0x00001433, 0x0000141A, - 0x00001401, 0x000013E8, 0x000013CF, 0x000013B6, - 0x0000139D, 0x00001384, 0x0000136B, 0x00001352, - 0x00001339, 0x00001320, 0x00001307, 0x000012EE, - 0x000012D5, 0x000012BC, 0x000012A2, 0x00001289, - 0x00001270, 0x00001257, 0x0000123E, 0x00001225, - 0x0000120C, 0x000011F3, 0x000011DA, 0x000011C1, - 0x000011A8, 0x0000118F, 0x00001176, 0x0000115D, - 0x00001143, 0x0000112A, 0x00001111, 0x000010F8, - 0x000010DF, 0x000010C6, 0x000010AD, 0x00001094, - 0x0000107B, 0x00001062, 0x00001049, 0x00001030, - 0x00001017, 0x00000FFD, 0x00000FE4, 0x00000FCB, - 0x00000FB2, 0x00000F99, 0x00000F80, 0x00000F67, - 0x00000F4E, 0x00000F35, 0x00000F1C, 0x00000F03, - 0x00000EE9, 0x00000ED0, 0x00000EB7, 0x00000E9E, - 0x00000E85, 0x00000E6C, 0x00000E53, 0x00000E3A, - 0x00000E21, 0x00000E08, 0x00000DEF, 0x00000DD5, - 0x00000DBC, 0x00000DA3, 0x00000D8A, 0x00000D71, - 0x00000D58, 0x00000D3F, 0x00000D26, 0x00000D0D, - 0x00000CF4, 0x00000CDA, 0x00000CC1, 0x00000CA8, - 0x00000C8F, 0x00000C76, 0x00000C5D, 0x00000C44, - 0x00000C2B, 0x00000C12, 0x00000BF9, 0x00000BDF, - 0x00000BC6, 0x00000BAD, 0x00000B94, 0x00000B7B, - 0x00000B62, 0x00000B49, 0x00000B30, 0x00000B17, - 0x00000AFD, 0x00000AE4, 0x00000ACB, 0x00000AB2, - 0x00000A99, 0x00000A80, 0x00000A67, 0x00000A4E, - 0x00000A35, 0x00000A1B, 0x00000A02, 0x000009E9, - 0x000009D0, 0x000009B7, 0x0000099E, 0x00000985, - 0x0000096C, 0x00000953, 0x00000939, 0x00000920, - 0x00000907, 0x000008EE, 0x000008D5, 0x000008BC, - 0x000008A3, 0x0000088A, 0x00000871, 0x00000857, - 0x0000083E, 0x00000825, 0x0000080C, 0x000007F3, - 0x000007DA, 0x000007C1, 0x000007A8, 0x0000078E, - 0x00000775, 0x0000075C, 0x00000743, 0x0000072A, - 0x00000711, 0x000006F8, 0x000006DF, 0x000006C5, - 0x000006AC, 0x00000693, 0x0000067A, 0x00000661, - 0x00000648, 0x0000062F, 0x00000616, 0x000005FC, - 0x000005E3, 0x000005CA, 0x000005B1, 0x00000598, - 0x0000057F, 0x00000566, 0x0000054D, 0x00000533, - 0x0000051A, 0x00000501, 0x000004E8, 0x000004CF, - 0x000004B6, 0x0000049D, 0x00000484, 0x0000046A, - 0x00000451, 0x00000438, 0x0000041F, 0x00000406, - 0x000003ED, 0x000003D4, 0x000003BA, 0x000003A1, - 0x00000388, 0x0000036F, 0x00000356, 0x0000033D, - 0x00000324, 0x0000030B, 0x000002F1, 0x000002D8, - 0x000002BF, 0x000002A6, 0x0000028D, 0x00000274, - 0x0000025B, 0x00000242, 0x00000228, 0x0000020F, - 0x000001F6, 0x000001DD, 0x000001C4, 0x000001AB, - 0x00000192, 0x00000178, 0x0000015F, 0x00000146, - 0x0000012D, 0x00000114, 0x000000FB, 0x000000E2, - 0x000000C9, 0x000000AF, 0x00000096, 0x0000007D, - 0x00000064, 0x0000004B, 0x00000032, 0x00000019, - 0x00000000, - }; - - // TODO: Better formatting like the cosine table. - const fixed16_16 s_tanTable[]= - { - 0, 25, 50, 75, - 100, - 125, - 150, - 175, - 201, - 226, - 251, - 276, - 301, - 326, - 351, - 376, - 402, - 427, - 452, - 477, - 502, - 527, - 552, - 578, - 603, - 628, - 653, - 678, - 703, - 728, - 754, - 779, - 804, - 829, - 854, - 879, - 904, - 929, - 955, - 980, - 1005, - 1030, - 1055, - 1080, - 1105, - 1131, - 1156, - 1181, - 1206, - 1231, - 1256, - 1281, - 1307, - 1332, - 1357, - 1382, - 1407, - 1432, - 1457, - 1483, - 1508, - 1533, - 1558, - 1583, - 1608, - 1633, - 1659, - 1684, - 1709, - 1734, - 1759, - 1784, - 1810, - 1835, - 1860, - 1885, - 1910, - 1935, - 1960, - 1986, - 2011, - 2036, - 2061, - 2086, - 2111, - 2137, - 2162, - 2187, - 2212, - 2237, - 2262, - 2288, - 2313, - 2338, - 2363, - 2388, - 2413, - 2439, - 2464, - 2489, - 2514, - 2539, - 2564, - 2590, - 2615, - 2640, - 2665, - 2690, - 2715, - 2741, - 2766, - 2791, - 2816, - 2841, - 2866, - 2892, - 2917, - 2942, - 2967, - 2992, - 3018, - 3043, - 3068, - 3093, - 3118, - 3144, - 3169, - 3194, - 3219, - 3244, - 3269, - 3295, - 3320, - 3345, - 3370, - 3395, - 3421, - 3446, - 3471, - 3496, - 3521, - 3547, - 3572, - 3597, - 3622, - 3648, - 3673, - 3698, - 3723, - 3748, - 3774, - 3799, - 3824, - 3849, - 3874, - 3900, - 3925, - 3950, - 3975, - 4001, - 4026, - 4051, - 4076, - 4101, - 4127, - 4152, - 4177, - 4202, - 4228, - 4253, - 4278, - 4303, - 4329, - 4354, - 4379, - 4404, - 4430, - 4455, - 4480, - 4505, - 4531, - 4556, - 4581, - 4606, - 4632, - 4657, - 4682, - 4707, - 4733, - 4758, - 4783, - 4808, - 4834, - 4859, - 4884, - 4910, - 4935, - 4960, - 4985, - 5011, - 5036, - 5061, - 5086, - 5112, - 5137, - 5162, - 5188, - 5213, - 5238, - 5264, - 5289, - 5314, - 5339, - 5365, - 5390, - 5415, - 5441, - 5466, - 5491, - 5517, - 5542, - 5567, - 5592, - 5618, - 5643, - 5668, - 5694, - 5719, - 5744, - 5770, - 5795, - 5820, - 5846, - 5871, - 5896, - 5922, - 5947, - 5972, - 5998, - 6023, - 6048, - 6074, - 6099, - 6124, - 6150, - 6175, - 6201, - 6226, - 6251, - 6277, - 6302, - 6327, - 6353, - 6378, - 6403, - 6429, - 6454, - 6480, - 6505, - 6530, - 6556, - 6581, - 6607, - 6632, - 6657, - 6683, - 6708, - 6733, - 6759, - 6784, - 6810, - 6835, - 6861, - 6886, - 6911, - 6937, - 6962, - 6988, - 7013, - 7038, - 7064, - 7089, - 7115, - 7140, - 7166, - 7191, - 7216, - 7242, - 7267, - 7293, - 7318, - 7344, - 7369, - 7395, - 7420, - 7445, - 7471, - 7496, - 7522, - 7547, - 7573, - 7598, - 7624, - 7649, - 7675, - 7700, - 7726, - 7751, - 7777, - 7802, - 7828, - 7853, - 7879, - 7904, - 7930, - 7955, - 7981, - 8006, - 8032, - 8057, - 8083, - 8108, - 8134, - 8159, - 8185, - 8210, - 8236, - 8261, - 8287, - 8312, - 8338, - 8363, - 8389, - 8414, - 8440, - 8466, - 8491, - 8517, - 8542, - 8568, - 8593, - 8619, - 8645, - 8670, - 8696, - 8721, - 8747, - 8772, - 8798, - 8824, - 8849, - 8875, - 8900, - 8926, - 8952, - 8977, - 9003, - 9028, - 9054, - 9080, - 9105, - 9131, - 9156, - 9182, - 9208, - 9233, - 9259, - 9285, - 9310, - 9336, - 9362, - 9387, - 9413, - 9438, - 9464, - 9490, - 9515, - 9541, - 9567, - 9592, - 9618, - 9644, - 9669, - 9695, - 9721, - 9747, - 9772, - 9798, - 9824, - 9849, - 9875, - 9901, - 9926, - 9952, - 9978, - 10004, - 10029, - 10055, - 10081, - 10106, - 10132, - 10158, - 10184, - 10209, - 10235, - 10261, - 10287, - 10312, - 10338, - 10364, - 10390, - 10415, - 10441, - 10467, - 10493, - 10519, - 10544, - 10570, - 10596, - 10622, - 10647, - 10673, - 10699, - 10725, - 10751, - 10777, - 10802, - 10828, - 10854, - 10880, - 10906, - 10931, - 10957, - 10983, - 11009, - 11035, - 11061, - 11086, - 11112, - 11138, - 11164, - 11190, - 11216, - 11242, - 11268, - 11293, - 11319, - 11345, - 11371, - 11397, - 11423, - 11449, - 11475, - 11501, - 11526, - 11552, - 11578, - 11604, - 11630, - 11656, - 11682, - 11708, - 11734, - 11760, - 11786, - 11812, - 11838, - 11864, - 11890, - 11916, - 11941, - 11967, - 11993, - 12019, - 12045, - 12071, - 12097, - 12123, - 12149, - 12175, - 12201, - 12227, - 12253, - 12279, - 12305, - 12331, - 12357, - 12383, - 12409, - 12436, - 12462, - 12488, - 12514, - 12540, - 12566, - 12592, - 12618, - 12644, - 12670, - 12696, - 12722, - 12748, - 12774, - 12800, - 12827, - 12853, - 12879, - 12905, - 12931, - 12957, - 12983, - 13009, - 13035, - 13062, - 13088, - 13114, - 13140, - 13166, - 13192, - 13218, - 13245, - 13271, - 13297, - 13323, - 13349, - 13375, - 13402, - 13428, - 13454, - 13480, - 13506, - 13533, - 13559, - 13585, - 13611, - 13637, - 13664, - 13690, - 13716, - 13742, - 13769, - 13795, - 13821, - 13847, - 13874, - 13900, - 13926, - 13952, - 13979, - 14005, - 14031, - 14057, - 14084, - 14110, - 14136, - 14163, - 14189, - 14215, - 14242, - 14268, - 14294, - 14321, - 14347, - 14373, - 14400, - 14426, - 14452, - 14479, - 14505, - 14531, - 14558, - 14584, - 14611, - 14637, - 14663, - 14690, - 14716, - 14743, - 14769, - 14795, - 14822, - 14848, - 14875, - 14901, - 14927, - 14954, - 14980, - 15007, - 15033, - 15060, - 15086, - 15113, - 15139, - 15166, - 15192, - 15219, - 15245, - 15272, - 15298, - 15325, - 15351, - 15378, - 15404, - 15431, - 15457, - 15484, - 15510, - 15537, - 15563, - 15590, - 15616, - 15643, - 15670, - 15696, - 15723, - 15749, - 15776, - 15802, - 15829, - 15856, - 15882, - 15909, - 15935, - 15962, - 15989, - 16015, - 16042, - 16069, - 16095, - 16122, - 16149, - 16175, - 16202, - 16229, - 16255, - 16282, - 16309, - 16335, - 16362, - 16389, - 16415, - 16442, - 16469, - 16496, - 16522, - 16549, - 16576, - 16603, - 16629, - 16656, - 16683, - 16710, - 16736, - 16763, - 16790, - 16817, - 16843, - 16870, - 16897, - 16924, - 16951, - 16977, - 17004, - 17031, - 17058, - 17085, - 17112, - 17138, - 17165, - 17192, - 17219, - 17246, - 17273, - 17300, - 17327, - 17353, - 17380, - 17407, - 17434, - 17461, - 17488, - 17515, - 17542, - 17569, - 17596, - 17623, - 17650, - 17677, - 17704, - 17731, - 17758, - 17784, - 17811, - 17838, - 17865, - 17892, - 17919, - 17946, - 17974, - 18001, - 18028, - 18055, - 18082, - 18109, - 18136, - 18163, - 18190, - 18217, - 18244, - 18271, - 18298, - 18325, - 18352, - 18380, - 18407, - 18434, - 18461, - 18488, - 18515, - 18542, - 18569, - 18597, - 18624, - 18651, - 18678, - 18705, - 18732, - 18760, - 18787, - 18814, - 18841, - 18868, - 18896, - 18923, - 18950, - 18977, - 19005, - 19032, - 19059, - 19086, - 19114, - 19141, - 19168, - 19195, - 19223, - 19250, - 19277, - 19305, - 19332, - 19359, - 19387, - 19414, - 19441, - 19469, - 19496, - 19523, - 19551, - 19578, - 19605, - 19633, - 19660, - 19688, - 19715, - 19742, - 19770, - 19797, - 19825, - 19852, - 19880, - 19907, - 19935, - 19962, - 19989, - 20017, - 20044, - 20072, - 20099, - 20127, - 20154, - 20182, - 20209, - 20237, - 20264, - 20292, - 20320, - 20347, - 20375, - 20402, - 20430, - 20457, - 20485, - 20513, - 20540, - 20568, - 20595, - 20623, - 20651, - 20678, - 20706, - 20734, - 20761, - 20789, - 20817, - 20844, - 20872, - 20900, - 20927, - 20955, - 20983, - 21010, - 21038, - 21066, - 21094, - 21121, - 21149, - 21177, - 21205, - 21232, - 21260, - 21288, - 21316, - 21343, - 21371, - 21399, - 21427, - 21455, - 21483, - 21510, - 21538, - 21566, - 21594, - 21622, - 21650, - 21678, - 21705, - 21733, - 21761, - 21789, - 21817, - 21845, - 21873, - 21901, - 21929, - 21957, - 21985, - 22013, - 22041, - 22069, - 22097, - 22125, - 22153, - 22181, - 22209, - 22237, - 22265, - 22293, - 22321, - 22349, - 22377, - 22405, - 22433, - 22461, - 22489, - 22517, - 22545, - 22573, - 22602, - 22630, - 22658, - 22686, - 22714, - 22742, - 22770, - 22799, - 22827, - 22855, - 22883, - 22911, - 22940, - 22968, - 22996, - 23024, - 23053, - 23081, - 23109, - 23137, - 23166, - 23194, - 23222, - 23250, - 23279, - 23307, - 23335, - 23364, - 23392, - 23420, - 23449, - 23477, - 23505, - 23534, - 23562, - 23591, - 23619, - 23647, - 23676, - 23704, - 23733, - 23761, - 23789, - 23818, - 23846, - 23875, - 23903, - 23932, - 23960, - 23989, - 24017, - 24046, - 24074, - 24103, - 24131, - 24160, - 24188, - 24217, - 24246, - 24274, - 24303, - 24331, - 24360, - 24389, - 24417, - 24446, - 24474, - 24503, - 24532, - 24560, - 24589, - 24618, - 24646, - 24675, - 24704, - 24732, - 24761, - 24790, - 24819, - 24847, - 24876, - 24905, - 24934, - 24962, - 24991, - 25020, - 25049, - 25078, - 25106, - 25135, - 25164, - 25193, - 25222, - 25251, - 25280, - 25308, - 25337, - 25366, - 25395, - 25424, - 25453, - 25482, - 25511, - 25540, - 25569, - 25598, - 25627, - 25656, - 25685, - 25714, - 25743, - 25772, - 25801, - 25830, - 25859, - 25888, - 25917, - 25946, - 25975, - 26004, - 26033, - 26062, - 26091, - 26120, - 26150, - 26179, - 26208, - 26237, - 26266, - 26295, - 26325, - 26354, - 26383, - 26412, - 26441, - 26471, - 26500, - 26529, - 26558, - 26588, - 26617, - 26646, - 26675, - 26705, - 26734, - 26763, - 26793, - 26822, - 26851, - 26881, - 26910, - 26940, - 26969, - 26998, - 27028, - 27057, - 27087, - 27116, - 27145, - 27175, - 27204, - 27234, - 27263, - 27293, - 27322, - 27352, - 27381, - 27411, - 27440, - 27470, - 27499, - 27529, - 27559, - 27588, - 27618, - 27647, - 27677, - 27707, - 27736, - 27766, - 27795, - 27825, - 27855, - 27884, - 27914, - 27944, - 27974, - 28003, - 28033, - 28063, - 28092, - 28122, - 28152, - 28182, - 28212, - 28241, - 28271, - 28301, - 28331, - 28361, - 28390, - 28420, - 28450, - 28480, - 28510, - 28540, - 28570, - 28600, - 28630, - 28660, - 28689, - 28719, - 28749, - 28779, - 28809, - 28839, - 28869, - 28899, - 28929, - 28959, - 28989, - 29020, - 29050, - 29080, - 29110, - 29140, - 29170, - 29200, - 29230, - 29260, - 29291, - 29321, - 29351, - 29381, - 29411, - 29441, - 29472, - 29502, - 29532, - 29562, - 29593, - 29623, - 29653, - 29683, - 29714, - 29744, - 29774, - 29805, - 29835, - 29865, - 29896, - 29926, - 29956, - 29987, - 30017, - 30048, - 30078, - 30108, - 30139, - 30169, - 30200, - 30230, - 30261, - 30291, - 30322, - 30352, - 30383, - 30413, - 30444, - 30474, - 30505, - 30536, - 30566, - 30597, - 30627, - 30658, - 30689, - 30719, - 30750, - 30781, - 30811, - 30842, - 30873, - 30904, - 30934, - 30965, - 30996, - 31026, - 31057, - 31088, - 31119, - 31150, - 31180, - 31211, - 31242, - 31273, - 31304, - 31335, - 31366, - 31396, - 31427, - 31458, - 31489, - 31520, - 31551, - 31582, - 31613, - 31644, - 31675, - 31706, - 31737, - 31768, - 31799, - 31830, - 31861, - 31892, - 31923, - 31955, - 31986, - 32017, - 32048, - 32079, - 32110, - 32141, - 32173, - 32204, - 32235, - 32266, - 32297, - 32329, - 32360, - 32391, - 32422, - 32454, - 32485, - 32516, - 32548, - 32579, - 32610, - 32642, - 32673, - 32705, - 32736, - 32767, - 32799, - 32830, - 32862, - 32893, - 32925, - 32956, - 32988, - 33019, - 33051, - 33082, - 33114, - 33145, - 33177, - 33208, - 33240, - 33272, - 33303, - 33335, - 33366, - 33398, - 33430, - 33461, - 33493, - 33525, - 33557, - 33588, - 33620, - 33652, - 33684, - 33715, - 33747, - 33779, - 33811, - 33843, - 33874, - 33906, - 33938, - 33970, - 34002, - 34034, - 34066, - 34098, - 34130, - 34162, - 34194, - 34225, - 34257, - 34289, - 34322, - 34354, - 34386, - 34418, - 34450, - 34482, - 34514, - 34546, - 34578, - 34610, - 34642, - 34675, - 34707, - 34739, - 34771, - 34803, - 34836, - 34868, - 34900, - 34932, - 34965, - 34997, - 35029, - 35062, - 35094, - 35126, - 35159, - 35191, - 35223, - 35256, - 35288, - 35321, - 35353, - 35385, - 35418, - 35450, - 35483, - 35515, - 35548, - 35580, - 35613, - 35646, - 35678, - 35711, - 35743, - 35776, - 35809, - 35841, - 35874, - 35907, - 35939, - 35972, - 36005, - 36037, - 36070, - 36103, - 36136, - 36168, - 36201, - 36234, - 36267, - 36300, - 36333, - 36365, - 36398, - 36431, - 36464, - 36497, - 36530, - 36563, - 36596, - 36629, - 36662, - 36695, - 36728, - 36761, - 36794, - 36827, - 36860, - 36893, - 36926, - 36959, - 36993, - 37026, - 37059, - 37092, - 37125, - 37158, - 37192, - 37225, - 37258, - 37291, - 37325, - 37358, - 37391, - 37425, - 37458, - 37491, - 37525, - 37558, - 37591, - 37625, - 37658, - 37692, - 37725, - 37759, - 37792, - 37826, - 37859, - 37893, - 37926, - 37960, - 37993, - 38027, - 38060, - 38094, - 38128, - 38161, - 38195, - 38229, - 38262, - 38296, - 38330, - 38364, - 38397, - 38431, - 38465, - 38499, - 38532, - 38566, - 38600, - 38634, - 38668, - 38702, - 38736, - 38770, - 38804, - 38837, - 38871, - 38905, - 38939, - 38973, - 39007, - 39042, - 39076, - 39110, - 39144, - 39178, - 39212, - 39246, - 39280, - 39314, - 39349, - 39383, - 39417, - 39451, - 39486, - 39520, - 39554, - 39588, - 39623, - 39657, - 39691, - 39726, - 39760, - 39794, - 39829, - 39863, - 39898, - 39932, - 39967, - 40001, - 40036, - 40070, - 40105, - 40139, - 40174, - 40208, - 40243, - 40278, - 40312, - 40347, - 40382, - 40416, - 40451, - 40486, - 40520, - 40555, - 40590, - 40625, - 40660, - 40694, - 40729, - 40764, - 40799, - 40834, - 40869, - 40904, - 40939, - 40973, - 41008, - 41043, - 41078, - 41113, - 41148, - 41184, - 41219, - 41254, - 41289, - 41324, - 41359, - 41394, - 41429, - 41465, - 41500, - 41535, - 41570, - 41605, - 41641, - 41676, - 41711, - 41747, - 41782, - 41817, - 41853, - 41888, - 41923, - 41959, - 41994, - 42030, - 42065, - 42101, - 42136, - 42172, - 42207, - 42243, - 42279, - 42314, - 42350, - 42385, - 42421, - 42457, - 42492, - 42528, - 42564, - 42600, - 42635, - 42671, - 42707, - 42743, - 42779, - 42814, - 42850, - 42886, - 42922, - 42958, - 42994, - 43030, - 43066, - 43102, - 43138, - 43174, - 43210, - 43246, - 43282, - 43318, - 43354, - 43390, - 43427, - 43463, - 43499, - 43535, - 43571, - 43608, - 43644, - 43680, - 43717, - 43753, - 43789, - 43826, - 43862, - 43898, - 43935, - 43971, - 44008, - 44044, - 44081, - 44117, - 44154, - 44190, - 44227, - 44263, - 44300, - 44337, - 44373, - 44410, - 44447, - 44483, - 44520, - 44557, - 44594, - 44630, - 44667, - 44704, - 44741, - 44778, - 44815, - 44851, - 44888, - 44925, - 44962, - 44999, - 45036, - 45073, - 45110, - 45147, - 45184, - 45221, - 45259, - 45296, - 45333, - 45370, - 45407, - 45444, - 45482, - 45519, - 45556, - 45593, - 45631, - 45668, - 45705, - 45743, - 45780, - 45818, - 45855, - 45892, - 45930, - 45967, - 46005, - 46042, - 46080, - 46118, - 46155, - 46193, - 46230, - 46268, - 46306, - 46343, - 46381, - 46419, - 46457, - 46494, - 46532, - 46570, - 46608, - 46646, - 46684, - 46721, - 46759, - 46797, - 46835, - 46873, - 46911, - 46949, - 46987, - 47025, - 47063, - 47102, - 47140, - 47178, - 47216, - 47254, - 47292, - 47331, - 47369, - 47407, - 47445, - 47484, - 47522, - 47560, - 47599, - 47637, - 47676, - 47714, - 47753, - 47791, - 47830, - 47868, - 47907, - 47945, - 47984, - 48022, - 48061, - 48100, - 48138, - 48177, - 48216, - 48255, - 48293, - 48332, - 48371, - 48410, - 48449, - 48488, - 48526, - 48565, - 48604, - 48643, - 48682, - 48721, - 48760, - 48799, - 48838, - 48878, - 48917, - 48956, - 48995, - 49034, - 49073, - 49113, - 49152, - 49191, - 49230, - 49270, - 49309, - 49349, - 49388, - 49427, - 49467, - 49506, - 49546, - 49585, - 49625, - 49664, - 49704, - 49744, - 49783, - 49823, - 49862, - 49902, - 49942, - 49982, - 50021, - 50061, - 50101, - 50141, - 50181, - 50221, - 50260, - 50300, - 50340, - 50380, - 50420, - 50460, - 50500, - 50540, - 50581, - 50621, - 50661, - 50701, - 50741, - 50781, - 50822, - 50862, - 50902, - 50942, - 50983, - 51023, - 51063, - 51104, - 51144, - 51185, - 51225, - 51266, - 51306, - 51347, - 51387, - 51428, - 51469, - 51509, - 51550, - 51591, - 51631, - 51672, - 51713, - 51754, - 51794, - 51835, - 51876, - 51917, - 51958, - 51999, - 52040, - 52081, - 52122, - 52163, - 52204, - 52245, - 52286, - 52327, - 52369, - 52410, - 52451, - 52492, - 52533, - 52575, - 52616, - 52657, - 52699, - 52740, - 52782, - 52823, - 52865, - 52906, - 52948, - 52989, - 53031, - 53072, - 53114, - 53156, - 53197, - 53239, - 53281, - 53322, - 53364, - 53406, - 53448, - 53490, - 53532, - 53574, - 53615, - 53657, - 53699, - 53741, - 53784, - 53826, - 53868, - 53910, - 53952, - 53994, - 54036, - 54079, - 54121, - 54163, - 54205, - 54248, - 54290, - 54333, - 54375, - 54417, - 54460, - 54502, - 54545, - 54587, - 54630, - 54673, - 54715, - 54758, - 54801, - 54843, - 54886, - 54929, - 54972, - 55015, - 55057, - 55100, - 55143, - 55186, - 55229, - 55272, - 55315, - 55358, - 55401, - 55444, - 55487, - 55531, - 55574, - 55617, - 55660, - 55704, - 55747, - 55790, - 55834, - 55877, - 55920, - 55964, - 56007, - 56051, - 56094, - 56138, - 56181, - 56225, - 56269, - 56312, - 56356, - 56400, - 56444, - 56487, - 56531, - 56575, - 56619, - 56663, - 56707, - 56751, - 56795, - 56839, - 56883, - 56927, - 56971, - 57015, - 57059, - 57104, - 57148, - 57192, - 57236, - 57281, - 57325, - 57369, - 57414, - 57458, - 57503, - 57547, - 57592, - 57636, - 57681, - 57725, - 57770, - 57815, - 57859, - 57904, - 57949, - 57994, - 58039, - 58083, - 58128, - 58173, - 58218, - 58263, - 58308, - 58353, - 58398, - 58443, - 58489, - 58534, - 58579, - 58624, - 58669, - 58715, - 58760, - 58805, - 58851, - 58896, - 58942, - 58987, - 59033, - 59078, - 59124, - 59169, - 59215, - 59261, - 59306, - 59352, - 59398, - 59444, - 59489, - 59535, - 59581, - 59627, - 59673, - 59719, - 59765, - 59811, - 59857, - 59903, - 59950, - 59996, - 60042, - 60088, - 60134, - 60181, - 60227, - 60273, - 60320, - 60366, - 60413, - 60459, - 60506, - 60552, - 60599, - 60646, - 60692, - 60739, - 60786, - 60833, - 60879, - 60926, - 60973, - 61020, - 61067, - 61114, - 61161, - 61208, - 61255, - 61302, - 61349, - 61396, - 61444, - 61491, - 61538, - 61585, - 61633, - 61680, - 61728, - 61775, - 61822, - 61870, - 61918, - 61965, - 62013, - 62060, - 62108, - 62156, - 62204, - 62251, - 62299, - 62347, - 62395, - 62443, - 62491, - 62539, - 62587, - 62635, - 62683, - 62731, - 62779, - 62828, - 62876, - 62924, - 62972, - 63021, - 63069, - 63118, - 63166, - 63215, - 63263, - 63312, - 63360, - 63409, - 63458, - 63506, - 63555, - 63604, - 63653, - 63702, - 63750, - 63799, - 63848, - 63897, - 63946, - 63996, - 64045, - 64094, - 64143, - 64192, - 64241, - 64291, - 64340, - 64389, - 64439, - 64488, - 64538, - 64587, - 64637, - 64687, - 64736, - 64786, - 64836, - 64885, - 64935, - 64985, - 65035, - 65085, - 65135, - 65185, - 65235, - 65285, - 65335, - 65385, - 65435, - 65485, - 65535, - 65586, - 65636, - 65686, - 65737, - 65787, - 65838, - 65888, - 65939, - 65989, - 66040, - 66091, - 66141, - 66192, - 66243, - 66294, - 66345, - 66396, - 66447, - 66498, - 66549, - 66600, - 66651, - 66702, - 66753, - 66804, - 66856, - 66907, - 66958, - 67010, - 67061, - 67113, - 67164, - 67216, - 67267, - 67319, - 67371, - 67422, - 67474, - 67526, - 67578, - 67629, - 67681, - 67733, - 67785, - 67837, - 67889, - 67942, - 67994, - 68046, - 68098, - 68151, - 68203, - 68255, - 68308, - 68360, - 68413, - 68465, - 68518, - 68570, - 68623, - 68676, - 68728, - 68781, - 68834, - 68887, - 68940, - 68993, - 69046, - 69099, - 69152, - 69205, - 69258, - 69312, - 69365, - 69418, - 69472, - 69525, - 69578, - 69632, - 69685, - 69739, - 69793, - 69846, - 69900, - 69954, - 70007, - 70061, - 70115, - 70169, - 70223, - 70277, - 70331, - 70385, - 70439, - 70494, - 70548, - 70602, - 70656, - 70711, - 70765, - 70820, - 70874, - 70929, - 70983, - 71038, - 71093, - 71147, - 71202, - 71257, - 71312, - 71367, - 71422, - 71477, - 71532, - 71587, - 71642, - 71697, - 71752, - 71808, - 71863, - 71918, - 71974, - 72029, - 72085, - 72140, - 72196, - 72252, - 72307, - 72363, - 72419, - 72475, - 72531, - 72587, - 72643, - 72699, - 72755, - 72811, - 72867, - 72923, - 72979, - 73036, - 73092, - 73149, - 73205, - 73262, - 73318, - 73375, - 73431, - 73488, - 73545, - 73602, - 73659, - 73715, - 73772, - 73829, - 73886, - 73944, - 74001, - 74058, - 74115, - 74172, - 74230, - 74287, - 74345, - 74402, - 74460, - 74517, - 74575, - 74633, - 74690, - 74748, - 74806, - 74864, - 74922, - 74980, - 75038, - 75096, - 75154, - 75213, - 75271, - 75329, - 75387, - 75446, - 75504, - 75563, - 75621, - 75680, - 75739, - 75797, - 75856, - 75915, - 75974, - 76033, - 76092, - 76151, - 76210, - 76269, - 76328, - 76388, - 76447, - 76506, - 76566, - 76625, - 76685, - 76744, - 76804, - 76864, - 76923, - 76983, - 77043, - 77103, - 77163, - 77223, - 77283, - 77343, - 77403, - 77463, - 77524, - 77584, - 77644, - 77705, - 77765, - 77826, - 77886, - 77947, - 78008, - 78068, - 78129, - 78190, - 78251, - 78312, - 78373, - 78434, - 78495, - 78557, - 78618, - 78679, - 78741, - 78802, - 78864, - 78925, - 78987, - 79048, - 79110, - 79172, - 79234, - 79296, - 79358, - 79420, - 79482, - 79544, - 79606, - 79668, - 79731, - 79793, - 79855, - 79918, - 79980, - 80043, - 80106, - 80168, - 80231, - 80294, - 80357, - 80420, - 80483, - 80546, - 80609, - 80672, - 80735, - 80799, - 80862, - 80925, - 80989, - 81053, - 81116, - 81180, - 81244, - 81307, - 81371, - 81435, - 81499, - 81563, - 81627, - 81691, - 81756, - 81820, - 81884, - 81949, - 82013, - 82078, - 82142, - 82207, - 82271, - 82336, - 82401, - 82466, - 82531, - 82596, - 82661, - 82726, - 82791, - 82857, - 82922, - 82987, - 83053, - 83118, - 83184, - 83250, - 83315, - 83381, - 83447, - 83513, - 83579, - 83645, - 83711, - 83777, - 83843, - 83910, - 83976, - 84043, - 84109, - 84176, - 84242, - 84309, - 84376, - 84443, - 84509, - 84576, - 84643, - 84710, - 84778, - 84845, - 84912, - 84980, - 85047, - 85114, - 85182, - 85250, - 85317, - 85385, - 85453, - 85521, - 85589, - 85657, - 85725, - 85793, - 85861, - 85930, - 85998, - 86066, - 86135, - 86204, - 86272, - 86341, - 86410, - 86479, - 86547, - 86616, - 86686, - 86755, - 86824, - 86893, - 86963, - 87032, - 87101, - 87171, - 87241, - 87310, - 87380, - 87450, - 87520, - 87590, - 87660, - 87730, - 87800, - 87871, - 87941, - 88011, - 88082, - 88152, - 88223, - 88294, - 88365, - 88435, - 88506, - 88577, - 88648, - 88720, - 88791, - 88862, - 88934, - 89005, - 89077, - 89148, - 89220, - 89292, - 89363, - 89435, - 89507, - 89579, - 89651, - 89724, - 89796, - 89868, - 89941, - 90013, - 90086, - 90158, - 90231, - 90304, - 90377, - 90450, - 90523, - 90596, - 90669, - 90742, - 90816, - 90889, - 90963, - 91036, - 91110, - 91184, - 91258, - 91332, - 91406, - 91480, - 91554, - 91628, - 91702, - 91777, - 91851, - 91926, - 92000, - 92075, - 92150, - 92225, - 92300, - 92375, - 92450, - 92525, - 92600, - 92675, - 92751, - 92826, - 92902, - 92978, - 93053, - 93129, - 93205, - 93281, - 93357, - 93434, - 93510, - 93586, - 93663, - 93739, - 93816, - 93892, - 93969, - 94046, - 94123, - 94200, - 94277, - 94354, - 94431, - 94509, - 94586, - 94664, - 94741, - 94819, - 94897, - 94975, - 95053, - 95131, - 95209, - 95287, - 95365, - 95444, - 95522, - 95601, - 95680, - 95758, - 95837, - 95916, - 95995, - 96074, - 96153, - 96233, - 96312, - 96391, - 96471, - 96551, - 96630, - 96710, - 96790, - 96870, - 96950, - 97030, - 97111, - 97191, - 97271, - 97352, - 97433, - 97513, - 97594, - 97675, - 97756, - 97837, - 97918, - 98000, - 98081, - 98163, - 98244, - 98326, - 98408, - 98489, - 98571, - 98653, - 98735, - 98818, - 98900, - 98982, - 99065, - 99148, - 99230, - 99313, - 99396, - 99479, - 99562, - 99645, - 99729, - 99812, - 99895, - 99979, - 100063, - 100146, - 100230, - 100314, - 100398, - 100482, - 100567, - 100651, - 100736, - 100820, - 100905, - 100990, - 101074, - 101159, - 101244, - 101330, - 101415, - 101500, - 101586, - 101671, - 101757, - 101843, - 101929, - 102015, - 102101, - 102187, - 102273, - 102360, - 102446, - 102533, - 102619, - 102706, - 102793, - 102880, - 102967, - 103054, - 103142, - 103229, - 103317, - 103404, - 103492, - 103580, - 103668, - 103756, - 103844, - 103933, - 104021, - 104109, - 104198, - 104287, - 104376, - 104465, - 104554, - 104643, - 104732, - 104821, - 104911, - 105000, - 105090, - 105180, - 105270, - 105360, - 105450, - 105540, - 105631, - 105721, - 105812, - 105902, - 105993, - 106084, - 106175, - 106266, - 106358, - 106449, - 106541, - 106632, - 106724, - 106816, - 106908, - 107000, - 107092, - 107184, - 107277, - 107369, - 107462, - 107555, - 107648, - 107741, - 107834, - 107927, - 108020, - 108114, - 108207, - 108301, - 108395, - 108489, - 108583, - 108677, - 108771, - 108866, - 108960, - 109055, - 109150, - 109245, - 109340, - 109435, - 109530, - 109626, - 109721, - 109817, - 109912, - 110008, - 110104, - 110200, - 110297, - 110393, - 110490, - 110586, - 110683, - 110780, - 110877, - 110974, - 111071, - 111169, - 111266, - 111364, - 111462, - 111560, - 111658, - 111756, - 111854, - 111952, - 112051, - 112150, - 112248, - 112347, - 112446, - 112546, - 112645, - 112744, - 112844, - 112944, - 113043, - 113143, - 113244, - 113344, - 113444, - 113545, - 113645, - 113746, - 113847, - 113948, - 114049, - 114151, - 114252, - 114354, - 114455, - 114557, - 114659, - 114761, - 114864, - 114966, - 115069, - 115171, - 115274, - 115377, - 115480, - 115583, - 115687, - 115790, - 115894, - 115998, - 116102, - 116206, - 116310, - 116414, - 116519, - 116623, - 116728, - 116833, - 116938, - 117044, - 117149, - 117254, - 117360, - 117466, - 117572, - 117678, - 117784, - 117891, - 117997, - 118104, - 118211, - 118318, - 118425, - 118532, - 118639, - 118747, - 118855, - 118963, - 119071, - 119179, - 119287, - 119396, - 119504, - 119613, - 119722, - 119831, - 119940, - 120050, - 120159, - 120269, - 120379, - 120489, - 120599, - 120709, - 120820, - 120930, - 121041, - 121152, - 121263, - 121374, - 121486, - 121597, - 121709, - 121821, - 121933, - 122045, - 122158, - 122270, - 122383, - 122496, - 122609, - 122722, - 122835, - 122949, - 123062, - 123176, - 123290, - 123404, - 123519, - 123633, - 123748, - 123863, - 123978, - 124093, - 124208, - 124324, - 124439, - 124555, - 124671, - 124787, - 124904, - 125020, - 125137, - 125254, - 125371, - 125488, - 125605, - 125723, - 125841, - 125958, - 126077, - 126195, - 126313, - 126432, - 126551, - 126669, - 126789, - 126908, - 127027, - 127147, - 127267, - 127387, - 127507, - 127627, - 127748, - 127869, - 127990, - 128111, - 128232, - 128353, - 128475, - 128597, - 128719, - 128841, - 128963, - 129086, - 129209, - 129331, - 129455, - 129578, - 129701, - 129825, - 129949, - 130073, - 130197, - 130322, - 130446, - 130571, - 130696, - 130821, - 130947, - 131072, - 131198, - 131324, - 131450, - 131576, - 131703, - 131830, - 131957, - 132084, - 132211, - 132338, - 132466, - 132594, - 132722, - 132851, - 132979, - 133108, - 133237, - 133366, - 133495, - 133625, - 133754, - 133884, - 134014, - 134145, - 134275, - 134406, - 134537, - 134668, - 134799, - 134931, - 135063, - 135195, - 135327, - 135459, - 135592, - 135725, - 135858, - 135991, - 136125, - 136258, - 136392, - 136526, - 136661, - 136795, - 136930, - 137065, - 137200, - 137335, - 137471, - 137607, - 137743, - 137879, - 138016, - 138152, - 138289, - 138426, - 138564, - 138701, - 138839, - 138977, - 139115, - 139254, - 139393, - 139532, - 139671, - 139810, - 139950, - 140090, - 140230, - 140370, - 140511, - 140651, - 140792, - 140934, - 141075, - 141217, - 141359, - 141501, - 141643, - 141786, - 141929, - 142072, - 142215, - 142359, - 142503, - 142647, - 142791, - 142936, - 143081, - 143226, - 143371, - 143517, - 143662, - 143808, - 143955, - 144101, - 144248, - 144395, - 144542, - 144690, - 144837, - 144986, - 145134, - 145282, - 145431, - 145580, - 145729, - 145879, - 146029, - 146179, - 146329, - 146480, - 146630, - 146781, - 146933, - 147084, - 147236, - 147388, - 147541, - 147693, - 147846, - 148000, - 148153, - 148307, - 148461, - 148615, - 148769, - 148924, - 149079, - 149235, - 149390, - 149546, - 149702, - 149859, - 150015, - 150172, - 150329, - 150487, - 150645, - 150803, - 150961, - 151120, - 151279, - 151438, - 151597, - 151757, - 151917, - 152077, - 152238, - 152399, - 152560, - 152722, - 152883, - 153045, - 153208, - 153370, - 153533, - 153697, - 153860, - 154024, - 154188, - 154352, - 154517, - 154682, - 154847, - 155013, - 155179, - 155345, - 155512, - 155678, - 155845, - 156013, - 156181, - 156349, - 156517, - 156686, - 156855, - 157024, - 157193, - 157363, - 157533, - 157704, - 157875, - 158046, - 158217, - 158389, - 158561, - 158734, - 158906, - 159079, - 159253, - 159427, - 159601, - 159775, - 159950, - 160125, - 160300, - 160476, - 160652, - 160828, - 161005, - 161182, - 161359, - 161537, - 161715, - 161893, - 162072, - 162251, - 162430, - 162610, - 162790, - 162970, - 163151, - 163332, - 163513, - 163695, - 163877, - 164060, - 164242, - 164426, - 164609, - 164793, - 164977, - 165162, - 165347, - 165532, - 165718, - 165904, - 166090, - 166277, - 166464, - 166651, - 166839, - 167027, - 167216, - 167405, - 167594, - 167784, - 167974, - 168164, - 168355, - 168546, - 168738, - 168930, - 169122, - 169315, - 169508, - 169701, - 169895, - 170089, - 170284, - 170479, - 170674, - 170870, - 171066, - 171263, - 171460, - 171657, - 171855, - 172053, - 172252, - 172451, - 172650, - 172850, - 173050, - 173251, - 173452, - 173653, - 173855, - 174057, - 174260, - 174463, - 174666, - 174870, - 175074, - 175279, - 175484, - 175690, - 175896, - 176102, - 176309, - 176516, - 176724, - 176932, - 177140, - 177349, - 177559, - 177769, - 177979, - 178190, - 178401, - 178612, - 178824, - 179037, - 179250, - 179463, - 179677, - 179891, - 180106, - 180321, - 180537, - 180753, - 180969, - 181186, - 181404, - 181622, - 181840, - 182059, - 182278, - 182498, - 182718, - 182939, - 183160, - 183382, - 183604, - 183827, - 184050, - 184274, - 184498, - 184722, - 184947, - 185173, - 185399, - 185625, - 185852, - 186080, - 186308, - 186536, - 186765, - 186995, - 187225, - 187455, - 187686, - 187918, - 188150, - 188382, - 188615, - 188849, - 189083, - 189318, - 189553, - 189789, - 190025, - 190261, - 190499, - 190736, - 190975, - 191213, - 191453, - 191693, - 191933, - 192174, - 192416, - 192658, - 192900, - 193143, - 193387, - 193631, - 193876, - 194122, - 194367, - 194614, - 194861, - 195109, - 195357, - 195606, - 195855, - 196105, - 196355, - 196606, - 196858, - 197110, - 197363, - 197616, - 197870, - 198125, - 198380, - 198636, - 198892, - 199149, - 199406, - 199664, - 199923, - 200182, - 200442, - 200703, - 200964, - 201226, - 201488, - 201751, - 202015, - 202279, - 202544, - 202809, - 203076, - 203342, - 203610, - 203878, - 204147, - 204416, - 204686, - 204956, - 205228, - 205500, - 205772, - 206045, - 206319, - 206594, - 206869, - 207145, - 207422, - 207699, - 207977, - 208255, - 208535, - 208815, - 209095, - 209376, - 209658, - 209941, - 210225, - 210509, - 210793, - 211079, - 211365, - 211652, - 211940, - 212228, - 212517, - 212807, - 213097, - 213389, - 213681, - 213973, - 214267, - 214561, - 214856, - 215151, - 215448, - 215745, - 216043, - 216341, - 216641, - 216941, - 217242, - 217544, - 217846, - 218149, - 218453, - 218758, - 219064, - 219370, - 219677, - 219985, - 220294, - 220603, - 220913, - 221225, - 221536, - 221849, - 222163, - 222477, - 222792, - 223108, - 223425, - 223743, - 224061, - 224381, - 224701, - 225022, - 225344, - 225666, - 225990, - 226314, - 226640, - 226966, - 227293, - 227621, - 227949, - 228279, - 228610, - 228941, - 229273, - 229606, - 229940, - 230275, - 230611, - 230948, - 231286, - 231624, - 231964, - 232304, - 232646, - 232988, - 233331, - 233676, - 234021, - 234367, - 234714, - 235062, - 235411, - 235761, - 236112, - 236463, - 236816, - 237170, - 237525, - 237881, - 238237, - 238595, - 238954, - 239314, - 239674, - 240036, - 240399, - 240763, - 241128, - 241493, - 241860, - 242228, - 242597, - 242967, - 243338, - 243711, - 244084, - 244458, - 244834, - 245210, - 245588, - 245966, - 246346, - 246727, - 247109, - 247492, - 247876, - 248261, - 248647, - 249035, - 249423, - 249813, - 250204, - 250596, - 250989, - 251384, - 251779, - 252176, - 252574, - 252973, - 253373, - 253774, - 254177, - 254581, - 254986, - 255392, - 255799, - 256208, - 256618, - 257029, - 257441, - 257855, - 258270, - 258686, - 259103, - 259522, - 259941, - 260363, - 260785, - 261209, - 261634, - 262060, - 262488, - 262917, - 263347, - 263779, - 264212, - 264646, - 265082, - 265519, - 265957, - 266397, - 266838, - 267280, - 267724, - 268169, - 268616, - 269064, - 269514, - 269965, - 270417, - 270871, - 271326, - 271782, - 272241, - 272700, - 273161, - 273624, - 274088, - 274553, - 275020, - 275489, - 275959, - 276430, - 276903, - 277378, - 277854, - 278332, - 278811, - 279292, - 279774, - 280258, - 280743, - 281231, - 281719, - 282210, - 282702, - 283195, - 283691, - 284188, - 284686, - 285186, - 285688, - 286192, - 286697, - 287204, - 287713, - 288223, - 288735, - 289249, - 289765, - 290282, - 290801, - 291322, - 291845, - 292369, - 292895, - 293423, - 293953, - 294485, - 295018, - 295554, - 296091, - 296630, - 297171, - 297714, - 298259, - 298805, - 299354, - 299904, - 300457, - 301011, - 301567, - 302126, - 302686, - 303248, - 303812, - 304379, - 304947, - 305517, - 306090, - 306664, - 307240, - 307819, - 308400, - 308982, - 309567, - 310154, - 310743, - 311335, - 311928, - 312524, - 313121, - 313721, - 314324, - 314928, - 315535, - 316143, - 316754, - 317368, - 317984, - 318602, - 319222, - 319844, - 320469, - 321097, - 321726, - 322358, - 322993, - 323629, - 324269, - 324910, - 325554, - 326201, - 326850, - 327502, - 328156, - 328812, - 329471, - 330133, - 330797, - 331464, - 332133, - 332805, - 333480, - 334157, - 334837, - 335519, - 336204, - 336892, - 337583, - 338276, - 338973, - 339671, - 340373, - 341078, - 341785, - 342495, - 343208, - 343924, - 344643, - 345364, - 346089, - 346816, - 347547, - 348280, - 349017, - 349756, - 350499, - 351244, - 351993, - 352744, - 353499, - 354257, - 355018, - 355783, - 356550, - 357321, - 358094, - 358872, - 359652, - 360436, - 361223, - 362013, - 362807, - 363604, - 364404, - 365208, - 366016, - 366826, - 367641, - 368458, - 369280, - 370105, - 370933, - 371765, - 372601, - 373440, - 374283, - 375130, - 375981, - 376835, - 377693, - 378555, - 379420, - 380290, - 381163, - 382040, - 382921, - 383807, - 384696, - 385589, - 386486, - 387387, - 388293, - 389202, - 390116, - 391033, - 391956, - 392882, - 393812, - 394747, - 395686, - 396630, - 397578, - 398530, - 399487, - 400448, - 401414, - 402384, - 403359, - 404338, - 405323, - 406311, - 407305, - 408303, - 409306, - 410314, - 411327, - 412345, - 413367, - 414395, - 415427, - 416465, - 417507, - 418555, - 419608, - 420666, - 421729, - 422798, - 423871, - 424951, - 426035, - 427125, - 428221, - 429322, - 430428, - 431540, - 432658, - 433781, - 434910, - 436045, - 437186, - 438332, - 439485, - 440643, - 441807, - 442978, - 444154, - 445337, - 446526, - 447720, - 448922, - 450129, - 451343, - 452564, - 453791, - 455024, - 456264, - 457511, - 458764, - 460024, - 461291, - 462565, - 463845, - 465133, - 466428, - 467729, - 469038, - 470354, - 471678, - 473009, - 474347, - 475692, - 477045, - 478406, - 479774, - 481150, - 482534, - 483925, - 485325, - 486732, - 488148, - 489571, - 491003, - 492443, - 493891, - 495348, - 496813, - 498287, - 499769, - 501260, - 502760, - 504269, - 505787, - 507313, - 508849, - 510394, - 511948, - 513512, - 515084, - 516667, - 518259, - 519861, - 521472, - 523093, - 524725, - 526366, - 528018, - 529679, - 531351, - 533034, - 534727, - 536431, - 538145, - 539870, - 541606, - 543353, - 545112, - 546881, - 548662, - 550455, - 552259, - 554074, - 555902, - 557741, - 559593, - 561457, - 563332, - 565221, - 567122, - 569035, - 570962, - 572901, - 574853, - 576819, - 578797, - 580790, - 582795, - 584815, - 586848, - 588896, - 590957, - 593033, - 595124, - 597229, - 599348, - 601483, - 603633, - 605798, - 607978, - 610174, - 612386, - 614613, - 616857, - 619117, - 621393, - 623686, - 625996, - 628323, - 630667, - 633028, - 635407, - 637804, - 640218, - 642651, - 645102, - 647572, - 650060, - 652568, - 655094, - 657640, - 660206, - 662792, - 665398, - 668024, - 670671, - 673338, - 676027, - 678737, - 681469, - 684223, - 686999, - 689797, - 692618, - 695461, - 698328, - 701219, - 704133, - 707072, - 710035, - 713023, - 716035, - 719073, - 722137, - 725227, - 728343, - 731486, - 734655, - 737853, - 741077, - 744330, - 747612, - 750922, - 754261, - 757631, - 761030, - 764459, - 767919, - 771411, - 774934, - 778490, - 782077, - 785698, - 789353, - 793041, - 796763, - 800521, - 804314, - 808143, - 812008, - 815910, - 819849, - 823827, - 827843, - 831898, - 835992, - 840127, - 844303, - 848521, - 852780, - 857082, - 861428, - 865817, - 870251, - 874731, - 879257, - 883829, - 888449, - 893118, - 897835, - 902602, - 907420, - 912290, - 917211, - 922186, - 927215, - 932298, - 937438, - 942634, - 947887, - 953200, - 958571, - 964004, - 969498, - 975055, - 980675, - 986361, - 992112, - 997931, - 1003818, - 1009775, - 1015802, - 1021901, - 1028074, - 1034322, - 1040645, - 1047047, - 1053527, - 1060087, - 1066729, - 1073455, - 1080266, - 1087164, - 1094149, - 1101225, - 1108393, - 1115654, - 1123011, - 1130465, - 1138018, - 1145673, - 1153430, - 1161294, - 1169265, - 1177345, - 1185538, - 1193845, - 1202270, - 1210813, - 1219479, - 1228269, - 1237186, - 1246233, - 1255414, - 1264730, - 1274185, - 1283782, - 1293525, - 1303416, - 1313459, - 1323658, - 1334015, - 1344536, - 1355224, - 1366083, - 1377116, - 1388329, - 1399726, - 1411311, - 1423088, - 1435064, - 1447242, - 1459629, - 1472229, - 1485047, - 1498091, - 1511365, - 1524876, - 1538631, - 1552635, - 1566897, - 1581422, - 1596218, - 1611294, - 1626656, - 1642314, - 1658276, - 1674550, - 1691147, - 1708075, - 1725345, - 1742967, - 1760953, - 1779313, - 1798060, - 1817205, - 1836761, - 1856743, - 1877164, - 1898038, - 1919381, - 1941209, - 1963539, - 1986387, - 2009773, - 2033716, - 2058236, - 2083353, - 2109090, - 2135471, - 2162519, - 2190260, - 2218722, - 2247933, - 2277922, - 2308722, - 2340365, - 2372887, - 2406325, - 2440718, - 2476107, - 2512537, - 2550055, - 2588709, - 2628552, - 2669640, - 2712032, - 2755792, - 2800985, - 2847685, - 2895968, - 2945916, - 2997615, - 3051161, - 3106654, - 3164201, - 3223920, - 3285935, - 3350382, - 3417407, - 3487167, - 3559833, - 3635591, - 3714643, - 3797207, - 3883524, - 3973856, - 4068489, - 4167737, - 4271947, - 4381501, - 4496821, - 4618374, - 4746679, - 4882315, - 5025930, - 5178248, - 5340085, - 5512363, - 5696125, - 5892561, - 6103026, - 6329081, - 6572525, - 6835443, - 7120270, - 7429864, - 7767602, - 8137505, - 8544398, - 8994120, - 9493811, - 10052288, - 10680573, - 11392628, - 12206405, - 13145377, - 14240842, - 15535482, - 17089047, - 18987848, - 21361347, - 24412986, - 28481835, - 34178221, - 42722794, - 56963745, - 85445637, - 170891290, - -2147483647, - -170891330, - -85445647, - -56963750, - -42722797, - -34178222, - -28481836, - -24412987, - -21361348, - -18987849, - -17089048, - -15535482, - -14240842, - -13145377, - -12206405, - -11392629, - -10680573, - -10052288, - -9493811, - -8994120, - -8544398, - -8137505, - -7767602, - -7429864, - -7120270, - -6835443, - -6572525, - -6329081, - -6103026, - -5892561, - -5696125, - -5512363, - -5340085, - -5178248, - -5025930, - -4882315, - -4746679, - -4618374, - -4496821, - -4381501, - -4271947, - -4167737, - -4068489, - -3973856, - -3883525, - -3797207, - -3714643, - -3635591, - -3559833, - -3487167, - -3417407, - -3350382, - -3285935, - -3223920, - -3164201, - -3106654, - -3051161, - -2997615, - -2945916, - -2895968, - -2847685, - -2800985, - -2755792, - -2712032, - -2669640, - -2628552, - -2588709, - -2550055, - -2512537, - -2476107, - -2440718, - -2406325, - -2372887, - -2340365, - -2308722, - -2277922, - -2247933, - -2218722, - -2190260, - -2162519, - -2135471, - -2109090, - -2083353, - -2058236, - -2033716, - -2009773, - -1986387, - -1963539, - -1941209, - -1919381, - -1898038, - -1877164, - -1856743, - -1836761, - -1817205, - -1798060, - -1779313, - -1760953, - -1742967, - -1725345, - -1708075, - -1691147, - -1674550, - -1658276, - -1642314, - -1626656, - -1611294, - -1596218, - -1581422, - -1566897, - -1552635, - -1538631, - -1524876, - -1511365, - -1498091, - -1485047, - -1472229, - -1459629, - -1447242, - -1435064, - -1423088, - -1411311, - -1399726, - -1388329, - -1377116, - -1366083, - -1355224, - -1344536, - -1334015, - -1323658, - -1313459, - -1303416, - -1293525, - -1283782, - -1274185, - -1264730, - -1255414, - -1246233, - -1237186, - -1228269, - -1219479, - -1210813, - -1202270, - -1193845, - -1185538, - -1177345, - -1169265, - -1161294, - -1153430, - -1145673, - -1138018, - -1130465, - -1123011, - -1115654, - -1108393, - -1101225, - -1094149, - -1087164, - -1080266, - -1073455, - -1066729, - -1060087, - -1053527, - -1047047, - -1040645, - -1034322, - -1028074, - -1021901, - -1015802, - -1009775, - -1003818, - -997931, - -992112, - -986361, - -980675, - -975055, - -969498, - -964004, - -958571, - -953200, - -947887, - -942634, - -937438, - -932298, - -927215, - -922186, - -917211, - -912290, - -907420, - -902602, - -897835, - -893118, - -888449, - -883829, - -879257, - -874731, - -870251, - -865817, - -861428, - -857082, - -852780, - -848521, - -844303, - -840127, - -835992, - -831898, - -827843, - -823827, - -819849, - -815910, - -812008, - -808143, - -804314, - -800521, - -796763, - -793041, - -789353, - -785698, - -782077, - -778490, - -774934, - -771411, - -767919, - -764459, - -761030, - -757631, - -754261, - -750922, - -747612, - -744330, - -741077, - -737853, - -734655, - -731486, - -728343, - -725227, - -722137, - -719073, - -716035, - -713023, - -710035, - -707072, - -704133, - -701219, - -698328, - -695461, - -692618, - -689797, - -686999, - -684223, - -681469, - -678737, - -676027, - -673338, - -670671, - -668024, - -665398, - -662792, - -660206, - -657640, - -655094, - -652568, - -650060, - -647572, - -645102, - -642651, - -640218, - -637804, - -635407, - -633028, - -630667, - -628323, - -625996, - -623686, - -621393, - -619117, - -616857, - -614613, - -612386, - -610174, - -607978, - -605798, - -603633, - -601483, - -599348, - -597229, - -595124, - -593033, - -590957, - -588896, - -586848, - -584815, - -582795, - -580790, - -578797, - -576819, - -574853, - -572901, - -570962, - -569035, - -567122, - -565221, - -563333, - -561457, - -559593, - -557741, - -555902, - -554074, - -552259, - -550455, - -548662, - -546881, - -545112, - -543353, - -541606, - -539870, - -538145, - -536431, - -534727, - -533034, - -531351, - -529679, - -528018, - -526366, - -524725, - -523093, - -521472, - -519861, - -518259, - -516667, - -515084, - -513512, - -511948, - -510394, - -508849, - -507313, - -505787, - -504269, - -502760, - -501260, - -499769, - -498287, - -496813, - -495348, - -493891, - -492443, - -491003, - -489571, - -488148, - -486732, - -485325, - -483925, - -482534, - -481150, - -479774, - -478406, - -477045, - -475692, - -474347, - -473009, - -471678, - -470354, - -469038, - -467729, - -466428, - -465133, - -463845, - -462565, - -461291, - -460024, - -458764, - -457511, - -456264, - -455024, - -453791, - -452564, - -451343, - -450129, - -448922, - -447720, - -446526, - -445337, - -444154, - -442978, - -441807, - -440643, - -439485, - -438332, - -437186, - -436045, - -434910, - -433781, - -432658, - -431540, - -430428, - -429322, - -428221, - -427125, - -426035, - -424951, - -423871, - -422798, - -421729, - -420666, - -419608, - -418555, - -417507, - -416465, - -415427, - -414395, - -413367, - -412345, - -411327, - -410314, - -409306, - -408303, - -407305, - -406311, - -405323, - -404338, - -403359, - -402384, - -401414, - -400448, - -399487, - -398530, - -397578, - -396630, - -395686, - -394747, - -393812, - -392882, - -391956, - -391033, - -390116, - -389202, - -388293, - -387387, - -386486, - -385589, - -384696, - -383807, - -382921, - -382040, - -381163, - -380290, - -379420, - -378555, - -377693, - -376835, - -375981, - -375130, - -374283, - -373440, - -372601, - -371765, - -370933, - -370105, - -369280, - -368458, - -367641, - -366826, - -366016, - -365208, - -364404, - -363604, - -362807, - -362013, - -361223, - -360436, - -359652, - -358872, - -358094, - -357321, - -356550, - -355783, - -355018, - -354257, - -353499, - -352744, - -351993, - -351244, - -350499, - -349756, - -349017, - -348280, - -347547, - -346816, - -346089, - -345364, - -344643, - -343924, - -343208, - -342495, - -341785, - -341078, - -340373, - -339671, - -338973, - -338276, - -337583, - -336892, - -336204, - -335519, - -334837, - -334157, - -333480, - -332805, - -332133, - -331464, - -330797, - -330133, - -329471, - -328812, - -328156, - -327502, - -326850, - -326201, - -325554, - -324910, - -324269, - -323629, - -322993, - -322358, - -321726, - -321097, - -320469, - -319844, - -319222, - -318602, - -317984, - -317368, - -316754, - -316143, - -315535, - -314928, - -314324, - -313721, - -313121, - -312524, - -311928, - -311335, - -310743, - -310154, - -309567, - -308982, - -308400, - -307819, - -307240, - -306664, - -306090, - -305517, - -304947, - -304379, - -303812, - -303248, - -302686, - -302126, - -301567, - -301011, - -300457, - -299904, - -299354, - -298805, - -298259, - -297714, - -297171, - -296630, - -296091, - -295554, - -295018, - -294485, - -293953, - -293423, - -292895, - -292369, - -291845, - -291322, - -290801, - -290282, - -289765, - -289249, - -288735, - -288223, - -287713, - -287204, - -286697, - -286192, - -285688, - -285186, - -284686, - -284188, - -283691, - -283195, - -282702, - -282210, - -281719, - -281231, - -280743, - -280258, - -279774, - -279292, - -278811, - -278332, - -277854, - -277378, - -276903, - -276430, - -275959, - -275489, - -275020, - -274553, - -274088, - -273624, - -273161, - -272700, - -272241, - -271782, - -271326, - -270871, - -270417, - -269965, - -269514, - -269064, - -268616, - -268169, - -267724, - -267280, - -266838, - -266397, - -265957, - -265519, - -265082, - -264646, - -264212, - -263779, - -263347, - -262917, - -262488, - -262060, - -261634, - -261209, - -260785, - -260363, - -259941, - -259522, - -259103, - -258686, - -258270, - -257855, - -257441, - -257029, - -256618, - -256208, - -255799, - -255392, - -254986, - -254581, - -254177, - -253774, - -253373, - -252973, - -252574, - -252176, - -251779, - -251384, - -250989, - -250596, - -250204, - -249813, - -249423, - -249035, - -248647, - -248261, - -247876, - -247492, - -247109, - -246727, - -246346, - -245966, - -245588, - -245210, - -244834, - -244458, - -244084, - -243711, - -243338, - -242967, - -242597, - -242228, - -241860, - -241493, - -241128, - -240763, - -240399, - -240036, - -239674, - -239314, - -238954, - -238595, - -238237, - -237881, - -237525, - -237170, - -236816, - -236463, - -236112, - -235761, - -235411, - -235062, - -234714, - -234367, - -234021, - -233676, - -233331, - -232988, - -232646, - -232304, - -231964, - -231624, - -231286, - -230948, - -230611, - -230275, - -229940, - -229606, - -229273, - -228941, - -228610, - -228279, - -227949, - -227621, - -227293, - -226966, - -226640, - -226314, - -225990, - -225666, - -225344, - -225022, - -224701, - -224381, - -224061, - -223743, - -223425, - -223108, - -222792, - -222477, - -222163, - -221849, - -221536, - -221225, - -220913, - -220603, - -220294, - -219985, - -219677, - -219370, - -219064, - -218758, - -218453, - -218149, - -217846, - -217544, - -217242, - -216941, - -216641, - -216341, - -216043, - -215745, - -215448, - -215151, - -214856, - -214561, - -214267, - -213973, - -213681, - -213389, - -213097, - -212807, - -212517, - -212228, - -211940, - -211652, - -211365, - -211079, - -210793, - -210509, - -210225, - -209941, - -209658, - -209376, - -209095, - -208815, - -208535, - -208255, - -207977, - -207699, - -207422, - -207145, - -206869, - -206594, - -206319, - -206045, - -205772, - -205500, - -205228, - -204956, - -204686, - -204416, - -204147, - -203878, - -203610, - -203342, - -203076, - -202809, - -202544, - -202279, - -202015, - -201751, - -201488, - -201226, - -200964, - -200703, - -200442, - -200182, - -199923, - -199664, - -199406, - -199149, - -198892, - -198636, - -198380, - -198125, - -197870, - -197616, - -197363, - -197110, - -196858, - -196606, - -196355, - -196105, - -195855, - -195606, - -195357, - -195109, - -194861, - -194614, - -194367, - -194122, - -193876, - -193631, - -193387, - -193143, - -192900, - -192658, - -192416, - -192174, - -191933, - -191693, - -191453, - -191213, - -190975, - -190736, - -190499, - -190261, - -190025, - -189789, - -189553, - -189318, - -189083, - -188849, - -188615, - -188382, - -188150, - -187918, - -187686, - -187455, - -187225, - -186995, - -186765, - -186536, - -186308, - -186080, - -185852, - -185625, - -185399, - -185173, - -184947, - -184722, - -184498, - -184274, - -184050, - -183827, - -183604, - -183382, - -183160, - -182939, - -182718, - -182498, - -182278, - -182059, - -181840, - -181622, - -181404, - -181186, - -180969, - -180753, - -180537, - -180321, - -180106, - -179891, - -179677, - -179463, - -179250, - -179037, - -178824, - -178612, - -178401, - -178190, - -177979, - -177769, - -177559, - -177349, - -177140, - -176932, - -176724, - -176516, - -176309, - -176102, - -175896, - -175690, - -175484, - -175279, - -175074, - -174870, - -174666, - -174463, - -174260, - -174057, - -173855, - -173653, - -173452, - -173251, - -173050, - -172850, - -172650, - -172451, - -172252, - -172053, - -171855, - -171657, - -171460, - -171263, - -171066, - -170870, - -170674, - -170479, - -170284, - -170089, - -169895, - -169701, - -169508, - -169315, - -169122, - -168930, - -168738, - -168546, - -168355, - -168164, - -167974, - -167784, - -167594, - -167405, - -167216, - -167027, - -166839, - -166651, - -166464, - -166277, - -166090, - -165904, - -165718, - -165532, - -165347, - -165162, - -164977, - -164793, - -164609, - -164426, - -164242, - -164060, - -163877, - -163695, - -163513, - -163332, - -163151, - -162970, - -162790, - -162610, - -162430, - -162251, - -162072, - -161893, - -161715, - -161537, - -161359, - -161182, - -161005, - -160828, - -160652, - -160476, - -160300, - -160125, - -159950, - -159775, - -159601, - -159427, - -159253, - -159079, - -158906, - -158734, - -158561, - -158389, - -158217, - -158046, - -157875, - -157704, - -157533, - -157363, - -157193, - -157024, - -156855, - -156686, - -156517, - -156349, - -156181, - -156013, - -155845, - -155678, - -155512, - -155345, - -155179, - -155013, - -154847, - -154682, - -154517, - -154352, - -154188, - -154024, - -153860, - -153697, - -153533, - -153370, - -153208, - -153045, - -152883, - -152722, - -152560, - -152399, - -152238, - -152077, - -151917, - -151757, - -151597, - -151438, - -151279, - -151120, - -150961, - -150803, - -150645, - -150487, - -150329, - -150172, - -150015, - -149859, - -149702, - -149546, - -149390, - -149235, - -149079, - -148924, - -148769, - -148615, - -148461, - -148307, - -148153, - -148000, - -147846, - -147693, - -147541, - -147388, - -147236, - -147084, - -146933, - -146781, - -146630, - -146480, - -146329, - -146179, - -146029, - -145879, - -145729, - -145580, - -145431, - -145282, - -145134, - -144986, - -144837, - -144690, - -144542, - -144395, - -144248, - -144101, - -143955, - -143808, - -143662, - -143517, - -143371, - -143226, - -143081, - -142936, - -142791, - -142647, - -142503, - -142359, - -142215, - -142072, - -141929, - -141786, - -141643, - -141501, - -141359, - -141217, - -141075, - -140934, - -140792, - -140651, - -140511, - -140370, - -140230, - -140090, - -139950, - -139810, - -139671, - -139532, - -139393, - -139254, - -139115, - -138977, - -138839, - -138701, - -138564, - -138426, - -138289, - -138152, - -138016, - -137879, - -137743, - -137607, - -137471, - -137335, - -137200, - -137065, - -136930, - -136795, - -136661, - -136526, - -136392, - -136258, - -136125, - -135991, - -135858, - -135725, - -135592, - -135459, - -135327, - -135195, - -135063, - -134931, - -134799, - -134668, - -134537, - -134406, - -134275, - -134145, - -134014, - -133884, - -133754, - -133625, - -133495, - -133366, - -133237, - -133108, - -132979, - -132851, - -132722, - -132594, - -132466, - -132338, - -132211, - -132084, - -131957, - -131830, - -131703, - -131576, - -131450, - -131324, - -131198, - -131072, - -130947, - -130821, - -130696, - -130571, - -130446, - -130322, - -130197, - -130073, - -129949, - -129825, - -129701, - -129578, - -129455, - -129331, - -129209, - -129086, - -128963, - -128841, - -128719, - -128597, - -128475, - -128353, - -128232, - -128111, - -127990, - -127869, - -127748, - -127627, - -127507, - -127387, - -127267, - -127147, - -127027, - -126908, - -126789, - -126669, - -126551, - -126432, - -126313, - -126195, - -126077, - -125958, - -125841, - -125723, - -125605, - -125488, - -125371, - -125254, - -125137, - -125020, - -124904, - -124787, - -124671, - -124555, - -124439, - -124324, - -124208, - -124093, - -123978, - -123863, - -123748, - -123633, - -123519, - -123404, - -123290, - -123176, - -123062, - -122949, - -122835, - -122722, - -122609, - -122496, - -122383, - -122270, - -122158, - -122045, - -121933, - -121821, - -121709, - -121597, - -121486, - -121374, - -121263, - -121152, - -121041, - -120930, - -120820, - -120709, - -120599, - -120489, - -120379, - -120269, - -120159, - -120050, - -119940, - -119831, - -119722, - -119613, - -119504, - -119396, - -119287, - -119179, - -119071, - -118963, - -118855, - -118747, - -118639, - -118532, - -118425, - -118318, - -118211, - -118104, - -117997, - -117891, - -117784, - -117678, - -117572, - -117466, - -117360, - -117254, - -117149, - -117044, - -116938, - -116833, - -116728, - -116623, - -116519, - -116414, - -116310, - -116206, - -116102, - -115998, - -115894, - -115790, - -115687, - -115583, - -115480, - -115377, - -115274, - -115171, - -115069, - -114966, - -114864, - -114761, - -114659, - -114557, - -114455, - -114354, - -114252, - -114151, - -114049, - -113948, - -113847, - -113746, - -113645, - -113545, - -113444, - -113344, - -113244, - -113143, - -113043, - -112944, - -112844, - -112744, - -112645, - -112546, - -112446, - -112347, - -112248, - -112150, - -112051, - -111952, - -111854, - -111756, - -111658, - -111560, - -111462, - -111364, - -111266, - -111169, - -111071, - -110974, - -110877, - -110780, - -110683, - -110586, - -110490, - -110393, - -110297, - -110200, - -110104, - -110008, - -109912, - -109817, - -109721, - -109626, - -109530, - -109435, - -109340, - -109245, - -109150, - -109055, - -108960, - -108866, - -108771, - -108677, - -108583, - -108489, - -108395, - -108301, - -108207, - -108114, - -108020, - -107927, - -107834, - -107741, - -107648, - -107555, - -107462, - -107369, - -107277, - -107184, - -107092, - -107000, - -106908, - -106816, - -106724, - -106632, - -106541, - -106449, - -106358, - -106266, - -106175, - -106084, - -105993, - -105902, - -105812, - -105721, - -105631, - -105540, - -105450, - -105360, - -105270, - -105180, - -105090, - -105000, - -104911, - -104821, - -104732, - -104643, - -104554, - -104465, - -104376, - -104287, - -104198, - -104109, - -104021, - -103933, - -103844, - -103756, - -103668, - -103580, - -103492, - -103404, - -103317, - -103229, - -103142, - -103054, - -102967, - -102880, - -102793, - -102706, - -102619, - -102533, - -102446, - -102360, - -102273, - -102187, - -102101, - -102015, - -101929, - -101843, - -101757, - -101671, - -101586, - -101500, - -101415, - -101330, - -101244, - -101159, - -101074, - -100990, - -100905, - -100820, - -100736, - -100651, - -100567, - -100482, - -100398, - -100314, - -100230, - -100146, - -100063, - -99979, - -99895, - -99812, - -99729, - -99645, - -99562, - -99479, - -99396, - -99313, - -99230, - -99148, - -99065, - -98982, - -98900, - -98818, - -98735, - -98653, - -98571, - -98489, - -98408, - -98326, - -98244, - -98163, - -98081, - -98000, - -97918, - -97837, - -97756, - -97675, - -97594, - -97513, - -97433, - -97352, - -97271, - -97191, - -97111, - -97030, - -96950, - -96870, - -96790, - -96710, - -96630, - -96551, - -96471, - -96391, - -96312, - -96233, - -96153, - -96074, - -95995, - -95916, - -95837, - -95758, - -95680, - -95601, - -95522, - -95444, - -95365, - -95287, - -95209, - -95131, - -95053, - -94975, - -94897, - -94819, - -94741, - -94664, - -94586, - -94509, - -94431, - -94354, - -94277, - -94200, - -94123, - -94046, - -93969, - -93892, - -93816, - -93739, - -93663, - -93586, - -93510, - -93434, - -93357, - -93281, - -93205, - -93129, - -93053, - -92978, - -92902, - -92826, - -92751, - -92675, - -92600, - -92525, - -92450, - -92375, - -92300, - -92225, - -92150, - -92075, - -92000, - -91926, - -91851, - -91777, - -91702, - -91628, - -91554, - -91480, - -91406, - -91332, - -91258, - -91184, - -91110, - -91036, - -90963, - -90889, - -90816, - -90742, - -90669, - -90596, - -90523, - -90450, - -90377, - -90304, - -90231, - -90158, - -90086, - -90013, - -89941, - -89868, - -89796, - -89724, - -89651, - -89579, - -89507, - -89435, - -89363, - -89292, - -89220, - -89148, - -89077, - -89005, - -88934, - -88862, - -88791, - -88720, - -88648, - -88577, - -88506, - -88435, - -88365, - -88294, - -88223, - -88152, - -88082, - -88011, - -87941, - -87871, - -87800, - -87730, - -87660, - -87590, - -87520, - -87450, - -87380, - -87310, - -87241, - -87171, - -87101, - -87032, - -86963, - -86893, - -86824, - -86755, - -86686, - -86616, - -86547, - -86479, - -86410, - -86341, - -86272, - -86204, - -86135, - -86066, - -85998, - -85930, - -85861, - -85793, - -85725, - -85657, - -85589, - -85521, - -85453, - -85385, - -85317, - -85250, - -85182, - -85114, - -85047, - -84980, - -84912, - -84845, - -84778, - -84710, - -84643, - -84576, - -84509, - -84443, - -84376, - -84309, - -84242, - -84176, - -84109, - -84043, - -83976, - -83910, - -83843, - -83777, - -83711, - -83645, - -83579, - -83513, - -83447, - -83381, - -83315, - -83250, - -83184, - -83118, - -83053, - -82987, - -82922, - -82857, - -82791, - -82726, - -82661, - -82596, - -82531, - -82466, - -82401, - -82336, - -82271, - -82207, - -82142, - -82078, - -82013, - -81949, - -81884, - -81820, - -81756, - -81691, - -81627, - -81563, - -81499, - -81435, - -81371, - -81307, - -81244, - -81180, - -81116, - -81053, - -80989, - -80925, - -80862, - -80799, - -80735, - -80672, - -80609, - -80546, - -80483, - -80420, - -80357, - -80294, - -80231, - -80168, - -80106, - -80043, - -79980, - -79918, - -79855, - -79793, - -79731, - -79668, - -79606, - -79544, - -79482, - -79420, - -79358, - -79296, - -79234, - -79172, - -79110, - -79048, - -78987, - -78925, - -78864, - -78802, - -78741, - -78679, - -78618, - -78557, - -78495, - -78434, - -78373, - -78312, - -78251, - -78190, - -78129, - -78068, - -78008, - -77947, - -77886, - -77826, - -77765, - -77705, - -77644, - -77584, - -77524, - -77463, - -77403, - -77343, - -77283, - -77223, - -77163, - -77103, - -77043, - -76983, - -76923, - -76864, - -76804, - -76744, - -76685, - -76625, - -76566, - -76506, - -76447, - -76388, - -76328, - -76269, - -76210, - -76151, - -76092, - -76033, - -75974, - -75915, - -75856, - -75797, - -75739, - -75680, - -75621, - -75563, - -75504, - -75446, - -75387, - -75329, - -75271, - -75213, - -75154, - -75096, - -75038, - -74980, - -74922, - -74864, - -74806, - -74748, - -74690, - -74633, - -74575, - -74517, - -74460, - -74402, - -74345, - -74287, - -74230, - -74172, - -74115, - -74058, - -74001, - -73944, - -73886, - -73829, - -73772, - -73715, - -73659, - -73602, - -73545, - -73488, - -73431, - -73375, - -73318, - -73262, - -73205, - -73149, - -73092, - -73036, - -72979, - -72923, - -72867, - -72811, - -72755, - -72699, - -72643, - -72587, - -72531, - -72475, - -72419, - -72363, - -72307, - -72252, - -72196, - -72140, - -72085, - -72029, - -71974, - -71918, - -71863, - -71808, - -71752, - -71697, - -71642, - -71587, - -71532, - -71477, - -71422, - -71367, - -71312, - -71257, - -71202, - -71147, - -71093, - -71038, - -70983, - -70929, - -70874, - -70820, - -70765, - -70711, - -70656, - -70602, - -70548, - -70494, - -70439, - -70385, - -70331, - -70277, - -70223, - -70169, - -70115, - -70061, - -70007, - -69954, - -69900, - -69846, - -69793, - -69739, - -69685, - -69632, - -69578, - -69525, - -69472, - -69418, - -69365, - -69312, - -69258, - -69205, - -69152, - -69099, - -69046, - -68993, - -68940, - -68887, - -68834, - -68781, - -68728, - -68676, - -68623, - -68570, - -68518, - -68465, - -68413, - -68360, - -68308, - -68255, - -68203, - -68151, - -68098, - -68046, - -67994, - -67942, - -67889, - -67837, - -67785, - -67733, - -67681, - -67629, - -67578, - -67526, - -67474, - -67422, - -67371, - -67319, - -67267, - -67216, - -67164, - -67113, - -67061, - -67010, - -66958, - -66907, - -66856, - -66804, - -66753, - -66702, - -66651, - -66600, - -66549, - -66498, - -66447, - -66396, - -66345, - -66294, - -66243, - -66192, - -66141, - -66091, - -66040, - -65989, - -65939, - -65888, - -65838, - -65787, - -65737, - -65686, - -65636, - -65586, - -65536, - -65485, - -65435, - -65385, - -65335, - -65285, - -65235, - -65185, - -65135, - -65085, - -65035, - -64985, - -64935, - -64885, - -64836, - -64786, - -64736, - -64687, - -64637, - -64587, - -64538, - -64488, - -64439, - -64389, - -64340, - -64291, - -64241, - -64192, - -64143, - -64094, - -64045, - -63996, - -63946, - -63897, - -63848, - -63799, - -63750, - -63702, - -63653, - -63604, - -63555, - -63506, - -63458, - -63409, - -63360, - -63312, - -63263, - -63215, - -63166, - -63118, - -63069, - -63021, - -62972, - -62924, - -62876, - -62828, - -62779, - -62731, - -62683, - -62635, - -62587, - -62539, - -62491, - -62443, - -62395, - -62347, - -62299, - -62251, - -62204, - -62156, - -62108, - -62060, - -62013, - -61965, - -61918, - -61870, - -61822, - -61775, - -61728, - -61680, - -61633, - -61585, - -61538, - -61491, - -61444, - -61396, - -61349, - -61302, - -61255, - -61208, - -61161, - -61114, - -61067, - -61020, - -60973, - -60926, - -60879, - -60833, - -60786, - -60739, - -60692, - -60646, - -60599, - -60552, - -60506, - -60459, - -60413, - -60366, - -60320, - -60273, - -60227, - -60181, - -60134, - -60088, - -60042, - -59996, - -59950, - -59903, - -59857, - -59811, - -59765, - -59719, - -59673, - -59627, - -59581, - -59535, - -59489, - -59444, - -59398, - -59352, - -59306, - -59261, - -59215, - -59169, - -59124, - -59078, - -59033, - -58987, - -58942, - -58896, - -58851, - -58805, - -58760, - -58715, - -58669, - -58624, - -58579, - -58534, - -58489, - -58443, - -58398, - -58353, - -58308, - -58263, - -58218, - -58173, - -58128, - -58083, - -58039, - -57994, - -57949, - -57904, - -57859, - -57815, - -57770, - -57725, - -57681, - -57636, - -57592, - -57547, - -57503, - -57458, - -57414, - -57369, - -57325, - -57281, - -57236, - -57192, - -57148, - -57104, - -57059, - -57015, - -56971, - -56927, - -56883, - -56839, - -56795, - -56751, - -56707, - -56663, - -56619, - -56575, - -56531, - -56487, - -56444, - -56400, - -56356, - -56312, - -56269, - -56225, - -56181, - -56138, - -56094, - -56051, - -56007, - -55964, - -55920, - -55877, - -55834, - -55790, - -55747, - -55704, - -55660, - -55617, - -55574, - -55531, - -55487, - -55444, - -55401, - -55358, - -55315, - -55272, - -55229, - -55186, - -55143, - -55100, - -55057, - -55015, - -54972, - -54929, - -54886, - -54843, - -54801, - -54758, - -54715, - -54673, - -54630, - -54587, - -54545, - -54502, - -54460, - -54417, - -54375, - -54333, - -54290, - -54248, - -54205, - -54163, - -54121, - -54079, - -54036, - -53994, - -53952, - -53910, - -53868, - -53826, - -53784, - -53741, - -53699, - -53657, - -53615, - -53574, - -53532, - -53490, - -53448, - -53406, - -53364, - -53322, - -53281, - -53239, - -53197, - -53156, - -53114, - -53072, - -53031, - -52989, - -52948, - -52906, - -52865, - -52823, - -52782, - -52740, - -52699, - -52657, - -52616, - -52575, - -52533, - -52492, - -52451, - -52410, - -52369, - -52327, - -52286, - -52245, - -52204, - -52163, - -52122, - -52081, - -52040, - -51999, - -51958, - -51917, - -51876, - -51835, - -51794, - -51754, - -51713, - -51672, - -51631, - -51591, - -51550, - -51509, - -51469, - -51428, - -51387, - -51347, - -51306, - -51266, - -51225, - -51185, - -51144, - -51104, - -51063, - -51023, - -50983, - -50942, - -50902, - -50862, - -50822, - -50781, - -50741, - -50701, - -50661, - -50621, - -50581, - -50540, - -50500, - -50460, - -50420, - -50380, - -50340, - -50300, - -50260, - -50221, - -50181, - -50141, - -50101, - -50061, - -50021, - -49982, - -49942, - -49902, - -49862, - -49823, - -49783, - -49744, - -49704, - -49664, - -49625, - -49585, - -49546, - -49506, - -49467, - -49427, - -49388, - -49349, - -49309, - -49270, - -49230, - -49191, - -49152, - -49113, - -49073, - -49034, - -48995, - -48956, - -48917, - -48878, - -48838, - -48799, - -48760, - -48721, - -48682, - -48643, - -48604, - -48565, - -48526, - -48488, - -48449, - -48410, - -48371, - -48332, - -48293, - -48255, - -48216, - -48177, - -48138, - -48100, - -48061, - -48022, - -47984, - -47945, - -47907, - -47868, - -47830, - -47791, - -47753, - -47714, - -47676, - -47637, - -47599, - -47560, - -47522, - -47484, - -47445, - -47407, - -47369, - -47331, - -47292, - -47254, - -47216, - -47178, - -47140, - -47102, - -47063, - -47025, - -46987, - -46949, - -46911, - -46873, - -46835, - -46797, - -46759, - -46721, - -46684, - -46646, - -46608, - -46570, - -46532, - -46494, - -46457, - -46419, - -46381, - -46343, - -46306, - -46268, - -46230, - -46193, - -46155, - -46118, - -46080, - -46042, - -46005, - -45967, - -45930, - -45892, - -45855, - -45818, - -45780, - -45743, - -45705, - -45668, - -45631, - -45593, - -45556, - -45519, - -45482, - -45444, - -45407, - -45370, - -45333, - -45296, - -45259, - -45221, - -45184, - -45147, - -45110, - -45073, - -45036, - -44999, - -44962, - -44925, - -44888, - -44851, - -44815, - -44778, - -44741, - -44704, - -44667, - -44630, - -44594, - -44557, - -44520, - -44483, - -44447, - -44410, - -44373, - -44337, - -44300, - -44263, - -44227, - -44190, - -44154, - -44117, - -44081, - -44044, - -44008, - -43971, - -43935, - -43898, - -43862, - -43826, - -43789, - -43753, - -43717, - -43680, - -43644, - -43608, - -43571, - -43535, - -43499, - -43463, - -43427, - -43390, - -43354, - -43318, - -43282, - -43246, - -43210, - -43174, - -43138, - -43102, - -43066, - -43030, - -42994, - -42958, - -42922, - -42886, - -42850, - -42814, - -42779, - -42743, - -42707, - -42671, - -42635, - -42600, - -42564, - -42528, - -42492, - -42457, - -42421, - -42385, - -42350, - -42314, - -42279, - -42243, - -42207, - -42172, - -42136, - -42101, - -42065, - -42030, - -41994, - -41959, - -41923, - -41888, - -41853, - -41817, - -41782, - -41747, - -41711, - -41676, - -41641, - -41605, - -41570, - -41535, - -41500, - -41465, - -41429, - -41394, - -41359, - -41324, - -41289, - -41254, - -41219, - -41184, - -41148, - -41113, - -41078, - -41043, - -41008, - -40973, - -40939, - -40904, - -40869, - -40834, - -40799, - -40764, - -40729, - -40694, - -40660, - -40625, - -40590, - -40555, - -40520, - -40486, - -40451, - -40416, - -40382, - -40347, - -40312, - -40278, - -40243, - -40208, - -40174, - -40139, - -40105, - -40070, - -40036, - -40001, - -39967, - -39932, - -39898, - -39863, - -39829, - -39794, - -39760, - -39726, - -39691, - -39657, - -39623, - -39588, - -39554, - -39520, - -39486, - -39451, - -39417, - -39383, - -39349, - -39314, - -39280, - -39246, - -39212, - -39178, - -39144, - -39110, - -39076, - -39042, - -39007, - -38973, - -38939, - -38905, - -38871, - -38837, - -38804, - -38770, - -38736, - -38702, - -38668, - -38634, - -38600, - -38566, - -38532, - -38499, - -38465, - -38431, - -38397, - -38364, - -38330, - -38296, - -38262, - -38229, - -38195, - -38161, - -38128, - -38094, - -38060, - -38027, - -37993, - -37960, - -37926, - -37893, - -37859, - -37826, - -37792, - -37759, - -37725, - -37692, - -37658, - -37625, - -37591, - -37558, - -37525, - -37491, - -37458, - -37425, - -37391, - -37358, - -37325, - -37291, - -37258, - -37225, - -37192, - -37158, - -37125, - -37092, - -37059, - -37026, - -36993, - -36959, - -36926, - -36893, - -36860, - -36827, - -36794, - -36761, - -36728, - -36695, - -36662, - -36629, - -36596, - -36563, - -36530, - -36497, - -36464, - -36431, - -36398, - -36365, - -36333, - -36300, - -36267, - -36234, - -36201, - -36168, - -36136, - -36103, - -36070, - -36037, - -36005, - -35972, - -35939, - -35907, - -35874, - -35841, - -35809, - -35776, - -35743, - -35711, - -35678, - -35646, - -35613, - -35580, - -35548, - -35515, - -35483, - -35450, - -35418, - -35385, - -35353, - -35321, - -35288, - -35256, - -35223, - -35191, - -35159, - -35126, - -35094, - -35062, - -35029, - -34997, - -34965, - -34932, - -34900, - -34868, - -34836, - -34803, - -34771, - -34739, - -34707, - -34675, - -34642, - -34610, - -34578, - -34546, - -34514, - -34482, - -34450, - -34418, - -34386, - -34354, - -34322, - -34289, - -34257, - -34225, - -34194, - -34162, - -34130, - -34098, - -34066, - -34034, - -34002, - -33970, - -33938, - -33906, - -33874, - -33843, - -33811, - -33779, - -33747, - -33715, - -33684, - -33652, - -33620, - -33588, - -33557, - -33525, - -33493, - -33461, - -33430, - -33398, - -33366, - -33335, - -33303, - -33272, - -33240, - -33208, - -33177, - -33145, - -33114, - -33082, - -33051, - -33019, - -32988, - -32956, - -32925, - -32893, - -32862, - -32830, - -32799, - -32767, - -32736, - -32705, - -32673, - -32642, - -32610, - -32579, - -32548, - -32516, - -32485, - -32454, - -32422, - -32391, - -32360, - -32329, - -32297, - -32266, - -32235, - -32204, - -32173, - -32141, - -32110, - -32079, - -32048, - -32017, - -31986, - -31955, - -31923, - -31892, - -31861, - -31830, - -31799, - -31768, - -31737, - -31706, - -31675, - -31644, - -31613, - -31582, - -31551, - -31520, - -31489, - -31458, - -31427, - -31396, - -31366, - -31335, - -31304, - -31273, - -31242, - -31211, - -31180, - -31150, - -31119, - -31088, - -31057, - -31026, - -30996, - -30965, - -30934, - -30904, - -30873, - -30842, - -30811, - -30781, - -30750, - -30719, - -30689, - -30658, - -30627, - -30597, - -30566, - -30536, - -30505, - -30474, - -30444, - -30413, - -30383, - -30352, - -30322, - -30291, - -30261, - -30230, - -30200, - -30169, - -30139, - -30108, - -30078, - -30048, - -30017, - -29987, - -29956, - -29926, - -29896, - -29865, - -29835, - -29805, - -29774, - -29744, - -29714, - -29683, - -29653, - -29623, - -29593, - -29562, - -29532, - -29502, - -29472, - -29441, - -29411, - -29381, - -29351, - -29321, - -29291, - -29260, - -29230, - -29200, - -29170, - -29140, - -29110, - -29080, - -29050, - -29020, - -28989, - -28959, - -28929, - -28899, - -28869, - -28839, - -28809, - -28779, - -28749, - -28719, - -28689, - -28660, - -28630, - -28600, - -28570, - -28540, - -28510, - -28480, - -28450, - -28420, - -28390, - -28361, - -28331, - -28301, - -28271, - -28241, - -28212, - -28182, - -28152, - -28122, - -28092, - -28063, - -28033, - -28003, - -27974, - -27944, - -27914, - -27884, - -27855, - -27825, - -27795, - -27766, - -27736, - -27707, - -27677, - -27647, - -27618, - -27588, - -27559, - -27529, - -27499, - -27470, - -27440, - -27411, - -27381, - -27352, - -27322, - -27293, - -27263, - -27234, - -27204, - -27175, - -27145, - -27116, - -27087, - -27057, - -27028, - -26998, - -26969, - -26940, - -26910, - -26881, - -26851, - -26822, - -26793, - -26763, - -26734, - -26705, - -26675, - -26646, - -26617, - -26588, - -26558, - -26529, - -26500, - -26471, - -26441, - -26412, - -26383, - -26354, - -26325, - -26295, - -26266, - -26237, - -26208, - -26179, - -26150, - -26120, - -26091, - -26062, - -26033, - -26004, - -25975, - -25946, - -25917, - -25888, - -25859, - -25830, - -25801, - -25772, - -25743, - -25714, - -25685, - -25656, - -25627, - -25598, - -25569, - -25540, - -25511, - -25482, - -25453, - -25424, - -25395, - -25366, - -25337, - -25308, - -25280, - -25251, - -25222, - -25193, - -25164, - -25135, - -25106, - -25078, - -25049, - -25020, - -24991, - -24962, - -24934, - -24905, - -24876, - -24847, - -24819, - -24790, - -24761, - -24732, - -24704, - -24675, - -24646, - -24618, - -24589, - -24560, - -24532, - -24503, - -24474, - -24446, - -24417, - -24389, - -24360, - -24331, - -24303, - -24274, - -24246, - -24217, - -24188, - -24160, - -24131, - -24103, - -24074, - -24046, - -24017, - -23989, - -23960, - -23932, - -23903, - -23875, - -23846, - -23818, - -23789, - -23761, - -23733, - -23704, - -23676, - -23647, - -23619, - -23591, - -23562, - -23534, - -23505, - -23477, - -23449, - -23420, - -23392, - -23364, - -23335, - -23307, - -23279, - -23250, - -23222, - -23194, - -23166, - -23137, - -23109, - -23081, - -23053, - -23024, - -22996, - -22968, - -22940, - -22911, - -22883, - -22855, - -22827, - -22799, - -22770, - -22742, - -22714, - -22686, - -22658, - -22630, - -22602, - -22573, - -22545, - -22517, - -22489, - -22461, - -22433, - -22405, - -22377, - -22349, - -22321, - -22293, - -22265, - -22237, - -22209, - -22181, - -22153, - -22125, - -22097, - -22069, - -22041, - -22013, - -21985, - -21957, - -21929, - -21901, - -21873, - -21845, - -21817, - -21789, - -21761, - -21733, - -21705, - -21678, - -21650, - -21622, - -21594, - -21566, - -21538, - -21510, - -21483, - -21455, - -21427, - -21399, - -21371, - -21343, - -21316, - -21288, - -21260, - -21232, - -21205, - -21177, - -21149, - -21121, - -21094, - -21066, - -21038, - -21010, - -20983, - -20955, - -20927, - -20900, - -20872, - -20844, - -20817, - -20789, - -20761, - -20734, - -20706, - -20678, - -20651, - -20623, - -20595, - -20568, - -20540, - -20513, - -20485, - -20457, - -20430, - -20402, - -20375, - -20347, - -20320, - -20292, - -20264, - -20237, - -20209, - -20182, - -20154, - -20127, - -20099, - -20072, - -20044, - -20017, - -19989, - -19962, - -19935, - -19907, - -19880, - -19852, - -19825, - -19797, - -19770, - -19742, - -19715, - -19688, - -19660, - -19633, - -19605, - -19578, - -19551, - -19523, - -19496, - -19469, - -19441, - -19414, - -19387, - -19359, - -19332, - -19305, - -19277, - -19250, - -19223, - -19195, - -19168, - -19141, - -19114, - -19086, - -19059, - -19032, - -19005, - -18977, - -18950, - -18923, - -18896, - -18868, - -18841, - -18814, - -18787, - -18760, - -18732, - -18705, - -18678, - -18651, - -18624, - -18597, - -18569, - -18542, - -18515, - -18488, - -18461, - -18434, - -18407, - -18380, - -18352, - -18325, - -18298, - -18271, - -18244, - -18217, - -18190, - -18163, - -18136, - -18109, - -18082, - -18055, - -18028, - -18001, - -17974, - -17946, - -17919, - -17892, - -17865, - -17838, - -17811, - -17784, - -17758, - -17731, - -17704, - -17677, - -17650, - -17623, - -17596, - -17569, - -17542, - -17515, - -17488, - -17461, - -17434, - -17407, - -17380, - -17353, - -17327, - -17300, - -17273, - -17246, - -17219, - -17192, - -17165, - -17138, - -17112, - -17085, - -17058, - -17031, - -17004, - -16977, - -16951, - -16924, - -16897, - -16870, - -16843, - -16817, - -16790, - -16763, - -16736, - -16710, - -16683, - -16656, - -16629, - -16603, - -16576, - -16549, - -16522, - -16496, - -16469, - -16442, - -16415, - -16389, - -16362, - -16335, - -16309, - -16282, - -16255, - -16229, - -16202, - -16175, - -16149, - -16122, - -16095, - -16069, - -16042, - -16015, - -15989, - -15962, - -15935, - -15909, - -15882, - -15856, - -15829, - -15802, - -15776, - -15749, - -15723, - -15696, - -15670, - -15643, - -15616, - -15590, - -15563, - -15537, - -15510, - -15484, - -15457, - -15431, - -15404, - -15378, - -15351, - -15325, - -15298, - -15272, - -15245, - -15219, - -15192, - -15166, - -15139, - -15113, - -15086, - -15060, - -15033, - -15007, - -14980, - -14954, - -14927, - -14901, - -14875, - -14848, - -14822, - -14795, - -14769, - -14743, - -14716, - -14690, - -14663, - -14637, - -14611, - -14584, - -14558, - -14531, - -14505, - -14479, - -14452, - -14426, - -14400, - -14373, - -14347, - -14321, - -14294, - -14268, - -14242, - -14215, - -14189, - -14163, - -14136, - -14110, - -14084, - -14057, - -14031, - -14005, - -13979, - -13952, - -13926, - -13900, - -13874, - -13847, - -13821, - -13795, - -13769, - -13742, - -13716, - -13690, - -13664, - -13637, - -13611, - -13585, - -13559, - -13533, - -13506, - -13480, - -13454, - -13428, - -13402, - -13375, - -13349, - -13323, - -13297, - -13271, - -13245, - -13218, - -13192, - -13166, - -13140, - -13114, - -13088, - -13062, - -13035, - -13009, - -12983, - -12957, - -12931, - -12905, - -12879, - -12853, - -12827, - -12800, - -12774, - -12748, - -12722, - -12696, - -12670, - -12644, - -12618, - -12592, - -12566, - -12540, - -12514, - -12488, - -12462, - -12436, - -12409, - -12383, - -12357, - -12331, - -12305, - -12279, - -12253, - -12227, - -12201, - -12175, - -12149, - -12123, - -12097, - -12071, - -12045, - -12019, - -11993, - -11967, - -11941, - -11916, - -11890, - -11864, - -11838, - -11812, - -11786, - -11760, - -11734, - -11708, - -11682, - -11656, - -11630, - -11604, - -11578, - -11552, - -11526, - -11501, - -11475, - -11449, - -11423, - -11397, - -11371, - -11345, - -11319, - -11293, - -11268, - -11242, - -11216, - -11190, - -11164, - -11138, - -11112, - -11086, - -11061, - -11035, - -11009, - -10983, - -10957, - -10931, - -10906, - -10880, - -10854, - -10828, - -10802, - -10777, - -10751, - -10725, - -10699, - -10673, - -10647, - -10622, - -10596, - -10570, - -10544, - -10519, - -10493, - -10467, - -10441, - -10415, - -10390, - -10364, - -10338, - -10312, - -10287, - -10261, - -10235, - -10209, - -10184, - -10158, - -10132, - -10106, - -10081, - -10055, - -10029, - -10004, - -9978, - -9952, - -9926, - -9901, - -9875, - -9849, - -9824, - -9798, - -9772, - -9747, - -9721, - -9695, - -9669, - -9644, - -9618, - -9592, - -9567, - -9541, - -9515, - -9490, - -9464, - -9438, - -9413, - -9387, - -9362, - -9336, - -9310, - -9285, - -9259, - -9233, - -9208, - -9182, - -9156, - -9131, - -9105, - -9080, - -9054, - -9028, - -9003, - -8977, - -8952, - -8926, - -8900, - -8875, - -8849, - -8824, - -8798, - -8772, - -8747, - -8721, - -8696, - -8670, - -8645, - -8619, - -8593, - -8568, - -8542, - -8517, - -8491, - -8466, - -8440, - -8414, - -8389, - -8363, - -8338, - -8312, - -8287, - -8261, - -8236, - -8210, - -8185, - -8159, - -8134, - -8108, - -8083, - -8057, - -8032, - -8006, - -7981, - -7955, - -7930, - -7904, - -7879, - -7853, - -7828, - -7802, - -7777, - -7751, - -7726, - -7700, - -7675, - -7649, - -7624, - -7598, - -7573, - -7547, - -7522, - -7496, - -7471, - -7445, - -7420, - -7395, - -7369, - -7344, - -7318, - -7293, - -7267, - -7242, - -7216, - -7191, - -7166, - -7140, - -7115, - -7089, - -7064, - -7038, - -7013, - -6988, - -6962, - -6937, - -6911, - -6886, - -6861, - -6835, - -6810, - -6784, - -6759, - -6733, - -6708, - -6683, - -6657, - -6632, - -6607, - -6581, - -6556, - -6530, - -6505, - -6480, - -6454, - -6429, - -6403, - -6378, - -6353, - -6327, - -6302, - -6277, - -6251, - -6226, - -6201, - -6175, - -6150, - -6124, - -6099, - -6074, - -6048, - -6023, - -5998, - -5972, - -5947, - -5922, - -5896, - -5871, - -5846, - -5820, - -5795, - -5770, - -5744, - -5719, - -5694, - -5668, - -5643, - -5618, - -5592, - -5567, - -5542, - -5517, - -5491, - -5466, - -5441, - -5415, - -5390, - -5365, - -5339, - -5314, - -5289, - -5264, - -5238, - -5213, - -5188, - -5162, - -5137, - -5112, - -5086, - -5061, - -5036, - -5011, - -4985, - -4960, - -4935, - -4910, - -4884, - -4859, - -4834, - -4808, - -4783, - -4758, - -4733, - -4707, - -4682, - -4657, - -4632, - -4606, - -4581, - -4556, - -4531, - -4505, - -4480, - -4455, - -4430, - -4404, - -4379, - -4354, - -4329, - -4303, - -4278, - -4253, - -4228, - -4202, - -4177, - -4152, - -4127, - -4101, - -4076, - -4051, - -4026, - -4001, - -3975, - -3950, - -3925, - -3900, - -3874, - -3849, - -3824, - -3799, - -3774, - -3748, - -3723, - -3698, - -3673, - -3648, - -3622, - -3597, - -3572, - -3547, - -3521, - -3496, - -3471, - -3446, - -3421, - -3395, - -3370, - -3345, - -3320, - -3295, - -3269, - -3244, - -3219, - -3194, - -3169, - -3144, - -3118, - -3093, - -3068, - -3043, - -3018, - -2992, - -2967, - -2942, - -2917, - -2892, - -2866, - -2841, - -2816, - -2791, - -2766, - -2741, - -2715, - -2690, - -2665, - -2640, - -2615, - -2590, - -2564, - -2539, - -2514, - -2489, - -2464, - -2439, - -2413, - -2388, - -2363, - -2338, - -2313, - -2288, - -2262, - -2237, - -2212, - -2187, - -2162, - -2137, - -2111, - -2086, - -2061, - -2036, - -2011, - -1986, - -1960, - -1935, - -1910, - -1885, - -1860, - -1835, - -1810, - -1784, - -1759, - -1734, - -1709, - -1684, - -1659, - -1633, - -1608, - -1583, - -1558, - -1533, - -1508, - -1483, - -1457, - -1432, - -1407, - -1382, - -1357, - -1332, - -1307, - -1281, - -1256, - -1231, - -1206, - -1181, - -1156, - -1131, - -1105, - -1080, - -1055, - -1030, - -1005, - -980, - -955, - -929, - -904, - -879, - -854, - -829, - -804, - -779, - -754, - -728, - -703, - -678, - -653, - -628, - -603, - -578, - -552, - -527, - -502, - -477, - -452, - -427, - -402, - -376, - -351, - -326, - -301, - -276, - -251, - -226, - -201, - -175, - -150, - -125, - -100, - -75, - -50, - -25, - }; -} diff --git a/components/darkforces/tfe/TFE_Jedi/Math/cosTable.h b/components/darkforces/tfe/TFE_Jedi/Math/cosTable.h deleted file mode 100644 index 1b4d00c6..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Math/cosTable.h +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include "fixedPoint.h" - -namespace TFE_Jedi -{ - extern const fixed16_16 s_cosTable[]; - extern const fixed16_16 s_tanTable[]; -} diff --git a/components/darkforces/tfe/TFE_Jedi/Math/fixedPoint.h b/components/darkforces/tfe/TFE_Jedi/Math/fixedPoint.h deleted file mode 100644 index a2d71f98..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Math/fixedPoint.h +++ /dev/null @@ -1,244 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include -#include - -// Set to 1 to assert on overflow, to ferret out precision issues with the Classic Renderer. -// Note, however, that overflow is expected when running at 320x200, so this should be 0 when making -// releases. -#define ASSERT_ON_OVERFLOW 0 - -namespace TFE_Jedi -{ - // Constants - #define HALF_16 0x8000 - #define ONE_16 0x10000 - #define ANGLE_MASK 0x3fff - #define ANGLE_MAX 0x4000 - - #define FRAC_BITS_16 16ll - #define FRAC_MASK_16 ((1 << FRAC_BITS_16) - 1) - #define FLOAT_SCALE_16 65536.0f - #define INV_FLOAT_SCALE_16 (1.0f/FLOAT_SCALE_16) - #define ANGLE_TO_FIXED_SCALE 4 - - // Fixed point type - typedef s32 fixed16_16; // 16.16 fixed point - typedef s32 angle14_32; // 14-bit angle in 32-bits (maps 360 degrees to 16384 angle units). - typedef s16 angle14_16; // 14-bit angle in 16-bits (maps 360 degrees to 16384 angle units). - - // Simple way of setting readable fixed point constants. - #define FIXED(x) ((x) << FRAC_BITS_16) - - // multiplies 2 fixed point numbers, the result is fixed point. - // 16.16 * 16.16 overflows 32 bit, so the calculation is done in 64 bit and then shifted back to 32 bit. -#if defined(TFE_ESPBOX) && defined(__mc68060__) -#ifdef CLIB_DEBUG_PROTOS_H - inline fixed16_16 mul16_fix(fixed16_16 x, fixed16_16 y) - { - return fixed16_16((s64(x) * s64(y)) >> FRAC_BITS_16); - } - inline fixed16_16 mul16_flt(fixed16_16 x, fixed16_16 y) - { - return fixed16_16((f64(x) * f64(y)) * (1.0 / 65536.0)); - } - inline fixed16_16 mul16_dbg(fixed16_16 x, fixed16_16 y, const char *func, int line) - { - fixed16_16 fix = mul16_fix(x,y); - fixed16_16 flt = mul16_flt(x,y); - if (fix != flt) - kprintf("%s:%ld %08x %08x\n", func, line, fix, flt); - return flt; - } - //#define mul16(x,y) mul16_dbg((x),(y),__FUNCTION__,__LINE__) - #define mul16(x,y) mul16_flt((x),(y)) -#else - inline fixed16_16 mul16_fix(fixed16_16 x, fixed16_16 y) - { - return fixed16_16((s64(x) * s64(y)) >> FRAC_BITS_16); - } - - inline fixed16_16 mul16(fixed16_16 x, fixed16_16 y) - { - /* - const int precision = 0; - const f64 x64 = f64(x >> precision); - const f64 y64 = f64(y >> precision); - - //return fixed16_16((x64 * y64) * (f64(1 << (precision * 2)) / 65536.0)); - return fixed16_16((x64 * y64) * (1.0 / 65536.0)) << (precision * 2); - */ - return fixed16_16((f64(x) * f64(y)) * (1.0 / 65536.0)); - } -#endif -#else - inline fixed16_16 mul16(fixed16_16 x, fixed16_16 y) - { - const s64 x64 = s64(x); - const s64 y64 = s64(y); - - // Overflow precision test. - #if ASSERT_ON_OVERFLOW == 1 - assert(((x64 * y64) >> FRAC_BITS_16) == fixed16_16((x64 * y64) >> FRAC_BITS_16)); - #endif - - return fixed16_16((x64 * y64) >> FRAC_BITS_16); - } -#endif - - // divides 2 fixed point numbers, the result is fixed point. - // 16.16 * FIXED_ONE overflows 32 bit, so the calculation is done in 64 bit but the result can be safely cast back to 32 bit. -#if defined(TFE_ESPBOX) && defined(__mc68060__) - inline fixed16_16 div16(fixed16_16 num, fixed16_16 denom) - { - const f64 num64 = f64(num); - const f64 den64 = f64(denom); - - return fixed16_16((num64 / den64) * 65536.0); - } -#else - inline fixed16_16 div16(fixed16_16 num, fixed16_16 denom) - { - const s64 num64 = s64(num); - const s64 den64 = s64(denom); - - // Overflow precision test. - #if ASSERT_ON_OVERFLOW == 1 - assert(((num64 << FRAC_BITS_16) / den64) == fixed16_16((num64 << FRAC_BITS_16) / den64)); - #endif - - return fixed16_16((num64 << FRAC_BITS_16) / den64); - } -#endif - - // truncates a 16.16 fixed point number, returns an int: x >> 16 - inline s32 floor16(fixed16_16 x) - { - return s32(x >> FRAC_BITS_16); - } - - inline fixed16_16 fract16(fixed16_16 x) - { - return x & FRAC_MASK_16; - } - - // computes a * b / c while keeping everything in 64 bits until the end. - inline fixed16_16 fusedMulDiv(fixed16_16 a, fixed16_16 b, fixed16_16 c) - { - const s64 a64 = s64(a); - const s64 b64 = s64(b); - const s64 c64 = s64(c); - s64 value = (a64 * b64) / c64; - - // Overflow precision test. - #if ASSERT_ON_OVERFLOW == 1 - assert(((a64 * b64) / c64) == fixed16_16((a64 * b64) / c64)); - #endif - - return fixed16_16(value); - } - - // rounds a 16.16 fixed point number, returns an int: (x + HALF_16) >> 16 - inline s32 round16(fixed16_16 x) - { - return s32((x + HALF_16) >> FRAC_BITS_16); - } - - // converts an integer to a fixed point number: x << 16 - inline fixed16_16 intToFixed16(s32 x) - { - return fixed16_16(x) << FRAC_BITS_16; - } - - inline fixed16_16 floatToFixed16(f32 x) - { - return fixed16_16(x * FLOAT_SCALE_16); - } - - inline f32 fixed16ToFloat(fixed16_16 x) - { - return f32(x) * INV_FLOAT_SCALE_16; - } - - inline angle14_16 floatToAngle(f32 angle) - { - return angle14_16(angle * 45.5111f); - } - - // Convert a floating point angle from [0, 2pi) to a fixed point value where 0 -> 0 and 2pi -> 16384 - // This isn't really the same as fixed16_16 but matches the original source. - inline fixed16_16 floatAngleToFixed(f32 angle) - { - return fixed16_16(16384.0f * angle / (2.0f*PI)); - } - - // Convert a floating point angle from [0, 2pi) to a fixed point value where 0 -> 0 and 2pi -> 16384 - // This isn't really the same as fixed16_16 but matches the original source. - inline fixed16_16 floatDegreesToFixed(f32 angle) - { - return fixed16_16(16384.0f * angle / 360.0f); - } - - inline s32 fixed16to12(fixed16_16 x) - { - return s32(x >> 4); - } - -#ifdef TFE_ESPBOX -/* -MIT License - -Copyright (c) 2019 Christophe Meessen - -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. -*/ - inline fixed16_16 fixedSqrt(fixed16_16 x) - { - u32 t, q, b, r; - r = x; - b = 0x40000000; - q = 0; - while (b > 0x40) - { - t = q + b; - if (r >= t) - { - r -= t; - q = t + b; // equivalent to q += 2*b - } - r <<= 1; - b >>= 1; - } - q >>= 8; - return q; - } -#else - // I cheat here with the fixedSqrt and just do a regular square root... - // TODO: Replace with 15-bit table-based sqrt? -- Also probably not necessary. - inline fixed16_16 fixedSqrt(fixed16_16 x) - { - const f32 fx = fixed16ToFloat(x); - return floatToFixed16(sqrtf(fx)); - } -#endif -} diff --git a/components/darkforces/tfe/TFE_Jedi/Memory/allocator.cpp b/components/darkforces/tfe/TFE_Jedi/Memory/allocator.cpp deleted file mode 100644 index 32d0ff6c..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Memory/allocator.cpp +++ /dev/null @@ -1,378 +0,0 @@ -#include "allocator.h" -#include -#include -#include -#include - -struct AllocHeader -{ - AllocHeader* prev; - AllocHeader* next; -}; - -struct Allocator -{ - Allocator* self; - AllocHeader* head; - AllocHeader* tail; - AllocHeader* iterPrev; - AllocHeader* iter; - MemoryRegion* region; - s32 size; - s32 refCount; - - // TFE - AllocHeader* iterSave; - AllocHeader* iterPrevSave; -}; - -namespace TFE_Jedi -{ - // Note that the invalid pointer value is chosen such that - // InvalidPointer + sizeof(AllocHeader) = 0 = null - // This is hardcoded in DF, here I calculate it based off of size_t so that it works for both 32-bit and 64-bit code. - static const size_t c_invalidPtr = (~size_t(0)) - sizeof(AllocHeader) + 1; - #define ALLOC_INVALID_PTR ((AllocHeader*)c_invalidPtr) - #define MAX_ALLOC_SIZE (8*1024*1024) // 8MB - - // Create and free an allocator. - Allocator* allocator_create(s32 allocSize, MemoryRegion* region) - { - if (allocSize > MAX_ALLOC_SIZE || allocSize <= 0) - { - TFE_System::logWrite(LOG_ERROR, "Allocator", "Invalid allocator size: %d", allocSize); - assert(0); - return nullptr; - } - region = region ? region : s_levelRegion; // If a null region is passed in, assume we want the level region. - Allocator* res = (Allocator*)TFE_Memory::region_alloc(region, sizeof(Allocator)); - if (!res) - { - TFE_System::logWrite(LOG_ERROR, "Allocator", "Could not allocate Allocator."); - assert(0); - return nullptr; - } - res->self = res; - res->region = region; - - // the original code used special bit patterns to represent invalid pointers. - res->head = ALLOC_INVALID_PTR; - res->tail = ALLOC_INVALID_PTR; - res->iterPrev = ALLOC_INVALID_PTR; - res->iter = ALLOC_INVALID_PTR; - res->size = allocSize + sizeof(AllocHeader); - res->refCount = 0; - - return res; - } - - void allocator_free(Allocator* alloc) - { - if (!alloc) { return; } - - void* item = allocator_getHead(alloc); - while (item) - { - allocator_deleteItem(alloc, item); - item = allocator_getNext(alloc); - } - - alloc->self = (Allocator*)ALLOC_INVALID_PTR; - TFE_Memory::region_free(alloc->region, alloc); - } - - bool allocator_validate(Allocator* alloc) - { - return alloc->self == alloc; - } - - // Allocate and free individual items. - void* allocator_newItem(Allocator* alloc) - { - if (!alloc) { return nullptr; } - - AllocHeader* header = (AllocHeader*)TFE_Memory::region_alloc(alloc->region, alloc->size); - if (!header) - { - TFE_System::logWrite(LOG_ERROR, "Allocator", "allocator_newItem - cannot allocate header of size %d", alloc->size); - assert(0); - return nullptr; - } - - header->next = ALLOC_INVALID_PTR; - header->prev = alloc->tail; - - if (alloc->tail != ALLOC_INVALID_PTR) - { - alloc->tail->next = header; - } - alloc->tail = header; - - if (alloc->head == ALLOC_INVALID_PTR) - { - alloc->head = header; - } - - return ((u8*)header + sizeof(AllocHeader)); - } - - void allocator_deleteItem(Allocator* alloc, void* item) - { - if (!alloc) { return; } - - AllocHeader* header = (AllocHeader*)((u8*)item - sizeof(AllocHeader)); - if (header == ALLOC_INVALID_PTR) { return; } - - AllocHeader* prev = header->prev; - AllocHeader* next = header->next; - - if (prev == ALLOC_INVALID_PTR) { alloc->head = next; } - else { prev->next = next; } - - if (next == ALLOC_INVALID_PTR) { alloc->tail = prev; } - else { next->prev = prev; } - - if (alloc->iter == header) - { - alloc->iter = header->prev; - } - if (alloc->iterPrev == header) - { - alloc->iterPrev = header->next; - } - - TFE_Memory::region_free(alloc->region, header); - } - - // Random access. - s32 allocator_getCount(Allocator* alloc) - { - if (!alloc) { return 0; } - - s32 count = 0; - AllocHeader* header = alloc->head; - while (header != ALLOC_INVALID_PTR) - { - count++; - header = header->next; - } - return count; - } - - s32 allocator_getCurPos(Allocator* alloc) - { - if (!alloc) { return -1; } - - s32 index = 0; - AllocHeader* iter = alloc->iter; - AllocHeader* header = alloc->head; - while (header != ALLOC_INVALID_PTR) - { - if (header == iter) - { - return index; - } - index++; - header = header->next; - } - return -1; - } - - void allocator_setPos(Allocator* alloc, s32 pos) - { - s32 index = 0; - AllocHeader* header = alloc->head; - alloc->iter = ALLOC_INVALID_PTR; - while (header != ALLOC_INVALID_PTR) - { - if (index == pos) - { - alloc->iter = header; - break; - } - index++; - header = header->next; - } - } - - s32 allocator_getPrevPos(Allocator* alloc) - { - if (!alloc) { return -1; } - - s32 index = 0; - AllocHeader* iterPrev = alloc->iterPrev; - AllocHeader* header = alloc->head; - while (header != ALLOC_INVALID_PTR) - { - if (header == iterPrev) - { - return index; - } - index++; - header = header->next; - } - return -1; - } - - void allocator_setPrevPos(Allocator* alloc, s32 pos) - { - s32 index = 0; - AllocHeader* header = alloc->head; - while (header != ALLOC_INVALID_PTR) - { - if (index == pos) - { - alloc->iterPrev = header; - break; - } - index++; - header = header->next; - } - } - - s32 allocator_getIndex(Allocator* alloc, void* item) - { - if (!item) { return -1; } - - AllocHeader* header = alloc->head; - s32 index = 0; - while (header != ALLOC_INVALID_PTR) - { - if ((u8*)item == (u8*)header + sizeof(AllocHeader)) - { - return index; - } - index++; - header = header->next; - } - return -1; - } - - void* allocator_getByIndex(Allocator* alloc, s32 index) - { - if (!alloc) { return nullptr; } - - AllocHeader* header = alloc->head; - while (index > 0 && header != ALLOC_INVALID_PTR) - { - index--; - header = header->next; - } - - alloc->iterPrev = header; - alloc->iter = header; - return (u8*)header + sizeof(AllocHeader); - } - - // Iteration - void allocator_saveIter(Allocator* alloc) - { - if (!alloc) { return; } - alloc->iterPrevSave = alloc->iterPrev; - alloc->iterSave = alloc->iter; - } - - void allocator_restoreIter(Allocator* alloc) - { - if (!alloc) { return; } - alloc->iterPrev = alloc->iterPrevSave; - alloc->iter = alloc->iterSave; - } - - void* allocator_getIter(Allocator* alloc) - { - return (u8*)alloc->iter + sizeof(AllocHeader); - } - - void allocator_setIter(Allocator* alloc, void* iter) - { - alloc->iter = (AllocHeader*)((u8*)iter - sizeof(AllocHeader)); - } - - void* allocator_getHead(Allocator* alloc) - { - if (!alloc) { return nullptr; } - - alloc->iterPrev = alloc->head; - alloc->iter = alloc->head; - return (u8*)alloc->iter + sizeof(AllocHeader); - } - - void* allocator_getHead_noIterUpdate(Allocator* alloc) - { - if (!alloc) { return nullptr; } - return (u8*)alloc->head + sizeof(AllocHeader); - } - - void* allocator_getTail(Allocator* alloc) - { - if (!alloc) { return nullptr; } - - alloc->iterPrev = alloc->tail; - alloc->iter = alloc->tail; - - return (u8*)alloc->tail + sizeof(AllocHeader); - } - - void* allocator_getTail_noIterUpdate(Allocator* alloc) - { - if (!alloc) { return nullptr; } - return (u8*)alloc->tail + sizeof(AllocHeader); - } - - void* allocator_getNext(Allocator* alloc) - { - if (!alloc) { return nullptr; } - - AllocHeader* iter = alloc->iter; - if (iter != ALLOC_INVALID_PTR) - { - alloc->iter = iter->next; - alloc->iterPrev = iter->next; - return (u8*)iter->next + sizeof(AllocHeader); - } - - iter = alloc->head; - if (iter == ALLOC_INVALID_PTR) { return nullptr; } - - alloc->iter = iter; - alloc->iterPrev = iter; - return (u8*)iter + sizeof(AllocHeader); - } - - void* allocator_getPrev(Allocator* alloc) - { - if (!alloc) { return nullptr; } - - AllocHeader* iterPrev = alloc->iterPrev; - if (iterPrev != ALLOC_INVALID_PTR) - { - AllocHeader* prev = iterPrev->prev; - alloc->iter = iterPrev->prev; - alloc->iterPrev = iterPrev->prev; - return (u8*)iterPrev->prev + sizeof(AllocHeader); - } - - alloc->iter = alloc->tail; - alloc->iterPrev = alloc->tail; - return (u8*)alloc->tail + sizeof(AllocHeader); - } - - // Ref counting. - void allocator_addRef(Allocator* alloc) - { - if (!alloc) { return; } - alloc->refCount++; - } - - void allocator_release(Allocator* alloc) - { - if (!alloc) { return; } - alloc->refCount--; - } - - s32 allocator_getRefCount(Allocator* alloc) - { - return alloc ? alloc->refCount : 0; - } -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Memory/allocator.h b/components/darkforces/tfe/TFE_Jedi/Memory/allocator.h deleted file mode 100644 index 9f40843c..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Memory/allocator.h +++ /dev/null @@ -1,46 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Allocator API as found in the Jedi Engine -////////////////////////////////////////////////////////////////////// -#include -#include - -struct Allocator; - -namespace TFE_Jedi -{ - // Create and free an allocator. - Allocator* allocator_create(s32 allocSize, MemoryRegion* region = nullptr); - void allocator_free(Allocator* alloc); - bool allocator_validate(Allocator* alloc); - - // Allocate and free individual items. - void* allocator_newItem(Allocator* alloc); - void allocator_deleteItem(Allocator* alloc, void* item); - - // Random access. - s32 allocator_getCount(Allocator* alloc); - s32 allocator_getIndex(Allocator* alloc, void* item); - void* allocator_getByIndex(Allocator* alloc, s32 index); - s32 allocator_getCurPos(Allocator* alloc); - s32 allocator_getPrevPos(Allocator* alloc); - void allocator_setPos(Allocator* alloc, s32 pos); - void allocator_setPrevPos(Allocator* alloc, s32 pos); - - // Iteration - void* allocator_getIter(Allocator* alloc); - void* allocator_getHead(Allocator* alloc); - void* allocator_getTail(Allocator* alloc); - void* allocator_getHead_noIterUpdate(Allocator* alloc); - void* allocator_getTail_noIterUpdate(Allocator* alloc); - void* allocator_getNext(Allocator* alloc); - void* allocator_getPrev(Allocator* alloc); - void allocator_saveIter(Allocator* alloc); - void allocator_restoreIter(Allocator* alloc); - void allocator_setIter(Allocator* alloc, void* iter); - - // Ref counting. - void allocator_addRef(Allocator* alloc); - void allocator_release(Allocator* alloc); - s32 allocator_getRefCount(Allocator* alloc); -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Memory/list.cpp b/components/darkforces/tfe/TFE_Jedi/Memory/list.cpp deleted file mode 100644 index 1d5bf0db..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Memory/list.cpp +++ /dev/null @@ -1,142 +0,0 @@ -#include - -#include "list.h" -#include - -namespace TFE_Jedi -{ - void initializeList(List* list); - - u8* list_getNext(List* list) - { - u8* iter = list->iter; - u8* end = list->end; - s32 step = list->step; - - // Search for the next item where the first byte is non-zero. - while (iter < end) - { - iter += step; - if (*iter) - { - list->iter = iter; - return iter + 1; - } - } - - return nullptr; - } - - u8* list_getHead(List* list) - { - u8* head = list->head; - list->iter = list->head; - // If the current entry is not filled, get the next one. - if (!(head[0] & 1)) - { - return list_getNext(list); - } - return head + 1; - } - - void list_removeItem(List* list, void* item) - { - if (!list || !item) { return; } - - u8* data = (u8*)item - 1; - // Already freed. - if (!data[0]) { return; } - - // Free the item and reduce the count. - data[0] = 0; - list->count--; - - // The original method of finding the next free won't really work today, so... - u8* nextFree = list->head; - for (s32 i = 0; i < list->capacity; i++, nextFree += list->step) - { - if (!nextFree[0]) - { - list->nextFree = nextFree; - break; - } - } - } - - u8* list_addItem(List* list) - { - u8* nextFree = list->nextFree; - if (nextFree) - { - u8* newItem = nextFree; - // By marking the first byte with 1, we signal that it is now used. - newItem[0] = 1; - - list->count++; - if (list->count >= list->capacity) - { - // This is the last available free item, so mark the nextFree as null. - nextFree = nullptr; - } - else - { - // Keep stepping forward until another free slot is found. - while (*nextFree) - { - nextFree += list->step; - } - } - - list->nextFree = nextFree; - return newItem + 1; - } - - // TODO(Core Game Loop Release) - // Handle Error - return nullptr; - } - - List* list_allocate(s32 elemSize, s32 capacity) - { - elemSize++; - s32 size = elemSize * capacity + sizeof(List); - List* list = (List*)game_alloc(size); - u8* end = (u8*)list + size; - list->end = end - elemSize; - list->self = list; - - u8* start = (u8*)list + sizeof(List); - list->head = start; - list->step = elemSize; - list->capacity = capacity; - - initializeList(list); - return list; - } - - void list_clear(List* list) - { - if (!list) { return; } - - s32 size = list->step * list->capacity + sizeof(List); - u8* end = (u8*)list + size; - list->end = end - list->step; - list->self = list; - - u8* start = (u8*)list + sizeof(List); - list->head = start; - - initializeList(list); - } - - void initializeList(List* list) - { - list->iter = list->head; - list->nextFree = list->head; - list->count = 0; - - s32 size = s32(list->end - list->head + list->step); - memset(list->head, 0, size); - } - -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Memory/list.h b/components/darkforces/tfe/TFE_Jedi/Memory/list.h deleted file mode 100644 index c27d300d..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Memory/list.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// List API as found in the Jedi Engine -////////////////////////////////////////////////////////////////////// -#include - -struct List -{ - List* self; - - u8* head; - u8* end; - u8* iter; - s32 step; - u8* nextFree; - s32 count; - s32 capacity; -}; - -namespace TFE_Jedi -{ - u8* list_getNext(List* list); - u8* list_getHead(List* list); - u8* list_addItem(List* list); - void list_removeItem(List* list, void* item); - List* list_allocate(s32 elemSize, s32 capacity); - void list_clear(List* list); -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rclassicFixed.cpp b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rclassicFixed.cpp deleted file mode 100644 index 12d09aa3..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rclassicFixed.cpp +++ /dev/null @@ -1,425 +0,0 @@ -#include - -#include -#include -#include -#include -#include -#include "rclassicFixedSharedState.h" -#include "rlightingFixed.h" -#include "rflatFixed.h" -#include "../redgePair.h" -#include "rsectorFixed.h" -#include "../rcommon.h" -#ifdef TFE_ESPBOX -#define s_width (320) -#define s_height (200) -#endif - -namespace TFE_Jedi -{ - -namespace RClassic_Fixed -{ - static JBool s_fullDetail = JTRUE; - static fixed16_16 s_viewWidth; - static fixed16_16 s_viewHeight; - static fixed16_16 s_minScreenX; - static fixed16_16 s_maxScreenX; - static fixed16_16 s_screenWidthFract; - static fixed16_16 s_oneOverWidthFract; - static fixed16_16 s_worldX; - static fixed16_16 s_worldY; - static fixed16_16 s_worldZ; - static fixed16_16 s_xOffset; - static fixed16_16 s_zOffset; - static angle14_32 s_worldYaw; - static angle14_32 s_maxPitch = 8192; - static s32 s_screenHeight; - static s32 s_pixelCount; - static s32 s_visionEffect; - static u32 s_pixelMask; - static RSector* s_sector; - - void setVisionEffect(s32 effect) - { - s_visionEffect = effect; - } - - void transformPointByCamera(vec3_fixed* worldPoint, vec3_fixed* viewPoint) - { - viewPoint->x = mul16(worldPoint->x, s_rcfState.cosYaw) + mul16(worldPoint->z, s_rcfState.sinYaw) + s_rcfState.cameraTrans.x; - viewPoint->y = worldPoint->y - s_rcfState.eyeHeight; - viewPoint->z = mul16(worldPoint->z, s_rcfState.cosYaw) + mul16(worldPoint->x, s_rcfState.negSinYaw) + s_rcfState.cameraTrans.z; - } - - void setCameraWorldPos(fixed16_16 x, fixed16_16 z, fixed16_16 eyeHeight) - { - s_worldX = x; - s_worldZ = z; - s_worldY = eyeHeight; - } - - void computeCameraTransform(RSector* sector, angle14_32 pitch, angle14_32 yaw, fixed16_16 camX, fixed16_16 camY, fixed16_16 camZ) - { - s_rcfState.cameraPos.x = camX; - s_rcfState.cameraPos.z = camZ; - s_rcfState.eyeHeight = camY; - - s_sector = sector; - - s_rcfState.cameraYaw = yaw; - s_rcfState.cameraPitch = pitch; - - s_xOffset = -camX; - s_zOffset = -camZ; - sinCosFixed(-yaw, &s_rcfState.sinYaw, &s_rcfState.cosYaw); - - s_rcfState.negSinYaw = -s_rcfState.sinYaw; - if (s_maxPitch != s_rcfState.cameraPitch) - { - fixed16_16 pitchOffset = mul16(tanFixed(pitch), s_rcfState.halfWidth); - s_rcfState.projOffsetY = s_rcfState.projOffsetYBase + pitchOffset; - s_screenYMidFix = s_screenYMidBase + floor16(pitchOffset); - - // yMax*0.5 / halfWidth; ~pixel Aspect -#ifdef TFE_ESPBOX - /* - s_rcfState.yPlaneBot = ((s_viewHeight >> 1) - pitchOffset / floor16(s_rcfState.halfWidth)); - s_rcfState.yPlaneTop = -((s_viewHeight >> 1) + pitchOffset / floor16(s_rcfState.halfWidth)); - */ - const fixed16_16 rcpHalfWidth = ONE_16 / floor16(s_rcfState.halfWidth); - s_rcfState.yPlaneBot = mul16((s_viewHeight >> 1) - pitchOffset, rcpHalfWidth); - s_rcfState.yPlaneTop = -mul16((s_viewHeight >> 1) + pitchOffset, rcpHalfWidth); -#else - s_rcfState.yPlaneBot = div16((s_viewHeight >> 1) - pitchOffset, s_rcfState.halfWidth); - s_rcfState.yPlaneTop = -div16((s_viewHeight >> 1) + pitchOffset, s_rcfState.halfWidth); -#endif - } - - s_rcfState.cameraTrans.z = mul16(s_zOffset, s_rcfState.cosYaw) + mul16(s_xOffset, s_rcfState.negSinYaw); - s_rcfState.cameraTrans.x = mul16(s_xOffset, s_rcfState.cosYaw) + mul16(s_zOffset, s_rcfState.sinYaw); - setCameraWorldPos(s_rcfState.cameraPos.x, s_rcfState.cameraPos.z, s_rcfState.eyeHeight); - s_worldYaw = s_rcfState.cameraYaw; - - // Camera Transform: - s_rcfState.cameraMtx[0] = s_rcfState.cosYaw; - s_rcfState.cameraMtx[2] = s_rcfState.negSinYaw; - s_rcfState.cameraMtx[6] = s_rcfState.sinYaw; - s_rcfState.cameraMtx[8] = s_rcfState.cosYaw; - } - - void computeSkyOffsets() - { - fixed16_16 parallax[2]; - TFE_Jedi::getSkyParallax(¶llax[0], ¶llax[1]); - - // angles range from -16384 to 16383; multiply by 4 to convert to [-1, 1) range. - s_rcfState.skyYawOffset = -mul16(s_rcfState.cameraYaw * ANGLE_TO_FIXED_SCALE, parallax[0]); - s_rcfState.skyPitchOffset = -mul16(s_rcfState.cameraPitch * ANGLE_TO_FIXED_SCALE, parallax[1]); - } - - void setupScreenParameters(s32 w, s32 h, s32 x0, s32 y0) - { - s_viewWidth = intToFixed16(w); - s_viewHeight = intToFixed16(h); - s_screenWidth = w; - s_screenHeight = h; - - s_minScreenX_Pixels = x0; - s_maxScreenX_Pixels = x0 + w - 1; - s_minScreenX = intToFixed16(s_minScreenX_Pixels); - s_maxScreenX = intToFixed16(s_maxScreenX_Pixels); - - s_minScreenY = y0; - s_maxScreenY = y0 + h - 1; - s_rcfState.windowMinY = intToFixed16(y0); - s_rcfState.windowMaxY = intToFixed16(y0 + h - 1); - - s_fullDetail = JTRUE; - s_pixelCount = w * h; - } - - void setupProjectionParameters(fixed16_16 halfWidthFixed, s32 xc, s32 yc) - { - s_rcfState.halfWidth = halfWidthFixed; - s_screenXMid = xc; - s_screenYMidFix = yc; - s_screenYMidBase = yc; - - s_rcfState.projOffsetX = intToFixed16(xc); - s_rcfState.projOffsetY = intToFixed16(yc); - s_rcfState.projOffsetYBase = s_rcfState.projOffsetY; - - s_windowX0 = s_minScreenX_Pixels; - s_windowX1 = s_maxScreenX_Pixels; - - s_rcfState.oneOverHalfWidth = div16(ONE_16, halfWidthFixed); - - // TFE -#ifdef TFE_ESPBOX - s_rcfState.focalLength = floor16(s_rcfState.halfWidth); - s_rcfState.focalLenAspect = floor16(s_rcfState.halfWidth); -#else - s_rcfState.focalLength = s_rcfState.halfWidth; - s_rcfState.focalLenAspect = s_rcfState.halfWidth; -#endif - } - - void setWidthFraction(fixed16_16 widthFract) - { - s_screenWidthFract = widthFract; - s_oneOverWidthFract = div16(ONE_16, widthFract); - } - - void buildRcpYTable() - { - s32 yMid = s_screenYMidFix; - for (s32 yOffset = -400; yOffset < 400; yOffset++) - { - if (yOffset == yMid) - { - s_rcfState.rcpY[yMid + 400] = ONE_16; - } - else - { - s_rcfState.rcpY[yOffset + 400] = div16(ONE_16, intToFixed16(yOffset - yMid)); - } - } - } - - void resetState() - { - s_rcfState.depth1d_all = nullptr; - s_rcfState.skyTable = nullptr; - s_rcfState.column_Z_Over_X = nullptr; - s_rcfState.column_X_Over_Z = nullptr; - s_rcfState.rcpY = nullptr; - - // Shared state - s_flatCount = 0; - s_columnTop = nullptr; - s_columnBot = nullptr; - s_windowTop_all = nullptr; - s_windowBot_all = nullptr; - } - - void buildProjectionTables(s32 xc, s32 yc, s32 w, s32 h) - { - s32 halfHeight = h >> 1; - s32 halfWidth = w >> 1; - - setupScreenParameters(w, h, xc - halfWidth, yc - halfHeight); - setupProjectionParameters(intToFixed16(halfWidth), xc, yc); - - s32 widthFract = div16(intToFixed16(w), FIXED(320)); - setWidthFraction(widthFract); - - EdgePairFixed* flatEdge = &s_rcfState.flatEdgeList[s_flatCount]; - s_rcfState.flatEdge = flatEdge; - flat_addEdges(s_screenWidth, s_minScreenX_Pixels, 0, s_rcfState.windowMaxY, 0, s_rcfState.windowMinY); - - s_columnTop = (s32*)game_realloc(s_columnTop, s_width * sizeof(s32)); - s_columnBot = (s32*)game_realloc(s_columnBot, s_width * sizeof(s32)); - s_rcfState.depth1d_all = (fixed16_16*)game_realloc(s_rcfState.depth1d_all, s_width * sizeof(fixed16_16) * (MAX_ADJOIN_DEPTH + 1)); - s_windowTop_all = (s32*)game_realloc(s_windowTop_all, s_width * sizeof(s32) * (MAX_ADJOIN_DEPTH + 1)); - s_windowBot_all = (s32*)game_realloc(s_windowBot_all, s_width * sizeof(s32) * (MAX_ADJOIN_DEPTH + 1)); - - memset(s_windowTop_all, s_minScreenY, 320); - memset(s_windowBot_all, s_maxScreenY, 320); - - // Build tables - s_rcfState.column_Z_Over_X = (fixed16_16*)game_realloc(s_rcfState.column_Z_Over_X, s_width * sizeof(fixed16_16)); - s_rcfState.column_X_Over_Z = (fixed16_16*)game_realloc(s_rcfState.column_X_Over_Z, s_width * sizeof(fixed16_16)); - s_rcfState.skyTable = (fixed16_16*)game_realloc(s_rcfState.skyTable, (s_width + 1) * sizeof(fixed16_16)); - - // Here we assume a 90 degree field of view, this forms a frustum (not drawn to scale): - // W = width of plane in pixels - // *---*---* - // \ Z| / Z = depth of plane - // \ | / - // \|/ - // * - // Where the distance to the screen where the half width is 0.5*W is also 0.5*W - // i.e. Z = 0.5*W. - // Z/X in screenspace = W / (x_in_pixels - 0.5*width_in_pixels) - s32 xMid = s_screenXMid; - for (s32 i = 0, x = 0; x < 320; x++, i++) - { - fixed16_16 xPos = intToFixed16(x - xMid); - s_rcfState.column_Z_Over_X[i] = (xMid != x) ? div16(s_rcfState.halfWidth, xPos) : s_rcfState.halfWidth; - } - - for (s32 i = 0, x = 0; x < 320; i++, x++) - { - if (x != xMid) - { - fixed16_16 xPos = intToFixed16(x - xMid); - s_rcfState.column_X_Over_Z[i] = div16(xPos, s_rcfState.halfWidth); - } - else - { - s_rcfState.column_X_Over_Z[i] = 0; - } - } - - s_rcfState.rcpY = (fixed16_16*)game_realloc(s_rcfState.rcpY, 4 * s_height * sizeof(fixed16_16)); - buildRcpYTable(); - } - - void computeSkyTable() - { - fixed16_16 parallax0, parallax1; - TFE_Jedi::getSkyParallax(¶llax0, ¶llax1); - - s32 xMid = s_screenXMid; - s_rcfState.skyTable[0] = 0; - for (s32 i = 0, x = 0; x < 320; i++, x++) - { - s32 xPos = x - xMid; - // This is atanf(float(x) / 160.0f) / (2pi) - f32 angleFractF = atanf(f32(xPos) / 160.0f) * 2607.595f; - fixed16_16 angleFract = fixed16_16(angleFractF) << 2; - - // This intentionally overflows when x = 0 and becomes 0... - s_rcfState.skyTable[1 + i] = mul16(angleFract, parallax0); - } - } - - void setIdentityMatrix(s32* mtx) - { - mtx[0] = ONE_16; - mtx[3] = 0; - mtx[6] = 0; - - mtx[1] = 0; - mtx[4] = ONE_16; - mtx[7] = 0; - - mtx[2] = 0; - mtx[5] = 0; - mtx[8] = ONE_16; - } - - void createLight(CameraLight* light, fixed16_16 x, fixed16_16 y, fixed16_16 z, fixed16_16 brightness) - { - vec3_fixed* dirWS = &light->lightWS; - dirWS->x = x; - dirWS->y = y; - dirWS->z = z; - light->brightness = brightness; - normalizeVec3(dirWS, dirWS); - } - - void changeResolution(s32 width, s32 height) - { -#ifndef TFE_ESPBOX - assert(width == 320 && height == 200); - s_width = width; - s_height = height; - s_flatCount = 0; -#endif - - buildProjectionTables(width >> 1, height >> 1, s_width, s_height - 2); - - fixed16_16 prevParallax0, prevParallax1; - TFE_Jedi::getSkyParallax(&prevParallax0, &prevParallax1); - - TFE_Jedi::setSkyParallax(FIXED(1024), FIXED(1024)); - computeSkyTable(); - - TFE_Jedi::setSkyParallax(prevParallax0, prevParallax1); - - s_lightCount = 0; - - createLight(&s_cameraLight[0], 0, 0, ONE_16, ONE_16); - s_lightCount++; - - createLight(&s_cameraLight[1], 0, ONE_16, 0, ONE_16); - s_lightCount++; - - createLight(&s_cameraLight[2], ONE_16, 0, 0, ONE_16); - s_lightCount++; - } - - void setupInitCameraAndLights() - { -#ifndef TFE_ESPBOX - s_width = 320; - s_height = 200; -#endif - - buildProjectionTables(160, 100, 320, 198); - TFE_Jedi::setSkyParallax(FIXED(1024), FIXED(1024)); - computeSkyTable(); - - setIdentityMatrix(s_rcfState.cameraMtx); - computeCameraTransform(nullptr, 0, 0, 0, 0, 0); - - s_lightCount = 0; - - createLight(&s_cameraLight[0], 0, 0, ONE_16, ONE_16); - s_lightCount++; - - createLight(&s_cameraLight[1], 0, ONE_16, 0, ONE_16); - s_lightCount++; - - createLight(&s_cameraLight[2], ONE_16, 0, 0, ONE_16); - s_lightCount++; - - s_colorMap = nullptr; - s_lightSourceRamp = nullptr; - s_enableFlatShading = JFALSE; - s_cameraLightSource = JFALSE; - s_pixelMask = 0xffffffff; - s_visionEffect = 0; - } - - // 2D - void textureBlitColumn(const u8* image, u8* outBuffer, s32 yPixelCount) - { - s32 end = yPixelCount - 1; - s32 offset = end * s_width; - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - outBuffer[offset] = image[i]; - } - } - - void blitTextureToScreen(TextureData* texture, s32 x0, s32 y0) - { - s32 x1 = x0 + texture->width - 1; - s32 y1 = y0 + texture->height - 1; - - if (x0 < 0) - { - x0 = 0; - } - if (y0 < 0) - { - y0 = 0; - } - if (x1 > s_width - 1) - { - x1 = s_width - 1; - } - if (y1 > s_height - 1) - { - y1 = s_height - 1; - } - s32 yPixelCount = y1 - y0 + 1; - - const u8* buffer = texture->image; - for (s32 x = x0; x <= x1; x++, buffer += texture->height) - { - textureBlitColumn(buffer, s_display + y0*s_width + x, yPixelCount); - } - } - - void clear3DView(u8* framebuffer) - { - memset(framebuffer, 0, s_width); - } -} // RClassic_Fixed - -} // TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rclassicFixed.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rclassicFixed.h deleted file mode 100644 index 57cd5282..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rclassicFixed.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once -#include - -struct ColorMap; -struct RSector; -struct TextureData; - -namespace TFE_Jedi -{ - struct EdgePairFixed; - - namespace RClassic_Fixed - { - void resetState(); - void setupInitCameraAndLights(); - void changeResolution(s32 width, s32 height); - - void computeCameraTransform(RSector* sector, angle14_32 pitch, angle14_32 yaw, fixed16_16 camX, fixed16_16 camY, fixed16_16 camZ); - void transformPointByCamera(vec3_fixed* worldPoint, vec3_fixed* viewPoint); - void blitTextureToScreen(TextureData* texture, s32 x0, s32 y0); - void clear3DView(u8* framebuffer); - void setVisionEffect(s32 effect); - void computeSkyOffsets(); - } // RClassic_Fixed -} // TFE_Jedi diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rclassicFixedSharedState.cpp b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rclassicFixedSharedState.cpp deleted file mode 100644 index 123f3135..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rclassicFixedSharedState.cpp +++ /dev/null @@ -1,14 +0,0 @@ -#include "rclassicFixedSharedState.h" - -namespace TFE_Jedi -{ -#ifdef TFE_ESPBOX - RClassicFixedState* s_rcfStatePtr = nullptr; - void rcf_setStatePtr(RClassicFixedState* state) - { - s_rcfStatePtr = state; - } -#else - RClassicFixedState s_rcfState = { 0 }; -#endif -} // TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rclassicFixedSharedState.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rclassicFixedSharedState.h deleted file mode 100644 index a1be430d..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rclassicFixedSharedState.h +++ /dev/null @@ -1,81 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Fixed-point shared state used by the Jedi Renderer. -// The floating-point sub-renderer will have its own mirrored struct -// of shared state. -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include - -namespace TFE_Jedi -{ - struct RClassicFixedState - { - // Resolution - fixed16_16 halfWidth; - fixed16_16 halfHeight; - fixed16_16 projOffsetX; - fixed16_16 projOffsetY; - fixed16_16 projOffsetYBase; - fixed16_16 oneOverHalfWidth; - - // Projection -#ifdef TFE_ESPBOX - s32 focalLength; - s32 focalLenAspect; -#else - fixed16_16 focalLength; - fixed16_16 focalLenAspect; -#endif - fixed16_16 eyeHeight; - fixed16_16* depth1d_all; - fixed16_16* depth1d; - - // Camera - vec3_fixed cameraPos; - vec2_fixed cameraTrans; - fixed16_16 cosYaw; - fixed16_16 sinYaw; - fixed16_16 negSinYaw; - fixed16_16 cameraYaw; - fixed16_16 cameraPitch; - fixed16_16 yPlaneTop; - fixed16_16 yPlaneBot; - fixed16_16 skyYawOffset; - fixed16_16 skyPitchOffset; - fixed16_16* skyTable; - fixed16_16 cameraMtx[9]; - - // Window - fixed16_16 windowMinZ; - fixed16_16 windowMinY; - fixed16_16 windowMaxY; - - // Column Heights - fixed16_16* column_Z_Over_X; - fixed16_16* column_X_Over_Z; - - // Flats - fixed16_16* rcpY; - EdgePairFixed* flatEdge; - EdgePairFixed flatEdgeList[MAX_SEG]; - EdgePairFixed* adjoinEdge; - EdgePairFixed adjoinEdgeList[MAX_ADJOIN_SEG * MAX_ADJOIN_DEPTH]; - - RWallSegmentFixed wallSegListDst[MAX_SEG]; - RWallSegmentFixed wallSegListSrc[MAX_SEG]; - RWallSegmentFixed** adjoinSegment; - }; -#ifdef TFE_ESPBOX - // The state (~320KB) is allocated by the platform (from the ROM pool in PSRAM) - // before the renderer is used; see rcf_setStatePtr(). - extern RClassicFixedState* s_rcfStatePtr; - #define s_rcfState (*TFE_Jedi::s_rcfStatePtr) - void rcf_setStatePtr(RClassicFixedState* state); -#else - extern RClassicFixedState s_rcfState; -#endif -} // TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/redgePairFixed.cpp b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/redgePairFixed.cpp deleted file mode 100644 index b826baf7..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/redgePairFixed.cpp +++ /dev/null @@ -1,50 +0,0 @@ -#include -#include "redgePairFixed.h" - -namespace TFE_Jedi -{ - -namespace RClassic_Fixed -{ - void edgePair_setup(s32 length, s32 x0, fixed16_16 dyFloor_dx, fixed16_16 yFloor1, fixed16_16 yFloor, fixed16_16 dyCeil_dx, fixed16_16 yCeil, fixed16_16 yCeil1, EdgePairFixed* edgePair) - { - const s32 yF0 = round16(yFloor); - const s32 yF1 = round16(yFloor1); - const s32 yC0 = round16(yCeil); - const s32 yC1 = round16(yCeil1); - - edgePair->yCeil0 = yCeil; - edgePair->yCeil1 = yCeil1; - edgePair->dyCeil_dx = dyCeil_dx; - if (yC0 < yC1) - { - edgePair->yPixel_C0 = yC0; - edgePair->yPixel_C1 = yC1; - } - else - { - edgePair->yPixel_C0 = yC1; - edgePair->yPixel_C1 = yC0; - } - - edgePair->yFloor0 = yFloor; - edgePair->yFloor1 = yFloor1; - edgePair->dyFloor_dx = dyFloor_dx; - if (yF0 > yF1) - { - edgePair->yPixel_F0 = yF0; - edgePair->yPixel_F1 = yF1; - } - else - { - edgePair->yPixel_F0 = yF1; - edgePair->yPixel_F1 = yF0; - } - - edgePair->lengthInPixels = length; - edgePair->x0 = x0; - edgePair->x1 = x0 + length - 1; - } -} // REdgePair_Fixed - -} // TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/redgePairFixed.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/redgePairFixed.h deleted file mode 100644 index 3f1c8c43..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/redgePairFixed.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include "../redgePair.h" - -namespace TFE_Jedi -{ - namespace RClassic_Fixed - { - void edgePair_setup(s32 length, s32 x0, fixed16_16 dyFloor_dx, fixed16_16 yFloor1, fixed16_16 yFloor, fixed16_16 dyCeil_dx, fixed16_16 yCeil, fixed16_16 yCeil1, EdgePairFixed* flat); - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rflatFixed.cpp b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rflatFixed.cpp deleted file mode 100644 index 6dbece54..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rflatFixed.cpp +++ /dev/null @@ -1,572 +0,0 @@ -#include -#include -#include "rflatFixed.h" -#include "rlightingFixed.h" -#include "redgePairFixed.h" -#include "rclassicFixed.h" -#include "rclassicFixedSharedState.h" -#ifdef TFE_ESPBOX -#include "../rscanline.cpp" -#else -#include "../rscanline.h" -#endif -#include "../rsectorRender.h" -#include "../redgePair.h" -#include "../rcommon.h" -#ifdef TFE_ESPBOX -#define FIXED_6_26 // 6.26 fixed point -#define s_width (320) -#define s_height (200) -#endif -#include - -namespace TFE_Jedi -{ - -namespace RClassic_Fixed -{ - static s32 s_scanlineX0; - - static fixed16_16 s_scanlineU0; - static fixed16_16 s_scanlineV0; - static fixed16_16 s_scanline_dUdX; - static fixed16_16 s_scanline_dVdX; - - static s32 s_scanlineWidth; - static const u8* s_scanlineLight; - static u8* s_scanlineOut; - - static u8* s_ftexImage; - static s32 s_ftexDataEnd; - static s32 s_ftexHeight; - static s32 s_ftexWidthMask; - static s32 s_ftexHeightMask; - static s32 s_ftexHeightLog2; -#ifdef TFE_ESPBOX1 - #define s_ftexDataEnd (4095) -#endif - - void flat_addEdges(s32 length, s32 x0, fixed16_16 dyFloor_dx, fixed16_16 yFloor, fixed16_16 dyCeil_dx, fixed16_16 yCeil) - {//t2++; - if (s_flatCount < MAX_SEG && length > 0) - { -#ifdef TFE_ESPBOX - const s32 lengthMinusOne = length - 1; - - fixed16_16 yCeil1 = yCeil; - if (dyCeil_dx != 0) - { - yCeil1 += dyCeil_dx * lengthMinusOne; - } - fixed16_16 yFloor1 = yFloor; - if (dyFloor_dx != 0) - { - yFloor1 += dyFloor_dx * lengthMinusOne; - } -#else - const fixed16_16 lengthFixed = intToFixed16(length - 1); - - fixed16_16 yCeil1 = yCeil; - if (dyCeil_dx != 0) - { - yCeil1 += mul16(dyCeil_dx, lengthFixed); - } - fixed16_16 yFloor1 = yFloor; - if (dyFloor_dx != 0) - { - yFloor1 += mul16(dyFloor_dx, lengthFixed); - } -#endif - - edgePair_setup(length, x0, dyFloor_dx, yFloor1, yFloor, dyCeil_dx, yCeil, yCeil1, s_rcfState.flatEdge); - - if (s_rcfState.flatEdge->yPixel_C1 - 1 > s_wallMaxCeilY) - { - s_wallMaxCeilY = s_rcfState.flatEdge->yPixel_C1 - 1; - } - if (s_rcfState.flatEdge->yPixel_F1 + 1 < s_wallMinFloorY) - { - s_wallMinFloorY = s_rcfState.flatEdge->yPixel_F1 + 1; - } - if (s_wallMaxCeilY < s_windowMinY_Pixels) - { - s_wallMaxCeilY = s_windowMinY_Pixels; - } - if (s_wallMinFloorY > s_windowMaxY_Pixels) - { - s_wallMinFloorY = s_windowMaxY_Pixels; - } - - s_rcfState.flatEdge++; - s_flatCount++; - } - } - - // This produces functionally identical results to the original but splits apart the U/V and dUdx/dVdx into seperate variables - // to account for C vs ASM differences. - void drawScanline() - { -#ifdef FIXED_6_26 - u32 U = s_scanlineU0 << 10; - u32 V = s_scanlineV0 << 10; - const u32 dUdX = s_scanline_dUdX << 10; - const u32 dVdX = s_scanline_dVdX << 10; - - // Note this produces a distorted mapping if the texture is not 64x64. - // This behavior matches the original. - u32 texel = ((U >> 26)<<6) + (V >> 26); - texel &= s_ftexDataEnd; - U += dUdX; - V += dVdX; - - for (s32 i = s_scanlineWidth - 1; i >= 0; i--) - { - u8 c = s_scanlineLight[s_ftexImage[texel]]; - texel = ((U >> 26)<<6) + (V >> 26); - texel &= s_ftexDataEnd; - U += dUdX; - V += dVdX; - s_scanlineOut[i] = c; - //s_scanlineOut[i] = ((u32)s_scanlineOut) & 0xFF; - } -#else - fixed16_16 U = s_scanlineU0; - fixed16_16 V = s_scanlineV0; - const fixed16_16 dUdX = s_scanline_dUdX; - const fixed16_16 dVdX = s_scanline_dVdX; - - // Note this produces a distorted mapping if the texture is not 64x64. - // This behavior matches the original. - u32 texel = ((floor16(U) & 63)<<6) + (floor16(V) & 63); - texel &= s_ftexDataEnd; - U += dUdX; - V += dVdX; - - for (s32 i = s_scanlineWidth - 1; i >= 0; i--) - { - u8 c = s_scanlineLight[s_ftexImage[texel]]; - texel = ((floor16(U) & 63)<<6) + (floor16(V) & 63); - texel &= s_ftexDataEnd; - U += dUdX; - V += dVdX; - s_scanlineOut[i] = c; - } -#endif - } - - void drawScanline_Fullbright() - { -#ifdef FIXED_6_26 - u32 V = s_scanlineV0 << 10; - u32 U = s_scanlineU0 << 10; - u32 dVdX = s_scanline_dVdX << 10; - u32 dUdX = s_scanline_dUdX << 10; - - // Note this produces a distorted mapping if the texture is not 64x64. - // This behavior matches the original. - u32 texel = ((U >> 26)<<6) + (V >> 26); - texel &= s_ftexDataEnd; - U += dUdX; - V += dVdX; - - for (s32 i = s_scanlineWidth - 1; i >= 0; i--) - { - u8 c = s_ftexImage[texel]; - texel = ((U >> 26)<<6) + (V >> 26); - texel &= s_ftexDataEnd; - U += dUdX; - V += dVdX; - s_scanlineOut[i] = c; - } -#else - fixed16_16 V = s_scanlineV0; - fixed16_16 U = s_scanlineU0; - fixed16_16 dVdX = s_scanline_dVdX; - fixed16_16 dUdX = s_scanline_dUdX; - - // Note this produces a distorted mapping if the texture is not 64x64. - // This behavior matches the original. - u32 texel = (floor16(U) & 63) * 64 + (floor16(V) & 63); - texel &= s_ftexDataEnd; - U += dUdX; - V += dVdX; - - for (s32 i = s_scanlineWidth - 1; i >= 0; i--) - { - u8 c = s_ftexImage[texel]; - texel = (floor16(U) & 63) * 64 + (floor16(V) & 63); - texel &= s_ftexDataEnd; - U += dUdX; - V += dVdX; - s_scanlineOut[i] = c; - } -#endif - } - - void drawScanline_Trans() - { -#ifdef FIXED_6_26 - u32 V = s_scanlineV0 << 10; - u32 U = s_scanlineU0 << 10; - u32 dVdX = s_scanline_dVdX << 10; - u32 dUdX = s_scanline_dUdX << 10; - - // Note this produces a distorted mapping if the texture is not 64x64. - // This behavior matches the original. - u32 texel = ((U >> 26)<<6) + (V >> 26); - texel &= s_ftexDataEnd; - U += dUdX; - V += dVdX; - - for (s32 i = s_scanlineWidth - 1; i >= 0; i--) - { - u8 baseColor = s_ftexImage[texel]; - u8 c = s_scanlineLight[baseColor]; - texel = ((U >> 26)<<6) + (V >> 26); - texel &= s_ftexDataEnd; - U += dUdX; - V += dVdX; - - if (baseColor) { s_scanlineOut[i] = c; } - } -#else - fixed16_16 V = s_scanlineV0; - fixed16_16 U = s_scanlineU0; - fixed16_16 dVdX = s_scanline_dVdX; - fixed16_16 dUdX = s_scanline_dUdX; - - // Note this produces a distorted mapping if the texture is not 64x64. - // This behavior matches the original. - u32 texel = (floor16(U) & 63) * 64 + (floor16(V) & 63); - texel &= s_ftexDataEnd; - U += dUdX; - V += dVdX; - - for (s32 i = s_scanlineWidth - 1; i >= 0; i--) - { - u8 baseColor = s_ftexImage[texel]; - u8 c = s_scanlineLight[baseColor]; - texel = (floor16(U) & 63) * 64 + (floor16(V) & 63); - texel &= s_ftexDataEnd; - U += dUdX; - V += dVdX; - - if (baseColor) { s_scanlineOut[i] = c; } - } -#endif - } - - void drawScanline_Fullbright_Trans() - { -#ifdef FIXED_6_26 - u32 V = s_scanlineV0 << 10; - u32 U = s_scanlineU0 << 10; - u32 dVdX = s_scanline_dVdX << 10; - u32 dUdX = s_scanline_dUdX << 10; - - // Note this produces a distorted mapping if the texture is not 64x64. - // This behavior matches the original. - u32 texel = ((U >> 26)<<6) + (V >> 26); - texel &= s_ftexDataEnd; - U += dUdX; - V += dVdX; - - for (s32 i = s_scanlineWidth - 1; i >= 0; i--) - { - u8 c = s_ftexImage[texel]; - texel = ((U >> 26)<<6) + (V >> 26); - texel &= s_ftexDataEnd; - U += dUdX; - V += dVdX; - if (c) { s_scanlineOut[i] = c; } - } -#else - fixed16_16 V = s_scanlineV0; - fixed16_16 U = s_scanlineU0; - fixed16_16 dVdX = s_scanline_dVdX; - fixed16_16 dUdX = s_scanline_dUdX; - - // Note this produces a distorted mapping if the texture is not 64x64. - // This behavior matches the original. - u32 texel = (floor16(U) & 63) * 64 + (floor16(V) & 63); - texel &= s_ftexDataEnd; - U += dUdX; - V += dVdX; - - for (s32 i = s_scanlineWidth - 1; i >= 0; i--) - { - u8 c = s_ftexImage[texel]; - texel = (floor16(U) & 63) * 64 + (floor16(V) & 63); - texel &= s_ftexDataEnd; - U += dUdX; - V += dVdX; - if (c) { s_scanlineOut[i] = c; } - } -#endif - } - - bool flat_setTexture(TextureData* tex) - { - if (!tex) { return false; } - - s_ftexHeight = tex->height; - s_ftexWidthMask = tex->width - 1; - s_ftexHeightMask = tex->height - 1; - s_ftexHeightLog2 = tex->logSizeY; - s_ftexImage = tex->image; -#ifndef TFE_ESPBOX1 - s_ftexDataEnd = tex->width * tex->height - 1; -#endif - - return true; - } - - void flat_drawCeiling(RSector* sector, EdgePairFixed* edges, s32 count) - { - fixed16_16 textureOffsetU = s_rcfState.cameraPos.x - sector->ceilOffset.x; - fixed16_16 textureOffsetV = sector->ceilOffset.z - s_rcfState.cameraPos.z; - - fixed16_16 relCeil = sector->ceilingHeight - s_rcfState.eyeHeight; -#ifdef TFE_ESPBOX - fixed16_16 scaledRelCeil = (relCeil * s_rcfState.focalLenAspect); -#else - fixed16_16 scaledRelCeil = mul16(relCeil, s_rcfState.focalLenAspect); -#endif - fixed16_16 cosScaledRelCeil = mul16(scaledRelCeil, s_rcfState.cosYaw); - fixed16_16 negSinRelCeil = -mul16(relCeil, s_rcfState.sinYaw); - fixed16_16 sinScaledRelCeil = mul16(scaledRelCeil, s_rcfState.sinYaw); - fixed16_16 negCosRelCeil = -mul16(relCeil, s_rcfState.cosYaw); - - if (!flat_setTexture(*sector->ceilTex)) { return; } - - for (s32 y = s_windowMinY_Pixels; y <= s_wallMaxCeilY && y < s_windowMaxY_Pixels; y++) - { - s32 x = s_windowMinX_Pixels; - s32 yOffset = y * s_width; - s32 yShear = s_screenYMidBase - s_screenYMidFix; - assert(yShear + y + s_height * 2 >= 0 && yShear + y + s_height * 2 <= s_height * 4); - fixed16_16 yRcp = s_rcfState.rcpY[yShear + y + s_height*2]; - fixed16_16 z = mul16(scaledRelCeil, yRcp); - - s32 left = 0; - s32 right = 0; - for (s32 i = 0; i < count;) - { - if (!flat_buildScanlineCeiling(i, count, x, y, left, right, s_scanlineWidth, edges)) - { - break; - } - - if (s_scanlineWidth > 0) - { - assert(left >= 0 && left + s_scanlineWidth <= s_width); - assert(y >= 0 && y < s_height); - s_scanlineX0 = left; - s_scanlineOut = &s_display[left + yOffset]; - - const fixed16_16 worldToTexelScale = fixed16_16(8); -#ifdef TFE_ESPBOX - s32 rightClip = right - s_screenXMid; -#else - fixed16_16 rightClip = intToFixed16(right - s_screenXMid); -#endif - -#ifdef TFE_ESPBOX - fixed16_16 v0 = mul16(cosScaledRelCeil - (negSinRelCeil * rightClip), yRcp); - fixed16_16 u0 = mul16(sinScaledRelCeil + (negCosRelCeil * rightClip), yRcp); -#else - fixed16_16 v0 = mul16(cosScaledRelCeil - mul16(negSinRelCeil, rightClip), yRcp); - fixed16_16 u0 = mul16(sinScaledRelCeil + mul16(negCosRelCeil, rightClip), yRcp); -#endif - - s_scanlineV0 = (v0 - textureOffsetV) * worldToTexelScale; - s_scanlineU0 = (u0 - textureOffsetU) * worldToTexelScale; - - s_scanline_dVdX = mul16(negSinRelCeil, yRcp) * worldToTexelScale; - s_scanline_dUdX = -mul16(negCosRelCeil, yRcp) * worldToTexelScale; - - s_scanlineLight = computeLighting(z, 0); - - if (s_scanlineLight) - { - drawScanline(); - } - else - { - drawScanline_Fullbright(); - } - } - } // while (i < count) - } - } - - void flat_drawFloor(RSector* sector, EdgePairFixed* edges, s32 count) - { - fixed16_16 textureOffsetU = s_rcfState.cameraPos.x - sector->floorOffset.x; - fixed16_16 textureOffsetV = sector->floorOffset.z - s_rcfState.cameraPos.z; - - fixed16_16 relFloor = sector->floorHeight - s_rcfState.eyeHeight; -#ifdef TFE_ESPBOX - fixed16_16 scaledRelFloor = (relFloor * s_rcfState.focalLenAspect); -#else - fixed16_16 scaledRelFloor = mul16(relFloor, s_rcfState.focalLenAspect); -#endif - - fixed16_16 cosScaledRelFloor = mul16(scaledRelFloor, s_rcfState.cosYaw); - fixed16_16 negSinRelFloor =-mul16(relFloor, s_rcfState.sinYaw); - fixed16_16 sinScaledRelFloor = mul16(scaledRelFloor, s_rcfState.sinYaw); - fixed16_16 negCosRelFloor =-mul16(relFloor, s_rcfState.cosYaw); - - if (!flat_setTexture(*sector->floorTex)) { return; } - - for (s32 y = max(s_wallMinFloorY, s_windowMinY_Pixels); y <= s_windowMaxY_Pixels; y++) - { - s32 x = s_windowMinX_Pixels; - s32 yOffset = y * s_width; - s32 yShear = s_screenYMidBase - s_screenYMidFix; - assert(yShear + y + s_height * 2 >= 0 && yShear + y + s_height * 2 <= s_height * 4); - fixed16_16 yRcp = s_rcfState.rcpY[yShear + y + s_height*2]; - fixed16_16 z = mul16(scaledRelFloor, yRcp); - - s32 left = 0; - s32 right = 0; - for (s32 i = 0; i < count;) - { - s32 winMaxX = s_windowMaxX_Pixels; - - // Search for the left edge of the scanline. - if (!flat_buildScanlineFloor(i, count, x, y, left, right, s_scanlineWidth, edges)) - { - break; - } - - if (s_scanlineWidth > 0) - { - assert(left >= 0 && left + s_scanlineWidth <= s_width); - assert(y >= 0 && y < s_height); - s_scanlineX0 = left; - s_scanlineOut = &s_display[left + yOffset]; - -#ifdef TFE_ESPBOX - s32 rightClip = right - s_screenXMid; -#else - fixed16_16 rightClip = intToFixed16(right - s_screenXMid); -#endif - fixed16_16 worldToTexelScale = fixed16_16(8); - -#ifdef TFE_ESPBOX - fixed16_16 v0 = mul16(cosScaledRelFloor - (negSinRelFloor * rightClip), yRcp); - fixed16_16 u0 = mul16(sinScaledRelFloor + (negCosRelFloor * rightClip), yRcp); -#else - fixed16_16 v0 = mul16(cosScaledRelFloor - mul16(negSinRelFloor, rightClip), yRcp); - fixed16_16 u0 = mul16(sinScaledRelFloor + mul16(negCosRelFloor, rightClip), yRcp); -#endif - s_scanlineV0 = (v0 - textureOffsetV) * worldToTexelScale; - s_scanlineU0 = (u0 - textureOffsetU) * worldToTexelScale; - - s_scanline_dVdX = mul16(negSinRelFloor, yRcp) * worldToTexelScale; - s_scanline_dUdX = -mul16(negCosRelFloor, yRcp) * worldToTexelScale; - s_scanlineLight = computeLighting(z, 0); - - if (s_scanlineLight) - { - drawScanline(); - } - else - { - drawScanline_Fullbright(); - } - } - } // while (i < count) - } - } - - ////////////////////////////////////////////////////////////////////// - // Polygon Scanline rendering using the same algorithms as flats. - ////////////////////////////////////////////////////////////////////// - typedef void(*ScanlineFunction)(); - static const ScanlineFunction c_scanlineDrawFunc[] = - { - drawScanline, - drawScanline_Fullbright, - drawScanline_Trans, - drawScanline_Fullbright_Trans - }; - - static fixed16_16 s_poly_offsetX; - static fixed16_16 s_poly_offsetZ; - - static fixed16_16 s_poly_scaledHOffset; - static fixed16_16 s_poly_sinYawHOffset; - static fixed16_16 s_poly_cosYawHOffset; - - static fixed16_16 s_poly_cosYawScaledHOffset; - static fixed16_16 s_poly_sinYawScaledHOffset; - - void flat_preparePolygon(fixed16_16 heightOffset, fixed16_16 offsetX, fixed16_16 offsetZ, TextureData* texture) - { - s_poly_offsetX = s_rcfState.cameraPos.x - offsetX; - s_poly_offsetZ = offsetZ - s_rcfState.cameraPos.z; - -#ifdef TFE_ESPBOX - s_poly_scaledHOffset = (heightOffset * s_rcfState.focalLenAspect); -#else - s_poly_scaledHOffset = mul16(heightOffset, s_rcfState.focalLenAspect); -#endif - s_poly_sinYawHOffset = mul16(s_rcfState.sinYaw, heightOffset); - s_poly_cosYawHOffset = mul16(s_rcfState.cosYaw, heightOffset); - - s_poly_cosYawScaledHOffset = mul16(s_rcfState.cosYaw, s_poly_scaledHOffset); - s_poly_sinYawScaledHOffset = mul16(s_rcfState.sinYaw, s_poly_scaledHOffset); - - s_ftexWidthMask = texture->width - 1; - s_ftexHeightMask = texture->height - 1; - s_ftexHeightLog2 = texture->logSizeY; - s_ftexImage = texture->image; -#ifndef TFE_ESPBOX1 - s_ftexDataEnd = texture->width * texture->height - 1; -#endif - } - - void flat_drawPolygonScanline(s32 x0, s32 x1, s32 y, bool trans) - { - x0 = max(x0, s_windowMinX_Pixels); - x1 = min(x1, s_windowMaxX_Pixels); - clipScanline(&x0, &x1, y); - - s_scanlineWidth = x1 - x0 + 1; - if (s_scanlineWidth <= 0) { return; } - - s_scanlineX0 = x0; - s_scanlineOut = &s_display[y * s_width + x0]; - - const s32 yShear = s_screenYMidBase - s_screenYMidFix; - assert(yShear + y + s_height * 2 >= 0 && yShear + y + s_height * 2 <= s_height * 4); - const fixed16_16 yRcp = s_rcfState.rcpY[yShear + y + s_height*2]; - const fixed16_16 z = mul16(s_poly_scaledHOffset, yRcp); -#ifdef TFE_ESPBOX - const s32 right = x1 - 1 - s_screenXMid; -#else - const fixed16_16 right = intToFixed16(x1 - 1 - s_screenXMid); -#endif - -#ifdef TFE_ESPBOX - const fixed16_16 u0 = s_poly_sinYawScaledHOffset - (s_poly_cosYawHOffset * right); - const fixed16_16 v0 = s_poly_cosYawScaledHOffset + (s_poly_sinYawHOffset * right); -#else - const fixed16_16 u0 = s_poly_sinYawScaledHOffset - mul16(s_poly_cosYawHOffset, right); - const fixed16_16 v0 = s_poly_cosYawScaledHOffset + mul16(s_poly_sinYawHOffset, right); -#endif - s_scanlineU0 = (mul16(u0, yRcp) - s_poly_offsetX) * 8; - s_scanlineV0 = (mul16(v0, yRcp) - s_poly_offsetZ) * 8; - s_scanline_dVdX = -mul16(s_poly_sinYawHOffset, yRcp) * 8; - s_scanline_dUdX = mul16(s_poly_cosYawHOffset, yRcp) * 8; - - s_scanlineLight = computeLighting(z, 0); - const s32 index = (!s_scanlineLight) + trans*2; - c_scanlineDrawFunc[index](); - } - -} // RFlatFixed - -} // TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rflatFixed.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rflatFixed.h deleted file mode 100644 index be873417..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rflatFixed.h +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include -#include - -struct RSector; -struct EdgePairFixed; - -namespace TFE_Jedi -{ - namespace RClassic_Fixed - { - void flat_addEdges(s32 length, s32 x0, fixed16_16 dyFloor_dx, fixed16_16 yFloor, fixed16_16 dyCeil_dx, fixed16_16 yCeil); - - void flat_drawCeiling(RSector* sector, EdgePairFixed* edges, s32 count); - void flat_drawFloor(RSector* sector, EdgePairFixed* edges, s32 count); - - // Set Parameters for 3D object rendering. - void flat_preparePolygon(fixed16_16 heightOffset, fixed16_16 offsetX, fixed16_16 offsetZ, TextureData* texture); - void flat_drawPolygonScanline(s32 x0, s32 x1, s32 y, bool trans); - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rlightingFixed.cpp b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rlightingFixed.cpp deleted file mode 100644 index 1bd32f58..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rlightingFixed.cpp +++ /dev/null @@ -1,80 +0,0 @@ -#include -#include -#include "rlightingFixed.h" -#include "rclassicFixed.h" -#include "../rcommon.h" -#include "../rlimits.h" -#ifdef TFE_ESPBOX -#define s_width (320) -#define s_height (200) -#endif - -namespace TFE_Jedi -{ - -namespace RClassic_Fixed -{ - CameraLight s_cameraLight[] = - { - { {0, 0, ONE_16}, {0, 0, 0}, ONE_16 }, - { {0, ONE_16, 0}, {0, 0, 0}, ONE_16 }, - { {ONE_16, 0, 0}, {0, 0, 0}, ONE_16 }, - }; - - void light_transformDirLights() - { - vec3_fixed pos = { 0 }; - vec3_fixed viewPos; - transformPointByCamera(&pos, &viewPos); - - for (s32 i = 0; i < s_lightCount; i++) - { - vec3_fixed dir; - transformPointByCamera(&s_cameraLight[i].lightWS, &dir); - s_cameraLight[i].lightVS.x = -(dir.x - viewPos.x); - s_cameraLight[i].lightVS.y = -(dir.y - viewPos.y); - s_cameraLight[i].lightVS.z = -(dir.z - viewPos.z); - normalizeVec3(&s_cameraLight[i].lightVS, &s_cameraLight[i].lightVS); - } - } - - u8 getLightLevelFromAtten(const u8* atten) - { - return u32(atten - s_colorMap) >> 8u; - } - - const u8* computeLighting(fixed16_16 depth, s32 lightOffset) - { - if (s_sectorAmbient >= MAX_LIGHT_LEVEL) { return nullptr; } - depth = max(depth, 0); - s32 light = 0; - - // handle camera lightsource - if (s_worldAmbient < MAX_LIGHT_LEVEL || s_cameraLightSource) - { - s32 depthScaled = min(s32(depth >> LIGHT_SCALE), 127); - s32 lightSource = MAX_LIGHT_LEVEL - (s_lightSourceRamp[depthScaled] + s_worldAmbient); - if (lightSource > 0) - { - light += lightSource; - } - } - - s32 secAmb = s_sectorAmbient; - if (light < secAmb) { light = secAmb; } - - s32 depthAtten = s32((depth >> LIGHT_ATTEN0) + (depth >> LIGHT_ATTEN1)); // depth * 3/32 - light = max(light - depthAtten, s_scaledAmbient); - - if (lightOffset != 0) - { - light += lightOffset; - } - if (light >= MAX_LIGHT_LEVEL) { return nullptr; } - light = max(light, 0); - - return &s_colorMap[light << 8]; - } -} // RLightingFixed - -} // TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rlightingFixed.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rlightingFixed.h deleted file mode 100644 index 22282930..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rlightingFixed.h +++ /dev/null @@ -1,30 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include -#include - -#define LIGHT_SCALE 14 -#define LIGHT_ATTEN0 20 -#define LIGHT_ATTEN1 21 - -namespace TFE_Jedi -{ - namespace RClassic_Fixed - { - struct CameraLight - { - vec3_fixed lightWS; - vec3_fixed lightVS; - fixed16_16 brightness; - }; - extern CameraLight s_cameraLight[]; - - void light_transformDirLights(); - u8 getLightLevelFromAtten(const u8* atten); - const u8* computeLighting(fixed16_16 depth, s32 lightOffset); - } -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed.cpp b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed.cpp deleted file mode 100644 index 80a34582..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed.cpp +++ /dev/null @@ -1,139 +0,0 @@ -#include -#include -#include -#include - -#include "robj3dFixed.h" -#include "robj3dFixed_TransformAndLighting.h" -#include "robj3dFixed_PolygonSetup.h" -#include "robj3dFixed_Culling.h" -#include "robj3dFixed_Clipping.h" -#include "robj3dFixed_PolygonDraw.h" -#include "../rclassicFixedSharedState.h" -#include "../../rcommon.h" -#ifdef TFE_ESPBOX -#define s_width (320) -#define s_height (200) -#endif - -namespace TFE_Jedi -{ - -extern s32 s_drawnObjCount; -extern SecObject* s_drawnObj[]; - -namespace RClassic_Fixed -{ - void robj3d_projectVertices(vec3_fixed* pos, s32 count, vec3_fixed* out); - void robj3d_drawVertices(s32 vertexCount, const vec3_fixed* vertices, u8 color); - int polygonSort(const void* r0, const void* r1); - - void robj3d_draw(SecObject* obj, JediModel* model) - { - // Handle transforms and vertex lighting. - robj3d_transformAndLight(obj, model); - - // Draw vertices and return if the flag is set. - if (model->flags & MFLAG_DRAW_VERTICES) - { - // If the MFLAG_DRAW_VERTICES flag is set, draw all vertices as points. - robj3d_drawVertices(model->vertexCount, s_verticesVS.data(), model->polygons[0].color); - return; - } - - // Cull backfacing polygons. The results are stored as "visPolygons" - s32 visPolygonCount = robj3d_backfaceCull(model); - // Nothing to render. - if (visPolygonCount < 1) { return; } - - // Sort polygons from back to front. - qsort(s_visPolygons.data(), visPolygonCount, sizeof(JmPolygon*), polygonSort); - - // Draw polygons - JmPolygon** visPolygon = s_visPolygons.data(); - JBool drawn = JFALSE; - for (s32 i = 0; i < visPolygonCount; i++, visPolygon++) - { - JmPolygon* polygon = *visPolygon; - if (polygon->vertexCount <= 0) { continue; } - - robj3d_setupPolygon(polygon); - - s32 polyVertexCount = clipPolygon(polygon); - // Cull the polygon if not enough vertices survive clipping. - if (polyVertexCount < 3) { continue; } - drawn = JTRUE; - - // Project the resulting vertices. - robj3d_projectVertices(s_polygonVerticesVS, polyVertexCount, s_polygonVerticesProj); - - // Draw polygon based on its shading mode. - robj3d_drawPolygon(polygon, polyVertexCount, obj, model); - } - - if (drawn && s_drawnObjCount < MAX_DRAWN_OBJ_STORE) - { - s_drawnObj[s_drawnObjCount++] = obj; - } - } - - void robj3d_drawVertices(s32 vertexCount, const vec3_fixed* vertices, u8 color) - { - // cannot draw if the color is transparent. - if (color == 0) { return; } - - // Loop through the vertices and draw them as pixels. - const vec3_fixed* vertex = vertices; - for (s32 v = 0; v < vertexCount; v++, vertex++) - { - const fixed16_16 z = vertex->z; - if (z <= ONE_16) { continue; } - -#ifdef TFE_ESPBOX - const fixed16_16 rcpZ = div16(ONE_16, z); - const s32 pixel_x = round16(mul16((vertex->x * s_rcfState.focalLength), rcpZ) + s_rcfState.projOffsetX); - const s32 pixel_y = round16(mul16((vertex->y * s_rcfState.focalLenAspect), rcpZ) + s_rcfState.projOffsetY); -#else - const s32 pixel_x = round16(div16(mul16(vertex->x, s_rcfState.focalLength), z) + s_rcfState.projOffsetX); - const s32 pixel_y = round16(div16(mul16(vertex->y, s_rcfState.focalLenAspect), z) + s_rcfState.projOffsetY); -#endif - - // If the X position is out of view, skip the vertex. - if (pixel_x < s_minScreenX_Pixels || pixel_x > s_maxScreenX_Pixels) - { - continue; - } - // Check the 1d depth buffer and Y positon and skip if occluded. - if (z >= s_rcfState.depth1d[pixel_x] || pixel_y > s_windowMaxY_Pixels || pixel_y < s_windowMinY_Pixels || pixel_y < s_windowTop[pixel_x] || pixel_y > s_windowBot[pixel_x]) - { - continue; - } - - s_display[pixel_y*s_width + pixel_x] = color; - } - } - - void robj3d_projectVertices(vec3_fixed* pos, s32 count, vec3_fixed* out) - { - for (s32 i = 0; i < count; i++, pos++, out++) - { -#ifdef TFE_ESPBOX - const fixed16_16 rcpZ = div16(ONE_16, pos->z); - out->x = round16(mul16((pos->x * s_rcfState.focalLength), rcpZ) + s_rcfState.projOffsetX); - out->y = round16(mul16((pos->y * s_rcfState.focalLenAspect), rcpZ) + s_rcfState.projOffsetY); -#else - out->x = round16(div16(mul16(pos->x, s_rcfState.focalLength), pos->z) + s_rcfState.projOffsetX); - out->y = round16(div16(mul16(pos->y, s_rcfState.focalLenAspect), pos->z) + s_rcfState.projOffsetY); -#endif - out->z = pos->z; - } - } - - int polygonSort(const void* r0, const void* r1) - { - JmPolygon* p0 = *((JmPolygon**)r0); - JmPolygon* p1 = *((JmPolygon**)r1); - return p1->zAve - p0->zAve; - } - -}} // TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed.h deleted file mode 100644 index 0c89dcc6..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include - -struct JediModel; -struct SecObject; - -namespace TFE_Jedi -{ - namespace RClassic_Fixed - { - void robj3d_draw(SecObject* obj, JediModel* model); - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_ClipFunc.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_ClipFunc.h deleted file mode 100644 index a27ef3a5..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_ClipFunc.h +++ /dev/null @@ -1,720 +0,0 @@ -////////////////////////////////////////////////////////////////////// -// Inline clip function to handle the various combinations. -////////////////////////////////////////////////////////////////////// - -#if defined(CLIP_INTENSITY) && !defined(CLIP_UV) -s32 robj3d_swapClipBuffersI(s32 outVertexCount) -#elif !defined(CLIP_INTENSITY) && defined(CLIP_UV) -s32 robj3d_swapClipBuffersT(s32 outVertexCount) -#elif defined(CLIP_INTENSITY) && defined(CLIP_UV) -s32 robj3d_swapClipBuffersTI(s32 outVertexCount) -#else -s32 robj3d_swapClipBuffers(s32 outVertexCount) -#endif -{ - // Swap src position and output position. - s_clipTempPos = s_clipPosSrc; - s_clipPosSrc = s_clipPosOut; - s_clipPosOut = s_clipTempPos; - - // Swap src intensity and output intensity. - #if defined(CLIP_INTENSITY) - s_clipTempIntensity = s_clipIntensitySrc; - s_clipIntensitySrc = s_clipIntensityOut; - s_clipIntensityOut = s_clipTempIntensity; - #endif - - #if defined(CLIP_UV) - s_clipTempUv = s_clipUvSrc; - s_clipUvSrc = s_clipUvOut; - s_clipUvOut = s_clipTempUv; - #endif - - s32 srcVertexCount = outVertexCount; - s32 end = srcVertexCount - 1; - - // Left clip plane. - s_clipPos0 = &s_clipPosSrc[end]; - s_clipPos1 = s_clipPosSrc; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = &s_clipIntensitySrc[end]; - s_clipIntensity1 = s_clipIntensitySrc; - #endif - - #if defined(CLIP_UV) - s_clipUv0 = &s_clipUvSrc[end]; - s_clipUv1 = s_clipUvSrc; - #endif - - return srcVertexCount; -} - -#undef SWAP_CLIP_BUFFERS - -#if defined(CLIP_INTENSITY) && !defined(CLIP_UV) - #define SWAP_CLIP_BUFFERS robj3d_swapClipBuffersI -#elif !defined(CLIP_INTENSITY) && defined(CLIP_UV) - #define SWAP_CLIP_BUFFERS robj3d_swapClipBuffersT -#elif defined(CLIP_INTENSITY) && defined(CLIP_UV) - #define SWAP_CLIP_BUFFERS robj3d_swapClipBuffersTI -#else - #define SWAP_CLIP_BUFFERS robj3d_swapClipBuffers -#endif - -#if defined(CLIP_INTENSITY) && !defined(CLIP_UV) -void computeIntersectionI(s32 outVertexCount) -#elif !defined(CLIP_INTENSITY) && defined(CLIP_UV) -void computeIntersectionT(s32 outVertexCount) -#elif defined(CLIP_INTENSITY) && defined(CLIP_UV) -void computeIntersectionTI(s32 outVertexCount) -#else -void computeIntersection(s32 outVertexCount) -#endif -{ - #if defined(CLIP_INTENSITY) - const fixed16_16 i0 = *s_clipIntensity0; - const fixed16_16 i1 = *s_clipIntensity1; - s_clipIntensityOut[outVertexCount] = i0 + mul16(s_clipParam, i1 - i0); - #endif - #if defined(CLIP_UV) - const vec2_fixed uv0 = *s_clipUv0; - const vec2_fixed uv1 = *s_clipUv1; - s_clipUvOut[outVertexCount].x = uv0.x + mul16(s_clipParam, uv1.x - uv0.x); - s_clipUvOut[outVertexCount].z = uv0.z + mul16(s_clipParam, uv1.z - uv0.z); - #endif -} - -#undef COMPUTE_CLIP_INTERSECTION -#if defined(CLIP_INTENSITY) && !defined(CLIP_UV) -#define COMPUTE_CLIP_INTERSECTION computeIntersectionI -#elif !defined(CLIP_INTENSITY) && defined(CLIP_UV) -#define COMPUTE_CLIP_INTERSECTION computeIntersectionT -#elif defined(CLIP_INTENSITY) && defined(CLIP_UV) -#define COMPUTE_CLIP_INTERSECTION computeIntersectionTI -#else -#define COMPUTE_CLIP_INTERSECTION computeIntersection -#endif - -#if defined(CLIP_INTENSITY) && !defined(CLIP_UV) -s32 robj3d_clipPolygonGouraud(vec3_fixed* pos, s32* intensity, s32 count) -#elif !defined(CLIP_INTENSITY) && defined(CLIP_UV) -s32 robj3d_clipPolygonUv(vec3_fixed* pos, vec2_fixed* uv, s32 count) -#elif defined(CLIP_INTENSITY) && defined(CLIP_UV) -s32 robj3d_clipPolygonUvGouraud(vec3_fixed* pos, vec2_fixed* uv, s32* intensity, s32 count) -#else -s32 robj3d_clipPolygon(vec3_fixed* pos, s32 count) -#endif -{ - s32 outVertexCount = 0; - s32 end = count - 1; - - #if defined(CLIP_INTENSITY) - s_clipIntensitySrc = intensity; - #endif - #if defined(CLIP_UV) - s_clipUvSrc = uv; - #endif - - s_clipPosSrc = pos; - - // Clip against the near plane. - s_clipPosOut = s_clipPosBuffer; - s_clipPos0 = &pos[count - 1]; - s_clipPos1 = pos; - - #if defined(CLIP_INTENSITY) - s_clipIntensityOut = s_clipIntensityBuffer; - s_clipIntensity0 = &intensity[count - 1]; - s_clipIntensity1 = intensity; - #endif - - #if defined(CLIP_UV) - s_clipUvOut = s_clipUvBuffer; - s_clipUv0 = &uv[count - 1]; - s_clipUv1 = uv; - #endif - - /////////////////////////////////////////////////// - // Near Clip Plane - /////////////////////////////////////////////////// - for (s32 i = 0; i < count; i++) - { - if (s_clipPos0->z < ONE_16 && s_clipPos1->z < ONE_16) - { - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - - continue; - } - - // Add vertex 0 if it is on or in front of the near plane. - if (s_clipPos0->z >= ONE_16) - { - s_clipPosOut[outVertexCount] = *s_clipPos0; - - #if defined(CLIP_INTENSITY) - s_clipIntensityOut[outVertexCount] = *s_clipIntensity0; - #endif - #if defined(CLIP_UV) - s_clipUvOut[outVertexCount] = *s_clipUv0; - #endif - - outVertexCount++; - } - - // If either position is exactly on the near plane continue. - if (s_clipPos0->z == ONE_16 || s_clipPos1->z == ONE_16) - { - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - - continue; - } - - // Finally clip the edge against the near plane, generating a new vertex. - if (s_clipPos0->z < ONE_16 || s_clipPos1->z < ONE_16) - { - const fixed16_16 z0 = s_clipPos0->z; - const fixed16_16 z1 = s_clipPos1->z; - - // Parametric clip coordinate. - s_clipParam = div16(ONE_16 - z0, z1 - z0); - // new vertex Z coordinate should be exactly 1.0 - s_clipPosOut[outVertexCount].z = ONE_16; - s_clipPosOut[outVertexCount].y = s_clipPos0->y + mul16(s_clipParam, s_clipPos1->y - s_clipPos0->y); - s_clipPosOut[outVertexCount].x = s_clipPos0->x + mul16(s_clipParam, s_clipPos1->x - s_clipPos0->x); - - COMPUTE_CLIP_INTERSECTION(outVertexCount); - outVertexCount++; - } - - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - } - // Return if the polygon is clipping away. - if (outVertexCount < 3) - { - return 0; - } - s32 srcVertexCount = SWAP_CLIP_BUFFERS(outVertexCount); - outVertexCount = 0; - - /////////////////////////////////////////////////// - // Left Clip Plane - /////////////////////////////////////////////////// - for (s32 i = 0; i < srcVertexCount; i++) - { - s_clipPlanePos0 = -s_clipPos0->z; - s_clipPlanePos1 = -s_clipPos1->z; - if (s_clipPos0->x < s_clipPlanePos0 && s_clipPos1->x < s_clipPlanePos1) - { - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - - continue; - } - - // Add vertex 0 if it is inside the plane. - if (s_clipPos0->x >= s_clipPlanePos0) - { - s_clipPosOut[outVertexCount] = *s_clipPos0; - - #if defined(CLIP_INTENSITY) - s_clipIntensityOut[outVertexCount] = *s_clipIntensity0; - #endif - #if defined(CLIP_UV) - s_clipUvOut[outVertexCount] = *s_clipUv0; - #endif - - outVertexCount++; - } - - // Skip clipping if either vertex is touching the plane. - if (s_clipPos0->x == s_clipPlanePos0 || s_clipPos1->x == s_clipPlanePos1) - { - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - - continue; - } - - // Clip the edge. - if (s_clipPos0->x < s_clipPlanePos0 || s_clipPos1->x < s_clipPlanePos1) - { - const fixed16_16 x0 = s_clipPos0->x; - const fixed16_16 x1 = s_clipPos1->x; - const fixed16_16 z0 = s_clipPos0->z; - const fixed16_16 z1 = s_clipPos1->z; - - const fixed16_16 dx = s_clipPos1->x - s_clipPos0->x; - const fixed16_16 dz = s_clipPos1->z - s_clipPos0->z; - - s_clipParam0 = mul16(x0, z1) - mul16(x1, z0); - s_clipParam1 = -dz - dx; - - s_clipIntersectZ = s_clipParam0; - if (s_clipParam1 != 0) - { - s_clipIntersectZ = div16(s_clipParam0, s_clipParam1); - } - s_clipIntersectX = -s_clipIntersectZ; - - fixed16_16 p, p0, p1; - if (TFE_Jedi::abs(dz) > TFE_Jedi::abs(dx)) - { - p1 = s_clipPos1->z; - p0 = s_clipPos0->z; - p = s_clipIntersectZ; - } - else - { - p1 = s_clipPos1->x; - p0 = s_clipPos0->x; - p = s_clipIntersectX; - } - s_clipParam = div16(p - p0, p1 - p0); - - s_clipPosOut[outVertexCount].x = s_clipIntersectX; - s_clipPosOut[outVertexCount].y = s_clipPos0->y + mul16(s_clipParam, s_clipPos1->y - s_clipPos0->y); - s_clipPosOut[outVertexCount].z = s_clipIntersectZ; - - COMPUTE_CLIP_INTERSECTION(outVertexCount); - outVertexCount++; - } - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - } - if (outVertexCount < 3) - { - return 0; - } - srcVertexCount = SWAP_CLIP_BUFFERS(outVertexCount); - outVertexCount = 0; - - /////////////////////////////////////////////////// - // Right Clip Plane - /////////////////////////////////////////////////// - for (s32 i = 0; i < srcVertexCount; i++) - { - s_clipPlanePos0 = s_clipPos0->z; - s_clipPlanePos1 = s_clipPos1->z; - if (s_clipPos0->x > s_clipPlanePos0 && s_clipPos1->x > s_clipPlanePos1) - { - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - - continue; - } - - // Add vertex 0 if it is inside the plane. - if (s_clipPos0->x <= s_clipPlanePos0) - { - s_clipPosOut[outVertexCount] = *s_clipPos0; - - #if defined(CLIP_INTENSITY) - s_clipIntensityOut[outVertexCount] = *s_clipIntensity0; - #endif - #if defined(CLIP_UV) - s_clipUvOut[outVertexCount] = *s_clipUv0; - #endif - - outVertexCount++; - } - - // Skip clipping if either vertex is touching the plane. - if (s_clipPos0->x == s_clipPlanePos0 || s_clipPos1->x == s_clipPlanePos1) - { - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - - continue; - } - - // Clip the edge. - if (s_clipPos0->x > s_clipPlanePos0 || s_clipPos1->x > s_clipPlanePos1) - { - const fixed16_16 x0 = s_clipPos0->x; - const fixed16_16 x1 = s_clipPos1->x; - const fixed16_16 z0 = s_clipPos0->z; - const fixed16_16 z1 = s_clipPos1->z; - - const fixed16_16 dx = s_clipPos1->x - s_clipPos0->x; - const fixed16_16 dz = s_clipPos1->z - s_clipPos0->z; - - s_clipParam0 = mul16(x0, z1) - mul16(x1, z0); - s_clipParam1 = dz - dx; - - s_clipIntersectZ = s_clipParam0; - if (s_clipParam1 != 0) - { - s_clipIntersectZ = div16(s_clipParam0, s_clipParam1); - } - s_clipIntersectX = s_clipIntersectZ; - - fixed16_16 p, p0, p1; - if (TFE_Jedi::abs(dz) > TFE_Jedi::abs(dx)) - { - p1 = s_clipPos1->z; - p0 = s_clipPos0->z; - p = s_clipIntersectZ; - } - else - { - p1 = s_clipPos1->x; - p0 = s_clipPos0->x; - p = s_clipIntersectX; - } - s_clipParam = div16(p - p0, p1 - p0); - - s_clipPosOut[outVertexCount].x = s_clipIntersectX; - s_clipPosOut[outVertexCount].y = s_clipPos0->y + mul16(s_clipParam, s_clipPos1->y - s_clipPos0->y); // edx - s_clipPosOut[outVertexCount].z = s_clipIntersectZ; - - COMPUTE_CLIP_INTERSECTION(outVertexCount); - outVertexCount++; - } - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - } - if (outVertexCount < 3) - { - return 0; - } - - srcVertexCount = SWAP_CLIP_BUFFERS(outVertexCount); - outVertexCount = 0; - - /////////////////////////////////////////////////// - // Top Clip Plane - /////////////////////////////////////////////////// - for (s32 i = 0; i < srcVertexCount; i++) - { - s_clipY0 = mul16(s_rcfState.yPlaneTop, s_clipPos0->z); - s_clipY1 = mul16(s_rcfState.yPlaneTop, s_clipPos1->z); - - // If the edge is completely behind the plane, then continue. - if (s_clipPos0->y < s_clipY0 && s_clipPos1->y < s_clipY1) - { - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - - continue; - } - // Add vertex 0 if it is inside the plane. - if (s_clipPos0->y > s_clipY0) - { - s_clipPosOut[outVertexCount] = *s_clipPos0; - - #if defined(CLIP_INTENSITY) - s_clipIntensityOut[outVertexCount] = *s_clipIntensity0; - #endif - #if defined(CLIP_UV) - s_clipUvOut[outVertexCount] = *s_clipUv0; - #endif - - outVertexCount++; - } - - // Skip clipping if either vertex is touching the plane. - if (s_clipPos0->y == s_clipY0 || s_clipPos1->y == s_clipY1) - { - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - - continue; - } - - // Clip the edge. - if (s_clipPos0->y < s_clipY0 || s_clipPos1->y < s_clipY1) - { - s_clipParam0 = mul16(s_clipPos0->y, s_clipPos1->z) - mul16(s_clipPos1->y, s_clipPos0->z); - - const fixed16_16 dy = s_clipPos1->y - s_clipPos0->y; - const fixed16_16 dz = s_clipPos1->z - s_clipPos0->z; - s_clipParam1 = mul16(s_rcfState.yPlaneTop, dz) - dy; - - s_clipIntersectZ = s_clipParam0; - if (s_clipParam1 != 0) - { - s_clipIntersectZ = div16(s_clipParam0, s_clipParam1); - } - s_clipIntersectY = mul16(s_rcfState.yPlaneTop, s_clipIntersectZ); - const fixed16_16 aDz = TFE_Jedi::abs(s_clipPos1->z - s_clipPos0->z); - const fixed16_16 aDy = TFE_Jedi::abs(s_clipPos1->y - s_clipPos0->y); - - fixed16_16 p, p0, p1; - if (aDz > aDy) - { - p1 = s_clipPos1->z; - p0 = s_clipPos0->z; - p = s_clipIntersectZ; - } - else - { - p1 = s_clipPos1->y; - p0 = s_clipPos0->y; - p = s_clipIntersectY; - } - s_clipParam = div16(p - p0, p1 - p0); - - s_clipPosOut[outVertexCount].x = s_clipPos0->x + mul16(s_clipParam, s_clipPos1->x - s_clipPos0->x); - s_clipPosOut[outVertexCount].y = s_clipIntersectY; - s_clipPosOut[outVertexCount].z = s_clipIntersectZ; - - COMPUTE_CLIP_INTERSECTION(outVertexCount); - outVertexCount++; - } - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - } - - if (outVertexCount < 3) - { - return 0; - } - srcVertexCount = SWAP_CLIP_BUFFERS(outVertexCount); - outVertexCount = 0; - - /////////////////////////////////////////////////// - // Bottom Clip Plane - /////////////////////////////////////////////////// - for (s32 i = 0; i < srcVertexCount; i++) - { - s_clipY0 = mul16(s_rcfState.yPlaneBot, s_clipPos0->z); - s_clipY1 = mul16(s_rcfState.yPlaneBot, s_clipPos1->z); - - // If the edge is completely behind the plane, then continue. - if (s_clipPos0->y > s_clipY0 && s_clipPos1->y > s_clipY1) - { - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - - continue; - } - - // Add vertex 0 if it is inside the plane. - if (s_clipPos0->y < s_clipY0) - { - s_clipPosOut[outVertexCount] = *s_clipPos0; - - #if defined(CLIP_INTENSITY) - s_clipIntensityOut[outVertexCount] = *s_clipIntensity0; - #endif - #if defined(CLIP_UV) - s_clipUvOut[outVertexCount] = *s_clipUv0; - #endif - - outVertexCount++; - } - - // Skip clipping if either vertex is touching the plane. - if (s_clipPos0->y == s_clipY0 || s_clipPos1->y == s_clipY1) - { - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - - continue; - } - - // Clip the edge. - if (s_clipPos0->y > s_clipY0 || s_clipPos1->y > s_clipY1) - { - s_clipParam0 = mul16(s_clipPos0->y, s_clipPos1->z) - mul16(s_clipPos1->y, s_clipPos0->z); - - const fixed16_16 dy = s_clipPos1->y - s_clipPos0->y; - const fixed16_16 dz = s_clipPos1->z - s_clipPos0->z; - s_clipParam1 = mul16(s_rcfState.yPlaneBot, dz) - dy; - - s_clipIntersectZ = s_clipParam0; - if (s_clipParam1 != 0) - { - s_clipIntersectZ = div16(s_clipParam0, s_clipParam1); - } - s_clipIntersectY = mul16(s_rcfState.yPlaneBot, s_clipIntersectZ); - const fixed16_16 aDz = TFE_Jedi::abs(s_clipPos1->z - s_clipPos0->z); - const fixed16_16 aDy = TFE_Jedi::abs(s_clipPos1->y - s_clipPos0->y); - - fixed16_16 p, p0, p1; - if (aDz > aDy) - { - p1 = s_clipPos1->z; - p0 = s_clipPos0->z; - p = s_clipIntersectZ; - } - else - { - p1 = s_clipPos1->y; - p0 = s_clipPos0->y; - p = s_clipIntersectY; - } - s_clipParam = div16(p - p0, p1 - p0); - - s_clipPosOut[outVertexCount].x = s_clipPos0->x + mul16(s_clipParam, s_clipPos1->x - s_clipPos0->x); - s_clipPosOut[outVertexCount].y = s_clipIntersectY; - s_clipPosOut[outVertexCount].z = s_clipIntersectZ; - - COMPUTE_CLIP_INTERSECTION(outVertexCount); - outVertexCount++; - } - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - } - if (outVertexCount < 3) - { - return 0; - } - - if (pos != s_clipPosOut) - { - memcpy(pos, s_clipPosOut, outVertexCount * sizeof(vec3_fixed)); - #if defined(CLIP_INTENSITY) - memcpy(intensity, s_clipIntensityOut, outVertexCount * sizeof(fixed16_16)); - #endif - #if defined(CLIP_UV) - memcpy(uv, s_clipUvOut, outVertexCount * sizeof(vec2_fixed)); - #endif - } - // There is a corner case where 0 z is produced which causes crashes on Windows. - // (It is kind of weird that it doesn't affect DOS...) - for (s32 i = 0; i < outVertexCount; i++) - { - pos[i].z = max(pos[i].z, ONE_16); - } - return outVertexCount; -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_Clipping.cpp b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_Clipping.cpp deleted file mode 100644 index fccbd5e5..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_Clipping.cpp +++ /dev/null @@ -1,104 +0,0 @@ -#include - -#include -#include -#include - -#include "robj3dFixed_Clipping.h" -#include "robj3dFixed_PolygonSetup.h" -#include "../rclassicFixedSharedState.h" -#include "../../rcommon.h" -#ifdef TFE_ESPBOX -#define s_width (320) -#define s_height (200) -#endif - -namespace TFE_Jedi -{ - -namespace RClassic_Fixed -{ - ///////////////////////////////////////////// - // Clipping - ///////////////////////////////////////////// - static fixed16_16 s_clipIntensityBuffer[POLY_MAX_VTX_COUNT]; // a buffer to hold clipped/final intensities - static vec3_fixed s_clipPosBuffer[POLY_MAX_VTX_COUNT]; // a buffer to hold clipped/final positions - static vec2_fixed s_clipUvBuffer[POLY_MAX_VTX_COUNT]; // a buffer to hold clipped/final texture coordinates - - static fixed16_16 s_clipY0; - static fixed16_16 s_clipY1; - static fixed16_16 s_clipParam0; - static fixed16_16 s_clipParam1; - static fixed16_16 s_clipIntersectY; - static fixed16_16 s_clipIntersectZ; - static vec3_fixed* s_clipTempPos; - static fixed16_16 s_clipPlanePos0; - static fixed16_16 s_clipPlanePos1; - static fixed16_16* s_clipTempIntensity; - static fixed16_16* s_clipIntensitySrc; - static fixed16_16* s_clipIntensity0; - static fixed16_16* s_clipIntensity1; - static vec2_fixed* s_clipTempUv; - static vec2_fixed* s_clipUvSrc; - static vec2_fixed* s_clipUv0; - static vec2_fixed* s_clipUv1; - static fixed16_16 s_clipParam; - static fixed16_16 s_clipIntersectX; - static vec3_fixed* s_clipPos0; - static vec3_fixed* s_clipPos1; - static vec3_fixed* s_clipPosSrc; - static vec3_fixed* s_clipPosOut; - static fixed16_16* s_clipIntensityOut; - static vec2_fixed* s_clipUvOut; - - //////////////////////////////////////////////// - // Instantiate Clip Routines. - // This abuses C-Macros to build 4 versions of - // the clipping functions based on the defines. - // - // This avoids duplicating a lot of the code 4 - // times and is probably pretty similar to what - // the original developers did at the time. - // - // This is similar to modern shader variants. - //////////////////////////////////////////////// - // Position only - #include "robj3dFixed_ClipFunc.h" - - // Position, Intensity - #define CLIP_INTENSITY - #include "robj3dFixed_ClipFunc.h" - - // Position, UV - #define CLIP_UV - #undef CLIP_INTENSITY - #include "robj3dFixed_ClipFunc.h" - - // Position, UV, Intensity - #define CLIP_INTENSITY - #include "robj3dFixed_ClipFunc.h" - - s32 clipPolygon(JmPolygon* polygon) - { - s32 polyVertexCount = 0; - if (polygon->shading == PSHADE_GOURAUD) - { - polyVertexCount = robj3d_clipPolygonGouraud(s_polygonVerticesVS, s_polygonIntensity, polygon->vertexCount); - } - else if (polygon->shading == PSHADE_TEXTURE) - { - polyVertexCount = robj3d_clipPolygonUv(s_polygonVerticesVS, s_polygonUv, polygon->vertexCount); - } - else if (polygon->shading == PSHADE_GOURAUD_TEXTURE) - { - polyVertexCount = robj3d_clipPolygonUvGouraud(s_polygonVerticesVS, s_polygonUv, s_polygonIntensity, polygon->vertexCount); - } - else - { - polyVertexCount = robj3d_clipPolygon(s_polygonVerticesVS, polygon->vertexCount); - } - - return polyVertexCount; - } - -}} // TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_Clipping.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_Clipping.h deleted file mode 100644 index 529c681b..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_Clipping.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include "../../rlimits.h" - -namespace TFE_Jedi -{ - namespace RClassic_Fixed - { - s32 clipPolygon(JmPolygon* polygon); - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_Culling.cpp b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_Culling.cpp deleted file mode 100644 index dceaa891..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_Culling.cpp +++ /dev/null @@ -1,93 +0,0 @@ -#include -#include -#include - -#include "robj3dFixed_Culling.h" -#include "robj3dFixed_TransformAndLighting.h" -#include "../rclassicFixedSharedState.h" -#include "../../rcommon.h" -#ifdef TFE_ESPBOX -#define s_width (320) -#define s_height (200) -#endif - -namespace TFE_Jedi -{ - -namespace RClassic_Fixed -{ - enum - { - POLYGON_FRONT_FACING = 0, - POLYGON_BACK_FACING, - }; - - // List of potentially visible polygons (after backface culling). - std::vector s_visPolygons; - - s32 getPolygonFacing(const vec3_fixed* normal, const vec3_fixed* pos) - { - const vec3_fixed offset = { -pos->x, -pos->y, -pos->z }; - return dot(normal, &offset) < 0 ? POLYGON_BACK_FACING : POLYGON_FRONT_FACING; - } - - s32 robj3d_backfaceCull(JediModel* model) - { - vec3_fixed* polygonNormal = s_polygonNormalsVS.data(); - s32 polygonCount = model->polygonCount; - JmPolygon* polygon = model->polygons; - for (s32 i = 0; i < polygonCount; i++, polygonNormal++, polygon++) - { - vec3_fixed* vertex = &s_verticesVS[polygon->indices[1]]; - polygonNormal->x -= vertex->x; - polygonNormal->y -= vertex->y; - polygonNormal->z -= vertex->z; - } - - if (polygonCount > s_visPolygons.size()) - { - s_visPolygons.resize(polygonCount * 2); - } - - JmPolygon** visPolygon = s_visPolygons.data(); - s32 visPolygonCount = 0; - - polygon = model->polygons; - polygonNormal = s_polygonNormalsVS.data(); - for (s32 i = 0; i < model->polygonCount; i++, polygon++, polygonNormal++) - { - vec3_fixed* pos = &s_verticesVS[polygon->indices[1]]; - s32 facing = getPolygonFacing(polygonNormal, pos); - if (facing == POLYGON_BACK_FACING) { continue; } - - visPolygonCount++; - s32 vertexCount = polygon->vertexCount; - s32 zAve = 0; - - s32* indices = polygon->indices; - for (s32 v = 0; v < vertexCount; v++) - { - zAve += s_verticesVS[indices[v]].z; - } - -#ifdef TFE_ESPBOX - polygon->zAve = zAve / vertexCount; // Todo IS this ok? -#else - polygon->zAve = div16(zAve, intToFixed16(vertexCount)); -#endif - *visPolygon = polygon; - visPolygon++; - } - - return visPolygonCount; - } - -}} // TFE_Jedi -#ifdef TFE_ESPBOX -// Shutdown only: release this file's cached container storage so nothing is -// left in the 4MB ROM block when the session ends (see esp_alloc.cpp). -void espbox_release_robj3dCulling_caches() -{ - std::vector().swap(TFE_Jedi::RClassic_Fixed::s_visPolygons); -} -#endif diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_Culling.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_Culling.h deleted file mode 100644 index 1892ce59..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_Culling.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include - -namespace TFE_Jedi -{ - namespace RClassic_Fixed - { - extern std::vector s_visPolygons; - s32 robj3d_backfaceCull(JediModel* model); - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_PolyRenderFunc.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_PolyRenderFunc.h deleted file mode 100644 index c73f2057..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_PolyRenderFunc.h +++ /dev/null @@ -1,495 +0,0 @@ -////////////////////////////////////////////////////////////////////// -// Inline polygon render functions -////////////////////////////////////////////////////////////////////// - -#if defined(POLY_INTENSITY) && !defined(POLY_UV) -s32 robj3d_findNextEdgeI(s32 xMinIndex, s32 xMin) -#elif !defined(POLY_INTENSITY) && defined(POLY_UV) -s32 robj3d_findNextEdgeT(s32 xMinIndex, s32 xMin) -#elif defined(POLY_INTENSITY) && defined(POLY_UV) -s32 robj3d_findNextEdgeTI(s32 xMinIndex, s32 xMin) -#else -s32 robj3d_findNextEdge(s32 xMinIndex, s32 xMin) -#endif -{ - s32 prevScanlineLen = s_edgeTopLength; - s32 curIndex = xMinIndex; - - // The min and max indices should not match, otherwise it is an error. - if (xMinIndex == s_polyMaxIndex) - { - s_edgeTopLength = prevScanlineLen; - return -1; - } - - while (1) - { - s32 nextIndex = curIndex + 1; - if (nextIndex >= s_polyVertexCount) { nextIndex = 0; } - else if (nextIndex < 0) { nextIndex = s_polyVertexCount - 1; } - - vec3_fixed* cur = &s_polyProjVtx[curIndex]; - vec3_fixed* next = &s_polyProjVtx[nextIndex]; - s32 dx = next->x - cur->x; - if (next->x == s_maxScreenX_Pixels) - { - dx++; - } - - if (dx > 0) - { - s_edgeTopLength = dx; - -#ifdef TFE_ESPBOX - const fixed16_16 step = ONE_16 / dx; -#else - const fixed16_16 step = div16(ONE_16, intToFixed16(dx)); -#endif - s_edgeTopY0_Pixel = cur->y; - s_edgeTop_Y0 = intToFixed16(cur->y); - -#ifdef TFE_ESPBOX - const s32 dy = next->y - cur->y; - s_edgeTop_dYdX = dy * step; -#else - const fixed16_16 dy = intToFixed16(next->y - cur->y); - s_edgeTop_dYdX = mul16(dy, step); -#endif - - const fixed16_16 dz = next->z - cur->z; - s_edgeTop_dZdX = mul16(dz, step); - s_edgeTop_Z0 = cur->z; - - #if defined(POLY_INTENSITY) - s_edgeTop_I0 = clamp(s_polyIntensity[curIndex], 0, VSHADE_MAX_INTENSITY); - const fixed16_16 dI = s_polyIntensity[nextIndex] - s_edgeTop_I0; - s_edgeTop_dIdX = mul16(dI, step); - #endif - #if defined(POLY_UV) - s_edgeTop_Uv0 = s_polyUv[curIndex]; - const fixed16_16 dU = s_polyUv[nextIndex].x - s_edgeTop_Uv0.x; - const fixed16_16 dV = s_polyUv[nextIndex].z - s_edgeTop_Uv0.z; - s_edgeTop_dUVdX.x = mul16(dU, step); - s_edgeTop_dUVdX.z = mul16(dV, step); - #endif - - s_edgeTopIndex = nextIndex; - return 0; - } - else if (nextIndex == s_polyMaxIndex) - { - s_edgeTopLength = prevScanlineLen; - return -1; - } - curIndex = nextIndex; - } - - // This shouldn't be reached, but just in case. - s_edgeTopLength = prevScanlineLen; - return -1; -} - -#if defined(POLY_INTENSITY) && !defined(POLY_UV) -s32 robj3d_findPrevEdgeI(s32 minXIndex) -#elif !defined(POLY_INTENSITY) && defined(POLY_UV) -s32 robj3d_findPrevEdgeT(s32 minXIndex) -#elif defined(POLY_INTENSITY) && defined(POLY_UV) -s32 robj3d_findPrevEdgeTI(s32 minXIndex) -#else -s32 robj3d_findPrevEdge(s32 minXIndex) -#endif -{ - const s32 len = s_edgeBotLength; - s32 curIndex = minXIndex; - if (minXIndex == s_polyMaxIndex) - { - s_edgeBotLength = len; - return -1; - } - - while (1) - { - s32 prevIndex = curIndex - 1; - if (prevIndex >= s_polyVertexCount) { prevIndex = 0; } - else if (prevIndex < 0) { prevIndex = s_polyVertexCount - 1; } - - vec3_fixed* cur = &s_polyProjVtx[curIndex]; - vec3_fixed* prev = &s_polyProjVtx[prevIndex]; - s32 dx = prev->x - cur->x; - if (s_maxScreenX_Pixels == prev->x) - { - dx++; - } - - if (dx > 0) - { - s_edgeBotLength = dx; - -#ifdef TFE_ESPBOX - const fixed16_16 step = ONE_16 / dx; -#else - const fixed16_16 step = div16(ONE_16, intToFixed16(dx)); -#endif - s_edgeBotY0_Pixel = cur->y; - s_edgeBot_Y0 = intToFixed16(cur->y); - - const s32 dy = prev->y - cur->y; -#ifdef TFE_ESPBOX - s_edgeBot_dYdX = dy * step; -#else - s_edgeBot_dYdX = mul16(intToFixed16(dy), step); -#endif - - const fixed16_16 dz = prev->z - cur->z; -#ifdef TFE_ESPBOX - //s_edgeBot_dZdX = dz / dx; - s_edgeBot_dZdX = mul16(dz, step); -#else - s_edgeBot_dZdX = div16(dz, intToFixed16(dx)); -#endif - s_edgeBot_Z0 = cur->z; - - #if defined(POLY_INTENSITY) - s_edgeBot_I0 = clamp(s_polyIntensity[curIndex], 0, VSHADE_MAX_INTENSITY); - const fixed16_16 dI = s_polyIntensity[prevIndex] - s_edgeBot_I0; - s_edgeBot_dIdX = mul16(dI, step); - #endif - #if defined(POLY_UV) - s_edgeBot_Uv0 = s_polyUv[curIndex]; - const fixed16_16 dU = s_polyUv[prevIndex].x - s_edgeBot_Uv0.x; - const fixed16_16 dV = s_polyUv[prevIndex].z - s_edgeBot_Uv0.z; - s_edgeBot_dUVdX.x = mul16(dU, step); - s_edgeBot_dUVdX.z = mul16(dV, step); - #endif - - s_edgeBotIndex = prevIndex; - - return 0; - } - else - { - curIndex = prevIndex; - if (prevIndex == s_polyMaxIndex) - { - s_edgeBotLength = len; - return -1; - } - } - } - s_edgeBotLength = len; - return -1; -} - -#if !defined(POLY_INTENSITY) && !defined(POLY_UV) -void robj3d_drawColumnFlatColor() -{ - s32 end = s_columnHeight - 1; - s32 offset = end * s_width; - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - s_pcolumnOut[offset] = s_polyColorIndex; - } -} -#endif - -#if defined(POLY_INTENSITY) && !defined(POLY_UV) -void robj3d_drawColumnShadedColor() -{ - const u8* colorMap = s_polyColorMap; - - fixed16_16 intensity = s_col_I0; - u8 colorIndex = s_polyColorIndex; - s32 dither = s_dither; - - s32 end = s_columnHeight - 1; - s32 offset = end * s_width; - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - s32 pixelIntensity = floor16(intensity); - if (dither) - { - const fixed16_16 iOffset = intensity - s_ditherOffset; - if (iOffset >= 0) - { - pixelIntensity = floor16(iOffset); - } - } - s_pcolumnOut[offset] = colorMap[(pixelIntensity&31)*256 + colorIndex]; - - intensity += s_col_dIdY; - dither = !dither; - } -} -#endif - -#if !defined(POLY_INTENSITY) && defined(POLY_UV) -void robj3d_drawColumnFlatTexture() -{ - const u8* colorMap = &s_polyColorMap[s_polyColorIndex * 256]; - const u8* textureData = s_polyTexture->image; - const s32 texHeight = s_polyTexture->height; - const s32 texWidthMask = s_polyTexture->width - 1; - const s32 texHeightMask = texHeight - 1; - - fixed16_16 U = s_col_Uv0.x; - fixed16_16 V = s_col_Uv0.z; - s32 end = s_columnHeight - 1; - s32 offset = end * s_width; - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - const u8 colorIndex = textureData[(floor16(U)&texWidthMask)*texHeight + (floor16(V)&texHeightMask)]; - s_pcolumnOut[offset] = colorMap[colorIndex]; - - U += s_col_dUVdY.x; - V += s_col_dUVdY.z; - } -} -#endif - -#if defined(POLY_INTENSITY) && defined(POLY_UV) -void robj3d_drawColumnShadedTexture() -{ - const u8* colorMap = s_polyColorMap; - const u8* textureData = s_polyTexture->image; - const s32 texHeight = s_polyTexture->height; - const s32 texWidthMask = s_polyTexture->width - 1; - const s32 texHeightMask = texHeight - 1; - - fixed16_16 U = s_col_Uv0.x; - fixed16_16 V = s_col_Uv0.z; - fixed16_16 I = s_col_I0; - - s32 end = s_columnHeight - 1; - s32 offset = end * s_width; - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - const u8 colorIndex = textureData[(floor16(U)&texWidthMask)*texHeight + (floor16(V)&texHeightMask)]; - const s32 pixelIntensity = floor16(I)&31; - s_pcolumnOut[offset] = colorMap[pixelIntensity*256 + colorIndex]; - - I += s_col_dIdY; - U += s_col_dUVdY.x; - V += s_col_dUVdY.z; - } -} -#endif - -#undef FIND_NEXT_EDGE -#undef FIND_PREV_EDGE -#undef DRAW_COLUMN -#if defined(POLY_INTENSITY) && !defined(POLY_UV) -#define FIND_NEXT_EDGE robj3d_findNextEdgeI -#define FIND_PREV_EDGE robj3d_findPrevEdgeI -#define DRAW_COLUMN robj3d_drawColumnShadedColor -#elif !defined(POLY_INTENSITY) && defined(POLY_UV) -#define FIND_NEXT_EDGE robj3d_findNextEdgeT -#define FIND_PREV_EDGE robj3d_findPrevEdgeT -#define DRAW_COLUMN robj3d_drawColumnFlatTexture -#elif defined(POLY_INTENSITY) && defined(POLY_UV) -#define FIND_NEXT_EDGE robj3d_findNextEdgeTI -#define FIND_PREV_EDGE robj3d_findPrevEdgeTI -#define DRAW_COLUMN robj3d_drawColumnShadedTexture -#else -#define FIND_NEXT_EDGE robj3d_findNextEdge -#define FIND_PREV_EDGE robj3d_findPrevEdge -#define DRAW_COLUMN robj3d_drawColumnFlatColor -#endif - -#if defined(POLY_INTENSITY) && !defined(POLY_UV) -void robj3d_drawShadedColorPolygon(vec3_fixed* projVertices, fixed16_16* intensity, s32 vertexCount, u8 color) -#elif !defined(POLY_INTENSITY) && defined(POLY_UV) -void robj3d_drawFlatTexturePolygon(vec3_fixed* projVertices, vec2_fixed* uv, s32 vertexCount, TextureData* texture, u8 color) -#elif defined(POLY_INTENSITY) && defined(POLY_UV) -void robj3d_drawShadedTexturePolygon(vec3_fixed* projVertices, vec2_fixed* uv, fixed16_16* intensity, s32 vertexCount, TextureData* texture) -#else -void robj3d_drawFlatColorPolygon(vec3_fixed* projVertices, s32 vertexCount, u8 color) -#endif -{ - s32 xMax = INT_MIN; - s32 xMin = INT_MAX; - s_polyProjVtx = projVertices; - s_polyVertexCount = vertexCount; - - #if defined(POLY_INTENSITY) - s_polyIntensity = intensity; - #endif - #if defined(POLY_UV) - s_polyUv = uv; - s_polyTexture = texture; - #endif - - s32 yMax = xMax; - s32 yMin = xMin; - if (vertexCount <= 0) { return; } - - // Compute the 2D bounding box of the polygon. - // Track the extreme vertex indices in X. - s32 minXIndex; - vec3_fixed* projVertex = projVertices; - for (s32 i = 0; i < s_polyVertexCount; i++, projVertex++) - { - const s32 x = projVertex->x; - if (x < xMin) - { - xMin = x; - minXIndex = i; - } - if (x > xMax) - { - xMax = x; - s_polyMaxIndex = i; - } - - const s32 y = projVertex->y; - if (y < yMin) { yMin = y; } - if (y > yMax) { yMax = y; } - } - - // If the polygon is too small or off screen, skip it. - if (xMin >= xMax || yMin > s_windowMaxY_Pixels || yMax < s_windowMinY_Pixels) { return; } - - assert(s_colorMap); - s_polyColorMap = s_colorMap; - #if !(defined(POLY_INTENSITY) && defined(POLY_UV)) - s_polyColorIndex = color; - #endif - #if defined(POLY_INTENSITY) && !defined(POLY_UV) - s_ditherOffset = HALF_16; - #endif - s_columnX = xMin; - - if (FIND_NEXT_EDGE(minXIndex, xMin) != 0 || FIND_PREV_EDGE(minXIndex) != 0) { return; } - - for (s32 foundEdge = 0; !foundEdge && s_columnX >= s_minScreenX_Pixels && s_columnX <= s_maxScreenX_Pixels; s_columnX++) - { - const fixed16_16 edgeMinZ = min(s_edgeBot_Z0, s_edgeTop_Z0); - const fixed16_16 z = s_rcfState.depth1d[s_columnX]; - - // Is ave edge Z occluded by walls? Is column outside of the vertical area? - if (edgeMinZ < z && s_edgeTopY0_Pixel <= s_windowMaxY_Pixels && s_edgeBotY0_Pixel >= s_windowMinY_Pixels) - { - const s32 winTop = s_objWindowTop[s_columnX]; - const s32 winBot = s_objWindowBot[s_columnX]; - s32 y0_Top = s_edgeTopY0_Pixel; - s32 y0_Bot = s_edgeBotY0_Pixel; - #if defined(POLY_INTENSITY) || defined(POLY_UV) - fixed16_16 yOffset = 0; - #endif - - if (y0_Top < winTop) - { - y0_Top = winTop; - } - if (y0_Bot > winBot) - { - #if defined(POLY_INTENSITY) || defined(POLY_UV) -#ifdef TFE_ESPBOX - yOffset = y0_Bot - winBot; -#else - yOffset = intToFixed16(y0_Bot - winBot); -#endif - #endif - y0_Bot = winBot; - } - - s_columnHeight = y0_Bot - y0_Top + 1; - if (s_columnHeight > 0) - { -#ifdef TFE_ESPBOX - const s32 height = s_edgeBotY0_Pixel - s_edgeTopY0_Pixel + 1; -#else - const fixed16_16 height = intToFixed16(s_edgeBotY0_Pixel - s_edgeTopY0_Pixel + 1); -#endif - s_pcolumnOut = &s_display[y0_Top*s_width + s_columnX]; - - #if defined(POLY_INTENSITY) -#ifdef TFE_ESPBOX - s_col_dIdY = (s_edgeTop_I0 - s_edgeBot_I0) / height; -#else - s_col_dIdY = div16(s_edgeTop_I0 - s_edgeBot_I0, height); -#endif - s_col_I0 = s_edgeBot_I0; - if (yOffset) - { -#ifdef TFE_ESPBOX - s_col_I0 += yOffset * s_col_dIdY; -#else - s_col_I0 += mul16(yOffset, s_col_dIdY); -#endif - } - s_dither = ((s_columnX & 1) ^ (y0_Bot & 1)) - 1; - #endif - - #if defined(POLY_UV) -#ifdef TFE_ESPBOX - /* - s_col_dUVdY.x = (s_edgeTop_Uv0.x - s_edgeBot_Uv0.x) / height; - s_col_dUVdY.z = (s_edgeTop_Uv0.z - s_edgeBot_Uv0.z) / height; - */ - const fixed16_16 rcpHeight = ONE_16 / height; - s_col_dUVdY.x = mul16(s_edgeTop_Uv0.x - s_edgeBot_Uv0.x, rcpHeight); - s_col_dUVdY.z = mul16(s_edgeTop_Uv0.z - s_edgeBot_Uv0.z, rcpHeight); -#else - s_col_dUVdY.x = div16(s_edgeTop_Uv0.x - s_edgeBot_Uv0.x, height); - s_col_dUVdY.z = div16(s_edgeTop_Uv0.z - s_edgeBot_Uv0.z, height); -#endif - s_col_Uv0 = s_edgeBot_Uv0; - if (yOffset) - { -#ifdef TFE_ESPBOX - s_col_Uv0.x += yOffset * s_col_dUVdY.x; - s_col_Uv0.z += yOffset * s_col_dUVdY.z; -#else - s_col_Uv0.x += mul16(yOffset, s_col_dUVdY.x); - s_col_Uv0.z += mul16(yOffset, s_col_dUVdY.z); -#endif - } - #endif - - DRAW_COLUMN(); - } - } - - s_edgeTopLength--; - if (s_edgeTopLength <= 0) - { - foundEdge = FIND_NEXT_EDGE(s_edgeTopIndex, s_columnX); - } - else - { - #if defined(POLY_INTENSITY) - s_edgeTop_I0 = clamp(s_edgeTop_I0 + s_edgeTop_dIdX, 0, VSHADE_MAX_INTENSITY); - #endif - #if defined(POLY_UV) - s_edgeTop_Uv0.x += s_edgeTop_dUVdX.x; - s_edgeTop_Uv0.z += s_edgeTop_dUVdX.z; - #endif - - s_edgeTop_Y0 += s_edgeTop_dYdX; - s_edgeTop_Z0 += s_edgeTop_dZdX; - s_edgeTopY0_Pixel = round16(s_edgeTop_Y0); - } - if (foundEdge == 0) - { - s_edgeBotLength--; - if (s_edgeBotLength <= 0) - { - foundEdge = FIND_PREV_EDGE(s_edgeBotIndex); - } - else - { - #if defined(POLY_INTENSITY) - s_edgeBot_I0 = clamp(s_edgeBot_I0 + s_edgeBot_dIdX, 0, VSHADE_MAX_INTENSITY); - #endif - #if defined(POLY_UV) - s_edgeBot_Uv0.x += s_edgeBot_dUVdX.x; - s_edgeBot_Uv0.z += s_edgeBot_dUVdX.z; - #endif - - s_edgeBot_Y0 += s_edgeBot_dYdX; - s_edgeBot_Z0 += s_edgeBot_dZdX; - s_edgeBotY0_Pixel = round16(s_edgeBot_Y0); - } - } - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_PolygonDraw.cpp b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_PolygonDraw.cpp deleted file mode 100644 index 1645a103..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_PolygonDraw.cpp +++ /dev/null @@ -1,470 +0,0 @@ -#include - -#include -#include -#include -#include -#include - -#include "robj3dFixed_TransformAndLighting.h" -#include "robj3dFixed_PolygonSetup.h" -#include "robj3dFixed_Clipping.h" -#include "../rsectorFixed.h" -#include "../rflatFixed.h" -#include "../rclassicFixedSharedState.h" -#include "../rlightingFixed.h" -#include "../../rcommon.h" -#ifdef TFE_ESPBOX -#define s_width (320) -#define s_height (200) -#endif - -namespace TFE_Jedi -{ - -namespace RClassic_Fixed -{ - //////////////////////////////////////////////// - // Polygon Drawing - //////////////////////////////////////////////// - // Polygon - static u8 s_polyColorIndex; - static s32 s_polyVertexCount; - static s32 s_polyMaxIndex; - static fixed16_16* s_polyIntensity; - static vec2_fixed* s_polyUv; - static vec3_fixed* s_polyProjVtx; - static const u8* s_polyColorMap; - static TextureData* s_polyTexture; - - // Column - static s32 s_columnX; - static s32 s_rowY; - static s32 s_columnHeight; - static s32 s_dither; - static u8* s_pcolumnOut; - - static fixed16_16 s_col_I0; - static fixed16_16 s_col_dIdY; - static vec2_fixed s_col_Uv0; - static vec2_fixed s_col_dUVdY; - - // Polygon Edges - static fixed16_16 s_ditherOffset; - // Bottom Edge - static fixed16_16 s_edgeBot_Z0; - static fixed16_16 s_edgeBot_dZdX; - static fixed16_16 s_edgeBot_dIdX; - static fixed16_16 s_edgeBot_I0; - static vec2_fixed s_edgeBot_dUVdX; - static vec2_fixed s_edgeBot_Uv0; - static fixed16_16 s_edgeBot_dYdX; - static fixed16_16 s_edgeBot_Y0; - // Top Edge - static fixed16_16 s_edgeTop_dIdX; - static vec2_fixed s_edgeTop_dUVdX; - static vec2_fixed s_edgeTop_Uv0; - static fixed16_16 s_edgeTop_dYdX; - static fixed16_16 s_edgeTop_Z0; - static fixed16_16 s_edgeTop_Y0; - static fixed16_16 s_edgeTop_dZdX; - static fixed16_16 s_edgeTop_I0; - // Left Edge - static fixed16_16 s_edgeLeft_X0; - static fixed16_16 s_edgeLeft_Z0; - static fixed16_16 s_edgeLeft_dXdY; - static fixed16_16 s_edgeLeft_dZmdY; - // Right Edge - static fixed16_16 s_edgeRight_X0; - static fixed16_16 s_edgeRight_Z0; - static fixed16_16 s_edgeRight_dXdY; - static fixed16_16 s_edgeRight_dZmdY; - // Edge Pixels & Indices - static s32 s_edgeBotY0_Pixel; - static s32 s_edgeTopY0_Pixel; - static s32 s_edgeLeft_X0_Pixel; - static s32 s_edgeRight_X0_Pixel; - static s32 s_edgeBotIndex; - static s32 s_edgeTopIndex; - static s32 s_edgeLeftIndex; - static s32 s_edgeRightIndex; - static s32 s_edgeTopLength; - static s32 s_edgeBotLength; - static s32 s_edgeLeftLength; - static s32 s_edgeRightLength; - - u8 robj3d_computePolygonColor(vec3_fixed* normal, u8 color, fixed16_16 z) - { - if (s_sectorAmbient >= MAX_LIGHT_LEVEL) { return color; } - s_polyColorMap = s_colorMap; - - s32 lightLevel = 0; - - fixed16_16 lighting = 0; - for (s32 i = 0; i < s_lightCount; i++) - { - const CameraLight* light = &s_cameraLight[i]; - const s32 L = dot(normal, &light->lightVS); - - if (L > 0) - { - const fixed16_16 brightness = mul16(light->brightness, VSHADE_MAX_INTENSITY); - lighting += mul16(L, brightness); - } - } - lightLevel += floor16(mul16(lighting, s_sectorAmbientFraction)); - if (lightLevel >= 31) { return color; } - - if (s_worldAmbient < 31 || s_cameraLightSource) - { - const s32 depthScaled = min(s32(z >> 14), 127); - const s32 cameraSource = MAX_LIGHT_LEVEL - (s_lightSourceRamp[depthScaled] + s_worldAmbient); - if (cameraSource > 0) - { - lightLevel += cameraSource; - } - } - lightLevel = max(lightLevel, s_sectorAmbient); - - z = max(z, 0); - const s32 falloff = (z >> LIGHT_ATTEN0) + (z >> LIGHT_ATTEN1); - lightLevel = max(lightLevel - falloff, s_scaledAmbient); - - if (lightLevel >= 31) { return color; } - if (lightLevel <= 0) { return s_polyColorMap[color]; } - - return s_polyColorMap[lightLevel*256 + color]; - } - - u8 robj3d_computePolygonLightLevel(vec3_fixed* normal, fixed16_16 z) - { - if (s_sectorAmbient >= 31) { return 31; } - s32 lightLevel = 0; - - fixed16_16 lighting = 0; - for (s32 i = 0; i < s_lightCount; i++) - { - const CameraLight* light = &s_cameraLight[i]; - const s32 L = dot(normal, &light->lightVS); - - if (L > 0) - { - const fixed16_16 brightness = mul16(light->brightness, VSHADE_MAX_INTENSITY); - lighting += mul16(L, brightness); - } - } - lightLevel += floor16(mul16(lighting, s_sectorAmbientFraction)); - if (lightLevel >= 31) { return 31; } - - if (s_worldAmbient < 31 || s_cameraLightSource) - { - const s32 depthScaled = min(s32(z >> 14), 127); - const s32 cameraSource = MAX_LIGHT_LEVEL - (s_lightSourceRamp[depthScaled] + s_worldAmbient); - if (cameraSource > 0) - { - lightLevel += cameraSource; - } - } - lightLevel = max(lightLevel, s_sectorAmbient); - - z = max(z, 0); - const s32 falloff = (z >> LIGHT_ATTEN0) + (z >> LIGHT_ATTEN1); - lightLevel = max(lightLevel - falloff, s_scaledAmbient); - - return clamp(lightLevel, 0, MAX_LIGHT_LEVEL); - } - - //////////////////////////////////////////////// - // Instantiate Polygon Draw Routines. - // This abuses C-Macros to build 4 versions of - // the drawing functions based on the defines. - // - // This avoids duplicating a lot of the code 4 - // times and is probably pretty similar to what - // the original developers did at the time. - // - // This is similar to modern shader variants. - //////////////////////////////////////////////// - // Flat color - #include "robj3dFixed_PolyRenderFunc.h" - - // Shaded - #define POLY_INTENSITY - #include "robj3dFixed_PolyRenderFunc.h" - - // Flat Texture - #define POLY_UV - #undef POLY_INTENSITY - #include "robj3dFixed_PolyRenderFunc.h" - - // Shaded Texture - #define POLY_INTENSITY - #include "robj3dFixed_PolyRenderFunc.h" - - //////////////////////////////////////////// - // Polygon Draw Routine for Shading = PLANE - // and support functions. - //////////////////////////////////////////// - s32 robj3d_findRightEdge(s32 minIndex) - { - s32 len = s_edgeRightLength; - if (minIndex == s_polyMaxIndex) - { - s_edgeRightLength = len; - return -1; - } - - s32 curIndex = minIndex; - while (1) - { - s32 nextIndex = curIndex + 1; - if (nextIndex >= s_polyVertexCount) { nextIndex = 0; } - else if (nextIndex < 0) { nextIndex = s_polyVertexCount - 1; } - - const vec3_fixed* cur = &s_polyProjVtx[curIndex]; - const vec3_fixed* next = &s_polyProjVtx[nextIndex]; - const s32 y0 = cur->y; - const s32 y1 = next->y; - - s32 dy = y1 - y0; - if (y1 == s_maxScreenY) { dy++; } - - if (dy > 0) - { - const s32 x0 = cur->x; - const s32 x1 = next->x; - const fixed16_16 dX = intToFixed16(x1 - x0); -#ifdef TFE_ESPBOX - const fixed16_16 dXdY = dX / dy; -#else - const fixed16_16 dY = intToFixed16(dy); - const fixed16_16 dXdY = div16(dX, dY); -#endif - - s_edgeRight_X0_Pixel = x0; - s_edgeRight_X0 = intToFixed16(x0); - s_edgeRightLength = dy; - - s_edgeRight_dXdY = dXdY; - s_edgeRight_Z0 = cur->z; - -#ifdef TFE_ESPBOX - s_edgeRight_dZmdY = (next->z - cur->z) * dy; -#else - s_edgeRight_dZmdY = mul16(next->z - cur->z, dY); -#endif - s_edgeRightIndex = nextIndex; - return 0; - } - else - { - curIndex = nextIndex; - if (nextIndex == s_polyMaxIndex) - { - break; - } - } - } - - s_edgeRightLength = len; - return -1; - } - - s32 robj3d_findLeftEdge(s32 minIndex) - { - s32 len = s_edgeLeftLength; - if (minIndex == s_polyMaxIndex) - { - s_edgeLeftLength = len; - return -1; - } - - s32 curIndex = minIndex; - while (1) - { - s32 prevIndex = curIndex - 1; - if (prevIndex >= s_polyVertexCount) { prevIndex = 0; } - else if (prevIndex < 0) { prevIndex = s_polyVertexCount - 1; } - - const vec3_fixed* cur = &s_polyProjVtx[curIndex]; - const vec3_fixed* prev = &s_polyProjVtx[prevIndex]; - const s32 y0 = cur->y; - const s32 y1 = prev->y; - - s32 dy = y1 - y0; - if (y1 == s_maxScreenY) { dy++; } - - if (dy > 0) - { - const s32 x0 = cur->x; - const s32 x1 = prev->x; - const fixed16_16 dX = intToFixed16(x1 - x0); -#ifdef TFE_ESPBOX - const fixed16_16 dXdY = dX / dy; -#else - const fixed16_16 dY = intToFixed16(dy); - const fixed16_16 dXdY = div16(dX, dY); -#endif - - s_edgeLeft_X0_Pixel = x0; - s_edgeLeft_X0 = intToFixed16(x0); - s_edgeLeftLength = dy; - - s_edgeLeft_dXdY = dXdY; - s_edgeLeft_Z0 = cur->z; - -#ifdef TFE_ESPBOX - s_edgeLeft_dZmdY = (prev->z - cur->z) * dy; -#else - s_edgeLeft_dZmdY = mul16(prev->z - cur->z, dY); -#endif - s_edgeLeftIndex = prevIndex; - return 0; - } - else - { - curIndex = prevIndex; - if (prevIndex == s_polyMaxIndex) - { - break; - } - } - } - - s_edgeLeftLength = len; - return -1; - } - - void robj3d_drawPlaneTexturePolygon(vec3_fixed* projVertices, s32 vertexCount, TextureData* texture, fixed16_16 planeY, fixed16_16 ceilOffsetX, fixed16_16 ceilOffsetZ, fixed16_16 floorOffsetX, fixed16_16 floorOffsetZ) - { - if (vertexCount <= 0) { return; } - - s32 yMin = INT_MAX; - s32 yMax = INT_MIN; - s32 minIndex = 0; - - s_polyProjVtx = projVertices; - s_polyVertexCount = vertexCount; - - vec3_fixed* vertex = projVertices; - for (s32 i = 0; i < s_polyVertexCount; i++, vertex++) - { - if (vertex->y < yMin) - { - yMin = vertex->y; - minIndex = i; - } - if (vertex->y > yMax) - { - yMax = vertex->y; - s_polyMaxIndex = i; - } - } - if (yMin >= yMax || yMin > s_windowMaxY_Pixels || yMax < s_windowMinY_Pixels) - { - return; - } - - bool trans = (texture->flags & OPACITY_TRANS) != 0; - s_rowY = yMin; - - if (robj3d_findLeftEdge(minIndex) != 0 || robj3d_findRightEdge(minIndex) != 0) - { - return; - } - - fixed16_16 heightOffset = planeY - s_rcfState.eyeHeight; - // TODO: Figure out why s_heightInPixels has the wrong sign here. - if (yMax <= s_screenYMidFix) - { - flat_preparePolygon(heightOffset, ceilOffsetX, ceilOffsetZ, texture); - } - else - { - flat_preparePolygon(heightOffset, floorOffsetX, floorOffsetZ, texture); - } - - s32 edgeFound = 0; - for (; edgeFound == 0 && s_rowY <= s_maxScreenY; s_rowY++) - { - if (s_rowY >= s_windowMinY_Pixels && s_windowMaxY_Pixels != 0 && s_edgeLeft_X0_Pixel <= s_windowMaxX_Pixels && s_edgeRight_X0_Pixel >= s_windowMinX_Pixels) - { - flat_drawPolygonScanline(s_edgeLeft_X0_Pixel, s_edgeRight_X0_Pixel, s_rowY, trans); - } - - s_edgeLeftLength--; - if (s_edgeLeftLength <= 0) - { - if (robj3d_findLeftEdge(s_edgeLeftIndex) != 0) { return; } - } - else - { - s_edgeLeft_X0 += s_edgeLeft_dXdY; - s_edgeLeft_Z0 += s_edgeLeft_dZmdY; - s_edgeLeft_X0_Pixel = round16(s_edgeLeft_X0); - - // Right Z0 increment in the wrong place again. - // TODO: Figure out the consequences of this bug. - //s_edgeRight_Z0 += s_edgeRight_dZmdY; - } - s_edgeRightLength--; - if (s_edgeRightLength <= 0) - { - if (robj3d_findRightEdge(s_edgeRightIndex) != 0) { return; } - } - else - { - s_edgeRight_X0 += s_edgeRight_dXdY; - s_edgeRight_X0_Pixel = round16(s_edgeRight_X0); - - // This is the proper place for this. - s_edgeRight_Z0 += s_edgeRight_dZmdY; - } - } - } - - void robj3d_drawPolygon(JmPolygon* polygon, s32 polyVertexCount, SecObject* obj, JediModel* model) - { - switch (polygon->shading) - { - case PSHADE_FLAT: - { - u8 color = polygon->color; - if (s_enableFlatShading) - { - color = robj3d_computePolygonColor(&s_polygonNormalsVS[polygon->index], color, polygon->zAve); - } - robj3d_drawFlatColorPolygon(s_polygonVerticesProj, polyVertexCount, color); - } break; - case PSHADE_GOURAUD: - { - robj3d_drawShadedColorPolygon(s_polygonVerticesProj, s_polygonIntensity, polyVertexCount, polygon->color); - } break; - case PSHADE_TEXTURE: - { - u8 lightLevel = 0; - if (s_enableFlatShading) - { - lightLevel = robj3d_computePolygonLightLevel(&s_polygonNormalsVS[polygon->index], polygon->zAve); - } - robj3d_drawFlatTexturePolygon(s_polygonVerticesProj, s_polygonUv, polyVertexCount, polygon->texture, lightLevel); - } break; - case PSHADE_GOURAUD_TEXTURE: - { - robj3d_drawShadedTexturePolygon(s_polygonVerticesProj, s_polygonUv, s_polygonIntensity, polyVertexCount, polygon->texture); - } break; - case PSHADE_PLANE: - { - const RSector* sector = obj->sector; - const fixed16_16 planeY = model->vertices[polygon->indices[0]].y + obj->posWS.y; - robj3d_drawPlaneTexturePolygon(s_polygonVerticesProj, polyVertexCount, polygon->texture, planeY, sector->ceilOffset.x, sector->ceilOffset.z, sector->floorOffset.x, sector->floorOffset.z); - } break; - default: - { - TFE_System::logWrite(LOG_ERROR, "Object3D Render Fixed", "Invalid shading mode: %d", polygon->shading); - assert(0); - } - } - } - -}} // TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_PolygonDraw.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_PolygonDraw.h deleted file mode 100644 index 6fcb8bcb..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_PolygonDraw.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include -#include "../../rlimits.h" - -namespace TFE_Jedi -{ - namespace RClassic_Fixed - { - void robj3d_drawPolygon(JmPolygon* polygon, s32 polyVertexCount, SecObject* obj, JediModel* model); - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_PolygonSetup.cpp b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_PolygonSetup.cpp deleted file mode 100644 index 0a55d34d..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_PolygonSetup.cpp +++ /dev/null @@ -1,59 +0,0 @@ -#include -#include -#include - -#include "robj3dFixed_PolygonSetup.h" -#include "robj3dFixed_TransformAndLighting.h" -#include "../rclassicFixedSharedState.h" - -namespace TFE_Jedi -{ - -namespace RClassic_Fixed -{ - vec3_fixed s_polygonVerticesVS[POLY_MAX_VTX_COUNT]; - vec3_fixed s_polygonVerticesProj[POLY_MAX_VTX_COUNT]; - vec2_fixed s_polygonUv[POLY_MAX_VTX_COUNT]; - fixed16_16 s_polygonIntensity[POLY_MAX_VTX_COUNT]; - - void robj3d_setupPolygon(JmPolygon* polygon) - { - // Copy polygon vertices. - for (s32 v = 0; v < polygon->vertexCount; v++) - { - s_polygonVerticesVS[v] = s_verticesVS[polygon->indices[v]]; - } - - // Copy uvs if required. - if (polygon->shading & PSHADE_TEXTURE) - { - const vec2_fixed* uv = (vec2_fixed*)polygon->uv; - const vec2_fixed zero = { 0 }; - if (uv) - { - for (s32 v = 0; v < polygon->vertexCount; v++) - { - s_polygonUv[v] = uv[v]; - } - } - else - { - for (s32 v = 0; v < polygon->vertexCount; v++) - { - s_polygonUv[v] = zero; - } - } - } - - // Copy intensities if required. - if (polygon->shading & PSHADE_GOURAUD) - { - const s32* indices = polygon->indices; - for (s32 v = 0; v < polygon->vertexCount; v++) - { - s_polygonIntensity[v] = s_vertexIntensity[indices[v]]; - } - } - } - -}} // TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_PolygonSetup.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_PolygonSetup.h deleted file mode 100644 index 410a9673..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_PolygonSetup.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include - -#define POLY_MAX_VTX_COUNT 32 - -namespace TFE_Jedi -{ - namespace RClassic_Fixed - { - extern vec3_fixed s_polygonVerticesVS[POLY_MAX_VTX_COUNT]; - extern vec3_fixed s_polygonVerticesProj[POLY_MAX_VTX_COUNT]; - extern vec2_fixed s_polygonUv[POLY_MAX_VTX_COUNT]; - extern fixed16_16 s_polygonIntensity[POLY_MAX_VTX_COUNT]; - - void robj3d_setupPolygon(JmPolygon* polygon); - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_TransformAndLighting.cpp b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_TransformAndLighting.cpp deleted file mode 100644 index 0b9d8d81..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_TransformAndLighting.cpp +++ /dev/null @@ -1,183 +0,0 @@ -#include -#include -#include -#include "robj3dFixed_TransformAndLighting.h" -#include "../rclassicFixedSharedState.h" -#include "../rlightingFixed.h" -#include "../../rcommon.h" -#ifdef TFE_ESPBOX -#define s_width (320) -#define s_height (200) -#endif - -namespace TFE_Jedi -{ - -namespace RClassic_Fixed -{ - ///////////////////////////////////////////// - // Settings - ///////////////////////////////////////////// - s32 s_enableFlatShading = 1; // Set to 0 to disable flat shading. - - ///////////////////////////////////////////// - // Vertex Processing - ///////////////////////////////////////////// - // TFE: Model limits have been lifted, requiring some changes. - // Vertex attributes transformed to viewspace. - std::vector s_verticesVS; - std::vector s_vertexNormalsVS; - // Vertex Lighting. - std::vector s_vertexIntensity; - - ///////////////////////////////////////////// - // Polygon Processing - ///////////////////////////////////////////// - // Polygon normals in viewspace (used for culling). - std::vector s_polygonNormalsVS; - - void robj3d_transformVertices(s32 vertexCount, vec3_fixed* vtxIn, s32* xform, vec3_fixed* offset, vec3_fixed* vtxOut) - { - for (s32 v = 0; v < vertexCount; v++, vtxOut++, vtxIn++) - { - vtxOut->x = mul16(vtxIn->x, xform[0]) + mul16(vtxIn->y, xform[3]) + mul16(vtxIn->z, xform[6]) + offset->x; - vtxOut->y = mul16(vtxIn->x, xform[1]) + mul16(vtxIn->y, xform[4]) + mul16(vtxIn->z, xform[7]) + offset->y; - vtxOut->z = mul16(vtxIn->x, xform[2]) + mul16(vtxIn->y, xform[5]) + mul16(vtxIn->z, xform[8]) + offset->z; - } - } - - fixed16_16 robj3d_dotProduct(const vec3_fixed* pos, const vec3_fixed* normal, const vec3_fixed* dir) - { - fixed16_16 nx = normal->x - pos->x; - fixed16_16 ny = normal->y - pos->y; - fixed16_16 nz = normal->z - pos->z; - - fixed16_16 dx = dir->x - pos->x; - fixed16_16 dy = dir->y - pos->y; - fixed16_16 dz = dir->z - pos->z; - - fixed16_16 ndx = mul16(nx, dx); - fixed16_16 ndy = mul16(ny, dy); - fixed16_16 ndz = mul16(nz, dz); - - return ndx + ndy + ndz; - } - - void robj3d_shadeVertices(s32 vertexCount, fixed16_16* outShading, const vec3_fixed* vertices, const vec3_fixed* normals) - { - const vec3_fixed* normal = normals; - const vec3_fixed* vertex = vertices; - for (s32 i = 0; i < vertexCount; i++, normal++, vertex++, outShading++) - { - fixed16_16 intensity = 0; - if (s_sectorAmbient >= 31) - { - intensity = VSHADE_MAX_INTENSITY; - } - else - { - // Lighting - fixed16_16 lightIntensity = 0; - for (s32 i = 0; i < s_lightCount; i++) - { - const CameraLight* light = &s_cameraLight[i]; - const vec3_fixed dir = - { - vertex->x + light->lightVS.x, - vertex->y + light->lightVS.y, - vertex->z + light->lightVS.z - }; - - const fixed16_16 I = robj3d_dotProduct(vertex, normal, &dir); - if (I > 0) - { - fixed16_16 source = light->brightness; - fixed16_16 sourceIntensity = mul16(VSHADE_MAX_INTENSITY, source); - lightIntensity += mul16(I, sourceIntensity); - } - } - intensity += mul16(lightIntensity, s_sectorAmbientFraction); - - // Distance falloff - const fixed16_16 z = max(0, vertex->z); - if (s_worldAmbient < 31 || s_cameraLightSource) - { - const s32 depthScaled = min(s32(z >> 14), 127); - const s32 cameraSource = MAX_LIGHT_LEVEL - (s_lightSourceRamp[depthScaled] + s_worldAmbient); - if (cameraSource > 0) - { - intensity += intToFixed16(cameraSource); - } - } - intensity = max(intensity, intToFixed16(s_sectorAmbient)); - - const s32 falloff = (z >> LIGHT_ATTEN0) + (z >> LIGHT_ATTEN1); - intensity = max(intensity - falloff, s_scaledAmbient); - intensity = clamp(intensity, 0, VSHADE_MAX_INTENSITY); - } - *outShading = intensity; - } - } - - void robj3d_allocateBuffers(JediModel* model) - { - if (model->vertexCount > s_verticesVS.size()) - { - s_verticesVS.resize(model->vertexCount); - s_vertexNormalsVS.resize(model->vertexCount); - s_vertexIntensity.resize(model->vertexCount); - } - if (model->polygonCount > s_polygonNormalsVS.size()) - { - s_polygonNormalsVS.resize(model->polygonCount); - } - } - - void robj3d_transformAndLight(SecObject* obj, JediModel* model) - { - vec3_fixed offsetWS; - offsetWS.x = obj->posWS.x - s_rcfState.cameraPos.x; - offsetWS.y = obj->posWS.y - s_rcfState.eyeHeight; - offsetWS.z = obj->posWS.z - s_rcfState.cameraPos.z; - - // Allocate buffer space. - robj3d_allocateBuffers(model); - - // Calculate the view space object camera offset. - vec3_fixed offsetVS; - rotateVectorM3x3(&offsetWS, &offsetVS, s_rcfState.cameraMtx); - - // Concatenate the camera and object rotation matrices. - fixed16_16 xform[9]; - mulMatrix3x3(s_rcfState.cameraMtx, obj->transform, xform); - - // Transform model vertices into view space. - robj3d_transformVertices(model->vertexCount, (vec3_fixed*)model->vertices, xform, &offsetVS, s_verticesVS.data()); - - // No need for polygon normals or lighting if MFLAG_DRAW_VERTICES is set. - if (model->flags & MFLAG_DRAW_VERTICES) { return; } - - // Polygon normals (used for backface culling) - robj3d_transformVertices(model->polygonCount, (vec3_fixed*)model->polygonNormals, xform, &offsetVS, s_polygonNormalsVS.data()); - - // Lighting - if (model->flags & MFLAG_VERTEX_LIT) - { - robj3d_transformVertices(model->vertexCount, (vec3_fixed*)model->vertexNormals, xform, &offsetVS, s_vertexNormalsVS.data()); - robj3d_shadeVertices(model->vertexCount, s_vertexIntensity.data(), s_verticesVS.data(), s_vertexNormalsVS.data()); - } - } - -}} // TFE_Jedi -#ifdef TFE_ESPBOX -// Shutdown only: release this file's cached container storage so nothing is -// left in the 4MB ROM block when the session ends (see esp_alloc.cpp). -void espbox_release_robj3d_caches() -{ - using namespace TFE_Jedi; - std::vector().swap(RClassic_Fixed::s_verticesVS); - std::vector().swap(RClassic_Fixed::s_vertexNormalsVS); - std::vector().swap(RClassic_Fixed::s_vertexIntensity); - std::vector().swap(RClassic_Fixed::s_polygonNormalsVS); -} -#endif diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_TransformAndLighting.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_TransformAndLighting.h deleted file mode 100644 index e223146d..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/robj3d_fixed/robj3dFixed_TransformAndLighting.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -struct SecObject; - -#define VSHADE_MAX_INTENSITY (31 * ONE_16) - -namespace TFE_Jedi -{ - namespace RClassic_Fixed - { - extern s32 s_enableFlatShading; - // Vertex attributes transformed to viewspace. - extern std::vector s_verticesVS; - extern std::vector s_vertexNormalsVS; - // Vertex Lighting. - extern std::vector s_vertexIntensity; - // Polygon normals in viewspace (used for culling). - extern std::vector s_polygonNormalsVS; - - void robj3d_transformAndLight(SecObject* obj, JediModel* model); - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rsectorFixed.cpp b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rsectorFixed.cpp deleted file mode 100644 index 6c3de847..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rsectorFixed.cpp +++ /dev/null @@ -1,667 +0,0 @@ -#include - -#include -#include -#include -#include -#include -#include -#include - -#include "rclassicFixed.h" -#include "rsectorFixed.h" -#include "rflatFixed.h" -#include "rlightingFixed.h" -#include "redgePairFixed.h" -#include "rclassicFixedSharedState.h" -#include "robj3d_fixed/robj3dFixed.h" -#include "../rcommon.h" -#ifdef TFE_ESPBOX -#define s_width (320) -#define s_height (200) -#endif - -using namespace TFE_Jedi::RClassic_Fixed; - -namespace TFE_Jedi -{ - namespace - { - int wallSortX(const void* r0, const void* r1) - { - return ((const RWallSegmentFixed*)r0)->wallX0 - ((const RWallSegmentFixed*)r1)->wallX0; - } - - int sortObjectsFixed(const void* r0, const void* r1) - { - SecObject* obj0 = *((SecObject**)r0); - SecObject* obj1 = *((SecObject**)r1); - - if (obj0->type == OBJ_TYPE_3D && obj1->type == OBJ_TYPE_3D) - { - // Both objects are 3D. - const fixed16_16 distSq0 = dotFixed(obj0->posVS, obj0->posVS); - const fixed16_16 distSq1 = dotFixed(obj1->posVS, obj1->posVS); - const fixed16_16 dist0 = fixedSqrt(distSq0); - const fixed16_16 dist1 = fixedSqrt(distSq1); - - if (obj0->model->isBridge && obj1->model->isBridge) - { - return dist1 - dist0; - } - else if (obj0->model->isBridge == 1) - { - return -1; - } - else if (obj1->model->isBridge == 1) - { - return 1; - } - - return dist1 - dist0; - } - else if (obj0->type == OBJ_TYPE_3D && obj0->model->isBridge) - { - return -1; - } - else if (obj1->type == OBJ_TYPE_3D && obj1->model->isBridge) - { - return 1; - } - - // Default case: - return obj1->posVS.z - obj0->posVS.z; - } - - s32 cullObjects(RSector* sector, SecObject** buffer) - { - s32 drawCount = 0; - SecObject** obj = sector->objectList; - s32 count = sector->objectCount; - - for (s32 i = count - 1; i >= 0 && drawCount < MAX_VIEW_OBJ_COUNT; i--, obj++) - { - // Search for the next allocated object. - SecObject* curObj = *obj; - while (!curObj) - { - obj++; - curObj = *obj; - } - - if (curObj->flags & OBJ_FLAG_NEEDS_TRANSFORM) - { - const s32 type = curObj->type; - if (type == OBJ_TYPE_SPRITE || type == OBJ_TYPE_FRAME) - { - if (curObj->posVS.z >= ONE_16) - { - buffer[drawCount++] = curObj; - } - } - else if (type == OBJ_TYPE_3D) - { - const fixed16_16 radius = curObj->model->radius; - const fixed16_16 zMax = curObj->posVS.z + radius; - // Near plane - if (zMax < ONE_16) { continue; } - - // Left plane - const fixed16_16 xMax = curObj->posVS.x + radius; - if (xMax < -zMax) { continue; } - - // Right plane - const fixed16_16 xMin = curObj->posVS.x - radius; - if (xMin > zMax) { continue; } - - // The object straddles the near plane, so add it and move on. - const fixed16_16 zMin = curObj->posVS.z - radius; - if (zMin <= 0) - { - buffer[drawCount++] = curObj; - continue; - } - - // Cull against the current "window." - const fixed16_16 z = curObj->posVS.z; -#ifdef TFE_ESPBOX - const s32 x0 = round16(div16((xMin * s_rcfState.focalLength), z)) + s_screenXMid; -#else - const s32 x0 = round16(div16(mul16(xMin, s_rcfState.focalLength), z)) + s_screenXMid; -#endif - if (x0 > s_windowMaxX_Pixels) { continue; } - -#ifdef TFE_ESPBOX - const s32 x1 = round16(div16((xMax * s_rcfState.focalLength), z)) + s_screenXMid; -#else - const s32 x1 = round16(div16(mul16(xMax, s_rcfState.focalLength), z)) + s_screenXMid; -#endif - if (x1 < s_windowMinX_Pixels) { continue; } - - // Finally add the object to render. - buffer[drawCount++] = curObj; - } - } - } - - return drawCount; - } - - void sprite_drawWax(s32 angle, SecObject* obj) - { - // Angles range from [0, 16384), divide by 512 to get 32 even buckets. - s32 angleDiff = (angle - obj->yaw) >> 9; - angleDiff &= 31; // up to 32 views - - // Get the animation based on the object state. - Wax* wax = obj->wax; - WaxAnim* anim = WAX_AnimPtr(wax, obj->anim & 0x1f); - if (anim) - { - // Then get the Sequence from the angle difference. - WaxView* view = WAX_ViewPtr(wax, anim, 31 - angleDiff); - // And finall the frame from the current sequence. - WaxFrame* frame = WAX_FramePtr(wax, view, obj->frame & 0x1f); - // Draw the frame. - sprite_drawFrame((u8*)wax, frame, obj); - } - } - } - - void TFE_Sectors_Fixed::prepare() - { - EdgePairFixed* flatEdge = &s_rcfState.flatEdgeList[s_flatCount]; - s_rcfState.flatEdge = flatEdge; - flat_addEdges(s_screenWidth, s_minScreenX_Pixels, 0, s_rcfState.windowMaxY, 0, s_rcfState.windowMinY); - - light_transformDirLights(); - } - - void TFE_Sectors_Fixed::destroy() - { - } - - void TFE_Sectors_Fixed::reset() - { - } - - void TFE_Sectors_Fixed::draw(RSector* sector) - { - s_curSector = sector; - s_sectorIndex++; - s_adjoinIndex++; - if (s_adjoinIndex > s_maxAdjoinIndex) - { - s_maxAdjoinIndex = s_adjoinIndex; - } - - s32* winTop = &s_windowTop_all[(s_adjoinDepth - 1) * s_width]; - s32* winBot = &s_windowBot_all[(s_adjoinDepth - 1) * s_width]; - s32* winTopNext = &s_windowTop_all[s_adjoinDepth * s_width]; - s32* winBotNext = &s_windowBot_all[s_adjoinDepth * s_width]; - - s_rcfState.depth1d = &s_rcfState.depth1d_all[(s_adjoinDepth - 1) * s_width]; - - s32 startWall = s_curSector->startWall; - s32 drawWallCount = s_curSector->drawWallCnt; - - if (s_flatLighting) - { - s_sectorAmbient = s_flatAmbient; - } - else - { - s_sectorAmbient = round16(s_curSector->ambient); - } - s_scaledAmbient = (s_sectorAmbient >> 1) + (s_sectorAmbient >> 2) + (s_sectorAmbient >> 3); - s_sectorAmbientFraction = s_sectorAmbient << 11; // fraction of ambient compared to max. - - s_windowTop = winTop; - s_windowBot = winBot; - fixed16_16* depthPrev = nullptr; - if (s_adjoinDepth > 1) - { - depthPrev = &s_rcfState.depth1d_all[(s_adjoinDepth - 2) * s_width]; - memcpy(&s_rcfState.depth1d[s_minScreenX_Pixels], &depthPrev[s_minScreenX_Pixels], s_width * 4); - } - - s_wallMaxCeilY = s_windowMinY_Pixels; - s_wallMinFloorY = s_windowMaxY_Pixels; - - if (s_drawFrame != s_curSector->prevDrawFrame) - { - TFE_ZONE_BEGIN(secXform, "Sector Vertex Transform"); - vec2_fixed* vtxWS = s_curSector->verticesWS; - vec2_fixed* vtxVS = s_curSector->verticesVS; - for (s32 v = 0; v < s_curSector->vertexCount; v++) - { - vtxVS->x = mul16(vtxWS->x, s_rcfState.cosYaw) + mul16(vtxWS->z, s_rcfState.sinYaw) + s_rcfState.cameraTrans.x; - vtxVS->z = mul16(vtxWS->x, s_rcfState.negSinYaw) + mul16(vtxWS->z, s_rcfState.cosYaw) + s_rcfState.cameraTrans.z; - vtxVS++; - vtxWS++; - } - TFE_ZONE_END(secXform); - - TFE_ZONE_BEGIN(objXform, "Sector Object Transform"); - SecObject** obj = s_curSector->objectList; - for (s32 i = s_curSector->objectCount - 1; i >= 0; i--, obj++) - { - SecObject* curObj = *obj; - while (!curObj) - { - obj++; - curObj = *obj; - } - - if (curObj->flags & OBJ_FLAG_NEEDS_TRANSFORM) - { - transformPointByCamera(&curObj->posWS, &curObj->posVS); - } - } - TFE_ZONE_END(objXform); - - TFE_ZONE_BEGIN(wallProcess, "Sector Wall Process"); - startWall = s_nextWall; - RWall* wall = s_curSector->walls; - for (s32 i = 0; i < s_curSector->wallCount; i++, wall++) - { - wall_process(wall); - } - drawWallCount = s_nextWall - startWall; - - s_curSector->startWall = startWall; - s_curSector->drawWallCnt = drawWallCount; - s_curSector->prevDrawFrame = s_drawFrame; - TFE_ZONE_END(wallProcess); - } - - RWallSegmentFixed* wallSegment = &s_rcfState.wallSegListDst[s_curWallSeg]; - s32 drawSegCnt = wall_mergeSort(wallSegment, MAX_SEG - s_curWallSeg, startWall, drawWallCount); - s_curWallSeg += drawSegCnt; - - TFE_ZONE_BEGIN(wallQSort, "Wall QSort"); - qsort(wallSegment, drawSegCnt, sizeof(RWallSegmentFixed), wallSortX); - TFE_ZONE_END(wallQSort); - - s32 flatCount = s_flatCount; - EdgePairFixed* flatEdge = &s_rcfState.flatEdgeList[s_flatCount]; - s_rcfState.flatEdge = flatEdge; - - s32 adjoinStart = s_adjoinSegCount; - EdgePairFixed* adjoinEdges = &s_rcfState.adjoinEdgeList[adjoinStart]; - RWallSegmentFixed* adjoinList[MAX_ADJOIN_DEPTH]; - - s_rcfState.adjoinEdge = adjoinEdges; - s_rcfState.adjoinSegment = adjoinList; - - // Draw each wall segment in the sector. - TFE_ZONE_BEGIN(secDrawWalls, "Draw Walls"); - for (s32 i = 0; i < drawSegCnt; i++, wallSegment++) - { - RWall* srcWall = wallSegment->srcWall; - RSector* nextSector = srcWall->nextSector; - - if (!nextSector) - { - wall_drawSolid(wallSegment); - } - else - { - const s32 df = srcWall->drawFlags; - assert(df >= 0); - if (df <= WDF_MIDDLE) - { - if (df == WDF_MIDDLE || (nextSector->flags1 & SEC_FLAGS1_EXT_FLOOR_ADJ)) - { - wall_drawMask(wallSegment); - } - else - { - wall_drawBottom(wallSegment); - } - } - else if (df == WDF_TOP) - { - if (nextSector->flags1 & SEC_FLAGS1_EXT_ADJ) - { - wall_drawMask(wallSegment); - } - else - { - wall_drawTop(wallSegment); - } - } - else if (df == WDF_TOP_AND_BOT) - { - if ((nextSector->flags1 & SEC_FLAGS1_EXT_ADJ) && (nextSector->flags1 & SEC_FLAGS1_EXT_FLOOR_ADJ)) - { - wall_drawMask(wallSegment); - } - else if (nextSector->flags1 & SEC_FLAGS1_EXT_ADJ) - { - wall_drawBottom(wallSegment); - } - else if (nextSector->flags1 & SEC_FLAGS1_EXT_FLOOR_ADJ) - { - wall_drawTop(wallSegment); - } - else - { - wall_drawTopAndBottom(wallSegment); - } - } - else // WDF_BOT - { - if (nextSector->flags1 & SEC_FLAGS1_EXT_FLOOR_ADJ) - { - wall_drawMask(wallSegment); - } - else - { - wall_drawBottom(wallSegment); - } - } - } - } - TFE_ZONE_END(secDrawWalls); - - TFE_ZONE_BEGIN(secDrawFlats, "Draw Flats"); - // Draw flats - // Note: in the DOS code flat drawing functions are called through function pointers. - // Since the function pointers always seem to be the same, the functions are called directly in this code. - // Most likely this was used for testing or debug drawing and may be added back in the future. - const s32 newFlatCount = s_flatCount - flatCount; - if (s_curSector->flags1 & SEC_FLAGS1_EXTERIOR) - { - if (s_curSector->flags1 & SEC_FLAGS1_NOWALL_DRAW) - { - wall_drawSkyTopNoWall(s_curSector); - } - else - { - wall_drawSkyTop(s_curSector); - } - } - else - { - flat_drawCeiling(s_curSector, flatEdge, newFlatCount); - } - if (s_curSector->flags1 & SEC_FLAGS1_PIT) - { - if (s_curSector->flags1 & SEC_FLAGS1_NOWALL_DRAW) - { - wall_drawSkyBottomNoWall(s_curSector); - } - else - { - wall_drawSkyBottom(s_curSector); - } - } - else - { - flat_drawFloor(s_curSector, flatEdge, newFlatCount); - } - TFE_ZONE_END(secDrawFlats); - - // Adjoins - s32 adjoinCount = s_adjoinSegCount - adjoinStart; - if (adjoinCount && s_adjoinDepth < MAX_ADJOIN_DEPTH) - { - adjoin_setupAdjoinWindow(winBot, winBotNext, winTop, winTopNext, adjoinEdges, adjoinCount); - RWallSegmentFixed** seg = adjoinList; - RWallSegmentFixed* prevAdjoinSeg = nullptr; - RWallSegmentFixed* curAdjoinSeg = nullptr; - - s32 adjoinEnd = adjoinCount - 1; - for (s32 i = 0; i < adjoinCount; i++, seg++, adjoinEdges++) - { - prevAdjoinSeg = curAdjoinSeg; - curAdjoinSeg = *seg; - - RWall* srcWall = curAdjoinSeg->srcWall; - RWallSegmentFixed* nextAdjoin = (i < adjoinEnd) ? *(seg + 1) : nullptr; - RSector* nextSector = srcWall->nextSector; - if (s_adjoinDepth < MAX_ADJOIN_DEPTH && s_adjoinDepth < s_maxDepthCount) - { - s32 index = s_adjoinDepth - 1; - saveValues(index); - - adjoin_computeWindowBounds(adjoinEdges); - s_adjoinDepth++; - if (s_adjoinDepth > s_maxAdjoinDepth) - { - s_maxAdjoinDepth = s_adjoinDepth; - } - - srcWall->drawFrame = s_drawFrame; - s_windowTop = winTopNext; - s_windowBot = winBotNext; - if (prevAdjoinSeg != 0) - { - if (prevAdjoinSeg->wallX1 + 1 == curAdjoinSeg->wallX0) - { - s_windowX0 = s_windowMinX_Pixels; - } - } - if (nextAdjoin) - { - if (curAdjoinSeg->wallX1 == nextAdjoin->wallX0 - 1) - { - s_windowX1 = s_windowMaxX_Pixels; - } - } - - s_rcfState.windowMinZ = min(curAdjoinSeg->z0, curAdjoinSeg->z1); - draw(nextSector); - - if (s_adjoinDepth) - { - s32 index = s_adjoinDepth - 2; - s_adjoinDepth--; - restoreValues(index); - } - srcWall->drawFrame = 0; - if (srcWall->flags1 & WF1_ADJ_MID_TEX) - { - TFE_ZONE("Draw Transparent Walls"); - wall_drawTransparent(curAdjoinSeg, adjoinEdges); - } - } - } - } - - if (!(s_curSector->flags1 & SEC_FLAGS1_SUBSECTOR) && depthPrev && s_drawFrame != s_prevSector->prevDrawFrame2) - { - memcpy(&depthPrev[s_windowMinX_Pixels], &s_rcfState.depth1d[s_windowMinX_Pixels], (s_windowMaxX_Pixels - s_windowMinX_Pixels + 1) * sizeof(fixed16_16)); - } - - // Objects - TFE_ZONE_BEGIN(secDrawObjects, "Draw Objects"); - const s32 objCount = cullObjects(s_curSector, s_objBuffer); - if (objCount > 0) - { - // Which top and bottom edges are we going to use to clip objects? - s_objWindowTop = s_windowTop; - if (s_windowMinY_Pixels < s_screenYMidFix || s_windowMaxCeil < s_screenYMidFix) - { - if (s_prevSector && s_prevSector->ceilingHeight <= s_curSector->ceilingHeight) - { - s_objWindowTop = s_windowTopPrev; - } - } - s_objWindowBot = s_windowBot; - if (s_windowMaxY_Pixels > s_screenYMidFix || s_windowMinFloor > s_screenYMidFix) - { - if (s_prevSector && s_prevSector->floorHeight >= s_curSector->floorHeight) - { - s_objWindowBot = s_windowBotPrev; - } - } - - // Sort objects in viewspace (generally back to front but there are special cases). - qsort(s_objBuffer, objCount, sizeof(SecObject*), sortObjectsFixed); - - // Draw objects in order. - for (s32 i = 0; i < objCount; i++) - { - SecObject* obj = s_objBuffer[i]; - const s32 type = obj->type; - if (type == OBJ_TYPE_SPRITE) - { - TFE_ZONE("Draw WAX"); - - fixed16_16 dx = s_rcfState.cameraPos.x - obj->posWS.x; - fixed16_16 dz = s_rcfState.cameraPos.z - obj->posWS.z; - angle14_32 angle = vec2ToAngle(dx, dz); - - sprite_drawWax(angle, obj); - } - else if (type == OBJ_TYPE_3D) - { - TFE_ZONE("Draw 3DO"); - - robj3d_draw(obj, obj->model); - } - else if (type == OBJ_TYPE_FRAME) - { - TFE_ZONE("Draw Frame"); - - sprite_drawFrame((u8*)obj->fme, obj->fme, obj); - } - } - } - TFE_ZONE_END(secDrawObjects); - - s_curSector->flags1 |= SEC_FLAGS1_RENDERED; - s_curSector->prevDrawFrame2 = s_drawFrame; - } - - void TFE_Sectors_Fixed::adjoin_setupAdjoinWindow(s32* winBot, s32* winBotNext, s32* winTop, s32* winTopNext, EdgePairFixed* adjoinEdges, s32 adjoinCount) - { - TFE_ZONE("Setup Adjoin Window"); - - // Note: This is pretty inefficient, especially at higher resolutions. - // The column loops below can be adjusted to do the copy only in the required ranges. - memcpy(&winTopNext[s_minScreenX_Pixels], &winTop[s_minScreenX_Pixels], s_width * 4); - memcpy(&winBotNext[s_minScreenX_Pixels], &winBot[s_minScreenX_Pixels], s_width * 4); - - // Loop through each adjoin and setup the column range based on the edge pair and the parent - // column range. - for (s32 i = 0; i < adjoinCount; i++, adjoinEdges++) - { - const s32 x0 = adjoinEdges->x0; - const s32 x1 = adjoinEdges->x1; - - const fixed16_16 ceil_dYdX = adjoinEdges->dyCeil_dx; - fixed16_16 y = adjoinEdges->yCeil0; - for (s32 x = x0; x <= x1; x++, y += ceil_dYdX) - { - s32 yPixel = round16(y); - s32 yBot = winBotNext[x]; - s32 yTop = winTop[x]; - if (yPixel > yTop) - { - winTopNext[x] = (yPixel <= yBot) ? yPixel : yBot + 1; - } - } - const fixed16_16 floor_dYdX = adjoinEdges->dyFloor_dx; - y = adjoinEdges->yFloor0; - for (s32 x = x0; x <= x1; x++, y += floor_dYdX) - { - s32 yPixel = round16(y); - s32 yTop = winTop[x]; - s32 yBot = winBot[x]; - if (yPixel < yBot) - { - winBotNext[x] = (yPixel >= yTop) ? yPixel : yTop - 1; - } - } - } - } - - void TFE_Sectors_Fixed::adjoin_computeWindowBounds(EdgePairFixed* adjoinEdges) - { - s32 yC = adjoinEdges->yPixel_C0; - if (yC > s_windowMinY_Pixels) - { - s_windowMinY_Pixels = yC; - } - s32 yF = adjoinEdges->yPixel_F0; - if (yF < s_windowMaxY_Pixels) - { - s_windowMaxY_Pixels = yF; - } - yC = adjoinEdges->yPixel_C1; - if (yC > s_windowMaxCeil) - { - s_windowMaxCeil = yC; - } - yF = adjoinEdges->yPixel_F1; - if (yF < s_windowMinFloor) - { - s_windowMinFloor = yF; - } - s_wallMaxCeilY = s_windowMinY_Pixels - 1; - s_wallMinFloorY = s_windowMaxY_Pixels + 1; - s_windowMinX_Pixels = adjoinEdges->x0; - s_windowMaxX_Pixels = adjoinEdges->x1; - s_windowTopPrev = s_windowTop; - s_windowBotPrev = s_windowBot; - s_prevSector = s_curSector; - } - - void TFE_Sectors_Fixed::saveValues(s32 index) - { - SectorSaveValues* dst = &s_sectorStack[index]; - dst->curSector = s_curSector; - dst->prevSector = s_prevSector; - dst->depth1d = s_rcfState.depth1d; - dst->windowX0 = s_windowX0; - dst->windowX1 = s_windowX1; - dst->windowMinY = s_windowMinY_Pixels; - dst->windowMaxY = s_windowMaxY_Pixels; - dst->windowMaxCeil = s_windowMaxCeil; - dst->windowMinFloor = s_windowMinFloor; - dst->wallMaxCeilY = s_wallMaxCeilY; - dst->wallMinFloorY = s_wallMinFloorY; - dst->windowMinX = s_windowMinX_Pixels; - dst->windowMaxX = s_windowMaxX_Pixels; - dst->windowTop = s_windowTop; - dst->windowBot = s_windowBot; - dst->windowTopPrev = s_windowTopPrev; - dst->windowBotPrev = s_windowBotPrev; - dst->sectorAmbient = s_sectorAmbient; - dst->scaledAmbient = s_scaledAmbient; - dst->sectorAmbientFraction = s_sectorAmbientFraction; - } - - void TFE_Sectors_Fixed::restoreValues(s32 index) - { - const SectorSaveValues* src = &s_sectorStack[index]; - s_curSector = src->curSector; - s_prevSector = src->prevSector; - s_rcfState.depth1d = (fixed16_16*)src->depth1d; - s_windowX0 = src->windowX0; - s_windowX1 = src->windowX1; - s_windowMinY_Pixels = src->windowMinY; - s_windowMaxY_Pixels = src->windowMaxY; - s_windowMaxCeil = src->windowMaxCeil; - s_windowMinFloor = src->windowMinFloor; - s_wallMaxCeilY = src->wallMaxCeilY; - s_wallMinFloorY = src->wallMinFloorY; - s_windowMinX_Pixels = src->windowMinX; - s_windowMaxX_Pixels = src->windowMaxX; - s_windowTop = src->windowTop; - s_windowBot = src->windowBot; - s_windowTopPrev = src->windowTopPrev; - s_windowBotPrev = src->windowBotPrev; - s_sectorAmbient = src->sectorAmbient; - s_scaledAmbient = src->scaledAmbient; - s_sectorAmbientFraction = src->sectorAmbientFraction; - } - - // Switch from float to fixed. - void TFE_Sectors_Fixed::subrendererChanged() - { - } -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rsectorFixed.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rsectorFixed.h deleted file mode 100644 index 09ed4774..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rsectorFixed.h +++ /dev/null @@ -1,33 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Sector -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include "rwallFixed.h" -#include "../rsectorRender.h" - -struct RWall; -struct SecObject; - -namespace TFE_Jedi -{ - class TFE_Sectors_Fixed : public TFE_Sectors - { - public: - // Sub-Renderer specific - void destroy() override; - void reset() override; - void prepare() override; - void draw(RSector* sector) override; - void subrendererChanged() override; - - private: - void saveValues(s32 index); - void restoreValues(s32 index); - void adjoin_computeWindowBounds(EdgePairFixed* adjoinEdges); - void adjoin_setupAdjoinWindow(s32* winBot, s32* winBotNext, s32* winTop, s32* winTopNext, EdgePairFixed* adjoinEdges, s32 adjoinCount); - }; -} // TFE_Jedi diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rwallFixed.cpp b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rwallFixed.cpp deleted file mode 100644 index c3e572a3..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rwallFixed.cpp +++ /dev/null @@ -1,3112 +0,0 @@ -#include - -#include -#include -#include -#include - -#include "rwallFixed.h" -#include -#include "rflatFixed.h" -#include "rlightingFixed.h" -#include "rsectorFixed.h" -#include "redgePairFixed.h" -#include "rclassicFixedSharedState.h" -#include "../rcommon.h" -#include "../jediRenderer.h" -#ifdef TFE_ESPBOX -#define s_width (320) -#define s_height (200) -#endif - -namespace TFE_Jedi -{ - -namespace RClassic_Fixed -{ - #define SKY_BASE_HEIGHT 200 - - enum SegSide - { - FRONT = 0xffff, - BACK = 0, - }; - - static fixed16_16 s_segmentCross; - static s32 s_texHeightMask; - static s32 s_yPixelCount; - static fixed16_16 s_vCoordStep; - static fixed16_16 s_vCoordFixed; - static const u8* s_columnLight; - static u8* s_texImage; - static u8* s_columnOut; -#ifdef TFE_ESPBOX - static u8* s_workBuffer = nullptr; // WAX_DECOMPRESS_SIZE (shared memory) -#else - static u8 s_workBuffer[WAX_DECOMPRESS_SIZE]; -#endif -#ifdef TFE_ESPBOX - static s32 s_xPixelCount; - #define SPRTEST -#endif - -#ifdef TFE_ESPBOX - static inline -#endif - s32 segmentCrossesLine(fixed16_16 ax0, fixed16_16 ay0, fixed16_16 ax1, fixed16_16 ay1, fixed16_16 bx0, fixed16_16 by0, fixed16_16 bx1, fixed16_16 by1); -#ifdef TFE_ESPBOX - static inline -#endif - fixed16_16 solveForZ_Numerator(RWallSegmentFixed* wallSegment); -#ifdef TFE_ESPBOX - static inline -#endif - fixed16_16 solveForZ(RWallSegmentFixed* wallSegment, s32 x, fixed16_16 numerator, fixed16_16* outViewDx=nullptr); - void drawColumn_Fullbright(); - void drawColumn_Lit(); - void drawColumn_Fullbright_Trans(); - void drawColumn_Lit_Trans(); -#ifdef TFE_ESPBOX - static inline -#endif - void wall_addAdjoinSegment(s32 length, s32 x0, fixed16_16 top_dydx, fixed16_16 y1, fixed16_16 bot_dydx, fixed16_16 y0, RWallSegmentFixed* wallSegment); - - // Column rendering functions that can be chosen at runtime. - enum ColumnFuncId - { - COLFUNC_FULLBRIGHT = 0, - COLFUNC_LIT, - COLFUNC_FULLBRIGHT_TRANS, - COLFUNC_LIT_TRANS, - - COLFUNC_COUNT - }; - - typedef void(*ColumnFunction)(); -#ifdef TFE_ESPBOX - void drawColumnS_Fullbright(); - void drawColumnS_Lit(); - void drawColumnS_Fullbright_Trans(); - void drawColumnS_Lit_Trans(); - - ColumnFunction s_columnFunc[COLFUNC_COUNT] = - { - drawColumnS_Fullbright, // COLFUNC_FULLBRIGHT - drawColumnS_Lit, // COLFUNC_LIT - drawColumnS_Fullbright_Trans, // COLFUNC_FULLBRIGHT_TRANS - drawColumnS_Lit_Trans, // COLFUNC_LIT_TRANS - }; -#else - ColumnFunction s_columnFunc[COLFUNC_COUNT] = - { - drawColumn_Fullbright, // COLFUNC_FULLBRIGHT - drawColumn_Lit, // COLFUNC_LIT - drawColumn_Fullbright_Trans, // COLFUNC_FULLBRIGHT_TRANS - drawColumn_Lit_Trans, // COLFUNC_LIT_TRANS - }; -#endif - -#ifdef TFE_ESPBOX - static inline -#endif - fixed16_16 frustumIntersect(fixed16_16 x0, fixed16_16 z0, fixed16_16 x1, fixed16_16 z1, fixed16_16 dx, fixed16_16 dz) - { - fixed16_16 xz; -#if defined(TFE_ESPBOX) && defined(__mc68060__) - // this is closer to the original behavior when an overflow happens - xz = floatToFixed16(fixed16ToFloat(x0) * fixed16ToFloat(z1) - fixed16ToFloat(z0) * fixed16ToFloat(x1)); -#else - xz = mul16(x0, z1) - mul16(z0, x1); -#endif - fixed16_16 dyx = dz - dx; - if (dyx != 0) - { - xz = div16(xz, dyx); - } - return xz; - } - - // Process the wall and produce an RWallSegment for rendering if the wall is potentially visible. - void wall_process(RWall* wall) - { - const vec2_fixed* p0 = wall->v0; - const vec2_fixed* p1 = wall->v1; - - // viewspace wall coordinates. - fixed16_16 x0 = p0->x; - fixed16_16 x1 = p1->x; - fixed16_16 z0 = p0->z; - fixed16_16 z1 = p1->z; - - // x values of frustum lines that pass through (x0,z0) and (x1,z1) - fixed16_16 left0 = -z0; - fixed16_16 left1 = -z1; - fixed16_16 right0 = z0; - fixed16_16 right1 = z1; - - // Cull the wall if it is completely beyind the camera. - if (z0 < 0 && z1 < 0) - { - wall->visible = 0; - return; - } - // Cull the wall if it is completely outside the view - if ((x0 < left0 && x1 < left1) || (x0 > right0 && x1 > right1)) - { - wall->visible = 0; - return; - } - - fixed16_16 dx = x1 - x0; - fixed16_16 dz = z1 - z0; - // Cull the wall if it is back facing. - // y0*dx - x0*dy - const fixed16_16 side = mul16(z0, dx) - mul16(x0, dz); - if (side < 0) - { - wall->visible = 0; - return; - } - - fixed16_16 curU = 0; - s32 clipLeft = 0; - s32 clipRight = 0; - s32 clipX1_Near = 0; - s32 clipX0_Near = 0; - - fixed16_16 texelLen = wall->texelLength; - fixed16_16 texelLenRem = texelLen; - - ////////////////////////////////////////////// - // Clip the Wall Segment by the left and right - // frustum lines. - ////////////////////////////////////////////// - - // The wall segment extends past the left clip line. - if (x0 < left0) - { - // Intersect the segment (x0, z0),(x1, z1) with the frustum line that passes through (-z0, z0) and (-z1, z1) - const fixed16_16 xz = frustumIntersect(x0, z0, x1, z1, dx, -dz); - - // Compute the parametric intersection of the segment and the left frustum line - // where s is in the range of [0.0, 1.0] - fixed16_16 s = 0; - if (dz != 0 && TFE_Jedi::abs(dz) > TFE_Jedi::abs(dx)) - { - s = div16(xz - z0, dz); - } - else if (dx != 0) - { - s = div16(-xz - x0, dx); - } - - // Update the x0,y0 coordinate of the segment. - x0 = -xz; - z0 = xz; - - if (s != 0) - { - // length of the clipped portion of the remaining texel length. - fixed16_16 clipLen = mul16(texelLenRem, s); - // adjust the U texel offset. - curU += clipLen; - // adjust the remaining texel length. - texelLenRem = texelLen - curU; - } - - // We have clipped the segment on the left side. - clipLeft = -1; - // Update dX and dZ - dx = x1 - x0; - dz = z1 - z0; - } - // The wall segment extends past the right clip line. - if (x1 > right1) - { - // Compute the coordinate where x0 + s*dx = z0 + s*dz - // Solve for s = (x0 - y0)/(dz - dx) - // Substitute: x = x0 + ((x0 - z0)/(dz - dx))*dx = (x0*z1 - z0*x1) / (dz - dx) - const fixed16_16 xz = frustumIntersect(x0, z0, x1, z1, dx, dz); - - // Compute the parametric intersection of the segment and the left frustum line - // where s is in the range of [0.0, 1.0] - // Note we are computing from the right side, i.e. distance from (x1,y1). - fixed16_16 s = 0; - if (dz != 0 && TFE_Jedi::abs(dz) > TFE_Jedi::abs(dx)) - { - s = div16(xz - z1, dz); - } - else if (dx != 0) - { - s = div16(xz - x1, dx); - } - - // Update the x1,y1 coordinate of the segment. - x1 = xz; - z1 = xz; - if (s != 0) - { - fixed16_16 adjLen = texelLen + mul16(texelLenRem, s); - fixed16_16 adjLenMinU = adjLen - curU; - - texelLen = adjLen; - texelLenRem = adjLenMinU; - } - - // We have clipped the segment on the right side. - clipRight = -1; - // Update dX and dZ - dx = x1 - x0; - dz = z1 - z0; - } - - ////////////////////////////////////////////////// - // Clip the Wall Segment by the near plane. - ////////////////////////////////////////////////// - if ((z0 < 0 || z1 < 0) && segmentCrossesLine(0, 0, 0, -s_rcfState.halfHeight, x0, x0, x1, z1) != 0) - { - wall->visible = 0; - return; - } - if (z0 < ONE_16 && z1 < ONE_16) - { - if (clipLeft != 0) - { - clipX0_Near = -1; - x0 = -ONE_16; - } - else - { - x0 = div16(x0, z0); - } - if (clipRight != 0) - { - x1 = ONE_16; - clipX1_Near = -1; - } - else - { - x1 = div16(x1, z1); - } - dx = x1 - x0; - dz = 0; - z0 = ONE_16; - z1 = ONE_16; - } - else if (z0 < ONE_16) - { - if (clipLeft != 0) - { - if (dz != 0) - { - fixed16_16 left = div16(z0, dz); - x0 += mul16(dx, left); - //curU += mul16(texelLenRem, left); - - dx = x1 - x0; - texelLenRem = texelLen - curU; - } - z0 = ONE_16; - clipX0_Near = -1; - dz = z1 - ONE_16; - } - else - { - // BUG: This is NOT correct but matches the original implementation. - // I am leaving it as-is to match the original DOS renderer. - // Fortunately hitting this case is VERY rare in practice. - x0 = div16(x0, z0); - z0 = ONE_16; - dz = z1 - ONE_16; - dx -= x0; - } - } - else if (z1 < ONE_16) - { - if (clipRight != 0) - { - if (dz != 0) - { - fixed16_16 s = div16(ONE_16 - x1, dz); - x1 += mul16(dx, s); - texelLen += mul16(texelLenRem, s); - texelLenRem = texelLen - curU; - dx = x1 - x0; - } - z1 = ONE_16; - dz = ONE_16 - z0; - clipX1_Near = -1; - } - else - { - // BUG: This is NOT correct but matches the original implementation. - // I am leaving it as-is to match the original DOS renderer. - // Fortunately hitting this case is VERY rare in practice. - x1 = div16(x1, z1); - z1 = ONE_16; - dx = x1 - x0; - dz = z1 - z0; - } - } - - ////////////////////////////////////////////////// - // Project. - ////////////////////////////////////////////////// - s32 x0pixel, x1pixel; -#ifdef TFE_ESPBOX - fixed16_16 x0proj = div16(x0 * s_rcfState.focalLength, z0) + s_rcfState.projOffsetX; - fixed16_16 x1proj = div16(x1 * s_rcfState.focalLength, z1) + s_rcfState.projOffsetX; -#else - fixed16_16 x0proj = div16(mul16(x0, s_rcfState.focalLength), z0) + s_rcfState.projOffsetX; - fixed16_16 x1proj = div16(mul16(x1, s_rcfState.focalLength), z1) + s_rcfState.projOffsetX; -#endif - x0pixel = round16(x0proj); - x1pixel = round16(x1proj) - 1; - - // Handle near plane clipping by adjusting the walls to avoid holes. - if (clipX0_Near != 0 && x0pixel > s_minScreenX_Pixels) - { - x0 = -ONE_16; - dx = x1 + ONE_16; - x0pixel = s_minScreenX_Pixels; - } - if (clipX1_Near != 0 && x1pixel < s_maxScreenX_Pixels) - { - dx = ONE_16 - x0; - x1pixel = s_maxScreenX_Pixels; - } - - // The wall is backfacing if x0 > x1 - if (x0pixel > x1pixel) - { - wall->visible = 0; - return; - } - // The wall is completely outside of the screen. - if (x0pixel > s_maxScreenX_Pixels || x1pixel < s_minScreenX_Pixels) - { - wall->visible = 0; - return; - } - if (s_nextWall == MAX_SEG) - { - TFE_System::logWrite(LOG_ERROR, "ClassicRenderer", "Wall_Process : Maximum processed walls exceeded!"); - wall->visible = 0; - return; - } - - RWallSegmentFixed* wallSeg = &s_rcfState.wallSegListSrc[s_nextWall]; - s_nextWall++; - - if (x0pixel < s_minScreenX_Pixels) - { - x0pixel = s_minScreenX_Pixels; - } - if (x1pixel > s_maxScreenX_Pixels) - { - x1pixel = s_maxScreenX_Pixels; - } - - wallSeg->srcWall = wall; - wallSeg->wallX0_raw = x0pixel; - wallSeg->wallX1_raw = x1pixel; - wallSeg->z0 = z0; - wallSeg->z1 = z1; - wallSeg->uCoord0 = curU; - wallSeg->wallX0 = x0pixel; - wallSeg->wallX1 = x1pixel; - wallSeg->x0View = x0; - - fixed16_16 slope, den; - s32 orient; - if (TFE_Jedi::abs(dx) > TFE_Jedi::abs(dz)) - { - slope = div16(dz, dx); - den = dx; - orient = WORIENT_DZ_DX; - } - else - { - slope = div16(dx, dz); - den = dz; - orient = WORIENT_DX_DZ; - } - - wallSeg->slope = slope; - wallSeg->uScale = div16(texelLenRem, den); - wallSeg->orient = orient; - /*if (x0pixel == x1pixel) - { - wallSeg->slope = 0; - }*/ - - wall->visible = 1; - } - - s32 wall_mergeSort(RWallSegmentFixed* segOutList, s32 availSpace, s32 start, s32 count) - { - TFE_ZONE("Wall Merge/Sort"); - - count = min(count, s_maxWallCount); - if (!count) { return 0; } - - s32 outIndex = 0; - s32 srcIndex = 0; - s32 splitWallCount = 0; - s32 splitWallIndex = -count; - - RWallSegmentFixed* srcSeg = &s_rcfState.wallSegListSrc[start]; - RWallSegmentFixed* curSegOut = segOutList; - - RWallSegmentFixed tempSeg; - RWallSegmentFixed* newSeg = &tempSeg; - RWallSegmentFixed splitWalls[MAX_SPLIT_WALLS]; - - while (1) - { - RWall* srcWall = srcSeg->srcWall; - JBool processed = (s_drawFrame == srcWall->drawFrame) ? JTRUE : JFALSE; - JBool insideWindow = ((srcSeg->z0 >= s_rcfState.windowMinZ || srcSeg->z1 >= s_rcfState.windowMinZ) && srcSeg->wallX0 <= s_windowMaxX_Pixels && srcSeg->wallX1 >= s_windowMinX_Pixels) ? JTRUE : JFALSE; - if (!processed && insideWindow) - { - // Copy the source segment into "newSeg" so it can be modified. - *newSeg = *srcSeg; - - // Clip the segment 'newSeg' to the current window. - if (newSeg->wallX0 < s_windowMinX_Pixels) { newSeg->wallX0 = s_windowMinX_Pixels; } - if (newSeg->wallX1 > s_windowMaxX_Pixels) { newSeg->wallX1 = s_windowMaxX_Pixels; } - - // Check 'newSeg' versus all of the segments already added for this sector. - RWallSegmentFixed* sortedSeg = segOutList; - s32 segHidden = 0; - for (s32 n = 0; n < outIndex && segHidden == 0; n++, sortedSeg++) - { - // Trivially skip segments that do not overlap in screenspace. - if (!(newSeg->wallX0 <= sortedSeg->wallX1 && sortedSeg->wallX0 <= newSeg->wallX1)) { continue; } - - RWall* outSrcWall = sortedSeg->srcWall; - RWall* newSrcWall = newSeg->srcWall; - - vec2_fixed* outV0 = outSrcWall->v0; - vec2_fixed* outV1 = outSrcWall->v1; - vec2_fixed* newV0 = newSrcWall->v0; - vec2_fixed* newV1 = newSrcWall->v1; - - fixed16_16 newMinZ = min(newV0->z, newV1->z); - fixed16_16 newMaxZ = max(newV0->z, newV1->z); - fixed16_16 outMinZ = min(outV0->z, outV1->z); - fixed16_16 outMaxZ = max(outV0->z, outV1->z); - s32 side; - - if (newSeg->wallX0 <= sortedSeg->wallX0 && newSeg->wallX1 >= sortedSeg->wallX1) - { - if (newMaxZ < outMinZ || newMinZ > outMaxZ) - { - // This is a clear case, the 'newSeg' is clearly in front of or behind the current 'sortedSeg' - side = (newV0->z < outV0->z) ? FRONT : BACK; - } - else if (newV0->z < outV0->z) - { - side = FRONT; - if ((segmentCrossesLine(outV0->x, outV0->z, 0, 0, newV0->x, newV0->z, newV1->x, newV1->z) || // (outV0, 0) does NOT cross (newV0, newV1) - segmentCrossesLine(outV1->x, outV1->z, 0, 0, newV0->x, newV0->z, newV1->x, newV1->z)) && // (outV1, 0) does NOT cross (newV0, newV1) - (!segmentCrossesLine(newV0->x, newV0->z, 0, 0, outV0->x, outV0->z, outV1->x, outV1->z) || // (newV0, 0) crosses (outV0, outV1) - !segmentCrossesLine(newV1->x, newV1->z, 0, 0, outV0->x, outV0->z, outV1->x, outV1->z))) // (newV1, 0) crosses (outV0, outV1) - { - side = BACK; - } - } - else // newV0->z >= outV0->z - { - side = BACK; - if ((segmentCrossesLine(newV0->x, newV0->z, 0, 0, outV0->x, outV0->z, outV1->x, outV1->z) || // (newV0, 0) does NOT cross (outV0, outV1) - segmentCrossesLine(newV1->x, newV1->z, 0, 0, outV0->x, outV0->z, outV1->x, outV1->z)) && // (newV1, 0) does NOT cross (outV0, outV1) - (!segmentCrossesLine(outV0->x, outV0->z, 0, 0, newV0->x, newV0->z, newV1->x, newV1->z) || // (outV0, 0) crosses (newV0, newV1) - !segmentCrossesLine(outV1->x, outV1->z, 0, 0, newV0->x, newV0->z, newV1->x, newV1->z))) // (outV1, 0) crosses (newV0, newV1) - { - side = FRONT; - } - } - - // 'newSeg' is in front of 'sortedSeg' and it completely hides it. - if (side == FRONT) - { - s32 copyCount = outIndex - 1 - n; - RWallSegmentFixed* outCur = sortedSeg; - RWallSegmentFixed* outNext = sortedSeg + 1; - - // We are deleting outCur since it is completely hidden by moving all segments from outNext onwards to outCur. - memmove(outCur, outNext, copyCount * sizeof(RWallSegmentFixed)); - - // We are deleting outCur since it is completely hidden by 'newSeg' - // Back up 1 step in the loop, so that outNext is processed (it will hold the same location as outCur before deletion). - curSegOut = curSegOut - 1; - sortedSeg = sortedSeg - 1; - outIndex--; - n--; - } - // 'newSeg' is behind 'sortedSeg' and they overlap. - else // (side == BACK) - { - // If 'newSeg' is behind 'sortedSeg' but it sticks out on both sides, then - // 'newSeg' must be split. - // |NNN|OOOOOOO|SSS| -> N = newSeg, O = sortedSeg, S = splitSeg from newSeg. - if (sortedSeg->wallX0 > newSeg->wallX0 && sortedSeg->wallX1 < newSeg->wallX1) - { - if (splitWallCount == MAX_SPLIT_WALLS) - { - TFE_System::logWrite(LOG_ERROR, "RendererClassic", "Wall_MergeSort : Maximum split walls exceeded!"); - segHidden = 0xffff; - newSeg->wallX1 = sortedSeg->wallX0 - 1; - break; - } - else - { - RWallSegmentFixed* splitWall = &splitWalls[splitWallCount]; - *splitWall = *newSeg; - splitWall->wallX0 = sortedSeg->wallX1 + 1; - splitWallCount++; - - newSeg->wallX1 = sortedSeg->wallX0 - 1; - } - } - // if 'newSeg' is to the left, adjust it to end where 'sortedSeg' starts. - // |NNN|OOOOOO| -> N = newSeg, O = sortedSeg - else if (sortedSeg->wallX0 > newSeg->wallX0) - { - newSeg->wallX1 = sortedSeg->wallX0 - 1; - } - // if 'newSeg' is to the right, adjust it to start where 'sortedSeg' ends. - // |OOOOO|NNN| -> N = newSeg, O = sortedSeg - else - { - newSeg->wallX0 = sortedSeg->wallX1 + 1; - } - } - } - else if (newSeg->wallX0 >= sortedSeg->wallX0 && newSeg->wallX1 <= sortedSeg->wallX1) - { - if (newMaxZ < outMinZ || newMinZ > outMaxZ) - { - side = (newV0->z < outV0->z) ? FRONT : BACK; - } - else if (newV0->z < outV0->z) - { - side = FRONT; - if ((segmentCrossesLine(outV0->x, outV0->z, 0, 0, newV0->x, newV0->z, newV1->x, newV1->z) || - segmentCrossesLine(outV1->x, outV1->z, 0, 0, newV0->x, newV0->z, newV1->x, newV1->z)) && - (!segmentCrossesLine(newV0->x, newV0->z, 0, 0, outV0->x, outV0->z, outV1->x, outV1->z) || - !segmentCrossesLine(newV1->x, newV1->z, 0, 0, outV0->x, outV0->z, outV1->x, outV1->z))) - { - side = BACK; - } - } - else // (newV0->z >= outV0->z) - { - side = BACK; - if ((segmentCrossesLine(newV0->x, newV0->z, 0, 0, outV0->x, outV0->z, outV1->x, outV1->z) || - segmentCrossesLine(newV1->x, newV1->z, 0, 0, outV0->x, outV0->z, outV1->x, outV1->z)) && - (!segmentCrossesLine(outV0->x, outV0->z, 0, 0, newV0->x, newV0->z, newV1->x, newV1->z) || - !segmentCrossesLine(outV1->x, outV1->z, 0, 0, newV0->x, newV0->z, newV1->x, newV1->z))) - { - side = FRONT; - } - } - - if (side == BACK) - { - // The new segment is hidden behind the 'sortedSeg' and can be discarded. - segHidden = 0xffff; - break; - } - // side == FRONT - else if (newSeg->wallX0 > sortedSeg->wallX0 && newSeg->wallX1 < sortedSeg->wallX1) - { - if (splitWallCount == MAX_SPLIT_WALLS) - { - TFE_System::logWrite(LOG_ERROR, "RendererClassic", "Wall_MergeSort : Maximum split walls exceeded!"); - segHidden = 0xffff; - break; - } - else - { - // Split sortedSeg into 2 and insert newSeg in between. - // { sortedSeg | newSeg | splitWall (from sortedSeg) } - RWallSegmentFixed* splitWall = &splitWalls[splitWallCount]; - splitWallCount++; - - *splitWall = *sortedSeg; - splitWall->wallX0 = newSeg->wallX1 + 1; - sortedSeg->wallX1 = newSeg->wallX0 - 1; - } - } - else if (newSeg->wallX0 > sortedSeg->wallX0) - { - sortedSeg->wallX1 = newSeg->wallX0 - 1; - } - else // (newSeg->wallX0 <= sortedSeg->wallX0) - { - sortedSeg->wallX0 = newSeg->wallX1 + 1; - } - } - else if (newSeg->wallX1 >= sortedSeg->wallX0 && newSeg->wallX1 < sortedSeg->wallX1) - { - if (newMaxZ < outMinZ || newMinZ > outMaxZ) - { - if (newV1->z < outV0->z) - { - sortedSeg->wallX0 = newSeg->wallX1 + 1; - } - else - { - newSeg->wallX1 = sortedSeg->wallX0 - 1; - } - } - else if (segmentCrossesLine(newV1->x, newV1->z, 0, 0, outV0->x, outV0->z, outV1->x, outV1->z) && - !segmentCrossesLine(outV0->x, outV0->z, 0, 0, newV0->x, newV0->z, newV1->x, newV1->z)) - { - sortedSeg->wallX0 = newSeg->wallX1 + 1; - } - else - { - newSeg->wallX1 = sortedSeg->wallX0 - 1; - } - } - else if (newMaxZ < outMinZ || newMinZ > outMaxZ) - { - if (newV0->z < outV1->z) - { - sortedSeg->wallX1 = newSeg->wallX0 - 1; - } - else - { - newSeg->wallX0 = sortedSeg->wallX1 + 1; - } - } - else if (segmentCrossesLine(newV0->x, newV0->z, 0, 0, outV0->x, outV0->z, outV1->x, outV1->z) && - !segmentCrossesLine(outV1->x, outV1->z, 0, 0, newV0->x, newV0->z, newV1->x, newV1->z)) - { - sortedSeg->wallX1 = newSeg->wallX0 - 1; - } - else - { - newSeg->wallX0 = sortedSeg->wallX1 + 1; - } - } // for (s32 n = 0; n < outIndex && segHidden == 0; n++, sortedSeg++) - - // If the new segment is still visible and not back facing. - if (segHidden == 0 && newSeg->wallX0 <= newSeg->wallX1) - { - if (outIndex == availSpace) - { - TFE_System::logWrite(LOG_ERROR, "RendererClassic", "Wall_MergeSort : Maximum merged walls exceeded!"); - } - else - { - // Copy the temporary segment to the current segment. - *curSegOut = *newSeg; - curSegOut++; - outIndex++; - } - } - } // if (!processed && insideWindow) - splitWallIndex++; - srcIndex++; - if (srcIndex < count) - { - srcSeg++; - } - else if (splitWallIndex < splitWallCount) - { - srcSeg = &splitWalls[splitWallIndex]; - } - else - { - break; - } - } // while (1) - - return outIndex; - } - -#ifdef TFE_ESPBOX - static inline -#endif - TextureData* setupSignTexture(RWall* srcWall, fixed16_16* signU0, fixed16_16* signU1, ColumnFunction* signFullbright, ColumnFunction* signLit) - { - if (!srcWall->signTex) { return nullptr; } - - TextureData* signTex = *srcWall->signTex; - *signU0 = 0; *signU1 = 0; - *signFullbright = nullptr; *signLit = nullptr; - if (signTex) - { - // Compute the U texel range, the overlay is only drawn within this range. - *signU0 = srcWall->signOffset.x; - *signU1 = *signU0 + intToFixed16(signTex->width); - - // Determine the column functions based on texture opacity and flags. - // In the original DOS code, the sign column functions are different but only because they do not apply the texture height mask - // per pixel. I decided to keep it simple, removing the extra binary AND per pixel is not worth adding 4 extra functions that are - // mostly redundant. - if (signTex->flags & OPACITY_TRANS) - { - *signFullbright = s_columnFunc[COLFUNC_FULLBRIGHT_TRANS]; - *signLit = s_columnFunc[(srcWall->flags1 & WF1_ILLUM_SIGN) ? COLFUNC_FULLBRIGHT_TRANS : COLFUNC_LIT_TRANS]; - } - else - { - *signFullbright = s_columnFunc[COLFUNC_FULLBRIGHT]; - *signLit = s_columnFunc[(srcWall->flags1 & WF1_ILLUM_SIGN) ? COLFUNC_FULLBRIGHT : COLFUNC_LIT]; - } - } - return signTex; - } - - void wall_drawSolid(RWallSegmentFixed* wallSegment) - { - RWall* srcWall = wallSegment->srcWall; - RSector* sector = srcWall->sector; - TextureData* texture = srcWall->midTex ? *srcWall->midTex : nullptr; - if (!texture) { return; } - - fixed16_16 ceilingHeight = sector->ceilingHeight; - fixed16_16 floorHeight = sector->floorHeight; - - fixed16_16 ceilEyeRel = ceilingHeight - s_rcfState.eyeHeight; - fixed16_16 floorEyeRel = floorHeight - s_rcfState.eyeHeight; - - fixed16_16 z0 = wallSegment->z0; - fixed16_16 z1 = wallSegment->z1; - - fixed16_16 y0C, y0F, y1C, y1F; -#ifdef TFE_ESPBOX - const fixed16_16 rcpZ0 = div16(ONE_16, z0); - const fixed16_16 rcpZ1 = div16(ONE_16, z1); - y0C = mul16((ceilEyeRel * s_rcfState.focalLenAspect), rcpZ0) + s_rcfState.projOffsetY; - y1C = mul16((ceilEyeRel * s_rcfState.focalLenAspect), rcpZ1) + s_rcfState.projOffsetY; - y0F = mul16((floorEyeRel * s_rcfState.focalLenAspect), rcpZ0) + s_rcfState.projOffsetY; - y1F = mul16((floorEyeRel * s_rcfState.focalLenAspect), rcpZ1) + s_rcfState.projOffsetY; -#else - y0C = div16(mul16(ceilEyeRel, s_rcfState.focalLenAspect), z0) + s_rcfState.projOffsetY; - y1C = div16(mul16(ceilEyeRel, s_rcfState.focalLenAspect), z1) + s_rcfState.projOffsetY; - y0F = div16(mul16(floorEyeRel, s_rcfState.focalLenAspect), z0) + s_rcfState.projOffsetY; - y1F = div16(mul16(floorEyeRel, s_rcfState.focalLenAspect), z1) + s_rcfState.projOffsetY; -#endif - - s32 y0C_pixel = round16(y0C); - s32 y1C_pixel = round16(y1C); - s32 y0F_pixel = round16(y0F); - s32 y1F_pixel = round16(y1F); - - s32 x = wallSegment->wallX0; - s32 length = wallSegment->wallX1 - wallSegment->wallX0 + 1; - fixed16_16 numerator = solveForZ_Numerator(wallSegment); - - // For some reason we only early-out if the ceiling is below the view. - if (y0C_pixel > s_windowMaxY_Pixels && y1C_pixel > s_windowMaxY_Pixels) - { - fixed16_16 yMax = intToFixed16(s_windowMaxY_Pixels + 1); - flat_addEdges(length, x, 0, yMax, 0, yMax); - - for (s32 i = 0; i < length; i++, x++) - { - s_rcfState.depth1d[x] = solveForZ(wallSegment, x, numerator); - s_columnTop[x] = s_windowMaxY_Pixels; - } - - srcWall->visible = 0; - return; - } - - s_texHeightMask = texture ? texture->height - 1 : 0; - - fixed16_16 signU0 = 0, signU1 = 0; - ColumnFunction signFullbright = nullptr, signLit = nullptr; - TextureData* signTex = setupSignTexture(srcWall, &signU0, &signU1, &signFullbright, &signLit); - -#ifdef TFE_ESPBOX - s32 wallDeltaX = wallSegment->wallX1_raw - wallSegment->wallX0_raw; - fixed16_16 dYdXtop = 0, dYdXbot = 0; - if (wallDeltaX != 0) - { - /* - dYdXtop = (y1C - y0C) / wallDeltaX; - dYdXbot = (y1F - y0F) / wallDeltaX; - */ - const fixed16_16 rcpWallDeltaX = ONE_16 / wallDeltaX; - dYdXtop = mul16(y1C - y0C, rcpWallDeltaX); - dYdXbot = mul16(y1F - y0F, rcpWallDeltaX); - } -#else - fixed16_16 wallDeltaX = intToFixed16(wallSegment->wallX1_raw - wallSegment->wallX0_raw); - fixed16_16 dYdXtop = 0, dYdXbot = 0; - if (wallDeltaX != 0) - { - dYdXtop = div16(y1C - y0C, wallDeltaX); - dYdXbot = div16(y1F - y0F, wallDeltaX); - } -#endif - -#ifdef TFE_ESPBOX - s32 clippedXDelta = wallSegment->wallX0 - wallSegment->wallX0_raw; - if (clippedXDelta != 0) - { - y0C += dYdXtop * clippedXDelta; - y0F += dYdXbot * clippedXDelta; - } -#else - fixed16_16 clippedXDelta = intToFixed16(wallSegment->wallX0 - wallSegment->wallX0_raw); - if (clippedXDelta != 0) - { - y0C += mul16(dYdXtop, clippedXDelta); - y0F += mul16(dYdXbot, clippedXDelta); - } -#endif - flat_addEdges(length, wallSegment->wallX0, dYdXbot, y0F, dYdXtop, y0C); - - const s32 texWidth = texture ? texture->width : 0; - const JBool flipHorz = ((srcWall->flags1 & WF1_FLIP_HORIZ)!=0) ? JTRUE : JFALSE; - - for (s32 i = 0; i < length; i++, x++) - { - s32 top = round16(y0C); - s32 bot = round16(y0F); - s_columnBot[x] = bot + 1; - s_columnTop[x] = top - 1; - - top = max(top, s_windowTop[x]); - bot = min(bot, s_windowBot[x]); - s_yPixelCount = bot - top + 1; - - fixed16_16 dxView = 0; - fixed16_16 z = solveForZ(wallSegment, x, numerator, &dxView); - s_rcfState.depth1d[x] = z; - - fixed16_16 uScale = wallSegment->uScale; - fixed16_16 uCoord0 = wallSegment->uCoord0 + srcWall->midOffset.x; - fixed16_16 uCoord = uCoord0 + ((wallSegment->orient == WORIENT_DZ_DX) ? mul16(dxView, uScale) : mul16(z - z0, uScale)); - - if (s_yPixelCount > 0) - { - // texture wrapping, assumes texWidth is a power of 2. - s32 texelU = floor16(uCoord) & (texWidth - 1); - // flip texture coordinate if flag set. - if (flipHorz) { texelU = texWidth - texelU - 1; } - - // Calculate the vertical texture coordinate start and increment. - fixed16_16 wallHeightPixels = y0F - y0C + ONE_16; - fixed16_16 wallHeightTexels = srcWall->midTexelHeight; - - // s_vCoordStep = tex coord "v" step per y pixel step -> dVdY; - s_vCoordStep = div16(wallHeightTexels, wallHeightPixels); - - // texel offset from the actual fixed point y position and the truncated y position. - fixed16_16 vPixelOffset = y0F - intToFixed16(bot) + HALF_16; - - // scale the texel offset based on the v coord step. - // the result is the sub-texel offset - fixed16_16 v0 = mul16(s_vCoordStep, vPixelOffset); - s_vCoordFixed = v0 + srcWall->midOffset.z; - - // Texture image data = imageStart + u * texHeight - s_texImage = texture->image + (texelU << texture->logSizeY); - s_columnLight = computeLighting(z, floor16(srcWall->wallLight)); - // column write output. - s_columnOut = &s_display[top * s_width + x]; - - // draw the column - if (s_columnLight) - { - drawColumn_Lit(); - } - else - { - drawColumn_Fullbright(); - } - - // Handle the "sign texture" - a wall overlay. - if (signTex && uCoord >= signU0 && uCoord <= signU1) - { -#ifdef TFE_ESPBOX - const fixed16_16 rcpVCoordStep = div16(ONE_16, s_vCoordStep); - fixed16_16 signYbot = y0F + mul16(srcWall->signOffset.z, rcpVCoordStep); - fixed16_16 signYtop = signYbot - mul16(intToFixed16(signTex->height), rcpVCoordStep) + ONE_16; -#else - fixed16_16 signYbot = y0F + div16(srcWall->signOffset.z, s_vCoordStep); - fixed16_16 signYtop = signYbot - div16(intToFixed16(signTex->height), s_vCoordStep) + ONE_16; -#endif - s32 y0 = max(round16(signYtop), top); - s32 y1 = min(round16(signYbot), bot); - s_yPixelCount = y1 - y0 + 1; - - if (s_yPixelCount > 0) - { - s_vCoordFixed = mul16(signYbot - intToFixed16(y1) + HALF_16, s_vCoordStep); - s_columnOut = &s_display[y0*s_width + x]; - texelU = floor16(uCoord - signU0); - s_texImage = &signTex->image[texelU << signTex->logSizeY]; - - s32 heightMask = s_texHeightMask; - s_texHeightMask = signTex->height - 1; - if (s_columnLight) - { - signLit(); - } - else - { - signFullbright(); - } - s_texHeightMask = heightMask; - } - } - } - - y0C += dYdXtop; - y0F += dYdXbot; - } - - srcWall->seen = JTRUE; - } - - void wall_drawTransparent(RWallSegmentFixed* wallSegment, EdgePairFixed* edge) - { - RWall* srcWall = wallSegment->srcWall; - RSector* sector = srcWall->sector; - TextureData* texture = *srcWall->midTex; - - fixed16_16 z0 = wallSegment->z0; - fixed16_16 yC0 = edge->yCeil0; - fixed16_16 yF0 = edge->yFloor0; - fixed16_16 uScale = wallSegment->uScale; - fixed16_16 uCoord0 = wallSegment->uCoord0 + srcWall->midOffset.x; - s32 lengthInPixels = edge->lengthInPixels; - - s_texHeightMask = texture->height - 1; - JBool flipHorz = ((srcWall->flags1 & WF1_FLIP_HORIZ)!=0) ? JTRUE : JFALSE; - - fixed16_16 ceil_dYdX = edge->dyCeil_dx; - fixed16_16 floor_dYdX = edge->dyFloor_dx; - fixed16_16 num = solveForZ_Numerator(wallSegment); - - for (s32 i = 0, x = edge->x0; i < lengthInPixels; i++, x++) - { - s32 top = s_windowTop[x]; - s32 bot = s_windowBot[x]; - - s32 yC_pixel = max(round16(yC0), top); - s32 yF_pixel = min(round16(yF0), bot); - - s_yPixelCount = yF_pixel - yC_pixel + 1; - if (s_yPixelCount > 0) - { - fixed16_16 dxView; - fixed16_16 z = solveForZ(wallSegment, x, num, &dxView); - fixed16_16 uCoord = uCoord0 + ((wallSegment->orient == WORIENT_DZ_DX) ? mul16(dxView, uScale) : mul16(z - z0, uScale)); - - s32 widthMask = texture->width - 1; - s32 texelU = floor16(uCoord) & widthMask; - if (flipHorz) - { - texelU = widthMask - texelU; - } - - s_texImage = &texture->image[texelU << texture->logSizeY]; - s_vCoordStep = div16(srcWall->midTexelHeight, yF0 - yC0 + ONE_16); - s_vCoordFixed = mul16(yF0 - intToFixed16(yF_pixel) + HALF_16, s_vCoordStep) + srcWall->midOffset.z; - - s_columnOut = &s_display[yC_pixel*s_width + x]; - s_rcfState.depth1d[x] = z; - s_columnLight = computeLighting(z, floor16(srcWall->wallLight)); - - if (s_columnLight) - { - drawColumn_Lit_Trans(); - } - else - { - drawColumn_Fullbright_Trans(); - } - } - - yC0 += ceil_dYdX; - yF0 += floor_dYdX; - } - } - - void wall_drawMask(RWallSegmentFixed* wallSegment) - { - RWall* srcWall = wallSegment->srcWall; - RSector* sector = srcWall->sector; - RSector* nextSector = srcWall->nextSector; - - fixed16_16 z0 = wallSegment->z0; - fixed16_16 z1 = wallSegment->z1; - u32 flags1 = sector->flags1; - u32 nextFlags1 = nextSector->flags1; - - fixed16_16 cProj0, cProj1; - if ((flags1 & SEC_FLAGS1_EXTERIOR) && (nextFlags1 & SEC_FLAGS1_EXT_ADJ)) // ceiling - { - cProj0 = cProj1 = s_rcfState.windowMinY; - } - else - { - fixed16_16 ceilRel = sector->ceilingHeight - s_rcfState.eyeHeight; -#ifdef TFE_ESPBOX - cProj0 = div16((ceilRel * s_rcfState.focalLenAspect), z0) + s_rcfState.projOffsetY; - cProj1 = div16((ceilRel * s_rcfState.focalLenAspect), z1) + s_rcfState.projOffsetY; -#else - cProj0 = div16(mul16(ceilRel, s_rcfState.focalLenAspect), z0) + s_rcfState.projOffsetY; - cProj1 = div16(mul16(ceilRel, s_rcfState.focalLenAspect), z1) + s_rcfState.projOffsetY; -#endif - } - - s32 c0pixel = round16(cProj0); - s32 c1pixel = round16(cProj1); - if (c0pixel > s_windowMaxY_Pixels && c1pixel > s_windowMaxY_Pixels) - { - s32 x = wallSegment->wallX0; - s32 length = wallSegment->wallX1 - wallSegment->wallX0 + 1; - flat_addEdges(length, x, 0, intToFixed16(s_windowMaxY_Pixels + 1), 0, intToFixed16(s_windowMaxY_Pixels + 1)); - const fixed16_16 numerator = solveForZ_Numerator(wallSegment); - for (s32 i = 0; i < length; i++, x++) - { - s_rcfState.depth1d[x] = solveForZ(wallSegment, x, numerator); - s_columnTop[x] = s_windowMaxY_Pixels; - } - - srcWall->visible = 0; - srcWall->seen = JTRUE; - return; - } - - fixed16_16 fProj0, fProj1; - if ((sector->flags1 & SEC_FLAGS1_PIT) && (nextFlags1 & SEC_FLAGS1_EXT_FLOOR_ADJ)) // floor - { - fProj0 = fProj1 = s_rcfState.windowMaxY; - } - else - { - fixed16_16 floorRel = sector->floorHeight - s_rcfState.eyeHeight; -#ifdef TFE_ESPBOX - fProj0 = div16((floorRel * s_rcfState.focalLenAspect), z0) + s_rcfState.projOffsetY; - fProj1 = div16((floorRel * s_rcfState.focalLenAspect), z1) + s_rcfState.projOffsetY; -#else - fProj0 = div16(mul16(floorRel, s_rcfState.focalLenAspect), z0) + s_rcfState.projOffsetY; - fProj1 = div16(mul16(floorRel, s_rcfState.focalLenAspect), z1) + s_rcfState.projOffsetY; -#endif - } - - s32 f0pixel = round16(fProj0); - s32 f1pixel = round16(fProj1); - if (f0pixel < s_windowMinY_Pixels && f1pixel < s_windowMinY_Pixels) - { - s32 x = wallSegment->wallX0; - s32 length = wallSegment->wallX1 - wallSegment->wallX0 + 1; - flat_addEdges(length, x, 0, intToFixed16(s_windowMinY_Pixels - 1), 0, intToFixed16(s_windowMinY_Pixels - 1)); - - const fixed16_16 numerator = solveForZ_Numerator(wallSegment); - for (s32 i = 0; i < length; i++, x++) - { - s_rcfState.depth1d[x] = solveForZ(wallSegment, x, numerator); - s_columnBot[x] = s_windowMinY_Pixels; - } - srcWall->visible = 0; - srcWall->seen = JTRUE; - return; - } - -#ifdef TFE_ESPBOX - s32 xStartOffset = wallSegment->wallX0 - wallSegment->wallX0_raw; -#else - fixed16_16 xStartOffset = intToFixed16(wallSegment->wallX0 - wallSegment->wallX0_raw); -#endif - s32 length = wallSegment->wallX1 - wallSegment->wallX0 + 1; - - fixed16_16 numerator = solveForZ_Numerator(wallSegment); -#ifdef TFE_ESPBOX - s32 lengthRaw = wallSegment->wallX1_raw - wallSegment->wallX0_raw; -#else - fixed16_16 lengthRaw = intToFixed16(wallSegment->wallX1_raw - wallSegment->wallX0_raw); -#endif - fixed16_16 dydxCeil = 0; - fixed16_16 dydxFloor = 0; -#ifdef TFE_ESPBOX - if (lengthRaw != 0) - { - /* - dydxCeil = (cProj1 - cProj0) / lengthRaw; - dydxFloor = (fProj1 - fProj0) / lengthRaw; - */ - const fixed16_16 rcpLengthRaw = ONE_16 / lengthRaw; - dydxCeil = mul16(cProj1 - cProj0, rcpLengthRaw); - dydxFloor = mul16(fProj1 - fProj0, rcpLengthRaw); - } -#else - if (lengthRaw != 0) - { - dydxCeil = div16(cProj1 - cProj0, lengthRaw); - dydxFloor = div16(fProj1 - fProj0, lengthRaw); - } -#endif - fixed16_16 y0 = cProj0; - fixed16_16 y1 = fProj0; - s32 x = wallSegment->wallX0; -#ifdef TFE_ESPBOX - if (xStartOffset != 0) - { - y0 = (dydxCeil * xStartOffset) + cProj0; - y1 = (dydxFloor * xStartOffset) + fProj0; - } -#else - if (xStartOffset != 0) - { - y0 = mul16(dydxCeil, xStartOffset) + cProj0; - y1 = mul16(dydxFloor, xStartOffset) + fProj0; - } -#endif - - flat_addEdges(length, x, dydxFloor, y1, dydxCeil, y0); - fixed16_16 nextFloor = nextSector->floorHeight; - fixed16_16 nextCeil = nextSector->ceilingHeight; - // There is an opening in this wall to the next sector. - if (nextFloor > nextCeil) - { - wall_addAdjoinSegment(length, x, dydxFloor, y1, dydxCeil, y0, wallSegment); - } - if (length != 0) - { - for (s32 i = 0; i < length; i++, x++) - { - s32 y0_pixel = round16(y0); - s32 y1_pixel = round16(y1); - s_columnTop[x] = y0_pixel - 1; - s_columnBot[x] = y1_pixel + 1; - - s_rcfState.depth1d[x] = solveForZ(wallSegment, x, numerator); - y0 += dydxCeil; - y1 += dydxFloor; - } - } - - srcWall->seen = JTRUE; - } - - void wall_drawBottom(RWallSegmentFixed* wallSegment) - { - RWall* wall = wallSegment->srcWall; - RSector* sector = wall->sector; - RSector* nextSector = wall->nextSector; - TextureData* tex = *wall->botTex; - if (!tex) { return; } - - fixed16_16 z0 = wallSegment->z0; - fixed16_16 z1 = wallSegment->z1; - - fixed16_16 cProj0, cProj1; - if ((sector->flags1 & SEC_FLAGS1_EXTERIOR) && (nextSector->flags1 & SEC_FLAGS1_EXT_ADJ)) - { - cProj0 = s_rcfState.windowMinY; - cProj1 = cProj0; - } - else - { - fixed16_16 ceilRel = sector->ceilingHeight - s_rcfState.eyeHeight; -#ifdef TFE_ESPBOX - cProj0 = div16((ceilRel * s_rcfState.focalLenAspect), z0) + s_rcfState.projOffsetY; - cProj1 = div16((ceilRel * s_rcfState.focalLenAspect), z1) + s_rcfState.projOffsetY; -#else - cProj0 = div16(mul16(ceilRel, s_rcfState.focalLenAspect), z0) + s_rcfState.projOffsetY; - cProj1 = div16(mul16(ceilRel, s_rcfState.focalLenAspect), z1) + s_rcfState.projOffsetY; -#endif - } - - s32 cy0 = round16(cProj0); - s32 cy1 = round16(cProj1); - if (cy0 > s_windowMaxY_Pixels && cy1 >= s_windowMaxY_Pixels) - { - wall->visible = 0; - s32 x = wallSegment->wallX0; - s32 length = wallSegment->wallX1 - x + 1; - - flat_addEdges(length, x, 0, intToFixed16(s_windowMaxY_Pixels + 1), 0, intToFixed16(s_windowMaxY_Pixels + 1)); - - fixed16_16 num = solveForZ_Numerator(wallSegment); - for (s32 i = 0; i < length; i++, x++) - { - s_rcfState.depth1d[x] = solveForZ(wallSegment, x, num); - s_columnTop[x] = s_windowMaxY_Pixels; - } - wall->seen = JTRUE; - return; - } - - fixed16_16 floorRel = sector->floorHeight - s_rcfState.eyeHeight; - fixed16_16 fProj0, fProj1; -#ifdef TFE_ESPBOX - fProj0 = div16((floorRel * s_rcfState.focalLenAspect), z0) + s_rcfState.projOffsetY; - fProj1 = div16((floorRel * s_rcfState.focalLenAspect), z1) + s_rcfState.projOffsetY; -#else - fProj0 = div16(mul16(floorRel, s_rcfState.focalLenAspect), z0) + s_rcfState.projOffsetY; - fProj1 = div16(mul16(floorRel, s_rcfState.focalLenAspect), z1) + s_rcfState.projOffsetY; -#endif - - s32 fy0 = round16(fProj0); - s32 fy1 = round16(fProj1); - if (fy0 < s_windowMinY_Pixels && fy1 < s_windowMinY_Pixels) - { - // Wall is above the top of the screen. - wall->visible = 0; - s32 x = wallSegment->wallX0; - s32 length = wallSegment->wallX1 - x + 1; - - flat_addEdges(length, x, 0, intToFixed16(s_windowMinY_Pixels - 1), 0, intToFixed16(s_windowMinY_Pixels - 1)); - - fixed16_16 num = solveForZ_Numerator(wallSegment); - for (s32 i = 0; i < length; i++, x++) - { - s_rcfState.depth1d[x] = solveForZ(wallSegment, x, num); - s_columnBot[x] = s_windowMinY_Pixels; - } - wall->seen = JTRUE; - return; - } - - fixed16_16 floorRelNext = nextSector->floorHeight - s_rcfState.eyeHeight; - fixed16_16 fNextProj0, fNextProj1; -#ifdef TFE_ESPBOX - fNextProj0 = div16((floorRelNext * s_rcfState.focalLenAspect), z0) + s_rcfState.projOffsetY; - fNextProj1 = div16((floorRelNext * s_rcfState.focalLenAspect), z1) + s_rcfState.projOffsetY; -#else - fNextProj0 = div16(mul16(floorRelNext, s_rcfState.focalLenAspect), z0) + s_rcfState.projOffsetY; - fNextProj1 = div16(mul16(floorRelNext, s_rcfState.focalLenAspect), z1) + s_rcfState.projOffsetY; -#endif - - s32 xOffset = wallSegment->wallX0 - wallSegment->wallX0_raw; - s32 length = wallSegment->wallX1 - wallSegment->wallX0 + 1; - s32 lengthRaw = wallSegment->wallX1_raw - wallSegment->wallX0_raw; - fixed16_16 lengthRawFixed = intToFixed16(lengthRaw); - fixed16_16 xOffsetFixed = intToFixed16(xOffset); - - fixed16_16 floorNext_dYdX = 0; - fixed16_16 floor_dYdX = 0; - fixed16_16 ceil_dYdX = 0; -#ifdef TFE_ESPBOX - if (lengthRaw != 0) - { -/* - floorNext_dYdX = (fNextProj1 - fNextProj0) / lengthRaw; - floor_dYdX = (fProj1 - fProj0) / lengthRaw; - ceil_dYdX = (cProj1 - cProj0) / lengthRaw; -*/ - const fixed16_16 rcpLengthRawFixed = ONE_16 / lengthRaw; - floorNext_dYdX = mul16(fNextProj1 - fNextProj0, rcpLengthRawFixed); - floor_dYdX = mul16(fProj1 - fProj0, rcpLengthRawFixed); - ceil_dYdX = mul16(cProj1 - cProj0, rcpLengthRawFixed); - } - if (xOffset) - { - fNextProj0 += floorNext_dYdX * xOffset; - fProj0 += floor_dYdX * xOffset; - cProj0 += ceil_dYdX * xOffset; - } -#else - if (lengthRawFixed != 0) - { - floorNext_dYdX = div16(fNextProj1 - fNextProj0, lengthRawFixed); - floor_dYdX = div16(fProj1 - fProj0, lengthRawFixed); - ceil_dYdX = div16(cProj1 - cProj0, lengthRawFixed); - } - if (xOffsetFixed) - { - fNextProj0 += mul16(floorNext_dYdX, xOffsetFixed); - fProj0 += mul16(floor_dYdX, xOffsetFixed); - cProj0 += mul16(ceil_dYdX, xOffsetFixed); - } -#endif - - fixed16_16 yTop = fNextProj0; - fixed16_16 yC = cProj0; - fixed16_16 yBot = fProj0; - s32 x = wallSegment->wallX0; - flat_addEdges(length, wallSegment->wallX0, floor_dYdX, fProj0, ceil_dYdX, cProj0); - - s32 yTop0 = round16(fNextProj0); - s32 yTop1 = round16(fNextProj1); - if ((yTop0 > s_windowMinY_Pixels || yTop1 > s_windowMinY_Pixels) && sector->ceilingHeight < nextSector->floorHeight) - { - wall_addAdjoinSegment(length, wallSegment->wallX0, floorNext_dYdX, fNextProj0, ceil_dYdX, cProj0, wallSegment); - } - - if (yTop0 > s_windowMaxY_Pixels && yTop1 > s_windowMaxY_Pixels) - { - s32 bot = s_windowMaxY_Pixels + 1; - fixed16_16 num = solveForZ_Numerator(wallSegment); - for (s32 i = 0; i < length; i++, x++, yC += ceil_dYdX) - { - s32 yC_pixel = min(round16(yC), s_windowBot[x]); - s_columnTop[x] = yC_pixel - 1; - s_columnBot[x] = bot; - s_rcfState.depth1d[x] = solveForZ(wallSegment, x, num); - } - wall->seen = JTRUE; - return; - } - - fixed16_16 u0 = wallSegment->uCoord0; - fixed16_16 num = solveForZ_Numerator(wallSegment); - s_texHeightMask = tex->height - 1; - JBool flipHorz = ((wall->flags1 & WF1_FLIP_HORIZ)!=0) ? JTRUE : JFALSE; - JBool illumSign = ((wall->flags1 & WF1_ILLUM_SIGN)!=0) ? JTRUE : JFALSE; - - fixed16_16 signU0 = 0, signU1 = 0; - ColumnFunction signFullbright = nullptr, signLit = nullptr; - TextureData* signTex = setupSignTexture(wall, &signU0, &signU1, &signFullbright, &signLit); - - if (length > 0) - { - for (s32 i = 0; i < length; i++, x++) - { - s32 yTop_pixel = round16(yTop); - s32 yC_pixel = round16(yC); - s32 yBot_pixel = round16(yBot); - - s_columnTop[x] = yC_pixel - 1; - s_columnBot[x] = yBot_pixel + 1; - - s32 bot = s_windowBot[x]; - s32 top = s_windowTop[x]; - if (yTop_pixel < s_windowTop[x]) - { - yTop_pixel = s_windowTop[x]; - } - if (yBot_pixel > s_windowBot[x]) - { - yBot_pixel = s_windowBot[x]; - } - s_yPixelCount = yBot_pixel - yTop_pixel + 1; - - // Calculate perspective correct Z and U (texture coordinate). - fixed16_16 dxView; - fixed16_16 z = solveForZ(wallSegment, x, num, &dxView); - fixed16_16 uCoord; - if (wallSegment->orient == WORIENT_DZ_DX) - { - uCoord = u0 + mul16(dxView, wallSegment->uScale) + wall->botOffset.x; - } - else - { - fixed16_16 dz = z - z0; - uCoord = u0 + mul16(dz, wallSegment->uScale) + wall->botOffset.x; - } - s_rcfState.depth1d[x] = z; - if (s_yPixelCount > 0) - { - s32 widthMask = tex->width - 1; - s32 texelU = floor16(uCoord) & widthMask; - if (flipHorz != 0) - { - texelU = widthMask - texelU; - } - - s_vCoordStep = div16(wall->botTexelHeight, yBot - yTop + ONE_16); - fixed16_16 v0 = mul16(yBot - intToFixed16(yBot_pixel) + HALF_16, s_vCoordStep); - s_vCoordFixed = v0 + wall->botOffset.z; - s_texImage = &tex->image[texelU << tex->logSizeY]; - s_columnOut = &s_display[yTop_pixel * s_width + x]; - s_columnLight = computeLighting(z, floor16(wall->wallLight)); - if (s_columnLight) - { - drawColumn_Lit(); - } - else - { - drawColumn_Fullbright(); - } - - // Handle the "sign texture" - a wall overlay. - if (signTex && uCoord >= signU0 && uCoord <= signU1) - { -#ifdef TFE_ESPBOX - const fixed16_16 rcpVCoordStep = div16(ONE_16, s_vCoordStep); - fixed16_16 signYBase = yBot + mul16(wall->signOffset.z, rcpVCoordStep); - s32 y0 = max(floor16(signYBase - mul16(intToFixed16(signTex->height), rcpVCoordStep) + ONE_16 + HALF_16), yTop_pixel); -#else - fixed16_16 signYBase = yBot + div16(wall->signOffset.z, s_vCoordStep); - s32 y0 = max(floor16(signYBase - div16(intToFixed16(signTex->height), s_vCoordStep) + ONE_16 + HALF_16), yTop_pixel); -#endif - s32 y1 = min(floor16(signYBase + HALF_16), yBot_pixel); - s_yPixelCount = y1 - y0 + 1; - - if (s_yPixelCount > 0) - { - s_vCoordFixed = mul16(signYBase - intToFixed16(y1) + HALF_16, s_vCoordStep); - s_columnOut = &s_display[y0*s_width + x]; - texelU = floor16(uCoord - signU0); - s_texImage = &signTex->image[texelU << signTex->logSizeY]; - - s32 heightMask = s_texHeightMask; - s_texHeightMask = signTex->height - 1; - if (s_columnLight) - { - signLit(); - } - else - { - signFullbright(); - } - s_texHeightMask = heightMask; - } - } - } - yTop += floorNext_dYdX; - yBot += floor_dYdX; - yC += ceil_dYdX; - } - } - wall->seen = JTRUE; - } - - void wall_drawTop(RWallSegmentFixed* wallSegment) - { - RWall* srcWall = wallSegment->srcWall; - RSector* sector = srcWall->sector; - RSector* next = srcWall->nextSector; - TextureData* texture = *srcWall->topTex; - if (!texture) { return; } - - fixed16_16 z0 = wallSegment->z0; - fixed16_16 z1 = wallSegment->z1; - fixed16_16 num = solveForZ_Numerator(wallSegment); - - s32 x0 = wallSegment->wallX0; - s32 lengthInPixels = wallSegment->wallX1 - wallSegment->wallX0 + 1; - - fixed16_16 ceilRel = sector->ceilingHeight - s_rcfState.eyeHeight; - fixed16_16 yC0, yC1; -#ifdef TFE_ESPBOX - yC0 = div16((ceilRel * s_rcfState.focalLenAspect), z0) + s_rcfState.projOffsetY; - yC1 = div16((ceilRel * s_rcfState.focalLenAspect), z1) + s_rcfState.projOffsetY; -#else - yC0 = div16(mul16(ceilRel, s_rcfState.focalLenAspect), z0) + s_rcfState.projOffsetY; - yC1 = div16(mul16(ceilRel, s_rcfState.focalLenAspect), z1) + s_rcfState.projOffsetY; -#endif - - s32 yC0_pixel = round16(yC0); - s32 yC1_pixel = round16(yC1); - - s_texHeightMask = texture->height - 1; - - if (yC0_pixel > s_windowMaxY_Pixels && yC1_pixel > s_windowMaxY_Pixels) - { - srcWall->visible = 0; - for (s32 i = 0; i < lengthInPixels; i++) { s_columnTop[x0 + i] = s_windowMaxY_Pixels; } - flat_addEdges(lengthInPixels, x0, 0, intToFixed16(s_windowMaxY_Pixels + 1), 0, intToFixed16(s_windowMaxY_Pixels + 1)); - for (s32 i = 0, x = x0; i < lengthInPixels; i++, x++) - { - s_rcfState.depth1d[x] = solveForZ(wallSegment, x, num); - s_columnTop[x] = s_windowMaxY_Pixels; - } - srcWall->seen = JTRUE; - return; - } - - fixed16_16 yF0, yF1; - if ((sector->flags1 & SEC_FLAGS1_PIT) && (next->flags1 & SEC_FLAGS1_EXT_FLOOR_ADJ)) - { - yF0 = yF1 = intToFixed16(s_windowMaxY_Pixels); - } - else - { - fixed16_16 floorRel = sector->floorHeight - s_rcfState.eyeHeight; -#ifdef TFE_ESPBOX - yF0 = div16((floorRel * s_rcfState.focalLenAspect), z0) + s_rcfState.projOffsetY; - yF1 = div16((floorRel * s_rcfState.focalLenAspect), z1) + s_rcfState.projOffsetY; -#else - yF0 = div16(mul16(floorRel, s_rcfState.focalLenAspect), z0) + s_rcfState.projOffsetY; - yF1 = div16(mul16(floorRel, s_rcfState.focalLenAspect), z1) + s_rcfState.projOffsetY; -#endif - } - s32 yF0_pixel = round16(yF0); - s32 yF1_pixel = round16(yF1); - if (yF0_pixel < s_windowMinY_Pixels && yF1_pixel < s_windowMinY_Pixels) - { - srcWall->visible = 0; - for (s32 i = 0; i < lengthInPixels; i++) { s_columnBot[x0 + i] = s_windowMinY_Pixels; } - flat_addEdges(lengthInPixels, x0, 0, intToFixed16(s_windowMinY_Pixels - 1), 0, intToFixed16(s_windowMinY_Pixels - 1)); - for (s32 i = 0, x = x0; i < lengthInPixels; i++, x++) - { - s_rcfState.depth1d[x] = solveForZ(wallSegment, x, num); - s_columnBot[x] = s_windowMinY_Pixels; - } - srcWall->seen = JTRUE; - return; - } - - fixed16_16 next_ceilRel = next->ceilingHeight - s_rcfState.eyeHeight; - fixed16_16 next_yC0, next_yC1; -#ifdef TFE_ESPBOX - next_yC0 = div16((next_ceilRel * s_rcfState.focalLenAspect), z0) + s_rcfState.projOffsetY; - next_yC1 = div16((next_ceilRel * s_rcfState.focalLenAspect), z1) + s_rcfState.projOffsetY; -#else - next_yC0 = div16(mul16(next_ceilRel, s_rcfState.focalLenAspect), z0) + s_rcfState.projOffsetY; - next_yC1 = div16(mul16(next_ceilRel, s_rcfState.focalLenAspect), z1) + s_rcfState.projOffsetY; -#endif - -#ifdef TFE_ESPBOX - s32 xOffset = wallSegment->wallX0 - wallSegment->wallX0_raw; - s32 length = wallSegment->wallX1_raw - wallSegment->wallX0_raw; -#else - fixed16_16 xOffset = intToFixed16(wallSegment->wallX0 - wallSegment->wallX0_raw); - fixed16_16 length = intToFixed16(wallSegment->wallX1_raw - wallSegment->wallX0_raw); -#endif - fixed16_16 ceil_dYdX = 0; - fixed16_16 next_ceil_dYdX = 0; - fixed16_16 floor_dYdX = 0; -#ifdef TFE_ESPBOX - if (length) - { - /* - ceil_dYdX = (yC1 - yC0) / length; - next_ceil_dYdX = (next_yC1 - next_yC0) / length; - floor_dYdX = (yF1 - yF0) / length; - */ - const fixed16_16 rcpLength = ONE_16 / length; - ceil_dYdX = mul16(yC1 - yC0, rcpLength); - next_ceil_dYdX = mul16(next_yC1 - next_yC0, rcpLength); - floor_dYdX = mul16(yF1 - yF0, rcpLength); - } - if (xOffset) - { - yC0 += ceil_dYdX * xOffset; - next_yC0 += next_ceil_dYdX * xOffset; - yF0 += floor_dYdX * xOffset; - } -#else - if (length) - { - ceil_dYdX = div16(yC1 - yC0, length); - next_ceil_dYdX = div16(next_yC1 - next_yC0, length); - floor_dYdX = div16(yF1 - yF0, length); - } - if (xOffset) - { - yC0 += mul16(ceil_dYdX, xOffset); - next_yC0 += mul16(next_ceil_dYdX, xOffset); - yF0 += mul16(floor_dYdX, xOffset); - } -#endif - - flat_addEdges(lengthInPixels, x0, floor_dYdX, yF0, ceil_dYdX, yC0); - s32 next_yC0_pixel = round16(next_yC0); - s32 next_yC1_pixel = round16(next_yC1); - if ((next_yC0_pixel < s_windowMaxY_Pixels || next_yC1_pixel < s_windowMaxY_Pixels) && (sector->floorHeight > next->ceilingHeight)) - { - wall_addAdjoinSegment(lengthInPixels, x0, floor_dYdX, yF0, next_ceil_dYdX, next_yC0, wallSegment); - } - - if (next_yC0_pixel < s_windowMinY_Pixels && next_yC1_pixel < s_windowMinY_Pixels) - { - for (s32 i = 0; i < lengthInPixels; i++) { s_columnTop[x0 + i] = s_windowMinY_Pixels - 1; } - for (s32 i = 0, x = x0; i < lengthInPixels; i++, x++) - { - yF0_pixel = round16(yF0); - if (yF0_pixel > s_windowBot[x]) - { - yF0_pixel = s_windowBot[x]; - } - - s_columnBot[x] = yF0_pixel + 1; - s_rcfState.depth1d[x] = solveForZ(wallSegment, x, num); - yF0 += floor_dYdX; - } - srcWall->seen = JTRUE; - return; - } - - fixed16_16 uCoord0 = wallSegment->uCoord0; - JBool flipHorz = ((srcWall->flags1 & WF1_FLIP_HORIZ)!=0) ? JTRUE : JFALSE; - JBool illumSign = ((srcWall->flags1 & WF1_ILLUM_SIGN)!=0) ? JTRUE : JFALSE; - - fixed16_16 signU0 = 0, signU1 = 0; - ColumnFunction signFullbright = nullptr, signLit = nullptr; - TextureData* signTex = setupSignTexture(srcWall, &signU0, &signU1, &signFullbright, &signLit); - - for (s32 i = 0, x = x0; i < lengthInPixels; i++, x++) - { - yC0_pixel = round16(yC0); - next_yC0_pixel = round16(next_yC0); - yF0_pixel = round16(yF0); - - s_columnTop[x] = yC0_pixel - 1; - s_columnBot[x] = yF0_pixel + 1; - s32 top = s_windowTop[x]; - if (yC0_pixel < top) - { - yC0_pixel = top; - } - s32 bot = s_windowBot[x]; - if (next_yC0_pixel > bot) - { - next_yC0_pixel = bot; - } - - s_yPixelCount = next_yC0_pixel - yC0_pixel + 1; - - fixed16_16 dxView; - fixed16_16 z = solveForZ(wallSegment, x, num, &dxView); - - fixed16_16 uScale = wallSegment->uScale; - fixed16_16 uCoord0 = wallSegment->uCoord0 + srcWall->topOffset.x; - fixed16_16 uCoord = uCoord0 + ((wallSegment->orient == WORIENT_DZ_DX) ? mul16(dxView, uScale) : mul16(z - z0, uScale)); - - s_rcfState.depth1d[x] = z; - if (s_yPixelCount > 0) - { - s32 widthMask = texture->width - 1; - s32 texelU = floor16(uCoord) & widthMask; - if (flipHorz) - { - texelU = widthMask - texelU; - } - assert(texelU >= 0 && texelU <= widthMask); - - s_vCoordStep = div16(srcWall->topTexelHeight, next_yC0 - yC0 + ONE_16); - s_vCoordFixed = srcWall->topOffset.z + mul16(next_yC0 - intToFixed16(next_yC0_pixel) + HALF_16, s_vCoordStep); - s_texImage = &texture->image[texelU << texture->logSizeY]; - - s_columnOut = &s_display[yC0_pixel * s_width + x]; - s_columnLight = computeLighting(z, floor16(srcWall->wallLight)); - if (s_columnLight) - { - drawColumn_Lit(); - } - else - { - drawColumn_Fullbright(); - } - - // Handle the "sign texture" - a wall overlay. - if (signTex && uCoord >= signU0 && uCoord <= signU1) - { -#ifdef TFE_ESPBOX - const fixed16_16 rcpVCoordStep = div16(ONE_16, s_vCoordStep); - fixed16_16 signYBase = next_yC0 + mul16(srcWall->signOffset.z, rcpVCoordStep); - s32 y0 = max(floor16(signYBase - mul16(intToFixed16(signTex->height), rcpVCoordStep) + ONE_16 + HALF_16), yC0_pixel); -#else - fixed16_16 signYBase = next_yC0 + div16(srcWall->signOffset.z, s_vCoordStep); - s32 y0 = max(floor16(signYBase - div16(intToFixed16(signTex->height), s_vCoordStep) + ONE_16 + HALF_16), yC0_pixel); -#endif - s32 y1 = min(floor16(signYBase + HALF_16), next_yC0_pixel); - s_yPixelCount = y1 - y0 + 1; - - if (s_yPixelCount > 0) - { - s_vCoordFixed = mul16(signYBase - intToFixed16(y1) + HALF_16, s_vCoordStep); - s_columnOut = &s_display[y0*s_width + x]; - texelU = floor16(uCoord - signU0); - s_texImage = &signTex->image[texelU << signTex->logSizeY]; - - s32 heightMask = s_texHeightMask; - s_texHeightMask = signTex->height - 1; - if (s_columnLight) - { - signLit(); - } - else - { - signFullbright(); - } - s_texHeightMask = heightMask; - } - } - } - - yC0 += ceil_dYdX; - next_yC0 += next_ceil_dYdX; - yF0 += floor_dYdX; - } - - srcWall->seen = JTRUE; - } - - void wall_drawTopAndBottom(RWallSegmentFixed* wallSegment) - { - RWall* srcWall = wallSegment->srcWall; - RSector* sector = srcWall->sector; - TextureData* topTex = *srcWall->topTex; - fixed16_16 z0 = wallSegment->z0; - fixed16_16 z1 = wallSegment->z1; - s32 x0 = wallSegment->wallX0; -#ifdef TFE_ESPBOX - s32 xOffset = wallSegment->wallX0 - wallSegment->wallX0_raw; -#else - fixed16_16 xOffset = intToFixed16(wallSegment->wallX0 - wallSegment->wallX0_raw); -#endif - s32 length = wallSegment->wallX1 - wallSegment->wallX0 + 1; -#ifdef TFE_ESPBOX - s32 lengthRaw = wallSegment->wallX1_raw - wallSegment->wallX0_raw; - fixed16_16 rcpLengthRaw = 0; - if (lengthRaw != 0) - { - rcpLengthRaw = ONE_16 / lengthRaw; - } -#else - fixed16_16 lengthRaw = intToFixed16(wallSegment->wallX1_raw - wallSegment->wallX0_raw); -#endif - - fixed16_16 ceilRel = sector->ceilingHeight - s_rcfState.eyeHeight; - fixed16_16 cProj0, cProj1; -#ifdef TFE_ESPBOX - cProj0 = div16((ceilRel * s_rcfState.focalLenAspect), z0) + s_rcfState.projOffsetY; - cProj1 = div16((ceilRel * s_rcfState.focalLenAspect), z1) + s_rcfState.projOffsetY; -#else - cProj0 = div16(mul16(ceilRel, s_rcfState.focalLenAspect), z0) + s_rcfState.projOffsetY; - cProj1 = div16(mul16(ceilRel, s_rcfState.focalLenAspect), z1) + s_rcfState.projOffsetY; -#endif - - s32 c0_pixel = round16(cProj0); - s32 c1_pixel = round16(cProj1); - - if (c0_pixel > s_windowMaxY_Pixels && c1_pixel > s_windowMaxY_Pixels) - { - srcWall->visible = 0; - for (s32 i = 0; i < length; i++) { s_columnTop[x0 + i] = s_windowMaxY_Pixels; } - - flat_addEdges(length, x0, 0, intToFixed16(s_windowMaxY_Pixels + 1), 0, intToFixed16(s_windowMaxY_Pixels + 1)); - fixed16_16 num = solveForZ_Numerator(wallSegment); - for (s32 i = 0, x = x0; i < length; i++, x++) - { - s_rcfState.depth1d[x] = solveForZ(wallSegment, x, num); - s_columnTop[x] = s_windowMaxY_Pixels; - } - srcWall->seen = JTRUE; - return; - } - - fixed16_16 floorRel = sector->floorHeight - s_rcfState.eyeHeight; - fixed16_16 fProj0, fProj1; -#ifdef TFE_ESPBOX - fProj0 = div16((floorRel * s_rcfState.focalLenAspect), z0) + s_rcfState.projOffsetY; - fProj1 = div16((floorRel * s_rcfState.focalLenAspect), z1) + s_rcfState.projOffsetY; -#else - fProj0 = div16(mul16(floorRel, s_rcfState.focalLenAspect), z0) + s_rcfState.projOffsetY; - fProj1 = div16(mul16(floorRel, s_rcfState.focalLenAspect), z1) + s_rcfState.projOffsetY; -#endif - - s32 f0_pixel = round16(fProj0); - s32 f1_pixel = round16(fProj1); - if (f0_pixel < s_windowMinY_Pixels && f1_pixel < s_windowMinY_Pixels) - { - srcWall->visible = 0; - for (s32 i = 0; i < length; i++) { s_columnBot[x0 + i] = s_windowMinY_Pixels; } - - flat_addEdges(length, x0, 0, intToFixed16(s_windowMinY_Pixels - 1), 0, intToFixed16(s_windowMinY_Pixels - 1)); - fixed16_16 num = solveForZ_Numerator(wallSegment); - - for (s32 i = 0, x = x0; i < length; i++, x++) - { - s_rcfState.depth1d[x] = solveForZ(wallSegment, x, num); - s_columnBot[x] = s_windowMinY_Pixels; - } - srcWall->seen = JTRUE; - return; - } - - RSector* nextSector = srcWall->nextSector; - fixed16_16 next_ceilRel = nextSector->ceilingHeight - s_rcfState.eyeHeight; - fixed16_16 next_cProj0, next_cProj1; -#ifdef TFE_ESPBOX - next_cProj0 = div16((next_ceilRel * s_rcfState.focalLenAspect), z0) + s_rcfState.projOffsetY; - next_cProj1 = div16((next_ceilRel * s_rcfState.focalLenAspect), z1) + s_rcfState.projOffsetY; -#else - next_cProj0 = div16(mul16(next_ceilRel, s_rcfState.focalLenAspect), z0) + s_rcfState.projOffsetY; - next_cProj1 = div16(mul16(next_ceilRel, s_rcfState.focalLenAspect), z1) + s_rcfState.projOffsetY; -#endif - - fixed16_16 ceil_dYdX = 0; - fixed16_16 next_ceil_dYdX = 0; -#ifdef TFE_ESPBOX - if (lengthRaw != 0) - { - /* - ceil_dYdX = (cProj1 - cProj0) / lengthRaw; - next_ceil_dYdX = (next_cProj1 - next_cProj0) / lengthRaw; - */ - ceil_dYdX = mul16(cProj1 - cProj0, rcpLengthRaw); - next_ceil_dYdX = mul16(next_cProj1 - next_cProj0, rcpLengthRaw); - } - if (xOffset) - { - cProj0 += ceil_dYdX * xOffset; - next_cProj0 += next_ceil_dYdX * xOffset; - } -#else - if (lengthRaw != 0) - { - ceil_dYdX = div16(cProj1 - cProj0, lengthRaw); - next_ceil_dYdX = div16(next_cProj1 - next_cProj0, lengthRaw); - } - if (xOffset) - { - cProj0 += mul16(ceil_dYdX, xOffset); - next_cProj0 += mul16(next_ceil_dYdX, xOffset); - } -#endif - - fixed16_16 yC0 = cProj0; - fixed16_16 yC1 = next_cProj0; - - s32 cn0_pixel = round16(next_cProj0); - s32 cn1_pixel = round16(next_cProj1); - if (topTex && (cn0_pixel >= s_windowMinY_Pixels || cn1_pixel >= s_windowMinY_Pixels)) - { - fixed16_16 u0 = wallSegment->uCoord0; - fixed16_16 num = solveForZ_Numerator(wallSegment); - s_texHeightMask = topTex->height - 1; - JBool flipHorz = ((srcWall->flags1 & WF1_FLIP_HORIZ)!=0) ? JTRUE : JFALSE; - - for (s32 i = 0, x = x0; i < length; i++, x++) - { - s32 yC1_pixel = round16(yC1); - s32 yC0_pixel = round16(yC0); - s_columnTop[x] = yC0_pixel - 1; - s32 top = s_windowTop[x]; - if (yC0_pixel < top) - { - yC0_pixel = top; - } - s32 bot = s_windowBot[x]; - if (yC1_pixel > bot) - { - yC1_pixel = bot; - } - s_yPixelCount = yC1_pixel - yC0_pixel + 1; - - // Calculate perspective correct Z and U (texture coordinate). - fixed16_16 dxView; - fixed16_16 z = solveForZ(wallSegment, x, num, &dxView); - fixed16_16 u; - if (wallSegment->orient == WORIENT_DZ_DX) - { - u = u0 + mul16(dxView, wallSegment->uScale) + srcWall->topOffset.x; - } - else - { - fixed16_16 dz = z - z0; - u = u0 + mul16(dz, wallSegment->uScale) + srcWall->topOffset.x; - } - s_rcfState.depth1d[x] = z; - if (s_yPixelCount > 0) - { - s32 widthMask = topTex->width - 1; - s32 texelU = floor16(u) & widthMask; - if (flipHorz) - { - texelU = widthMask - texelU; - } - s_vCoordStep = div16(srcWall->topTexelHeight, yC1 - yC0 + ONE_16); - fixed16_16 yOffset = yC1 - intToFixed16(yC1_pixel) + HALF_16; - s_vCoordFixed = mul16(yOffset, s_vCoordStep) + srcWall->topOffset.z; - s_texImage = &topTex->image[texelU << topTex->logSizeY]; - s_columnOut = &s_display[yC0_pixel * s_width + x]; - s_columnLight = computeLighting(z, floor16(srcWall->wallLight)); - - if (s_columnLight) - { - drawColumn_Lit(); - } - else - { - drawColumn_Fullbright(); - } - } - yC0 += ceil_dYdX; - yC1 += next_ceil_dYdX; - } - } - else - { - for (s32 i = 0; i < length; i++) { s_columnTop[x0 + i] = s_windowMinY_Pixels - 1; } - } - - fixed16_16 next_floorRel = nextSector->floorHeight - s_rcfState.eyeHeight; - fixed16_16 next_fProj0, next_fProj1; -#ifdef TFE_ESPBOX - next_fProj0 = div16((next_floorRel * s_rcfState.focalLenAspect), z0) + s_rcfState.projOffsetY; - next_fProj1 = div16((next_floorRel * s_rcfState.focalLenAspect), z1) + s_rcfState.projOffsetY; -#else - next_fProj0 = div16(mul16(next_floorRel, s_rcfState.focalLenAspect), z0) + s_rcfState.projOffsetY; - next_fProj1 = div16(mul16(next_floorRel, s_rcfState.focalLenAspect), z1) + s_rcfState.projOffsetY; -#endif - - fixed16_16 next_floor_dYdX = 0; - fixed16_16 floor_dYdX = 0; -#ifdef TFE_ESPBOX - if (lengthRaw > 0) - { - /* - next_floor_dYdX = (next_fProj1 - next_fProj0) / lengthRaw; - floor_dYdX = (fProj1 - fProj0) / lengthRaw; - */ - next_floor_dYdX = mul16(next_fProj1 - next_fProj0, rcpLengthRaw); - floor_dYdX = mul16(fProj1 - fProj0, rcpLengthRaw); - } - if (xOffset) - { - next_fProj0 += next_floor_dYdX * xOffset; - fProj0 += floor_dYdX * xOffset; - } -#else - if (lengthRaw > 0) - { - next_floor_dYdX = div16(next_fProj1 - next_fProj0, lengthRaw); - floor_dYdX = div16(fProj1 - fProj0, lengthRaw); - } - if (xOffset) - { - next_fProj0 += mul16(next_floor_dYdX, xOffset); - fProj0 += mul16(floor_dYdX, xOffset); - } -#endif - - fixed16_16 yF0 = next_fProj0; - fixed16_16 yF1 = fProj0; - TextureData* botTex = *srcWall->botTex; - f0_pixel = round16(next_fProj0); - f1_pixel = round16(next_fProj1); - - if (botTex && (f0_pixel <= s_windowMaxY_Pixels || f1_pixel <= s_windowMaxY_Pixels)) - { - fixed16_16 u0 = wallSegment->uCoord0; - fixed16_16 num = solveForZ_Numerator(wallSegment); - - s_texHeightMask = botTex->height - 1; - JBool flipHorz = ((srcWall->flags1 & WF1_FLIP_HORIZ)!=0) ? JTRUE : JFALSE; - JBool illumSign = ((srcWall->flags1 & WF1_ILLUM_SIGN)!=0) ? JTRUE : JFALSE; - - fixed16_16 signU0 = 0, signU1 = 0; - ColumnFunction signFullbright = nullptr, signLit = nullptr; - TextureData* signTex = setupSignTexture(srcWall, &signU0, &signU1, &signFullbright, &signLit); - - if (length > 0) - { - for (s32 i = 0, x = x0; i < length; i++, x++) - { - s32 yF0_pixel = round16(yF0); - s32 yF1_pixel = round16(yF1); - s32 top = s_windowTop[x]; - s_columnBot[x] = yF1_pixel + 1; - if (yF0_pixel < top) - { - yF0_pixel = top; - } - s32 bot = s_windowBot[x]; - if (yF1_pixel > bot) - { - yF1_pixel = bot; - } - s_yPixelCount = yF1_pixel - yF0_pixel + 1; // eax - - // Calculate perspective correct Z and U (texture coordinate). - fixed16_16 dxView; - fixed16_16 z = solveForZ(wallSegment, x, num, &dxView); - fixed16_16 uCoord; - if (wallSegment->orient == WORIENT_DZ_DX) - { - uCoord = u0 + mul16(dxView, wallSegment->uScale) + srcWall->botOffset.x; - } - else - { - fixed16_16 dz = z - z0; - uCoord = u0 + mul16(dz, wallSegment->uScale) + srcWall->botOffset.x; - } - s_rcfState.depth1d[x] = z; - if (s_yPixelCount > 0) - { - s32 widthMask = botTex->width - 1; - s32 texelU = floor16(uCoord) & widthMask; - if (flipHorz) - { - texelU = widthMask - texelU; - } - s_vCoordStep = div16(srcWall->botTexelHeight, yF1 - yF0 + ONE_16); - s_vCoordFixed = srcWall->botOffset.z + mul16(yF1 - intToFixed16(yF1_pixel) + HALF_16, s_vCoordStep); - s_texImage = &botTex->image[texelU << botTex->logSizeY]; - s_columnOut = &s_display[yF0_pixel * s_width + x]; - s_columnLight = computeLighting(z, floor16(srcWall->wallLight)); - - if (s_columnLight) - { - drawColumn_Lit(); - } - else - { - drawColumn_Fullbright(); - } - - // Handle the "sign texture" - a wall overlay. - if (signTex && uCoord >= signU0 && uCoord <= signU1) - { -#ifdef TFE_ESPBOX - const fixed16_16 rcpVCoordStep = div16(ONE_16, s_vCoordStep); - fixed16_16 signYBase = yF1 + mul16(srcWall->signOffset.z, rcpVCoordStep); - s32 y0 = max(floor16(signYBase - mul16(intToFixed16(signTex->height), rcpVCoordStep) + ONE_16 + HALF_16), yF0_pixel); -#else - fixed16_16 signYBase = yF1 + div16(srcWall->signOffset.z, s_vCoordStep); - s32 y0 = max(floor16(signYBase - div16(intToFixed16(signTex->height), s_vCoordStep) + ONE_16 + HALF_16), yF0_pixel); -#endif - s32 y1 = min(floor16(signYBase + HALF_16), yF1_pixel); - s_yPixelCount = y1 - y0 + 1; - - if (s_yPixelCount > 0) - { - s_vCoordFixed = mul16(signYBase - intToFixed16(y1) + HALF_16, s_vCoordStep); - s_columnOut = &s_display[y0*s_width + x]; - texelU = floor16(uCoord - signU0); - s_texImage = &signTex->image[texelU << signTex->logSizeY]; - - s32 heightMask = s_texHeightMask; - s_texHeightMask = signTex->height - 1; - if (s_columnLight) - { - signLit(); - } - else - { - signFullbright(); - } - s_texHeightMask = heightMask; - } - } - } - yF1 += floor_dYdX; - yF0 += next_floor_dYdX; - } - } - } - else - { - for (s32 i = 0; i < length; i++) { s_columnBot[x0 + i] = s_windowMaxY_Pixels + 1; } - } - flat_addEdges(length, x0, floor_dYdX, fProj0, ceil_dYdX, cProj0); - - s32 next_f0_pixel = round16(next_fProj0); - s32 next_f1_pixel = round16(next_fProj1); - s32 next_c0_pixel = round16(next_cProj0); - s32 next_c1_pixel = round16(next_cProj1); - if ((next_f0_pixel <= s_windowMinY_Pixels && next_f1_pixel <= s_windowMinY_Pixels) || (next_c0_pixel >= s_windowMaxY_Pixels && next_c1_pixel >= s_windowMaxY_Pixels) || (nextSector->floorHeight <= nextSector->ceilingHeight)) - { - srcWall->seen = JTRUE; - return; - } - - wall_addAdjoinSegment(length, x0, next_floor_dYdX, next_fProj0 - ONE_16, next_ceil_dYdX, next_cProj0 + ONE_16, wallSegment); - srcWall->seen = JTRUE; - } - - // Parts of the code inside 's_height == SKY_BASE_HEIGHT' are based on the original DOS exe. - // Other parts of those same conditionals are modified to handle higher resolutions. - void wall_drawSkyTop(RSector* sector) - { - if (s_wallMaxCeilY < s_windowMinY_Pixels) { return; } - TFE_ZONE("Draw Sky"); - - TextureData* texture = *sector->ceilTex; - fixed16_16 heightScale; - // In the original code (at the original 200p resolution) the sky is setup to step exactly one texel per vertical pixel - // However with higher resolutions this must be scaled to look the same. - if (s_height == SKY_BASE_HEIGHT) - { - s_vCoordStep = ONE_16; - heightScale = ONE_16; - } - else - { - s_vCoordStep = ONE_16 * SKY_BASE_HEIGHT / s_height; - heightScale = div16(intToFixed16(SKY_BASE_HEIGHT), intToFixed16(s_height)); - } - s_texHeightMask = texture->height - 1; - const s32 texWidthMask = texture->width - 1; - - for (s32 x = s_windowMinX_Pixels; x <= s_windowMaxX_Pixels; x++) - { - const s32 y0 = s_windowTop[x]; - const s32 y1 = min(s_columnTop[x], s_windowBot[x]); - - s_yPixelCount = y1 - y0 + 1; - if (s_yPixelCount > 0) - { - if (s_height == SKY_BASE_HEIGHT) - { - s_vCoordFixed = intToFixed16(s_texHeightMask - y1) - s_rcfState.skyPitchOffset - sector->ceilOffset.z; - } - else - { - s_vCoordFixed = intToFixed16(s_texHeightMask) - mul16(intToFixed16(y1), heightScale) - s_rcfState.skyPitchOffset - sector->ceilOffset.z; - } - - s32 texelU = ( floor16(sector->ceilOffset.x - s_rcfState.skyYawOffset + s_rcfState.skyTable[x]) ) & texWidthMask; - s_texImage = &texture->image[texelU << texture->logSizeY]; - s_columnOut = &s_display[y0*s_width + x]; - drawColumn_Fullbright(); - } - } - } - - void wall_drawSkyTopNoWall(RSector* sector) - { - TFE_ZONE("Draw Sky"); - const TextureData* texture = *sector->ceilTex; - - fixed16_16 heightScale; - // In the original code (at the original 200p resolution) the sky is setup to step exactly one texel per vertical pixel - // However with higher resolutions this must be scaled to look the same. - if (s_height == SKY_BASE_HEIGHT) - { - s_vCoordStep = ONE_16; - heightScale = ONE_16; - } - else - { - s_vCoordStep = ONE_16 * SKY_BASE_HEIGHT / s_height; - heightScale = div16(intToFixed16(SKY_BASE_HEIGHT), intToFixed16(s_height)); - } - - s_texHeightMask = texture->height - 1; - for (s32 x = s_windowMinX_Pixels; x <= s_windowMaxX_Pixels; x++) - { - const s32 y0 = s_windowTop[x]; - const s32 y1 = min(s_screenYMidFix - 1, s_windowBot[x]); - - s_yPixelCount = y1 - y0 + 1; - if (s_yPixelCount > 0) - { - if (s_height == SKY_BASE_HEIGHT) - { - s_vCoordFixed = intToFixed16(s_texHeightMask - y1) - s_rcfState.skyPitchOffset - sector->ceilOffset.z; - } - else - { - s_vCoordFixed = intToFixed16(s_texHeightMask) - mul16(intToFixed16(y1), heightScale) - s_rcfState.skyPitchOffset - sector->ceilOffset.z; - } - - s32 widthMask = texture->width - 1; - s32 texelU = floor16(sector->ceilOffset.x - s_rcfState.skyYawOffset + s_rcfState.skyTable[x]) & widthMask; - s_texImage = &texture->image[texelU << texture->logSizeY]; - s_columnOut = &s_display[y0*s_width + x]; - - drawColumn_Fullbright(); - } - } - } - - // Parts of the code inside 's_height == SKY_BASE_HEIGHT' are based on the original DOS exe. - // Other parts of those same conditionals are modified to handle higher resolutions. - void wall_drawSkyBottom(RSector* sector) - { - if (s_wallMinFloorY > s_windowMaxY_Pixels) { return; } - TFE_ZONE("Draw Sky"); - - TextureData* texture = *sector->floorTex; - fixed16_16 heightScale; - // In the original code (at the original 200p resolution) the sky is setup to step exactly one texel per vertical pixel - // However with higher resolutions this must be scaled to look the same. - if (s_height == SKY_BASE_HEIGHT) - { - s_vCoordStep = ONE_16; - heightScale = ONE_16; - } - else - { - s_vCoordStep = ONE_16 * SKY_BASE_HEIGHT / s_height; - heightScale = div16(intToFixed16(SKY_BASE_HEIGHT), intToFixed16(s_height)); - } - s_texHeightMask = texture->height - 1; - const s32 texWidthMask = texture->width - 1; - - for (s32 x = s_windowMinX_Pixels; x <= s_windowMaxX_Pixels; x++) - { - const s32 y0 = max(s_columnBot[x], s_windowTop[x]); - const s32 y1 = s_windowBot[x]; - - s_yPixelCount = y1 - y0 + 1; - if (s_yPixelCount > 0) - { - if (s_height == SKY_BASE_HEIGHT) - { - s_vCoordFixed = intToFixed16(s_texHeightMask - y1) - s_rcfState.skyPitchOffset - sector->floorOffset.z; - } - else - { - s_vCoordFixed = intToFixed16(s_texHeightMask) - mul16(intToFixed16(y1), heightScale) - s_rcfState.skyPitchOffset - sector->floorOffset.z; - } - - s32 texelU = floor16(sector->floorOffset.x - s_rcfState.skyYawOffset + s_rcfState.skyTable[x]) & texWidthMask; - s_texImage = &texture->image[texelU << texture->logSizeY]; - s_columnOut = &s_display[y0*s_width + x]; - drawColumn_Fullbright(); - } - } - } - - void wall_drawSkyBottomNoWall(RSector* sector) - { - TFE_ZONE("Draw Sky"); - const TextureData* texture = *sector->floorTex; - - fixed16_16 heightScale; - // In the original code (at the original 200p resolution) the sky is setup to step exactly one texel per vertical pixel - // However with higher resolutions this must be scaled to look the same. - if (s_height == SKY_BASE_HEIGHT) - { - s_vCoordStep = ONE_16; - heightScale = ONE_16; - } - else - { - s_vCoordStep = ONE_16 * SKY_BASE_HEIGHT / s_height; - heightScale = div16(intToFixed16(SKY_BASE_HEIGHT), intToFixed16(s_height)); - } - - s_texHeightMask = texture->height - 1; - for (s32 x = s_windowMinX_Pixels; x <= s_windowMaxX_Pixels; x++) - { - const s32 y0 = max(s_screenYMidFix, s_windowTop[x]); - const s32 y1 = s_windowBot[x]; - - s_yPixelCount = y1 - y0 + 1; - if (s_yPixelCount > 0) - { - if (s_height == SKY_BASE_HEIGHT) - { - s_vCoordFixed = intToFixed16(s_texHeightMask - y1) - s_rcfState.skyPitchOffset - sector->floorOffset.z; - } - else - { - s_vCoordFixed = intToFixed16(s_texHeightMask) - mul16(intToFixed16(y1), heightScale) - s_rcfState.skyPitchOffset - sector->floorOffset.z; - } - - s32 widthMask = texture->width - 1; - s32 texelU = floor16(sector->floorOffset.x - s_rcfState.skyYawOffset + s_rcfState.skyTable[x]) & widthMask; - s_texImage = &texture->image[texelU << texture->logSizeY]; - s_columnOut = &s_display[y0*s_width + x]; - - drawColumn_Fullbright(); - } - } - } - - // Determines if segment A is disjoint from the line formed by B - i.e. they do not intersect. - // Returns 1 if segment A does NOT cross line B or 0 if it does. -#ifdef TFE_ESPBOX - static inline -#endif - s32 segmentCrossesLine(fixed16_16 ax0, fixed16_16 ay0, fixed16_16 ax1, fixed16_16 ay1, fixed16_16 bx0, fixed16_16 by0, fixed16_16 bx1, fixed16_16 by1) - { - // Convert from 16 fractional bits to 12. - bx0 = fixed16to12(bx0); - by0 = fixed16to12(by0); - ax1 = fixed16to12(ax1); - ax0 = fixed16to12(ax0); - ay0 = fixed16to12(ay0); - ay1 = fixed16to12(ay1); - bx1 = fixed16to12(bx1); - by1 = fixed16to12(by1); - - // mul16() functions on 12 bit values is equivalent to: a * b / 16 - // [ (a1-b0)x(b1-b0) ].[ (a0-b0)x(b1 - b0) ] - // In 2D x = "perp product" - s_segmentCross = mul16(mul16(ax1 - bx0, by1 - by0) - mul16(ay1 - by0, bx1 - bx0), - mul16(ax0 - bx0, by1 - by0) - mul16(ay0 - by0, bx1 - bx0)); - - return s_segmentCross > 0 ? 1 : 0; - } - - // When solving for Z, part of the computation can be done once per wall. - fixed16_16 solveForZ_Numerator(RWallSegmentFixed* wallSegment) - { - const fixed16_16 z0 = wallSegment->z0; - - fixed16_16 numerator; - if (wallSegment->orient == WORIENT_DZ_DX) - { - numerator = z0 - mul16(wallSegment->slope, wallSegment->x0View); - } - else // WORIENT_DX_DZ - { - numerator = wallSegment->x0View - mul16(wallSegment->slope, z0); - } - - return numerator; - } - - // Solve for perspective correct Z at the current x pixel coordinate. - fixed16_16 solveForZ(RWallSegmentFixed* wallSegment, s32 x, fixed16_16 numerator, fixed16_16* outViewDx/*=nullptr*/) - { - fixed16_16 z; // perspective correct z coordinate at the current x pixel coordinate. - if (wallSegment->orient == WORIENT_DZ_DX) - { - // Solve for viewspace X at the current pixel x coordinate in order to get dx in viewspace. - fixed16_16 den = s_rcfState.column_Z_Over_X[x] - wallSegment->slope; - // Avoid divide by zero. - if (den == 0) { den = 1; } - - fixed16_16 xView = div16(numerator, den); - // Use the saved x0View to get dx in viewspace. - fixed16_16 dxView = xView - wallSegment->x0View; - // avoid recalculating for u coordinate computation. - if (outViewDx) { *outViewDx = dxView; } - // Once we have dx in viewspace, we multiply by the slope (dZ/dX) in order to get dz. - fixed16_16 dz = mul16(dxView, wallSegment->slope); - // Then add z0 to get z(x) that is perspective correct. - z = wallSegment->z0 + dz; - } - else // WORIENT_DX_DZ - { - // Directly solve for Z at the current pixel x coordinate. - fixed16_16 den = s_rcfState.column_X_Over_Z[x] - wallSegment->slope; - // Avoid divide by 0. - if (den == 0) { den = 1; } - - z = div16(numerator, den); - } - - return z; - } - - void drawColumn_Fullbright() - { - fixed16_16 vCoordFixed = s_vCoordFixed; - u8* tex = s_texImage; - - s32 v = floor16(vCoordFixed) & s_texHeightMask; - s32 end = s_yPixelCount - 1; - - s32 offset = end * s_width; - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - const u8 c = tex[v]; - vCoordFixed += s_vCoordStep; - v = floor16(vCoordFixed) & s_texHeightMask; - s_columnOut[offset] = c; - } - } - - void drawColumn_Lit() - { - fixed16_16 vCoordFixed = s_vCoordFixed; - u8* tex = s_texImage; - - s32 v = floor16(vCoordFixed) & s_texHeightMask; - s32 end = s_yPixelCount - 1; - - s32 offset = end * s_width; - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - const u8 c = s_columnLight[tex[v]]; - vCoordFixed += s_vCoordStep; - v = floor16(vCoordFixed) & s_texHeightMask; - s_columnOut[offset] = c; - } - } - - void drawColumn_Fullbright_Trans() - { - fixed16_16 vCoordFixed = s_vCoordFixed; - u8* tex = s_texImage; - - s32 v = floor16(vCoordFixed) & s_texHeightMask; - s32 end = s_yPixelCount - 1; - - s32 offset = end * s_width; - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - const u8 c = tex[v]; - vCoordFixed += s_vCoordStep; - v = floor16(vCoordFixed) & s_texHeightMask; - if (c) { s_columnOut[offset] = c; } - } - } - - void drawColumn_Lit_Trans() - { - fixed16_16 vCoordFixed = s_vCoordFixed; - u8* tex = s_texImage; - - s32 v = floor16(vCoordFixed) & s_texHeightMask; - s32 end = s_yPixelCount - 1; - - s32 offset = end * s_width; - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - const u8 c = tex[v]; - vCoordFixed += s_vCoordStep; - v = floor16(vCoordFixed) & s_texHeightMask; - if (c) { s_columnOut[offset] = s_columnLight[c]; } - } - } - -#ifdef TFE_ESPBOX - void drawColumnS_Fullbright() - { - fixed16_16 vCoordFixed = s_vCoordFixed; - u8* tex = s_texImage; - - s32 v = floor16(vCoordFixed); - s32 end = s_yPixelCount - 1; - - s32 offset = end * s_width; - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - const u8 c = tex[v]; - vCoordFixed += s_vCoordStep; - v = floor16(vCoordFixed); - s_columnOut[offset] = c; - } - } - - void drawColumnS_Lit() - { - fixed16_16 vCoordFixed = s_vCoordFixed; - u8* tex = s_texImage; - - s32 v = floor16(vCoordFixed); - s32 end = s_yPixelCount - 1; - - s32 offset = end * s_width; - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - const u8 c = s_columnLight[tex[v]]; - vCoordFixed += s_vCoordStep; - v = floor16(vCoordFixed); - s_columnOut[offset] = c; - } - } - - void drawColumnS_Fullbright_Trans() - { - fixed16_16 vCoordFixed = s_vCoordFixed; - u8* tex = s_texImage; - - s32 v = floor16(vCoordFixed); - s32 end = s_yPixelCount - 1; - - s32 offset = end * s_width; -#ifdef SPRTEST - switch (s_xPixelCount+1) - { - case 1: - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - u8 c = tex[v]; - vCoordFixed += s_vCoordStep; - v = floor16(vCoordFixed); - if (c) { s_columnOut[offset] = c; } - } - break; - case 2: - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - u8 c = tex[v]; - vCoordFixed += s_vCoordStep; - v = floor16(vCoordFixed); - if (c) - { - //c = s_xPixelCount; // TODO test - s_columnOut[offset] = c; - s_columnOut[offset+1] = c; - } - } - break; - case 3: - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - u8 c = tex[v]; - vCoordFixed += s_vCoordStep; - v = floor16(vCoordFixed); - if (c) - { - //c = s_xPixelCount; // TODO test - s_columnOut[offset] = c; - s_columnOut[offset+1] = c; - s_columnOut[offset+2] = c; - } - } - break; - case 4: - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - u8 c = tex[v]; - vCoordFixed += s_vCoordStep; - v = floor16(vCoordFixed); - if (c) - { - //c = s_xPixelCount; // TODO test - s_columnOut[offset] = c; - s_columnOut[offset+1] = c; - s_columnOut[offset+2] = c; - s_columnOut[offset+3] = c; - } - } - break; - case 5: - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - u8 c = tex[v]; - vCoordFixed += s_vCoordStep; - v = floor16(vCoordFixed); - if (c) - { - //c = s_xPixelCount; // TODO test - s_columnOut[offset] = c; - s_columnOut[offset+1] = c; - s_columnOut[offset+2] = c; - s_columnOut[offset+3] = c; - s_columnOut[offset+4] = c; - } - } - break; - case 6: - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - u8 c = tex[v]; - vCoordFixed += s_vCoordStep; - v = floor16(vCoordFixed); - if (c) - { - //c = s_xPixelCount; // TODO test - s_columnOut[offset] = c; - s_columnOut[offset+1] = c; - s_columnOut[offset+2] = c; - s_columnOut[offset+3] = c; - s_columnOut[offset+4] = c; - s_columnOut[offset+5] = c; - } - } - break; - case 7: - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - u8 c = tex[v]; - vCoordFixed += s_vCoordStep; - v = floor16(vCoordFixed); - if (c) - { - //c = s_xPixelCount; // TODO test - s_columnOut[offset] = c; - s_columnOut[offset+1] = c; - s_columnOut[offset+2] = c; - s_columnOut[offset+3] = c; - s_columnOut[offset+4] = c; - s_columnOut[offset+5] = c; - s_columnOut[offset+6] = c; - } - } - break; - case 8: - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - u8 c = tex[v]; - vCoordFixed += s_vCoordStep; - v = floor16(vCoordFixed); - if (c) - { - ////c = s_xPixelCount; // TODO test - s_columnOut[offset] = c; - s_columnOut[offset+1] = c; - s_columnOut[offset+2] = c; - s_columnOut[offset+3] = c; - s_columnOut[offset+4] = c; - s_columnOut[offset+5] = c; - s_columnOut[offset+6] = c; - s_columnOut[offset+7] = c; - } - } - break; - default: - //kprintf("unhandled width %ld\n", s_xPixelCount+1); - break; - } -#else - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - const u8 c = tex[v]; - vCoordFixed += s_vCoordStep; - v = floor16(vCoordFixed); - if (c) { s_columnOut[offset] = c; } - } -#endif - } - - void drawColumnS_Lit_Trans() - { - fixed16_16 vCoordFixed = s_vCoordFixed; - u8* tex = s_texImage; - - s32 v = floor16(vCoordFixed); - s32 end = s_yPixelCount - 1; - - s32 offset = end * s_width; -#ifdef SPRTEST - switch (s_xPixelCount+1) - { - case 1: - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - u8 c = tex[v]; - vCoordFixed += s_vCoordStep; - v = floor16(vCoordFixed); - if (c) { s_columnOut[offset] = s_columnLight[c]; } - } - break; - case 2: - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - u8 c = tex[v]; - vCoordFixed += s_vCoordStep; - v = floor16(vCoordFixed); - if (c) - { - c = s_columnLight[c]; - s_columnOut[offset] = c; - s_columnOut[offset+1] = c; - } - } - break; - case 3: - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - u8 c = tex[v]; - vCoordFixed += s_vCoordStep; - v = floor16(vCoordFixed); - if (c) - { - c = s_columnLight[c]; - s_columnOut[offset] = c; - s_columnOut[offset+1] = c; - s_columnOut[offset+2] = c; - } - } - break; - case 4: - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - u8 c = tex[v]; - vCoordFixed += s_vCoordStep; - v = floor16(vCoordFixed); - if (c) - { - c = s_columnLight[c]; - s_columnOut[offset] = c; - s_columnOut[offset+1] = c; - s_columnOut[offset+2] = c; - s_columnOut[offset+3] = c; - } - } - break; - case 5: - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - u8 c = tex[v]; - vCoordFixed += s_vCoordStep; - v = floor16(vCoordFixed); - if (c) - { - c = s_columnLight[c]; - s_columnOut[offset] = c; - s_columnOut[offset+1] = c; - s_columnOut[offset+2] = c; - s_columnOut[offset+3] = c; - s_columnOut[offset+4] = c; - } - } - break; - case 6: - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - u8 c = tex[v]; - vCoordFixed += s_vCoordStep; - v = floor16(vCoordFixed); - if (c) - { - c = s_columnLight[c]; - s_columnOut[offset] = c; - s_columnOut[offset+1] = c; - s_columnOut[offset+2] = c; - s_columnOut[offset+3] = c; - s_columnOut[offset+4] = c; - s_columnOut[offset+5] = c; - } - } - break; - case 7: - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - u8 c = tex[v]; - vCoordFixed += s_vCoordStep; - v = floor16(vCoordFixed); - if (c) - { - c = s_columnLight[c]; - s_columnOut[offset] = c; - s_columnOut[offset+1] = c; - s_columnOut[offset+2] = c; - s_columnOut[offset+3] = c; - s_columnOut[offset+4] = c; - s_columnOut[offset+5] = c; - s_columnOut[offset+6] = c; - } - } - break; - case 8: - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - u8 c = tex[v]; - vCoordFixed += s_vCoordStep; - v = floor16(vCoordFixed); - if (c) - { - c = s_columnLight[c]; - s_columnOut[offset] = c; - s_columnOut[offset+1] = c; - s_columnOut[offset+2] = c; - s_columnOut[offset+3] = c; - s_columnOut[offset+4] = c; - s_columnOut[offset+5] = c; - s_columnOut[offset+6] = c; - s_columnOut[offset+7] = c; - } - } - break; - default: - //kprintf("unhandled width %ld\n", s_xPixelCount+1); - break; - } -#else - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - const u8 c = tex[v]; - vCoordFixed += s_vCoordStep; - v = floor16(vCoordFixed); - if (c) { s_columnOut[offset] = s_columnLight[c]; } - } -#endif - } -#endif - - static inline void wall_addAdjoinSegment(s32 length, s32 x0, fixed16_16 top_dydx, fixed16_16 y1, fixed16_16 bot_dydx, fixed16_16 y0, RWallSegmentFixed* wallSegment) - { - if (s_adjoinSegCount < MAX_ADJOIN_SEG) - { -#ifdef TFE_ESPBOX - s32 lengthMinusOne = length - 1; - fixed16_16 y0End = y0; - if (bot_dydx != 0) - { - y0End += bot_dydx * lengthMinusOne; - } - fixed16_16 y1End = y1; - if (top_dydx != 0) - { - y1End += top_dydx * lengthMinusOne; - } -#else - fixed16_16 lengthFixed = intToFixed16(length - 1); - fixed16_16 y0End = y0; - if (bot_dydx != 0) - { - y0End += mul16(bot_dydx, lengthFixed); - } - fixed16_16 y1End = y1; - if (top_dydx != 0) - { - y1End += mul16(top_dydx, lengthFixed); - } -#endif - edgePair_setup(length, x0, top_dydx, y1End, y1, bot_dydx, y0, y0End, s_rcfState.adjoinEdge); - - s_rcfState.adjoinEdge++; - s_adjoinSegCount++; - - *s_rcfState.adjoinSegment = wallSegment; - s_rcfState.adjoinSegment++; - } - } - - // Refactor this into a sprite specific file. - void sprite_drawFrame(u8* basePtr, WaxFrame* frame, SecObject* obj) - { - if (!frame) { return; } - - const WaxCell* cell = WAX_CellPtr(basePtr, frame); - const fixed16_16 z = obj->posVS.z; - const s32 flip = frame->flip; - // Make sure the sprite isn't behind the near plane. - if (z < ONE_16) { return; } - JBool drawn = JFALSE; - - const fixed16_16 x0 = obj->posVS.x - frame->offsetX; - const fixed16_16 yOffset = frame->heightWS - frame->offsetY; - const fixed16_16 y0 = obj->posVS.y - yOffset; - - const fixed16_16 rcpZ = div16(ONE_16, z); -#ifdef TFE_ESPBOX - const fixed16_16 projX0 = mul16((x0 * s_rcfState.focalLength), rcpZ) + s_rcfState.projOffsetX; - const fixed16_16 projY0 = mul16((y0 * s_rcfState.focalLenAspect), rcpZ) + s_rcfState.projOffsetY; -#else - const fixed16_16 projX0 = mul16(mul16(x0, s_rcfState.focalLength), rcpZ) + s_rcfState.projOffsetX; - const fixed16_16 projY0 = mul16(mul16(y0, s_rcfState.focalLenAspect), rcpZ) + s_rcfState.projOffsetY; -#endif - - s32 x0_pixel = round16(projX0); - s32 y0_pixel = round16(projY0); - if (x0_pixel > s_windowMaxX_Pixels || y0_pixel > s_windowMaxY_Pixels) - { - return; - } - - const fixed16_16 x1 = x0 + frame->widthWS; - const fixed16_16 y1 = y0 + frame->heightWS; - -#ifdef TFE_ESPBOX - const fixed16_16 projX1 = mul16((x1 * s_rcfState.focalLength), rcpZ) + s_rcfState.projOffsetX; - const fixed16_16 projY1 = mul16((y1 * s_rcfState.focalLenAspect), rcpZ) + s_rcfState.projOffsetY; -#else - const fixed16_16 projX1 = mul16(mul16(x1, s_rcfState.focalLength), rcpZ) + s_rcfState.projOffsetX; - const fixed16_16 projY1 = mul16(mul16(y1, s_rcfState.focalLenAspect), rcpZ) + s_rcfState.projOffsetY; -#endif - - s32 x1_pixel = round16(projX1); - s32 y1_pixel = round16(projY1); - if (x1_pixel < s_windowMinX_Pixels || y1_pixel < s_windowMinY_Pixels) - { - return; - } - - const s32 length = x1_pixel - x0_pixel + 1; - if (length <= 0) - { - return; - } - - const fixed16_16 height = projY1 - projY0 + ONE_16; - const fixed16_16 width = projX1 - projX0 + ONE_16; - const fixed16_16 uCoordStep = div16(intToFixed16(cell->sizeX), width); - s_vCoordStep = div16(intToFixed16(cell->sizeY), height); - - fixed16_16 uCoord = 0; - if (x0_pixel < s_windowX0) - { - const s32 dx = s_windowX0 - x0_pixel; -#ifdef TFE_ESPBOX - uCoord = uCoordStep * dx; -#else - uCoord = mul16(uCoordStep, intToFixed16(dx)); -#endif - x0_pixel = s_windowX0; - } - if (x1_pixel > s_windowX1) - { - x1_pixel = s_windowX1; - } - - // Compute the lighting for the whole sprite. - s_columnLight = computeLighting(z, 0); - - // Figure out the correct column function. - ColumnFunction spriteColumnFunc; -#if 0 // TODO HACK - if (s_columnLight && !(obj->flags & OBJ_FLAG_FULLBRIGHT) && !s_flatLighting) - { - spriteColumnFunc = s_columnFunc[COLFUNC_LIT]; - } - else - { - spriteColumnFunc = s_columnFunc[COLFUNC_FULLBRIGHT]; - } -#else - //s_columnLight = NULL; // TODO HACK REMOVE - if (s_columnLight && !(obj->flags & OBJ_FLAG_FULLBRIGHT) && !s_flatLighting) - { - spriteColumnFunc = s_columnFunc[COLFUNC_LIT_TRANS]; - } - else - { - spriteColumnFunc = s_columnFunc[COLFUNC_FULLBRIGHT_TRANS]; - } -#endif - - // Draw - const s32 compressed = cell->compressed; - u8* imageData = (u8*)cell + sizeof(WaxCell); - - s32 n; - u8* image; -#ifdef TFE_ESPBOX - fixed16_16 yCoordStep = 0; -#endif - if (compressed == 1) - { - n = -1; - image = imageData + (cell->sizeX * sizeof(u32)); -#ifdef TFE_ESPBOX - yCoordStep = height / cell->sizeY; - //spriteColumnFunc -= 2; // non transparent variant -#endif - } - else - { - n = 0; - image = imageData; - } - - if (x0_pixel > x1_pixel) - { - return; - } - - // This should be set to handle all sizes, repeating is not required. - s_texHeightMask = 0xffff; - -#ifdef SPRTEST - s_xPixelCount = 0; -#endif - const u32* columnOffset = (u32*)(basePtr + cell->columnOffset); - for (s32 x = x0_pixel; x <= x1_pixel; x++, uCoord += uCoordStep) - { -#ifdef SPRTEST - // consume the extra pixels - if (s_xPixelCount > 0) - { - s_xPixelCount--; - continue; - } -#endif - if (z < s_rcfState.depth1d[x]) - { - s32 y0 = y0_pixel; - s32 y1 = y1_pixel; - - const s32 top = s_objWindowTop[x]; - if (y0 < top) - { - y0 = top; - } - const s32 bot = s_objWindowBot[x]; - if (y1 > bot) - { - y1 = bot; - } - - s_yPixelCount = y1 - y0 + 1; - if (s_yPixelCount > 0) - { -#ifdef TFE_ESPBOX -#ifdef SPRTEST - s_xPixelCount = 0; - if (uCoordStep < ONE_16) - { - //kprintf("uCoordStep %08lx\n", uCoordStep); - /* - fixed16_16 uCoordNew = uCoord; - kprintf("(%08lx + %08lx) = %08lx, uCoord %08lx\n", uCoordNew, uCoordStep, uCoordNew + uCoordStep, uCoord); - while ((uCoordNew += uCoordStep) == uCoord && (x + s_xPixelCount) <= x1_pixel) - */ - fixed16_16 uCoordNew = uCoord; - s32 texelU = floor16(uCoord); - while (floor16(uCoordNew += uCoordStep) == texelU && s_xPixelCount < 8-1 && (x + s_xPixelCount) < x1_pixel) - { - s_xPixelCount++; - } - } -#endif - - const s32 vOffset = y1_pixel - y1; - s_vCoordFixed = vOffset * s_vCoordStep; -#else - const fixed16_16 vOffset = intToFixed16(y1_pixel - y1); - s_vCoordFixed = mul16(vOffset, s_vCoordStep); -#endif - - s32 texelU = min(cell->sizeX-1, floor16(uCoord)); - if (flip) - { - texelU = cell->sizeX - texelU - 1; - } - - if (compressed) - { - const u8* colPtr = (u8*)cell + columnOffset[texelU]; -#ifdef TFE_ESPBOX - // find the first non-transparent texel... - u8 count = *colPtr; - if (count & 0x80) - { - count &= 0x7f; - // TODO sub-pixel precision - //fixed16_16 countFixed = intToFixed16(count) - ONE_16 + fract16(s_vCoordFixed); - //fixed16_16 countFixed = intToFixed16(count) - fract16(s_vCoordFixed); - fixed16_16 countFixed = intToFixed16(count) - HALF_16; - s_vCoordFixed = max(s_vCoordFixed, countFixed); - s32 skip = round16(count * yCoordStep) - vOffset; - if (skip > 0) - s_yPixelCount -= skip; - } -#endif - - // Decompress the column into "work buffer." - assert(cell->sizeY <= 1024 && texelU >= 0 && texelU < cell->sizeX); - sprite_decompressColumn(colPtr, s_workBuffer, cell->sizeY); - s_texImage = (u8*)s_workBuffer; -#ifdef TFE_ESPBOX - // ... and the last one - u8 height = s_workBuffer[cell->sizeY]; - s32 diff = cell->sizeY - height - 1; - if (diff > 0) - { - s32 diffScreen = round16(diff * yCoordStep); - //s32 diffScreen = floor16((diff - 1) * yCoordStep); - s32 skipScreen = y0 - y0_pixel; - s32 skip = diffScreen - skipScreen; - //kprintf("U %3ld sizeY %3ld height %3ld\n", texelU, cell->sizeY, height); - if (skip > 0) - { - y0 += skip; - s_yPixelCount -= skip; - } - } -#endif - } - else - { - s_texImage = (u8*)image + columnOffset[texelU]; - } - // Output. - s_columnOut = &s_display[y0 * s_width + x]; - // Draw the column. - spriteColumnFunc(); - if (s_yPixelCount > 1) { drawn = JTRUE; } - } - } - } -#ifdef SPRTEST - // reset for signs - s_xPixelCount = 0; -#endif - - if (drawn && s_drawnObjCount < MAX_DRAWN_OBJ_STORE) - { - s_drawnObj[s_drawnObjCount++] = obj; - } - } -} // RClassic_Fixed - -} // TFE_Jedi -#ifdef TFE_ESPBOX -void espbox_shared_rwallFixed(bool alloc) -{ - ESPBOX_SHARED_ALLOC(TFE_Jedi::RClassic_Fixed::s_workBuffer, WAX_DECOMPRESS_SIZE); -} -#endif diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rwallFixed.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rwallFixed.h deleted file mode 100644 index 9e4ffb26..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Fixed/rwallFixed.h +++ /dev/null @@ -1,44 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include -#include "../rlimits.h" -#include "../rwallRender.h" -#include "../rwallSegment.h" - -struct RSector; -struct EdgePairFixed; - -namespace TFE_Jedi -{ - namespace RClassic_Fixed - { - void wall_process(RWall* wall); - s32 wall_mergeSort(RWallSegmentFixed* segOutList, s32 availSpace, s32 start, s32 count); - - void wall_drawSolid(RWallSegmentFixed* wallSegment); - void wall_drawTransparent(RWallSegmentFixed* wallSegment, EdgePairFixed* edge); - void wall_drawMask(RWallSegmentFixed* wallSegment); - void wall_drawBottom(RWallSegmentFixed* wallSegment); - void wall_drawTop(RWallSegmentFixed* wallSegment); - void wall_drawTopAndBottom(RWallSegmentFixed* wallSegment); - - void wall_drawSkyTop(RSector* sector); - void wall_drawSkyTopNoWall(RSector* sector); - void wall_drawSkyBottom(RSector* sector); - void wall_drawSkyBottomNoWall(RSector* sector); - -#ifndef TFE_ESPBOX - void wall_addAdjoinSegment(s32 length, s32 x0, fixed16_16 top_dydx, fixed16_16 y1, fixed16_16 bot_dydx, fixed16_16 y0, RWallSegmentFixed* wallSegment); -#endif - - // Sprite code for now because so much is shared. - void sprite_drawFrame(u8* basePtr, WaxFrame* frame, SecObject* obj); - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/fixedPoint20.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/fixedPoint20.h deleted file mode 100644 index 8db8906f..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/fixedPoint20.h +++ /dev/null @@ -1,64 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////////////// -// 44.20 Fixed point (64 bit), designed for inner scanline/column loops only. -////////////////////////////////////////////////////////////////////////////// -#include -#include -#include - -namespace TFE_Jedi -{ - // Constants - #define HALF_20 0x80000 - #define ONE_20 0x100000 - - #define FRAC_BITS_20 20ll - #define FLOAT_SCALE_20 1048576.0 - - // Fixed point type - typedef s64 fixed44_20; - - // multiplies 2 fixed point numbers, the result is fixed point. - inline fixed44_20 mul20(fixed44_20 x, fixed44_20 y) - { - return (x * y) >> FRAC_BITS_20; - } - - // divides 2 fixed point numbers, the result is fixed point. - inline fixed44_20 div20(fixed44_20 num, fixed44_20 denom) - { - return (num << FRAC_BITS_20) / denom; - } - - // truncates a 44.20 fixed point number, returns an int: x >> 20 - inline s32 floor20(fixed44_20 x) - { - return s32(x >> FRAC_BITS_20); - } - - // computes a * b / c without intermediate operations. - inline fixed44_20 fusedMulDiv20(fixed44_20 a, fixed44_20 b, fixed44_20 c) - { - return (a * b) / c; - } - - // rounds a 44.20 fixed point number, returns an int: (x + HALF_20) >> 20 - inline s32 round20(fixed44_20 x) - { - return s32((x + HALF_20) >> FRAC_BITS_20); - } - - // converts an integer to a fixed point number: x << 20 - inline fixed44_20 intToFixed20(s32 x) - { - return fixed44_20(x) << FRAC_BITS_20; - } - - // converts a floating point value to 64-bit fixed point value. - // note the conversion to double before scaling to avoid overflow. - inline fixed44_20 floatToFixed20(f32 x) - { - const f64 x64 = f64(x) * FLOAT_SCALE_20; - return fixed44_20(x64); - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/rclassicFloat.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/rclassicFloat.h deleted file mode 100644 index 0207c787..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/rclassicFloat.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once -#include - -struct ColorMap; -struct RSector; -struct TextureData; - -namespace TFE_Jedi -{ - struct EdgePairFixed; - - namespace RClassic_Float - { - void resetState(); - void setupInitCameraAndLights(s32 width, s32 height); - void changeResolution(s32 width, s32 height); - - void computeCameraTransform(RSector* sector, f32 pitch, f32 yaw, f32 camX, f32 camY, f32 camZ); - void transformPointByCamera(vec3_float* worldPoint, vec3_float* viewPoint); - void blitTextureToScreen(TextureData* texture, s32 x0, s32 y0); - void clear3DView(u8* framebuffer); - void setVisionEffect(s32 effect); - void computeSkyOffsets(); - } // RClassic_Float -} // TFE_Jedi diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/rclassicFloatSharedState.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/rclassicFloatSharedState.h deleted file mode 100644 index a7511566..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/rclassicFloatSharedState.h +++ /dev/null @@ -1,66 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Fixed-point shared state used by the Jedi Renderer. -// The floating-point sub-renderer will have its own mirrored struct -// of shared state. -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include - -namespace TFE_Jedi -{ - struct RClassicFloatState - { - // Resolution - f32 halfWidth; - f32 halfHeight; - f32 projOffsetX; - f32 projOffsetY; - f32 projOffsetYBase; - f32 oneOverHalfWidth; - - // Projection - f32 focalLength; - f32 focalLenAspect; - f32 eyeHeight; - f32* depth1d_all; - f32* depth1d; - - // Camera - vec3_float cameraPos; - vec2_float cameraTrans; - f32 cosYaw; - f32 sinYaw; - f32 negSinYaw; - f32 cameraYaw; - f32 cameraPitch; - f32 yPlaneTop; - f32 yPlaneBot; - f32 skyYawOffset; - f32 skyPitchOffset; - f32* skyTable; - f32 cameraMtx[9]; - f32 aspectScaleX; - f32 aspectScaleY; - f32 nearPlaneHalfLen; - - // Window - f32 windowMinZ; - f32 windowMinY; - f32 windowMaxY; - - // Flats - EdgePairFloat* flatEdge; - EdgePairFloat flatEdgeList[MAX_SEG_EXT]; - EdgePairFloat* adjoinEdge; - EdgePairFloat* adjoinEdgeList; - - RWallSegmentFloat wallSegListDst[MAX_SEG_EXT]; - RWallSegmentFloat wallSegListSrc[MAX_SEG_EXT]; - RWallSegmentFloat** adjoinSegment; - }; - extern RClassicFloatState s_rcfltState; -} // TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/redgePairFloat.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/redgePairFloat.h deleted file mode 100644 index 15c8af3d..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/redgePairFloat.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include "../redgePair.h" - -namespace TFE_Jedi -{ - namespace RClassic_Float - { - void edgePair_setup(s32 length, s32 x0, f32 dyFloor_dx, f32 yFloor1, f32 yFloor, f32 dyCeil_dx, f32 yCeil, f32 yCeil1, EdgePairFloat* flat); - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/rflatFloat.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/rflatFloat.h deleted file mode 100644 index 14513444..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/rflatFloat.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include -#include - -struct RSector; - -namespace TFE_Jedi -{ - struct EdgePairFloat; - struct SectorCached; - - namespace RClassic_Float - { - void flat_addEdges(s32 length, s32 x0, f32 dyFloor_dx, f32 yFloor, f32 dyCeil_dx, f32 yCeil); - - void flat_drawCeiling(SectorCached* sectorCached, EdgePairFloat* edges, s32 count); - void flat_drawFloor(SectorCached* sectorCached, EdgePairFloat* edges, s32 count); - - // Set Parameters for 3D object rendering. - void flat_preparePolygon(f32 heightOffset, f32 offsetX, f32 offsetZ, TextureData* texture); - void flat_drawPolygonScanline(s32 x0, s32 x1, s32 y, bool trans); - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/rlightingFloat.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/rlightingFloat.h deleted file mode 100644 index 3e6412ef..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/rlightingFloat.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include -#include - -namespace TFE_Jedi -{ - namespace RClassic_Float - { - struct CameraLightFlt - { - vec3_float lightWS; - vec3_float lightVS; - f32 brightness; - }; - extern CameraLightFlt s_cameraLight[]; - - void light_transformDirLights(); - const u8* computeLighting(f32 depth, s32 lightOffset); - } -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/robj3d_float/robj3dFloat.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/robj3d_float/robj3dFloat.h deleted file mode 100644 index 7f373085..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/robj3d_float/robj3dFloat.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include - -struct JediModel; -struct SecObject; - -namespace TFE_Jedi -{ - namespace RClassic_Float - { - void robj3d_draw(SecObject* obj, JediModel* model); - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/robj3d_float/robj3dFloat_ClipFunc.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/robj3d_float/robj3dFloat_ClipFunc.h deleted file mode 100644 index c61c2028..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/robj3d_float/robj3dFloat_ClipFunc.h +++ /dev/null @@ -1,721 +0,0 @@ -////////////////////////////////////////////////////////////////////// -// Inline clip function to handle the various combinations. -////////////////////////////////////////////////////////////////////// -#include - -#if defined(CLIP_INTENSITY) && !defined(CLIP_UV) -s32 robj3d_swapClipBuffersI(s32 outVertexCount) -#elif !defined(CLIP_INTENSITY) && defined(CLIP_UV) -s32 robj3d_swapClipBuffersT(s32 outVertexCount) -#elif defined(CLIP_INTENSITY) && defined(CLIP_UV) -s32 robj3d_swapClipBuffersTI(s32 outVertexCount) -#else -s32 robj3d_swapClipBuffers(s32 outVertexCount) -#endif -{ - // Swap src position and output position. - s_clipTempPos = s_clipPosSrc; - s_clipPosSrc = s_clipPosOut; - s_clipPosOut = s_clipTempPos; - - // Swap src intensity and output intensity. - #if defined(CLIP_INTENSITY) - s_clipTempIntensity = s_clipIntensitySrc; - s_clipIntensitySrc = s_clipIntensityOut; - s_clipIntensityOut = s_clipTempIntensity; - #endif - - #if defined(CLIP_UV) - s_clipTempUv = s_clipUvSrc; - s_clipUvSrc = s_clipUvOut; - s_clipUvOut = s_clipTempUv; - #endif - - s32 srcVertexCount = outVertexCount; - s32 end = srcVertexCount - 1; - - // Left clip plane. - s_clipPos0 = &s_clipPosSrc[end]; - s_clipPos1 = s_clipPosSrc; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = &s_clipIntensitySrc[end]; - s_clipIntensity1 = s_clipIntensitySrc; - #endif - - #if defined(CLIP_UV) - s_clipUv0 = &s_clipUvSrc[end]; - s_clipUv1 = s_clipUvSrc; - #endif - - return srcVertexCount; -} - -#undef SWAP_CLIP_BUFFERS - -#if defined(CLIP_INTENSITY) && !defined(CLIP_UV) - #define SWAP_CLIP_BUFFERS robj3d_swapClipBuffersI -#elif !defined(CLIP_INTENSITY) && defined(CLIP_UV) - #define SWAP_CLIP_BUFFERS robj3d_swapClipBuffersT -#elif defined(CLIP_INTENSITY) && defined(CLIP_UV) - #define SWAP_CLIP_BUFFERS robj3d_swapClipBuffersTI -#else - #define SWAP_CLIP_BUFFERS robj3d_swapClipBuffers -#endif - -#if defined(CLIP_INTENSITY) && !defined(CLIP_UV) -void computeIntersectionI(s32 outVertexCount) -#elif !defined(CLIP_INTENSITY) && defined(CLIP_UV) -void computeIntersectionT(s32 outVertexCount) -#elif defined(CLIP_INTENSITY) && defined(CLIP_UV) -void computeIntersectionTI(s32 outVertexCount) -#else -void computeIntersection(s32 outVertexCount) -#endif -{ - #if defined(CLIP_INTENSITY) - const f32 i0 = *s_clipIntensity0; - const f32 i1 = *s_clipIntensity1; - s_clipIntensityOut[outVertexCount] = i0 + s_clipParam*(i1 - i0); - #endif - #if defined(CLIP_UV) - const vec2_float uv0 = *s_clipUv0; - const vec2_float uv1 = *s_clipUv1; - s_clipUvOut[outVertexCount].x = uv0.x + s_clipParam*(uv1.x - uv0.x); - s_clipUvOut[outVertexCount].z = uv0.z + s_clipParam*(uv1.z - uv0.z); - #endif -} - -#undef COMPUTE_CLIP_INTERSECTION -#if defined(CLIP_INTENSITY) && !defined(CLIP_UV) -#define COMPUTE_CLIP_INTERSECTION computeIntersectionI -#elif !defined(CLIP_INTENSITY) && defined(CLIP_UV) -#define COMPUTE_CLIP_INTERSECTION computeIntersectionT -#elif defined(CLIP_INTENSITY) && defined(CLIP_UV) -#define COMPUTE_CLIP_INTERSECTION computeIntersectionTI -#else -#define COMPUTE_CLIP_INTERSECTION computeIntersection -#endif - -#if defined(CLIP_INTENSITY) && !defined(CLIP_UV) -s32 robj3d_clipPolygonGouraud(vec3_float* pos, f32* intensity, s32 count) -#elif !defined(CLIP_INTENSITY) && defined(CLIP_UV) -s32 robj3d_clipPolygonUv(vec3_float* pos, vec2_float* uv, s32 count) -#elif defined(CLIP_INTENSITY) && defined(CLIP_UV) -s32 robj3d_clipPolygonUvGouraud(vec3_float* pos, vec2_float* uv, f32* intensity, s32 count) -#else -s32 robj3d_clipPolygon(vec3_float* pos, s32 count) -#endif -{ - s32 outVertexCount = 0; - s32 end = count - 1; - - #if defined(CLIP_INTENSITY) - s_clipIntensitySrc = intensity; - #endif - #if defined(CLIP_UV) - s_clipUvSrc = uv; - #endif - - s_clipPosSrc = pos; - - // Clip against the near plane. - s_clipPosOut = s_clipPosBuffer; - s_clipPos0 = &pos[count - 1]; - s_clipPos1 = pos; - - #if defined(CLIP_INTENSITY) - s_clipIntensityOut = s_clipIntensityBuffer; - s_clipIntensity0 = &intensity[count - 1]; - s_clipIntensity1 = intensity; - #endif - - #if defined(CLIP_UV) - s_clipUvOut = s_clipUvBuffer; - s_clipUv0 = &uv[count - 1]; - s_clipUv1 = uv; - #endif - - /////////////////////////////////////////////////// - // Near Clip Plane - /////////////////////////////////////////////////// - for (s32 i = 0; i < count; i++) - { - if (s_clipPos0->z < 1.0f && s_clipPos1->z < 1.0f) - { - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - - continue; - } - - // Add vertex 0 if it is on or in front of the near plane. - if (s_clipPos0->z >= 1.0f) - { - s_clipPosOut[outVertexCount] = *s_clipPos0; - - #if defined(CLIP_INTENSITY) - s_clipIntensityOut[outVertexCount] = *s_clipIntensity0; - #endif - #if defined(CLIP_UV) - s_clipUvOut[outVertexCount] = *s_clipUv0; - #endif - - outVertexCount++; - } - - // If either position is exactly on the near plane continue. - if (s_clipPos0->z == 1.0f || s_clipPos1->z == 1.0f) - { - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - - continue; - } - - // Finally clip the edge against the near plane, generating a new vertex. - if (s_clipPos0->z < 1.0f || s_clipPos1->z < 1.0f) - { - const f32 z0 = s_clipPos0->z; - const f32 z1 = s_clipPos1->z; - - // Parametric clip coordinate. - s_clipParam = (1.0f - z0) / (z1 - z0); - // new vertex Z coordinate should be exactly 1.0 - s_clipPosOut[outVertexCount].z = 1.0f; - s_clipPosOut[outVertexCount].y = s_clipPos0->y + s_clipParam*(s_clipPos1->y - s_clipPos0->y); - s_clipPosOut[outVertexCount].x = s_clipPos0->x + s_clipParam*(s_clipPos1->x - s_clipPos0->x); - - COMPUTE_CLIP_INTERSECTION(outVertexCount); - outVertexCount++; - } - - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - } - // Return if the polygon is clipping away. - if (outVertexCount < 3) - { - return 0; - } - s32 srcVertexCount = SWAP_CLIP_BUFFERS(outVertexCount); - outVertexCount = 0; - - /////////////////////////////////////////////////// - // Left Clip Plane - /////////////////////////////////////////////////// - for (s32 i = 0; i < srcVertexCount; i++) - { - s_clipPlanePos0 = -s_clipPos0->z * s_rcfltState.nearPlaneHalfLen; - s_clipPlanePos1 = -s_clipPos1->z * s_rcfltState.nearPlaneHalfLen; - if (s_clipPos0->x < s_clipPlanePos0 && s_clipPos1->x < s_clipPlanePos1) - { - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - - continue; - } - - // Add vertex 0 if it is inside the plane. - if (s_clipPos0->x >= s_clipPlanePos0) - { - s_clipPosOut[outVertexCount] = *s_clipPos0; - - #if defined(CLIP_INTENSITY) - s_clipIntensityOut[outVertexCount] = *s_clipIntensity0; - #endif - #if defined(CLIP_UV) - s_clipUvOut[outVertexCount] = *s_clipUv0; - #endif - - outVertexCount++; - } - - // Skip clipping if either vertex is touching the plane. - if (s_clipPos0->x == s_clipPlanePos0 || s_clipPos1->x == s_clipPlanePos1) - { - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - - continue; - } - - // Clip the edge. - if (s_clipPos0->x < s_clipPlanePos0 || s_clipPos1->x < s_clipPlanePos1) - { - const f32 x0 = s_clipPos0->x; - const f32 x1 = s_clipPos1->x; - const f32 z0 = s_clipPos0->z; - const f32 z1 = s_clipPos1->z; - - const f32 dx = s_clipPos1->x - s_clipPos0->x; - const f32 dz = s_clipPos1->z - s_clipPos0->z; - - s_clipParam0 = (x0*z1) - (x1*z0); - s_clipParam1 = -dz*s_rcfltState.nearPlaneHalfLen - dx; - - s_clipIntersectZ = s_clipParam0; - if (s_clipParam1 != 0) - { - s_clipIntersectZ = s_clipParam0 / s_clipParam1; - } - s_clipIntersectX = -s_clipIntersectZ * s_rcfltState.nearPlaneHalfLen; - - f32 p, p0, p1; - if (TFE_Jedi::abs(dz) > TFE_Jedi::abs(dx)) - { - p1 = s_clipPos1->z; - p0 = s_clipPos0->z; - p = s_clipIntersectZ; - } - else - { - p1 = s_clipPos1->x; - p0 = s_clipPos0->x; - p = s_clipIntersectX; - } - s_clipParam = (p - p0) / (p1 - p0); - - s_clipPosOut[outVertexCount].x = s_clipIntersectX; - s_clipPosOut[outVertexCount].y = s_clipPos0->y + s_clipParam*(s_clipPos1->y - s_clipPos0->y); - s_clipPosOut[outVertexCount].z = s_clipIntersectZ; - - COMPUTE_CLIP_INTERSECTION(outVertexCount); - outVertexCount++; - } - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - } - if (outVertexCount < 3) - { - return 0; - } - srcVertexCount = SWAP_CLIP_BUFFERS(outVertexCount); - outVertexCount = 0; - - /////////////////////////////////////////////////// - // Right Clip Plane - /////////////////////////////////////////////////// - for (s32 i = 0; i < srcVertexCount; i++) - { - s_clipPlanePos0 = s_clipPos0->z * s_rcfltState.nearPlaneHalfLen; - s_clipPlanePos1 = s_clipPos1->z * s_rcfltState.nearPlaneHalfLen; - if (s_clipPos0->x > s_clipPlanePos0 && s_clipPos1->x > s_clipPlanePos1) - { - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - - continue; - } - - // Add vertex 0 if it is inside the plane. - if (s_clipPos0->x <= s_clipPlanePos0) - { - s_clipPosOut[outVertexCount] = *s_clipPos0; - - #if defined(CLIP_INTENSITY) - s_clipIntensityOut[outVertexCount] = *s_clipIntensity0; - #endif - #if defined(CLIP_UV) - s_clipUvOut[outVertexCount] = *s_clipUv0; - #endif - - outVertexCount++; - } - - // Skip clipping if either vertex is touching the plane. - if (s_clipPos0->x == s_clipPlanePos0 || s_clipPos1->x == s_clipPlanePos1) - { - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - - continue; - } - - // Clip the edge. - if (s_clipPos0->x > s_clipPlanePos0 || s_clipPos1->x > s_clipPlanePos1) - { - const f32 x0 = s_clipPos0->x; - const f32 x1 = s_clipPos1->x; - const f32 z0 = s_clipPos0->z; - const f32 z1 = s_clipPos1->z; - - const f32 dx = s_clipPos1->x - s_clipPos0->x; - const f32 dz = s_clipPos1->z - s_clipPos0->z; - - s_clipParam0 = (x0*z1) - (x1*z0); - s_clipParam1 = s_rcfltState.nearPlaneHalfLen*dz - dx; - - s_clipIntersectZ = s_clipParam0; - if (s_clipParam1 != 0) - { - s_clipIntersectZ = s_clipParam0 / s_clipParam1; - } - s_clipIntersectX = s_rcfltState.nearPlaneHalfLen * s_clipIntersectZ; - - f32 p, p0, p1; - if (TFE_Jedi::abs(dz) > TFE_Jedi::abs(dx)) - { - p1 = s_clipPos1->z; - p0 = s_clipPos0->z; - p = s_clipIntersectZ; - } - else - { - p1 = s_clipPos1->x; - p0 = s_clipPos0->x; - p = s_clipIntersectX; - } - s_clipParam = (p - p0) / (p1 - p0); - - s_clipPosOut[outVertexCount].x = s_clipIntersectX; - s_clipPosOut[outVertexCount].y = s_clipPos0->y + s_clipParam*(s_clipPos1->y - s_clipPos0->y); - s_clipPosOut[outVertexCount].z = s_clipIntersectZ; - - COMPUTE_CLIP_INTERSECTION(outVertexCount); - outVertexCount++; - } - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - } - if (outVertexCount < 3) - { - return 0; - } - - srcVertexCount = SWAP_CLIP_BUFFERS(outVertexCount); - outVertexCount = 0; - - /////////////////////////////////////////////////// - // Top Clip Plane - /////////////////////////////////////////////////// - for (s32 i = 0; i < srcVertexCount; i++) - { - s_clipY0 = s_rcfltState.yPlaneTop * s_clipPos0->z; - s_clipY1 = s_rcfltState.yPlaneTop * s_clipPos1->z; - - // If the edge is completely behind the plane, then continue. - if (s_clipPos0->y < s_clipY0 && s_clipPos1->y < s_clipY1) - { - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - - continue; - } - // Add vertex 0 if it is inside the plane. - if (s_clipPos0->y > s_clipY0) - { - s_clipPosOut[outVertexCount] = *s_clipPos0; - - #if defined(CLIP_INTENSITY) - s_clipIntensityOut[outVertexCount] = *s_clipIntensity0; - #endif - #if defined(CLIP_UV) - s_clipUvOut[outVertexCount] = *s_clipUv0; - #endif - - outVertexCount++; - } - - // Skip clipping if either vertex is touching the plane. - if (s_clipPos0->y == s_clipY0 || s_clipPos1->y == s_clipY1) - { - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - - continue; - } - - // Clip the edge. - if (s_clipPos0->y < s_clipY0 || s_clipPos1->y < s_clipY1) - { - s_clipParam0 = (s_clipPos0->y*s_clipPos1->z) - (s_clipPos1->y*s_clipPos0->z); - - const f32 dy = s_clipPos1->y - s_clipPos0->y; - const f32 dz = s_clipPos1->z - s_clipPos0->z; - s_clipParam1 = s_rcfltState.yPlaneTop*dz - dy; - - s_clipIntersectZ = s_clipParam0; - if (s_clipParam1 != 0) - { - s_clipIntersectZ = s_clipParam0 / s_clipParam1; - } - s_clipIntersectY = s_rcfltState.yPlaneTop * s_clipIntersectZ; - const f32 aDz = TFE_Jedi::abs(s_clipPos1->z - s_clipPos0->z); - const f32 aDy = TFE_Jedi::abs(s_clipPos1->y - s_clipPos0->y); - - f32 p, p0, p1; - if (aDz > aDy) - { - p1 = s_clipPos1->z; - p0 = s_clipPos0->z; - p = s_clipIntersectZ; - } - else - { - p1 = s_clipPos1->y; - p0 = s_clipPos0->y; - p = s_clipIntersectY; - } - s_clipParam = (p - p0) / (p1 - p0); - - s_clipPosOut[outVertexCount].x = s_clipPos0->x + s_clipParam*(s_clipPos1->x - s_clipPos0->x); - s_clipPosOut[outVertexCount].y = s_clipIntersectY; - s_clipPosOut[outVertexCount].z = s_clipIntersectZ; - - COMPUTE_CLIP_INTERSECTION(outVertexCount); - outVertexCount++; - } - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - } - - if (outVertexCount < 3) - { - return 0; - } - srcVertexCount = SWAP_CLIP_BUFFERS(outVertexCount); - outVertexCount = 0; - - /////////////////////////////////////////////////// - // Bottom Clip Plane - /////////////////////////////////////////////////// - for (s32 i = 0; i < srcVertexCount; i++) - { - s_clipY0 = s_rcfltState.yPlaneBot * s_clipPos0->z; - s_clipY1 = s_rcfltState.yPlaneBot * s_clipPos1->z; - - // If the edge is completely behind the plane, then continue. - if (s_clipPos0->y > s_clipY0 && s_clipPos1->y > s_clipY1) - { - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - - continue; - } - - // Add vertex 0 if it is inside the plane. - if (s_clipPos0->y < s_clipY0) - { - s_clipPosOut[outVertexCount] = *s_clipPos0; - - #if defined(CLIP_INTENSITY) - s_clipIntensityOut[outVertexCount] = *s_clipIntensity0; - #endif - #if defined(CLIP_UV) - s_clipUvOut[outVertexCount] = *s_clipUv0; - #endif - - outVertexCount++; - } - - // Skip clipping if either vertex is touching the plane. - if (s_clipPos0->y == s_clipY0 || s_clipPos1->y == s_clipY1) - { - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - - continue; - } - - // Clip the edge. - if (s_clipPos0->y > s_clipY0 || s_clipPos1->y > s_clipY1) - { - s_clipParam0 = (s_clipPos0->y*s_clipPos1->z) - (s_clipPos1->y*s_clipPos0->z); - - const f32 dy = s_clipPos1->y - s_clipPos0->y; - const f32 dz = s_clipPos1->z - s_clipPos0->z; - s_clipParam1 = s_rcfltState.yPlaneBot*dz - dy; - - s_clipIntersectZ = s_clipParam0; - if (s_clipParam1 != 0) - { - s_clipIntersectZ = s_clipParam0 / s_clipParam1; - } - s_clipIntersectY = s_rcfltState.yPlaneBot * s_clipIntersectZ; - const f32 aDz = TFE_Jedi::abs(s_clipPos1->z - s_clipPos0->z); - const f32 aDy = TFE_Jedi::abs(s_clipPos1->y - s_clipPos0->y); - - f32 p, p0, p1; - if (aDz > aDy) - { - p1 = s_clipPos1->z; - p0 = s_clipPos0->z; - p = s_clipIntersectZ; - } - else - { - p1 = s_clipPos1->y; - p0 = s_clipPos0->y; - p = s_clipIntersectY; - } - s_clipParam = (p - p0) / (p1 - p0); - - s_clipPosOut[outVertexCount].x = s_clipPos0->x + s_clipParam*(s_clipPos1->x - s_clipPos0->x); - s_clipPosOut[outVertexCount].y = s_clipIntersectY; - s_clipPosOut[outVertexCount].z = s_clipIntersectZ; - - COMPUTE_CLIP_INTERSECTION(outVertexCount); - outVertexCount++; - } - s_clipPos0 = s_clipPos1; - s_clipPos1++; - - #if defined(CLIP_INTENSITY) - s_clipIntensity0 = s_clipIntensity1; - s_clipIntensity1++; - #endif - #if defined(CLIP_UV) - s_clipUv0 = s_clipUv1; - s_clipUv1++; - #endif - } - if (outVertexCount < 3) - { - return 0; - } - - if (pos != s_clipPosOut) - { - memcpy(pos, s_clipPosOut, outVertexCount * sizeof(vec3_float)); - #if defined(CLIP_INTENSITY) - memcpy(intensity, s_clipIntensityOut, outVertexCount * sizeof(f32)); - #endif - #if defined(CLIP_UV) - memcpy(uv, s_clipUvOut, outVertexCount * sizeof(vec2_float)); - #endif - } - // There is a corner case where 0 z is produced which causes crashes on Windows. - // (It is kind of weird that it doesn't affect DOS...) - for (s32 i = 0; i < outVertexCount; i++) - { - pos[i].z = max(pos[i].z, 1.0f); - } - return outVertexCount; -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/robj3d_float/robj3dFloat_Clipping.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/robj3d_float/robj3dFloat_Clipping.h deleted file mode 100644 index c24efb7f..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/robj3d_float/robj3dFloat_Clipping.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include "../../rlimits.h" - -namespace TFE_Jedi -{ - namespace RClassic_Float - { - s32 clipPolygon(JmPolygon* polygon); - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/robj3d_float/robj3dFloat_Culling.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/robj3d_float/robj3dFloat_Culling.h deleted file mode 100644 index 1629f991..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/robj3d_float/robj3dFloat_Culling.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include - -namespace TFE_Jedi -{ - namespace RClassic_Float - { - extern std::vector s_visPolygons; - s32 robj3d_backfaceCull(JediModel* model); - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/robj3d_float/robj3dFloat_PolyRenderFunc.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/robj3d_float/robj3dFloat_PolyRenderFunc.h deleted file mode 100644 index 3c55cdaf..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/robj3d_float/robj3dFloat_PolyRenderFunc.h +++ /dev/null @@ -1,458 +0,0 @@ -////////////////////////////////////////////////////////////////////// -// Inline polygon render functions -////////////////////////////////////////////////////////////////////// - -#if defined(POLY_INTENSITY) && !defined(POLY_UV) -s32 robj3d_findNextEdgeI(s32 xMinIndex, s32 xMin) -#elif !defined(POLY_INTENSITY) && defined(POLY_UV) -s32 robj3d_findNextEdgeT(s32 xMinIndex, s32 xMin) -#elif defined(POLY_INTENSITY) && defined(POLY_UV) -s32 robj3d_findNextEdgeTI(s32 xMinIndex, s32 xMin) -#else -s32 robj3d_findNextEdge(s32 xMinIndex, s32 xMin) -#endif -{ - s32 prevScanlineLen = s_edgeTopLength; - s32 curIndex = xMinIndex; - - // The min and max indices should not match, otherwise it is an error. - if (xMinIndex == s_polyMaxIndex) - { - s_edgeTopLength = prevScanlineLen; - return -1; - } - - while (1) - { - s32 nextIndex = curIndex + 1; - if (nextIndex >= s_polyVertexCount) { nextIndex = 0; } - else if (nextIndex < 0) { nextIndex = s_polyVertexCount - 1; } - - vec3_float* cur = &s_polyProjVtx[curIndex]; - vec3_float* next = &s_polyProjVtx[nextIndex]; - const s32 x0 = s32(cur->x + 0.5f); - const s32 x1 = s32(next->x + 0.5f); - const s32 y0 = s32(cur->y + 0.5f); - const s32 y1 = s32(next->y + 0.5f); - s32 dx = x1 - x0; - if (x1 == s_maxScreenX_Pixels) - { - dx++; - } - - if (dx > 0) - { - s_edgeTopLength = dx; - - const f32 step = 1.0f / f32(dx); - s_edgeTopY0_Pixel = y0; - s_edgeTop_Y0 = f32(y0); - - const f32 dy = f32(y1 - y0); - s_edgeTop_dYdX = dy * step; - - const f32 dz = next->z - cur->z; - s_edgeTop_dZdX = dz * step; - s_edgeTop_Z0 = cur->z; - - #if defined(POLY_INTENSITY) - s_edgeTop_I0 = clamp(s_polyIntensity[curIndex], 0.0f, VSHADE_MAX_INTENSITY_FLT); - const f32 dI = s_polyIntensity[nextIndex] - s_edgeTop_I0; - s_edgeTop_dIdX = dI * step; - #endif - #if defined(POLY_UV) - s_edgeTop_Uv0 = s_polyUv[curIndex]; - const f32 dU = s_polyUv[nextIndex].x - s_edgeTop_Uv0.x; - const f32 dV = s_polyUv[nextIndex].z - s_edgeTop_Uv0.z; - s_edgeTop_dUVdX.x = dU * step; - s_edgeTop_dUVdX.z = dV * step; - #endif - - s_edgeTopIndex = nextIndex; - return 0; - } - else if (nextIndex == s_polyMaxIndex) - { - s_edgeTopLength = prevScanlineLen; - return -1; - } - curIndex = nextIndex; - } - - // This shouldn't be reached, but just in case. - s_edgeTopLength = prevScanlineLen; - return -1; -} - -#if defined(POLY_INTENSITY) && !defined(POLY_UV) -s32 robj3d_findPrevEdgeI(s32 minXIndex) -#elif !defined(POLY_INTENSITY) && defined(POLY_UV) -s32 robj3d_findPrevEdgeT(s32 minXIndex) -#elif defined(POLY_INTENSITY) && defined(POLY_UV) -s32 robj3d_findPrevEdgeTI(s32 minXIndex) -#else -s32 robj3d_findPrevEdge(s32 minXIndex) -#endif -{ - const s32 len = s_edgeBotLength; - s32 curIndex = minXIndex; - if (minXIndex == s_polyMaxIndex) - { - s_edgeBotLength = len; - return -1; - } - - while (1) - { - s32 prevIndex = curIndex - 1; - if (prevIndex >= s_polyVertexCount) { prevIndex = 0; } - else if (prevIndex < 0) { prevIndex = s_polyVertexCount - 1; } - - vec3_float* cur = &s_polyProjVtx[curIndex]; - vec3_float* prev = &s_polyProjVtx[prevIndex]; - const s32 x0 = s32(cur->x + 0.5f); - const s32 x1 = s32(prev->x + 0.5f); - const s32 y0 = s32(cur->y + 0.5f); - const s32 y1 = s32(prev->y + 0.5f); - s32 dx = x1 - x0; - if (s_maxScreenX_Pixels == x1) - { - dx++; - } - - if (dx > 0) - { - s_edgeBotLength = dx; - - const f32 step = 1.0f / f32(dx); - s_edgeBotY0_Pixel = y0; - s_edgeBot_Y0 = f32(y0); - - const s32 dy = y1 - y0; - s_edgeBot_dYdX = f32(dy) * step; - - const f32 dz = prev->z - cur->z; - s_edgeBot_dZdX = dz / f32(dx); - s_edgeBot_Z0 = cur->z; - - #if defined(POLY_INTENSITY) - s_edgeBot_I0 = clamp(s_polyIntensity[curIndex], 0.0f, VSHADE_MAX_INTENSITY_FLT); - const f32 dI = s_polyIntensity[prevIndex] - s_edgeBot_I0; - s_edgeBot_dIdX = dI * step; - #endif - #if defined(POLY_UV) - s_edgeBot_Uv0 = s_polyUv[curIndex]; - const f32 dU = s_polyUv[prevIndex].x - s_edgeBot_Uv0.x; - const f32 dV = s_polyUv[prevIndex].z - s_edgeBot_Uv0.z; - s_edgeBot_dUVdX.x = dU * step; - s_edgeBot_dUVdX.z = dV * step; - #endif - - s_edgeBotIndex = prevIndex; - - return 0; - } - else - { - curIndex = prevIndex; - if (prevIndex == s_polyMaxIndex) - { - s_edgeBotLength = len; - return -1; - } - } - } - s_edgeBotLength = len; - return -1; -} - -#if !defined(POLY_INTENSITY) && !defined(POLY_UV) -void robj3d_drawColumnFlatColor() -{ - s32 end = s_columnHeight - 1; - s32 offset = end * s_width; - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - s_pcolumnOut[offset] = s_polyColorIndex; - } -} -#endif - -#if defined(POLY_INTENSITY) && !defined(POLY_UV) -void robj3d_drawColumnShadedColor() -{ - const u8* colorMap = s_polyColorMap; - - fixed44_20 intensity = s_col_I0; - u8 colorIndex = s_polyColorIndex; - s32 dither = s_dither; - - s32 end = s_columnHeight - 1; - s32 offset = end * s_width; - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - s32 pixelIntensity = floor20(intensity); - if (dither) - { - const fixed44_20 iOffset = intensity - s_ditherOffset; - if (iOffset >= 0) - { - pixelIntensity = floor20(iOffset); - } - } - s_pcolumnOut[offset] = colorMap[(pixelIntensity&31)*256 + colorIndex]; - - intensity += s_col_dIdY; - dither = !dither; - } -} -#endif - -#if !defined(POLY_INTENSITY) && defined(POLY_UV) -void robj3d_drawColumnFlatTexture() -{ - const u8* colorMap = &s_polyColorMap[s_polyColorIndex * 256]; - const u8* textureData = s_polyTexture->image; - const s32 texHeight = s_polyTexture->height; - const s32 texWidthMask = s_polyTexture->width - 1; - const s32 texHeightMask = texHeight - 1; - - fixed44_20 U = s_col_Uv0.x; - fixed44_20 V = s_col_Uv0.z; - - s32 end = s_columnHeight - 1; - s32 offset = end * s_width; - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - const u8 colorIndex = textureData[(floor20(U)&texWidthMask)*texHeight + (floor20(V)&texHeightMask)]; - s_pcolumnOut[offset] = colorMap[colorIndex]; - - U += s_col_dUVdY.x; - V += s_col_dUVdY.z; - } -} -#endif - -#if defined(POLY_INTENSITY) && defined(POLY_UV) -void robj3d_drawColumnShadedTexture() -{ - const u8* colorMap = s_polyColorMap; - const u8* textureData = s_polyTexture->image; - const s32 texHeight = s_polyTexture->height; - const s32 texWidthMask = s_polyTexture->width - 1; - const s32 texHeightMask = texHeight - 1; - - fixed44_20 U = s_col_Uv0.x; - fixed44_20 V = s_col_Uv0.z; - fixed44_20 I = s_col_I0; - - s32 end = s_columnHeight - 1; - s32 offset = end * s_width; - for (s32 i = end; i >= 0; i--, offset -= s_width) - { - const u8 colorIndex = textureData[(floor20(U)&texWidthMask)*texHeight + (floor20(V)&texHeightMask)]; - const s32 pixelIntensity = floor20(I)&31; - s_pcolumnOut[offset] = colorMap[pixelIntensity*256 + colorIndex]; - - I += s_col_dIdY; - U += s_col_dUVdY.x; - V += s_col_dUVdY.z; - } -} -#endif - -#undef FIND_NEXT_EDGE -#undef FIND_PREV_EDGE -#undef DRAW_COLUMN -#if defined(POLY_INTENSITY) && !defined(POLY_UV) -#define FIND_NEXT_EDGE robj3d_findNextEdgeI -#define FIND_PREV_EDGE robj3d_findPrevEdgeI -#define DRAW_COLUMN robj3d_drawColumnShadedColor -#elif !defined(POLY_INTENSITY) && defined(POLY_UV) -#define FIND_NEXT_EDGE robj3d_findNextEdgeT -#define FIND_PREV_EDGE robj3d_findPrevEdgeT -#define DRAW_COLUMN robj3d_drawColumnFlatTexture -#elif defined(POLY_INTENSITY) && defined(POLY_UV) -#define FIND_NEXT_EDGE robj3d_findNextEdgeTI -#define FIND_PREV_EDGE robj3d_findPrevEdgeTI -#define DRAW_COLUMN robj3d_drawColumnShadedTexture -#else -#define FIND_NEXT_EDGE robj3d_findNextEdge -#define FIND_PREV_EDGE robj3d_findPrevEdge -#define DRAW_COLUMN robj3d_drawColumnFlatColor -#endif - -#if defined(POLY_INTENSITY) && !defined(POLY_UV) -void robj3d_drawShadedColorPolygon(vec3_float* projVertices, f32* intensity, s32 vertexCount, u8 color) -#elif !defined(POLY_INTENSITY) && defined(POLY_UV) -void robj3d_drawFlatTexturePolygon(vec3_float* projVertices, vec2_float* uv, s32 vertexCount, TextureData* texture, u8 color) -#elif defined(POLY_INTENSITY) && defined(POLY_UV) -void robj3d_drawShadedTexturePolygon(vec3_float* projVertices, vec2_float* uv, f32* intensity, s32 vertexCount, TextureData* texture) -#else -void robj3d_drawFlatColorPolygon(vec3_float* projVertices, s32 vertexCount, u8 color) -#endif -{ - s32 xMax = INT_MIN; - s32 xMin = INT_MAX; - s_polyProjVtx = projVertices; - s_polyVertexCount = vertexCount; - - #if defined(POLY_INTENSITY) - s_polyIntensity = intensity; - #endif - #if defined(POLY_UV) - s_polyUv = uv; - s_polyTexture = texture; - #endif - - s32 yMax = xMax; - s32 yMin = xMin; - if (vertexCount <= 0) { return; } - - // Compute the 2D bounding box of the polygon. - // Track the extreme vertex indices in X. - s32 minXIndex; - vec3_float* projVertex = projVertices; - for (s32 i = 0; i < s_polyVertexCount; i++, projVertex++) - { - const s32 x = s32(projVertex->x + 0.5f); - if (x < xMin) - { - xMin = x; - minXIndex = i; - } - if (x > xMax) - { - xMax = x; - s_polyMaxIndex = i; - } - - const s32 y = s32(projVertex->y + 0.5f); - if (y < yMin) { yMin = y; } - if (y > yMax) { yMax = y; } - } - - // If the polygon is too small or off screen, skip it. - if (xMin >= xMax || yMin > s_windowMaxY_Pixels || yMax < s_windowMinY_Pixels) { return; } - - assert(s_colorMap); - s_polyColorMap = s_colorMap; - #if !(defined(POLY_INTENSITY) && defined(POLY_UV)) - s_polyColorIndex = color; - #endif - #if defined(POLY_INTENSITY) && !defined(POLY_UV) - s_ditherOffset = HALF_20; - #endif - s_columnX = xMin; - - if (FIND_NEXT_EDGE(minXIndex, xMin) != 0 || FIND_PREV_EDGE(minXIndex) != 0) { return; } - - for (s32 foundEdge = 0; !foundEdge && s_columnX >= s_minScreenX_Pixels && s_columnX <= s_maxScreenX_Pixels; s_columnX++) - { - const f32 edgeMinZ = min(s_edgeBot_Z0, s_edgeTop_Z0); - const f32 z = s_rcfltState.depth1d[s_columnX]; - - // Is ave edge Z occluded by walls? Is column outside of the vertical area? - if (edgeMinZ < z && s_edgeTopY0_Pixel <= s_windowMaxY_Pixels && s_edgeBotY0_Pixel >= s_windowMinY_Pixels) - { - const s32 winTop = s_objWindowTop[s_columnX]; - const s32 winBot = s_objWindowBot[s_columnX]; - s32 y0_Top = s_edgeTopY0_Pixel; - s32 y0_Bot = s_edgeBotY0_Pixel; - #if defined(POLY_INTENSITY) || defined(POLY_UV) - f32 yOffset = 0.0f; - #endif - - if (y0_Top < winTop) - { - y0_Top = winTop; - } - if (y0_Bot > winBot) - { - #if defined(POLY_INTENSITY) || defined(POLY_UV) - yOffset = f32(y0_Bot - winBot); - #endif - y0_Bot = winBot; - } - - s_columnHeight = y0_Bot - y0_Top + 1; - if (s_columnHeight > 0) - { - const f32 height = f32(s_edgeBotY0_Pixel - s_edgeTopY0_Pixel + 1); - s_pcolumnOut = &s_display[y0_Top*s_width + s_columnX]; - - #if defined(POLY_INTENSITY) - f32 col_dIdY = (s_edgeTop_I0 - s_edgeBot_I0) / height; - f32 col_I0 = s_edgeBot_I0; - if (yOffset) - { - col_I0 += (yOffset * col_dIdY); - } - s_col_dIdY = floatToFixed20(col_dIdY); - s_col_I0 = floatToFixed20(col_I0); - s_dither = ((s_columnX & 1) ^ (y0_Bot & 1)) - 1; - #endif - - #if defined(POLY_UV) - vec2_float dUVdY; - dUVdY.x = (s_edgeTop_Uv0.x - s_edgeBot_Uv0.x) / height; - dUVdY.z = (s_edgeTop_Uv0.z - s_edgeBot_Uv0.z) / height; - vec2_float col_Uv0 = s_edgeBot_Uv0; - if (yOffset != 0.0f) - { - col_Uv0.x += (yOffset * dUVdY.x); - col_Uv0.z += (yOffset * dUVdY.z); - } - s_col_Uv0.x = floatToFixed20(col_Uv0.x); - s_col_Uv0.z = floatToFixed20(col_Uv0.z); - s_col_dUVdY.x = floatToFixed20(dUVdY.x); - s_col_dUVdY.z = floatToFixed20(dUVdY.z); - #endif - - DRAW_COLUMN(); - } - } - - s_edgeTopLength--; - if (s_edgeTopLength <= 0) - { - foundEdge = FIND_NEXT_EDGE(s_edgeTopIndex, s_columnX); - } - else - { - #if defined(POLY_INTENSITY) - s_edgeTop_I0 = clamp(s_edgeTop_I0 + s_edgeTop_dIdX, 0.0f, VSHADE_MAX_INTENSITY_FLT); - #endif - #if defined(POLY_UV) - s_edgeTop_Uv0.x += s_edgeTop_dUVdX.x; - s_edgeTop_Uv0.z += s_edgeTop_dUVdX.z; - #endif - - s_edgeTop_Y0 += s_edgeTop_dYdX; - s_edgeTop_Z0 += s_edgeTop_dZdX; - s_edgeTopY0_Pixel = roundFloat(s_edgeTop_Y0); - } - if (foundEdge == 0) - { - s_edgeBotLength--; - if (s_edgeBotLength <= 0) - { - foundEdge = FIND_PREV_EDGE(s_edgeBotIndex); - } - else - { - #if defined(POLY_INTENSITY) - s_edgeBot_I0 = clamp(s_edgeBot_I0 + s_edgeBot_dIdX, 0.0f, VSHADE_MAX_INTENSITY_FLT); - #endif - #if defined(POLY_UV) - s_edgeBot_Uv0.x += s_edgeBot_dUVdX.x; - s_edgeBot_Uv0.z += s_edgeBot_dUVdX.z; - #endif - - s_edgeBot_Y0 += s_edgeBot_dYdX; - s_edgeBot_Z0 += s_edgeBot_dZdX; - s_edgeBotY0_Pixel = roundFloat(s_edgeBot_Y0); - } - } - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/robj3d_float/robj3dFloat_PolygonDraw.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/robj3d_float/robj3dFloat_PolygonDraw.h deleted file mode 100644 index 6904d823..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/robj3d_float/robj3dFloat_PolygonDraw.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include -#include "../../rlimits.h" - -namespace TFE_Jedi -{ - namespace RClassic_Float - { - void robj3d_drawPolygon(JmPolygon* polygon, s32 polyVertexCount, SecObject* obj, JediModel* model); - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/robj3d_float/robj3dFloat_PolygonSetup.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/robj3d_float/robj3dFloat_PolygonSetup.h deleted file mode 100644 index 5dacb5b0..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/robj3d_float/robj3dFloat_PolygonSetup.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include - -#define POLY_MAX_VTX_COUNT 32 - -namespace TFE_Jedi -{ - namespace RClassic_Float - { - extern vec3_float s_polygonVerticesVS[POLY_MAX_VTX_COUNT]; - extern vec3_float s_polygonVerticesProj[POLY_MAX_VTX_COUNT]; - extern vec2_float s_polygonUv[POLY_MAX_VTX_COUNT]; - extern f32 s_polygonIntensity[POLY_MAX_VTX_COUNT]; - - void robj3d_setupPolygon(JmPolygon* polygon); - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/robj3d_float/robj3dFloat_TransformAndLighting.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/robj3d_float/robj3dFloat_TransformAndLighting.h deleted file mode 100644 index fb1678d2..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/robj3d_float/robj3dFloat_TransformAndLighting.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -struct SecObject; - -#define VSHADE_MAX_INTENSITY_FLT 31.0f - -namespace TFE_Jedi -{ - namespace RClassic_Float - { - extern s32 s_enableFlatShading; - // Vertex attributes transformed to viewspace. - extern std::vector s_verticesVS; - extern std::vector s_vertexNormalsVS; - // Vertex Lighting. - extern std::vector s_vertexIntensity; - // Polygon normals in viewspace (used for culling). - extern std::vector s_polygonNormalsVS; - - void robj3d_transformAndLight(SecObject* obj, JediModel* model); - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/rsectorFloat.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/rsectorFloat.h deleted file mode 100644 index e3660625..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/rsectorFloat.h +++ /dev/null @@ -1,62 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Sector -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include "rwallFloat.h" -#include "rflatFloat.h" -#include "../rsectorRender.h" - -struct RWall; -struct SecObject; - -namespace TFE_Jedi -{ - struct SectorCached - { - RSector* sector; // base sector. - WallCached* cachedWalls; - s32 objectCapacity; - // Floating point version of view space vertices. - vec2_float* verticesVS; - // Space for floating point positions. - vec3_float* objPosVS; - // Cached floor and ceiling heights (second height not required for rendering). - f32 floorHeight; - f32 ceilingHeight; - // Cached Texture offsets - vec2_float floorOffset; - vec2_float ceilOffset; - }; - - class TFE_Sectors_Float : public TFE_Sectors - { - public: - TFE_Sectors_Float() : m_cachedSectors(nullptr), m_cachedSectorCount(0) {} - - // Sub-Renderer specific - void destroy() override; - void reset() override; - void prepare() override; - void draw(RSector* sector) override; - void subrendererChanged() override; - - private: - void saveValues(s32 index); - void restoreValues(s32 index); - void adjoin_computeWindowBounds(EdgePairFloat* adjoinEdges); - void adjoin_setupAdjoinWindow(s32* winBot, s32* winBotNext, s32* winTop, s32* winTopNext, EdgePairFloat* adjoinEdges, s32 adjoinCount); - - void freeCachedData(); - void allocateCachedData(); - void updateCachedSector(SectorCached* cached, u32 flags); - void updateCachedWalls(SectorCached* cached, u32 flags); - - public: - SectorCached* m_cachedSectors = nullptr; - u32 m_cachedSectorCount = 0; - }; -} // TFE_Jedi diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/rwallFloat.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/rwallFloat.h deleted file mode 100644 index 046bfc81..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/rwallFloat.h +++ /dev/null @@ -1,70 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include -#include "../rlimits.h" -#include "../rwallRender.h" -#include "../rwallSegment.h" - -struct RSector; - -namespace TFE_Jedi -{ - struct EdgePairFloat; - struct SectorCached; - - struct WallCached - { - RWall* wall; // base wall. - SectorCached* sector; - // Vertices (viewspace) - points to cached vertices. - vec2_float* v0; - vec2_float* v1; - // Wall length in texels. - f32 texelLength; - - // Wall heights in texels. - f32 topTexelHeight; - f32 midTexelHeight; - f32 botTexelHeight; - - // Texture Offsets - vec2_float topOffset; - vec2_float midOffset; - vec2_float botOffset; - vec2_float signOffset; - - // Direction and length. - vec2_float wallDir; - f32 length; - }; - - namespace RClassic_Float - { - void wall_process(WallCached* wallCached); - s32 wall_mergeSort(RWallSegmentFloat* segOutList, s32 availSpace, s32 start, s32 count); - - void wall_drawSolid(RWallSegmentFloat* wallSegment); - void wall_drawTransparent(RWallSegmentFloat* wallSegment, EdgePairFloat* edge); - void wall_drawMask(RWallSegmentFloat* wallSegment); - void wall_drawBottom(RWallSegmentFloat* wallSegment); - void wall_drawTop(RWallSegmentFloat* wallSegment); - void wall_drawTopAndBottom(RWallSegmentFloat* wallSegment); - - void wall_drawSkyTop(RSector* sector); - void wall_drawSkyTopNoWall(RSector* sector); - void wall_drawSkyBottom(RSector* sector); - void wall_drawSkyBottomNoWall(RSector* sector); - - void wall_addAdjoinSegment(s32 length, s32 x0, f32 top_dydx, f32 y1, f32 bot_dydx, f32 y0, RWallSegmentFloat* wallSegment); - - // Sprite code for now because so much is shared. - void sprite_drawFrame(u8* basePtr, WaxFrame* frame, SecObject* obj, vec3_float* cachedPosVS); - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/screenDraw.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/screenDraw.h deleted file mode 100644 index ad835077..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_Float/screenDraw.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Screen Line Drawing -////////////////////////////////////////////////////////////////////// -#include -#include -#include - -struct ScreenRect; - -namespace TFE_Jedi -{ - struct DrawRect - { - s32 x0; - s32 y0; - s32 x1; - s32 y1; - }; - - void screen_drawPoint(ScreenRect* rect, s32 x, s32 z, u8 color, u8* framebuffer); - void screen_drawLine(ScreenRect* rect, s32 x0, s32 z0, s32 x1, s32 z1, u8 color, u8* framebuffer); - void screen_drawCircle(ScreenRect* rect, s32 x, s32 z, s32 r, s32 stepAngle, u8 color, u8* framebuffer); - - JBool screen_clipLineToRect(ScreenRect* rect, s32* x0, s32* z0, s32* x1, s32* z1); - - void blitTextureToScreen(TextureData* texture, DrawRect* rect, s32 x0, s32 y0, u8* output, JBool forceTransparency=JFALSE); - void blitTextureToScreenLit(TextureData* texture, DrawRect* rect, s32 x0, s32 y0, const u8* atten, u8* output, JBool forceTransparency=JFALSE); -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/debug.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/debug.h deleted file mode 100644 index 0097c990..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/debug.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Renderer Debug -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include - -namespace TFE_Jedi -{ - extern s32 s_maxPortals; - extern s32 s_maxWallSeg; - extern s32 s_portalsTraversed; - extern s32 s_wallSegGenerated; - - void debug_update(); - void debug_addQuad(Vec2f v0, Vec2f v1, f32 y0, f32 y1, f32 portalY0, f32 portalY1, bool isPortal); -} // TFE_Jedi diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/frustum.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/frustum.h deleted file mode 100644 index fe8fe4b4..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/frustum.h +++ /dev/null @@ -1,62 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Frustum management -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include - -namespace TFE_Jedi -{ - enum FrustumConstants - { - FRUSTUM_STACK_SIZE = 256, - FRUSTUM_PLANE_MAX = 256, - }; - - struct Frustum - { - u32 planeCount; - Vec4f planes[FRUSTUM_PLANE_MAX]; - }; - - struct Polygon - { - s32 vertexCount; - Vec3f vtx[FRUSTUM_PLANE_MAX]; - }; - - void frustum_copy(const Frustum* src, Frustum* dst); - void frustum_clearStack(); - void frustum_push(Frustum& frustum); - - Frustum* frustum_pop(); - Frustum* frustum_getBack(); - Frustum* frustum_getFront(); - - // Returns true if the sphere defined by {pos, radius} is fully or partially inside of the current frustum on the stack. - bool frustum_sphereInside(Vec3f pos, f32 radius); - - // Returns true if the quad is in front of the near plane. - bool frustum_quadInside(const Vec3f v0, const Vec3f v1); - - // This clips the quad formed from {corner0, corner1} against the current frustum on the stack. - // Returns false if the quad is outside of the frustum, else true. - bool frustum_clipQuadToFrustum(Vec3f corner0, Vec3f corner1, Polygon* output, bool ignoreNearPlane = false); - // Clip quad to list of planes. - bool frustum_clipQuadToPlanes(s32 count, const Vec4f* plane, Vec3f corner0, Vec3f corner1, Polygon* output); - - // Builds a new frustum such that each polygon edge becomes a plane that passes through the camera and - // the polygon plane defines the near plane. - void frustum_buildFromPolygon(const Polygon* polygon, Frustum* newFrustum); - - // Builds a world-space frustum from the camera. - void frustum_buildFromCamera(); - - // Build a single plane from an edge and the camera position. - Vec4f frustum_calculatePlaneFromEdge(const Vec3f* edge); - - // Distance of pos from plane. - f32 frustum_planeDist(const Vec4f* plane, const Vec3f* pos); -} // TFE_Jedi diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/modelGPU.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/modelGPU.h deleted file mode 100644 index a30da07a..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/modelGPU.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Manage and render 3DO models. -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include -#include "sbuffer.h" - -namespace TFE_Jedi -{ - bool model_init(); - void model_destroy(); - // This needs to be called *after* texture packing is complete so that textureIds are already set. - void model_loadGpuModels(); - - void model_drawListClear(); - void model_drawListFinish(); - - void model_add(void* obj, JediModel* model, Vec3f posWS, fixed16_16* transform, f32 ambient, Vec2f floorOffset, Vec2f ceilOffset, u32 portalInfo); - void model_drawList(); -} // TFE_Jedi diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/objectPortalPlanes.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/objectPortalPlanes.h deleted file mode 100644 index ab21f3bd..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/objectPortalPlanes.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Display list for rendering sector geometry -////////////////////////////////////////////////////////////////////// -#include -#include -#include "sectorDisplayList.h" - -namespace TFE_Jedi -{ - void objectPortalPlanes_init(); - void objectPortalPlanes_destroy(); - - void objectPortalPlanes_clear(); - void objectPortalPlanes_finish(); - - void objectPortalPlanes_bind(s32 index); - void objectPortalPlanes_unbind(s32 index); - - u32 objectPortalPlanes_add(u32 count, const Vec4f* planes); -} // TFE_Jedi diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/rclassicGPU.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/rclassicGPU.h deleted file mode 100644 index 1c9b6937..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/rclassicGPU.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once -#include - -struct ColorMap; -struct RSector; -struct TextureData; - -namespace TFE_Jedi -{ - namespace RClassic_GPU - { - void resetState(); - void setupInitCameraAndLights(s32 width, s32 height); - void changeResolution(s32 width, s32 height); - - void computeCameraTransform(RSector* sector, f32 pitch, f32 yaw, f32 camX, f32 camY, f32 camZ); - void transformPointByCamera(vec3_float* worldPoint, vec3_float* viewPoint); - void computeSkyOffsets(); - } // RClassic_GPU -} // TFE_Jedi diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/renderDebug.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/renderDebug.h deleted file mode 100644 index 1ec10d86..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/renderDebug.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Renderer Debugging -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include "../rsectorRender.h" - -namespace TFE_Jedi -{ - void renderDebug_enable(bool enable); - void renderDebug_addLine(Vec3f v0, Vec3f v1, const u8* color); - void renderDebug_addPolygon(s32 count, Vec3f* vtx, Vec4f color); - void renderDebug_draw(); -} // TFE_Jedi diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/rsectorGPU.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/rsectorGPU.h deleted file mode 100644 index 927568d9..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/rsectorGPU.h +++ /dev/null @@ -1,45 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Sector -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include "../rsectorRender.h" -#include "../textureInfo.h" - -class TextureGpu; - -namespace TFE_Jedi -{ - class TFE_Sectors_GPU : public TFE_Sectors - { - public: - TFE_Sectors_GPU() : m_gpuInit(false), m_levelInit(false), m_gpuBuffersAllocated(false), m_prevSectorCount(0), m_prevWallCount(0) {} - - // Sub-Renderer specific - void destroy() override; - void reset() override; - void prepare() override; - void draw(RSector* sector) override; - void subrendererChanged() override; - - void flushCache(); - - static TextureGpu* getColormap(); - - private: - static bool updateShaderSettings(bool initialize = false); - static bool updateShaders(); - static void updateColorMap(); - private: - bool m_gpuInit; - bool m_levelInit; - bool m_gpuBuffersAllocated; - s32 m_prevSectorCount; - s32 m_prevWallCount; - - public: - }; -} // TFE_Jedi diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/sbuffer.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/sbuffer.h deleted file mode 100644 index 785a5c4a..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/sbuffer.h +++ /dev/null @@ -1,56 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// S-Buffer (S = span or segment) used to sort and clip walls in -// world space based on the camera position. -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include - -namespace TFE_Jedi -{ - struct Segment - { - Vec3f normal; - Vec2f v0, v1; - f32 y0, y1; - f32 portalY0, portalY1; - bool portal; - s32 id; - // positions projected onto the camera plane, used for sorting and overlap tests. - f32 x0, x1; - }; - - struct SegmentClipped - { - SegmentClipped* prev; - SegmentClipped* next; - Segment* seg; - - // Adjusted values when segments need to be split. - f32 x0, x1; - Vec2f v0, v1; - }; - - // Clip rule called on portal segments. - // Return true if the segment should clip the incoming segment. - typedef bool(*SBufferClipRule)(s32 id); - - f32 sbuffer_projectToUnitSquare(Vec2f coord); - void sbuffer_handleEdgeWrapping(f32& x0, f32& x1); - bool sbuffer_splitByRange(Segment* seg, Vec2f* range, Vec2f* points, s32 rangeCount); - Vec2f sbuffer_clip(Vec2f v0, Vec2f v1, Vec2f pointOnPlane); - - void sbuffer_clear(); - void sbuffer_mergeSegments(); - void sbuffer_insertSegment(Segment* seg); - SegmentClipped* sbuffer_get(); - - // Clips a segment to the buffer but does *not* update the s-buffer itself. - // The result will be zero or more output segments. - // If no clip rule is passed in, assume all current segments clip the source segment. - s32 sbuffer_clipSegmentToBuffer(Vec2f v0, Vec2f v1, s32 rangeCount, Vec2f* range, Vec2f* rangeSrc, s32 maxOutputSegs, SegmentClipped* dstSegs, SBufferClipRule clipRule = nullptr); - - void sbuffer_debugDisplay(); -} // TFE_Jedi diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/screenDrawGPU.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/screenDrawGPU.h deleted file mode 100644 index 1bb56f08..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/screenDrawGPU.h +++ /dev/null @@ -1,45 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Screen Drawing functions using GPU rendering. -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include "../screenDraw.h" -#include "../textureInfo.h" - -namespace TFE_Jedi -{ - void screenGPU_init(); - void screenGPU_destroy(); - - void screenGPU_beginLines(u32 width, u32 height); - void screenGPU_endLines(); - - void screenGPU_beginImageQuads(u32 width, u32 height); - void screenGPU_endImageQuads(); - void screenGPU_addImageQuad(s32 x0, s32 z0, s32 x1, s32 z1, TextureGpu* texture); - void screenGPU_addImageQuad(s32 x0, s32 z0, s32 x1, s32 z1, f32 u0, f32 u1, TextureGpu* texture); - - void screenGPU_beginQuads(u32 width, u32 height); - void screenGPU_endQuads(); - - void screenGPU_setHudTextureCallbacks(s32 count, TextureListCallback* callbacks); - - void screenGPU_drawPoint(ScreenRect* rect, s32 x, s32 z, u8 color); - void screenGPU_drawLine(ScreenRect* rect, s32 x0, s32 z0, s32 x1, s32 z1, u8 color); - - void screenGPU_blitTexture(TextureData* texture, DrawRect* rect, s32 x0, s32 y0, JBool forceTransparency=JFALSE, JBool forceOpaque=JFALSE); - void screenGPU_blitTextureLit(TextureData* texture, DrawRect* rect, s32 x0, s32 y0, u8 lightLevel, JBool forceTransparency=JFALSE); - - // Scaled versions. - void screenGPU_blitTextureScaled(TextureData* texture, DrawRect* rect, fixed16_16 x0, fixed16_16 y0, fixed16_16 xScale, fixed16_16 yScale, u8 lightLevel, JBool forceTransparency = JFALSE); - void screenGPU_drawColoredQuad(fixed16_16 x0, fixed16_16 y0, fixed16_16 x1, fixed16_16 y1, u8 color); - - void screenGPU_blitTexture(ScreenImage* texture, DrawRect* rect, s32 x0, s32 y0); - void screenGPU_blitTextureScaled(ScreenImage* texture, DrawRect* rect, s32 x0, s32 y0, fixed16_16 xScale, fixed16_16 yScale); - void screenGPU_blitTextureLitScaled(ScreenImage* texture, DrawRect* rect, s32 x0, s32 y0, fixed16_16 xScale, fixed16_16 yScale, u8 lightLevel); - - void screenGPU_blitTextureIScale(TextureData* texture, DrawRect* rect, s32 x0, s32 y0, s32 scale); -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/sectorDisplayList.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/sectorDisplayList.h deleted file mode 100644 index 1177e71b..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/sectorDisplayList.h +++ /dev/null @@ -1,62 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Display list for rendering sector geometry -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include "sbuffer.h" - -namespace TFE_Jedi -{ - // Pack portal info into a 16-bit value. - #define PACK_PORTAL_INFO(offset, count) (u32(offset) | (u32(count) << 16u)) - #define UNPACK_PORTAL_INFO_COUNT(info) (info >> 16u) - #define UNPACK_PORTAL_INFO_OFFSET(info) (info & ((1u << 16u) - 1u)) - - enum SectorPass - { - SECTOR_PASS_OPAQUE = 0, - SECTOR_PASS_TRANS, - SECTOR_PASS_COUNT - }; - - enum PlaneType - { - PLANE_TYPE_TOP = FLAG_BIT(0), - PLANE_TYPE_BOT = FLAG_BIT(1), - PLANE_TYPE_BOTH = PLANE_TYPE_TOP | PLANE_TYPE_BOT, - }; - - enum Contants - { - MAX_PORTAL_PLANES = 8, // Minimum custom clipping plane limit for OpenGL 3.3 - MAX_DISP_ITEMS = 65536, - MAX_BUFFER_SIZE = 65536, - }; - - struct GPUCachedSector - { - f32 floorHeight; - f32 ceilingHeight; - u64 builtFrame; - - s32 wallStart; - }; - - void sdisplayList_init(s32* posIndex, s32* dataIndex, s32 planesIndex); - void sdisplayList_destroy(); - - void sdisplayList_clear(); - void sdisplayList_finish(); - - void sdisplayList_addSegment(RSector* curSector, GPUCachedSector* cached, SegmentClipped* wallSeg, bool forceTreatAsSolid=false); - bool sdisplayList_addPortal(Vec3f p0, Vec3f p1, s32 parentPortalId); - void sdisplayList_draw(SectorPass passId); - - s32 sdisplayList_getSize(SectorPass passId = SECTOR_PASS_OPAQUE); - - u32 sdisplayList_getPackedPortalInfo(s32 portalId); - u32 sdisplayList_getPlanesFromPortal(u32 portalId, u32 planeType, Vec4f* outPlanes); -} // TFE_Jedi diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/spriteDisplayList.h b/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/spriteDisplayList.h deleted file mode 100644 index 29cecb56..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/RClassic_GPU/spriteDisplayList.h +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Display list for rendering sprites (WAX & FME). -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include -#include "sbuffer.h" - -namespace TFE_Jedi -{ - struct SpriteDrawFrame - { - // Frame Data. - void* basePtr; - WaxFrame* frame; - void* objPtr; - // Position Data. - Vec2f v0, v1; // base vertex positions - Vec2f c0, c1; // clipped vertex positions. - f32 posY; - // Sector. - RSector* curSector; - // Flags - bool fullbright; - // Portal data. - u32 portalInfo; - }; - - void sprdisplayList_init(s32 startIndex); - void sprdisplayList_destroy(); - - void sprdisplayList_clear(); - void sprdisplayList_finish(); - - void sprdisplayList_addFrame(const SpriteDrawFrame* const drawFrame); - void sprdisplayList_draw(); - - s32 sprdisplayList_getSize(); -} // TFE_Jedi diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/jediRenderer.cpp b/components/darkforces/tfe/TFE_Jedi/Renderer/jediRenderer.cpp deleted file mode 100644 index ad985cdb..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/jediRenderer.cpp +++ /dev/null @@ -1,520 +0,0 @@ -#include "jediRenderer.h" -#include -#include -#include -#include "rcommon.h" -#include "rsectorRender.h" -#include "screenDraw.h" -#include "RClassic_Fixed/rclassicFixedSharedState.h" -#include "RClassic_Fixed/rclassicFixed.h" -#include "RClassic_Fixed/rsectorFixed.h" - -#include "RClassic_Float/rclassicFloat.h" -#include "RClassic_Float/rsectorFloat.h" -#include "RClassic_Float/rclassicFloatSharedState.h" - -#include "RClassic_GPU/rclassicGPU.h" -#include "RClassic_GPU/rsectorGPU.h" -#include "RClassic_GPU/screenDrawGPU.h" - -#include -#include -#include -#include -#include -#include - -namespace TFE_Jedi -{ - static bool s_init = false; - static TFE_SubRenderer s_subRenderer = TSR_CLASSIC_FIXED; - static std::vector s_hudTextureCallbacks; - static TFE_Sectors* s_sectorRendererCache[TSR_COUNT] = { nullptr }; - bool s_showWireframe = false; - TFE_Sectors* s_sectorRenderer = nullptr; - RendererType s_rendererType = RENDERER_SOFTWARE; - - ///////////////////////////////////////////// - // Forward Declarations - ///////////////////////////////////////////// - void clear1dDepth(); - void console_setSubRenderer(const std::vector& args); - void console_getSubRenderer(const std::vector& args); - - ///////////////////////////////////////////// - // Implementation - ///////////////////////////////////////////// - void renderer_resetState() - { - RClassic_Fixed::resetState(); - RClassic_Float::resetState(); - RClassic_GPU::resetState(); - s_hudTextureCallbacks.clear(); - screen_clear(); - - for (s32 i = 0; i < TSR_COUNT; i++) - { - if (s_sectorRendererCache[i]) - { - s_sectorRendererCache[i]->destroy(); - delete s_sectorRendererCache[i]; - } - s_sectorRendererCache[i] = nullptr; - } - - s_sectorRenderer = nullptr; - s_subRenderer = TSR_INVALID; - s_init = false; - vfb_setMode(); - } - - TFE_Sectors* renderer_getSectorRenderer(TFE_SubRenderer renderer) - { - switch (renderer) - { - case TSR_CLASSIC_FIXED: - if (!s_sectorRendererCache[renderer]) - { - s_sectorRendererCache[renderer] = new TFE_Sectors_Fixed(); - } - return s_sectorRendererCache[renderer]; - break; - case TSR_CLASSIC_FLOAT: - if (!s_sectorRendererCache[renderer]) - { - s_sectorRendererCache[renderer] = new TFE_Sectors_Float(); - } - return s_sectorRendererCache[renderer]; - break; - case TSR_CLASSIC_GPU: - if (!s_sectorRendererCache[renderer]) - { - s_sectorRendererCache[renderer] = new TFE_Sectors_GPU(); - } - return s_sectorRendererCache[renderer]; - break; - } - TFE_System::logWrite(LOG_ERROR, "Jedi Renderer", "Invalid Sector Renderer."); - return nullptr; - } - - void renderer_init() - { - if (s_init) { return; } - s_init = true; - // Setup Debug CVars. - s_maxWallCount = 0xffff; - s_maxDepthCount = 0xffff; - CVAR_INT(s_maxWallCount, "d_maxWallCount", CVFLAG_DO_NOT_SERIALIZE, "Maximum wall count for a given sector."); - CVAR_INT(s_maxDepthCount, "d_maxDepthCount", CVFLAG_DO_NOT_SERIALIZE, "Maximum adjoin depth count."); - CVAR_INT(s_sectorAmbient, "d_sectorAmbient", CVFLAG_DO_NOT_SERIALIZE, "Current Sector Ambient."); - CVAR_BOOL(s_showWireframe, "d_enableWireframe", CVFLAG_DO_NOT_SERIALIZE, "Enable wireframe rendering."); - - // Remove temporarily until they do something useful again. - CCMD("rsetSubRenderer", console_setSubRenderer, 1, "Set the sub-renderer - valid values are: Classic_Fixed, Classic_Float, Classic_GPU."); - CCMD("rgetSubRenderer", console_getSubRenderer, 0, "Get the current sub-renderer."); - - // Setup performance counters. - TFE_COUNTER(s_maxAdjoinDepth, "Maximum Adjoin Depth"); - TFE_COUNTER(s_maxAdjoinIndex, "Maximum Adjoin Count"); - TFE_COUNTER(s_sectorIndex, "Sector Count"); - TFE_COUNTER(s_flatCount, "Flat Count"); - TFE_COUNTER(s_curWallSeg, "Wall Segment Count"); - TFE_COUNTER(s_adjoinSegCount, "Adjoin Segment Count"); - - s_sectorRenderer = renderer_getSectorRenderer(TSR_CLASSIC_FIXED); - renderer_setLimits(); - } - - void renderer_destroy() - { - renderer_resetState(); - } - - void renderer_reset() - { - // Reset all allocated renderers. - for (s32 i = 0; i < TSR_COUNT; i++) - { - if (s_sectorRendererCache[i]) - { - s_sectorRendererCache[i]->reset(); - } - } - } - - void renderer_setLimits() - { - if (TFE_Settings::getGraphicsSettings()->extendAjoinLimits) - { - s_maxSegCount = MAX_SEG_EXT; - s_maxAdjoinSegCount = MAX_ADJOIN_SEG_EXT; - s_maxAdjoinDepthRecursion = MAX_ADJOIN_DEPTH_EXT; - } - else - { - s_maxSegCount = MAX_SEG; - s_maxAdjoinSegCount = MAX_ADJOIN_SEG; - s_maxAdjoinDepthRecursion = MAX_ADJOIN_DEPTH; - } - } - - void renderer_setType(RendererType type) - { - s_rendererType = type; - render_setResolution(); - } - - RendererType renderer_getType() - { - return s_rendererType; - } - - void setupInitCameraAndLights() - { - u32 dispWidth, dispHeight; - vfb_getResolution(&dispWidth, &dispHeight); - dispWidth = max((s32)dispWidth, 320); - dispHeight = max((s32)dispHeight, 200); - - RClassic_Fixed::setupInitCameraAndLights(); - RClassic_Float::setupInitCameraAndLights(dispWidth, dispHeight); - RClassic_GPU::setupInitCameraAndLights(dispWidth, dispHeight); - } - - void blitTextureToScreen(TextureData* texture, s32 x0, s32 y0) - { - RClassic_Fixed::blitTextureToScreen(texture, x0, y0); - } - - void clear3DView(u8* framebuffer) - { - RClassic_Fixed::clear3DView(framebuffer); - } - - void renderer_addHudTextureCallback(TextureListCallback hudTextureCallback) - { - s_hudTextureCallbacks.push_back(hudTextureCallback); - } - - void console_setSubRenderer(const std::vector& args) - { - if (args.size() < 2) { return; } - const char* value = args[1].c_str(); - - if (strcasecmp(value, "Classic_Fixed") == 0) - { - setSubRenderer(TSR_CLASSIC_FIXED); - } - else if (strcasecmp(value, "Classic_Float") == 0) - { - setSubRenderer(TSR_CLASSIC_FLOAT); - } - else if (strcasecmp(value, "Classic_GPU") == 0) - { - setSubRenderer(TSR_CLASSIC_GPU); - } - } - - void console_getSubRenderer(const std::vector& args) - { - const char* c_subRenderers[] = - { - "Classic_Fixed", // TSR_CLASSIC_FIXED - "Classic_Float", // TSR_CLASSIC_FLOAT - "Classic_GPU", // TSR_CLASSIC_GPU - }; - TFE_Console::addToHistory(c_subRenderers[s_subRenderer]); - } - - JBool render_setResolution() - { - TFE_Settings_Graphics* graphics = TFE_Settings::getGraphicsSettings(); - DisplayInfo info; - TFE_RenderBackend::getDisplayInfo(&info); - - s32 width = graphics->gameResolution.x; - s32 height = graphics->gameResolution.z; - if (graphics->widescreen && (height == 200 || height == 400)) - { - width = (height * info.width / info.height) * 12 / 10; - } - else if (graphics->widescreen) - { - width = height * info.width / info.height; - } - // Make sure the adjustedWidth is divisible by 4. - width = 4 * ((width + 3) >> 2); - - TFE_SubRenderer subRenderer = s_rendererType == RENDERER_HARDWARE ? TSR_CLASSIC_GPU : (width == 320 && height == 200) ? TSR_CLASSIC_FIXED : TSR_CLASSIC_FLOAT; - vfb_setMode(subRenderer == TSR_CLASSIC_GPU ? VFB_RENDER_TRAGET : VFB_TEXTURE); - if (!vfb_setResolution(width, height)) - { - return JFALSE; - } - - if (s_subRenderer != subRenderer) - { - s_subRenderer = subRenderer; - if (s_sectorRenderer) - { - s_sectorRenderer->subrendererChanged(); - } - s_sectorRenderer = nullptr; - } - - if (width == 320 && height == 200 && subRenderer == TSR_CLASSIC_FIXED) - { - if (!s_sectorRenderer) - { - s_sectorRenderer = renderer_getSectorRenderer(TSR_CLASSIC_FIXED); - } - screen_enableGPU(false); - RClassic_Fixed::changeResolution(width, height); - } - else if (s_rendererType == RENDERER_SOFTWARE) - { - if (!s_sectorRenderer) - { - s_sectorRenderer = renderer_getSectorRenderer(TSR_CLASSIC_FLOAT); - } - screen_enableGPU(false); - RClassic_Float::changeResolution(width, height); - } - else - { - if (!s_sectorRenderer) - { - TFE_Sectors_GPU* sectorRendererGpu = (TFE_Sectors_GPU*)renderer_getSectorRenderer(TSR_CLASSIC_GPU); - screenGPU_setHudTextureCallbacks((s32)s_hudTextureCallbacks.size(), s_hudTextureCallbacks.data()); - s_sectorRenderer = sectorRendererGpu; - sectorRendererGpu->flushCache(); - screenGPU_init(); - } - screen_enableGPU(true); - RClassic_GPU::changeResolution(width, height); - } - return JTRUE; - } - - void renderer_setVisionEffect(s32 effect) - { - if (s_subRenderer == TSR_CLASSIC_FIXED) { RClassic_Fixed::setVisionEffect(effect); } - } - - TFE_SubRenderer getSubRenderer() - { - return s_subRenderer; - } - - JBool setSubRenderer(TFE_SubRenderer subRenderer/* = TSR_CLASSIC_FIXED*/) - { - if (subRenderer == TSR_HIGH_RESOLUTION) - { - subRenderer = s_rendererType == RENDERER_HARDWARE ? TSR_CLASSIC_GPU : TSR_CLASSIC_FLOAT; - } - - if (subRenderer == s_subRenderer) - { - return JFALSE; - } - - s_subRenderer = subRenderer; - if (s_sectorRenderer) - { - s_sectorRenderer->subrendererChanged(); - } - s_sectorRenderer = nullptr; - - vfb_setMode(subRenderer == TSR_CLASSIC_GPU ? VFB_RENDER_TRAGET : VFB_TEXTURE); - switch (subRenderer) - { - case TSR_CLASSIC_FIXED: - { - vfb_setResolution(320, 200); - s_sectorRenderer = renderer_getSectorRenderer(TSR_CLASSIC_FIXED); - screen_enableGPU(false); - RClassic_Fixed::setupInitCameraAndLights(); - } break; - case TSR_CLASSIC_FLOAT: - { - s_sectorRenderer = renderer_getSectorRenderer(TSR_CLASSIC_FLOAT); - - u32 width, height; - vfb_getResolution(&width, &height); - screen_enableGPU(false); - RClassic_Float::setupInitCameraAndLights(width, height); - } break; - case TSR_CLASSIC_GPU: - { - TFE_Sectors_GPU* sectorRendererGpu = (TFE_Sectors_GPU*)renderer_getSectorRenderer(TSR_CLASSIC_GPU); - screenGPU_setHudTextureCallbacks((s32)s_hudTextureCallbacks.size(), s_hudTextureCallbacks.data()); - s_sectorRenderer = sectorRendererGpu; - - u32 width, height; - vfb_getResolution(&width, &height); - screen_enableGPU(true); - screenGPU_init(); - RClassic_GPU::setupInitCameraAndLights(width, height); - } break; - } - return JTRUE; - } - - void renderer_setWorldAmbient(s32 value) - { - s_worldAmbient = MAX_LIGHT_LEVEL - value; - } - - void renderer_setupCameraLight(JBool flatShading, JBool headlamp) - { - s_enableFlatShading = flatShading; - s_cameraLightSource = headlamp; - } - - void renderer_computeCameraTransform(RSector* sector, angle14_32 pitch, angle14_32 yaw, fixed16_16 camX, fixed16_16 camY, fixed16_16 camZ) - { - #if 0 - if (s_subRenderer == TSR_CLASSIC_FIXED) - { - RClassic_Fixed::computeCameraTransform(sector, pitch, yaw, camX, camY, camZ); - } - else if (s_subRenderer == TSR_CLASSIC_FLOAT) - { - RClassic_Float::computeCameraTransform(sector, f32(pitch), f32(yaw), fixed16ToFloat(camX), fixed16ToFloat(camY), fixed16ToFloat(camZ)); - } - #endif - - // For now compute both fixed-point and floating-point camera transforms so that it is easier to swap between sub-renderers. - // TODO: Find a cleaner alternative. - RClassic_Fixed::computeCameraTransform(sector, pitch, yaw, camX, camY, camZ); - RClassic_Float::computeCameraTransform(sector, f32(pitch), f32(yaw), fixed16ToFloat(camX), fixed16ToFloat(camY), fixed16ToFloat(camZ)); - RClassic_GPU::computeCameraTransform(sector, f32(pitch), f32(yaw), fixed16ToFloat(camX), fixed16ToFloat(camY), fixed16ToFloat(camZ)); - } - - void beginRender() - { - if (!s_sectorRenderer) - { - TFE_SubRenderer subRenderer = s_subRenderer; - s_subRenderer = TSR_INVALID; - setSubRenderer(subRenderer); - } - if (s_subRenderer == TSR_CLASSIC_GPU) - { - vfb_bindRenderTarget(/*clearColor*/s_showWireframe); - - u32 width, height; - vfb_getResolution(&width, &height); - screenDraw_beginQuads(width, height); - } - } - - void endRender() - { - if (s_subRenderer == TSR_CLASSIC_GPU) - { - screenDraw_endQuads(); - screenDraw_endLines(); - vfb_unbindRenderTarget(); - } - } - - void drawWorld(u8* display, RSector* sector, const u8* colormap, const u8* lightSourceRamp) - { - // Clear the top pixel row. - if (s_subRenderer != TSR_CLASSIC_GPU) - { - memset(display, 0, s_width); - memset(display + (s_height - 1) * s_width, 0, s_width); - } - - s_drawFrame++; - if (s_subRenderer == TSR_CLASSIC_FIXED) - { - RClassic_Fixed::computeSkyOffsets(); - } - else if (s_subRenderer == TSR_CLASSIC_FLOAT) - { - RClassic_Float::computeSkyOffsets(); - } - else if (s_subRenderer == TSR_CLASSIC_GPU) - { - RClassic_GPU::computeSkyOffsets(); - } - - s_display = display; - s_colorMap = colormap; - s_lightSourceRamp = lightSourceRamp; - if (s_subRenderer != TSR_CLASSIC_GPU) - { - clear1dDepth(); - } - - s_windowMinX_Pixels = s_minScreenX_Pixels; - s_windowMaxX_Pixels = s_maxScreenX_Pixels; - s_windowMinY_Pixels = 1; - s_windowMaxY_Pixels = s_height - 1; - s_windowMaxCeil = s_minScreenY; - s_windowMinFloor = s_maxScreenY; - s_flatCount = 0; - s_nextWall = 0; - s_curWallSeg = 0; - s_drawnObjCount = 0; - - s_prevSector = nullptr; - s_sectorIndex = 0; - s_maxAdjoinIndex = 0; - s_adjoinSegCount = 1; - s_adjoinIndex = 0; - - s_adjoinDepth = 1; - s_maxAdjoinDepth = 1; - - if (s_subRenderer != TSR_CLASSIC_GPU) - { - for (s32 i = 0; i < s_width; i++) - { - s_columnTop[i] = s_minScreenY; - s_columnBot[i] = s_maxScreenY; - s_windowTop_all[i] = s_minScreenY; - s_windowBot_all[i] = s_maxScreenY; - } - } - - // Recursively draws sectors and their contents (sprites, 3D objects). - { - TFE_ZONE("Sector Draw"); - s_sectorRenderer->prepare(); - s_sectorRenderer->draw(sector); - } - } - - ///////////////////////////////////////////// - // Internal - ///////////////////////////////////////////// - void clear1dDepth() - { - if (s_subRenderer == TSR_CLASSIC_FIXED) - { - memset(s_rcfState.depth1d_all, 0, s_width * sizeof(s32)); - s_rcfState.windowMinZ = 0; - } -#ifndef TFE_ESPBOX - else if (s_subRenderer == TSR_CLASSIC_FLOAT) - { - memset(s_rcfltState.depth1d_all, 0, s_width * sizeof(f32)); - s_rcfltState.windowMinZ = 0.0f; - } -#endif - } -} - -#ifdef TFE_ESPBOX -// Shutdown only: release this file's cached container storage so nothing is -// left in the 4MB ROM block when the session ends (see esp_alloc.cpp). -void espbox_release_renderer_caches() -{ - std::vector().swap(TFE_Jedi::s_hudTextureCallbacks); -} -#endif diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/jediRenderer.h b/components/darkforces/tfe/TFE_Jedi/Renderer/jediRenderer.h deleted file mode 100644 index 005b364e..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/jediRenderer.h +++ /dev/null @@ -1,91 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Jedi Renderer -// Classic Dark Forces (DOS) Jedi derived renderer. -// -// Copyright note: -// While the project as a whole is licensed under GPL-2.0, some of the -// code under TFE_JediRenderer/ was derived from reverse-engineered -// code from "Dark Forces" (DOS) which is copyrighted by LucasArts. -// The original renderer is contained in RClassic_Fixed/ and the -// RClassic_Float/ and RClassic_GPU/ sub-renderers are derived from -// that code. -// -// I consider the reverse-engineering to be "Fair Use" - a means of -// supporting the games on other platforms and to improve support on -// existing platforms without claiming ownership of the games -// themselves or their IPs. -// -// That said using this code in a commercial project is risky without -// permission of the original copyright holders (LucasArts). -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include - -enum TFE_SubRenderer -{ - TSR_CLASSIC_FIXED = 0, // The Reverse-Engineered DOS Jedi Renderer, using 16.16 fixed point. - TSR_CLASSIC_FLOAT, // Derived from the Reverse-Engineered Jedi Renderer but using floating point. - TSR_CLASSIC_GPU, // Derived from the Reverse-Engineered Jedi Renderer but using the GPU for low-level rendering. - TSR_COUNT, - TSR_HIGH_RESOLUTION, // Pick a high resolution renderer based on the type. - TSR_INVALID, // Invalid sub-renderer. -}; - -enum RendererType -{ - RENDERER_SOFTWARE = 0, - RENDERER_HARDWARE, - RENDERER_COUNT -}; - -namespace TFE_Jedi -{ - void renderer_resetState(); - void renderer_init(); - void renderer_destroy(); - void renderer_reset(); - void renderer_setLimits(); - void renderer_setType(RendererType type = RENDERER_SOFTWARE); - void setupInitCameraAndLights(); - void renderer_computeCameraTransform(RSector* sector, angle14_32 pitch, angle14_32 yaw, fixed16_16 camX, fixed16_16 camY, fixed16_16 camZ); - - // Set the current sub-renderer. - // Note that changing the sub-renderer at runtime may result in re-initialization of rendering data, causing a hitch. - JBool setSubRenderer(TFE_SubRenderer subRenderer = TSR_CLASSIC_FIXED); - TFE_SubRenderer getSubRenderer(); - RendererType renderer_getType(); - - // Camera parameters: yaw, pitch, position (x, y, z) - // sectorId containing the camera. - // ambient base or offset (default = MAX_LIGHT_LEVEL). - // camera light source - true if there is a camera based light source, in which case worldAmbient is treated as an offset. - // false if there is no camera light source, worldAmbient is then the base ambient. - //void setCamera(f32 yaw, f32 pitch, f32 x, f32 y, f32 z, s32 sectorId, s32 worldAmbient = 0, bool cameraLightSource = false); - // Draw the scene to the passed in display using the colormap for shading. - void drawWorld(u8* display, RSector* sector, const u8* colormap, const u8* lightSourceRamp); - - // Added for TFE so the GPU renderer knows the beginning and end of the drawing frame. - void beginRender(); - void endRender(); - - JBool render_setResolution(); - void renderer_setVisionEffect(s32 effect); - void renderer_setupCameraLight(JBool flatShading, JBool headlamp); - void renderer_setWorldAmbient(s32 value); - - // 2D - void blitTextureToScreen(TextureData* texture, s32 x0, s32 y0); - void clear3DView(u8* framebuffer); - - // TFE - // Add a hud texture callback, these will be called when setting up the GPU renderer - void renderer_addHudTextureCallback(TextureListCallback hudTextureCallback); - - extern s32 s_drawnObjCount; - extern bool s_showWireframe; - extern SecObject* s_drawnObj[]; -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/rcommon.cpp b/components/darkforces/tfe/TFE_Jedi/Renderer/rcommon.cpp deleted file mode 100644 index ee32a912..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/rcommon.cpp +++ /dev/null @@ -1,122 +0,0 @@ -#include "rcommon.h" -#include "redgePair.h" - -struct SecObject; - -namespace TFE_Jedi -{ - // Resolution - s32 s_width = 320; - s32 s_height = 200; - s32 s_screenYMidFix; - s32 s_screenYMidFlt; - s32 s_screenYMidBase; - s32 s_minScreenY; - s32 s_maxScreenY; - s32 s_screenXMid; - - // Window - s32 s_minScreenX_Pixels; - s32 s_maxScreenX_Pixels; - s32 s_windowMinX_Pixels; - s32 s_windowMaxX_Pixels; - s32 s_windowMinY_Pixels; - s32 s_windowMaxY_Pixels; - s32 s_windowMaxCeil; - s32 s_windowMinFloor; - s32 s_screenWidth; - - // Display - u8* s_display; - - // Render - RSector* s_prevSector; - s32 s_sectorIndex; - s32 s_maxAdjoinIndex; - s32 s_adjoinIndex; - s32 s_maxAdjoinDepth; - s32 s_windowX0; - s32 s_windowX1; - - // Column Heights - s32* s_columnTop = nullptr; - s32* s_columnBot = nullptr; - s32* s_windowTop_all = nullptr; - s32* s_windowBot_all = nullptr; - s32* s_windowTop = nullptr; - s32* s_windowBot = nullptr; - s32* s_windowTopPrev = nullptr; - s32* s_windowBotPrev = nullptr; - - s32* s_objWindowTop = nullptr; - s32* s_objWindowBot = nullptr; - - // Segment list. - s32 s_nextWall; - s32 s_curWallSeg; - s32 s_adjoinSegCount; - s32 s_adjoinDepth; - s32 s_drawFrame = 0; - - // Flats - s32 s_flatCount; - s32 s_wallMaxCeilY; - s32 s_wallMinFloorY; - - // Lighting - const u8* s_colorMap = nullptr; - const u8* s_lightSourceRamp = nullptr; - s32 s_flatAmbient = 0; - s32 s_sectorAmbient; - s32 s_scaledAmbient; - s32 s_cameraLightSource; - JBool s_enableFlatShading; - s32 s_worldAmbient; - s32 s_sectorAmbientFraction; - s32 s_lightCount = 3; - JBool s_flatLighting = JFALSE; - - // Limits - s32 s_maxSegCount = MAX_SEG; - s32 s_maxAdjoinSegCount = MAX_ADJOIN_SEG; - s32 s_maxAdjoinDepthRecursion = MAX_ADJOIN_DEPTH; - - // Debug - s32 s_maxWallCount; - s32 s_maxDepthCount; - - s32 s_drawnObjCount; - SecObject* s_drawnObj[MAX_DRAWN_OBJ_STORE]; - - ////////////////////////////////////////////////////////// - // Common Functions - ////////////////////////////////////////////////////////// - void sprite_decompressColumn(const u8* colData, u8* outBuffer, s32 height) - { - for (s32 y = 0, i = 0; y < height; ) - { - u8 count = *colData; - colData++; - - if (count & 0x80) - { - count &= 0x7f; - for (s32 r = 0; r < count; r++, y++) - { - outBuffer[y] = 0; - } - } - else - { - for (s32 r = 0; r < count; r++, y++, colData++) - { - outBuffer[y] = *colData; - } -#ifdef TFE_ESPBOX - // put the index last visible texel at the end of the buffer - outBuffer[height] = y; -#endif - } - } - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/rcommon.h b/components/darkforces/tfe/TFE_Jedi/Renderer/rcommon.h deleted file mode 100644 index f7e90133..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/rcommon.h +++ /dev/null @@ -1,93 +0,0 @@ -#pragma once -#include -#include "rlimits.h" -#include "rwallRender.h" - -struct ColorMap; - -namespace TFE_Jedi -{ - // Resolution - extern s32 s_width; - extern s32 s_height; - extern s32 s_screenYMidFix; - extern s32 s_screenYMidFlt; - extern s32 s_screenYMidBase; - extern s32 s_minScreenY; - extern s32 s_maxScreenY; - extern s32 s_screenXMid; - - // Window - extern s32 s_minScreenX_Pixels; - extern s32 s_maxScreenX_Pixels; - extern s32 s_windowMinX_Pixels; - extern s32 s_windowMaxX_Pixels; - extern s32 s_windowMinY_Pixels; - extern s32 s_windowMaxY_Pixels; - extern s32 s_windowMaxCeil; - extern s32 s_windowMinFloor; - extern s32 s_screenWidth; - - // Display - extern u8* s_display; - - // Render - extern RSector* s_prevSector; - extern s32 s_sectorIndex; - extern s32 s_maxAdjoinIndex; - extern s32 s_adjoinIndex; - extern s32 s_maxAdjoinDepth; - extern s32 s_windowX0; - extern s32 s_windowX1; - - // Column Heights - extern s32* s_columnTop; - extern s32* s_columnBot; - extern s32* s_windowTop_all; - extern s32* s_windowBot_all; - extern s32* s_windowTop; - extern s32* s_windowBot; - extern s32* s_windowTopPrev; - extern s32* s_windowBotPrev; - - extern s32* s_objWindowTop; - extern s32* s_objWindowBot; - - // WallSegments - extern s32 s_nextWall; - extern s32 s_curWallSeg; - extern s32 s_adjoinSegCount; - extern s32 s_adjoinDepth; - extern s32 s_drawFrame; - - // Flats - extern s32 s_flatCount; - extern s32 s_wallMaxCeilY; - extern s32 s_wallMinFloorY; - - // Lighting - extern const u8* s_colorMap; - extern const u8* s_lightSourceRamp; - extern s32 s_flatAmbient; - extern s32 s_sectorAmbient; - extern s32 s_scaledAmbient; - extern s32 s_cameraLightSource; - extern JBool s_enableFlatShading; - extern s32 s_worldAmbient; - extern s32 s_sectorAmbientFraction; - extern s32 s_lightCount; // Number of directional lights that affect 3D objects. - - extern JBool s_flatLighting; - - // Limits - extern s32 s_maxSegCount; - extern s32 s_maxAdjoinSegCount; - extern s32 s_maxAdjoinDepthRecursion; - - // Debug - extern s32 s_maxWallCount; - extern s32 s_maxDepthCount; - - // Common functions - void sprite_decompressColumn(const u8* colData, u8* outBuffer, s32 height); -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/redgePair.h b/components/darkforces/tfe/TFE_Jedi/Renderer/redgePair.h deleted file mode 100644 index 347ceb36..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/redgePair.h +++ /dev/null @@ -1,63 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include -#include - -namespace TFE_Jedi -{ - // A pair of edges along a single surface. - // This can represent either the top and bottom of walls for flat rendering or - // the top and bottom edges of an adjoin. - - struct EdgePairFixed - { - // Ceiling - fixed16_16 yCeil0; - fixed16_16 yCeil1; - fixed16_16 dyCeil_dx; - - // Floor - fixed16_16 yFloor0; - fixed16_16 yFloor1; - fixed16_16 dyFloor_dx; - - // Values in pixels - s32 yPixel_C0; - s32 yPixel_C1; - s32 yPixel_F0; - s32 yPixel_F1; - - // Screen X parameters, [x0, x1] is inclusive screen pixels. - s32 lengthInPixels; - s32 x0; - s32 x1; - }; - - struct EdgePairFloat - { - // Ceiling - f32 yCeil0; - f32 yCeil1; - f32 dyCeil_dx; - - // Floor - f32 yFloor0; - f32 yFloor1; - f32 dyFloor_dx; - - // Values in pixels - s32 yPixel_C0; - s32 yPixel_C1; - s32 yPixel_F0; - s32 yPixel_F1; - - // Screen X parameters, [x0, x1] is inclusive screen pixels. - s32 lengthInPixels; - s32 x0; - s32 x1; - }; -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/rlimits.h b/components/darkforces/tfe/TFE_Jedi/Renderer/rlimits.h deleted file mode 100644 index a8844bcc..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/rlimits.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once -#include - -namespace TFE_Jedi -{ - #define MAX_DRAWN_OBJ_STORE 32 // Maximum number of drawn sprites stored for future reference (like autoaim). - #define MAX_SEG 384 // Maximum number of wall segments visible in the frame. - #define MAX_ADJOIN_SEG 128 // Maximum number of adjoin segements visible in the frame. - #define MAX_SPLIT_WALLS 40 // Maximum number of times walls can be split in a sector. - #define MAX_ADJOIN_DEPTH 40 // Maximum adjoin depth - basically how many adjoins you can see through. - #define MAX_VIEW_OBJ_COUNT 128 // Maximum number of rendered objects in a single sector / view. - #define LIGHT_SOURCE_LEVELS 128 // Number of levels in the light source (like the headlamp or weapon fire). - #define LIGHT_LEVELS 32 // Number of light levels, maximum = LIGHT_LEVELS - 1 - #define MAX_LIGHT_LEVEL (LIGHT_LEVELS-1) - - // Extended Max Limits - #define MAX_SEG_EXT 2048 // Maximum number of wall segments with extended limits, this allows for ~1 wall/pixel column @1080p like vanilla @ 320x200 - #define MAX_ADJOIN_SEG_EXT 1024 // Maximum number of adjoin segments with extended limits. - #define MAX_ADJOIN_DEPTH_EXT 255 // Maximum adjoin recursion depth with extended limits. -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/robjectRender.h b/components/darkforces/tfe/TFE_Jedi/Renderer/robjectRender.h deleted file mode 100644 index 857315bb..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/robjectRender.h +++ /dev/null @@ -1,67 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include -#include "rmath.h" - -struct JediModel; -struct RSector; - -namespace TFE_Jedi -{ - enum ObjectType - { - OBJ_TYPE_SPRITE = 1, - OBJ_TYPE_3D = 2, - OBJ_TYPE_FRAME = 3, - }; - - enum ObjectFlags - { - OBJ_FLAG_RENDERABLE = (1 << 2), // The object is renderable, such as a 3D object, sprite or frame. - OBJ_FLAG_FULLBRIGHT = (1 << 3), // The object should be rendered fullbright (no shading). - }; - - struct SecObject - { - SecObject* self; - s32 type; - u32 typeFlags; - - vec3 posWS; - vec3 posVS; - - fixed16_16 worldWidth; - fixed16_16 worldHeight; - s32 transform[9]; - // Cached floating point transform (not used by Fixed Point sub-renderer). - f32 transformFlt[9]; - - // Rendering data. - union - { - JediModel* model; - Wax* wax; - WaxFrame* fme; - void* ptr; - }; - - s32 frame; - s32 anim; - RSector* sector; - - // See ObjectFlags above. - s32 flags; - - s16 pitch; - s16 yaw; - s16 roll; - s16 index; // index in containing sector object list. - - // Temporary (until Jedi Renderer is finished) - u32 gameObjId; - }; -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/rscanline.cpp b/components/darkforces/tfe/TFE_Jedi/Renderer/rscanline.cpp deleted file mode 100644 index cbade759..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/rscanline.cpp +++ /dev/null @@ -1,323 +0,0 @@ -#include "rscanline.h" -#include "rcommon.h" -#include - -namespace TFE_Jedi -{ -#ifdef TFE_ESPBOX - static inline -#endif - bool flat_buildScanlineCeiling(s32& i, s32 count, s32& x, s32 y, s32& left, s32& right, s32& scanlineLength, const EdgePairFixed* edges) - { - // Search for the left edge of the scanline. - s32 hasLeft = 0; - s32 hasRight = 0; - while (i < count && hasLeft == 0) - { - const EdgePairFixed* edge = &edges[i]; - if (y < edge->yPixel_C0) // Y is above the current edge, so start at left = x - { - left = x; - i++; - hasLeft = -1; - x = edge->x1 + 1; - } - else if (y >= edge->yPixel_C1) // Y is inside the current edge, so step to the end (left not set yet). - { - x = edge->x1 + 1; - i++; - if (i >= count) - { - hasLeft = -1; - left = x; - } - } - else if (edge->dyCeil_dx > 0) // find the left intersection. - { - x = edge->x0; - s32 ey = s_columnTop[x]; - while (x < s_windowMaxX_Pixels && y > ey) - { - x++; - ey = s_columnTop[x]; - }; - - left = x; - x = edge->x1 + 1; - hasLeft = -1; - i++; - } - else - { - left = x; - hasLeft = -1; - } - } // while (i < count && hasLeft == 0) - - if (i < count) - { - // Search for the right edge of the scanline. - while (i < count && hasRight == 0) - { - const EdgePairFixed* edge = &edges[i]; - if (y < edge->yPixel_C0) // Y is above the current edge, so move on to the next edge. - { - x = edge->x1 + 1; - i++; - if (i >= count) - { - right = x; - hasRight = -1; - } - } - else if (y >= edge->yPixel_C1) // Y is below the current edge so it must be the end. - { - right = x - 1; - x = edge->x1 + 1; - i++; - hasRight = -1; - } - else - { - if (edge->dyCeil_dx >= 0) - { - hasRight = -1; - right = x; - break; - } - else - { - x = edge->x0; - s32 ey = s_columnTop[x]; - while (x < s_windowMaxX_Pixels && ey >= y) - { - x++; - ey = s_columnTop[x]; - } - right = x; - x = edge->x1 + 1; - i++; - hasRight = -1; - break; - } - } - } - } // if (i < count) - else - { - if (hasLeft == 0) { return false; } - right = x; - } - - clipScanline(&left, &right, y); - scanlineLength = right - left + 1; - return true; - } - -#ifdef TFE_ESPBOX - static inline -#endif - bool flat_buildScanlineFloor(s32& i, s32 count, s32& x, s32 y, s32& left, s32& right, s32& scanlineLength, const EdgePairFixed* edges) - { - // Search for the left edge of the scanline. - s32 hasLeft = 0; - s32 hasRight = 0; - while (i < count && hasLeft == 0) - { - const EdgePairFixed* edge = &edges[i]; - if (y >= edge->yPixel_F0) // Y is above the current edge, so start at left = x - { - left = x; - i++; - hasLeft = -1; - x = edge->x1 + 1; - } - else if (y < edge->yPixel_F1) // Y is inside the current edge, so step to the end (left not set yet). - { - x = edge->x1 + 1; - i++; - if (i >= count) - { - hasLeft = -1; - left = x; - } - } - else if (edge->dyFloor_dx < 0) // find the left intersection. - { - x = edge->x0; - s32 ey = s_columnBot[x]; - while (x < s_windowMaxX_Pixels && y < ey) - { - x++; - ey = s_columnBot[x]; - }; - - left = x; - x = edge->x1 + 1; - hasLeft = -1; - i++; - } - else - { - left = x; - hasLeft = -1; - } - } // while (i < count && hasLeft == 0) - - if (i < count) - { - // Search for the right edge of the scanline. - while (i < count && hasRight == 0) - { - const EdgePairFixed* edge = &edges[i]; - if (y >= edge->yPixel_F0) // Y is above the current edge, so move on to the next edge. - { - x = edge->x1 + 1; - i++; - if (i >= count) - { - right = x; - hasRight = -1; - } - } - else if (y < edge->yPixel_F1) // Y is below the current edge so it must be the end. - { - right = x - 1; - x = edge->x1 + 1; - i++; - hasRight = -1; - } - else - { - if (edge->dyFloor_dx <= 0) - { - hasRight = -1; - right = x; - break; - } - else - { - x = edge->x0; - s32 ey = s_columnBot[x]; - while (x < s_windowMaxX_Pixels && ey <= y) - { - x++; - ey = s_columnBot[x]; - } - right = x; - x = edge->x1 + 1; - i++; - hasRight = -1; - break; - } - } - } - } // if (i < count) - else - { - if (hasLeft == 0) { return false; } - right = x; - } - - clipScanline(&left, &right, y); - scanlineLength = right - left + 1; - return true; - } - -#ifdef TFE_ESPBOX - static -#endif - void clipScanline(s32* left, s32* right, s32 y) - { - s32 x0 = *left; - s32 x1 = *right; - if (x0 > s_windowMaxX_Pixels || x1 < s_windowMinX_Pixels) - { - *left = x1 + 1; - return; - } - if (x0 < s_windowMinX_Pixels) { x0 = s_windowMinX_Pixels; *left = x0; } - if (x1 > s_windowMaxX_Pixels) { x1 = s_windowMaxX_Pixels; *right = x1; } - - // s_windowMaxCeil and s_windowMinFloor overlap and y is inside that overlap. - if (y < s_windowMaxCeil && y > s_windowMinFloor) - { - // Find the left side of the scanline. - s32* top = &s_windowTop[x0]; - s32* bot = &s_windowBot[x0]; - while (x0 <= x1) - { - if (y >= *top && y <= *bot) - { - break; - } - x0++; - top++; - bot++; - }; - *left = x0; - if (x0 > x1) - { - return; - } - - // Find the right side of the scanline. - top = &s_windowTop[x1]; - bot = &s_windowBot[x1]; - while (1) - { - if ((y >= *top && y <= *bot) || (x0 > x1)) - { - *right = x1; - return; - } - x1--; - top--; - bot--; - }; - } - // y is on the ceiling plane. - if (y < s_windowMaxCeil) - { - s32* top = &s_windowTop[x0]; - while (*top > y && x1 >= x0) - { - x0++; - top++; - } - *left = x0; - if (x0 <= x1) - { - s32* top = &s_windowTop[x1]; - while (*top > y && x1 >= x0) - { - x1--; - top--; - } - *right = x1; - } - } - // y is on the floor plane. - else if (y > s_windowMinFloor) - { - s32* bot = &s_windowBot[x0]; - while (*bot < y && x0 <= x1) - { - x0++; - bot++; - } - *left = x0; - - if (x0 <= x1) - { - bot = &s_windowBot[x1]; - while (*bot < y && x1 >= x0) - { - x1--; - bot--; - } - *right = x1; - } - } - } -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/rscanline.h b/components/darkforces/tfe/TFE_Jedi/Renderer/rscanline.h deleted file mode 100644 index 0460dd8f..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/rscanline.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include "redgePair.h" -#include -#include - -namespace TFE_Jedi -{ -#ifdef TFE_ESPBOX - static inline -#endif - bool flat_buildScanlineCeiling(s32& i, s32 count, s32& x, s32 y, s32& left, s32& right, s32& scanlineLength, const EdgePairFixed* edges); -#ifdef TFE_ESPBOX - static inline -#endif - bool flat_buildScanlineFloor(s32& i, s32 count, s32& x, s32 y, s32& left, s32& right, s32& scanlineLength, const EdgePairFixed* edges); -#ifdef TFE_ESPBOX - static -#endif - void clipScanline(s32* left, s32* right, s32 y); -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/rsectorRender.cpp b/components/darkforces/tfe/TFE_Jedi/Renderer/rsectorRender.cpp deleted file mode 100644 index 3132404e..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/rsectorRender.cpp +++ /dev/null @@ -1,38 +0,0 @@ -#include "rsectorRender.h" -#include "redgePair.h" -#include -#include "rcommon.h" - -namespace TFE_Jedi -{ - void TFE_Sectors::computeAdjoinWindowBounds(EdgePairFixed* adjoinEdges) - { - s32 yC = adjoinEdges->yPixel_C0; - if (yC > s_windowMinY_Pixels) - { - s_windowMinY_Pixels = yC; - } - s32 yF = adjoinEdges->yPixel_F0; - if (yF < s_windowMaxY_Pixels) - { - s_windowMaxY_Pixels = yF; - } - yC = adjoinEdges->yPixel_C1; - if (yC > s_windowMaxCeil) - { - s_windowMaxCeil = yC; - } - yF = adjoinEdges->yPixel_F1; - if (yF < s_windowMinFloor) - { - s_windowMinFloor = yF; - } - s_wallMaxCeilY = s_windowMinY_Pixels - 1; - s_wallMinFloorY = s_windowMaxY_Pixels + 1; - s_windowMinX_Pixels = adjoinEdges->x0; - s_windowMaxX_Pixels = adjoinEdges->x1; - s_windowTopPrev = s_windowTop; - s_windowBotPrev = s_windowBot; - s_prevSector = s_curSector; - } -} // TFE_Jedi diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/rsectorRender.h b/components/darkforces/tfe/TFE_Jedi/Renderer/rsectorRender.h deleted file mode 100644 index 61c985aa..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/rsectorRender.h +++ /dev/null @@ -1,81 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Sector -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include "rlimits.h" - -struct TextureFrame; -struct RWall; -struct SecObject; - -namespace TFE_Jedi -{ - enum SectorUpdateFlags - { - SEC_UPDATE = (1 << 0), - SEC_UPDATE_GEO = (1 << 1), - SEC_UPDATE_ALL = SEC_UPDATE | SEC_UPDATE_GEO - }; - - // Values saved at a given level of the stack while traversing sectors. - // This is 80 bytes in the original DOS code but will be more in The Force Engine - // due to 64 bit pointers. - struct SectorSaveValues - { - RSector* curSector; - RSector* prevSector; - void* depth1d; - u32 windowX0; - u32 windowX1; - s32 windowMinY; - s32 windowMaxY; - s32 windowMaxCeil; - s32 windowMinFloor; - s32 wallMaxCeilY; - s32 wallMinFloorY; - u32 windowMinX; - u32 windowMaxX; - s32* windowTop; - s32* windowBot; - s32* windowTopPrev; - s32* windowBotPrev; - s32 sectorAmbient; - s32 scaledAmbient; - s32 sectorAmbientFraction; - }; - - struct EdgePairFixed; - - class TFE_Sectors - { - public: - void computeAdjoinWindowBounds(EdgePairFixed* adjoinEdges); - - // Sub-Renderer specific - virtual void destroy() = 0; - virtual void reset() = 0; - virtual void prepare() = 0; - virtual void draw(RSector* sector) = 0; - virtual void subrendererChanged() = 0; - - // Tests if a point (p2) is to the left, on or right of an infinite line (p0 -> p1). - // Return: >0 p2 is on the left of the line. - // =0 p2 is on the line. - // <0 p2 is on the right of the line. - inline f32 isLeft(Vec2f p0, Vec2f p1, Vec2f p2) - { - return (p1.x - p0.x) * (p2.z - p0.z) - (p2.x - p0.x) * (p1.z - p0.z); - } - - protected: - SectorSaveValues s_sectorStack[MAX_ADJOIN_DEPTH]; - - RSector* s_curSector; - MemoryPool* s_memPool; - SecObject* s_objBuffer[MAX_VIEW_OBJ_COUNT]; - }; -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/rwallRender.h b/components/darkforces/tfe/TFE_Jedi/Renderer/rwallRender.h deleted file mode 100644 index 31748b7b..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/rwallRender.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include - -struct TextureFrame; -struct Allocator; - -namespace TFE_Jedi -{ - enum WallOrient - { - WORIENT_DZ_DX = 0, - WORIENT_DX_DZ = 1 - }; - - enum WallDrawFlags - { - WDF_MIDDLE = 0, - WDF_TOP = 1, - WDF_BOT = 2, - WDF_TOP_AND_BOT = 3, - }; -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/rwallSegment.h b/components/darkforces/tfe/TFE_Jedi/Renderer/rwallSegment.h deleted file mode 100644 index bec5ab8c..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/rwallSegment.h +++ /dev/null @@ -1,52 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wall -// Dark Forces Derived Renderer - Wall functions -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include - -namespace TFE_Jedi -{ - struct WallCached; - - struct RWallSegmentFixed - { - RWall* srcWall; // Source wall - s32 wallX0_raw; // Projected wall X coordinates before adjoin/wall clipping. - s32 wallX1_raw; - s32 wallX0; // Clipped projected X Coordinates. - s32 wallX1; - u8 orient; // Wall orientation (WORIENT_DZ_DX or WORIENT_DX_DZ) - u8 pad8[3]; - - fixed16_16 z0; // Depth - fixed16_16 z1; - fixed16_16 uCoord0; // Texture U coordinate offset based on clipping. - fixed16_16 x0View; // Viewspace vertex 0 X coordinate. - - fixed16_16 slope; // Wall slope - fixed16_16 uScale; // dUdX or dUdZ based on wall orientation. - }; - - struct RWallSegmentFloat - { - WallCached* srcWall;// Source wall - s32 wallX0_raw; // Projected wall X coordinates before adjoin/wall clipping. - s32 wallX1_raw; - s32 wallX0; // Clipped projected X Coordinates. - s32 wallX1; - u8 orient; // Wall orientation (WORIENT_DZ_DX or WORIENT_DX_DZ) - u8 pad8[3]; - - f32 z0; // Depth - f32 z1; - f32 uCoord0; // Texture U coordinate offset based on clipping. - f32 x0View; // Viewspace vertex 0 X coordinate. - - f32 slope; // Wall slope - f32 uScale; // dUdX or dUdZ based on wall orientation. - }; -} diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/screenDraw.cpp b/components/darkforces/tfe/TFE_Jedi/Renderer/screenDraw.cpp deleted file mode 100644 index 50fc3cc4..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/screenDraw.cpp +++ /dev/null @@ -1,1089 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#include "screenDraw.h" - -namespace TFE_Jedi -{ - enum ClipLines - { - CLIP_LEFT = 0x0001, - CLIP_RIGHT = 0x0010, - CLIP_TOP = 0x1000, - CLIP_BOT = 0x0100, - }; - - static u8 s_transColor = 0; -#ifdef TFE_ESPBOX - #define s_gpuEnabled (false) -#else - static bool s_gpuEnabled = false; -#endif - - void blitTextureToScreenScaledText(ScreenImage* texture, DrawRect* rect, s32 x0, s32 y0, fixed16_16 xScale, fixed16_16 yScale, u8* output); - - void screen_clear() - { - s_transColor = 0; -#ifndef TFE_ESPBOX - s_gpuEnabled = false; -#endif - } - - void screen_enableGPU(bool enable) - { -#ifndef TFE_ESPBOX - s_gpuEnabled = enable; -#endif - } - - void screenDraw_beginLines(u32 width, u32 height) - { - if (s_gpuEnabled) - { - screenGPU_beginLines(width, height); - } - } - - void screenDraw_endLines() - { - if (s_gpuEnabled) - { - screenGPU_endLines(); - } - } - - void screenDraw_beginQuads(u32 width, u32 height) - { - if (s_gpuEnabled) - { - screenGPU_beginImageQuads(width, height); - screenGPU_beginQuads(width, height); - } - } - - void screenDraw_endQuads() - { - if (s_gpuEnabled) - { - screenGPU_endImageQuads(); - screenGPU_endQuads(); - } - } - - void screen_drawPoint(ScreenRect* rect, s32 x, s32 z, u8 color, u8* framebuffer) - { - if (x < rect->left || x > rect->right || z < rect->top || z > rect->bot) { return; } - if (s_gpuEnabled) - { - screenGPU_drawPoint(rect, x, z, color); - return; - } - framebuffer[z*vfb_getStride()+x] = color; - } - - void screen_drawLine(ScreenRect* rect, s32 x0, s32 z0, s32 x1, s32 z1, u8 color, u8* framebuffer) - { - if (s_gpuEnabled) - { - screenGPU_drawLine(rect, x0, z0, x1, z1, color); - return; - } - if (!screen_clipLineToRect(rect, &x0, &z0, &x1, &z1)) { return; } - - const u32 stride = vfb_getStride(); - s32 x = x0, z = z0; - s32 dx = x1 - x; - s32 dz = z1 - z; - s32 xDir = (dx > 0) ? 1 : -1; - s32 zDir = (dz > 0) ? 1 : -1; - - if (xDir < 0) { dz = -dz; } - if (zDir > 0) { dx = -dx; } - - // Place the first point. - framebuffer[z0*stride + x0] = color; - - s32 dist = 0; - while (x != x1 || z != z1) - { - s32 absXDist = abs(dx + dist); - s32 absZDist = abs(dz + dist); - if (absZDist < absXDist) - { - dist += dz; - x += xDir; - } - else - { - dist += dx; - z += zDir; - } - framebuffer[z*stride + x] = color; - } - } - - void screen_drawCircle(ScreenRect* rect, s32 x, s32 z, s32 r, s32 stepAngle, u8 color, u8* framebuffer) - { - s32 rPixel = floor16(r + HALF_16); - s32 x1 = x + rPixel; - s32 x0 = x - rPixel; - s32 z1 = z + rPixel; - s32 z0 = z - rPixel; - if (x1 < rect->left || x0 > rect->right || z1 < rect->top || z0 > rect->bot) - { - return; - } - - fixed16_16 cosAngle, sinAngle; - sinCosFixed(0, &sinAngle, &cosAngle); - s32 cx0 = x + floor16(mul16(r, cosAngle) + HALF_16); - s32 cz0 = z + floor16(mul16(r, sinAngle) + HALF_16); - - s32 curAngle = stepAngle; - while (curAngle <= 16384) - { - sinCosFixed(curAngle, &sinAngle, &cosAngle); - s32 cx1 = x + floor16(mul16(r, cosAngle) + HALF_16); - s32 cz1 = z + floor16(mul16(r, sinAngle) + HALF_16); - - screen_drawLine(rect, cx0, cz0, cx1, cz1, color, framebuffer); - - curAngle += stepAngle; - cx0 = cx1; - cz0 = cz1; - } - } - - JBool screen_clipLineToRect(ScreenRect* rect, s32* x0, s32* z0, s32* x1, s32* z1) - { - u32 clip0 = 0; - if (*x0 < rect->left) { clip0 = CLIP_LEFT; } - else if (*x0 > rect->right) { clip0 = CLIP_RIGHT; } - if (*z0 < rect->top) { clip0 |= CLIP_TOP; } - else if (*z0 > rect->bot) { clip0 |= CLIP_BOT; } - - u32 clip1 = 0; - if (*x1 < rect->left) { clip1 = CLIP_LEFT; } - else if (*x1 > rect->right) { clip1 = CLIP_RIGHT; } - if (*z1 < rect->top) { clip1 |= CLIP_TOP; } - else if (*z1 > rect->bot) { clip1 |= CLIP_BOT; } - - // Triavially accept or reject. - if (!clip0 && !clip1) - { - return JTRUE; - } - else if (clip1 & clip0) - { - return JFALSE; - } - - fixed16_16 z0F = intToFixed16(*z0); - fixed16_16 x1F = intToFixed16(*x1); - fixed16_16 z1F = intToFixed16(*z1); - fixed16_16 x0F = intToFixed16(*x0); - JBool isVert = (x0F == x1F) ? JTRUE : JFALSE; - JBool isHorz = (z0F == z1F) ? JTRUE : JFALSE; - while (1) - { - u32 clip = clip0 ? clip0 : clip1; - fixed16_16 dx = x1F - x0F; - fixed16_16 dz = z1F - z0F; - fixed16_16 clipX, clipZ; - if (clip & (CLIP_TOP | CLIP_BOT)) - { - fixed16_16 clipLine = intToFixed16((clip & CLIP_TOP) ? rect->top : rect->bot); - if (isVert) - { - clipX = x0F; - } - else - { - clipX = mul16(div16(dx, dz), (clipLine - z0F)) + x0F; - } - clipZ = clipLine; - } - else if (clip & (CLIP_RIGHT | CLIP_LEFT)) - { - fixed16_16 clipLine = intToFixed16((clip & CLIP_RIGHT) ? rect->right : rect->left); - if (isHorz) - { - clipZ = z0F; - } - else - { - clipZ = mul16(div16(dz, dx), (clipLine - x0F)) + z0F; - } - clipX = clipLine; - } - s32 newX = floor16(clipX); - s32 newZ = floor16(clipZ); - if (clip0 == clip) - { - x0F = clipX; - z0F = clipZ; - } - else - { - x1F = clipX; - z1F = clipZ; - } - - u32 newClip = 0; - if (newX < rect->left) { newClip = CLIP_LEFT; } - else if (newX > rect->right) { newClip = CLIP_RIGHT; } - if (newZ < rect->top) { newClip|= CLIP_TOP; } - else if (newZ > rect->bot) { newClip|= CLIP_BOT; } - - if (clip0 == clip) { clip0 = newClip; } - else { clip1 = newClip; } - - if (!clip0 && !clip1) - { - *x0 = floor16(x0F); - *z0 = floor16(z0F); - *x1 = floor16(x1F); - *z1 = floor16(z1F); - return JTRUE; - } - else if (clip1&clip0) - { - return JFALSE; - } - } - return JFALSE; - } - - ///////////////////////////////////////////////////////// - // Original drawing code assumes 320x200 - ///////////////////////////////////////////////////////// - -#ifdef TFE_ESPBOX -#define vfb_getStride() (320) -#endif - -#ifdef TFE_ESPBOX - static inline -#endif - void textureBlitColumnOpaque(u8* image, u8* outBuffer, s32 yPixelCount) - { - s32 end = yPixelCount - 1; - s32 offset = 0; - const u32 stride = vfb_getStride(); - for (s32 i = end; i >= 0; i--, offset += stride) - { - outBuffer[offset] = image[i]; - } - } - -#ifdef TFE_ESPBOX - static inline -#endif - void textureBlitColumnTrans(u8* image, u8* outBuffer, s32 yPixelCount) - { - s32 end = yPixelCount - 1; - s32 offset = 0; - const u32 stride = vfb_getStride(); - for (s32 i = end; i >= 0; i--, offset += stride) - { - if (image[i] != s_transColor) { outBuffer[offset] = image[i]; } - } - } - -#ifdef TFE_ESPBOX - static inline -#endif - void textureBlitColumnOpaqueRow(u8* image, u8* outBuffer, s32 imageStride, s32 yPixelCount) - { - s32 end = yPixelCount - 1; - s32 offset = 0; - s32 yOffset = end * imageStride; - const u32 stride = vfb_getStride(); - for (s32 i = end; i >= 0; i--, offset += stride, yOffset -= imageStride) - { - outBuffer[offset] = image[yOffset]; - } - } - -#ifdef TFE_ESPBOX - static inline -#endif - void textureBlitColumnTransRow(u8* image, u8* outBuffer, s32 imageStride, s32 yPixelCount) - { - s32 end = yPixelCount - 1; - s32 offset = 0; - s32 yOffset = end * imageStride; - const u32 stride = vfb_getStride(); - for (s32 i = end; i >= 0; i--, offset += stride, yOffset -= imageStride) - { - if (image[yOffset] != s_transColor) { outBuffer[offset] = image[yOffset]; } - } - } - - ////////////////////////////////// - // Image blit functions -#ifdef TFE_ESPBOX - static inline -#endif - void imageBlitColumnOpaque(u8* image, u8* outBuffer, s32 yPixelCount) - { - s32 end = yPixelCount - 1; - s32 offset = 0; - const u32 stride = vfb_getStride(); - for (s32 i = end; i >= 0; i--, offset += stride, image++) - { - outBuffer[offset] = *image; - } - } - -#ifdef TFE_ESPBOX - static inline -#endif - void imageBlitColumnTrans(u8* image, u8* outBuffer, s32 yPixelCount) - { - s32 end = yPixelCount - 1; - s32 offset = 0; - const u32 stride = vfb_getStride(); - for (s32 i = end; i >= 0; i--, offset += stride) - { - u8 color = *image; - if (color != s_transColor) { outBuffer[offset] = color; } - } - } - -#ifdef TFE_ESPBOX - static inline -#endif - void imageBlitColumnOpaqueRow(u8* image, u8* outBuffer, s32 imageStride, s32 yPixelCount) - { - s32 end = yPixelCount - 1; - s32 offset = 0; - s32 yOffset = 0; - const u32 stride = vfb_getStride(); - for (s32 i = end; i >= 0; i--, offset += stride, yOffset += imageStride) - { - outBuffer[offset] = image[yOffset]; - } - } - -#ifdef TFE_ESPBOX - static inline -#endif - void imageBlitColumnTransRow(u8* image, u8* outBuffer, s32 imageStride, s32 yPixelCount) - { - s32 end = yPixelCount - 1; - s32 offset = 0; - s32 yOffset = 0; - const u32 stride = vfb_getStride(); - for (s32 i = end; i >= 0; i--, offset += stride, yOffset += imageStride) - { - u8 color = image[yOffset]; - if (color != s_transColor) { outBuffer[offset] = color; } - } - } - - ///////////////////////////////// - -#ifdef TFE_ESPBOX - static inline -#endif - void textureBlitColumnOpaqueLit(u8* image, u8* outBuffer, s32 yPixelCount, const u8* atten) - { - s32 end = yPixelCount - 1; - s32 offset = 0; - const u32 stride = vfb_getStride(); - for (s32 i = end; i >= 0; i--, offset += stride) - { - outBuffer[offset] = atten[image[i]]; - } - } - -#ifdef TFE_ESPBOX - static inline -#endif - void textureBlitColumnTransLit(u8* image, u8* outBuffer, s32 yPixelCount, const u8* atten) - { - s32 end = yPixelCount - 1; - s32 offset = 0; - const u32 stride = vfb_getStride(); - for (s32 i = end; i >= 0; i--, offset += stride) - { - if (image[i] != s_transColor) { outBuffer[offset] = atten[image[i]]; } - } - } - - void blitTextureToScreen(TextureData* texture, DrawRect* rect, s32 x0, s32 y0, u8* output, JBool forceTransparency, JBool forceOpaque) - { - if (s_gpuEnabled) - { - screenGPU_blitTextureLit(texture, rect, intToFixed16(x0), intToFixed16(y0), 31); - return; - } - s32 x1 = x0 + texture->width - 1; - s32 y1 = y0 + texture->height - 1; - - // Cull if outside of the draw rect. - if (x1 < rect->x0 || y1 < rect->y0 || x0 > rect->x1 || y0 > rect->y1) { return; } - - s32 srcX = 0, srcY = 0; - if (y0 < rect->y0) - { - y0 = rect->y0; - } - if (y1 > rect->y1) - { - srcY = y1 - rect->y1; - y1 = rect->y1; - } - - if (x0 < rect->x0) - { - srcX = x0 - rect->x0; - x0 = rect->x0; - } - if (x1 > rect->x1) - { - x1 = rect->x1; - } - - s32 yPixelCount = y1 - y0 + 1; - if (yPixelCount <= 0) { return; } - - u8* buffer = texture->image + texture->height*srcX + srcY; - const u32 stride = vfb_getStride(); - if (!forceOpaque && ((texture->flags & OPACITY_TRANS) || forceTransparency)) - { - for (s32 col = x0; col <= x1; col++, buffer += texture->height) - { - textureBlitColumnTrans(buffer, output + y0 * stride + col, yPixelCount); - } - } - else - { - for (s32 col = x0; col <= x1; col++, buffer += texture->height) - { - textureBlitColumnOpaque(buffer, output + y0 * stride + col, yPixelCount); - } - } - } - - void blitTextureToScreenLit(TextureData* texture, DrawRect* rect, s32 x0, s32 y0, const u8* atten, u8* output, JBool forceTransparency) - { - if (s_gpuEnabled) - { - u8 lightLevel = RClassic_Fixed::getLightLevelFromAtten(atten); - screenGPU_blitTextureLit(texture, rect, intToFixed16(x0), intToFixed16(y0), lightLevel); - return; - } - s32 x1 = x0 + texture->width - 1; - s32 y1 = y0 + texture->height - 1; - - // Cull if outside of the draw rect. - if (x1 < rect->x0 || y1 < rect->y0 || x0 > rect->x1 || y0 > rect->y1) { return; } - - s32 srcX = 0, srcY = 0; - if (y0 < rect->y0) - { - y0 = rect->y0; - } - if (y1 > rect->y1) - { - srcY = y1 - rect->y1; - y1 = rect->y1; - } - - if (x0 < rect->x0) - { - srcX = x0 - rect->x0; - x0 = rect->x0; - } - if (x1 > rect->x1) - { - x1 = rect->x1; - } - - s32 yPixelCount = y1 - y0 + 1; - if (yPixelCount <= 0) { return; } - - u8* buffer = texture->image + texture->height*srcX + srcY; - const u32 stride = vfb_getStride(); - if ((texture->flags & OPACITY_TRANS) || forceTransparency) - { - for (s32 col = x0; col <= x1; col++, buffer += texture->height) - { - textureBlitColumnTransLit(buffer, output + y0 * stride + col, yPixelCount, atten); - } - } - else - { - for (s32 col = x0; col <= x1; col++, buffer += texture->height) - { - textureBlitColumnOpaqueLit(buffer, output + y0 * stride + col, yPixelCount, atten); - } - } - } - -#ifdef TFE_ESPBOX -#undef vfb_getStride -#endif - - ///////////////////////////////////////////////////////// - // The "scaled" variants allow for scaling. - ///////////////////////////////////////////////////////// - void textureBlitColumnOpaqueScaled(u8* image, u8* outBuffer, s32 yPixelCount, fixed16_16 vCoord, fixed16_16 vStep) - { - s32 end = yPixelCount - 1; - s32 offset = 0; - const u32 stride = vfb_getStride(); - for (s32 i = end; i >= 0; i--, offset += stride, vCoord += vStep) - { - s32 v = floor16(vCoord); - outBuffer[offset] = image[v]; - } - } - - void textureBlitColumnTransScaled(u8* image, u8* outBuffer, s32 yPixelCount, fixed16_16 vCoord, fixed16_16 vStep) - { - s32 end = yPixelCount - 1; - s32 offset = 0; - const u32 stride = vfb_getStride(); - for (s32 i = end; i >= 0; i--, offset += stride, vCoord += vStep) - { - s32 v = floor16(vCoord); - if (image[v]) { outBuffer[offset] = image[v]; } - } - } - - void textureBlitColumnTransIScaled(u8* image, u8* outBuffer, s32 yPixelCount, s32 scale, s32 v0) - { - s32 end = yPixelCount - 1; - s32 offset = 0; - const u32 stride = vfb_getStride(); - s32 vStep = 0; - s32 v = v0; - for (s32 i = end; i >= 0; i--, offset += stride) - { - if (image[v]) { outBuffer[offset] = image[v]; } - - vStep++; - if (vStep >= scale) - { - vStep = 0; - v--; - } - } - } - - void textureBlitColumnOpaqueLitScaled(u8* image, u8* outBuffer, s32 yPixelCount, const u8* atten, fixed16_16 vCoord, fixed16_16 vStep) - { - s32 end = yPixelCount - 1; - s32 offset = 0; - const u32 stride = vfb_getStride(); - for (s32 i = end; i >= 0; i--, offset += stride, vCoord += vStep) - { - s32 v = floor16(vCoord); - outBuffer[offset] = atten[image[v]]; - } - } - - void textureBlitColumnTransLitScaled(u8* image, u8* outBuffer, s32 yPixelCount, const u8* atten, fixed16_16 vCoord, fixed16_16 vStep) - { - s32 end = yPixelCount - 1; - s32 offset = 0; - const u32 stride = vfb_getStride(); - for (s32 i = end; i >= 0; i--, offset += stride, vCoord += vStep) - { - s32 v = floor16(vCoord); - if (image[v]) { outBuffer[offset] = atten[image[v]]; } - } - } - - void textureBlitColumnOpaqueScaledRow(u8* image, u8* outBuffer, s32 yPixelCount, s32 imageStride, fixed16_16 vCoord, fixed16_16 vStep) - { - s32 end = yPixelCount - 1; - s32 offset = 0; - const u32 stride = vfb_getStride(); - for (s32 i = end; i >= 0; i--, offset += stride, vCoord += vStep) - { - s32 v = floor16(vCoord)*imageStride; - outBuffer[offset] = image[v]; - } - } - - void screenDraw_setTransColor(u8 color) - { - s_transColor = color; - } - - void textureBlitColumnTransScaledRow(u8* image, u8* outBuffer, s32 yPixelCount, s32 imageStride, fixed16_16 vCoord, fixed16_16 vStep) - { - s32 end = yPixelCount - 1; - s32 offset = 0; - const u32 stride = vfb_getStride(); - for (s32 i = end; i >= 0; i--, offset += stride, vCoord += vStep) - { - s32 v = floor16(vCoord)*imageStride; - if (image[v] != s_transColor) { outBuffer[offset] = image[v]; } - } - } - - void textureBlitColumnOpaqueLitScaledRow(u8* image, u8* outBuffer, s32 yPixelCount, s32 imageStride, const u8* atten, fixed16_16 vCoord, fixed16_16 vStep) - { - s32 end = yPixelCount - 1; - s32 offset = 0; - const u32 stride = vfb_getStride(); - for (s32 i = end; i >= 0; i--, offset += stride, vCoord += vStep) - { - s32 v = floor16(vCoord)*imageStride; - outBuffer[offset] = atten[image[v]]; - } - } - - void textureBlitColumnTransLitScaledRow(u8* image, u8* outBuffer, s32 yPixelCount, s32 imageStride, const u8* atten, fixed16_16 vCoord, fixed16_16 vStep) - { - s32 end = yPixelCount - 1; - s32 offset = 0; - const u32 stride = vfb_getStride(); - for (s32 i = end; i >= 0; i--, offset += stride, vCoord += vStep) - { - s32 v = floor16(vCoord)*imageStride; - if (image[v]) { outBuffer[offset] = atten[image[v]]; } - } - } - - void blitTextureToScreenScaled(TextureData* texture, DrawRect* rect, s32 x0, s32 y0, fixed16_16 xScale, fixed16_16 yScale, u8* output, JBool forceTransparency) - { - if (s_gpuEnabled) - { - screenGPU_blitTextureScaled(texture, rect, intToFixed16(x0), intToFixed16(y0), xScale, yScale, 31); - return; - } - ScreenImage image = - { - texture->width, - texture->height, - texture->image, - (forceTransparency || (texture->flags & OPACITY_TRANS)) ? JTRUE : JFALSE, - JTRUE - }; - blitTextureToScreenScaled(&image, rect, x0, y0, xScale, yScale, output); - } - - void blitTextureToScreenScaledText(TextureData* texture, DrawRect* rect, s32 x0, s32 y0, fixed16_16 xScale, fixed16_16 yScale, u8* output, JBool forceTransparency) - { - if (s_gpuEnabled) - { - screenGPU_blitTextureScaled(texture, rect, intToFixed16(x0), intToFixed16(y0), xScale, yScale, 31); - return; - } - ScreenImage image = - { - texture->width, - texture->height, - texture->image, - (forceTransparency || (texture->flags & OPACITY_TRANS)) ? JTRUE : JFALSE, - JTRUE - }; - blitTextureToScreenScaledText(&image, rect, x0, y0, xScale, yScale, output); - } - - void blitTextureToScreenIScale(TextureData* texture, DrawRect* rect, s32 x0, s32 y0, s32 scale, u8* output) - { - if (s_gpuEnabled) - { - screenGPU_blitTextureScaled(texture, rect, intToFixed16(x0), intToFixed16(y0), intToFixed16(scale), intToFixed16(scale), 31); - return; - } - s32 x1 = x0 + (texture->width - 1)*scale; - s32 y1 = y0 + (texture->height - 1)*scale; - s32 yPixelCount = y1 - y0 + 1; - if (yPixelCount <= 0) { return; } - - s32 uStep = scale; - s32 u = 0; - const u32 stride = vfb_getStride(); - for (s32 col = x0; col <= x1; col++) - { - u8* buffer = texture->image + u*texture->height; - textureBlitColumnTransIScaled(buffer, output + y0 * stride + col, yPixelCount, scale, texture->height - 1); - - uStep++; - if (uStep >= scale) - { - uStep = 0; - u++; - } - } - } - -#ifdef TFE_ESPBOX -#define vfb_getStride() (320) -#endif - - void blitTextureToScreen(ScreenImage* texture, DrawRect* rect, s32 x0, s32 y0, u8* output) - { - if (s_gpuEnabled) { return; } - s32 x1 = x0 + texture->width - 1; - s32 y1 = y0 + texture->height - 1; - - // Cull if outside of the draw rect. - if (x1 < rect->x0 || y1 < rect->y0 || x0 > rect->x1 || y0 > rect->y1) { return; } - - s32 srcX = 0, srcY = 0; - if (y0 < rect->y0) - { - y0 = rect->y0; - } - if (y1 > rect->y1) - { - srcY = y1 - rect->y1; - y1 = rect->y1; - } - - if (x0 < rect->x0) - { - srcX = x0 - rect->x0; - x0 = rect->x0; - } - if (x1 > rect->x1) - { - x1 = rect->x1; - } - - s32 yPixelCount = y1 - y0 + 1; - if (yPixelCount <= 0) { return; } - - const u32 stride = vfb_getStride(); - output += y0 * stride; - if (texture->columnOriented) - { - u8* buffer = texture->image + texture->height*srcX + srcY; - if (texture->trans) - { - for (s32 col = x0; col <= x1; col++, buffer += texture->height) - { - imageBlitColumnTrans(buffer, output + col, yPixelCount); - } - } - else - { - for (s32 col = x0; col <= x1; col++, buffer += texture->height) - { - imageBlitColumnOpaque(buffer, output + col, yPixelCount); - } - } - } - else - { - u8* buffer = texture->image + texture->width*srcY + srcX; - if (texture->trans) - { - for (s32 col = x0; col <= x1; col++, buffer++) - { - imageBlitColumnTransRow(buffer, output + col, texture->width, yPixelCount); - } - } - else - { - for (s32 col = x0; col <= x1; col++, buffer++) - { - imageBlitColumnOpaqueRow(buffer, output + col, texture->width, yPixelCount); - } - } - } - } - -#ifdef TFE_ESPBOX -#undef vfb_getStride -#endif - - void blitTextureToScreenScaled(ScreenImage* texture, DrawRect* rect, s32 x0, s32 y0, fixed16_16 xScale, fixed16_16 yScale, u8* output) - { - if (s_gpuEnabled) - { - return; - } - s32 x1 = x0 + floor16(mul16(intToFixed16(texture->width - 1), xScale)); - s32 y1 = y0 + floor16(mul16(intToFixed16(texture->height - 1), yScale)); - fixed16_16 u0 = 0, v1 = 0; - fixed16_16 v0 = intToFixed16(texture->height - 1); - fixed16_16 uStep = div16(intToFixed16(texture->width), intToFixed16(x1 - x0 + 1)); - fixed16_16 vStep = -div16(intToFixed16(texture->height), intToFixed16(y1 - y0 + 1)); - - if (!texture->columnOriented) - { - swap(v0, v1); - vStep = -vStep; - } - - // Cull if outside of the draw rect. - if (x1 < rect->x0 || y1 < rect->y0 || x0 > rect->x1 || y0 > rect->y1) { return; } - - if (y0 < rect->y0) - { - v0 += vStep * (rect->y0 - y0); - y0 = rect->y0; - } - if (y1 > rect->y1) - { - y1 = rect->y1; - } - - if (x0 < rect->x0) - { - u0 += uStep * (rect->x0 - x0); - x0 = rect->x0; - } - if (x1 > rect->x1) - { - x1 = rect->x1; - } - - s32 yPixelCount = y1 - y0 + 1; - if (yPixelCount <= 0) { return; } - - const u32 stride = vfb_getStride(); - if (texture->columnOriented) - { - fixed16_16 u = u0; - if (texture->trans) - { - for (s32 col = x0; col <= x1; col++, u += uStep) - { - u8* buffer = texture->image + floor16(u)*texture->height; - textureBlitColumnTransScaled(buffer, output + y0 * stride + col, yPixelCount, v0, vStep); - } - } - else - { - for (s32 col = x0; col <= x1; col++, u += uStep) - { - u8* buffer = texture->image + floor16(u)*texture->height; - textureBlitColumnOpaqueScaled(buffer, output + y0 * stride + col, yPixelCount, v0, vStep); - } - } - } - else - { - const s32 imageStride = texture->width; - fixed16_16 u = u0; - if (texture->trans) - { - for (s32 col = x0; col <= x1; col++, u += uStep) - { - u8* buffer = texture->image + floor16(u); - textureBlitColumnTransScaledRow(buffer, output + y0 * stride + col, yPixelCount, imageStride, v0, vStep); - } - } - else - { - for (s32 col = x0; col <= x1; col++, u += uStep) - { - u8* buffer = texture->image + floor16(u); - textureBlitColumnOpaqueScaledRow(buffer, output + y0 * stride + col, yPixelCount, imageStride, v0, vStep); - } - } - } - } - - void blitTextureToScreenScaledText(ScreenImage* texture, DrawRect* rect, s32 x0, s32 y0, fixed16_16 xScale, fixed16_16 yScale, u8* output) - { - if (s_gpuEnabled) - { - return; - } - s32 x1 = x0 + floor16(mul16(intToFixed16(texture->width), xScale)); - s32 y1 = y0 + floor16(mul16(intToFixed16(texture->height), yScale)); - fixed16_16 u0 = 0, v1 = 0; - fixed16_16 v0 = intToFixed16(texture->height) - 1; - fixed16_16 uStep = div16(intToFixed16(texture->width), intToFixed16(x1 - x0)); - fixed16_16 vStep = -div16(intToFixed16(texture->height), intToFixed16(y1 - y0)); - - if (!texture->columnOriented) - { - swap(v0, v1); - vStep = -vStep; - } - - // Cull if outside of the draw rect. - if (x1 < rect->x0 || y1 < rect->y0 || x0 > rect->x1 || y0 > rect->y1) { return; } - - if (y0 < rect->y0) - { - v0 += vStep * (rect->y0 - y0); - y0 = rect->y0; - } - if (y1 > rect->y1) - { - y1 = rect->y1; - } - - if (x0 < rect->x0) - { - u0 += uStep * (rect->x0 - x0); - x0 = rect->x0; - } - if (x1 > rect->x1) - { - x1 = rect->x1; - } - - s32 yPixelCount = y1 - y0 + 1; - if (yPixelCount <= 0) { return; } - - const u32 stride = vfb_getStride(); - if (texture->columnOriented) - { - fixed16_16 u = u0; - if (texture->trans) - { - for (s32 col = x0; col <= x1; col++, u += uStep) - { - u8* buffer = texture->image + floor16(u)*texture->height; - textureBlitColumnTransScaled(buffer, output + y0 * stride + col, yPixelCount, v0, vStep); - } - } - else - { - for (s32 col = x0; col <= x1; col++, u += uStep) - { - u8* buffer = texture->image + floor16(u)*texture->height; - textureBlitColumnOpaqueScaled(buffer, output + y0 * stride + col, yPixelCount, v0, vStep); - } - } - } - else - { - const s32 imageStride = texture->width; - fixed16_16 u = u0; - if (texture->trans) - { - for (s32 col = x0; col <= x1; col++, u += uStep) - { - u8* buffer = texture->image + floor16(u); - textureBlitColumnTransScaledRow(buffer, output + y0 * stride + col, yPixelCount, imageStride, v0, vStep); - } - } - else - { - for (s32 col = x0; col <= x1; col++, u += uStep) - { - u8* buffer = texture->image + floor16(u); - textureBlitColumnOpaqueScaledRow(buffer, output + y0 * stride + col, yPixelCount, imageStride, v0, vStep); - } - } - } - } - - void blitTextureToScreenLitScaled(TextureData* texture, DrawRect* rect, s32 x0, s32 y0, fixed16_16 xScale, fixed16_16 yScale, const u8* atten, u8* output, JBool forceTransparency) - { - if (s_gpuEnabled) - { - u8 lightLevel = RClassic_Fixed::getLightLevelFromAtten(atten); - screenGPU_blitTextureScaled(texture, rect, intToFixed16(x0), intToFixed16(y0), xScale, yScale, lightLevel); - return; - } - ScreenImage image = - { - texture->width, - texture->height, - texture->image, - forceTransparency || (texture->flags & OPACITY_TRANS) ? JTRUE : JFALSE, - JTRUE - }; - blitTextureToScreenLitScaled(&image, rect, x0, y0, xScale, yScale, atten, output); - } - - void blitTextureToScreenLitScaled(ScreenImage* texture, DrawRect* rect, s32 x0, s32 y0, fixed16_16 xScale, fixed16_16 yScale, const u8* atten, u8* output) - { - if (s_gpuEnabled) { return; } - s32 x1 = x0 + floor16(mul16(intToFixed16(texture->width - 1), xScale)); - s32 y1 = y0 + floor16(mul16(intToFixed16(texture->height - 1), yScale)); - fixed16_16 u0 = 0, v1 = 0; - fixed16_16 u1 = intToFixed16(texture->width - 1); - fixed16_16 v0 = intToFixed16(texture->height - 1); - fixed16_16 uStep = div16(intToFixed16(texture->width - 1), intToFixed16(x1 - x0)); - fixed16_16 vStep = -div16(intToFixed16(texture->height - 1), intToFixed16(y1 - y0)); - - if (!texture->columnOriented) - { - swap(v0, v1); - vStep = -vStep; - } - - // Cull if outside of the draw rect. - if (x1 < rect->x0 || y1 < rect->y0 || x0 > rect->x1 || y0 > rect->y1) { return; } - - if (y0 < rect->y0) - { - v0 += vStep * (rect->y0 - y0); - y0 = rect->y0; - } - if (y1 > rect->y1) - { - y1 = rect->y1; - } - - if (x0 < rect->x0) - { - u0 += uStep * (rect->x0 - x0); - x0 = rect->x0; - } - if (x1 > rect->x1) - { - x1 = rect->x1; - } - - s32 yPixelCount = y1 - y0 + 1; - if (yPixelCount <= 0) { return; } - - const u32 stride = vfb_getStride(); - if (texture->columnOriented) - { - fixed16_16 u = u0; - if (texture->trans) - { - for (s32 col = x0; col <= x1; col++, u += uStep) - { - u8* buffer = texture->image + floor16(u)*texture->height; - textureBlitColumnTransLitScaled(buffer, output + y0 * stride + col, yPixelCount, atten, v0, vStep); - } - } - else - { - for (s32 col = x0; col <= x1; col++, u += uStep) - { - u8* buffer = texture->image + floor16(u)*texture->height; - textureBlitColumnOpaqueLitScaled(buffer, output + y0 * stride + col, yPixelCount, atten, v0, vStep); - } - } - } - else - { - const s32 imageStride = texture->width; - fixed16_16 u = u0; - if (texture->trans) - { - for (s32 col = x0; col <= x1; col++, u += uStep) - { - u8* buffer = texture->image + floor16(u); - textureBlitColumnTransLitScaledRow(buffer, output + y0 * stride + col, yPixelCount, imageStride, atten, v0, vStep); - } - } - else - { - for (s32 col = x0; col <= x1; col++, u += uStep) - { - u8* buffer = texture->image + floor16(u); - textureBlitColumnOpaqueLitScaledRow(buffer, output + y0 * stride + col, yPixelCount, imageStride, atten, v0, vStep); - } - } - } - } - -} // TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/screenDraw.h b/components/darkforces/tfe/TFE_Jedi/Renderer/screenDraw.h deleted file mode 100644 index ca898a3c..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/screenDraw.h +++ /dev/null @@ -1,59 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Screen Line Drawing -////////////////////////////////////////////////////////////////////// -#include -#include -#include - -struct ScreenRect; -struct TextureData; - -namespace TFE_Jedi -{ - struct DrawRect - { - s32 x0; - s32 y0; - s32 x1; - s32 y1; - }; - - struct ScreenImage - { - s32 width; - s32 height; - u8* image; - JBool trans; - JBool columnOriented; - }; - - void screen_clear(); - void screen_enableGPU(bool enable); - void screenDraw_beginLines(u32 width, u32 height); - void screenDraw_endLines(); - void screenDraw_beginQuads(u32 width, u32 height); - void screenDraw_endQuads(); - - void screen_drawPoint(ScreenRect* rect, s32 x, s32 z, u8 color, u8* framebuffer); - void screen_drawLine(ScreenRect* rect, s32 x0, s32 z0, s32 x1, s32 z1, u8 color, u8* framebuffer); - void screen_drawCircle(ScreenRect* rect, s32 x, s32 z, s32 r, s32 stepAngle, u8 color, u8* framebuffer); - - JBool screen_clipLineToRect(ScreenRect* rect, s32* x0, s32* z0, s32* x1, s32* z1); - - void blitTextureToScreen(TextureData* texture, DrawRect* rect, s32 x0, s32 y0, u8* output, JBool forceTransparency=JFALSE, JBool forceOpaque=JFALSE); - void blitTextureToScreenLit(TextureData* texture, DrawRect* rect, s32 x0, s32 y0, const u8* atten, u8* output, JBool forceTransparency=JFALSE); - - // Scaled versions. - void blitTextureToScreenScaled(TextureData* texture, DrawRect* rect, s32 x0, s32 y0, fixed16_16 xScale, fixed16_16 yScale, u8* output, JBool forceTransparency = JFALSE); - void blitTextureToScreenScaledText(TextureData* texture, DrawRect* rect, s32 x0, s32 y0, fixed16_16 xScale, fixed16_16 yScale, u8* output, JBool forceTransparency = JFALSE); - void blitTextureToScreenLitScaled(TextureData* texture, DrawRect* rect, s32 x0, s32 y0, fixed16_16 xScale, fixed16_16 yScale, const u8* atten, u8* output, JBool forceTransparency = JFALSE); - - void blitTextureToScreen(ScreenImage* texture, DrawRect* rect, s32 x0, s32 y0, u8* output); - void blitTextureToScreenScaled(ScreenImage* texture, DrawRect* rect, s32 x0, s32 y0, fixed16_16 xScale, fixed16_16 yScale, u8* output); - void blitTextureToScreenLitScaled(ScreenImage* texture, DrawRect* rect, s32 x0, s32 y0, fixed16_16 xScale, fixed16_16 yScale, const u8* atten, u8* output); - - void blitTextureToScreenIScale(TextureData* texture, DrawRect* rect, s32 x0, s32 y0, s32 scale, u8* output); - - void screenDraw_setTransColor(u8 color); -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/textureInfo.h b/components/darkforces/tfe/TFE_Jedi/Renderer/textureInfo.h deleted file mode 100644 index 506662b0..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/textureInfo.h +++ /dev/null @@ -1,53 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Jedi Renderer -// Classic Dark Forces (DOS) Jedi derived renderer. -// -// Copyright note: -// While the project as a whole is licensed under GPL-2.0, some of the -// code under TFE_JediRenderer/ was derived from reverse-engineered -// code from "Dark Forces" (DOS) which is copyrighted by LucasArts. -// The original renderer is contained in RClassic_Fixed/ and the -// RClassic_Float/ and RClassic_GPU/ sub-renderers are derived from -// that code. -// -// I consider the reverse-engineering to be "Fair Use" - a means of -// supporting the games on other platforms and to improve support on -// existing platforms without claiming ownership of the games -// themselves or their IPs. -// -// That said using this code in a commercial project is risky without -// permission of the original copyright holders (LucasArts). -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include - -namespace TFE_Jedi -{ - // GPU renderer - enum TextureInfoType - { - TEXINFO_DF_TEXTURE_DATA = 0, - TEXINFO_DF_ANIM_TEX, - TEXINFO_DF_WAX_CELL, - TEXINFO_DF_DELT_TEX, - TEXINFO_COUNT - }; - - struct TextureInfo - { - TextureInfoType type; - union - { - TextureData* texData; - AnimatedTexture* animTex; - WaxFrame* frame; - }; - void* basePtr = nullptr; // used for WAX/Frame. - s32 sortKey = 0; // Calculated by Texture Packer. - }; - typedef std::vector TextureInfoList; - typedef bool(*TextureListCallback)(TextureInfoList& texList, AssetPool pool); -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/virtualFramebuffer.cpp b/components/darkforces/tfe/TFE_Jedi/Renderer/virtualFramebuffer.cpp deleted file mode 100644 index d0e10942..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/virtualFramebuffer.cpp +++ /dev/null @@ -1,310 +0,0 @@ -#include - -#include "virtualFramebuffer.h" -#include -#include -#include - -namespace TFE_Jedi -{ -#ifdef TFE_ESPBOX - // The platform supplies the 320x200 8-bit buffer (see vfb_setPlatformBuffer()). - static u8* s_frameBuffer320x200 = nullptr; -#else - static u8 s_frameBuffer320x200[320 * 200]; -#endif - static u8* s_frameBuffer = nullptr; - static u8* s_curFrameBuffer = nullptr; - - static u32 s_width = 0; - static u32 s_height = 0; - static u32 s_prevWidth = 0; - static u32 s_prevHeight = 0; - static s32 s_widescreenOffset = 0; - static bool s_widescreen = false; - -#ifdef TFE_ESPBOX - static u32* s_palette = nullptr; // 256 entries (shared memory) -#else - static u32 s_palette[256]; -#endif - - static fixed16_16 s_xScale = ONE_16; - static fixed16_16 s_yScale = ONE_16; - - static ScreenRect s_screenRect[VFB_RECT_COUNT]; - static ScreenRect s_screenPrev[VFB_RECT_COUNT]; - - static FramebufferMode s_mode = VFB_TEXTURE; - static FramebufferMode s_nextMode = VFB_TEXTURE; - - void vfb_createVirtualDisplay(u32 width, u32 height); - -#ifdef TFE_ESPBOX - void vfb_setPlatformBuffer(u8* buffer) - { - s_frameBuffer320x200 = buffer; - if (s_width == 320 && s_height == 200) - { - s_curFrameBuffer = buffer; - } - } - - void vfb_resetState() - { - s_width = 0; - s_height = 0; - s_curFrameBuffer = nullptr; - } -#endif - - //////////////////////////////////////////////////////////////////////// - // Setup - // ----------------- - // Note that the current graphics settings are - // used internally when setting up (GPU palette conversion,etc.) - //////////////////////////////////////////////////////////////////////// - JBool vfb_setResolution(u32 width, u32 height) - { - TFE_Settings_Graphics* graphics = TFE_Settings::getGraphicsSettings(); - if (width == s_width && height == s_height && s_widescreen == graphics->widescreen && s_mode == s_nextMode) - { - return JFALSE; - } - s_widescreen = graphics->widescreen; - s_mode = s_nextMode; - - if (width == 320 && height == 200) - { - s_width = width; - s_height = height; - - s_curFrameBuffer = s_frameBuffer320x200; - vfb_createVirtualDisplay(width, height); - - s_xScale = ONE_16; - s_yScale = ONE_16; - s_widescreenOffset = 0; - } - else - { - s_width = width; - s_height = height; - s_prevWidth = s_width; - s_prevHeight = s_height; - - free(s_frameBuffer); - s_frameBuffer = (u8*)malloc(s_width * s_height); - s_curFrameBuffer = s_frameBuffer; - - vfb_createVirtualDisplay(width, height); - - // Square or rectangular pixels? - if (s_height == 200 || s_height == 400) - { - // Rectangular pixels - s_yScale = div16(intToFixed16(s_height), intToFixed16(200)); - s_xScale = s_yScale; - - if (s_height == 200) - { - s_widescreenOffset = (s_width - 320) / 2; - } - else if (s_height == 400) - { - s_widescreenOffset = (s_width - 640) / 2; - } - } - else - { - // Square pixels - s_yScale = div16(intToFixed16(s_height), intToFixed16(200)); - // yScale / 1.2 - s_xScale = div16(s_yScale, 78643); - - s_widescreenOffset = max(0, ((s32)s_width - (s32)s_height*4/3) / 2); - } - } - memset(s_curFrameBuffer, 0, s_width * s_height); - - s_screenRect[VFB_RECT_UI] = - { - 0, - 0, - s32(s_width) - 1, - s32(s_height) - 1, - }; - - s_screenRect[VFB_RECT_RENDER] = - { - 0, - 1, - s32(s_width) - 1, - s32(s_height) - 2, - }; - - // Avoid flashing the previous buffer when swapping. - vfb_swap(); - vfb_swap(); - - return JTRUE; - } - - u32* vfb_getPalette() - { - return s_palette; - } - - void vfb_setPalette(const u32* palette) - { - memcpy(s_palette, palette, sizeof(u32) * 256); - TFE_RenderBackend::setPalette(palette); - } - - void vfb_setMode(FramebufferMode mode) - { - s_nextMode = mode; - } - - //////////////////////////// - // Get Scale Factors - //////////////////////////// - fixed16_16 vfb_getXScale() - { - return s_xScale; - } - - fixed16_16 vfb_getYScale() - { - return s_yScale; - } - - s32 vfb_getWidescreenOffset() - { - return s_widescreenOffset; - } - - void vfb_forceToBlack() - { - if (s_mode == VFB_TEXTURE) - { - memset(vfb_getCpuBuffer(), 0, s_width * s_height); - // Black for two frames. - vfb_swap(); - vfb_swap(); - } - else - { - f32 color[] = { 0.0f, 0.0f, 0.0f, 1.0f }; - TFE_RenderBackend::clearVirtualDisplay(color); - } - } - - void vfb_bindRenderTarget(bool clearColor) - { - TFE_RenderBackend::bindVirtualDisplay(); - - // For now, in the future disable again (but clear depth). - f32 color[] = { 0.0f, 0.0f, 0.0f, 1.0f }; - TFE_RenderBackend::clearVirtualDisplay(color, clearColor); - } - - void vfb_unbindRenderTarget() - { - TFE_RenderBackend::unbindRenderTarget(); - } - - //////////////////////////// - // Per-Frame - //////////////////////////// - // Frame rendering is done, copy the results to GPU memory. - void vfb_swap() - { - TFE_RenderBackend::updateVirtualDisplay(s_curFrameBuffer, s_width * s_height); - } - - //////////////////////////// - // Query - //////////////////////////// - // Get the CPU buffer for rendering. - u8* vfb_getCpuBuffer() - { - return s_curFrameBuffer; - } - - // Set the clip rect. - void vfb_setScreenRect(ScreenRectType type, ScreenRect* rect) - { - s_screenPrev[type] = s_screenRect[type]; - s_screenRect[type] = *rect; - } - - void vfb_restoreScreenRect(ScreenRectType type) - { - s_screenRect[type] = s_screenPrev[type]; - } - - // Get the valid screen rect for the current mode. - ScreenRect* vfb_getScreenRect(ScreenRectType type) - { - return &s_screenRect[type]; - } - - // Returns 'true' if using square pixels, otherwise 'false'. - void vfb_getResolution(u32* width, u32* height) - { - *width = s_width; - *height = s_height; - } - - // Returns the stride for rendering stride - u32 vfb_getStride() - { - return s_width; - } - - //////////////////////////// - // Internal - //////////////////////////// - void vfb_createVirtualDisplay(u32 width, u32 height) - { - // Setup or update the virtual display. - TFE_Settings_Graphics* graphics = TFE_Settings::getGraphicsSettings(); - u32 vdispFlags = 0; - if (graphics->asyncFramebuffer) - { - vdispFlags |= VDISP_ASYNC_FRAMEBUFFER; - } - if (graphics->gpuColorConvert) - { - vdispFlags |= VDISP_GPU_COLOR_CONVERT; - } - if (graphics->widescreen && (width != 320 || height != 200)) - { - vdispFlags |= VDISP_WIDESCREEN; - } - if (s_mode == VFB_RENDER_TRAGET) - { - vdispFlags |= VDISP_RENDER_TARGET; - } - - // TFE Specific: always use 320x200 when rendering in-game UI (for now). - VirtualDisplayInfo vdisp = - { - DMODE_ASPECT_CORRECT, // Output display mode. - vdispFlags, // See VirtualDisplayFlags. - - width, // full width - height, // full height - width, // width for 2D game UI and cutscenes. - height, // width for 3D drawing. - }; - TFE_RenderBackend::createVirtualDisplay(vdisp); - } -} // namespace TFE_Jedi -#ifdef TFE_ESPBOX -void espbox_shared_vfb(bool alloc) -{ - ESPBOX_SHARED_ALLOC(TFE_Jedi::s_palette, 256); -} -#endif diff --git a/components/darkforces/tfe/TFE_Jedi/Renderer/virtualFramebuffer.h b/components/darkforces/tfe/TFE_Jedi/Renderer/virtualFramebuffer.h deleted file mode 100644 index 8b6061ca..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Renderer/virtualFramebuffer.h +++ /dev/null @@ -1,86 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// This is TFE specific, but added to TFE_Jedi for convenience. -// -// Virtual Framebuffer wraps up the screen rect / resolution / virtual -// display handling together to make handling different resolutions in -// the Jedi Renderer and in-game easier. -////////////////////////////////////////////////////////////////////// -#include -#include - -struct ScreenRect -{ - s32 left; - s32 top; - s32 right; - s32 bot; -}; - -namespace TFE_Jedi -{ - enum ScreenRectType - { - VFB_RECT_RENDER = 0, - VFB_RECT_UI, - VFB_RECT_COUNT - }; - - enum FramebufferMode - { - VFB_UNSET = 0, - VFB_TEXTURE, - VFB_RENDER_TRAGET, - }; - - //////////////////////////////////////////////////////////////////////// - // Setup - // ----------------- - // Note that the current graphics settings are - // used internally when setting up (GPU palette conversion,etc.) - //////////////////////////////////////////////////////////////////////// - JBool vfb_setResolution(u32 width, u32 height); -#ifdef TFE_ESPBOX - // Platform supplied 320x200 8-bit framebuffer; must be set before vfb_setResolution(). - void vfb_setPlatformBuffer(u8* buffer); - // Forget the current resolution so the next vfb_setResolution() re-initializes. - void vfb_resetState(); -#endif - void vfb_setPalette(const u32* palette); - void vfb_setMode(FramebufferMode mode = VFB_TEXTURE); - u32* vfb_getPalette(); - - //////////////////////////// - // Get Scale Factors - //////////////////////////// - fixed16_16 vfb_getXScale(); - fixed16_16 vfb_getYScale(); - s32 vfb_getWidescreenOffset(); - - //////////////////////////// - // Per-Frame - //////////////////////////// - // Frame rendering is done, copy the results to GPU memory. - void vfb_swap(); - void vfb_forceToBlack(); - - void vfb_bindRenderTarget(bool clearColor = false); - void vfb_unbindRenderTarget(); - - //////////////////////////// - // Clipping - //////////////////////////// - void vfb_setScreenRect(ScreenRectType type, ScreenRect* rect); - void vfb_restoreScreenRect(ScreenRectType type); - - //////////////////////////// - // Query - //////////////////////////// - // Get the CPU buffer for rendering. - u8* vfb_getCpuBuffer(); - // Get the valid screen rect for the current mode. - ScreenRect* vfb_getScreenRect(ScreenRectType type); - void vfb_getResolution(u32* width, u32* height); - // Returns the stride for rendering stride - u32 vfb_getStride(); -} // namespace TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Serialization/serialization.cpp b/components/darkforces/tfe/TFE_Jedi/Serialization/serialization.cpp deleted file mode 100644 index b9a7acaf..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Serialization/serialization.cpp +++ /dev/null @@ -1,154 +0,0 @@ -#include - -#include "serialization.h" -#include -#include - -using namespace TFE_DarkForces; -using namespace TFE_Memory; - -namespace TFE_Jedi -{ - // Asset IDs from pool + index. - #define GEN_ID(index, pool) (index) | ((pool) << 24) - #define ID_GET_INDEX(id) ((id) & 0xffffff) - #define ID_GET_POOL(id) AssetPool((id) >> 24) - - u32 s_sVersion = 0; - SerializationMode s_sMode = SMODE_UNKNOWN; - - void serialization_serializeDfSound(Stream* stream, u32 version, SoundSourceId* id) - { - s32 soundDataId = -1; - if (s_sMode == SMODE_WRITE) - { - soundDataId = sound_getIndexFromId(*id); - } - SERIALIZE(version, soundDataId, -1); - if (s_sMode == SMODE_READ) - { - *id = (soundDataId < 0) ? NULL_SOUND : sound_getSoundFromIndex(soundDataId, false); - } - } - - void serialization_serializeSectorPtr(Stream* stream, u32 version, RSector*& sector) - { - s32 sectorIndex = -1; - if (s_sMode == SMODE_WRITE && sector) - { - sectorIndex = sector->index; - } - SERIALIZE(version, sectorIndex, -1); - assert(sectorIndex == -1 || (sectorIndex >= 0 && sectorIndex <= (s32)s_levelState.sectorCount)); - if (s_sMode == SMODE_READ) - { - if (sectorIndex == s_levelState.sectorCount) - { - sector = s_levelState.controlSector; - } - else - { - sector = sectorIndex < 0 ? nullptr : &s_levelState.sectors[sectorIndex]; - } - } - } - - void serialization_serializeAnimatedTexturePtr(Stream* stream, u32 version, AnimatedTexture*& animTex) - { - s32 index = -1; - if (s_sMode == SMODE_WRITE && animTex) - { - Allocator* animTexAlloc = bitmap_getAnimTextureAlloc(); - if (animTexAlloc) - { - index = allocator_getIndex(animTexAlloc, animTex); - } - } - SERIALIZE(version, index, -1); - if (s_sMode == SMODE_READ) - { - animTex = nullptr; - Allocator* animTexAlloc = bitmap_getAnimTextureAlloc(); - if (animTexAlloc && index >= 0) - { - animTex = (AnimatedTexture*)allocator_getByIndex(animTexAlloc, index); - } - } - } - - void serialization_serializeTexturePtr(Stream* stream, u32 version, TextureData*& texture) - { - s32 id = -1; - if (s_sMode == SMODE_WRITE && texture) - { - s32 index; - AssetPool pool; - if (bitmap_getTextureIndex(texture, &index, &pool)) - { - id = GEN_ID(index, pool); - } - } - SERIALIZE(version, id, -1); - if (s_sMode == SMODE_READ) - { - texture = (id < 0) ? nullptr : bitmap_getTextureByIndex(ID_GET_INDEX(id), ID_GET_POOL(id)); - } - } - - void serialization_serialize3doPtr(Stream* stream, u32 version, JediModel*& model) - { - s32 id = -1; - if (s_sMode == SMODE_WRITE && model) - { - s32 index; - AssetPool pool; - if (TFE_Model_Jedi::getModelIndex(model, &index, &pool)) - { - id = GEN_ID(index, pool); - } - } - SERIALIZE(version, id, -1); - if (s_sMode == SMODE_READ) - { - model = (id < 0) ? nullptr : TFE_Model_Jedi::getModelByIndex(ID_GET_INDEX(id), ID_GET_POOL(id)); - } - } - - void serialization_serializeWaxPtr(Stream* stream, u32 version, JediWax*& wax) - { - s32 id = -1; - if (s_sMode == SMODE_WRITE && wax) - { - s32 index; - AssetPool pool; - if (TFE_Sprite_Jedi::getWaxIndex(wax, &index, &pool)) - { - id = GEN_ID(index, pool); - } - } - SERIALIZE(version, id, -1); - if (s_sMode == SMODE_READ) - { - wax = (id < 0) ? nullptr : TFE_Sprite_Jedi::getWaxByIndex(ID_GET_INDEX(id), ID_GET_POOL(id)); - } - } - - void serialization_serializeFramePtr(Stream* stream, u32 version, JediFrame*& frame) - { - s32 id = -1; - if (s_sMode == SMODE_WRITE && frame) - { - s32 index; - AssetPool pool; - if (TFE_Sprite_Jedi::getFrameIndex(frame, &index, &pool)) - { - id = GEN_ID(index, pool); - } - } - SERIALIZE(version, id, -1); - if (s_sMode == SMODE_READ) - { - frame = (id < 0) ? nullptr : TFE_Sprite_Jedi::getFrameByIndex(ID_GET_INDEX(id), ID_GET_POOL(id)); - } - } -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Serialization/serialization.h b/components/darkforces/tfe/TFE_Jedi/Serialization/serialization.h deleted file mode 100644 index e3027707..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Serialization/serialization.h +++ /dev/null @@ -1,78 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Serialization -// This was added for TFE and is not directly based on -// reverse-engineered code. However, it was built to handle JEDI and -// Dark Forces types. -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include - -struct AnimatedTexture; - -namespace TFE_Jedi -{ - enum SaveVersion : u32 - { - SaveVersionInit = 1, - SaveVersionCur = SaveVersionInit, - }; - - enum SerializationMode - { - SMODE_WRITE = 0, - SMODE_READ, - SMODE_UNKNOWN, - }; - - extern u32 s_sVersion; - extern SerializationMode s_sMode; - - // This will generate an signed 32-bit index from a pointer, given a base pointer (start of an array, for example) and size of each element. - // Note this will produce invalid results if index > INT_MAX (~2 billion). - #define PTR_INDEX_S32(ptr, base, stride) s32((std::ptrdiff_t(ptr) - std::ptrdiff_t(base)) / stride) - #define INDEX_PTR_S32(index, base, stride) ((u8*)base + index * stride) - - #define SERIALIZE_VERSION(curVer) \ - { \ - u32 ver = curVer; \ - if (s_sMode == SMODE_WRITE) { stream->writeBuffer(&ver, sizeof(ver)); } \ - else if (s_sMode == SMODE_READ) { stream->readBuffer(&ver, sizeof(ver)); } \ - serialization_setVersion(ver); \ - } - - #define SERIALIZE(v, x, def) \ - if (s_sMode == SMODE_WRITE && s_sVersion >= v) { stream->writeBuffer(&x, sizeof(x)); } \ - else if (s_sMode == SMODE_READ) \ - { \ - if (s_sVersion >= v) { stream->readBuffer(&x, sizeof(x)); } \ - else { x = def; } \ - } - #define SERIALIZE_BUF(v, x, s) if (s_sMode == SMODE_WRITE && s_sVersion >= v) { stream->writeBuffer(x, s); } \ - else if (s_sMode == SMODE_READ) \ - { \ - if (s_sVersion >= v) { stream->readBuffer(x, s); } \ - else { memset(x, 0, s); } \ - } - - // Discard values that were previously added. This might mean skipping over data in the stream and ignoring it. - // This is done by advancing the stream by the size of the type or buffer. - // v0 = version added, v1 = version removed. - #define SERIALIZE_DISCARD(v0, v1, type) if (s_sVersion >= v0 && s_sVersion < v1 && s_sMode == SMODE_READ) { stream->seek(sizeof(type), ORIGIN_CURRENT); } - #define SERIALIZE_BUF_DISCARD(v0, v1, s) if (s_sVersion >= v0 && s_sVersion < v1 && s_sMode == SMODE_READ) { stream->seek(s, ORIGIN_CURRENT); } - - inline void serialization_setVersion(u32 version) { s_sVersion = version; } - inline void serialization_setMode(SerializationMode mode) { s_sMode = mode; } - inline SerializationMode serialization_getMode() { return s_sMode; } - - void serialization_serializeDfSound(Stream* stream, u32 version, SoundSourceId* id); - void serialization_serializeSectorPtr(Stream* stream, u32 version, RSector*& sector); - void serialization_serializeAnimatedTexturePtr(Stream* stream, u32 version, AnimatedTexture*& animTex); - void serialization_serializeTexturePtr(Stream* stream, u32 version, TextureData*& texture); - void serialization_serialize3doPtr(Stream* stream, u32 version, JediModel*& model); - void serialization_serializeWaxPtr(Stream* stream, u32 version, JediWax*& wax); - void serialization_serializeFramePtr(Stream* stream, u32 version, JediFrame*& frame); -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Task/task.cpp b/components/darkforces/tfe/TFE_Jedi/Task/task.cpp deleted file mode 100644 index 56e5ba6a..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Task/task.cpp +++ /dev/null @@ -1,712 +0,0 @@ -#include - -#include "task.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace TFE_DarkForces; -using namespace TFE_Memory; - -// #define TASK_DEBUG 1 - -enum TaskConstants -{ - TASK_MAX_LEVELS = 16, // Maximum number of recursion levels. - TASK_INIT_LEVEL = -1, -}; - -struct TaskContext -{ - s32 ip[TASK_MAX_LEVELS]; // Current instruction pointer (IP) for each level of recursion. - TaskFunc callstack[TASK_MAX_LEVELS]; // Funcion pointer for each level of recursion. - - u8* stackMem; // starts out null, can point to the block if ever needed. - u32 stackOffset; // where in the stack we are. - - u8* stackPtr[TASK_MAX_LEVELS]; - u32 stackSize[TASK_MAX_LEVELS]; - u8 delayedCall[TASK_MAX_LEVELS]; - - s32 level; - s32 callLevel; -}; - -#ifdef TASK_DEBUG -#define TASK_MSG(...) TFE_System::logWrite(LOG_MSG, "TASK", __VA_ARGS__) -#else -#define TASK_MSG(...) -#endif - -struct Task -{ - char name[32]; - - Task* prev; - Task* next; - Task* subtaskNext; - Task* subtaskParent; // For secondary tasks, this is the parent they are attached to. - Task* retTask; // Task to return to once this one is completed or paused. - void* userData; - JBool framebreak; // JTRUE if the task loop should end after this task. - - // Used in place of stack memory. - TaskContext context; - TaskFunc localRunFunc; - - // Timing. - Tick nextTick; -}; - -namespace TFE_Jedi -{ - enum - { - TASK_CHUNK_SIZE = 256, - TASK_PREALLOCATED_CHUNKS = 1, - -#ifdef TFE_ESPBOX - TASK_STACK_SIZE = 8 * 1024, // 8KB of (local context) stack memory per task. - TASK_STACK_CHUNK_SIZE = 16, // 128KB of memory per chunk of 16 tasks with stack memory. -#else - TASK_STACK_SIZE = 32 * 1024, // 32KB of stack memory. - TASK_STACK_CHUNK_SIZE = 64, // 2MB of memory for 64 tasks with stack memory. -#endif - }; - - ChunkedArray* s_tasks = nullptr; - ChunkedArray* s_stackBlocks = nullptr; - s32 s_taskCount = 0; - - Task s_rootTask; - Task* s_taskIter = nullptr; - Task* s_curTask = nullptr; - MessageType s_currentMsg = MSG_FREE_TASK; - - TaskContext* s_curContext = nullptr; - - static f64 s_prevTime = 0.0; - static f64 s_minIntervalInSec = 0.0; - static s32 s_frameActiveTaskCount = 0; - static JBool s_taskSystemPaused = JFALSE; - static bool s_enableTimeLimiter = true; - static Task* s_taskPauseTask = nullptr; - - void selectNextTask(); - - void createRootTask() - { - s_tasks = createChunkedArray(sizeof(Task), TASK_CHUNK_SIZE, TASK_PREALLOCATED_CHUNKS, s_gameRegion); - s_stackBlocks = createChunkedArray(TASK_STACK_SIZE, TASK_STACK_CHUNK_SIZE, TASK_PREALLOCATED_CHUNKS, s_gameRegion); - - s_rootTask = { 0 }; - s_rootTask.prev = &s_rootTask; - s_rootTask.next = &s_rootTask; - s_rootTask.nextTick = TASK_SLEEP; - - s_taskIter = &s_rootTask; - s_curTask = &s_rootTask; - s_taskCount = 0; - s_frameActiveTaskCount = 0; - - CVAR_BOOL(s_enableTimeLimiter, "d_enableTaskTimeLimiter", CVFLAG_DO_NOT_SERIALIZE, "Enable the task time limiter."); - } - - Task* createSubTask(const char* name, TaskFunc func, TaskFunc localRunFunc) - { - if (!s_tasks) - { - createRootTask(); - } - - Task* newTask = (Task*)allocFromChunkedArray(s_tasks); - assert(newTask); - - s_taskCount++; - strcpy(newTask->name, name); - - // Insert newTask at the head of the subtask list in the current "mainline" task. - newTask->next = s_curTask->subtaskNext; - newTask->prev = nullptr; - if (s_curTask->subtaskNext) - { - s_curTask->subtaskNext->prev = newTask; - } - s_curTask->subtaskNext = newTask; - - // The subtask parent is the current task. - newTask->subtaskParent = s_curTask; - // This task has no subtasks. - newTask->subtaskNext = nullptr; - newTask->retTask = nullptr; - newTask->userData = nullptr; - newTask->framebreak = JFALSE; - - newTask->nextTick = 0; - - newTask->context = { 0 }; - newTask->context.callstack[0] = func; - newTask->localRunFunc = localRunFunc; - newTask->context.level = TASK_INIT_LEVEL; - return newTask; - } - - Task* createTask(const char* name, TaskFunc func, JBool framebreak, TaskFunc localRunFunc) - { - if (!s_tasks) - { - createRootTask(); - } - - Task* newTask = (Task*)allocFromChunkedArray(s_tasks); - assert(newTask); - - s_taskCount++; - // Insert the task after 's_taskIter' - strcpy(newTask->name, name); - newTask->next = s_taskIter->next; - // This was missing? - if (s_taskIter->next) - { - s_taskIter->next->prev = newTask; - } - newTask->prev = s_taskIter; - s_taskIter->next = newTask; - - newTask->subtaskNext = nullptr; - newTask->subtaskParent = nullptr; - newTask->retTask = nullptr; - newTask->userData = nullptr; - newTask->framebreak = framebreak; - - newTask->context = { 0 }; - newTask->context.callstack[0] = func; - newTask->localRunFunc = localRunFunc; - newTask->context.level = TASK_INIT_LEVEL; - newTask->nextTick = s_curTick; - - return newTask; - } - - void task_serializeState(Stream* stream, Task* task, void* userData, LocalMemorySerCallback localMemCallback) - { - SERIALIZE(SaveVersionInit, task->context.ip[0], 0); - SERIALIZE(SaveVersionInit, task->context.stackSize[0], 0); - SERIALIZE(SaveVersionInit, task->nextTick, 0); - if (serialization_getMode() == SMODE_READ && !task->context.stackMem) - { - task->context.stackMem = (u8*)allocFromChunkedArray(s_stackBlocks); - memset(task->context.stackMem, 0, sizeof(u32) * TASK_MAX_LEVELS); - task->context.stackOffset = 0; - task->context.stackPtr[0] = task->context.stackMem; - } - SERIALIZE(SaveVersionInit, task->context.stackOffset, 0); - if (localMemCallback) - { - localMemCallback(stream, userData, task->context.stackPtr[0]); - } - else - { - // This only works with relocatable state. - SERIALIZE_BUF(SaveVersionInit, task->context.stackPtr[0], task->context.stackSize[0]); - } - } - - Task* task_getCurrent() - { - return s_curTask; - } - - void task_pause(JBool pause, Task* pauseRunTask) - { - s_taskSystemPaused = pause; - s_taskPauseTask = pauseRunTask; - } - - void task_free(Task* task) - { - // Select the next task before deletion (to avoid executing the same task again). - if (task == s_curTask) - { - selectNextTask(); - } - // Then remove the task. - if (task->prev) - { - task->prev->next = task->next; - } - if (task->next) - { - task->next->prev = task->prev; - } - // Handle deleting sub-tasks. - if (task->subtaskNext) - { - // Should we free subtasks? - assert(0); - } - // If this task was the subtaskNext, then move the next subtask into that role. - Task* parent = task->subtaskParent; - if (parent && parent->subtaskNext == task) - { - parent->subtaskNext = task->next; - } - - // Free any memory allocated for the local context. - freeToChunkedArray(s_stackBlocks, task->context.stackMem); - // Finally free the task itself from the chunked array. - freeToChunkedArray(s_tasks, task); - s_taskCount--; - } - - void task_reset() - { - s_rootTask = { 0 }; - s_rootTask.prev = &s_rootTask; - s_rootTask.next = &s_rootTask; - s_rootTask.nextTick = TASK_SLEEP; - - s_taskIter = &s_rootTask; - s_curTask = &s_rootTask; - s_taskCount = 0; - s_frameActiveTaskCount = 0; - - s_taskSystemPaused = JFALSE; - s_taskPauseTask = nullptr; - } - - void task_freeAll() - { - chunkedArrayClear(s_tasks); - chunkedArrayClear(s_stackBlocks); - - s_curTask = nullptr; - s_curContext = nullptr; - s_taskCount = 0; - } - - void task_shutdown() - { - freeChunkedArray(s_tasks); - freeChunkedArray(s_stackBlocks); - - s_curTask = nullptr; - s_taskIter = nullptr; - s_tasks = nullptr; - s_stackBlocks = nullptr; - s_curContext = nullptr; - s_taskCount = 0; - - s_prevTime = 0.0; - s_minIntervalInSec = 0.0; - s_frameActiveTaskCount = 0; - s_taskSystemPaused = JFALSE; - s_taskPauseTask = nullptr; - } - - void task_makeActive(Task* task) - { - task->nextTick = 0; - } - - void task_setNextTick(Task* task, Tick tick) - { - task->nextTick = tick; - } - - void task_setUserData(Task* task, void* data) - { - if (!task) { return; } - task->userData = data; - } - - void* task_getUserData() - { - return s_curTask ? s_curTask->userData : nullptr; - } - - const char* task_getName(Task* task) - { - return task->name; - } - - void task_setMessage(MessageType msg) - { - s_currentMsg = msg; - } - - void task_runLocal(Task* task, MessageType msg) - { - if (task->localRunFunc) - { - Task* prevCur = s_curTask; - s_curTask = task; - - task->localRunFunc(msg); - - s_curTask = prevCur; - } - } - - bool task_hasLocalMsgFunc(Task* task) - { - return task->localRunFunc != nullptr; - } - - void ctxReturn() - { - TASK_MSG("Return from function, task: '%s'.", s_curTask->name); - - s32 level = 0; - if (s_curContext) - { - level = s_curContext->level; - assert(s_curContext->level >= 0 && s_curContext->level < TASK_MAX_LEVELS); - if (level <= 0 || !s_curContext->delayedCall[level-1]) - { - s_curContext->level--; - } - else - { - // We need to reduce by 2 levels since a delayed call does not immediately return to the calling function. - s_curContext->level -= 2; - } - assert(s_curContext->level >= -1 && s_curContext->level < TASK_MAX_LEVELS); - - if (s_curContext->callLevel > 0) { s_curContext->callLevel--; } - } - - if (level == 0 && s_curTask) - { - task_free(s_curTask); - } - else if (s_curContext && s_curContext->stackPtr[level]) - { - // Return the stack memory allocated for this level. - s_curContext->stackOffset -= s_curContext->stackSize[level]; - assert(s_curContext->stackOffset >= 0 && s_curContext->stackOffset < TASK_STACK_SIZE); - s_curContext->stackPtr[level] = nullptr; - s_curContext->stackSize[level] = 0; - } - } - - void selectNextTask() - { - // Find the next task to run. - Task* task = s_curTask; - while (1) - { - ////////////////////////////////////////////////////////////////////////////////////////// - // Execution: - // * Go to the next task - // * Check to see if there are sub-tasks - // * If so, the assign current to the sub-task. - // * Execute the task. - // * Once we are on the last sub-task, then go back to the parent. - // * Once the parent executes, then we move on to parent->next and start all over. - if (task->next) - { - // Move the to the next task. - task = task->next; - // If the task has sub-tasks, loop until we find the last one. - // This is usually only one deep. - while (task->subtaskNext) - { - task = task->subtaskNext; - } - // Then execute the task. - if (task->nextTick <= s_curTick || task->framebreak) - { - s_currentMsg = MSG_RUN_TASK; - s_curTask = task; - return; - } - } - else if (task->subtaskParent) - { - // Otherwise, try to execute the parent. - task = task->subtaskParent; - if (task->nextTick <= s_curTick || task->framebreak) - { - s_currentMsg = MSG_RUN_TASK; - s_curTask = task; - return; - } - } - else - { - break; - } - } - - // If no selection is possible, assign the first task. - if (!s_curTask && s_taskCount) - { - s_curTask = (Task*)chunkedArrayGet(s_tasks, 0); - } - } - - void itask_run(Task* task, MessageType msg) - { - Task* retTask = s_curTask; - - task->retTask = s_curTask; - s_currentMsg = msg; - s_curTask = task; - - TASK_MSG("Run task '%s' with msg: '%d'.", task->name, s_currentMsg); - s_curContext = &s_curTask->context; - s32 level = max(0, s_curContext->level + 1); - TaskFunc runFunc = s_curContext->callstack[level]; - assert(runFunc); - if (runFunc) - { - runFunc(s_currentMsg); - } - if (retTask != s_curTask) - { - TFE_System::logWrite(LOG_WARNING, "Task", "Correction required upon returning for task_runAndReturn."); - s_curTask = retTask; - s_curContext = &s_curTask->context; - } - TASK_MSG("Return to task '%s'.", s_curTask->name); - } - - void itask_yield(Tick delay, s32 ip) - { - // This is caused by a bug in a mod. - // TODO: Figure out the root cause. - if (s_curContext != &s_curTask->context) - { - s_curContext = &s_curTask->context; - } - - // Copy the ip so we know where to return. - assert(s_curContext->level >= 0 && s_curContext->level < TASK_MAX_LEVELS); - s_curContext->ip[s_curContext->level] = ip; - s_curContext->level--; - - TASK_MSG("Task yield: '%s' for %u ticks", s_curTask->name, delay); - - // If there is a return task, then take it next. - if (s_curTask->retTask) - { - // Clear out the return task once it is executed. - Task* retTask = s_curTask->retTask; - s_curTask->retTask = nullptr; - - // Set the next task. - s_currentMsg = MSG_RUN_TASK; - s_curTask = retTask; - s_curContext = &s_curTask->context; - - TASK_MSG("Return Task: '%s'", s_curTask->name); - return; - } - - // Update the current tick based on the delay. - s_curTask->nextTick = (delay < TASK_SLEEP) ? s_curTick + delay : delay; - - // Find the next task to run. - selectNextTask(); - assert(s_curTask); - TASK_MSG("Task Selected: '%s'", s_curTask->name); - } - - void task_setMinStepInterval(f64 minIntervalInSec) - { - s_prevTime = TFE_System::getTime(); - s_minIntervalInSec = minIntervalInSec; - } - - JBool task_canRun() - { - if (s_taskCount && s_enableTimeLimiter) - { - const f64 time = TFE_System::getTime(); - if (time - s_prevTime < s_minIntervalInSec) - { - return JFALSE; - } - } - return JTRUE; - } - - void task_updateTime() - { - s_prevTime = TFE_System::getTime(); - } - - // Called once per frame to run all of the tasks. - // Returns JFALSE if it cannot be run due to the time interval. - JBool task_run() - { - if (!s_taskCount) - { - return JTRUE; - } - TFE_ZONE("Task System"); - - // Limit the update rate by the minimum interval. - // Dark Forces uses discrete 'ticks' to track time and the game behavior is very odd with 0 tick frames. - const f64 time = TFE_System::getTime(); - if (time - s_prevTime < s_minIntervalInSec) - { - return JFALSE; - } - s_prevTime = time; - s_currentMsg = MSG_RUN_TASK; - s_frameActiveTaskCount = 0; - - // Return if the task system is paused. - if (s_taskSystemPaused) - { - if (s_taskPauseTask) - { - s_curTask = s_taskPauseTask; - if (s_curTask->nextTick <= s_curTick) - { - s_frameActiveTaskCount++; - - s_curContext = &s_curTask->context; - s32 level = max(0, s_curContext->level + 1); - TaskFunc runFunc = s_curContext->callstack[level]; - assert(runFunc); - - if (runFunc) - { - runFunc(s_currentMsg); - } - } - } - return JTRUE; - } - - // Keep processing tasks until the "framebreak" task is hit. - // Once the framebreak task completes (if it is not sleeping), then break out of the loop - processing will resume - // on the next task on the next frame. - // Note: the original code just loop here forever, but we break it up between frames to play nice with modern operating systems. - while (s_curTask) - { - TASK_MSG("Current Task: '%s'.", s_curTask->name); - JBool framebreak = s_curTask->framebreak; - - // This should only be false when hitting the "framebreak" task which is sleeping. - if (s_curTask->nextTick <= s_curTick) - { - s_frameActiveTaskCount++; - - s_curContext = &s_curTask->context; - s32 level = max(0, s_curContext->level + 1); - TaskFunc runFunc = s_curContext->callstack[level]; - assert(runFunc); - - if (runFunc) - { - runFunc(s_currentMsg); - } - } - else - { - selectNextTask(); - } - - if (framebreak) - { - break; - } - } - return JTRUE; - } - - void task_setDefaults() - { - s_curTask = &s_rootTask; - s_taskIter = &s_rootTask; - - TFE_COUNTER(s_taskCount, "Task Count"); - TFE_COUNTER(s_frameActiveTaskCount, "Active Tasks"); - } - - s32 task_getCount() - { - return s_taskCount; - } - - s32 ctxGetIP() - { - assert(s_curContext->level >= 0 && s_curContext->level < TASK_MAX_LEVELS); - return s_curContext->ip[s_curContext->level]; - } - - void ctxAllocate(u32 size) - { - if (!size) { return; } - if (!s_curContext->stackMem) - { - s_curContext->stackMem = (u8*)allocFromChunkedArray(s_stackBlocks); - memset(s_curContext->stackSize, 0, sizeof(u32) * TASK_MAX_LEVELS); - s_curContext->stackOffset = 0; - } - - s32 level = s_curContext->level; - if (!s_curContext->stackPtr[level]) - { - s_curContext->stackPtr[level] = s_curContext->stackMem + s_curContext->stackOffset; - s_curContext->stackSize[level] = size; - s_curContext->stackOffset += size; - assert(s_curContext->stackOffset >= 0 && s_curContext->stackOffset < TASK_STACK_SIZE); - - // Clear out the memory. - memset(s_curContext->stackPtr[level], 0, size); - } - } - - void* ctxGet() - { - return s_curContext->stackPtr[s_curContext->level]; - } - - void ctxBegin() - { - s_curContext->level++; - } - - // Direct calls from a task are a bit complicated, especially when those calls can yield. - // This task needs to track the current IP at the calling level so it can be resumed when the new function returns. - // In addition, we must detect when the return is delayed - due to a yield in the called function - - // so that the recursion level is properly handled on delayed return. - bool ctxCall(TaskFunc func, MessageType msg, s32 ip, const char* funcName) - { - TASK_MSG("Call Function: '%s', %d.", funcName, msg); - - assert(s_curContext->level >= 0 && s_curContext->level + 1 < TASK_MAX_LEVELS); - TaskContext* startContext = s_curContext; - if (s_curContext->level == 0) - { - s_curContext->callLevel = 0; - } - s32 startLevel = s_curContext->level; - s32 startCallLevel = s_curContext->callLevel; - startContext->delayedCall[startLevel] = 0; - s_curContext->callLevel++; - - s_curContext->ip[s_curContext->level] = ip; - s_curContext->callstack[s_curContext->level + 1] = func; - s_curContext->ip[s_curContext->level + 1] = 0; - func(msg); - - if (startCallLevel != startContext->callLevel) - { - startContext->delayedCall[startLevel] = 1; - } - return startCallLevel != startContext->callLevel; - } -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Jedi/Task/task.h b/components/darkforces/tfe/TFE_Jedi/Task/task.h deleted file mode 100644 index defc4c20..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Task/task.h +++ /dev/null @@ -1,103 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Task -// Basic "Task" system based on Dark Forces DOS. -// However - this code is greatly simplified, pushing some of the -// complexity to the task functions. -// The original code used a "coroutine" like task system (similar to -// fibers) - which adds a lot of unrequired complexity (saving stack -// state, yield, delays, etc.). -// -// The TFE version simplifies the system. -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include - -struct Task; -#include "taskMacros.h" - -enum TaskDelay -{ - TASK_SLEEP = 0xffffffff, - TASK_NO_DELAY = 0, -}; -typedef void(*LocalMemorySerCallback)(Stream* stream, void* userData, void* mem); - -//////////////////////////////////////////////////////////////////////// -// Task System API -namespace TFE_Jedi -{ - // Create a "main" task. Generally, main tasks are executed in the order created. - Task* createTask(const char* name, TaskFunc func, JBool framebreak = JFALSE, TaskFunc localRunFunc = nullptr); - // Create a "subtask" under the current task. All sub-tasks under a main task are executed *before* that main task. - Task* createSubTask(const char* name, TaskFunc func, TaskFunc localRunFunc = nullptr); - - // Serialize task state, such as local memory. - // This currently assumes "simple" use cases - it does not unwind recursions yet. - // On load, the task should be created as normal first and then have its state serialized. - // If local task function state includes pointers or other non-pod data, a local memory serialization callback - // needs to be provided and the state be properly serialized by the client. The callback should properly handle - // both saving and loading. See vueLogic_serializeTaskLocalMemory() in TFE_DarkForces/vueLogic.cpp for an example. - void task_serializeState(Stream* stream, Task* task, void* userData = nullptr, LocalMemorySerCallback localMemCallback = nullptr); - - Task* task_getCurrent(); - - void task_pause(JBool pause, Task* pauseRunTask = nullptr); - void task_free(Task* task); - void task_freeAll(); - void task_reset(); - void task_shutdown(); - - void task_makeActive(Task* task); - void task_setNextTick(Task* task, Tick tick); - void task_setUserData(Task* task, void* data); - void task_setMessage(MessageType msg); - void* task_getUserData(); - - const char* task_getName(Task* task); - - void task_runLocal(Task* task, MessageType msg); - bool task_hasLocalMsgFunc(Task* task); - - // Call once per frame to run the tasks. - // The core idea is to split the original recursive tasks into - // an iterative loop that can be called into every frame. - // This interacts better with modern systems, such as Windows. - // Another option is to run the game and rendering loop in its own - // thread and then blit the results in the main thread. - // Returns false if tasks cannot be run due to the time interval. - JBool task_run(); - JBool task_canRun(); - void task_setDefaults(); - void task_setMinStepInterval(f64 minIntervalInSec); - - void task_updateTime(); - s32 task_getCount(); -} -//////////////////////////////////////////////////////////////////////// -// Task Function API: -// -// task_begin / task_begin_ctx -// This must be called at the top of the function -// after the LocalContext definition. -// Use task_begin_ctx if persistant local variables -// are required, otherwise use task_begin -// -// task_end -// This must be called at the end of the function. -// Once called, the task will be deleted and removed. -// -// task_yield(delay) -// Call to return from the function and resume later: -// TASK_NO_DELAY - next frame. -// TASK_SLEEP - put to sleep until task_makeActive() is called -// Other - the delay in ticks before the function is resumed. -// -// taskCtx -// Access to the persistant local variables, as defined by the -// LocalContext struct before task_begin_ctx is called. -// Example: taskCtx->i, for struct LocalContext { s32 i; } -//////////////////////////////////////////////////////////////////////// diff --git a/components/darkforces/tfe/TFE_Jedi/Task/taskMacros.h b/components/darkforces/tfe/TFE_Jedi/Task/taskMacros.h deleted file mode 100644 index 10af85c8..00000000 --- a/components/darkforces/tfe/TFE_Jedi/Task/taskMacros.h +++ /dev/null @@ -1,72 +0,0 @@ -#pragma once - -#ifndef __FUNCTION__ - #ifndef _WIN32 //*NIX - #define __FUNCTION__ __func__ - #endif -#endif - -#define task_begin \ - ctxBegin(); \ - switch (ctxGetIP()) \ - { \ - case 0: - -#define task_begin_ctx \ - ctxBegin(); \ - ctxAllocate(sizeof(LocalContext)); \ - switch (ctxGetIP()) \ - { \ - case 0: - -#define task_end \ - } \ - ctxReturn(); - -#define task_yield(delay) \ - do { itask_yield(delay, __LINE__); \ - return; \ - case __LINE__:; \ - } while (0) - -#define task_runAndReturn(task, msg) \ - itask_run(task, msg) - -#define task_callTaskFunc(func) \ - do { if (ctxCall(func, msg, __LINE__, __FUNCTION__)) { return; } \ - case __LINE__:; \ - } while (0) - -#define task_callTaskFuncWithMsg(func, newId) \ - do { if (ctxCall(func, newId, __LINE__, __FUNCTION__)) { return; } \ - case __LINE__:; \ - } while (0) - -#define taskCtx ((LocalContext*)ctxGet()) -#define local(x) ((LocalContext*)ctxGet())->x - -#define task_waitWhileIdNotZero(ticks) \ - do \ - { \ - task_yield(ticks); \ - } while (msg != MSG_RUN_TASK) - -#define task_localBlockBegin { -#define task_localBlockEnd } - -namespace TFE_Jedi -{ - typedef void(*TaskFunc)(MessageType msg); - - ////////////////////////////////////////// - // Internal functions used by macros. - ////////////////////////////////////////// - s32 ctxGetIP(); - void ctxAllocate(u32 size); - void* ctxGet(); - void ctxBegin(); - bool ctxCall(TaskFunc func, MessageType msg, s32 ip, const char* funcName); - void ctxReturn(); - void itask_yield(Tick delay, s32 ip); - void itask_run(Task* task, MessageType msg); -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Memory/chunkedArray.cpp b/components/darkforces/tfe/TFE_Memory/chunkedArray.cpp deleted file mode 100644 index 330069e1..00000000 --- a/components/darkforces/tfe/TFE_Memory/chunkedArray.cpp +++ /dev/null @@ -1,245 +0,0 @@ -#include - -#include "chunkedArray.h" -#include -#include -#include -#include -#include -#include -#include - -// Uncomment the following line to verify memory on free. -#ifdef _DEBUG -#define _VERIFY_CHUNKED_ARR_FREE 1 -#endif - -struct ChunkedArray -{ - u32 elemSize; // size of an element. - u32 elemPerChunk; // number of elements. - - u32 elemCount; // number of elements. - u32 chunkCount; // capacity. - - u32 freeSlotCount; - u32 freeSlotCapacity; - - u8** chunks; - u8** freeSlots; - MemoryRegion* region; -}; - -namespace TFE_Memory -{ - enum - { - FREE_SLOT_STEP = 32, - }; - void addFreeSlot(ChunkedArray* arr, u8* ptr); - - void serialize(ChunkedArray* arr, FileStream* file) - { - assert(file); - size_t size = size_t(&arr->chunks) - sizeof(arr); - file->writeBuffer(arr, (u32)size); - - const u32 chunkAllocSize = arr->elemPerChunk * arr->elemSize; - for (u32 i = 0; i < arr->chunkCount; i++) - { - file->write(arr->chunks[i], chunkAllocSize); - } - - for (u32 i = 0; i < arr->freeSlotCount; i++) - { - s32 freeSlotIndex = getSlotIndex(arr, arr->freeSlots[i]); - file->write(&freeSlotIndex); - } - } - - ChunkedArray* restore(FileStream* file, MemoryRegion* region) - { - assert(file && region); - ChunkedArray* arr = (ChunkedArray*)region_alloc(region, sizeof(ChunkedArray)); - memset(arr, 0, sizeof(ChunkedArray)); - - size_t size = size_t(&arr->chunks) - sizeof(arr); - file->readBuffer(arr, (u32)size); - - arr->chunks = (u8**)region_realloc(region, arr->chunks, sizeof(u8*) * arr->chunkCount); - const u32 chunkAllocSize = arr->elemPerChunk * arr->elemSize; - for (u32 i = 0; i < arr->chunkCount; i++) - { - arr->chunks[i] = (u8*)region_alloc(region, chunkAllocSize); - file->read(arr->chunks[i], chunkAllocSize); - } - - arr->freeSlots = (u8**)region_realloc(region, arr->freeSlots, sizeof(u8**) * arr->freeSlotCapacity); - for (u32 i = 0; i < arr->freeSlotCount; i++) - { - s32 freeSlotIndex; - file->read(&freeSlotIndex); - if (freeSlotIndex >= 0) - { - arr->freeSlots[i] = arr->chunks[freeSlotIndex]; - } - else - { - arr->freeSlots[i] = nullptr; - } - } - return arr; - } - - ChunkedArray* createChunkedArray(u32 elemSize, u32 elemPerChunk, u32 initChunkCount, MemoryRegion* region) - { - ChunkedArray* arr = (ChunkedArray*)region_alloc(region, sizeof(ChunkedArray)); - memset(arr, 0, sizeof(ChunkedArray)); - - arr->region = region; - arr->elemSize = elemSize; - arr->elemCount = 0; - - arr->elemPerChunk = elemPerChunk; - arr->chunkCount = initChunkCount; - arr->chunks = (u8**)region_realloc(region, arr->chunks, sizeof(u8*) * initChunkCount); - - arr->freeSlotCount = 0; - arr->freeSlotCapacity = 0; - arr->freeSlots = nullptr; - - const u32 chunkAllocSize = elemPerChunk * elemSize; - for (u32 i = 0; i < initChunkCount; i++) - { - arr->chunks[i] = (u8*)region_alloc(region, chunkAllocSize); - } - - return arr; - } - - void freeChunkedArray(ChunkedArray* arr) - { - if (!arr) { return; } - - for (u32 i = 0; i < arr->chunkCount; i++) - { - region_free(arr->region, arr->chunks[i]); - } - region_free(arr->region, arr->chunks); - region_free(arr->region, arr->freeSlots); - region_free(arr->region, arr); - } - - void* allocFromChunkedArray(ChunkedArray* arr) - { - if (arr->freeSlotCount) - { - arr->freeSlotCount--; - return arr->freeSlots[arr->freeSlotCount]; - } - s32 elementIndex = arr->elemCount; - arr->elemCount++; - - const u32 newChunkIndex = elementIndex / arr->elemPerChunk; - const u32 newChunkCount = newChunkIndex + 1; - if (newChunkCount > arr->chunkCount) - { - arr->chunks = (u8**)region_realloc(arr->region, arr->chunks, sizeof(u8*) * newChunkCount); - - const u32 chunkAllocSize = arr->elemPerChunk * arr->elemSize; - for (u32 i = arr->chunkCount; i < newChunkCount; i++) - { - arr->chunks[i] = (u8*)region_alloc(arr->region, chunkAllocSize); - } - arr->chunkCount = newChunkCount; - } - - const u32 index = elementIndex - newChunkIndex*arr->elemPerChunk; - assert(index < arr->elemPerChunk); - return arr->chunks[newChunkIndex] + index*arr->elemSize; - } - - void freeToChunkedArray(ChunkedArray* arr, void* ptr) - { - if (!arr || !ptr) { return; } - -#ifdef _VERIFY_CHUNKED_ARR_FREE - // First verify that the memory is contained within the chunked array. - for (s32 i = arr->chunkCount - 1; i >= 0; i--) - { - if (ptr >= arr->chunks[i]) - { - assert(ptr < arr->chunks[i] + arr->elemPerChunk * arr->elemSize); - // Then find the index. - u32 index = u32((u8*)ptr - arr->chunks[i]) / arr->elemSize; - assert(index < arr->elemPerChunk); - break; - } - } - // Then verify that it hasn't already been freed. - for (u32 i = 0; i < arr->freeSlotCount; i++) - { - assert(arr->freeSlots[i] != ptr); - } -#endif - - addFreeSlot(arr, (u8*)ptr); - } - - void chunkedArrayClear(ChunkedArray* arr) - { - if (!arr) { return; } - - arr->elemCount = 0; - arr->freeSlotCount = 0; - for (u32 i = 0; i < arr->chunkCount; i++) - { - memset(arr->chunks[i], 0, arr->elemPerChunk * arr->elemSize); - } - } - - u32 chunkedArraySize(ChunkedArray* arr) - { - if (!arr) { return 0; } - return arr->elemCount; - } - - u32 chunkedArrayCount(ChunkedArray* arr) - { - if (!arr) { return 0; } - return arr->elemCount - arr->freeSlotCount; - } - - void* chunkedArrayGet(ChunkedArray* arr, u32 index) - { - u32 chunkId = index / arr->elemPerChunk; - u32 elemId = index - chunkId*arr->elemPerChunk; - assert(chunkId < arr->chunkCount); - // Range checking. - if (chunkId >= arr->chunkCount) { return nullptr; } - return arr->chunks[chunkId] + elemId*arr->elemSize; - } - - void addFreeSlot(ChunkedArray* arr, u8* ptr) - { - if (arr->freeSlotCount + 1 >= arr->freeSlotCapacity) - { - arr->freeSlotCapacity += FREE_SLOT_STEP; - arr->freeSlots = (u8**)region_realloc(arr->region, arr->freeSlots, sizeof(u8*) * arr->freeSlotCapacity); - } - arr->freeSlots[arr->freeSlotCount] = ptr; - arr->freeSlotCount++; - } - - s32 getSlotIndex(ChunkedArray* arr, u8* ptr) - { - for (s32 i = 0; i < (s32)arr->chunkCount; i++) - { - if (arr->chunks[i] == ptr) - { - return i; - } - } - return -1; - } -} diff --git a/components/darkforces/tfe/TFE_Memory/chunkedArray.h b/components/darkforces/tfe/TFE_Memory/chunkedArray.h deleted file mode 100644 index e0fab6f9..00000000 --- a/components/darkforces/tfe/TFE_Memory/chunkedArray.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Chunked array allocator -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include - -struct ChunkedArray; -struct MemoryRegion; - -namespace TFE_Memory -{ - ChunkedArray* createChunkedArray(u32 elemSize, u32 elemPerChunk, u32 initChunkCount, MemoryRegion* region); - // Free everything. - void freeChunkedArray(ChunkedArray* arr); - // Empty the array but do not free the memory. - void chunkedArrayClear(ChunkedArray* arr); - - void* allocFromChunkedArray(ChunkedArray* arr); - void freeToChunkedArray(ChunkedArray* arr, void* ptr); - - u32 chunkedArraySize(ChunkedArray* arr); - u32 chunkedArrayCount(ChunkedArray* arr); - void* chunkedArrayGet(ChunkedArray* arr, u32 index); - - void serialize(ChunkedArray* arr, FileStream* file); - ChunkedArray* restore(FileStream* file, MemoryRegion* region); - - s32 getSlotIndex(ChunkedArray* arr, u8* ptr); -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Memory/memoryRegion.h b/components/darkforces/tfe/TFE_Memory/memoryRegion.h deleted file mode 100644 index 10d0bc63..00000000 --- a/components/darkforces/tfe/TFE_Memory/memoryRegion.h +++ /dev/null @@ -1,44 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// General purpose memory allocator which acts as a region of -// memory which can be quickly cleared. -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include - -struct MemoryRegion; -typedef u32 RelativePointer; - -#define NULL_RELATIVE_POINTER 0 - -namespace TFE_Memory -{ - MemoryRegion* region_create(const char* name, size_t blockSize, size_t maxSize = 0u); - void region_clear(MemoryRegion* region); - void region_destroy(MemoryRegion* region); - - void* region_alloc(MemoryRegion* region, size_t size); - void* region_realloc(MemoryRegion* region, void* ptr, size_t size); - void region_free(MemoryRegion* region, void* ptr); - - size_t region_getMemoryUsed(MemoryRegion* region); -#ifdef TFE_ESPBOX - // Debug: whether ptr is inside an allocation of this region. - bool region_contains(MemoryRegion* region, const void* ptr); -#endif - size_t region_getMemoryCapacity(MemoryRegion* region); - void region_getBlockInfo(MemoryRegion* region, size_t* blockCount, size_t* blockSize); - - RelativePointer region_getRelativePointer(MemoryRegion* region, void* ptr); - void* region_getRealPointer(MemoryRegion* region, RelativePointer ptr); - - // TODO: Support writing to and restoring from streams in memory. - bool region_serializeToDisk(MemoryRegion* region, FileStream* file); - // Restore a region from disk. If 'region' is NULL then a new region is allocated, - // otherwise it will attempt to reuse the existing region. - MemoryRegion* region_restoreFromDisk(MemoryRegion* region, FileStream* file); - - void region_test(); -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Outlaws/outlawsMain.cpp b/components/darkforces/tfe/TFE_Outlaws/outlawsMain.cpp deleted file mode 100644 index f5ba967c..00000000 --- a/components/darkforces/tfe/TFE_Outlaws/outlawsMain.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include "outlawsMain.h" - -namespace TFE_Outlaws -{ - bool Outlaws::runGame(s32 argCount, const char* argv[], Stream* stream) - { - // STUB - return false; - } - - void Outlaws::pauseGame(bool pause) - { - // STUB - } - - void Outlaws::pauseSound(bool pause) - { - // STUB - } - - void Outlaws::restartMusic() - { - // STUB - } - - void Outlaws::exitGame() - { - // STUB - } - - // Outlaws does not use loopGame() -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Outlaws/outlawsMain.h b/components/darkforces/tfe/TFE_Outlaws/outlawsMain.h deleted file mode 100644 index cd1bd3cc..00000000 --- a/components/darkforces/tfe/TFE_Outlaws/outlawsMain.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Game Level -// Manages the game while playing levels in first person. -// This holds one or more players, handles input updates, etc. -////////////////////////////////////////////////////////////////////// -#include - -namespace TFE_Outlaws -{ - struct Outlaws : IGame - { - bool runGame(s32 argCount, const char* argv[], Stream* stream) override; - void pauseGame(bool pause) override; - void pauseSound(bool pause) override; - void restartMusic() override; - void exitGame() override; - }; -} diff --git a/components/darkforces/tfe/TFE_Polygon/MPE_fastpoly2tri.h b/components/darkforces/tfe/TFE_Polygon/MPE_fastpoly2tri.h deleted file mode 100644 index a1a95033..00000000 --- a/components/darkforces/tfe/TFE_Polygon/MPE_fastpoly2tri.h +++ /dev/null @@ -1,2205 +0,0 @@ -/* fast-poly2tri - v1.0 - - Rewrite of the poly2tri library (https://github.com/jhasse/poly2tri) - by Unspongeful (@unspongeful). - - Based on the Sweep-line, Constrained Delauney Triangulation (CDT) See: Domiter, - V. and Zalik, B.(2008)'Sweep-line algorithm for constrained Delaunay - triangulation', International Journal of Geographical Information Science - "FlipScan" Constrained Edge Algorithm by Thomas hln, thahlen@gmail.com - - This library's focus is speed. No validation is performed, other than - basic debug-time assert. - Passing malformed data will result in a crash, _you must_ pre-validate - the data. - - NOTE: Unlike unlike poly2tri's original implementation I removed - the ability to add Steiner points explicitly, but they can be added - by manipulating the internal state of the context. - - - //////////////////////////////// - - To include in your project: - #define MPE_POLY2TRI_IMPLEMENTATION - before you include this file in *one* C or C++ file to create the implementation. - - // i.e. it should look like this: - #include ... - #define MPE_POLY2TRI_IMPLEMENTATION - #include "MPE_fastpoly2tri.h" - - On multiple compilation unit builds you must also redefine - `insternal_static` to extern. - - //////////////////////////////// - Usage: - - // The maximum number of points you expect to need - // This value is used by the library to calculate - // working memory required - uint32_t MaxPointCount = 100; - - // Request how much memory (in bytes) you should - // allocate for the library - size_t MemoryRequired = MPE_PolyMemoryRequired(MaxPointCount); - - // Allocate a void* memory block of size MemoryRequired - // IMPORTANT: The memory must be zero initialized - void* Memory = calloc(MemoryRequired, 1); - - // Initialize the poly context by passing the memory pointer, - // and max number of points from before - MPEPolyContext PolyContext; - if (MPE_PolyInitContext(&PolyContext, Memory, MaxPointCount)) - { - // Populate the points of the polyline for the shape - // you want to triangulate using one of the following - // two methods: - - // Option A - One point at a time - for(...) - { - MPEPolyPoint* Point = MPE_PolyPushPoint(&PolyContext); - Point->X = ...; - Point->Y = ...; - } - - // Option B - memcpy - // This option requires your point data structure to - // correspond to MPEPolyPoint. See below. - uint32_t PointCount = ...; - MPEPolyPoint* FirstPoint = MPE_PolyPushPointArray(&PolyContext, PointCount); - memcpy(FirstPoint, YOUR_POINT_DATA, sizeof(MPEPolyPoint)*PointCount); - - // IMPORTANT: Both push functions perform no validation other - // than an assert for bounds checking. You must make sure your - // point data is correct: - // - Duplicate points are not supported - // - Bounds checking is not implemented other than debug asserts - - // Add the polyline for the edge. This will consume all points added so far. - MPE_PolyAddEdge(&PolyContext); - - // If you want to add holes to the shape you can do: - if (AddHoles) - { - MPEPolyPoint* Hole = MPE_PolyPushPointArray(&PolyContext, 4); - Hole[0].X = 325; Hole[0].Y = 437; - Hole[1].X = 320; Hole[1].Y = 423; - Hole[2].X = 329; Hole[2].Y = 413; - Hole[3].X = 332; Hole[3].Y = 423; - MPE_PolyAddHole(&PolyContext); - } - - // Triangulate the shape - MPE_PolyTriangulate(&PolyContext); - - // The resulting triangles can be used like so - for (uxx TriangleIndex = 0; TriangleIndex < PolyContext.TriangleCount; ++TriangleIndex) - { - MPEPolyTriangle* Triangle = PolyContext.Triangles[TriangleIndex]; - MPEPolyPoint* PointA = Triangle->Points[0]; - MPEPolyPoint* PointB = Triangle->Points[1]; - MPEPolyPoint* PointC = Triangle->Points[2]; - } - // You may want to copy the resulting triangle soup into - // your own data structures if you plan on using them often - // as the Points and Triangles from the PolyContext are not - // compact in memory. - - - //////////////////////////////// - Configuration defines: - - #define MPE_POLY2TRI_USE_DOUBLE - To use double precision floating point for calculations - - #define MPE_POLY2TRI_USE_CUSTOM_SORT - To use the a custom merge sort implementation. Enabling this option will - require more working memory. - - //////////////////////////////// - Standard library overrides - - #define MPE_MemorySet, MPE_MemoryCopy - To avoid including string.h - - #define internal_static - Defaults to static, but you can change it if not using a unity-style build. - - LICENSE - MIT (same as original license) - -*/ -#ifndef MPE_POLY2TRI_HEADER -#define MPE_POLY2TRI_HEADER - -//SECTION: Engine define overrides - -#include // fabs fabsf - -#ifndef MPE_MemorySet - #include //memset - #define MPE_MemorySet memset - #define MPE_MemoryCopy memcpy -#endif - -#ifndef MPE_Assert - #include - #define MPE_Assert assert -#endif - -#ifndef uxx - #include // uint32_t - typedef uint8_t u8; - typedef int32_t i32; - typedef int32_t b32; - typedef uint32_t u32; - typedef float f32; - typedef double f64; - typedef size_t uxx; - //typedef ssize_t bxx; - typedef s64 bxx; - typedef intptr_t imm; - typedef uintptr_t umm; -#endif - -#ifdef MPE_POLY2TRI_USE_DOUBLE - typedef double poly_float; -#else - typedef float poly_float; -#endif - -#ifndef internal_static - #define internal_static static -#endif -#ifndef MPE_INLINE - #define MPE_INLINE inline -#endif - -#ifdef __cplusplus - extern "C" { -#endif - -///////////////////// - -typedef struct MPEPolyAllocator -{ - u8* Memory; - umm Size; - umm Used; -} MPEPolyAllocator; - -typedef struct MPEPolyPoint -{ - struct MPEPolyEdge* FirstEdge; - poly_float X; - poly_float Y; -} MPEPolyPoint; - -typedef struct MPEPolyTriangle -{ - struct MPEPolyTriangle* Neighbors[3]; - MPEPolyPoint* Points[3]; - uxx Flags; -} MPEPolyTriangle; - -typedef struct MPEPolyNode -{ - struct MPEPolyNode* Next; - struct MPEPolyNode* Prev; - MPEPolyPoint* Point; - MPEPolyTriangle* Triangle; - poly_float Value; -#ifndef MPE_POLY2TRI_USE_DOUBLE - u32 _PADDING; -#endif -} MPEPolyNode; - -typedef struct MPEPolyBasin -{ - MPEPolyNode* LeftNode; - MPEPolyNode* BottomNode; - MPEPolyNode* RightNode; - poly_float Width; -#ifdef MPE_POLY2TRI_USE_DOUBLE - bxx LeftHighest; -#else - b32 LeftHighest; -#endif -} MPEPolyBasin; - -typedef struct MPEPolyEdge -{ - MPEPolyPoint* P; - MPEPolyPoint* Q; - struct MPEPolyEdge* Next; -} MPEPolyEdge; - -typedef struct MPEEdgeEvent -{ - MPEPolyEdge* ConstrainedEdge; - bxx Right; -} MPEEdgeEvent; - - -typedef struct MPEPolyContext -{ - void* UserData; - void* Memory; - MPEPolyAllocator Allocator; - MPEPolyBasin Basin; - MPEEdgeEvent EdgeEvent; - MPEPolyNode* HeadNode; - MPEPolyNode* TailNode; - MPEPolyNode* SearchNode; - - MPEPolyTriangle* TrianglePool; - MPEPolyTriangle** Triangles; - MPEPolyTriangle** TempTriangles; - MPEPolyPoint** Points; - MPEPolyPoint* PointsPool; - MPEPolyNode* Nodes; - - MPEPolyPoint* HeadPoint; - MPEPolyPoint* TailPoint; - - u32 MaxPointCount; - u32 PointPoolCount; - u32 PointCount; - u32 TrianglePoolCount; - u32 TriangleCount; - u32 NodeCount; - b32 Valid; - u32 _PADDING; -} MPEPolyContext; - - -///////////////////// -// PUBLIC API - -internal_static -umm MPE_PolyMemoryRequired(u32 MaxPointCount); - -internal_static -b32 MPE_PolyInitContext(MPEPolyContext* PolyContext, void* Memory, u32 MaxPointCount); - -internal_static -MPEPolyPoint* MPE_PolyPushPoint(MPEPolyContext* PolyContext); - -internal_static -MPEPolyPoint* MPE_PolyPushPointArray(MPEPolyContext* PolyContext, u32 Count); - -internal_static -void MPE_PolyAddEdge(MPEPolyContext* PolyContext); - -internal_static -void MPE_PolyTriangulate(MPEPolyContext* PolyContext); - -//SECTION: Required overrides - -#ifdef __cplusplus -} -#endif - -#endif // MPE_POLY2TRI_HEADER - - -#ifdef MPE_POLY2TRI_IMPLEMENTATION - -////////////////////// -// IMPLEMENTATION - -#define MPE_POLY2TRI_EPSILON (poly_float)1e-12f -#define MPE_POLY2TRI_POINT_COUNT_EPSILON 16 - -#ifndef MPE_InvalidCodePath - #define MPE_InvalidCodePath MPE_Assert(0) -#endif - -#ifndef MPE_TRUE - #define MPE_FALSE 0 - #define MPE_TRUE 1 -#endif - - -#ifndef MPE_Assert - #error "Please #define MPE_Assert to assert from or custom implementation" -#endif -#ifndef MPE_MemorySet - #error "Please #define MPE_MemorySet to memset from or custom implementation" -#endif - - -#define MPE_PolyPush(Allocator, Type) ((Type*)MPE_PolyPushRaw(&Allocator, sizeof(Type))) -#define MPE_PolyPushArray(Allocator, Type, Count) ((Type*)MPE_PolyPushRaw(&Allocator, sizeof(Type) * Count)) - -internal_static -u8* MPE_PolyPushRaw(MPEPolyAllocator* Allocator, umm Size); - -typedef struct MPEPolyEdges -{ - u8 ConstrainedCW; - u8 ConstrainedCCW; - u8 DelaunayCW; - u8 DelaunayCCW; -} MPEPolyEdges; - -enum MPEPolyOrientation -{ - MPEPolyOrientation_CCW, - MPEPolyOrientation_CW, - MPEPolyOrientation_Collinear -}; - -enum MPEPolyTriFlag -{ - MPEPolyTriFlag_DelaunayEdge0 = 1 << 0, - MPEPolyTriFlag_DelaunayEdge1 = 1 << 1, - MPEPolyTriFlag_DelaunayEdge2 = 1 << 2, - MPEPolyTriFlag_ConstrainedEdge0 = 1 << 3, - MPEPolyTriFlag_ConstrainedEdge1 = 1 << 4, - MPEPolyTriFlag_ConstrainedEdge2 = 1 << 5, - - MPEPolyTriFlag_IsInterior = 1 << 30, - - MPEPolyTriFlag_DelaunayEdgeMask = MPEPolyTriFlag_DelaunayEdge0 | MPEPolyTriFlag_DelaunayEdge1 | MPEPolyTriFlag_DelaunayEdge2, - MPEPolyTriFlag_ConstrainedEdgeMask = MPEPolyTriFlag_ConstrainedEdge0 | MPEPolyTriFlag_ConstrainedEdge1 | MPEPolyTriFlag_ConstrainedEdge2 -}; - - -static u32 MPEPolyEdgeLUT[] = {0, 1, 2, 0, 1, 2, 3}; - -internal_static -u8* MPE_PolyPushRaw(MPEPolyAllocator* Allocator, umm Size) -{ - u8* Result = 0; - if (Allocator->Used + Size <= Allocator->Size) - { - Result = Allocator->Memory + Allocator->Used; - Allocator->Used += Size; - } - else - { - MPE_InvalidCodePath; - } - return Result; -} - - -/* - Formula to calculate signed area - Positive if CCW - Negative if CW - 0 if collinear - A[P1,P2,P3] = (x1*y2 - y1*x2) + (x2*y3 - y2*x3) + (x3*y1 - y3*x1) - = (x1-x3)*(y2-y3) - (y1-y3)*(x2-x3) - */ - -internal_static -uxx MPE_PolyOrient2D(MPEPolyPoint* PointA, MPEPolyPoint* PointB, MPEPolyPoint* PointC) -{ - uxx Result; - MPE_Assert(PointA != PointB && PointA != PointC && PointB != PointC); - poly_float DeltaLeft = (PointA->X - PointC->X) * (PointB->Y - PointC->Y); - poly_float DeltaRight = (PointA->Y - PointC->Y) * (PointB->X - PointC->X); - poly_float Value = DeltaLeft - DeltaRight; - if (Value > -MPE_POLY2TRI_EPSILON && Value < MPE_POLY2TRI_EPSILON) - { - Result = MPEPolyOrientation_Collinear; - } - else if (Value > 0) - { - Result = MPEPolyOrientation_CCW; - } - else - { - Result = MPEPolyOrientation_CW; - } - return Result; -} - -internal_static -bxx MPE_PolyInScanArea(MPEPolyPoint* PointA, MPEPolyPoint* PointB, MPEPolyPoint* PointC, MPEPolyPoint* PointD) -{ - MPE_Assert(PointA != PointB && PointA != PointC && PointA != PointD && - PointB != PointC && PointB != PointD && - PointC != PointD); - poly_float oadb = (PointA->X - PointB->X) * (PointD->Y - PointB->Y) - (PointD->X - PointB->X) * (PointA->Y - PointB->Y); - bxx Result; - if (oadb >= -MPE_POLY2TRI_EPSILON) - { - Result = MPE_FALSE; - } - else - { - poly_float oadc = (PointA->X - PointC->X) * (PointD->Y - PointC->Y) - (PointD->X - PointC->X) * (PointA->Y - PointC->Y); - if (oadc <= MPE_POLY2TRI_EPSILON) - { - Result = MPE_FALSE; - } - else - { - Result = MPE_TRUE; - } - } - return Result; -} - -internal_static MPE_INLINE -bxx MPE_PolyContainsPoint(MPEPolyTriangle* Triangle, MPEPolyPoint* Point) -{ - MPE_Assert(Point); - bxx Result = Point == Triangle->Points[0] || Point == Triangle->Points[1] || Point == Triangle->Points[2]; - return Result; -} - -internal_static MPE_INLINE -bxx MPE_PolyContainsPoints(MPEPolyTriangle* Triangle, MPEPolyPoint* Point, MPEPolyPoint* OtherPoint) -{ - bxx Result = MPE_PolyContainsPoint(Triangle, Point) && MPE_PolyContainsPoint(Triangle, OtherPoint); - return Result; -} - -internal_static -void MPE_PolySwapNeighbors(MPEPolyTriangle* Triangle, MPEPolyTriangle* OldNeighbor, MPEPolyTriangle* NewNeighbor) -{ - for(u32 NeighborIndex = 0;; ++NeighborIndex) - { - MPE_Assert(NeighborIndex < 3); - if (Triangle->Neighbors[NeighborIndex] == OldNeighbor) - { - Triangle->Neighbors[NeighborIndex] = NewNeighbor; - break; - } - } -} - -internal_static -void MPE_PolyMarkNeighborTri(MPEPolyTriangle* Triangle, MPEPolyTriangle* Neighbor) -{ - for (u32 EdgeIndex = 0; EdgeIndex < 3; ++EdgeIndex) - { - u32 NextEdgeIndex = MPEPolyEdgeLUT[EdgeIndex+1]; - for (u32 NeighborIndex = 0; NeighborIndex < 3; ++NeighborIndex) - { - u32 NextNeighborIndex = MPEPolyEdgeLUT[NeighborIndex+1]; - if ((Triangle->Points[EdgeIndex] == Neighbor->Points[NeighborIndex] && - Triangle->Points[NextEdgeIndex] == Neighbor->Points[NextNeighborIndex]) || - (Triangle->Points[EdgeIndex] == Neighbor->Points[NextNeighborIndex] && - Triangle->Points[NextEdgeIndex] == Neighbor->Points[NeighborIndex])) - { - Triangle->Neighbors[MPEPolyEdgeLUT[NextEdgeIndex+1]] = Neighbor; - Neighbor->Neighbors[MPEPolyEdgeLUT[NextNeighborIndex+1]] = Triangle; - return; - } - } - } -} - -internal_static MPE_INLINE -void MPE_ClearDelunayEdges(MPEPolyTriangle* Triangle) -{ - Triangle->Flags &= ~(uxx)MPEPolyTriFlag_DelaunayEdgeMask; -} - -internal_static -MPEPolyPoint* MPE_PointCW(MPEPolyTriangle* Triangle, MPEPolyPoint* Point, i32* PointIndex) -{ - MPEPolyPoint* Result; - if (Point == Triangle->Points[0]) - { - Result = Triangle->Points[2]; - *PointIndex = 2; - } - else if (Point == Triangle->Points[1]) - { - Result = Triangle->Points[0]; - *PointIndex = 0; - } - else if (Point == Triangle->Points[2]) - { - Result = Triangle->Points[1]; - *PointIndex = 1; - } - else - { - MPE_InvalidCodePath; - Result = 0; - *PointIndex = -1; - } - return Result; -} - -internal_static -MPEPolyTriangle* MPE_NeighborCCW(MPEPolyTriangle* Triangle, MPEPolyPoint* Point) -{ - MPEPolyTriangle* Result; - if (Point == Triangle->Points[0]) - { - Result = Triangle->Neighbors[2]; - } - else if (Point == Triangle->Points[1]) - { - Result = Triangle->Neighbors[0]; - } - else - { - MPE_Assert(Point == Triangle->Points[2]); - Result = Triangle->Neighbors[1]; - } - return Result; -} - -#define FLAG(Tri, Name) (Tri->Flags & MPEPolyTriFlag_##Name) == MPEPolyTriFlag_## Name - -internal_static -void MPE_SetAdjacentEdges(MPEPolyTriangle* Triangle, MPEPolyPoint* Point, MPEPolyEdges Edges, bxx Clockwise) -{ - uxx Mask; - uxx NewFlags; - if (Point == Triangle->Points[0]) - { - if (Clockwise) - { - Mask = MPEPolyTriFlag_ConstrainedEdge1 | MPEPolyTriFlag_DelaunayEdge1; - NewFlags = (Edges.ConstrainedCW & MPEPolyTriFlag_ConstrainedEdge1) | - (Edges.DelaunayCW & MPEPolyTriFlag_DelaunayEdge1); - } - else - { - Mask = MPEPolyTriFlag_ConstrainedEdge2 | MPEPolyTriFlag_DelaunayEdge2; - NewFlags = (Edges.ConstrainedCCW & MPEPolyTriFlag_ConstrainedEdge2) | - (Edges.DelaunayCCW & MPEPolyTriFlag_DelaunayEdge2); - } - } - else if (Point == Triangle->Points[1]) - { - if (Clockwise) - { - Mask = MPEPolyTriFlag_ConstrainedEdge2 | MPEPolyTriFlag_DelaunayEdge2; - NewFlags = (Edges.ConstrainedCW & MPEPolyTriFlag_ConstrainedEdge2) | - (Edges.DelaunayCW & MPEPolyTriFlag_DelaunayEdge2); - } - else - { - Mask = MPEPolyTriFlag_ConstrainedEdge0 | MPEPolyTriFlag_DelaunayEdge0; - NewFlags = (Edges.ConstrainedCCW & MPEPolyTriFlag_ConstrainedEdge0) | - (Edges.DelaunayCCW & MPEPolyTriFlag_DelaunayEdge0); - } - } - else - { - if (Clockwise) - { - Mask = MPEPolyTriFlag_ConstrainedEdge0 | MPEPolyTriFlag_DelaunayEdge0; - NewFlags = (Edges.ConstrainedCW & MPEPolyTriFlag_ConstrainedEdge0) | - (Edges.DelaunayCW & MPEPolyTriFlag_DelaunayEdge0); - } - else - { - Mask = MPEPolyTriFlag_ConstrainedEdge1 | MPEPolyTriFlag_DelaunayEdge1; - NewFlags = (Edges.ConstrainedCCW & MPEPolyTriFlag_ConstrainedEdge1) | - (Edges.DelaunayCCW & MPEPolyTriFlag_DelaunayEdge1); - } - } - Triangle->Flags = (Triangle->Flags & ~Mask) | NewFlags; -} - - -internal_static -uxx MPE_GetConstrainedEdgeCW(MPEPolyTriangle* Triangle, MPEPolyPoint* Point) -{ - uxx Result; - if (Point == Triangle->Points[0]) - { - Result = Triangle->Flags & MPEPolyTriFlag_ConstrainedEdge1; - } - else if (Point == Triangle->Points[1]) - { - Result = Triangle->Flags & MPEPolyTriFlag_ConstrainedEdge2; - } - else - { - MPE_Assert(Point == Triangle->Points[2]); - Result = Triangle->Flags & MPEPolyTriFlag_ConstrainedEdge0; - } - return Result; -} - -internal_static MPE_INLINE -MPEPolyTriangle* MPE_PolyNeighborAcross(MPEPolyTriangle* Triangle, MPEPolyPoint* OppositePoint) -{ - MPEPolyTriangle* Result; - if (OppositePoint == Triangle->Points[0]) - { - Result = Triangle->Neighbors[0]; - } - else if (OppositePoint == Triangle->Points[1]) - { - Result = Triangle->Neighbors[1]; - } - else - { - MPE_Assert(OppositePoint == Triangle->Points[2]); - Result = Triangle->Neighbors[2]; - } - return Result; -} - - -internal_static MPE_INLINE -void MPE_PolyLegalizePoint(MPEPolyTriangle* Triangle, MPEPolyPoint* Point) -{ - Triangle->Points[1] = Triangle->Points[0]; - Triangle->Points[0] = Triangle->Points[2]; - Triangle->Points[2] = Point; -} - -internal_static -i32 MPE_PolyPointIndex(MPEPolyTriangle* Triangle, MPEPolyPoint* Point) -{ - i32 Result; - if (Point == Triangle->Points[0]) - { - Result = 0; - } - else if (Point == Triangle->Points[1]) - { - Result = 1; - } - else if (Point == Triangle->Points[2]) - { - Result = 2; - } - else - { - Result = -1; - MPE_InvalidCodePath; - } - return Result; -} - -internal_static -i32 MPE_EdgeIndex(MPEPolyTriangle* Triangle, MPEPolyPoint* P1, MPEPolyPoint* P2) -{ - i32 Result = -1; - if (Triangle->Points[0] == P1) - { - if (Triangle->Points[1] == P2) - { - Result = 2; - } - else if (Triangle->Points[2] == P2) - { - Result = 1; - } - } - else if (Triangle->Points[1] == P1) - { - if (Triangle->Points[2] == P2) - { - Result = 0; - } - else if (Triangle->Points[0] == P2) - { - Result = 2; - } - } - else if (Triangle->Points[2] == P1) - { - if (Triangle->Points[0] == P2) - { - Result = 1; - } - else if (Triangle->Points[1] == P2) - { - Result = 0; - } - } - return Result; -} - - -internal_static MPE_INLINE -void MPE_PolyMarkConstrainedEdgeIndex(MPEPolyTriangle* Triangle, i32 Index) -{ - MPE_Assert(Index >= 0); - Triangle->Flags |= (uxx)MPEPolyTriFlag_ConstrainedEdge0 << (u32)Index; -} - -internal_static MPE_INLINE -void MPE_PolyMarkDelaunayEdge(MPEPolyTriangle* Triangle, i32 Index) -{ - MPE_Assert(Index >= 0); - Triangle->Flags |= (uxx)MPEPolyTriFlag_DelaunayEdge0 << (u32)Index; -} - -internal_static -void MPE_PolyMarkConstrainedEdgePoints(MPEPolyTriangle* Triangle, MPEPolyPoint* Point, MPEPolyPoint* OtherPoint) -{ - if ((OtherPoint == Triangle->Points[0] && Point == Triangle->Points[1]) || - (OtherPoint == Triangle->Points[1] && Point == Triangle->Points[0])) - { - MPE_PolyMarkConstrainedEdgeIndex(Triangle, 2); - } - else if ((OtherPoint == Triangle->Points[0] && Point == Triangle->Points[2]) || - (OtherPoint == Triangle->Points[2] && Point == Triangle->Points[0])) - { - MPE_PolyMarkConstrainedEdgeIndex(Triangle, 1); - } - else if ((OtherPoint == Triangle->Points[1] && Point == Triangle->Points[2]) || - (OtherPoint == Triangle->Points[2] && Point == Triangle->Points[1])) - { - MPE_PolyMarkConstrainedEdgeIndex(Triangle, 0); - } -} - -internal_static MPE_INLINE -void MPE_PolyMarkConstrainedEdge(MPEPolyTriangle* Triangle, MPEPolyEdge* Edge) -{ - MPE_PolyMarkConstrainedEdgePoints(Triangle, Edge->P, Edge->Q); -} - -internal_static MPE_INLINE -MPEPolyNode* MPE_PolyNode(MPEPolyContext* PolyContext, MPEPolyPoint* Point, MPEPolyTriangle* Triangle) -{ - MPEPolyNode* Result = PolyContext->Nodes + PolyContext->NodeCount++; - Result->Point = Point; - Result->Triangle = Triangle; - Result->Value = Point->X; - return Result; -} - -internal_static -MPEPolyPoint* MPE_PolyPushPoint(MPEPolyContext* PolyContext) -{ - MPE_Assert(PolyContext->MaxPointCount > PolyContext->PointPoolCount); - MPEPolyPoint* Result = PolyContext->PointsPool + PolyContext->PointPoolCount++; - return Result; -} - -internal_static -MPEPolyPoint* MPE_PolyPushPointArray(MPEPolyContext* PolyContext, u32 Count) -{ - MPE_Assert(PolyContext->MaxPointCount > (PolyContext->PointPoolCount+Count)); - MPEPolyPoint* Result = PolyContext->PointsPool + PolyContext->PointPoolCount; - PolyContext->PointPoolCount += Count; - return Result; -} - - -internal_static MPE_INLINE -MPEPolyTriangle* MPE_PushTriangle(MPEPolyContext* PolyContext, MPEPolyPoint* A, MPEPolyPoint* B, MPEPolyPoint* C) -{ - MPEPolyTriangle* Result = PolyContext->TrianglePool + PolyContext->TrianglePoolCount++; - Result->Points[0] = A; - Result->Points[1] = B; - Result->Points[2] = C; - return Result; -} - -internal_static MPE_INLINE -MPEPolyNode* MPE_LocatePoint(MPEPolyContext* PolyContext, MPEPolyPoint* Point) -{ - poly_float PX = Point->X; - MPEPolyNode* Node = PolyContext->SearchNode; - poly_float NX = Node->Point->X; - - if (PX < NX) - { - while ((Node = Node->Prev)) - { - if (Point == Node->Point) - { - break; - } - } - } - else if ((PX - NX) < MPE_POLY2TRI_EPSILON) - { - if (Point != Node->Point) - { - // We might have two nodes with same X Value for a short time - if (Point == Node->Prev->Point) - { - Node = Node->Prev; - } - else - { - MPE_Assert(Point == Node->Next->Point); - Node = Node->Next; - } - } - } - else - { - while ((Node = Node->Next)) - { - if (Point == Node->Point) - { - break; - } - } - } - if (Node) - { - PolyContext->SearchNode = Node; - } - return Node; -} - -internal_static -bxx MPE_IsEdgeSideOfTriangle(MPEPolyTriangle* Triangle, MPEPolyPoint* EdgeP, MPEPolyPoint* EdgeQ) -{ - i32 EdgeIndex = MPE_EdgeIndex(Triangle, EdgeP, EdgeQ); - bxx Result; - if (EdgeIndex != -1) - { - MPE_PolyMarkConstrainedEdgeIndex(Triangle, EdgeIndex); - MPEPolyTriangle* NeighborTriangle = Triangle->Neighbors[EdgeIndex]; - if (NeighborTriangle) - { - MPE_PolyMarkConstrainedEdgePoints(NeighborTriangle, EdgeP, EdgeQ); - } - Result = MPE_TRUE; - } - else - { - Result = MPE_FALSE; - } - return Result; -} - -internal_static -bxx MPE_AngleExceeds90Degrees(MPEPolyPoint* Origin, MPEPolyPoint* PointA, MPEPolyPoint* PointB) -{ - poly_float AX = PointA->X - Origin->X; - poly_float AY = PointA->Y - Origin->Y; - poly_float BX = PointB->X - Origin->X; - poly_float BY = PointB->Y - Origin->Y; - poly_float DotProduct = AX * BX + AY * BY; - bxx Result = DotProduct < 0; - return Result; -} - -internal_static -bxx MPE_AngleExceedsPlus90DegreesOrIsNegative(MPEPolyPoint* Origin, MPEPolyPoint* PointA, MPEPolyPoint* PointB) -{ - poly_float AX = PointA->X - Origin->X; - poly_float AY = PointA->Y - Origin->Y; - poly_float BX = PointB->X - Origin->X; - poly_float BY = PointB->Y - Origin->Y; - poly_float DotProduct = AX * BX + AY * BY; - poly_float Direction = AX * BY - AY * BX; - bxx Result = DotProduct < 0 || Direction < 0; - return Result; -} - - -internal_static -bxx MPE_LargeHole_DontFill(MPEPolyNode* Node) -{ - bxx Result; - MPEPolyNode* NextNode = Node->Next; - MPEPolyNode* PrevNode = Node->Prev; - if (!MPE_AngleExceeds90Degrees(Node->Point, NextNode->Point, PrevNode->Point)) - { - Result = MPE_FALSE; - } - else - { - // Check additional points on front. - MPEPolyNode* Next2Node = NextNode->Next; - // "..Plus.." because only want angles on same side as MPEPolyPoint being added. - if (Next2Node && !MPE_AngleExceedsPlus90DegreesOrIsNegative(Node->Point, Next2Node->Point, PrevNode->Point)) - { - Result = MPE_FALSE; - } - else - { - MPEPolyNode* Prev2Node = PrevNode->Prev; - // "..Plus.." because only want angles on same side as MPEPolyPoint being added. - if (Prev2Node && !MPE_AngleExceedsPlus90DegreesOrIsNegative(Node->Point, NextNode->Point, Prev2Node->Point)) - { - Result = MPE_FALSE; - } - else - { - Result = MPE_TRUE; - } - } - } - return Result; -} - -internal_static MPE_INLINE -bxx MPE_PolyShouldFillBasin(MPEPolyNode* Node) -{ - poly_float AX = Node->Point->X; - poly_float AY = Node->Point->Y; - poly_float BX = Node->Next->Next->Point->X; - poly_float BY = Node->Next->Next->Point->Y; - poly_float DotProduct = AX * BX + AY * BY; - poly_float Direction = AX * BY - AY * BX; - bxx Result = DotProduct < 0 || Direction > 0; - return Result; -} - -/** - * Requirement: - * 1. a,b and c form a triangle. - * 2. a and d is know to be on opposite side of bc - * a - * + - * / \ - * / \ - * b/ \c - * +-------+ - * / d \ - * / \ - * Fact: d has to be in area B to have a chance to be inside the circle formed by - * a,b and c - * d is outside B if MPE_PolyOrient2D(a,b,d) or MPE_PolyOrient2D(c,a,d) is CW - * This preknowledge gives us a way to optimize the incircle test - */ - -internal_static -bxx MPE_PolyInCircle(MPEPolyPoint* PointA, MPEPolyPoint* PointB, MPEPolyPoint* pc, MPEPolyPoint* pd) -{ - bxx Result; - poly_float adx = PointA->X - pd->X; - poly_float ady = PointA->Y - pd->Y; - poly_float bdx = PointB->X - pd->X; - poly_float bdy = PointB->Y - pd->Y; - - poly_float adxbdy = adx * bdy; - poly_float bdxady = bdx * ady; - poly_float oabd = adxbdy - bdxady; - - if (oabd <= 0) - { - Result = MPE_FALSE; - } - else - { - poly_float cdx = pc->X - pd->X; - poly_float cdy = pc->Y - pd->Y; - - poly_float cdxady = cdx * ady; - poly_float adxcdy = adx * cdy; - poly_float ocad = cdxady - adxcdy; - - if (ocad <= 0) - { - Result = MPE_FALSE; - } - else - { - poly_float bdxcdy = bdx * cdy; - poly_float cdxbdy = cdx * bdy; - - poly_float alift = adx * adx + ady * ady; - poly_float blift = bdx * bdx + bdy * bdy; - poly_float clift = cdx * cdx + cdy * cdy; - - poly_float det = alift * (bdxcdy - cdxbdy) + blift * ocad + clift * oabd; - Result = det > 0; - } - } - return Result; -} - -/** - * Rotates a triangle pair one vertex CW - * n2 n2 - * P +-----+ P +-----+ - * | t /| |\ t | - * | / | | \ | - * n1| / |n3 n1| \ |n3 - * | / | after CW | \ | - * |/ oT | | oT \| - * +-----+ oP +-----+ - * n4 n4 - */ -internal_static -void MPE_PolyRotateTrianglePair(MPEPolyTriangle* Triangle, MPEPolyPoint* Point, i32 PointIndex, MPEPolyTriangle* OtherTriangle, - MPEPolyPoint* OtherPoint, i32 OtherPointIndex) -{ - MPE_Assert(PointIndex >= 0 && OtherPointIndex >= 0); - uxx Flags = Triangle->Flags; - uxx OtherFlags = OtherTriangle->Flags; - MPEPolyEdges AdjacentEdges; - MPEPolyEdges OtherAdjacentEdges; - - u32 RotateAmount = MPEPolyEdgeLUT[PointIndex+1]; - u32 OtherRotateAmount = MPEPolyEdgeLUT[OtherPointIndex+1]; - - MPEPolyTriangle* Neighbor1 = Triangle->Neighbors[MPEPolyEdgeLUT[1+RotateAmount]]; - MPEPolyTriangle* Neighbor2 = Triangle->Neighbors[RotateAmount]; - MPEPolyTriangle* Neighbor3 = OtherTriangle->Neighbors[MPEPolyEdgeLUT[1+OtherRotateAmount]]; - MPEPolyTriangle* Neighbor4 = OtherTriangle->Neighbors[OtherRotateAmount]; - - Triangle->Neighbors[RotateAmount] = Neighbor3; - Triangle->Neighbors[MPEPolyEdgeLUT[RotateAmount+1]] = Neighbor2; - Triangle->Neighbors[MPEPolyEdgeLUT[RotateAmount+2]] = OtherTriangle; - OtherTriangle->Neighbors[OtherRotateAmount] = Neighbor1; - OtherTriangle->Neighbors[MPEPolyEdgeLUT[OtherRotateAmount+1]] = Neighbor4; - OtherTriangle->Neighbors[MPEPolyEdgeLUT[OtherRotateAmount+2]] = Triangle; - - if (Neighbor1) - { - MPE_PolySwapNeighbors(Neighbor1, Triangle, OtherTriangle); - } - if (Neighbor3) - { - MPE_PolySwapNeighbors(Neighbor3, OtherTriangle, Triangle); - } - - Triangle->Points[RotateAmount] = Triangle->Points[MPEPolyEdgeLUT[2+RotateAmount]]; - Triangle->Points[MPEPolyEdgeLUT[2+RotateAmount]] = Triangle->Points[MPEPolyEdgeLUT[1+RotateAmount]]; - Triangle->Points[MPEPolyEdgeLUT[1+RotateAmount]] = OtherPoint; - OtherTriangle->Points[OtherRotateAmount] = OtherTriangle->Points[MPEPolyEdgeLUT[2+OtherRotateAmount]]; - OtherTriangle->Points[MPEPolyEdgeLUT[2+OtherRotateAmount]] = OtherTriangle->Points[MPEPolyEdgeLUT[1+OtherRotateAmount]]; - OtherTriangle->Points[MPEPolyEdgeLUT[1+OtherRotateAmount]] = Point; - - AdjacentEdges.ConstrainedCW = Flags & ((uxx)MPEPolyTriFlag_ConstrainedEdge0 << ((RotateAmount))) ? 0xFF : 0; - AdjacentEdges.ConstrainedCCW = Flags & ((uxx)MPEPolyTriFlag_ConstrainedEdge0 << (MPEPolyEdgeLUT[RotateAmount+1])) ? 0xFF : 0; - AdjacentEdges.DelaunayCW = Flags & ((uxx)MPEPolyTriFlag_DelaunayEdge0 << ((RotateAmount))) ? 0xFF : 0; - AdjacentEdges.DelaunayCCW = Flags & ((uxx)MPEPolyTriFlag_DelaunayEdge0 << (MPEPolyEdgeLUT[RotateAmount+1])) ? 0xFF : 0; - - OtherAdjacentEdges.ConstrainedCW = OtherFlags & ((uxx)MPEPolyTriFlag_ConstrainedEdge0 << (MPEPolyEdgeLUT[OtherRotateAmount])) ? 0xFF : 0; - OtherAdjacentEdges.ConstrainedCCW = OtherFlags & ((uxx)MPEPolyTriFlag_ConstrainedEdge0 << (MPEPolyEdgeLUT[OtherRotateAmount+1])) ? 0xFF : 0; - OtherAdjacentEdges.DelaunayCW = OtherFlags & ((uxx)MPEPolyTriFlag_DelaunayEdge0 << (MPEPolyEdgeLUT[OtherRotateAmount])) ? 0xFF : 0; - OtherAdjacentEdges.DelaunayCCW = OtherFlags & ((uxx)MPEPolyTriFlag_DelaunayEdge0 << (MPEPolyEdgeLUT[OtherRotateAmount+1])) ? 0xFF : 0; - - MPE_SetAdjacentEdges(Triangle, Point, AdjacentEdges, MPE_TRUE); - MPE_SetAdjacentEdges(Triangle, OtherPoint, OtherAdjacentEdges, MPE_FALSE); - MPE_SetAdjacentEdges(OtherTriangle, Point, AdjacentEdges, MPE_FALSE); - MPE_SetAdjacentEdges(OtherTriangle, OtherPoint, OtherAdjacentEdges, MPE_TRUE); -} - -internal_static -bxx MPE_PolyIsShallow(MPEPolyContext* PolyContext, MPEPolyNode* Node) -{ - poly_float Height; - if (PolyContext->Basin.LeftHighest) - { - Height = PolyContext->Basin.LeftNode->Point->Y - Node->Point->Y; - } - else - { - Height = PolyContext->Basin.RightNode->Point->Y - Node->Point->Y; - } - - bxx Result = PolyContext->Basin.Width > Height; - return Result; -} - -internal_static -bxx MPE_PolyLegalize(MPEPolyContext* PolyContext, MPEPolyTriangle* Triangle); - -internal_static -void MPE_PolyMapTriangleToNodes(MPEPolyContext* PolyContext, MPEPolyTriangle* Triangle); - -internal_static -void MPE_PolyFill(MPEPolyContext* PolyContext, MPEPolyNode* Node) -{ - MPEPolyTriangle* Triangle = MPE_PushTriangle(PolyContext, Node->Prev->Point, Node->Point, Node->Next->Point); - - // TODO: should copy the ConstrainedEdge Value from neighbor Triangles - // for now ConstrainedEdge values are copied during the legalize - // static int count; - // printf("POLY %i\n", count++); - MPE_PolyMarkNeighborTri(Triangle, Node->Prev->Triangle); - MPE_PolyMarkNeighborTri(Triangle, Node->Triangle); - - // Update the advancing front - Node->Prev->Next = Node->Next; - Node->Next->Prev = Node->Prev; - - // If it was legalized the Triangle has already been mapped - if (!MPE_PolyLegalize(PolyContext, Triangle)) - { - MPE_PolyMapTriangleToNodes(PolyContext, Triangle); - } -} - - -internal_static -void MPE_FillBasinReq(MPEPolyContext* PolyContext, MPEPolyNode* Node) -{ - // if shallow stop filling - if (MPE_PolyIsShallow(PolyContext, Node)) - { - return; - } - - MPE_PolyFill(PolyContext, Node); - - if (Node->Prev == PolyContext->Basin.LeftNode && Node->Next == PolyContext->Basin.RightNode) - { - return; - } - else if (Node->Prev == PolyContext->Basin.LeftNode) - { - uxx Orientation = MPE_PolyOrient2D(Node->Point, Node->Next->Point, Node->Next->Next->Point); - if (Orientation == MPEPolyOrientation_CW) - { - return; - } - Node = Node->Next; - } - else if (Node->Next == PolyContext->Basin.RightNode) - { - uxx Orientation = MPE_PolyOrient2D(Node->Point, Node->Prev->Point, Node->Prev->Prev->Point); - if (Orientation == MPEPolyOrientation_CCW) - { - return; - } - Node = Node->Prev; - } - else - { - // Continue with the neighbor Node with lowest Y Value - if (Node->Prev->Point->Y < Node->Next->Point->Y) - { - Node = Node->Prev; - } - else - { - Node = Node->Next; - } - } - - MPE_FillBasinReq(PolyContext, Node); -} - -internal_static -void MPE_FillBasin(MPEPolyContext* PolyContext, MPEPolyNode* Node) -{ - if (MPE_PolyOrient2D(Node->Point, Node->Next->Point, Node->Next->Next->Point) == MPEPolyOrientation_CCW) - { - PolyContext->Basin.LeftNode = Node->Next->Next; - } - else - { - PolyContext->Basin.LeftNode = Node->Next; - } - - // Find the bottom and Right Node - PolyContext->Basin.BottomNode = PolyContext->Basin.LeftNode; - while (PolyContext->Basin.BottomNode->Next && - PolyContext->Basin.BottomNode->Point->Y >= - PolyContext->Basin.BottomNode->Next->Point->Y) - { - PolyContext->Basin.BottomNode = PolyContext->Basin.BottomNode->Next; - } - if (PolyContext->Basin.BottomNode != PolyContext->Basin.LeftNode) - { - PolyContext->Basin.RightNode = PolyContext->Basin.BottomNode; - while (PolyContext->Basin.RightNode->Next && - PolyContext->Basin.RightNode->Point->Y < PolyContext->Basin.RightNode->Next->Point->Y) - { - PolyContext->Basin.RightNode = PolyContext->Basin.RightNode->Next; - } - if (PolyContext->Basin.RightNode != PolyContext->Basin.BottomNode) - { - PolyContext->Basin.Width = - PolyContext->Basin.RightNode->Point->X - PolyContext->Basin.LeftNode->Point->X; - PolyContext->Basin.LeftHighest = - PolyContext->Basin.LeftNode->Point->Y > PolyContext->Basin.RightNode->Point->Y; - - MPE_FillBasinReq(PolyContext, PolyContext->Basin.BottomNode); - } - } -} - -internal_static -void MPE_FillRightConcaveEdgeEvent(MPEPolyContext* PolyContext, MPEPolyEdge* Edge, MPEPolyNode* Node); - -internal_static -void MPE_FillRightConvexEdgeEvent(MPEPolyContext* PolyContext, MPEPolyEdge* Edge, MPEPolyNode* Node); - -internal_static -void MPE_FillLeftBelowEdgeEvent(MPEPolyContext* PolyContext, MPEPolyEdge* Edge, MPEPolyNode* Node); - -internal_static -void MPE_FillLeftConcaveEdgeEvent(MPEPolyContext* PolyContext, MPEPolyEdge* Edge, MPEPolyNode* Node); - -internal_static -void MPE_FillLeftConvexEdgeEvent(MPEPolyContext* PolyContext, MPEPolyEdge* Edge, MPEPolyNode* Node); - -internal_static -void MPE_FillRightBelowEdgeEvent(MPEPolyContext* PolyContext, MPEPolyEdge* Edge, MPEPolyNode* Node) -{ - if (Node->Point->X < Edge->P->X) - { - if (MPE_PolyOrient2D(Node->Point, Node->Next->Point, Node->Next->Next->Point) == MPEPolyOrientation_CCW) - { - // Concave - MPE_FillRightConcaveEdgeEvent(PolyContext, Edge, Node); - } - else - { - // Convex - MPE_FillRightConvexEdgeEvent(PolyContext, Edge, Node); - // Retry this one - MPE_FillRightBelowEdgeEvent(PolyContext, Edge, Node); - } - } -} - -internal_static -void MPE_FillRightAboveEdgeEvent(MPEPolyContext* PolyContext, MPEPolyEdge* Edge, MPEPolyNode* Node) -{ - while (Node->Next->Point->X < Edge->P->X) - { - // Check if Next Node is below the Edge - if (MPE_PolyOrient2D(Edge->Q, Node->Next->Point, Edge->P) == MPEPolyOrientation_CCW) - { - MPE_FillRightBelowEdgeEvent(PolyContext, Edge, Node); - } - else - { - Node = Node->Next; - } - } -} - -internal_static -void MPE_FillRightConcaveEdgeEvent(MPEPolyContext* PolyContext, MPEPolyEdge* Edge, MPEPolyNode* Node) -{ - MPE_PolyFill(PolyContext, Node->Next); - if (Node->Next->Point != Edge->P) - { - // Next above or below Edge? - if (MPE_PolyOrient2D(Edge->Q, Node->Next->Point, Edge->P) == MPEPolyOrientation_CCW) - { - // Below - if (MPE_PolyOrient2D(Node->Point, Node->Next->Point, Node->Next->Next->Point) == MPEPolyOrientation_CCW) - { - // Next is concave - MPE_FillRightConcaveEdgeEvent(PolyContext, Edge, Node); - } - else - { - // Next is convex - } - } - } -} - -internal_static -void MPE_FillRightConvexEdgeEvent(MPEPolyContext* PolyContext, MPEPolyEdge* Edge, MPEPolyNode* Node) -{ - // Next concave or convex? - if (MPE_PolyOrient2D(Node->Next->Point, Node->Next->Next->Point, - Node->Next->Next->Next->Point) == MPEPolyOrientation_CCW) - { - // Concave - MPE_FillRightConcaveEdgeEvent(PolyContext, Edge, Node->Next); - } - else - { - // Convex - // Next above or below Edge? - if (MPE_PolyOrient2D(Edge->Q, Node->Next->Next->Point, Edge->P) == MPEPolyOrientation_CCW) - { - // Below - MPE_FillRightConvexEdgeEvent(PolyContext, Edge, Node->Next); - } - else - { - // Above - } - } -} - -internal_static -void MPE_FillLeftAboveEdgeEvent(MPEPolyContext* PolyContext, MPEPolyEdge* Edge, MPEPolyNode* Node) -{ - while (Node->Prev->Point->X > Edge->P->X) - { - // Check if Next Node is below the Edge - if (MPE_PolyOrient2D(Edge->Q, Node->Prev->Point, Edge->P) == MPEPolyOrientation_CW) - { - MPE_FillLeftBelowEdgeEvent(PolyContext, Edge, Node); - } - else - { - Node = Node->Prev; - } - } -} - -internal_static -void MPE_FillEdgeEvent(MPEPolyContext* PolyContext, MPEPolyEdge* Edge, MPEPolyNode* Node) -{ - if (PolyContext->EdgeEvent.Right) - { - MPE_FillRightAboveEdgeEvent(PolyContext, Edge, Node); - } - else - { - MPE_FillLeftAboveEdgeEvent(PolyContext, Edge, Node); - } -} - -internal_static -void MPE_FillLeftBelowEdgeEvent(MPEPolyContext* PolyContext, MPEPolyEdge* Edge, MPEPolyNode* Node) -{ - if (Node->Point->X > Edge->P->X) - { - if (MPE_PolyOrient2D(Node->Point, Node->Prev->Point, Node->Prev->Prev->Point) == MPEPolyOrientation_CW) - { - // Concave - MPE_FillLeftConcaveEdgeEvent(PolyContext, Edge, Node); - } - else - { - // Convex - MPE_FillLeftConvexEdgeEvent(PolyContext, Edge, Node); - // Retry this one - MPE_FillLeftBelowEdgeEvent(PolyContext, Edge, Node); - } - } -} - -internal_static -void MPE_FillLeftConvexEdgeEvent(MPEPolyContext* PolyContext, MPEPolyEdge* Edge, MPEPolyNode* Node) -{ - // Next concave or convex? - if (MPE_PolyOrient2D(Node->Prev->Point, Node->Prev->Prev->Point, - Node->Prev->Prev->Prev->Point) == MPEPolyOrientation_CW) - { - // Concave - MPE_FillLeftConcaveEdgeEvent(PolyContext, Edge, Node->Prev); - } - else - { - // Convex - // Next above or below Edge? - if (MPE_PolyOrient2D(Edge->Q, Node->Prev->Prev->Point, Edge->P) == MPEPolyOrientation_CW) - { - // Below - MPE_FillLeftConvexEdgeEvent(PolyContext, Edge, Node->Prev); - } - else - { - // Above - } - } -} - -internal_static -void MPE_FillLeftConcaveEdgeEvent(MPEPolyContext* PolyContext, MPEPolyEdge* Edge, MPEPolyNode* Node) -{ - MPE_PolyFill(PolyContext, Node->Prev); - if (Node->Prev->Point != Edge->P) - { - // Next above or below Edge? - if (MPE_PolyOrient2D(Edge->Q, Node->Prev->Point, Edge->P) == MPEPolyOrientation_CW) - { - // Below - if (MPE_PolyOrient2D(Node->Point, Node->Prev->Point, Node->Prev->Prev->Point) == MPEPolyOrientation_CW) - { - // Next is concave - MPE_FillLeftConcaveEdgeEvent(PolyContext, Edge, Node); - } - else - { - // Next is convex - } - } - } -} - -internal_static -MPEPolyTriangle* MPE_NextFlipTriangle(MPEPolyContext* PolyContext, uxx Orientation, MPEPolyTriangle* Triangle, - MPEPolyTriangle* OtherTriangle, MPEPolyPoint* Point, i32 PointIndex, - i32 OtherPointIndex, i32* NewPointIndex) -{ - MPE_Assert(PointIndex >= 0 && OtherPointIndex >= 0); - MPEPolyTriangle* Result; - if (Orientation == MPEPolyOrientation_CCW) - { - // OtherTriangle is not crossing Edge after flip - // i32 EdgeIndex = MPE_EdgeIndex(OtherTriangle, Point, OtherPoint); - i32 EdgeIndex = OtherPointIndex; - // MPE_Assert(EdgeIndex == OtherPointIndex); - MPE_Assert(EdgeIndex != -1); - MPE_PolyMarkDelaunayEdge(OtherTriangle, EdgeIndex); - MPE_PolyLegalize(PolyContext, OtherTriangle); - MPE_ClearDelunayEdges(OtherTriangle); - Result = Triangle; - } - else - { - // Triangle is not crossing Edge after flip - // i32 EdgeIndex = PointIndex - OtherPointIndex; - // if (EdgeIndex < 0) - // { - // EdgeIndex = -EdgeIndex; - // } - // i32 EdgeIndex = MPE_EdgeIndex(Triangle, Point, OtherPoint); - i32 EdgeIndex = PointIndex; - MPE_Assert(EdgeIndex == PointIndex); - MPE_Assert(EdgeIndex != -1); - MPE_PolyMarkDelaunayEdge(Triangle, EdgeIndex); - MPE_PolyLegalize(PolyContext, Triangle); - MPE_ClearDelunayEdges(Triangle); - Result = OtherTriangle; - } - *NewPointIndex = MPE_PolyPointIndex(Result, Point); - - // MPE_Assert(*NewPointIndex >= 0); - MPE_Assert(Result->Points[*NewPointIndex] == Point); - return Result; -} - -internal_static MPE_INLINE -i32 MPE_NextFlipPoint(MPEPolyPoint* EdgeP, MPEPolyPoint* EdgeQ, MPEPolyPoint* OtherPoint, i32 OtherPointIndex) -{ - MPE_Assert(OtherPoint != EdgeP); - uxx Orientation = MPE_PolyOrient2D(EdgeQ, OtherPoint, EdgeP); - i32 Result; - if (Orientation == MPEPolyOrientation_CW) - { - Result = (i32)MPEPolyEdgeLUT[OtherPointIndex+1]; - } - else - { - MPE_Assert(Orientation == MPEPolyOrientation_CCW); - Result = (i32)MPEPolyEdgeLUT[OtherPointIndex+2]; - } - return Result; -} - - -internal_static -void MPE_FlipScanEdgeEvent(MPEPolyContext* PolyContext, MPEPolyPoint* EdgeP, MPEPolyPoint* EdgeQ, i32 EdgeQIndex, - MPEPolyTriangle* FlipTriangle, MPEPolyTriangle* Triangle, i32 PointIndex); - -internal_static -void MPE_EdgeEventPoints(MPEPolyContext* PolyContext, MPEPolyPoint* EdgeP, MPEPolyPoint* EdgeQ, i32 EdgeQIndex, - MPEPolyTriangle* Triangle, MPEPolyPoint* Point, i32 PointIndex); - -internal_static -void MPE_FlipEdgeEvent(MPEPolyContext* PolyContext, MPEPolyPoint* EdgeP, MPEPolyPoint* EdgeQ, i32 EdgeQIndex, MPEPolyTriangle* Triangle, - MPEPolyPoint* Point, i32 PointIndex) -{ - MPE_Assert(PointIndex >= 0 && EdgeQIndex >= 0); - MPE_Assert(Triangle->Points[PointIndex] == Point); - MPEPolyTriangle* OtherTriangle = MPE_PolyNeighborAcross(Triangle, Point); - MPE_Assert(OtherTriangle); - i32 OtherPointIndex; - MPEPolyPoint* CWPoint = Triangle->Points[MPEPolyEdgeLUT[PointIndex+2]]; - MPEPolyPoint* CCWPoint = Triangle->Points[MPEPolyEdgeLUT[PointIndex+1]]; - MPEPolyPoint* OtherPoint = MPE_PointCW(OtherTriangle, CWPoint, &OtherPointIndex); - - if (MPE_PolyInScanArea(Point, CCWPoint, CWPoint, OtherPoint)) - { - // Lets rotate shared Edge one vertex CW - MPE_PolyRotateTrianglePair(Triangle, Point, PointIndex, OtherTriangle, OtherPoint, OtherPointIndex); - MPE_PolyMapTriangleToNodes(PolyContext, Triangle); - MPE_PolyMapTriangleToNodes(PolyContext, OtherTriangle); - - if (Point == EdgeQ && OtherPoint == EdgeP) - { - if (EdgeQ == PolyContext->EdgeEvent.ConstrainedEdge->Q && - EdgeP == PolyContext->EdgeEvent.ConstrainedEdge->P) - { - MPE_PolyMarkConstrainedEdgePoints(Triangle, EdgeP, EdgeQ); - MPE_PolyMarkConstrainedEdgePoints(OtherTriangle, EdgeP, EdgeQ); - MPE_PolyLegalize(PolyContext, Triangle); - MPE_PolyLegalize(PolyContext, OtherTriangle); - } - else - { - // XXX: I think one of the Triangles should be legalized here? - } - } - else - { - MPE_Assert(OtherPoint != EdgeP && OtherPoint != EdgeQ && OtherPoint != Point); - - uxx Orientation = MPE_PolyOrient2D(EdgeQ, OtherPoint, EdgeP); - i32 NewPointIndex; - Triangle = MPE_NextFlipTriangle(PolyContext, Orientation, Triangle, OtherTriangle, Point, PointIndex, OtherPointIndex, &NewPointIndex); - MPE_FlipEdgeEvent(PolyContext, EdgeP, EdgeQ, EdgeQIndex, Triangle, Point, NewPointIndex); - } - } - else - { - // MPE_BREAK; - MPE_Assert(OtherPoint != EdgeP); - i32 NewPointIndex = MPE_NextFlipPoint(EdgeP, EdgeQ, OtherPoint, OtherPointIndex); - EdgeQIndex = MPE_PolyPointIndex(Triangle, EdgeQ); - MPE_FlipScanEdgeEvent(PolyContext, EdgeP, EdgeQ, EdgeQIndex, Triangle, OtherTriangle, NewPointIndex); - PointIndex = MPE_PolyPointIndex(Triangle, Point); - MPE_EdgeEventPoints(PolyContext, EdgeP, EdgeQ, EdgeQIndex, Triangle, Point, PointIndex); - } -} - -internal_static -void MPE_FlipScanEdgeEvent(MPEPolyContext* PolyContext, MPEPolyPoint* EdgeP, MPEPolyPoint* EdgeQ, i32 EdgeQIndex, - MPEPolyTriangle* FlipTriangle, MPEPolyTriangle* Triangle, i32 PointIndex) -{ - MPE_Assert(PointIndex >= 0 && EdgeQIndex >= 0); - MPE_Assert(EdgeQ == FlipTriangle->Points[EdgeQIndex]); - MPEPolyTriangle* OtherTriangle = Triangle->Neighbors[PointIndex]; - i32 OtherPointIndex; - MPEPolyPoint* CWPoint = Triangle->Points[MPEPolyEdgeLUT[PointIndex+2]]; - // MPEPolyPoint* CCWPoint = Triangle->Points[MPEPolyEdgeLUT[PointIndex+1]]; - MPEPolyPoint* FlipCWPoint = FlipTriangle->Points[MPEPolyEdgeLUT[EdgeQIndex+2]]; - MPEPolyPoint* FlipCCWPoint = FlipTriangle->Points[MPEPolyEdgeLUT[EdgeQIndex+1]]; - MPEPolyPoint* OtherPoint = MPE_PointCW(OtherTriangle, CWPoint, &OtherPointIndex); - - if (MPE_PolyInScanArea(EdgeQ, FlipCCWPoint, FlipCWPoint, OtherPoint)) - { - // flip with new edge OtherPoint->EdgeQ - MPE_FlipEdgeEvent(PolyContext, EdgeQ, OtherPoint, PointIndex, OtherTriangle, OtherPoint, OtherPointIndex); - // TODO: Actually I just figured out that it should be possible to - // improve this by getting the Next OtherTriangle and op before the the above - // flip and continue the flipScanEdgeEvent here - // set new OtherTriangle and op here and uxx back to inScanArea test - // also need to set a new FlipTriangle first - // Turns out at first glance that this is somewhat complicated - // so it will have to wait. - } - else - { - i32 NewPointIndex = MPE_NextFlipPoint(EdgeP, EdgeQ, OtherPoint, OtherPointIndex); - MPE_FlipScanEdgeEvent(PolyContext, EdgeP, EdgeQ, EdgeQIndex, FlipTriangle, OtherTriangle, NewPointIndex); - } -} - -internal_static -void MPE_PolyMapTriangleToNodes(MPEPolyContext* PolyContext, MPEPolyTriangle* Triangle) -{ - for (uxx TriangleIndex = 0; TriangleIndex < 3; ++TriangleIndex) - { - if (!Triangle->Neighbors[TriangleIndex]) - { - MPEPolyPoint* NextPoint = Triangle->Points[MPEPolyEdgeLUT[TriangleIndex+2]]; - MPEPolyNode* Node = MPE_LocatePoint(PolyContext, NextPoint); - if (Node) - { - Node->Triangle = Triangle; - } - } - } -} - -internal_static -void MPE_PolyFinalizeTriangles(MPEPolyContext* PolyContext, MPEPolyTriangle* StartTriangle) -{ - PolyContext->Triangles = MPE_PolyPush(PolyContext->Allocator, MPEPolyTriangle*); - - u32 TriangleCount = 0; - PolyContext->TempTriangles[TriangleCount++] = StartTriangle; - while (TriangleCount) - { - MPEPolyTriangle* TempTriangle = PolyContext->TempTriangles[--TriangleCount]; - if (!(TempTriangle->Flags & MPEPolyTriFlag_IsInterior)) - { - TempTriangle->Flags |= MPEPolyTriFlag_IsInterior; - PolyContext->Triangles[PolyContext->TriangleCount++] = TempTriangle; - - for (uxx NeighborIndex = 0; NeighborIndex < 3; ++NeighborIndex) - { - uxx BitMask = (uxx)MPEPolyTriFlag_ConstrainedEdge0 << NeighborIndex; - if (!(TempTriangle->Flags & BitMask)) - { - if (TempTriangle->Neighbors[NeighborIndex]) - { - PolyContext->TempTriangles[TriangleCount++] = TempTriangle->Neighbors[NeighborIndex]; - } - } - } - } - } -} - -internal_static -bxx MPE_PolyLegalize(MPEPolyContext* PolyContext, MPEPolyTriangle* Triangle) -{ - bxx Result = MPE_FALSE; - // To legalize a Triangle we start by finding if any of the three edges - // violate the Delaunay condition - for (u32 EdgeIndex = 0; EdgeIndex < 3; ++EdgeIndex) - { - if (Triangle->Flags & ((uxx)MPEPolyTriFlag_DelaunayEdge0 << EdgeIndex)) - { - continue; - } - - MPEPolyTriangle* OtherTriangle = Triangle->Neighbors[EdgeIndex]; - - if (OtherTriangle) - { - MPEPolyPoint* Point = Triangle->Points[EdgeIndex]; - i32 OtherPointIndex; - MPEPolyPoint* CWPoint = Triangle->Points[MPEPolyEdgeLUT[EdgeIndex+2]]; - MPEPolyPoint* OtherPoint = MPE_PointCW(OtherTriangle, CWPoint, &OtherPointIndex); - // If this is a Constrained Edge or a Delaunay Edge(only during recursive - // legalization) - // then we should not try to legalize - uxx CombinedMask = (((uxx)MPEPolyTriFlag_ConstrainedEdge0 << OtherPointIndex) | - ((uxx)MPEPolyTriFlag_DelaunayEdge0 << OtherPointIndex)); - if (OtherTriangle->Flags & CombinedMask) - { - uxx Mask = (uxx)MPEPolyTriFlag_ConstrainedEdge0 << EdgeIndex; - uxx NewFlag = (OtherTriangle->Flags & ((uxx)MPEPolyTriFlag_ConstrainedEdge0 << OtherPointIndex)) ? Mask : 0; - Triangle->Flags = (Triangle->Flags & ~Mask) | NewFlag; - continue; - } - - MPEPolyPoint* CCWPoint = Triangle->Points[MPEPolyEdgeLUT[EdgeIndex+1]]; - bxx IsInside = MPE_PolyInCircle(Point, CCWPoint, CWPoint, OtherPoint); - if (IsInside) - { - // Lets mark this shared edge as Delaunay - Triangle->Flags |= (uxx)MPEPolyTriFlag_DelaunayEdge0 << EdgeIndex; - OtherTriangle->Flags |= (uxx)MPEPolyTriFlag_DelaunayEdge0 << OtherPointIndex; - - // Lets rotate shared edge one vertex CW to legalize it - MPE_PolyRotateTrianglePair(Triangle, Point, (i32)EdgeIndex, OtherTriangle, OtherPoint, OtherPointIndex); - - // We now got one valid Delaunay Edge shared by two Triangles - // This gives us 4 new edges to check for Delaunay - - // Make sure that Triangle to Node mapping is done only one time for a - // specific Triangle - bxx NotLegalized = !MPE_PolyLegalize(PolyContext, Triangle); - if (NotLegalized) - { - MPE_PolyMapTriangleToNodes(PolyContext, Triangle); - } - - NotLegalized = !MPE_PolyLegalize(PolyContext, OtherTriangle); - if (NotLegalized) - { - MPE_PolyMapTriangleToNodes(PolyContext, OtherTriangle); - } - - // Reset the Delaunay edges, since they only are valid Delaunay edges - // until we add a new Triangle or MPEPolyPoint. - // XXX: need to think about this. Can these edges be tried after we - // return to previous recursive level? - Triangle->Flags &= ~(uxx)MPEPolyTriFlag_DelaunayEdge0 << EdgeIndex; - OtherTriangle->Flags &= ~(uxx)MPEPolyTriFlag_DelaunayEdge0 << OtherPointIndex; - - // If Triangle have been legalized no need to check the other edges - // since - // the recursive legalization will handles those so we can end here. - Result = MPE_TRUE; - break; - } - } - } - return Result; -} - -internal_static -void MPE_EdgeEventPoints(MPEPolyContext* PolyContext, MPEPolyPoint* EdgeP, MPEPolyPoint* EdgeQ, i32 EdgeQIndex, - MPEPolyTriangle* Triangle, MPEPolyPoint* Point, i32 PointIndex) -{ - if (MPE_IsEdgeSideOfTriangle(Triangle, EdgeP, EdgeQ)) - { - return; - } - MPE_Assert(PointIndex >= 0 && EdgeQIndex >= 0); - MPE_Assert(Triangle->Points[PointIndex] == Point); - i32 Point1Index = (i32)MPEPolyEdgeLUT[PointIndex+1]; - MPEPolyPoint* Point1 = Triangle->Points[Point1Index]; - uxx Orientation1 = MPE_PolyOrient2D(EdgeQ, Point1, EdgeP); - if (Orientation1 == MPEPolyOrientation_Collinear) - { - if (MPE_PolyContainsPoints(Triangle, EdgeQ, Point1)) - { - MPE_PolyMarkConstrainedEdgePoints(Triangle, EdgeQ, Point1); - // We are modifying the maybe it would be better to - // not change the given and just keep a variable for the new - // - PolyContext->EdgeEvent.ConstrainedEdge->Q = Point1; - Triangle = MPE_PolyNeighborAcross(Triangle, Point); - MPE_EdgeEventPoints(PolyContext, EdgeP, Point1, Point1Index, Triangle, Point1, Point1Index); - } - else - { - MPE_InvalidCodePath; - } - return; - } - - i32 Point2Index = (i32)MPEPolyEdgeLUT[PointIndex+2]; - MPEPolyPoint* Point2 = Triangle->Points[Point2Index]; - uxx Orientation2 = MPE_PolyOrient2D(EdgeQ, Point2, EdgeP); - if (Orientation2 == MPEPolyOrientation_Collinear) - { - if (MPE_PolyContainsPoints(Triangle, EdgeQ, Point2)) - { - MPE_PolyMarkConstrainedEdgePoints(Triangle, EdgeQ, Point2); - // We are modifying the maybe it would be better to - // not change the given and just keep a variable for the new - // - PolyContext->EdgeEvent.ConstrainedEdge->Q = Point2; - Triangle = MPE_PolyNeighborAcross(Triangle, Point); - MPE_EdgeEventPoints(PolyContext, EdgeP, Point2, Point2Index, Triangle, Point2, Point2Index); - } - else - { - MPE_InvalidCodePath; - } - return; - } - - if (Orientation1 == Orientation2) - { - // Need to decide if we are rotating CW or CCW to get to a Triangle - // that will cross edge - MPEPolyTriangle* NewTriangle; - i32 NewPointIndex = (i32)MPEPolyEdgeLUT[PointIndex+(i32)Orientation1+1]; - NewTriangle = Triangle->Neighbors[NewPointIndex]; - MPE_Assert(NewTriangle); - NewPointIndex = MPE_PolyPointIndex(NewTriangle, Point); - MPE_Assert(NewPointIndex == MPE_PolyPointIndex(NewTriangle, Point)); - MPE_EdgeEventPoints(PolyContext, EdgeP, EdgeQ, EdgeQIndex, NewTriangle, Point, NewPointIndex); - } - else - { - // This Triangle crosses so lets flippin start! - MPE_FlipEdgeEvent(PolyContext, EdgeP, EdgeQ, EdgeQIndex, Triangle, Point, PointIndex); - } -} - -internal_static -void MPE_PolyAddEdge(MPEPolyContext* PolyContext) -{ - MPEPolyPoint* Points = PolyContext->PointsPool + PolyContext->PointCount; - u32 PointCount = PolyContext->PointPoolCount - PolyContext->PointCount; - MPE_Assert(PointCount && PointCount < PolyContext->MaxPointCount); - for (uxx PointIndex = 0; PointIndex < PointCount; ++PointIndex) - { - uxx NextPointIndex = PointIndex < PointCount - 1 ? PointIndex + 1 : 0; - MPEPolyPoint* A = Points + PointIndex; - MPEPolyPoint* B = Points + NextPointIndex; - PolyContext->Points[PolyContext->PointCount++] = A; - MPEPolyEdge* Edge = MPE_PolyPush(PolyContext->Allocator, MPEPolyEdge); - - if ((A->Y > B->Y) || - ((B->Y - A->Y) < MPE_POLY2TRI_EPSILON && (A->X > B->X))) - { - Edge->Q = A; - Edge->P = B; - } - else - { - Edge->P = A; - Edge->Q = B; - } - - MPE_Assert(fabsf(A->Y - B->Y) > MPE_POLY2TRI_EPSILON || - fabsf(A->X - B->X) > MPE_POLY2TRI_EPSILON); - - if (Edge->Q->FirstEdge) - { - MPEPolyEdge* LastEdge = Edge->Q->FirstEdge; - while(LastEdge && LastEdge->Next) - { - LastEdge = LastEdge->Next; - } - LastEdge->Next = Edge; - } - else - { - Edge->Q->FirstEdge = Edge; - } - } -} - - -internal_static MPE_INLINE -void MPE_PolyAddHole(MPEPolyContext* PolyContext) -{ - MPE_PolyAddEdge(PolyContext); -} - -internal_static MPE_INLINE -void MPE_PolyAddPoints(MPEPolyContext* PolyContext, MPEPolyPoint* Points, u32 PointCount) -{ - for (uxx PointIndex = 0; PointIndex < PointCount; ++PointIndex) - { - MPEPolyPoint* Point = Points + PointIndex; - PolyContext->Points[PolyContext->PointCount++] = Point; - } -} - - -//SECTION: Sort - -#define MPE_POLY_COMPARE(A, B) \ - (((A)->Y < (B)->Y) || (((A)->Y - (B)->Y) < MPE_POLY2TRI_EPSILON && ((A)->X < (B)->X))) - -#ifdef MPE_POLY2TRI_USE_CUSTOM_SORT -internal_static -void MPE_PolySort(MPEPolyPoint** Points, MPEPolyPoint** Temp, u32 Count) -{ - MPE_Assert(Count); - if (Count <= 1) - { - - } - else if (Count == 2) - { - MPEPolyPoint* A = Points[0]; - MPEPolyPoint* B = Points[1]; - if ((A->Y > B->Y) || - ((B->Y - A->Y) < MPE_POLY2TRI_EPSILON && A->X >= B->X)) - { - MPEPolyPoint* Swap = A; - Points[0] = B; - Points[1] = Swap; - } - } - else - { - u32 Half0 = Count / 2; - u32 Half1 = Count - Half0; - - MPEPolyPoint** InHalf0 = Points; - MPEPolyPoint** InHalf1 = Points + Half0; - MPEPolyPoint** End = Points + Count; - - MPE_PolySort(InHalf0, Temp, Half0); - MPE_PolySort(InHalf1, Temp, Half1); - - MPEPolyPoint** ReadHalf0 = InHalf0; - MPEPolyPoint** ReadHalf1 = InHalf1; - - //NOTE: Don't merge if two halves are already sorted - if (InHalf1[-1]->Y > InHalf1[0]->Y) - { - MPEPolyPoint** Out = Temp; - for (u32 WriteIndex = 0; WriteIndex < Count; ++WriteIndex) - { - if(ReadHalf0 == InHalf1) - { - *Out++ = *ReadHalf1++; - } - else if (ReadHalf1 == End) - { - *Out++ = *ReadHalf0++; - } - else - { - MPEPolyPoint* A = ReadHalf0[0]; - MPEPolyPoint* B = ReadHalf1[0]; - if (MPE_POLY_COMPARE(A, B)) - { - *Out++ = *ReadHalf0++; - } - else - { - *Out++ = *ReadHalf1++; - } - } - } - MPE_MemoryCopy(Points, Temp, sizeof(*Points) * Count); - } - } -} -#else -internal_static -i32 MPE_PolySortCompare(MPEPolyPoint** A, MPEPolyPoint** B) -{ - i32 Result; - if ((*A)->Y < (*B)->Y) - { - Result = -1; - } - else if (((*A)->Y - (*B)->Y) < MPE_POLY2TRI_EPSILON) - { - if ((*A)->X < (*B)->X) - { - Result = -1; - } - else - { - Result = 1; - } - } - else - { - Result = 1; - } - return Result; -} -#endif - -internal_static -void MPE_PolyTriangulate(MPEPolyContext* PolyContext) -{ - MPE_Assert(PolyContext->PointCount); - u32 PointCount = PolyContext->PointCount; - //NOTE: Init triangulation - { - poly_float Xmax = PolyContext->Points[0]->X; - poly_float Xmin = PolyContext->Points[0]->X; - poly_float Ymax = PolyContext->Points[0]->Y; - poly_float Ymin = PolyContext->Points[0]->Y; - //TODO: Calculate min and max during sort - for (uxx PointIndex = 0; PointIndex < PolyContext->PointCount; ++PointIndex) - { - MPEPolyPoint* Point = PolyContext->Points[PointIndex]; - if (Point->X > Xmax) - { - Xmax = Point->X; - } - if (Point->X < Xmin) - { - Xmin = Point->X; - } - if (Point->Y > Ymax) - { - Ymax = Point->Y; - } - if (Point->Y < Ymin) - { - Ymin = Point->Y; - } - } -#define MPE_INITIAL_TRIANGLE_FACTOR (poly_float)0.3f - poly_float Dx = MPE_INITIAL_TRIANGLE_FACTOR * (Xmax - Xmin); - poly_float Dy = MPE_INITIAL_TRIANGLE_FACTOR * (Ymax - Ymin); - MPEPolyPoint* Head = MPE_PolyPush(PolyContext->Allocator, MPEPolyPoint); - Head->X = Xmax + Dx; - Head->Y = Ymin - Dy; - MPEPolyPoint* Tail = MPE_PolyPush(PolyContext->Allocator, MPEPolyPoint); - Tail->X = Xmin - Dx; - Tail->Y = Ymin - Dy; - PolyContext->HeadPoint = Head; - PolyContext->TailPoint = Tail; - } - - //NOTE: Sort points - { -#ifdef MPE_POLY2TRI_USE_CUSTOM_SORT - umm BeforeRollback = PolyContext->Allocator.Used; - MPEPolyPoint** Temp = MPE_PolyPushArray(PolyContext->Allocator, MPEPolyPoint*, PointCount); - MPE_PolySort(PolyContext->Points, Temp, PointCount); - MPE_MemorySet(PolyContext->Allocator.Memory+BeforeRollback, 0, PolyContext->Allocator.Used - BeforeRollback); - PolyContext->Allocator.Used = BeforeRollback; -#else - qsort(PolyContext->Points, PointCount, sizeof(MPEPolyPoint*), (int(*)(const void*, const void*))MPE_PolySortCompare); -#endif - } - - //NOTE: Create advancing front - { - MPEPolyTriangle* Triangle = MPE_PushTriangle(PolyContext, PolyContext->Points[0], PolyContext->TailPoint, PolyContext->HeadPoint); - - MPEPolyNode* Head = MPE_PolyNode(PolyContext, Triangle->Points[1], Triangle); - MPEPolyNode* Middle = MPE_PolyNode(PolyContext, Triangle->Points[0], Triangle); - MPEPolyNode* Tail = MPE_PolyNode(PolyContext, Triangle->Points[2], 0); - - PolyContext->HeadNode = PolyContext->SearchNode = Head; - PolyContext->TailNode = Tail; - Head->Next = Middle; - Middle->Next = Tail; - Middle->Prev = Head; - Tail->Prev = Middle; - } - - //NOTE: Sweep points - { - for (uxx PointIndex = 1; PointIndex < PolyContext->PointCount; ++PointIndex) - { - MPEPolyPoint* Point = PolyContext->Points[PointIndex]; - MPEPolyNode* Node; - MPEPolyNode* NewNode; - { - Node = PolyContext->SearchNode; - if (Point->X < Node->Value) - { - while ((Node = Node->Prev)) - { - if (Point->X >= Node->Value) - { - PolyContext->SearchNode = Node; - break; - } - } - } - else - { - while ((Node = Node->Next)) - { - if (Point->X < Node->Value) - { - PolyContext->SearchNode = Node->Prev; - Node = Node->Prev; - break; - } - } - } - } - - //NOTE: New front triangle - { - MPEPolyTriangle* NewTriangle = MPE_PushTriangle(PolyContext, Point, Node->Point, Node->Next->Point); - MPE_PolyMarkNeighborTri(NewTriangle, Node->Triangle); - - NewNode = MPE_PolyNode(PolyContext, Point, 0); - NewNode->Next = Node->Next; - NewNode->Prev = Node; - Node->Next->Prev = NewNode; - Node->Next = NewNode; - - if (!MPE_PolyLegalize(PolyContext, NewTriangle)) - { - MPE_PolyMapTriangleToNodes(PolyContext, NewTriangle); - } - MPE_Assert(NewNode->Triangle == NewTriangle); - - // Only need to check +epsilon since MPEPolyPoint never have smaller - // X Value than Node due to how we fetch nodes from the front - if (Point->X <= Node->Point->X + MPE_POLY2TRI_EPSILON) - { - MPE_PolyFill(PolyContext, Node); - } - - //NOTE: FillAdvancingFront - { - // Fill Right holes - MPEPolyNode* NextNode = NewNode->Next; - - while (NextNode->Next) - { - // if HoleAngle exceeds 90 degrees then break. - if (MPE_LargeHole_DontFill(NextNode)) - { - break; - } - MPE_PolyFill(PolyContext, NextNode); - NextNode = NextNode->Next; - } - - - // Fill left holes - NextNode = NewNode->Prev; - - while (NextNode->Prev) - { - // if HoleAngle exceeds 90 degrees then break. - if (MPE_LargeHole_DontFill(NextNode)) - { - break; - } - MPE_PolyFill(PolyContext, NextNode); - NextNode = NextNode->Prev; - } - - // Fill Right basins - if (NewNode->Next && NewNode->Next->Next) - { - if (MPE_PolyShouldFillBasin(NewNode)) - { - MPE_FillBasin(PolyContext, NewNode); - } - } - } - } - for (MPEPolyEdge* Edge = Point->FirstEdge; Edge; Edge = Edge->Next) - { - //NOTE: Edge event - PolyContext->EdgeEvent.ConstrainedEdge = Edge; - PolyContext->EdgeEvent.Right = (Edge->P->X > Edge->Q->X); - - if (!MPE_IsEdgeSideOfTriangle(NewNode->Triangle, Edge->P, Edge->Q)) - { - // For now we will do all needed filling - // TODO: integrate with flip process might give some better performance - // but for now this avoid the issue with cases that needs both flips and - // fills - MPE_FillEdgeEvent(PolyContext, Edge, NewNode); - i32 EdgeQIndex = MPE_PolyPointIndex(NewNode->Triangle, Edge->Q); - MPE_EdgeEventPoints(PolyContext, Edge->P, Edge->Q, EdgeQIndex, NewNode->Triangle, Edge->Q, EdgeQIndex); - } - } - } - } - - //NOTE: Finalize polygon - { - MPEPolyTriangle* Triangle = PolyContext->HeadNode->Next->Triangle; - MPEPolyPoint* Point = PolyContext->HeadNode->Next->Point; - MPEPolyTriangle* PrevValid = Triangle; - while (!MPE_GetConstrainedEdgeCW(Triangle, Point)) - { - Triangle = MPE_NeighborCCW(Triangle, Point); - if (!Triangle) { Triangle = PrevValid; break; } - PrevValid = Triangle; - } - MPE_PolyFinalizeTriangles(PolyContext, Triangle); - } -} - -internal_static -b32 MPE_PolyInitContext(MPEPolyContext* PolyContext, void* Memory, u32 MaxPointCount) -{ - if (Memory && MaxPointCount) - { - umm MemorySize = MPE_PolyMemoryRequired(MaxPointCount); - MaxPointCount = MaxPointCount + MPE_POLY2TRI_POINT_COUNT_EPSILON; - u32 MaxTrianglePoolCount = MaxPointCount*2; - - MPE_MemorySet(PolyContext, 0, sizeof(*PolyContext)); - // Align to 8 bytes - umm AlignmentOffset = 0; - u8* MemoryBytes = (u8*)Memory; - umm MemoryAddress = (umm)(MemoryBytes); - if(MemoryAddress & 0x7) - { - AlignmentOffset = (0x8) - (MemoryAddress & 0x7); - } - MPE_Assert(AlignmentOffset == 0); - PolyContext->Memory = Memory; - PolyContext->Allocator.Size = MemorySize-AlignmentOffset; - PolyContext->Allocator.Memory = (u8*)Memory + AlignmentOffset; - - PolyContext->MaxPointCount = MaxPointCount; - PolyContext->PointsPool = MPE_PolyPushArray(PolyContext->Allocator, MPEPolyPoint, MaxPointCount); - PolyContext->Points = MPE_PolyPushArray(PolyContext->Allocator, MPEPolyPoint*, MaxPointCount); - PolyContext->TrianglePool = MPE_PolyPushArray(PolyContext->Allocator, MPEPolyTriangle, MaxTrianglePoolCount); - PolyContext->TempTriangles = MPE_PolyPushArray(PolyContext->Allocator, MPEPolyTriangle*, MaxTrianglePoolCount); - PolyContext->Nodes = MPE_PolyPushArray(PolyContext->Allocator, MPEPolyNode, MaxPointCount); - PolyContext->Valid = MPE_TRUE; - } - else - { - PolyContext->Valid = MPE_FALSE; - } - - return PolyContext->Valid; -} - -internal_static -umm MPE_PolyMemoryRequired(u32 MaxPointCount) -{ - MaxPointCount += MPE_POLY2TRI_POINT_COUNT_EPSILON; - umm EstimatedSizePerPoint = sizeof(MPEPolyEdge) + - sizeof(MPEPolyPoint) + - sizeof(MPEPolyPoint*) + - sizeof(MPEPolyPoint*) + - sizeof(MPEPolyNode) + - sizeof(MPEPolyTriangle) * 2 + - sizeof(MPEPolyTriangle*) * 2 + - sizeof(MPEPolyTriangle*) * 2; - umm Result = EstimatedSizePerPoint * MaxPointCount + 0x8; - return Result; -} - -#endif // MPE_POLY2TRI_IMPLEMENTATION diff --git a/components/darkforces/tfe/TFE_Polygon/polygon.h b/components/darkforces/tfe/TFE_Polygon/polygon.h deleted file mode 100644 index 2c41d7ee..00000000 --- a/components/darkforces/tfe/TFE_Polygon/polygon.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once -#include -#include -#define MAX_POLYGON_VTX 1024 -#define MAX_CONVEX_POLYGONS 1024 - -// Handling complex polygons. -struct Polygon -{ - s32 vtxCount; - Vec2f vtx[MAX_POLYGON_VTX]; -}; - -struct Triangle -{ - Vec2f vtx[3]; -}; - -// TFE_Polygon uses the "Ear-clipping" algorithm to convert concave polygons into a set of convex polygons suitable for rendering. -// See https://www.geometrictools.com/Documentation/TriangulationByEarClipping.pdf for more information on the core algorithm. -// Note the geometrictools implementation was not used. -namespace TFE_Polygon -{ - // Decompose a concave polygon with holes into convex polygons. - // A contour is a complete polygon. If it is a hole than the winding should be reversed compared to the outer polygon. - Triangle* decomposeComplexPolygon(u32 contourCount, const Polygon* contours, u32* outConvexPolyCount); - f32 signedArea(u32 vertexCount, const Vec2f* vertices); - - bool init(); - void shutdown(); -} diff --git a/components/darkforces/tfe/TFE_PostProcess/blit.h b/components/darkforces/tfe/TFE_PostProcess/blit.h deleted file mode 100644 index 46d20185..00000000 --- a/components/darkforces/tfe/TFE_PostProcess/blit.h +++ /dev/null @@ -1,47 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// GPU Based blit. -////////////////////////////////////////////////////////////////////// - -#include -#include "postprocesseffect.h" - -enum BlitFeature -{ - BLIT_GPU_COLOR_CONVERSION = (1 << 0), - BLIT_GPU_COLOR_CORRECTION = (1 << 1), - BLIT_BLOOM = (1 << 2), - - BLIT_FEATURE_COUNT = 3, - BLIT_FEATURE_COMBO_COUNT = 6, -}; - -struct ColorCorrection; - -class Blit : public PostProcessEffect -{ -public: - // Load shaders, setup geometry. - bool init() override; - // Free GPU assets. - void destroy() override; - - // Execute the post process. - void setEffectState() override; - - // Enable various features. - void enableFeatures(u32 features); - void disableFeatures(u32 features); - bool featureEnabled(u32 feature) const; - - void setColorCorrectionParameters(const ColorCorrection* parameters); - -private: - u32 m_features = 0; - Shader m_featureShaders[BLIT_FEATURE_COMBO_COUNT]; - Vec4f m_colorCorrectParam; - s32 m_colorCorrectVarId; - - void setupShader(); - bool buildShaders(); -}; diff --git a/components/darkforces/tfe/TFE_PostProcess/bloomDownsample.h b/components/darkforces/tfe/TFE_PostProcess/bloomDownsample.h deleted file mode 100644 index 04898cbb..00000000 --- a/components/darkforces/tfe/TFE_PostProcess/bloomDownsample.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// GPU Based blit. -////////////////////////////////////////////////////////////////////// - -#include -#include "postprocesseffect.h" - -class BloomDownsample : public PostProcessEffect -{ -public: - // Load shaders, setup geometry. - bool init() override; - // Free GPU assets. - void destroy() override; - - // Execute the post process. - void setEffectState() override; - -private: - Shader m_shaderInternal; - - void setupShader(); - bool buildShaders(); -}; diff --git a/components/darkforces/tfe/TFE_PostProcess/bloomMerge.h b/components/darkforces/tfe/TFE_PostProcess/bloomMerge.h deleted file mode 100644 index cf131c64..00000000 --- a/components/darkforces/tfe/TFE_PostProcess/bloomMerge.h +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// GPU Based blit. -////////////////////////////////////////////////////////////////////// - -#include -#include "postprocesseffect.h" - -class BloomMerge : public PostProcessEffect -{ -public: - // Load shaders, setup geometry. - bool init() override; - // Free GPU assets. - void destroy() override; - - // Execute the post process. - void setEffectState() override; - -private: - Shader m_shaderInternal; - s32 m_bloomSpreadId; - - void setupShader(); - bool buildShaders(); -}; diff --git a/components/darkforces/tfe/TFE_PostProcess/bloomThreshold.h b/components/darkforces/tfe/TFE_PostProcess/bloomThreshold.h deleted file mode 100644 index 987b68ab..00000000 --- a/components/darkforces/tfe/TFE_PostProcess/bloomThreshold.h +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// GPU Based blit. -////////////////////////////////////////////////////////////////////// - -#include -#include "postprocesseffect.h" - -class BloomThreshold : public PostProcessEffect -{ -public: - // Load shaders, setup geometry. - bool init() override; - // Free GPU assets. - void destroy() override; - - // Execute the post process. - void setEffectState() override; - -private: - Shader m_shaderInternal; - s32 m_bloomIntensityId; - - void setupShader(); - bool buildShaders(); -}; diff --git a/components/darkforces/tfe/TFE_PostProcess/overlay.h b/components/darkforces/tfe/TFE_PostProcess/overlay.h deleted file mode 100644 index 9b52703f..00000000 --- a/components/darkforces/tfe/TFE_PostProcess/overlay.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// GPU Based blit. -////////////////////////////////////////////////////////////////////// - -#include -#include "postprocesseffect.h" - -class Overlay : public PostProcessEffect -{ -public: - // Load shaders, setup geometry. - bool init() override; - // Free GPU assets. - void destroy() override; - - // Execute the post process. - void setEffectState() override; - -public: - s32 m_tintId; - s32 m_uvOffsetSizeId; - -private: - Shader m_overlayShader; - bool buildShaders(); -}; diff --git a/components/darkforces/tfe/TFE_PostProcess/postprocess.h b/components/darkforces/tfe/TFE_PostProcess/postprocess.h deleted file mode 100644 index 9194b461..00000000 --- a/components/darkforces/tfe/TFE_PostProcess/postprocess.h +++ /dev/null @@ -1,53 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// TFE Post Process System -// Post Process effects are appended and executing in order. -// Effects can have an input image and output render target and can -// be chained together. -////////////////////////////////////////////////////////////////////// - -#include -#include -#include -#include - -class PostProcessEffect; -struct PostEffectInput; - -struct OverlayImage -{ - TextureGpu* texture; - // Area of the texture to draw as an overlay. - u32 overlayWidth; - u32 overlayHeight; - u32 overlayX; - u32 overlayY; -}; - -typedef u32 OverlayID; - -namespace TFE_PostProcess -{ - bool init(); - void destroy(); - - void clearEffectStack(); - void appendEffect(PostProcessEffect* effect, u32 inputCount, const PostEffectInput* inputs, RenderTargetHandle output = nullptr, s32 x = 0, s32 y = 0, s32 width = 0, s32 height = 0, bool forceLinearFilter = false); - - // Overlays - images drawn on top after the post process stack has executed. - OverlayID addOverlayTexture(OverlayImage* overlay, f32* tint, f32 screenX, f32 screenY, f32 scale = 1.0f); - const OverlayImage* getOverlayImage(OverlayID id); - void setOverlayImage(OverlayID id, const OverlayImage* image); - - void modifyOverlay(OverlayID id, f32* tint, f32 screenX, f32 screenY, f32 scale = 1.0f); - void getOverlaySettings(OverlayID id, f32* tint, f32* screenX, f32* screenY, f32* scale); - void enableOverlay(OverlayID id, bool enable); - void removeOverlay(OverlayID id); - void removeAllOverlays(); - - // Execute Post effects and overlays. - void execute(); - - // Internal - void drawRectangle(); -} diff --git a/components/darkforces/tfe/TFE_PostProcess/postprocesseffect.h b/components/darkforces/tfe/TFE_PostProcess/postprocesseffect.h deleted file mode 100644 index abed1135..00000000 --- a/components/darkforces/tfe/TFE_PostProcess/postprocesseffect.h +++ /dev/null @@ -1,44 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// GPU Based blit. -////////////////////////////////////////////////////////////////////// - -#include -#include - -class TextureGpu; -class DynamicTexture; - -enum PostEffectInputType -{ - PTYPE_TEXTURE = 0, - PTYPE_DYNAMIC_TEX, - PTYPE_COUNT -}; - -struct PostEffectInput -{ - PostEffectInputType type; - union - { - void* ptr; // This void pointer is here so that array initializers work in C++. - TextureGpu* tex; // Standard GPU texture. - DynamicTexture* dyntex; // Dynamic GPU texture. - }; -}; - -class PostProcessEffect -{ -public: - // Load shaders, setup geometry. - virtual bool init() = 0; - // Free GPU assets. - virtual void destroy() = 0; - - // Set the post process render state. - virtual void setEffectState() = 0; - -public: - Shader* m_shader; - s32 m_scaleOffsetId; -}; diff --git a/components/darkforces/tfe/TFE_RenderBackend/dynamicTexture.h b/components/darkforces/tfe/TFE_RenderBackend/dynamicTexture.h deleted file mode 100644 index cc89a798..00000000 --- a/components/darkforces/tfe/TFE_RenderBackend/dynamicTexture.h +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Dynamic multi-buffered texture. -////////////////////////////////////////////////////////////////////// - -#include -#include -#include - -enum DynamicTexFormat -{ - DTEX_RGBA8 = 0, - DTEX_R8, - DTEX_COUNT -}; - -class DynamicTexture -{ -public: - DynamicTexture() : m_bufferCount(0), m_readBuffer(0), m_writeBuffer(0), m_format(DTEX_RGBA8), m_textures(nullptr), m_stagingBuffers(nullptr) {} - ~DynamicTexture(); - - bool create(u32 width, u32 height, u32 bufferCount, DynamicTexFormat format = DTEX_RGBA8); - void resize(u32 newWidth, u32 newHeight); - bool changeBufferCount(u32 newBufferCount, bool forceRealloc=false); - - void update(const void* imageData, size_t size); - void bind(u32 slot = 0) const; - - inline const TextureGpu* getTexture() const { return m_textures[m_readBuffer]; } - inline u32 getWidth() const { return m_width; } - inline u32 getHeight() const { return m_height; } - -private: - void freeBuffers(); - - u32 m_bufferCount; - u32 m_readBuffer; - u32 m_writeBuffer; - u32 m_width; - u32 m_height; - DynamicTexFormat m_format; - - TextureGpu** m_textures; - u32* m_stagingBuffers; - - static std::vector s_tempBuffer; - static u32 s_alignment; -}; diff --git a/components/darkforces/tfe/TFE_RenderBackend/indexBuffer.h b/components/darkforces/tfe/TFE_RenderBackend/indexBuffer.h deleted file mode 100644 index 7ff9a244..00000000 --- a/components/darkforces/tfe/TFE_RenderBackend/indexBuffer.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wrapper for OpenGL textures that expose the limited set of -// required functionality. -////////////////////////////////////////////////////////////////////// - -#include - -class IndexBuffer -{ -public: - IndexBuffer() : m_stride(0), m_count(0), m_dynamic(false), m_gpuHandle(0) {} - ~IndexBuffer(); - - bool create(u32 count, u32 stride, bool dynamic, void* initData = nullptr); - void destroy(); - - void update(const void* buffer, size_t size); - // bind() returns the size type that should be used in draw commands. - u32 bind(); - void unbind(); - - inline u32 getHandle() const { return m_gpuHandle; } - -private: - u32 m_stride; - u32 m_count; - u32 m_size; - u32 m_gpuHandle; - bool m_dynamic; -}; diff --git a/components/darkforces/tfe/TFE_RenderBackend/renderBackend.h b/components/darkforces/tfe/TFE_RenderBackend/renderBackend.h deleted file mode 100644 index fe16b3b2..00000000 --- a/components/darkforces/tfe/TFE_RenderBackend/renderBackend.h +++ /dev/null @@ -1,170 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine GPU Library -// This handles low level access to the GPU device and is used by -// both the software and hardware rendering systems in order to -// provide basic access. -// -// Renderers will create a virtual display or render target. -// swap() handles blitting this result and then rendering UI -// on top. -////////////////////////////////////////////////////////////////////// - -#include -#include -#include - -enum WindowFlags -{ - WINFLAG_FULLSCREEN = 1 << 0, - WINFLAG_VSYNC = 1 << 1, -}; - -enum DisplayMode -{ - DMODE_STRETCH = 0, // Stretch the virtual display over the whole window, useful for widescreen. - DMODE_ASPECT_CORRECT, // Letter/Pillar box to maintain the correct aspect ratio. - DMODE_COUNT -}; - -struct WindowState -{ - char name[256]; - u32 width; - u32 height; - u32 baseWindowWidth; - u32 baseWindowHeight; - u32 monitorWidth; - u32 monitorHeight; - u32 flags; - f32 refreshRate; -}; - -struct DisplayInfo -{ - u32 width; - u32 height; - f32 refreshRate; //0.0 if vsync not enabled. -}; - -enum VirtualDisplayFlags -{ - VDISP_WIDESCREEN = (1 << 0), // Widescreen output - VDISP_ASYNC_FRAMEBUFFER = (1 << 1), // Asynchronous framebuffer upload, trades latency for performance. - VDISP_GPU_COLOR_CONVERT = (1 << 2), // Use Gpu color conversion, reducing upload bandwidth for a small GPU cost. - VDISP_RENDER_TARGET = (1 << 3), // Create a render target for GPU rendering. - VDISP_DEFAULT = (VDISP_ASYNC_FRAMEBUFFER | VDISP_GPU_COLOR_CONVERT) -}; - -struct VirtualDisplayInfo -{ - DisplayMode mode = DMODE_ASPECT_CORRECT; // Output display mode. - u32 flags = VDISP_DEFAULT; // See VirtualDisplayFlags. - - u32 width; // full width - u32 height; // full height - u32 widthUi; // width for 2D game UI and cutscenes. - u32 width3d; // width for 3D drawing. - - // offset3d = (width - width3d)>>1 - // offsetUi = (width - widthUi)>>1 - // stride = width -}; - -struct ColorCorrection -{ - f32 brightness; - f32 contrast; - f32 saturation; - f32 gamma; -}; - -struct MonitorInfo -{ - s32 x, y; - s32 w, h; -}; - -typedef void* RenderTargetHandle; -class TextureGpu; - -namespace TFE_RenderBackend -{ - bool init(const WindowState& state); - void destroy(); - bool getVsyncEnabled(); - void enableVsync(bool enable); - - void setClearColor(const f32* color); - void swap(bool blitVirtualDisplay); - void queueScreenshot(const char* screenshotPath); - void startGifRecording(const char* path); - void stopGifRecording(); - void captureScreenToMemory(u32* mem); - - void resize(s32 width, s32 height); - s32 getDisplayCount(); - s32 getDisplayIndex(s32 x, s32 y); - bool getDisplayMonitorInfo(s32 displayIndex, MonitorInfo* monitorInfo); - f32 getDisplayRefreshRate(); - void getCurrentMonitorInfo(MonitorInfo* monitorInfo); - void enableFullscreen(bool enable); - void clearWindow(); - - void getDisplayInfo(DisplayInfo* displayInfo); - void updateSettings(); - - // virtual display - bool createVirtualDisplay(const VirtualDisplayInfo& vdispInfo); - void updateVirtualDisplay(const void* buffer, size_t size); - void bindVirtualDisplay(); - void copyToVirtualDisplay(RenderTargetHandle src); - void copyBackbufferToRenderTarget(RenderTargetHandle dst); - void clearVirtualDisplay(f32* color, bool clearColor=true); - void setPalette(const u32* palette); - const u32* getPalette(); - const TextureGpu* getPaletteTexture(); - void setColorCorrection(bool enabled, const ColorCorrection* color = nullptr, bool bloomChanged = false); - bool getWidescreen(); - bool getFrameBufferAsync(); - bool getGPUColorConvert(); - void* getVirtualDisplayGpuPtr(); - - u32 getVirtualDisplayWidth2D(); - u32 getVirtualDisplayWidth3D(); - u32 getVirtualDisplayHeight(); - u32 getVirtualDisplayOffset2D(); - u32 getVirtualDisplayOffset3D(); - - // core gpu functionality for UI and editor. - // Render target. - RenderTargetHandle createRenderTarget(u32 width, u32 height, bool hasDepthBuffer = false); - void freeRenderTarget(RenderTargetHandle handle); - void bindRenderTarget(RenderTargetHandle handle); - void clearRenderTarget(RenderTargetHandle handle, const f32* clearColor, f32 clearDepth = 1.0f); - void clearRenderTargetDepth(RenderTargetHandle handle, f32 clearDepth = 1.0f); - void copyRenderTarget(RenderTargetHandle dst, RenderTargetHandle src); - void unbindRenderTarget(); - const TextureGpu* getRenderTargetTexture(RenderTargetHandle rtHandle); - void getRenderTargetDim(RenderTargetHandle rtHandle, u32* width, u32* height); - - // Create a GPU version of a texture, assumes RGBA8 and returns a GPU handle. - TextureGpu* createTexture(u32 width, u32 height, const u32* data, MagFilter magFilter = MAG_FILTER_NONE); - TextureGpu* createTexture(u32 width, u32 height, TexFormat format); - TextureGpu* createTextureArray(u32 width, u32 height, u32 layers, u32 channels); - void freeTexture(TextureGpu* texture); - void getTextureDim(TextureGpu* texture, u32* width, u32* height); - void* getGpuPtr(const TextureGpu* texture); - - // Toggle bloom - but only the final post process. - void bloomPostEnable(bool enable = true); - - // Generic triangle draw. - // triCount : number of triangles to draw. - // indexStride : index buffer stride in bytes. - // indexOffset : starting index. - void drawIndexedTriangles(u32 triCount, u32 indexStride, u32 indexStart = 0u); - - // Generic line draw. - void drawLines(u32 lineCount); -}; diff --git a/components/darkforces/tfe/TFE_RenderBackend/renderState.h b/components/darkforces/tfe/TFE_RenderBackend/renderState.h deleted file mode 100644 index ec60c478..00000000 --- a/components/darkforces/tfe/TFE_RenderBackend/renderState.h +++ /dev/null @@ -1,88 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine GPU Library -// This handles low level access to the GPU device and is used by -// both the software and hardware rendering systems in order to -// provide basic access. -// -// Renderers will create a virtual display or render target. -// swap() handles blitting this result and then rendering UI -// on top. -////////////////////////////////////////////////////////////////////// - -#include - -enum StateEnable -{ - STATE_CULLING = (1 << 0), - STATE_BLEND = (1 << 1), - STATE_DEPTH_TEST = (1 << 2), - STATE_DEPTH_WRITE = (1 << 3), - STATE_STENCIL_WRITE = (1 << 4), - STATE_STENCIL_TEST = (1 << 5), - STATE_WIREFRAME = (1 << 6), -}; - -enum StateBlendFactor -{ - BLEND_ONE = 0, - BLEND_ZERO, - BLEND_SRC_ALPHA, - BLEND_ONE_MINUS_SRC_ALPHA, -}; - -enum StateBlendFunc -{ - BLEND_FUNC_ADD = 0, -}; - -enum ColorMaskChannels -{ - CMASK_NONE = 0, - CMASK_RED = (1 << 0), - CMASK_GREEN = (1 << 1), - CMASK_BLUE = (1 << 2), - CMASK_ALPHA = (1 << 3), - CMASK_RGB = CMASK_RED | CMASK_GREEN | CMASK_BLUE, - CMASK_ALL = CMASK_RED | CMASK_GREEN | CMASK_BLUE | CMASK_ALPHA -}; - -enum ComparisonFunction -{ - CMP_NEVER = 0, - CMP_LESS, - CMP_EQUAL, - CMP_LEQUAL, - CMP_GREATER, - CMP_NOTEQUAL, - CMP_GEQUAL, - CMP_ALWAYS, - CMP_COUNT -}; - -enum StencilOp -{ - OP_KEEP = 0, - OP_ZERO, - OP_INC, - OP_DEC, - OP_INVERT, - OP_REPLACE, - OP_INC_WRAP, - OP_DEC_WRAP, - OP_COUNT -}; - -namespace TFE_RenderState -{ - void clear(); - - void setStateEnable(bool enable, u32 stateFlags); - void setBlendMode(StateBlendFactor srcFactor, StateBlendFactor dstFactor, StateBlendFunc func = BLEND_FUNC_ADD); - void setDepthFunction(ComparisonFunction func); - void setStencilFunction(ComparisonFunction func, s32 ref, u32 mask = 0xffffffff); - void setStencilOp(StencilOp stencilFail, StencilOp depthFail, StencilOp depthStencilPass); - void setColorMask(u32 colorMask); - void setDepthBias(f32 factor = 0.0f, f32 bias = 0.0f); - void enableClipPlanes(s32 count = 0); -}; diff --git a/components/darkforces/tfe/TFE_RenderBackend/shader.h b/components/darkforces/tfe/TFE_RenderBackend/shader.h deleted file mode 100644 index c3892cd4..00000000 --- a/components/darkforces/tfe/TFE_RenderBackend/shader.h +++ /dev/null @@ -1,73 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// An OpenGL system to blit a texture to the screen. Uses a hardcoded -// basic shader + fullscreen triangle. -// -// Additional optional features can be added later such as filtering, -// bloom and GPU color conversion. -////////////////////////////////////////////////////////////////////// - -#include -#include - -enum ShaderVariableType -{ - SVT_SCALAR = 0, - SVT_VEC2, - SVT_VEC3, - SVT_VEC4, - SVT_ISCALAR, - SVT_IVEC2, - SVT_IVEC3, - SVT_IVEC4, - SVT_USCALAR, - SVT_UVEC2, - SVT_UVEC3, - SVT_UVEC4, - SVT_MAT3x3, - SVT_MAT4x3, - SVT_MAT4x4, - SVT_COUNT -}; - -enum ShaderVersion -{ - SHADER_VER_COMPTABILE = 0, // Lowest support version. - SHADER_VER_STD, // Standard, minimum requirement for GPU renderer. - SHADER_VER_COMPUTE, // Shader version with compute support. -}; - -struct ShaderDefine -{ - std::string name; - std::string value; -}; - -class Shader -{ -public: - Shader() : m_gpuHandle(0), m_clipPlaneCount(0), m_shaderVersion(SHADER_VER_COMPTABILE) {} - - bool create(const char* vertexShaderCode, const char* fragmentShaderCode, const char* defineString = nullptr, ShaderVersion version = SHADER_VER_COMPTABILE); - bool load(const char* vertexShader, const char* fragmentShader, u32 defineCount = 0, ShaderDefine* defines = nullptr, ShaderVersion version = SHADER_VER_COMPTABILE); - void enableClipPlanes(s32 count); - void destroy(); - - void bind(); - static void unbind(); - - void bindTextureNameToSlot(const char* texName, s32 slot); - s32 getVariableId(const char* name); - void setVariable(s32 id, ShaderVariableType type, const f32* data); - void setVariable(s32 id, ShaderVariableType type, const s32* data); - void setVariable(s32 id, ShaderVariableType type, const u32* data); - - s32 getVariables(); - - inline u32 getHandle() { return m_gpuHandle; } - -private: - u32 m_gpuHandle; - s32 m_clipPlaneCount; - ShaderVersion m_shaderVersion; -}; diff --git a/components/darkforces/tfe/TFE_RenderBackend/shaderBuffer.h b/components/darkforces/tfe/TFE_RenderBackend/shaderBuffer.h deleted file mode 100644 index 362f10a8..00000000 --- a/components/darkforces/tfe/TFE_RenderBackend/shaderBuffer.h +++ /dev/null @@ -1,52 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wrapper for "shader buffers" - which can either be backed by -// Buffer Textures or Shader Storage Buffers depending on capabilities. -// Typically hardware will be limited to strides as: -// * 1, 2, or 4 channels -////////////////////////////////////////////////////////////////////// - -#include - -enum BufferChannelType -{ - BUF_CHANNEL_UINT = 0, - BUF_CHANNEL_INT, - BUF_CHANNEL_FLOAT, - BUF_CHANNEL_COUNT, - BUF_CHANNEL_INVALID, -}; - -struct ShaderBufferDef -{ - u32 channelCount; // 1, 2, 4 channels (R, RG, RGBA) - u32 channelSize; // 1, 2, 4 bytes (u8; s16,u16; s32,u32,f32) - BufferChannelType channelType; -}; - -class ShaderBuffer -{ -public: - ShaderBuffer() : m_stride(0), m_count(0), m_size(0), m_initialized(false) {} - ~ShaderBuffer(); - - bool create(u32 count, const ShaderBufferDef& bufferDef, bool dynamic, void* initData = nullptr); - void destroy(); - - void update(const void* buffer, size_t size); - void bind(s32 bindPoint) const; - void unbind(s32 bindPoint) const; - - inline u32 getHandle() const { return m_gpuHandle[0]; } - - static s32 getMaxSize(); - -private: - ShaderBufferDef m_bufferDef; - u32 m_stride; - u32 m_count; - u32 m_size; - u32 m_gpuHandle[2]; - bool m_dynamic; - bool m_initialized; -}; diff --git a/components/darkforces/tfe/TFE_RenderBackend/textureGpu.h b/components/darkforces/tfe/TFE_RenderBackend/textureGpu.h deleted file mode 100644 index 67d173de..00000000 --- a/components/darkforces/tfe/TFE_RenderBackend/textureGpu.h +++ /dev/null @@ -1,53 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wrapper for OpenGL textures that expose the limited set of -// required functionality. -////////////////////////////////////////////////////////////////////// - -#include - -enum MagFilter -{ - MAG_FILTER_NONE = 0, - MAG_FILTER_LINEAR, -}; - -enum TexFormat -{ - TEX_RGBA8 = 0, - TEX_R8, - TEX_RGBAF16, - TEX_R16F, - TEX_COUNT -}; - -class TextureGpu -{ -public: - TextureGpu() : m_width(0), m_height(0), m_channels(4), m_bytesPerChannel(1), m_layers(1), m_gpuHandle(0) {} - ~TextureGpu(); - - bool create(u32 width, u32 height, TexFormat format = TEX_RGBA8, bool hasMipmaps = false, MagFilter magFilter = MAG_FILTER_NONE); - bool createArray(u32 width, u32 height, u32 layers, u32 channels = 4); - bool createWithData(u32 width, u32 height, const void* buffer, MagFilter magFilter = MAG_FILTER_NONE); - bool update(const void* buffer, size_t size, s32 layer = -1); // layer = -1 means update all layers, otherwise it is the layer index. - void bind(u32 slot = 0) const; - static void clear(u32 slot = 0); - static void clearSlots(u32 count, u32 start = 0); - - void setFilter(MagFilter filter); - - u32 getWidth() const { return m_width; } - u32 getHeight() const { return m_height; } - u32 getLayers() const { return m_layers; } - - inline u32 getHandle() const { return m_gpuHandle; } - -private: - u32 m_width; - u32 m_height; - u32 m_channels; - u32 m_bytesPerChannel; - u32 m_layers; - u32 m_gpuHandle; -}; diff --git a/components/darkforces/tfe/TFE_RenderBackend/vertexBuffer.h b/components/darkforces/tfe/TFE_RenderBackend/vertexBuffer.h deleted file mode 100644 index 12d25893..00000000 --- a/components/darkforces/tfe/TFE_RenderBackend/vertexBuffer.h +++ /dev/null @@ -1,67 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Wrapper for OpenGL textures that expose the limited set of -// required functionality. -////////////////////////////////////////////////////////////////////// - -#include - -// Maps between shader attribute name and attribute ID. -enum AttributeId -{ - ATTR_POS = 0, - ATTR_NRM, - ATTR_UV, - ATTR_UV1, - ATTR_UV2, - ATTR_UV3, - ATTR_COLOR, - ATTR_COUNT -}; - -enum AttributeType -{ - ATYPE_FLOAT = 0, - ATYPE_UINT32, - ATYPE_INT32, - ATYPE_UINT16, - ATYPE_INT16, - ATYPE_UINT8, - ATYPE_INT8, - ATYPE_COUNT -}; - -struct AttributeMapping -{ - AttributeId id; - AttributeType type; - u32 channels; // Number of channels (usually 1 - 4) - u32 offset; // Attribute offset in bytes, 0 = compute automatically. - bool normalized; -}; - -class VertexBuffer -{ -public: - VertexBuffer() : m_stride(0), m_count(0), m_attrCount(0), m_dynamic(false), m_gpuHandle(0), m_attrMapping(nullptr) {} - ~VertexBuffer(); - - bool create(u32 count, u32 stride, u32 attrCount, const AttributeMapping* attrMapping, bool dynamic, void* initData = nullptr); - void destroy(); - - void update(const void* buffer, size_t size); - void bind(); - void unbind(); - - inline u32 getHandle() const { return m_gpuHandle; } - -private: - u32 m_stride; - u32 m_count; - u32 m_size; - u32 m_gpuHandle; - u32 m_attrCount; - bool m_dynamic; - - AttributeMapping* m_attrMapping; -}; diff --git a/components/darkforces/tfe/TFE_RenderShared/lineDraw2d.h b/components/darkforces/tfe/TFE_RenderShared/lineDraw2d.h deleted file mode 100644 index 7c6f22b3..00000000 --- a/components/darkforces/tfe/TFE_RenderShared/lineDraw2d.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// GPU 2D antialiased line drawing -////////////////////////////////////////////////////////////////////// - -#include - -namespace TFE_RenderShared -{ - bool init(); - void destroy(); - - void lineDraw2d_begin(u32 width, u32 height); - void lineDraw2d_addLines(u32 count, f32 width, const Vec2f* lines, const u32* lineColors); - void lineDraw2d_addLine(f32 width, const Vec2f* vertices, const u32* colors); - - void lineDraw2d_drawLines(); -} diff --git a/components/darkforces/tfe/TFE_RenderShared/quadDraw2d.h b/components/darkforces/tfe/TFE_RenderShared/quadDraw2d.h deleted file mode 100644 index 528b3d93..00000000 --- a/components/darkforces/tfe/TFE_RenderShared/quadDraw2d.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// GPU 2D antialiased line drawing -////////////////////////////////////////////////////////////////////// - -#include -#include - -namespace TFE_RenderShared -{ - bool quadInit(); - void quadDestroy(); - - void quadDraw2d_begin(u32 width, u32 height); - void quadDraw2d_add(u32 count, const Vec2f* vertices, const u32* colors, f32 u0, f32 u1, TextureGpu* texture); - void quadDraw2d_add(const Vec2f* vertices, const u32* colors, TextureGpu* texture); - void quadDraw2d_add(const Vec2f* vertices, const u32* colors, f32 u0, f32 u1, TextureGpu* texture); - - void quadDraw2d_draw(); -} diff --git a/components/darkforces/tfe/TFE_RenderShared/texturePacker.h b/components/darkforces/tfe/TFE_RenderShared/texturePacker.h deleted file mode 100644 index bc2f2b34..00000000 --- a/components/darkforces/tfe/TFE_RenderShared/texturePacker.h +++ /dev/null @@ -1,77 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// Pack level textures into an atlas texture or array of textures. -////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include -#include -#include - - -struct TextureData; -struct AnimatedTexture; -struct WaxFrame; - -namespace TFE_Jedi -{ - struct TextureNode; - - struct TexturePage - { - s32 textureCount; - u8* backingMemory = nullptr; - TextureNode* root = nullptr; - }; - - struct TexturePacker - { - // GPU resources - ShaderBuffer textureTableGPU; // full texture table, includes all pages. - TextureGpu* texture = nullptr; // texture array, where each slice is a page. - - // CPU memory, this is kept around so it can be used on multiple levels. - Vec4i* textureTable = nullptr; // CPU memory for texture table. - TexturePage** pages = nullptr; // CPU copy of texture pages. - - // General Data - s32 width = 0; // Page dimensions. - s32 height = 0; - s32 texturesPacked = 0; // Total textures packed over all pages. - s32 pageCount = 0; // Number of texture pages. - s32 reservedPages = 0; // Number of reserved pages. - s32 reservedTexturesPacked = 0; - - // For debugging. - char name[64]; - }; - - // Initialize the texture packer once, it is persistent across levels. - TexturePacker* texturepacker_init(const char* name, s32 width, s32 height); - // Free memory and GPU buffers. Note: GPU textures need to be persistent, so the level allocator will not be used. - void texturepacker_destroy(TexturePacker* texturePacker); - - // Begin the packing process, this clears out the texture packer. - bool texturepacker_begin(TexturePacker* texturePacker); - // Commit the final packing to GPU memory. - void texturepacker_commit(); - - // Reset the texture packer for new games. - void texturepacker_reset(); - - // Reserved Pages - void texturepacker_reserveCommitedPages(TexturePacker* texturePacker); - bool texturepacker_hasReservedPages(TexturePacker* texturePacker); - void texturepacker_discardUnreservedPages(TexturePacker* texturePacker); - - // Global Texture Packer. - TexturePacker* texturepacker_getGlobal(); - void texturepacker_freeGlobal(); - - // Pack textures of various types into a single texture atlas. - // The client must provide a 'getList' function to get a list of 'TextureInfo' (see above). - // Note this may be called multiple times on the same texture packer, new pages are created as needed. - s32 texturepacker_pack(TextureListCallback getList, AssetPool pool); -} // TFE_Jedi \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_Settings/gameSourceData.h b/components/darkforces/tfe/TFE_Settings/gameSourceData.h deleted file mode 100644 index 83638441..00000000 --- a/components/darkforces/tfe/TFE_Settings/gameSourceData.h +++ /dev/null @@ -1,86 +0,0 @@ -#pragma once -#include - -enum GameID -{ - Game_Dark_Forces = 0, - Game_Outlaws, - Game_Count -}; - -#ifndef TFE_ESPBOX -namespace TFE_Settings -{ - static const char* c_gameName[] = - { - "Dark Forces", - "Outlaws", - }; - - // GOG Product IDs: - static const char* c_gogProductId[Game_Count] = - { - "1421404433", // Game_Dark_Forces - "1425302464" // Game_Outlaws - }; - - static const char* c_steamLocalPath[Game_Count] = - { - "dark forces/Game/", // Game_Dark_Forces - "outlaws/", // Game_Outlaws - }; - - static const char* c_steamLocalSubPath[Game_Count] = - { - "Game/", // Game_Dark_Forces - "/", // Game_Outlaws - }; - - static const u32 c_steamProductId[Game_Count] = - { - 32400, // Game_Dark_Forces - 559620, // Game_Outlaws - }; - - // A file that should be checked to double-check the found path actually works. - static const char* c_validationFile[Game_Count] = - { - "DARK.GOB", // Game_Dark_Forces - "OUTLAWS.LAB", // Game_Outlaws - }; - - static const char* c_darkForcesLocations[] = - { - // C drive - "C:/Program Files (x86)/Steam/steamapps/common/dark forces/Game/", - "C:/Program Files/Steam/steamapps/common/dark forces/Game/", - "C:/Program Files (x86)/GOG.com/Star Wars - Dark Forces/", - "C:/GOG Games/Star Wars - Dark Forces/", - // D drive - "D:/Program Files (x86)/Steam/steamapps/common/dark forces/Game/", - "D:/Program Files/Steam/steamapps/common/dark forces/Game/", - "D:/Program Files (x86)/GOG.com/Star Wars - Dark Forces/", - "D:/GOG Games/Star Wars - Dark Forces/", - }; - static const char* c_outlawsLocations[] = - { - // C drive - "C:/Program Files (x86)/Steam/steamapps/common/outlaws/", - "C:/Program Files/Steam/steamapps/common/outlaws/", - "C:/Program Files (x86)/GOG.com/outlaws/", - "C:/GOG Games/outlaws/", - // D drive - "D:/Program Files (x86)/Steam/steamapps/common/outlaws/", - "D:/Program Files/Steam/steamapps/common/outlaws/", - "D:/Program Files (x86)/GOG.com/outlaws/", - "D:/GOG Games/outlaws/", - }; - static const u32 c_hardcodedPathCount = TFE_ARRAYSIZE(c_darkForcesLocations); - - static const char** c_gameLocations[] = - { - c_darkForcesLocations, - c_outlawsLocations - }; -} -#endif diff --git a/components/darkforces/tfe/TFE_Settings/settings.cpp b/components/darkforces/tfe/TFE_Settings/settings.cpp deleted file mode 100644 index 49dfdf3e..00000000 --- a/components/darkforces/tfe/TFE_Settings/settings.cpp +++ /dev/null @@ -1,1140 +0,0 @@ -#include "settings.h" -#include -#include "gameSourceData.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef _WIN32 -#include "windows/registry.h" -#endif - -#ifdef __linux__ -#include "linux/steamlnx.h" -#endif - -namespace TFE_Settings -{ - ////////////////////////////////////////////////////////////////////////////////// - // Local State - ////////////////////////////////////////////////////////////////////////////////// -#define LINEBUF_LEN 1024 - -#ifdef TFE_ESPBOX - static char* s_settingsPath = nullptr; // TFE_MAX_PATH (shared memory) -#else - static char s_settingsPath[TFE_MAX_PATH]; -#endif - static TFE_Settings_Window s_windowSettings = {}; - static TFE_Settings_Graphics s_graphicsSettings = {}; - static TFE_Settings_Hud s_hudSettings = {}; - static TFE_Settings_Sound s_soundSettings = {}; - static TFE_Settings_System s_systemSettings = {}; - static TFE_Settings_A11y s_a11ySettings = {}; - static TFE_Game s_game = {}; - static TFE_Settings_Game s_gameSettings = {}; -#ifdef TFE_ESPBOX - static char* s_lineBuffer = nullptr; // LINEBUF_LEN (shared memory) -#else - static char s_lineBuffer[LINEBUF_LEN]; -#endif - static std::vector s_iniBuffer; - - enum SectionID - { - SECTION_WINDOW = 0, - SECTION_GRAPHICS, - SECTION_HUD, - SECTION_SOUND, - SECTION_SYSTEM, - SECTION_A11Y, //accessibility - SECTION_GAME, - SECTION_DARK_FORCES, - SECTION_OUTLAWS, - SECTION_CVAR, - SECTION_COUNT, - SECTION_INVALID = SECTION_COUNT, - SECTION_GAME_START = SECTION_DARK_FORCES - }; - - static const char* c_sectionNames[SECTION_COUNT] = - { - "Window", - "Graphics", - "Hud", - "Sound", - "System", - "A11y", - "Game", - "Dark_Forces", - "Outlaws", - "CVar", - }; - -#ifdef TFE_ESPBOX - static const char* c_gameName[] = - { - "Dark Forces", - "Outlaws", - }; - - // A file that should be checked to double-check the found path actually works. - static const char* c_validationFile[Game_Count] = - { - "DARK.GOB", // Game_Dark_Forces - "OUTLAWS.LAB", // Game_Outlaws - }; -#endif - - ////////////////////////////////////////////////////////////////////////////////// - // Forward Declarations - ////////////////////////////////////////////////////////////////////////////////// - // Write - void writeWindowSettings(FileStream& settings); - void writeGraphicsSettings(FileStream& settings); - void writeHudSettings(FileStream& settings); - void writeSoundSettings(FileStream& settings); - void writeSystemSettings(FileStream& settings); - void writeA11ySettings(FileStream& settings); - void writeGameSettings(FileStream& settings); - void writePerGameSettings(FileStream& settings); - void writeCVars(FileStream& settings); - - // Read - bool readFromDisk(); - void parseIniFile(const char* buffer, size_t len); - void parseWindowSettings(const char* key, const char* value); - void parseGraphicsSettings(const char* key, const char* value); - void parseHudSettings(const char* key, const char* value); - void parseSoundSettings(const char* key, const char* value); - void parseSystemSettings(const char* key, const char* value); - void parseA11ySettings(const char* key, const char* value); - void parseGame(const char* key, const char* value); - void parseDark_ForcesSettings(const char* key, const char* value); - void parseOutlawsSettings(const char* key, const char* value); - void parseCVars(const char* key, const char* value); - void checkGameData(); - - ////////////////////////////////////////////////////////////////////////////////// - // Implementation - ////////////////////////////////////////////////////////////////////////////////// - bool init(bool& firstRun) - { - // Clear out game settings. - s_gameSettings = {}; - for (u32 i = 0; i < Game_Count; i++) - { - strcpy(s_gameSettings.header[i].gameName, c_gameName[i]); - } - strcpy(s_game.game, s_gameSettings.header[0].gameName); - - TFE_Paths::appendPath(PATH_USER_DOCUMENTS, "settings.ini", s_settingsPath); - if (FileUtil::exists(s_settingsPath)) - { - firstRun = false; - if (readFromDisk()) - { - return true; - } - TFE_System::logWrite(LOG_WARNING, "Settings", "Cannot parse 'settings.ini' - recreating it."); - } - - firstRun = true; - autodetectGamePaths(); - return writeToDisk(); - } - - void shutdown() - { - // Write any settings to disk before shutting down. - writeToDisk(); - } - - void autodetectGamePaths() - { - for (u32 gameId = 0; gameId < Game_Count; gameId++) - { - const size_t sourcePathLen = strlen(s_gameSettings.header[gameId].sourcePath); - bool pathValid = sourcePathLen && validatePath(s_gameSettings.header[gameId].sourcePath, c_validationFile[gameId]); - - // First check locally, and then check the registry. - if (!pathValid && gameId == Game_Dark_Forces) // Only Dark Forces for now. - { - // First try the local path. - char localPath[TFE_MAX_PATH]; - TFE_Paths::appendPath(PATH_PROGRAM, "DARK.GOB", localPath); - - FileStream file; - if (file.open(localPath, Stream::MODE_READ)) - { - if (file.getSize() > 1) - { - strcpy(s_gameSettings.header[gameId].sourcePath, TFE_Paths::getPath(PATH_PROGRAM)); - FileUtil::fixupPath(s_gameSettings.header[gameId].sourcePath); - pathValid = true; - } - file.close(); - } - - // Then try local/Games/Dark Forces/ - if (!pathValid) - { - char gamePath[TFE_MAX_PATH]; - sprintf(gamePath, "%sGames/Dark Forces/", TFE_Paths::getPath(PATH_PROGRAM)); - FileUtil::fixupPath(gamePath); - - sprintf(localPath, "%sDARK.GOB", gamePath); - if (file.open(localPath, Stream::MODE_READ)) - { - if (file.getSize() > 1) - { - strcpy(s_gameSettings.header[gameId].sourcePath, gamePath); - pathValid = true; - } - file.close(); - } - } - } - -#ifdef _WIN32 - // Next try looking through the registry. - if (!pathValid) - { - pathValid = WindowsRegistry::getSteamPathFromRegistry(c_steamProductId[gameId], c_steamLocalPath[gameId], c_steamLocalSubPath[gameId], c_validationFile[gameId], s_gameSettings.header[gameId].sourcePath); - - if (!pathValid) - { - pathValid = WindowsRegistry::getGogPathFromRegistry(c_gogProductId[gameId], c_validationFile[gameId], s_gameSettings.header[gameId].sourcePath); - } - } -#endif -#ifdef __linux__ - if (!pathValid) - { - pathValid = LinuxSteam::getSteamPath(c_steamProductId[gameId], c_steamLocalSubPath[gameId], - c_validationFile[gameId], s_gameSettings.header[gameId].sourcePath); - } -#endif -#ifndef TFE_ESPBOX - // If the registry approach fails, just try looking in the various hardcoded paths. - if (!pathValid) - { - // Try various possible locations. - const char** locations = c_gameLocations[gameId]; - for (u32 i = 0; i < c_hardcodedPathCount; i++) - { - if (FileUtil::directoryExits(locations[i])) - { - strcpy(s_gameSettings.header[gameId].sourcePath, locations[i]); - pathValid = true; - break; - } - } - } -#endif - } - writeToDisk(); - } - - bool readFromDisk() - { - FileStream settings; - if (settings.open(s_settingsPath, Stream::MODE_READ)) - { - const size_t len = settings.getSize(); - s_iniBuffer.resize(len + 1); - s_iniBuffer[len] = 0; - settings.readBuffer(s_iniBuffer.data(), (u32)len); - settings.close(); - - parseIniFile(s_iniBuffer.data(), len); - autodetectGamePaths(); - - return true; - } - return false; - } - - bool writeToDisk() - { - FileStream settings; - if (settings.open(s_settingsPath, Stream::MODE_WRITE)) - { - writeWindowSettings(settings); - writeGraphicsSettings(settings); - writeHudSettings(settings); - writeSoundSettings(settings); - writeSystemSettings(settings); - writeA11ySettings(settings); - writeGameSettings(settings); - writePerGameSettings(settings); - writeCVars(settings); - settings.close(); - - return true; - } - return false; - } - - // Get and set settings. - TFE_Settings_Window* getWindowSettings() - { - return &s_windowSettings; - } - - TFE_Settings_Graphics* getGraphicsSettings() - { - return &s_graphicsSettings; - } - - TFE_Settings_Hud* getHudSettings() - { - return &s_hudSettings; - } - - TFE_Settings_Sound* getSoundSettings() - { - return &s_soundSettings; - } - - TFE_Settings_System* getSystemSettings() - { - return &s_systemSettings; - } - - TFE_Settings_A11y* getA11ySettings() - { - return &s_a11ySettings; - } - - TFE_Game* getGame() - { - return &s_game; - } - - TFE_GameHeader* getGameHeader(const char* gameName) - { - for (u32 i = 0; i < Game_Count; i++) - { - if (strcasecmp(gameName, c_gameName[i]) == 0) - { - return &s_gameSettings.header[i]; - } - } - - return nullptr; - } - - TFE_Settings_Game* getGameSettings() - { - return &s_gameSettings; - } - - void writeHeader(FileStream& file, const char* section) - { - snprintf(s_lineBuffer, LINEBUF_LEN, "[%s]\r\n", section); - file.writeBuffer(s_lineBuffer, (u32)strlen(s_lineBuffer)); - } - - void writeComment(FileStream& file, const char* comment) - { - snprintf(s_lineBuffer, LINEBUF_LEN, ";%s\r\n", comment); - file.writeBuffer(s_lineBuffer, (u32)strlen(s_lineBuffer)); - } - - void writeKeyValue_String(FileStream& file, const char* key, const char* value) - { - snprintf(s_lineBuffer, LINEBUF_LEN, "%s=\"%s\"\r\n", key, value); - file.writeBuffer(s_lineBuffer, (u32)strlen(s_lineBuffer)); - } - - void writeKeyValue_Int(FileStream& file, const char* key, s32 value) - { - snprintf(s_lineBuffer, LINEBUF_LEN, "%s=%d\r\n", key, value); - file.writeBuffer(s_lineBuffer, (u32)strlen(s_lineBuffer)); - } - - void writeKeyValue_Float(FileStream& file, const char* key, f32 value) - { - snprintf(s_lineBuffer, LINEBUF_LEN, "%s=%0.3f\r\n", key, value); - file.writeBuffer(s_lineBuffer, (u32)strlen(s_lineBuffer)); - } - - void writeKeyValue_Bool(FileStream& file, const char* key, bool value) - { - snprintf(s_lineBuffer, LINEBUF_LEN, "%s=%s\r\n", key, value ? "true" : "false"); - file.writeBuffer(s_lineBuffer, (u32)strlen(s_lineBuffer)); - } - - void writeKeyValue_RGBA(FileStream& file, const char* key, RGBA value) - { - writeKeyValue_Int(file, key, value.color); - } - - void writeWindowSettings(FileStream& settings) - { - writeHeader(settings, c_sectionNames[SECTION_WINDOW]); - writeKeyValue_Int(settings, "x", s_windowSettings.x); - writeKeyValue_Int(settings, "y", s_windowSettings.y); - writeKeyValue_Int(settings, "width", s_windowSettings.width); - writeKeyValue_Int(settings, "height", s_windowSettings.height); - writeKeyValue_Int(settings, "baseWidth", s_windowSettings.baseWidth); - writeKeyValue_Int(settings, "baseHeight", s_windowSettings.baseHeight); - writeKeyValue_Bool(settings, "fullscreen", s_windowSettings.fullscreen); - } - - void writeGraphicsSettings(FileStream& settings) - { - writeHeader(settings, c_sectionNames[SECTION_GRAPHICS]); - writeKeyValue_Int(settings, "gameWidth", s_graphicsSettings.gameResolution.x); - writeKeyValue_Int(settings, "gameHeight", s_graphicsSettings.gameResolution.z); - writeKeyValue_Bool(settings, "widescreen", s_graphicsSettings.widescreen); - writeKeyValue_Bool(settings, "asyncFramebuffer", s_graphicsSettings.asyncFramebuffer); - writeKeyValue_Bool(settings, "gpuColorConvert", s_graphicsSettings.gpuColorConvert); - writeKeyValue_Bool(settings, "colorCorrection", s_graphicsSettings.colorCorrection); - writeKeyValue_Bool(settings, "perspectiveCorrect3DO", s_graphicsSettings.perspectiveCorrectTexturing); - writeKeyValue_Bool(settings, "extendAjoinLimits", s_graphicsSettings.extendAjoinLimits); - writeKeyValue_Bool(settings, "vsync", s_graphicsSettings.vsync); - writeKeyValue_Bool(settings, "show_fps", s_graphicsSettings.showFps); - writeKeyValue_Bool(settings, "3doNormalFix", s_graphicsSettings.fix3doNormalOverflow); - writeKeyValue_Bool(settings, "ignore3doLimits", s_graphicsSettings.ignore3doLimits); - writeKeyValue_Bool(settings, "ditheredBilinear", s_graphicsSettings.ditheredBilinear); - writeKeyValue_Int(settings, "frameRateLimit", s_graphicsSettings.frameRateLimit); - writeKeyValue_Float(settings, "brightness", s_graphicsSettings.brightness); - writeKeyValue_Float(settings, "contrast", s_graphicsSettings.contrast); - writeKeyValue_Float(settings, "saturation", s_graphicsSettings.saturation); - writeKeyValue_Float(settings, "gamma", s_graphicsSettings.gamma); - - writeKeyValue_Bool(settings, "reticleEnable", s_graphicsSettings.reticleEnable); - writeKeyValue_Int(settings, "reticleIndex", s_graphicsSettings.reticleIndex); - writeKeyValue_Float(settings, "reticleRed", s_graphicsSettings.reticleRed); - writeKeyValue_Float(settings, "reticleGreen", s_graphicsSettings.reticleGreen); - writeKeyValue_Float(settings, "reticleBlue", s_graphicsSettings.reticleBlue); - writeKeyValue_Float(settings, "reticleOpacity", s_graphicsSettings.reticleOpacity); - writeKeyValue_Float(settings, "reticleScale", s_graphicsSettings.reticleScale); - - writeKeyValue_Bool(settings, "bloomEnabled", s_graphicsSettings.bloomEnabled); - writeKeyValue_Float(settings, "bloomStrength", s_graphicsSettings.bloomStrength); - writeKeyValue_Float(settings, "bloomSpread", s_graphicsSettings.bloomSpread); - - writeKeyValue_Int(settings, "renderer", s_graphicsSettings.rendererIndex); - writeKeyValue_Int(settings, "colorMode", s_graphicsSettings.colorMode); - writeKeyValue_Int(settings, "skyMode", s_graphicsSettings.skyMode); - } - - void writeHudSettings(FileStream& settings) - { - writeHeader(settings, c_sectionNames[SECTION_HUD]); -#ifndef TFE_ESPBOX - writeKeyValue_String(settings, "hudScale", c_tfeHudScaleStrings[s_hudSettings.hudScale]); - writeKeyValue_String(settings, "hudPos", c_tfeHudPosStrings[s_hudSettings.hudPos]); -#endif - writeKeyValue_Float(settings, "scale", s_hudSettings.scale); - writeKeyValue_Int(settings, "pixelOffsetLeft", s_hudSettings.pixelOffset[0]); - writeKeyValue_Int(settings, "pixelOffsetRight", s_hudSettings.pixelOffset[1]); - writeKeyValue_Int(settings, "pixelOffsetY", s_hudSettings.pixelOffset[2]); - } - - void writeSoundSettings(FileStream& settings) - { - writeHeader(settings, c_sectionNames[SECTION_SOUND]); - writeKeyValue_Float(settings, "masterVolume", s_soundSettings.masterVolume); - writeKeyValue_Float(settings, "soundFxVolume", s_soundSettings.soundFxVolume); - writeKeyValue_Float(settings, "musicVolume", s_soundSettings.musicVolume); - writeKeyValue_Float(settings, "cutsceneSoundFxVolume", s_soundSettings.cutsceneSoundFxVolume); - writeKeyValue_Float(settings, "cutsceneMusicVolume", s_soundSettings.cutsceneMusicVolume); - writeKeyValue_Int(settings, "audioDevice", s_soundSettings.audioDevice); - writeKeyValue_Int(settings, "midiOutput", s_soundSettings.midiOutput); - writeKeyValue_Int(settings, "midiType", s_soundSettings.midiType); - writeKeyValue_Bool(settings, "use16Channels", s_soundSettings.use16Channels); - writeKeyValue_Bool(settings, "disableSoundInMenus", s_soundSettings.disableSoundInMenus); - } - - void writeSystemSettings(FileStream& settings) - { - writeHeader(settings, c_sectionNames[SECTION_SYSTEM]); - writeKeyValue_Bool(settings, "gameExitsToMenu", s_systemSettings.gameQuitExitsToMenu); - writeKeyValue_Bool(settings, "returnToModLoader", s_systemSettings.returnToModLoader); - } - - void writeA11ySettings(FileStream& settings) - { - writeHeader(settings, c_sectionNames[SECTION_A11Y]); - writeKeyValue_Bool(settings, "showCutsceneSubtitles", s_a11ySettings.showCutsceneSubtitles); - writeKeyValue_Bool(settings, "showCutsceneCaptions", s_a11ySettings.showCutsceneCaptions); - writeKeyValue_Int(settings, "cutsceneFontSize", s_a11ySettings.cutsceneFontSize); - writeKeyValue_RGBA(settings, "cutsceneFontColor", s_a11ySettings.cutsceneFontColor); - writeKeyValue_Float(settings, "cutsceneTextBackgroundAlpha", s_a11ySettings.cutsceneTextBackgroundAlpha); - writeKeyValue_Bool(settings, "showCutsceneTextBorder", s_a11ySettings.showCutsceneTextBorder); - writeKeyValue_Float(settings, "cutsceneTextSpeed", s_a11ySettings.cutsceneTextSpeed); - - writeKeyValue_Bool(settings, "showGameplaySubtitles", s_a11ySettings.showGameplaySubtitles); - writeKeyValue_Bool(settings, "showGameplayCaptions", s_a11ySettings.showGameplayCaptions); - writeKeyValue_Int(settings, "gameplayFontSize", s_a11ySettings.gameplayFontSize); - writeKeyValue_RGBA(settings, "gameplayFontColor", s_a11ySettings.gameplayFontColor); - writeKeyValue_Float(settings, "gameplayTextBackgroundAlpha", s_a11ySettings.gameplayTextBackgroundAlpha); - writeKeyValue_Bool(settings, "showGameplayTextBorder", s_a11ySettings.showGameplayTextBorder); - writeKeyValue_Int(settings, "gameplayMaxTextLines", s_a11ySettings.gameplayMaxTextLines); - writeKeyValue_Float(settings, "gameplayTextSpeed", s_a11ySettings.gameplayTextSpeed); - writeKeyValue_Int(settings, "gameplayCaptionMinVolume", s_a11ySettings.gameplayCaptionMinVolume); - } - - void writeGameSettings(FileStream& settings) - { - writeHeader(settings, c_sectionNames[SECTION_GAME]); - writeKeyValue_String(settings, "game", s_game.game); - } - - void writePerGameSettings(FileStream& settings) - { - for (u32 i = 0; i < Game_Count; i++) - { - writeHeader(settings, c_sectionNames[SECTION_GAME_START + i]); - writeKeyValue_String(settings, "sourcePath", s_gameSettings.header[i].sourcePath); - writeKeyValue_String(settings, "emulatorPath", s_gameSettings.header[i].emulatorPath); - - if (i == Game_Dark_Forces) - { - writeKeyValue_Int(settings, "airControl", s_gameSettings.df_airControl); - writeKeyValue_Bool(settings, "bobaFettFacePlayer", s_gameSettings.df_bobaFettFacePlayer); - writeKeyValue_Bool(settings, "smoothVUEs", s_gameSettings.df_smoothVUEs); - writeKeyValue_Bool(settings, "disableFightMusic", s_gameSettings.df_disableFightMusic); - writeKeyValue_Bool(settings, "enableAutoaim", s_gameSettings.df_enableAutoaim); - writeKeyValue_Bool(settings, "showSecretFoundMsg", s_gameSettings.df_showSecretFoundMsg); - writeKeyValue_Bool(settings, "autorun", s_gameSettings.df_autorun); - writeKeyValue_Bool(settings, "ignoreInfLimit", s_gameSettings.df_ignoreInfLimit); - writeKeyValue_Int(settings, "pitchLimit", s_gameSettings.df_pitchLimit); - } - } - } - - void writeCVars(FileStream& settings) - { - writeHeader(settings, c_sectionNames[SECTION_CVAR]); - u32 count = TFE_Console::getCVarCount(); - char value[256]; - for (u32 i = 0; i < count; i++) - { - const TFE_Console::CVar* cvar = TFE_Console::getCVarByIndex(i); - if (cvar->flags & CVFLAG_DO_NOT_SERIALIZE) - { - continue; - } - - switch (cvar->type) - { - case TFE_Console::CVAR_INT: - sprintf(value, "int %d", cvar->valueInt ? (*cvar->valueInt) : cvar->serializedInt); - break; - case TFE_Console::CVAR_FLOAT: - sprintf(value, "float %f", cvar->valueFloat ? (*cvar->valueFloat) : cvar->serializedFlt); - break; - case TFE_Console::CVAR_BOOL: - sprintf(value, "bool %s", cvar->valueBool ? ((*cvar->valueBool) ? "true" : "false") : (cvar->serializedBool ? "true" : "false")); - break; - case TFE_Console::CVAR_STRING: - sprintf(value, "string \"%s\"", cvar->valueString ? cvar->valueString : cvar->serializedString.c_str()); - break; - default: - continue; - }; - - writeKeyValue_String(settings, cvar->name.c_str(), value); - } - } - - SectionID parseSectionName(const char* name) - { - char sectionName[LINEBUF_LEN]; - memcpy(sectionName, name + 1, strlen(name) - 2); - sectionName[strlen(name) - 2] = 0; - - for (u32 i = 0; i < SECTION_COUNT; i++) - { - if (strcasecmp(c_sectionNames[i], sectionName) == 0) - { - return SectionID(i); - } - } - return SECTION_INVALID; - } - - void parseIniFile(const char* buffer, size_t len) - { - TFE_Parser parser; - parser.init(buffer, len); - parser.addCommentString(";"); - parser.addCommentString("#"); - - size_t bufferPos = 0; - SectionID curSection = SECTION_INVALID; - - while (bufferPos < len) - { - const char* line = parser.readLine(bufferPos); - if (!line) { break; } - - TokenList tokens; - parser.tokenizeLine(line, tokens); - if (tokens.size() < 1) { continue; } - - if (tokens.size() == 1) - { - curSection = parseSectionName(tokens[0].c_str()); - if (curSection == SECTION_INVALID) - { - continue; - } - } - else if (tokens.size() == 2) - { - switch (curSection) - { - case SECTION_WINDOW: - parseWindowSettings(tokens[0].c_str(), tokens[1].c_str()); - break; - case SECTION_GRAPHICS: - parseGraphicsSettings(tokens[0].c_str(), tokens[1].c_str()); - break; - case SECTION_HUD: - parseHudSettings(tokens[0].c_str(), tokens[1].c_str()); - break; - case SECTION_SOUND: - parseSoundSettings(tokens[0].c_str(), tokens[1].c_str()); - break; - case SECTION_SYSTEM: - parseSystemSettings(tokens[0].c_str(), tokens[1].c_str()); - break; - case SECTION_A11Y: - parseA11ySettings(tokens[0].c_str(), tokens[1].c_str()); - break; - case SECTION_GAME: - parseGame(tokens[0].c_str(), tokens[1].c_str()); - break; - case SECTION_DARK_FORCES: - parseDark_ForcesSettings(tokens[0].c_str(), tokens[1].c_str()); - break; - case SECTION_OUTLAWS: - parseOutlawsSettings(tokens[0].c_str(), tokens[1].c_str()); - break; - case SECTION_CVAR: - parseCVars(tokens[0].c_str(), tokens[1].c_str()); - break; - default: - assert(0); - }; - } - } - } - - s32 parseInt(const char* value) - { - char* endPtr = nullptr; - return strtol(value, &endPtr, 10); - } - - f32 parseFloat(const char* value) - { - char* endPtr = nullptr; - return (f32)strtod(value, &endPtr); - } - - bool parseBool(const char* value) - { - if (value[0] == 'f' || value[0] == '0') { return false; } - return true; - } - - RGBA parseColor(const char* value) - { - s32 v = parseInt(value); - return RGBA(v); - } - - void parseWindowSettings(const char* key, const char* value) - { - if (strcasecmp("x", key) == 0) - { - s_windowSettings.x = parseInt(value); - } - else if (strcasecmp("y", key) == 0) - { - s_windowSettings.y = parseInt(value); - } - else if (strcasecmp("width", key) == 0) - { - s_windowSettings.width = parseInt(value); - } - else if (strcasecmp("height", key) == 0) - { - s_windowSettings.height = parseInt(value); - } - else if (strcasecmp("baseWidth", key) == 0) - { - s_windowSettings.baseWidth = parseInt(value); - } - else if (strcasecmp("baseHeight", key) == 0) - { - s_windowSettings.baseHeight = parseInt(value); - } - else if (strcasecmp("fullscreen", key) == 0) - { - s_windowSettings.fullscreen = parseBool(value); - } - } - - void parseGraphicsSettings(const char* key, const char* value) - { - if (strcasecmp("gameWidth", key) == 0) - { - s_graphicsSettings.gameResolution.x = parseInt(value); - } - else if (strcasecmp("gameHeight", key) == 0) - { - s_graphicsSettings.gameResolution.z = parseInt(value); - } - else if (strcasecmp("widescreen", key) == 0) - { - s_graphicsSettings.widescreen = parseBool(value); - } - else if (strcasecmp("asyncFramebuffer", key) == 0) - { - s_graphicsSettings.asyncFramebuffer = parseBool(value); - } - else if (strcasecmp("gpuColorConvert", key) == 0) - { - s_graphicsSettings.gpuColorConvert = parseBool(value); - } - else if (strcasecmp("colorCorrection", key) == 0) - { - s_graphicsSettings.colorCorrection = parseBool(value); - } - else if (strcasecmp("perspectiveCorrect3DO", key) == 0) - { - s_graphicsSettings.perspectiveCorrectTexturing = parseBool(value); - } - else if (strcasecmp("extendAjoinLimits", key) == 0) - { - s_graphicsSettings.extendAjoinLimits = parseBool(value); - } - else if (strcasecmp("vsync", key) == 0) - { - s_graphicsSettings.vsync = parseBool(value); - } - else if (strcasecmp("show_fps", key) == 0) - { - s_graphicsSettings.showFps = parseBool(value); - } - else if (strcasecmp("3doNormalFix", key) == 0) - { - s_graphicsSettings.fix3doNormalOverflow = parseBool(value); - } - else if (strcasecmp("ignore3doLimits", key) == 0) - { - s_graphicsSettings.ignore3doLimits = parseBool(value); - } - else if (strcasecmp("ditheredBilinear", key) == 0) - { - s_graphicsSettings.ditheredBilinear = parseBool(value); - } - else if (strcasecmp("frameRateLimit", key) == 0) - { - s_graphicsSettings.frameRateLimit = parseInt(value); - } - else if (strcasecmp("brightness", key) == 0) - { - s_graphicsSettings.brightness = parseFloat(value); - } - else if (strcasecmp("contrast", key) == 0) - { - s_graphicsSettings.contrast = parseFloat(value); - } - else if (strcasecmp("saturation", key) == 0) - { - s_graphicsSettings.saturation = parseFloat(value); - } - else if (strcasecmp("gamma", key) == 0) - { - s_graphicsSettings.gamma = parseFloat(value); - } - else if (strcasecmp("reticleEnable", key) == 0) - { - s_graphicsSettings.reticleEnable = parseBool(value); - } - else if (strcasecmp("reticleIndex", key) == 0) - { - s_graphicsSettings.reticleIndex = parseInt(value); - } - else if (strcasecmp("reticleRed", key) == 0) - { - s_graphicsSettings.reticleRed = parseFloat(value); - } - else if (strcasecmp("reticleGreen", key) == 0) - { - s_graphicsSettings.reticleGreen = parseFloat(value); - } - else if (strcasecmp("reticleBlue", key) == 0) - { - s_graphicsSettings.reticleBlue = parseFloat(value); - } - else if (strcasecmp("reticleOpacity", key) == 0) - { - s_graphicsSettings.reticleOpacity = parseFloat(value); - } - else if (strcasecmp("reticleScale", key) == 0) - { - s_graphicsSettings.reticleScale = parseFloat(value); - } - else if (strcasecmp("bloomEnabled", key) == 0) - { - s_graphicsSettings.bloomEnabled = parseBool(value); - } - else if (strcasecmp("bloomStrength", key) == 0) - { - s_graphicsSettings.bloomStrength = parseFloat(value); - } - else if (strcasecmp("bloomSpread", key) == 0) - { - s_graphicsSettings.bloomSpread = parseFloat(value); - } - else if (strcasecmp("renderer", key) == 0) - { - s_graphicsSettings.rendererIndex = parseInt(value); - } - else if (strcasecmp("colorMode", key) == 0) - { - s_graphicsSettings.colorMode = parseInt(value); - } - else if (strcasecmp("skyMode", key) == 0) - { - s_graphicsSettings.skyMode = SkyMode(parseInt(value)); - } - } - - void parseHudSettings(const char* key, const char* value) - { - if (strcasecmp("hudScale", key) == 0) - { -#ifndef TFE_ESPBOX - for (size_t i = 0; i < TFE_ARRAYSIZE(c_tfeHudScaleStrings); i++) - { - if (strcasecmp(value, c_tfeHudScaleStrings[i]) == 0) - { - s_hudSettings.hudScale = TFE_HudScale(i); - break; - } - } -#endif - } - else if (strcasecmp("hudPos", key) == 0) - { -#ifndef TFE_ESPBOX - for (size_t i = 0; i < TFE_ARRAYSIZE(c_tfeHudPosStrings); i++) - { - if (strcasecmp(value, c_tfeHudPosStrings[i]) == 0) - { - s_hudSettings.hudPos = TFE_HudPosition(i); - break; - } - } -#endif - } - else if (strcasecmp("scale", key) == 0) - { - s_hudSettings.scale = parseFloat(value); - } - else if (strcasecmp("pixelOffsetLeft", key) == 0) - { - s_hudSettings.pixelOffset[0] = parseInt(value); - } - else if (strcasecmp("pixelOffsetRight", key) == 0) - { - s_hudSettings.pixelOffset[1] = parseInt(value); - } - else if (strcasecmp("pixelOffsetY", key) == 0) - { - s_hudSettings.pixelOffset[2] = parseInt(value); - } - } - - void parseSoundSettings(const char* key, const char* value) - { - if (strcasecmp("masterVolume", key) == 0) - { - s_soundSettings.masterVolume = parseFloat(value); - } - else if (strcasecmp("soundFxVolume", key) == 0) - { - s_soundSettings.soundFxVolume = parseFloat(value); - } - else if (strcasecmp("musicVolume", key) == 0) - { - s_soundSettings.musicVolume = parseFloat(value); - } - else if (strcasecmp("cutsceneSoundFxVolume", key) == 0) - { - s_soundSettings.cutsceneSoundFxVolume = parseFloat(value); - } - else if (strcasecmp("cutsceneMusicVolume", key) == 0) - { - s_soundSettings.cutsceneMusicVolume = parseFloat(value); - } - else if (strcasecmp("audioDevice", key) == 0) - { - s_soundSettings.audioDevice = parseInt(value); - } - else if (strcasecmp("midiOutput", key) == 0) - { - s_soundSettings.midiOutput = parseInt(value); - } - else if (strcasecmp("midiType", key) == 0) - { - s_soundSettings.midiType = parseInt(value); - } - else if (strcasecmp("use16Channels", key) == 0) - { - s_soundSettings.use16Channels = parseBool(value); - } - else if (strcasecmp("disableSoundInMenus", key) == 0) - { - s_soundSettings.disableSoundInMenus = parseBool(value); - } - } - - void parseSystemSettings(const char* key, const char* value) - { - if (strcasecmp("gameExitsToMenu", key) == 0) - { - s_systemSettings.gameQuitExitsToMenu = parseBool(value); - } - else if (strcasecmp("returnToModLoader", key) == 0) - { - s_systemSettings.returnToModLoader = parseBool(value); - } - } - - void parseA11ySettings(const char* key, const char* value) - { - if (strcasecmp("showCutsceneSubtitles", key) == 0) - { - s_a11ySettings.showCutsceneSubtitles = parseBool(value); - } - else if (strcasecmp("showCutsceneCaptions", key) == 0) - { - s_a11ySettings.showCutsceneCaptions = parseBool(value); - } - else if (strcasecmp("showGameplaySubtitles", key) == 0) - { - s_a11ySettings.showGameplaySubtitles = parseBool(value); - } - else if (strcasecmp("showGameplayCaptions", key) == 0) - { - s_a11ySettings.showGameplayCaptions = parseBool(value); - } - else if (strcasecmp("cutsceneFontSize", key) == 0) - { - s_a11ySettings.cutsceneFontSize = (FontSize)parseInt(value); - } - else if (strcasecmp("gameplayFontSize", key) == 0) - { - s_a11ySettings.gameplayFontSize = (FontSize)parseInt(value); - } - else if (strcasecmp("cutsceneFontColor", key) == 0) - { - s_a11ySettings.cutsceneFontColor = parseColor(value); - } - else if (strcasecmp("gameplayFontColor", key) == 0) - { - s_a11ySettings.gameplayFontColor = parseColor(value); - } - else if (strcasecmp("cutsceneTextBackgroundAlpha", key) == 0) - { - s_a11ySettings.cutsceneTextBackgroundAlpha = parseFloat(value); - } - else if (strcasecmp("gameplayTextBackgroundAlpha", key) == 0) - { - s_a11ySettings.gameplayTextBackgroundAlpha = parseFloat(value); - } - else if (strcasecmp("gameplayMaxTextLines", key) == 0) - { - s_a11ySettings.gameplayMaxTextLines = parseInt(value); - } - else if (strcasecmp("showCutsceneTextBorder", key) == 0) - { - s_a11ySettings.showCutsceneTextBorder = parseBool(value); - } - else if (strcasecmp("showGameplayTextBorder", key) == 0) - { - s_a11ySettings.showGameplayTextBorder = parseBool(value); - } - else if (strcasecmp("cutsceneTextSpeed", key) == 0) - { - s_a11ySettings.cutsceneTextSpeed = parseFloat(value); - } - else if (strcasecmp("gameplayTextSpeed", key) == 0) - { - s_a11ySettings.gameplayTextSpeed = parseFloat(value); - } - else if (strcasecmp("gameplayCaptionMinVolume", key) == 0) - { - s_a11ySettings.gameplayCaptionMinVolume = parseInt(value); - } - } - - void parseGame(const char* key, const char* value) - { - if (strcasecmp("game", key) == 0) - { - strcpy(s_game.game, value); - // Get the game ID. - s_game.id = Game_Count; - for (u32 i = 0; i < Game_Count; i++) - { - if (strcasecmp(s_game.game, c_gameName[i]) == 0) - { - s_game.id = GameID(i); - break; - } - } - } - } - - void appendSlash(char* path) - { - size_t len = strlen(path); - if (len == 0) { return; } - if (path[len - 1] == '\\' || path[len - 1] == '/') { return; } - - path[len] = '/'; - path[len + 1] = 0; - } - - void parseDark_ForcesSettings(const char* key, const char* value) - { - if (strcasecmp("sourcePath", key) == 0) - { - strcpy(s_gameSettings.header[Game_Dark_Forces].sourcePath, value); - appendSlash(s_gameSettings.header[Game_Dark_Forces].sourcePath); - } - else if (strcasecmp("emulatorPath", key) == 0) - { - strcpy(s_gameSettings.header[Game_Dark_Forces].emulatorPath, value); - appendSlash(s_gameSettings.header[Game_Dark_Forces].emulatorPath); - } - else if (strcasecmp("airControl", key) == 0) - { - s_gameSettings.df_airControl = std::min(std::max(parseInt(value), s32(0)), s32(8)); - } - else if (strcasecmp("bobaFettFacePlayer", key) == 0) - { - s_gameSettings.df_bobaFettFacePlayer = parseBool(value); - } - else if (strcasecmp("smoothVUEs", key) == 0) - { - s_gameSettings.df_smoothVUEs = parseBool(value); - } - else if (strcasecmp("disableFightMusic", key) == 0) - { - s_gameSettings.df_disableFightMusic = parseBool(value); - } - else if (strcasecmp("enableAutoaim", key) == 0) - { - s_gameSettings.df_enableAutoaim = parseBool(value); - } - else if (strcasecmp("showSecretFoundMsg", key) == 0) - { - s_gameSettings.df_showSecretFoundMsg = parseBool(value); - } - else if (strcasecmp("autorun", key) == 0) - { - s_gameSettings.df_autorun = parseBool(value); - } - else if (strcasecmp("ignoreInfLimit", key) == 0) - { - s_gameSettings.df_ignoreInfLimit = parseBool(value); - } - else if (strcasecmp("pitchLimit", key) == 0) - { - s_gameSettings.df_pitchLimit = PitchLimit(parseInt(value)); - } - } - - void parseOutlawsSettings(const char* key, const char* value) - { - if (strcasecmp("sourcePath", key) == 0) - { - strcpy(s_gameSettings.header[Game_Outlaws].sourcePath, value); - appendSlash(s_gameSettings.header[Game_Outlaws].sourcePath); - } - } - - void parseCVars(const char* key, const char* _value) - { - // Split the value into - char tmp[256]; - strcpy(tmp, _value); - - char* type = strtok(tmp, " "); - char* value = strtok(nullptr, " "); - if (!type || !value) { return; } - - if (strcasecmp(type, "int") == 0) - { - TFE_Console::addSerializedCVarInt(key, parseInt(value)); - } - else if (strcasecmp(type, "float") == 0) - { - TFE_Console::addSerializedCVarFloat(key, parseFloat(value)); - } - else if (strcasecmp(type, "bool") == 0) - { - TFE_Console::addSerializedCVarBool(key, parseBool(value)); - } - else if (strcasecmp(type, "string") == 0) - { - value = &value[1]; - value[strlen(value) - 1] = 0; - TFE_Console::addSerializedCVarString(key, value); - } - } - - bool validatePath(const char* path, const char* sentinel) - { - if (!FileUtil::directoryExits(path)) { return false; } - - char sentinelPath[TFE_MAX_PATH]; - sprintf(sentinelPath, "%s%s", path, sentinel); - FileStream file; - if (!file.open(sentinelPath, Stream::MODE_READ)) - { - return false; - } - bool valid = file.getSize() > 1; - file.close(); - - return valid; - } -} - -#ifdef TFE_ESPBOX -void espbox_shared_settings(bool alloc) -{ - ESPBOX_SHARED_ALLOC(TFE_Settings::s_settingsPath, TFE_MAX_PATH); - ESPBOX_SHARED_ALLOC(TFE_Settings::s_lineBuffer, LINEBUF_LEN); -} -#endif - -#ifdef TFE_ESPBOX -// Shutdown only: release this file's cached container storage so nothing is -// left in the 4MB ROM block when the session ends (see esp_alloc.cpp). -void espbox_release_settings_caches() -{ - std::vector().swap(TFE_Settings::s_iniBuffer); -} -#endif diff --git a/components/darkforces/tfe/TFE_Settings/settings.h b/components/darkforces/tfe/TFE_Settings/settings.h deleted file mode 100644 index fbb66cf7..00000000 --- a/components/darkforces/tfe/TFE_Settings/settings.h +++ /dev/null @@ -1,296 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Settings -// This is a global repository for program settings in an INI like -// format. -// -// This includes reading and writing settings as well as storing an -// in-memory cache to get accessed at runtime. -////////////////////////////////////////////////////////////////////// - -#include -#include -#include -#include "gameSourceData.h" - -enum SkyMode -{ - SKYMODE_VANILLA = 0, - SKYMODE_CYLINDER, - SKYMODE_COUNT -}; - -enum ColorMode -{ - COLORMODE_8BIT = 0, // Default vanilla - COLORMODE_8BIT_INTERP, // Interpolate between colormap values. - // COLORMODE_TRUE_COLOR, // Will be enabled when the feature comes online. - COLORMODE_COUNT, -}; - -#ifndef TFE_ESPBOX -static const char* c_tfeSkyModeStrings[] = -{ - "Vanilla", // SKYMODE_VANILLA - "Cylinder", // SKYMODE_CYLINDER -}; -#endif - -struct TFE_Settings_Window -{ - s32 x = 0; - s32 y = 64; - u32 width = 1280; - u32 height = 720; - u32 baseWidth = 1280; - u32 baseHeight = 720; - bool fullscreen = true; -}; - -struct TFE_Settings_Graphics -{ - Vec2i gameResolution = { 320, 200 }; - bool widescreen = false; - bool asyncFramebuffer = true; - bool gpuColorConvert = true; - bool colorCorrection = false; - bool perspectiveCorrectTexturing = false; - bool extendAjoinLimits = true; - bool vsync = true; - bool showFps = false; - bool fix3doNormalOverflow = true; - bool ignore3doLimits = true; - s32 frameRateLimit = 0; - f32 brightness = 1.0f; - f32 contrast = 1.0f; - f32 saturation = 1.0f; - f32 gamma = 1.0f; - s32 rendererIndex = 0; - s32 colorMode = COLORMODE_8BIT; - - // 8-bit options. - bool ditheredBilinear = false; - - // Reticle - bool reticleEnable = false; - s32 reticleIndex = 6; - f32 reticleRed = 0.25f; - f32 reticleGreen = 1.00f; - f32 reticleBlue = 0.25f; - f32 reticleOpacity = 1.00f; - f32 reticleScale = 1.0f; - - // Bloom options - bool bloomEnabled = false; - f32 bloomStrength = 0.4f; - f32 bloomSpread = 0.6f; - - // Sky (Ignored when using the software renderer) - s32 skyMode = SKYMODE_CYLINDER; -}; - -enum TFE_HudScale -{ - TFE_HUDSCALE_PROPORTIONAL = 0, - TFE_HUDSCALE_SCALED, -}; - -enum TFE_HudPosition -{ - TFE_HUDPOS_EDGE = 0, // Hud elements on the edges of the screen. - TFE_HUDPOS_4_3, // Hud elements locked to 4:3 (even in widescreen). -}; - -enum PitchLimit -{ - PITCH_VANILLA = 0, - PITCH_VANILLA_PLUS, - PITCH_HIGH, - PITCH_MAXIMUM, - PITCH_COUNT -}; - -enum FontSize -{ - FONT_SMALL, - FONT_MEDIUM, - FONT_LARGE, - FONT_XL -}; - -#ifndef TFE_ESPBOX -static const char* c_tfeHudScaleStrings[] = -{ - "Proportional", // TFE_HUDSCALE_PROPORTIONAL - "Scaled", // TFE_HUDSCALE_SCALED -}; - -static const char* c_tfeHudPosStrings[] = -{ - "Edge", // TFE_HUDPOS_EDGE - "4:3", // TFE_HUDPOS_4_3 -}; - -static const char* c_tfePitchLimit[] = -{ - "Vanilla (45 degrees)", - "Vanilla+ (60 degrees)", - "High (75 degrees)", - "Maximum" -}; -#endif - -struct TFE_Settings_Hud -{ - // Determines whether the HUD stays the same size on screen regardless of resolution or if it gets smaller with higher resolution. - TFE_HudScale hudScale = TFE_HUDSCALE_PROPORTIONAL; - // This setting determines how the left and right corners are calculated, which have an offset of (0,0). - TFE_HudPosition hudPos = TFE_HUDPOS_EDGE; - - // Scale of the HUD, ignored if HudScale is TFE_HUDSCALE_PROPORTIONAL. - f32 scale = 1.0f; - // Pixel offset from the left hud corner, right is (-leftX, leftY) - s32 pixelOffset[3] = { 0 }; -}; - -struct TFE_Settings_Sound -{ - f32 masterVolume = 1.0f; - f32 soundFxVolume = 0.75f; - f32 musicVolume = 1.0f; - f32 cutsceneSoundFxVolume = 0.9f; - f32 cutsceneMusicVolume = 1.0f; - s32 audioDevice = -1; // Use the audio device default. - s32 midiOutput = -1; // Use the midi type default. - s32 midiType = MIDI_TYPE_DEFAULT; - bool use16Channels = false; - bool disableSoundInMenus = false; -}; - -struct TFE_Game -{ - char game[64] = "Dark Forces"; - GameID id; -}; - -struct TFE_GameHeader -{ - char gameName[64]=""; - char sourcePath[TFE_MAX_PATH]=""; - char emulatorPath[TFE_MAX_PATH]=""; -}; - -struct TFE_Settings_Game -{ - TFE_GameHeader header[Game_Count]; - - // Dark Forces - s32 df_airControl = 0; // Air control, default = 0, where 0 = speed/256 and 8 = speed; range = [0, 8] - bool df_bobaFettFacePlayer = false; // Make Boba Fett try to face the player in all his attack phases. - bool df_smoothVUEs = false; // Smooths VUE animations (e.g. the Moldy Crow entering and exiting levels) - bool df_disableFightMusic = false; // Set to true to disable fight music and music transitions during gameplay. - bool df_enableAutoaim = true; // Set to true to enable autoaim, false to disable. - bool df_showSecretFoundMsg = true; // Show a message when the player finds a secret. - bool df_autorun = false; // Run by default instead of walk. - bool df_ignoreInfLimit = true; // Ignore the vanilla INF limit. - PitchLimit df_pitchLimit = PITCH_VANILLA_PLUS; -}; - -struct TFE_Settings_System -{ - bool gameQuitExitsToMenu = true; // Quitting from the game returns to the main menu instead. - bool returnToModLoader = true; // Return to the Mod Loader if running a mod. -}; - -/// -/// Represents an RGBA color as a 32-bit unsigned integer, with properties for reading the channel -/// values as U8s or floats. -/// -struct RGBA -{ - u32 color; - u8 getAlpha() { return (color >> 24) & 0xff; } - u8 getRed() { return (color >> 16) & 0xff; } - u8 getGreen() { return (color >> 8) & 0xff; } - u8 getBlue() { return color & 0xff; } - - f32 getAlphaF() { return getAlpha() / 255.0f; } - f32 getRedF() { return getRed() / 255.0f; } - f32 getGreenF() { return getGreen() / 255.0f; } - f32 getBlueF() { return getBlue() / 255.0f; } - - RGBA() - { - - } - - RGBA(u32 color) - { - this->color = color; - } - - static RGBA fromFloats(f32 r, f32 g, f32 b) - { - RGBA color; - color.color = (u8)(b * 255) + ((u8)(g * 255) << 8) + ((u8)(r * 255) << 16) + (255 << 24); - return color; - } - static RGBA fromFloats(f32 r, f32 g, f32 b, f32 a) - { - RGBA color; - color.color = (u8)(b * 255) + ((u8)(g * 255) << 8) + ((u8)(r * 255) << 16) + ((u8)(a * 255) << 24); - return color; - } -}; - -struct RGBAf { - f32 r, g, b, a; - - RGBA ToRGBA() - { - return RGBA::fromFloats(r, g, b, a); - } -}; - -struct TFE_Settings_A11y -{ - bool showCutsceneSubtitles; //voice - bool showCutsceneCaptions; //descriptive (e.g. "[Mine beeping]", "[Engine roaring]" - FontSize cutsceneFontSize; - RGBA cutsceneFontColor = RGBA::fromFloats(1.0f, 1.0f, 1.0f); - f32 cutsceneTextBackgroundAlpha = 0.75f; - bool showCutsceneTextBorder = true; - f32 cutsceneTextSpeed = 1.0f; - - bool showGameplaySubtitles; //voice - bool showGameplayCaptions; //descriptive - FontSize gameplayFontSize; - RGBA gameplayFontColor = RGBA::fromFloats(1.0f, 1.0f, 1.0f); - int gameplayMaxTextLines = 3; - f32 gameplayTextBackgroundAlpha = 0.0f; - bool showGameplayTextBorder = false; - f32 gameplayTextSpeed = 1.0f; - s32 gameplayCaptionMinVolume = 32; //in range 0 - 127 -}; - -namespace TFE_Settings -{ - bool init(bool& firstRun); - void shutdown(); - - bool writeToDisk(); - - // Get and set settings. - TFE_Settings_Window* getWindowSettings(); - TFE_Settings_Graphics* getGraphicsSettings(); - TFE_Settings_Hud* getHudSettings(); - TFE_Settings_Sound* getSoundSettings(); - TFE_Settings_System* getSystemSettings(); - TFE_Game* getGame(); - TFE_GameHeader* getGameHeader(const char* gameName); - TFE_Settings_Game* getGameSettings(); - TFE_Settings_A11y* getA11ySettings(); - - bool validatePath(const char* path, const char* sentinel); - void autodetectGamePaths(); -} diff --git a/components/darkforces/tfe/TFE_System/CrashHandler/crashHandler.h b/components/darkforces/tfe/TFE_System/CrashHandler/crashHandler.h deleted file mode 100644 index 94f7982d..00000000 --- a/components/darkforces/tfe/TFE_System/CrashHandler/crashHandler.h +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once -#include - -namespace TFE_CrashHandler -{ - // Sets exception handlers that work on per-process basis - void setProcessExceptionHandlers(); - - // Installs C++ exception handlers that function on per-thread basis - void setThreadExceptionHandlers(); -}; - - diff --git a/components/darkforces/tfe/TFE_System/Threads/Linux/mutexLinux.h b/components/darkforces/tfe/TFE_System/Threads/Linux/mutexLinux.h deleted file mode 100644 index 7e228a59..00000000 --- a/components/darkforces/tfe/TFE_System/Threads/Linux/mutexLinux.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once -#include -#include "../mutex.h" - -class MutexLinux : public Mutex -{ -public: - MutexLinux(); - virtual ~MutexLinux(); - - virtual s32 lock(); - virtual s32 unlock(); - -private: - pthread_mutex_t m_handle; -}; diff --git a/components/darkforces/tfe/TFE_System/Threads/Linux/threadLinux.h b/components/darkforces/tfe/TFE_System/Threads/Linux/threadLinux.h deleted file mode 100644 index 6c7fcca7..00000000 --- a/components/darkforces/tfe/TFE_System/Threads/Linux/threadLinux.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once -#include -#include "../thread.h" - -class ThreadLinux : public Thread -{ -public: - ThreadLinux(const char* name, ThreadFunc func, void* userData); - virtual ~ThreadLinux(); - - virtual bool run(); - virtual void pause(); - virtual void resume(); - virtual void waitOnExit(void); - -protected: - pthread_t m_handle; -}; diff --git a/components/darkforces/tfe/TFE_System/Threads/Win32/mutexWin32.h b/components/darkforces/tfe/TFE_System/Threads/Win32/mutexWin32.h deleted file mode 100644 index 0be077b3..00000000 --- a/components/darkforces/tfe/TFE_System/Threads/Win32/mutexWin32.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once -#include -#include "../mutex.h" - -class MutexWin32 : public Mutex -{ -public: - MutexWin32(); - virtual ~MutexWin32(); - - virtual s32 lock(); - virtual s32 unlock(); - -private: - mutable CRITICAL_SECTION C; -}; diff --git a/components/darkforces/tfe/TFE_System/Threads/Win32/signalWin32.h b/components/darkforces/tfe/TFE_System/Threads/Win32/signalWin32.h deleted file mode 100644 index f03c36aa..00000000 --- a/components/darkforces/tfe/TFE_System/Threads/Win32/signalWin32.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once -#include -#include "../signal.h" - -class SignalWin32 : public Signal -{ -public: - SignalWin32(); - virtual ~SignalWin32(); - - virtual void fire(); - virtual bool wait(u32 timeOutInMS=TIMEOUT_INFINITE, bool reset=true); - -protected: - HANDLE m_win32Handle; -}; diff --git a/components/darkforces/tfe/TFE_System/Threads/Win32/threadWin32.h b/components/darkforces/tfe/TFE_System/Threads/Win32/threadWin32.h deleted file mode 100644 index 684abdc6..00000000 --- a/components/darkforces/tfe/TFE_System/Threads/Win32/threadWin32.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once -#include -#include "../thread.h" - -class ThreadWin32 : public Thread -{ -public: - ThreadWin32(const char* name, ThreadFunc func, void* userData); - virtual ~ThreadWin32(); - - virtual bool run(); - virtual void pause(); - virtual void resume(); - virtual void waitOnExit(); - -protected: - HANDLE m_win32Handle; -}; diff --git a/components/darkforces/tfe/TFE_System/Threads/mutex.h b/components/darkforces/tfe/TFE_System/Threads/mutex.h deleted file mode 100644 index 92f53b16..00000000 --- a/components/darkforces/tfe/TFE_System/Threads/mutex.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once -#include - -class Mutex -{ -public: - virtual ~Mutex() {}; - - virtual s32 lock() = 0; - virtual s32 unlock() = 0; - -protected: - Mutex() {}; - -public: - //static factory function - creates the correct platform dependent version - static Mutex* create(); -}; diff --git a/components/darkforces/tfe/TFE_System/Threads/signal.h b/components/darkforces/tfe/TFE_System/Threads/signal.h deleted file mode 100644 index 72ba8c48..00000000 --- a/components/darkforces/tfe/TFE_System/Threads/signal.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once -#include -#include - -#define TIMEOUT_INFINITE 0xFFFFFFFF - -class Signal -{ -public: - ~Signal() {}; - - virtual void fire() = 0; - //returns true if signaled, false if the timeout was hit instead. - virtual bool wait(u32 timeOutInMS=TIMEOUT_INFINITE, bool reset=true) = 0; - -public: - //static factory function - creates the correct platform dependent version - static Signal* create(); - -protected: -}; diff --git a/components/darkforces/tfe/TFE_System/Threads/thread.h b/components/darkforces/tfe/TFE_System/Threads/thread.h deleted file mode 100644 index 30d8d0c1..00000000 --- a/components/darkforces/tfe/TFE_System/Threads/thread.h +++ /dev/null @@ -1,46 +0,0 @@ -#pragma once -#include -#include - -#ifdef _WIN32 - #define TFE_THREADRET u32 -#else - #define TFE_THREADRET void* -#endif - -typedef TFE_THREADRET (TFE_STDCALL* ThreadFunc)(void*); - -class Thread -{ -public: - virtual ~Thread() {}; - - virtual bool run() = 0; - virtual void pause() = 0; - virtual void resume() = 0; - virtual void waitOnExit() = 0; - - bool isRunning() { return m_isRunning; } - bool isPaused() { return m_isPaused; } - -protected: - Thread(const char* name, ThreadFunc func, void* userData) - { - m_func = func; - m_userData = userData; - strcpy(m_name, name); - m_isRunning = false; - m_isPaused = false; - } - -public: - //static factory function - creates the correct platform dependent version - static Thread* create(const char* name, ThreadFunc func, void* userData); - -protected: - ThreadFunc m_func; - void* m_userData; - bool m_isRunning; - bool m_isPaused; - char m_name[256]; -}; diff --git a/components/darkforces/tfe/TFE_System/endian.h b/components/darkforces/tfe/TFE_System/endian.h deleted file mode 100644 index b0292d87..00000000 --- a/components/darkforces/tfe/TFE_System/endian.h +++ /dev/null @@ -1,52 +0,0 @@ -#pragma once - -#include "types.h" -#include - -namespace TFE_Endian -{ - inline u16 le16_to_cpu(u16 x) - { - return SDL_SwapLE16(x); - } - - inline u32 le32_to_cpu(u32 x) - { - return SDL_SwapLE32(x); - } - - inline u32 cpu_to_le32(u32 x) - { - return SDL_SwapLE32(x); - } - - inline u64 le64_to_cpu(u64 x) - { - return SDL_SwapLE64(x); - } - - inline f32 lef32_to_cpu(f32 x) - { - return SDL_SwapFloatLE(x); - } - - inline u16 be16_to_cpu(u16 x) - { - return SDL_SwapBE16(x); - } - - inline u32 be32_to_cpu(u32 x) - { - return SDL_SwapBE32(x); - } - - inline u64 be64_to_cpu(u64 x) - { - return SDL_SwapBE64(x); - } - - inline f32 bef32_to_cpu(f32 x) - { - return SDL_SwapFloatBE(x); - } -} diff --git a/components/darkforces/tfe/TFE_System/espboxShared.h b/components/darkforces/tfe/TFE_System/espboxShared.h deleted file mode 100644 index 938a7c6b..00000000 --- a/components/darkforces/tfe/TFE_System/espboxShared.h +++ /dev/null @@ -1,30 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// TFE_ESPBOX: the engine's large statics live in BoxEmu's 4MB ROM block. -// -// A converted static keeps its name but becomes a pointer. The file that -// owns it defines an espbox_shared_(bool alloc) hook that allocates it -// (zeroed) from the block, or releases it and clears the pointer; the hooks -// are called from darkforces_init_shared_memory() / -// darkforces_free_shared_memory(). See src/platform/esp_alloc.cpp. -////////////////////////////////////////////////////////////////////// -#ifdef TFE_ESPBOX -#include - -extern "C" void* espbox_pool_calloc(size_t size); -extern "C" void espbox_pool_free(void* ptr); - -// Set when any hook's allocation fails; checked by darkforces_init_shared_memory(). -extern bool g_espboxSharedAllocFailed; - -#define ESPBOX_SHARED_ALLOC(ptr, count) \ - do { \ - if (alloc) { \ - (ptr) = static_cast(espbox_pool_calloc(sizeof(*(ptr)) * (count))); \ - if (!(ptr)) { g_espboxSharedAllocFailed = true; } \ - } else { \ - espbox_pool_free(static_cast(ptr)); \ - (ptr) = nullptr; \ - } \ - } while (0) -#endif diff --git a/components/darkforces/tfe/TFE_System/frameLimiter.h b/components/darkforces/tfe/TFE_System/frameLimiter.h deleted file mode 100644 index 505b3096..00000000 --- a/components/darkforces/tfe/TFE_System/frameLimiter.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine System Library -// System functionality, such as timers and logging. -////////////////////////////////////////////////////////////////////// - -#include "system.h" - -namespace TFE_System -{ - // Set the frame limit in Frames Per Second (FPS). - // A value of 0 sets no limit. - void frameLimiter_set(f64 limitFPS = 0.0); - f64 frameLimiter_getAccuracy(); - - void frameLimiter_begin(); - void frameLimiter_end(); -} diff --git a/components/darkforces/tfe/TFE_System/log.cpp b/components/darkforces/tfe/TFE_System/log.cpp deleted file mode 100644 index b312b538..00000000 --- a/components/darkforces/tfe/TFE_System/log.cpp +++ /dev/null @@ -1,65 +0,0 @@ -// ESP32 (esp-box-emu) logging: write to the serial console only. The desktop -// version also mirrors everything to a log file, but flushing a file on the SD -// card for every message is far too slow here. -#include -#include -#include - -#include - -namespace TFE_System -{ - static char s_msgStr[1024]; - static const char* c_typeNames[]= - { - "", //LOG_MSG = 0, - "Warning", //LOG_WARNING, - "Error", //LOG_ERROR, - "Critical", //LOG_CRITICAL, - }; - - bool logOpen(const char* filename) - { - (void)filename; - return true; - } - - void logClose() - { - } - - void debugWrite(const char* tag, const char* str, ...) - { - if (!tag || !str) { return; } - - va_list arg; - va_start(arg, str); - vsnprintf(s_msgStr, sizeof(s_msgStr), str, arg); - va_end(arg); - - printf("[%s] %s\n", tag, s_msgStr); - } - - void logWrite(LogWriteType type, const char* tag, const char* str, ...) - { - if (type >= LOG_COUNT || !tag || !str) { return; } - - va_list arg; - va_start(arg, str); - vsnprintf(s_msgStr, sizeof(s_msgStr), str, arg); - va_end(arg); - - // Strip a trailing newline, one is always added below. - size_t len = strlen(s_msgStr); - while (len && (s_msgStr[len - 1] == '\n' || s_msgStr[len - 1] == '\r')) { s_msgStr[--len] = 0; } - - if (type != LOG_MSG) - { - printf("[TFE %s : %s] %s\n", c_typeNames[type], tag, s_msgStr); - } - else - { - printf("[TFE %s] %s\n", tag, s_msgStr); - } - } -} diff --git a/components/darkforces/tfe/TFE_System/math.cpp b/components/darkforces/tfe/TFE_System/math.cpp deleted file mode 100644 index d3c065e5..00000000 --- a/components/darkforces/tfe/TFE_System/math.cpp +++ /dev/null @@ -1,145 +0,0 @@ -#include "math.h" - -namespace TFE_Math -{ - Mat3 computeViewMatrix(const Vec3f* lookDir, const Vec3f* upDir) - { - Vec3f rightDir = cross(lookDir, upDir); - rightDir = normalize(&rightDir); - - Vec3f orthoUp = cross(&rightDir, lookDir); - orthoUp = normalize(&orthoUp); - - return { rightDir, orthoUp, *lookDir }; - } - - Mat3 transpose(const Mat3& mtx) - { - Mat3 res; - res.m0 = { mtx.m0.x, mtx.m1.x, mtx.m2.x }; - res.m1 = { mtx.m0.y, mtx.m1.y, mtx.m2.y }; - res.m2 = { mtx.m0.z, mtx.m1.z, mtx.m2.z }; - - return res; - } - - Mat4 transpose4(Mat4 mtx) - { - Mat4 out; - out.m0 = { mtx.m0.x, mtx.m1.x, mtx.m2.x, mtx.m3.x }; - out.m1 = { mtx.m0.y, mtx.m1.y, mtx.m2.y, mtx.m3.y }; - out.m2 = { mtx.m0.z, mtx.m1.z, mtx.m2.z, mtx.m3.z }; - out.m3 = { mtx.m0.w, mtx.m1.w, mtx.m2.w, mtx.m3.w }; - return out; - } - - Mat4 computeProjMatrix(f32 fovInRadians, f32 aspectRatio, f32 zNear, f32 zFar) - { - // Build a projection matrix. - const f32 yScale = 1.0f / tanf(fovInRadians * 0.5f); - const f32 xScale = yScale / aspectRatio; - const f32 zScale = zFar / (zNear - zFar); - const f32 wScale = zNear * zFar / (zNear - zFar); - - Mat4 r; - r.m0 = { xScale, 0.0f, 0.0f, 0.0f }; - r.m1 = { 0.0f, yScale, 0.0f, 0.0f }; - r.m2 = { 0.0f, 0.0f, zScale, wScale }; - r.m3 = { 0.0f, 0.0f, -1.0f, 0.0f }; - - return r; - } - - Mat4 computeProjMatrixExplicit(f32 xScale, f32 yScale, f32 zNear, f32 zFar) - { - // Build a projection matrix. - const f32 zScale = zFar / (zNear - zFar); - const f32 wScale = zNear * zFar / (zNear - zFar); - - Mat4 r; - r.m0 = { xScale, 0.0f, 0.0f, 0.0f }; - r.m1 = { 0.0f, yScale, 0.0f, 0.0f }; - r.m2 = { 0.0f, 0.0f, zScale, wScale }; - r.m3 = { 0.0f, 0.0f, -1.0f, 0.0f }; - - return r; - } - - Mat4 computeInvProjMatrix(const Mat4& mtx) - { - const f32 xScale = mtx.m0.x; // a - const f32 yScale = mtx.m1.y; // b - const f32 zScale = mtx.m2.z; // c - const f32 wScale = mtx.m2.w; // d - const f32 w2 = mtx.m3.z; // e - - Mat4 inv = { 0 }; - inv.m0.x = 1.0f / xScale; - inv.m1.y = 1.0f / yScale; - inv.m2.w = 1.0f / w2; - inv.m3.z = 1.0f / wScale; - inv.m3.w = -zScale / (wScale * w2); - - return inv; - } - - Mat4 mulMatrix4(const Mat4& mtx0, const Mat4& mtx1) - { - Mat4 mtxOut; - mtxOut.data[0] = mtx0.data[0]*mtx1.data[0] + mtx0.data[1]*mtx1.data[4] + mtx0.data[2]*mtx1.data[8] + mtx0.data[3]*mtx1.data[12]; - mtxOut.data[1] = mtx0.data[0]*mtx1.data[1] + mtx0.data[1]*mtx1.data[5] + mtx0.data[2]*mtx1.data[9] + mtx0.data[3]*mtx1.data[13]; - mtxOut.data[2] = mtx0.data[0]*mtx1.data[2] + mtx0.data[1]*mtx1.data[6] + mtx0.data[2]*mtx1.data[10] + mtx0.data[3]*mtx1.data[14]; - mtxOut.data[3] = mtx0.data[0]*mtx1.data[3] + mtx0.data[1]*mtx1.data[7] + mtx0.data[2]*mtx1.data[11] + mtx0.data[3]*mtx1.data[15]; - - mtxOut.data[4] = mtx0.data[4]*mtx1.data[0] + mtx0.data[5]*mtx1.data[4] + mtx0.data[6]*mtx1.data[8] + mtx0.data[7]*mtx1.data[12]; - mtxOut.data[5] = mtx0.data[4]*mtx1.data[1] + mtx0.data[5]*mtx1.data[5] + mtx0.data[6]*mtx1.data[9] + mtx0.data[7]*mtx1.data[13]; - mtxOut.data[6] = mtx0.data[4]*mtx1.data[2] + mtx0.data[5]*mtx1.data[6] + mtx0.data[6]*mtx1.data[10] + mtx0.data[7]*mtx1.data[14]; - mtxOut.data[7] = mtx0.data[4]*mtx1.data[3] + mtx0.data[5]*mtx1.data[7] + mtx0.data[6]*mtx1.data[11] + mtx0.data[7]*mtx1.data[15]; - - mtxOut.data[8] = mtx0.data[8]*mtx1.data[0] + mtx0.data[9]*mtx1.data[4] + mtx0.data[10]*mtx1.data[8] + mtx0.data[11]*mtx1.data[12]; - mtxOut.data[9] = mtx0.data[8]*mtx1.data[1] + mtx0.data[9]*mtx1.data[5] + mtx0.data[10]*mtx1.data[9] + mtx0.data[11]*mtx1.data[13]; - mtxOut.data[10] = mtx0.data[8]*mtx1.data[2] + mtx0.data[9]*mtx1.data[6] + mtx0.data[10]*mtx1.data[10] + mtx0.data[11]*mtx1.data[14]; - mtxOut.data[11] = mtx0.data[8]*mtx1.data[3] + mtx0.data[9]*mtx1.data[7] + mtx0.data[10]*mtx1.data[11] + mtx0.data[11]*mtx1.data[15]; - - mtxOut.data[12] = mtx0.data[12]*mtx1.data[0] + mtx0.data[13]*mtx1.data[4] + mtx0.data[14]*mtx1.data[8] + mtx0.data[15]*mtx1.data[12]; - mtxOut.data[13] = mtx0.data[12]*mtx1.data[1] + mtx0.data[13]*mtx1.data[5] + mtx0.data[14]*mtx1.data[9] + mtx0.data[15]*mtx1.data[13]; - mtxOut.data[14] = mtx0.data[12]*mtx1.data[2] + mtx0.data[13]*mtx1.data[6] + mtx0.data[14]*mtx1.data[10] + mtx0.data[15]*mtx1.data[14]; - mtxOut.data[15] = mtx0.data[12]*mtx1.data[3] + mtx0.data[13]*mtx1.data[7] + mtx0.data[14]*mtx1.data[11] + mtx0.data[15]*mtx1.data[15]; - - return mtxOut; - } - - void buildRotationMatrix(Vec3f angles, Vec3f* mat) - { - if (angles.x == 0.0f && angles.y == 0.0f && angles.z == 0.0f) - { - // Identity. - mat[0] = { 1.0f, 0.0f, 0.0f }; - mat[1] = { 0.0f, 1.0f, 0.0f }; - mat[2] = { 0.0f, 0.0f, 1.0f }; - } - else if (angles.x == 0.0f && angles.z == 0.0f) - { - // Yaw only. - const f32 ca = cosf(angles.y); - const f32 sa = sinf(angles.y); - mat[0] = { ca, 0.0f, sa }; - mat[1] = { 0.0f, 1.0f, 0.0f }; - mat[2] = { -sa, 0.0f, ca }; - } - else - { - // Full orientation. - const f32 cZ = cosf(angles.x); - const f32 sZ = sinf(angles.x); - const f32 cY = cosf(angles.y); - const f32 sY = sinf(angles.y); - const f32 cX = cosf(angles.z); - const f32 sX = sinf(angles.z); - - mat[0] = { cZ * cY, cZ * sY * sX - sZ * cX, cZ * sY * cX + sZ * sX }; - mat[1] = { sZ * cY, sZ * sY * sX + cZ * cX, sZ * sY * cX - cZ * sX }; - mat[2] = {-sY, cY * sX, cY * cX }; - } - } -} diff --git a/components/darkforces/tfe/TFE_System/math.h b/components/darkforces/tfe/TFE_System/math.h deleted file mode 100644 index ba10c72a..00000000 --- a/components/darkforces/tfe/TFE_System/math.h +++ /dev/null @@ -1,153 +0,0 @@ -#pragma once - -#include "types.h" -#include -#include - -namespace TFE_Math -{ - inline f32 sign(f32 x) - { - return x < 0.0f ? -1.0f : 1.0f; - } - - inline bool isPow2(u32 x) - { - return (x > 0) && (x & (x - 1)) == 0; - } - - inline bool isPow2(s32 x) - { - return (x > 0) && (x & (x - 1)) == 0; - } - - inline u32 log2(u32 x) - { - if (x == 0 || x == 1) { return 0; } - - u32 l2 = 0; - while (x > 1) - { - l2++; - x >>= 1; - } - return l2; - } - - inline u32 nextPow2(u32 x) - { - if (x == 0) { return 0; } - - x--; - x |= x >> 1; - x |= x >> 2; - x |= x >> 4; - x |= x >> 8; - x |= x >> 16; - x++; - return x; - } - - inline f32 fract(f32 x) - { - return x - floorf(x); - } - - // the effective range is (-4.8, 4.8]. Outside of that the value is clamped at [-1, 1]. - inline f32 tanhf_series(f32 beta) - { - if (beta > 4.8f) { return 1.0f; } - else if (beta <= -4.8f) { return -1.0f; } - - const f32 x2 = beta * beta; - const f32 a = beta * (135135.0f + x2 * (17325.0f + x2 * (378.0f + x2))); - const f32 b = 135135.0f + x2 * (62370.0f + x2 * (3150.0f + x2 * 28.0f)); - return a / b; - } - - inline f32 dot(const Vec2f* p0, const Vec2f* p1) - { - return p0->x*p1->x + p0->z*p1->z; - } - - inline f32 dot(const Vec3f* p0, const Vec3f* p1) - { - return p0->x*p1->x + p0->y*p1->y + p0->z*p1->z; - } - - inline f32 dot(const Vec4f* p0, const Vec4f* p1) - { - return p0->x*p1->x + p0->y*p1->y + p0->z*p1->z + p0->w*p1->w; - } - - inline f32 distance(const Vec3f* p0, const Vec3f* p1) - { - Vec3f diff = { p1->x - p0->x, p1->y - p0->y, p1->z - p0->z }; - return sqrtf(dot(&diff, &diff)); - } - - inline f32 distance(const Vec2f* p0, const Vec2f* p1) - { - Vec2f diff = { p1->x - p0->x, p1->z - p0->z }; - return sqrtf(dot(&diff, &diff)); - } - - inline f32 distanceSq(const Vec3f* p0, const Vec3f* p1) - { - Vec3f diff = { p1->x - p0->x, p1->y - p0->y, p1->z - p0->z }; - return dot(&diff, &diff); - } - - inline f32 distanceSq(const Vec2f* p0, const Vec2f* p1) - { - Vec2f diff = { p1->x - p0->x, p1->z - p0->z }; - return dot(&diff, &diff); - } - - inline Vec3f normalize(const Vec3f* vec) - { - const f32 lenSq = dot(vec, vec); - Vec3f nrm; - if (lenSq > FLT_EPSILON) - { - const f32 scale = 1.0f / sqrtf(lenSq); - nrm = { vec->x * scale, vec->y * scale, vec->z * scale }; - } - else - { - nrm = *vec; - } - return nrm; - } - - inline Vec2f normalize(const Vec2f* vec) - { - const f32 lenSq = dot(vec, vec); - Vec2f nrm; - if (lenSq > FLT_EPSILON) - { - const f32 scale = 1.0f / sqrtf(lenSq); - nrm = { vec->x * scale, vec->z * scale }; - } - else - { - nrm = *vec; - } - return nrm; - } - - inline Vec3f cross(const Vec3f* a, const Vec3f* b) - { - return { a->y*b->z - a->z*b->y, a->z*b->x - a->x*b->z, a->x*b->y - a->y*b->x }; - } - - Mat3 computeViewMatrix(const Vec3f* lookDir, const Vec3f* upDir); - Mat3 transpose(const Mat3& mtx); - Mat4 transpose4(Mat4 mtx); - Mat4 computeProjMatrix(f32 fovInRadians, f32 aspectRatio, f32 zNear, f32 zFar); - Mat4 computeProjMatrixExplicit(f32 xScale, f32 yScale, f32 zNear, f32 zFar); - Mat4 computeInvProjMatrix(const Mat4& mtx); - Mat4 mulMatrix4(const Mat4& mtx0, const Mat4& mtx1); - - void buildRotationMatrix(Vec3f angles, Vec3f* mat); -} diff --git a/components/darkforces/tfe/TFE_System/memoryPool.h b/components/darkforces/tfe/TFE_System/memoryPool.h deleted file mode 100644 index a8715ddd..00000000 --- a/components/darkforces/tfe/TFE_System/memoryPool.h +++ /dev/null @@ -1,35 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Memory Pool -// A frame based memory allocator -////////////////////////////////////////////////////////////////////// - -#include "types.h" -#include -#include - -class MemoryPool -{ -public: - MemoryPool(); - - void init(size_t poolSize, const char* name); - - void clear(); - void* allocate(size_t size); - // Allocates a new block of memory and copies the old memory into the new memory. - // However this does not free the old memory since this is a frame based allocator - so this should be used sparingly. - void* reallocate(void* ptr, size_t oldSize, size_t newSize); - - void setWarningWatermark(size_t sizeToWarn) { m_waterMark = sizeToWarn; } - - size_t getMemoryUsed() const { return m_ptr; } - f32 getPercentUsed() const { return m_poolSize ? f32(m_ptr) / f32(m_poolSize) : 0.0f; } - -private: - std::vector m_memory; - std::string m_name; - size_t m_poolSize; - size_t m_waterMark; - size_t m_ptr; -}; diff --git a/components/darkforces/tfe/TFE_System/parser.cpp b/components/darkforces/tfe/TFE_System/parser.cpp deleted file mode 100644 index cb62006b..00000000 --- a/components/darkforces/tfe/TFE_System/parser.cpp +++ /dev/null @@ -1,324 +0,0 @@ -#include - -#include "parser.h" -#include -#include -#ifdef TFE_ESPBOX -#include -#include -#endif - -namespace -{ -#ifdef TFE_ESPBOX - static char* s_line = nullptr; // 4096 bytes (shared memory) -#else - static char s_line[4096]; -#endif - bool isWhitespace(const char c) - { - if (c > 32 && c < 127) - { - return false; - } - return true; - } - - bool isSeparator(const char c) - { - if (c == '=' || c == ',') - { - return true; - } - return false; - } -} - -TFE_Parser::TFE_Parser() : m_buffer(nullptr), m_bufferLen(0u), m_enableBlockComments(false), m_blockComment(false), m_enableColorSeperator(false), m_convertToUppercase(false) {} -#ifdef TFE_ESPBOX -TFE_Parser::~TFE_Parser() -{ - free(m_window); -} - -namespace -{ - // Window size and the amount kept available ahead of the read position (must - // exceed the longest line, which s_line limits to 4096 bytes). - constexpr size_t WINDOW_SIZE = 64 * 1024; - constexpr size_t WINDOW_RESERVE = 8 * 1024; -} - -bool TFE_Parser::initFromFile(FileStream* file) -{ - if (!m_window) - { - m_window = (char*)malloc(WINDOW_SIZE + 1); - if (!m_window) { return false; } - } - m_file = file; - m_buffer = m_window; - m_bufferLen = 0; - m_fileSize = file->getSize(); - m_filePos = 0; - m_eof = (m_fileSize == 0); - size_t pos = 0; - refillWindow(pos); - return true; -} - -// Keep at least WINDOW_RESERVE bytes available after bufferPos (until the end of -// the file): drop what has been consumed and read the next part of the file. -void TFE_Parser::refillWindow(size_t& bufferPos) -{ - if (!m_file || m_eof || m_bufferLen - bufferPos >= WINDOW_RESERVE) { return; } - if (bufferPos > 0) - { - memmove(m_window, m_window + bufferPos, m_bufferLen - bufferPos); - m_bufferLen -= bufferPos; - bufferPos = 0; - } - // The loaders open other files while parsing (textures, palettes, ...), some of - // them in the same archive, which moves the archive's current file and - // position: select this file again and seek to where the window ended. The - // read is also clamped to the file (archive reads are not). - size_t want = WINDOW_SIZE - m_bufferLen; - if (want > m_fileSize - m_filePos) { want = m_fileSize - m_filePos; } - m_file->reselect(); - m_file->seek((s32)m_filePos); - // Read byte-wise elements: a single element of `want` bytes would read nothing - // at all once fewer bytes than that remain in the file. - const size_t got = want ? m_file->readBuffer(m_window + m_bufferLen, 1, (u32)want) : 0; - m_bufferLen += got; - m_filePos += got; - m_window[m_bufferLen] = 0; // the block comment check looks one byte ahead. - if (got < want || m_filePos >= m_fileSize) { m_eof = true; } -} -#else -TFE_Parser::~TFE_Parser() {} -#endif - -void TFE_Parser::init(const char* buffer, size_t len) -{ - m_buffer = buffer; - m_bufferLen = len; -#ifdef TFE_ESPBOX - m_file = nullptr; - m_eof = true; -#endif -} - -// Enable block comments of the form /*...*/ -void TFE_Parser::enableBlockComments() -{ - m_enableBlockComments = true; -} - -// Enable : as a seperator but do not remove it. -void TFE_Parser::enableColonSeperator() -{ - m_enableColorSeperator = true; -} - -// Add a string representing a comment, such as ";" "#" "//" -void TFE_Parser::addCommentString(const char* comment) -{ - m_commentStrings.push_back(comment); -} - -// Convert resulting strings to upper case, defaults to false. -void TFE_Parser::convertToUpperCase(bool enable) -{ - m_convertToUppercase = enable; -} - -bool TFE_Parser::isComment(const char* buffer) -{ - const size_t commentCount = m_commentStrings.size(); - const std::string* comments = m_commentStrings.data(); - for (size_t c = 0; c < commentCount; c++) - { - if (strncmp(comments[c].c_str(), buffer, comments[c].length()) == 0) - { - return true; - } - } - return false; -} - -// Read the next non-comment/whitespace line. -const char* TFE_Parser::readLine(size_t& bufferPos, bool skipLeadingWhitespace, bool commentOnlyAtBeginning) -{ -#ifdef TFE_ESPBOX - refillWindow(bufferPos); -#endif - if (bufferPos >= m_bufferLen || m_bufferLen < 1) { return nullptr; } - - // Keep reading lines until either one has real content or we reach the end of the buffer. - bool lineHasContent = false; - s32 skip = -1; - while (!lineHasContent) - { -#ifdef TFE_ESPBOX - // Refill before testing for the end: the window may have been consumed exactly - // up to its end by the previous line while the file still has more. - refillWindow(bufferPos); -#endif - if (bufferPos >= m_bufferLen) { break; } - s_line[0] = 0; - size_t linePos = 0; - bool inComment = false; - for (size_t i = bufferPos; i < m_bufferLen; i++) - { - bufferPos = i + 1; - - if (m_enableBlockComments && i > 0 && m_buffer[i-1] == '*' && m_buffer[i] == '/') - { - m_blockComment = false; - } - else if (m_enableBlockComments && m_buffer[i] == '/' && m_buffer[i+1] == '*') - { - m_blockComment = true; - } - else if (m_buffer[i] == '\n' || m_buffer[i] == '\r') - { - // search for the next valid character, then end it. - for (size_t ii = i + 1; ii < m_bufferLen; ii++) - { - if (m_buffer[ii] != '\n' && m_buffer[ii] != '\r') - { - bufferPos = ii; - break; - } - } - break; - } - else if (!inComment && !m_blockComment) - { - // is this the beginning of a comment? - if (!commentOnlyAtBeginning) - { - inComment = isComment(m_buffer + i); - } - - // if not in a comment, go ahead and add to the line. - if (!inComment) - { - if (m_convertToUppercase) - { - s_line[linePos++] = toupper(m_buffer[i]); - } - else - { - s_line[linePos++] = m_buffer[i]; - } - } - } - } - s_line[linePos] = 0; - - // check to see if the line has any content. - lineHasContent = false; - skip = -1; - for (size_t i = 0; i < linePos; i++) - { - // Content is any non-white space character. - if (!isWhitespace(s_line[i])) - { - // Is this a comment? - if (commentOnlyAtBeginning && isComment(&s_line[i])) - { - break; - } - if (skip < 0) { skip = s32(i); } - lineHasContent = true; - break; - } - } - } - - if (lineHasContent && skipLeadingWhitespace && skip > 0) - { - return &s_line[skip]; - } - - return s_line[0]!=0 ? s_line : nullptr; -} - -// Split a line into tokens using space, comma or equals as separators. -// Note strings with spaces still work, they need to be closed in quotes, which are removed upon tokenizing. -void TFE_Parser::tokenizeLine(const char* line, TokenList& tokens) -{ - tokens.clear(); - - const size_t len = strlen(line); - // first move past leading whitespace and ending white space. - size_t start = 0, end = 0; - for (size_t c = 0; c < len; c++) - { - if (!isWhitespace(line[c])) - { - if (start == 0 && end == 0) { start = c; } - end = c + 1; - } - } - - // next start reading tokens. - bool inQuote = false; - char curToken[1024]; - size_t curTokenPos = 0; - // TODO: Add an option to allow white space in tokens when not in quotes, but still remove trailing/ending whitespace. - // This is useful for names. - for (size_t c = start; c < end; c++) - { - if (line[c] == '"') - { - if (inQuote && curTokenPos == 0) - { - tokens.push_back(""); - } - inQuote = !inQuote; - } - else if (!inQuote && (isWhitespace(line[c]) || isSeparator(line[c]))) - { - curToken[curTokenPos] = 0; - if (curTokenPos) - { - tokens.push_back(curToken); - } - - curTokenPos = 0; - curToken[0] = 0; - } - else if (!inQuote && m_enableColorSeperator && line[c] == ':') - { - curToken[curTokenPos++] = line[c]; - - curToken[curTokenPos] = 0; - if (curTokenPos) - { - tokens.push_back(curToken); - } - - curTokenPos = 0; - curToken[0] = 0; - } - else - { - curToken[curTokenPos++] = line[c]; - } - } - - if (curTokenPos) - { - curToken[curTokenPos] = 0; - tokens.push_back(curToken); - } -} - -#ifdef TFE_ESPBOX -void espbox_shared_parser(bool alloc) -{ - ESPBOX_SHARED_ALLOC(s_line, 4096); -} -#endif diff --git a/components/darkforces/tfe/TFE_System/parser.h b/components/darkforces/tfe/TFE_System/parser.h deleted file mode 100644 index fe77d134..00000000 --- a/components/darkforces/tfe/TFE_System/parser.h +++ /dev/null @@ -1,66 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine System Library -// System functionality, such as timers and logging. -////////////////////////////////////////////////////////////////////// - -#include "types.h" -#include -#include - -typedef std::vector TokenList; -class FileStream; - -class TFE_Parser -{ -public: - TFE_Parser(); - ~TFE_Parser(); - - void init(const char* buffer, size_t len); -#ifdef TFE_ESPBOX - // Parse straight from an open file through a small sliding window instead of - // a buffer holding the whole file (level files are up to ~1MB). The file must - // stay open while the parser is used; readLine() keeps bufferPos valid across - // window refills. - bool initFromFile(FileStream* file); -#endif - - // Enable block comments of the form /*...*/ - void enableBlockComments(); - - // Enable : as a seperator but do not remove it. - void enableColonSeperator(); - - // Add a string representing a comment, such as ";" "#" "//" - void addCommentString(const char* comment); - - // Convert resulting strings to upper case, defaults to false. - void convertToUpperCase(bool enable); - - // Read the next non-comment/whitespace line. - const char* readLine(size_t& bufferPos, bool skipLeadingWhitespace = false, bool commentOnlyAtBeginning = false); - // Split a line into tokens using space, comma or equals as separators. - // Note strings with spaces still work, they need to be closed in quotes, which are removed upon tokenizing. - void tokenizeLine(const char* line, TokenList& tokens); - -private: - const char* m_buffer; - size_t m_bufferLen; - TokenList m_commentStrings; - bool m_enableBlockComments; - bool m_blockComment; - bool m_enableColorSeperator; - bool m_convertToUppercase; - -private: - bool isComment(const char* buffer); -#ifdef TFE_ESPBOX - void refillWindow(size_t& bufferPos); - FileStream* m_file = nullptr; - char* m_window = nullptr; - bool m_eof = true; - size_t m_fileSize = 0; - size_t m_filePos = 0; // bytes of the file read into the window so far -#endif -}; diff --git a/components/darkforces/tfe/TFE_System/profiler.h b/components/darkforces/tfe/TFE_System/profiler.h deleted file mode 100644 index ffed7196..00000000 --- a/components/darkforces/tfe/TFE_System/profiler.h +++ /dev/null @@ -1,113 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Profiler -// Simple "zone" based profiler. -// Add TFE_PROFILE_ENABLED to preprocessor defines in the build to enable. -// Currently does not respect the call path, that is TODO. -////////////////////////////////////////////////////////////////////// - -#include "types.h" -#include "system.h" - -#ifndef TFE_ESPBOX -#define TFE_PROFILE_ENABLED 1 -#endif - -#define TOKENPASTE(x, y) x ## y -#define TOKENPASTE2(x, y) TOKENPASTE(x, y) -#ifdef TFE_PROFILE_ENABLED -#define TFE_ZONE(name) TFE_Profiler_Zone TOKENPASTE2(__localZone, __LINE__)(name, __FUNCTION__, __LINE__) -#define TFE_ZONE_BEGIN(varName, name) TFE_Profiler_ZoneManual varName(name, __FUNCTION__, __LINE__) -#define TFE_ZONE_END(varName) varName.end() -#define TFE_FRAME_BEGIN() TFE_Profiler::frameBegin() -#define TFE_FRAME_END() TFE_Profiler::frameEnd() -#define TFE_COUNTER(varName, name) TFE_Profiler::addCounter(name, &varName) -#else -#define TFE_ZONE(name) -#define TFE_ZONE_BEGIN(varName, name) -#define TFE_ZONE_END(varName) -#define TFE_FRAME_BEGIN() -#define TFE_FRAME_END() -#define TFE_COUNTER(varName, name) -#endif - -#define NULL_ZONE 0xffffffff - -#ifdef TFE_PROFILE_ENABLED -struct TFE_ZoneInfo -{ - char* name; - char* func; - u32 lineNumber; - u32 level; - u32 parentId; - f64 timeInZone; - f64 timeInZoneAve; - f64 fractOfParentAve; -}; - -struct TFE_CounterInfo -{ - char* name; - s32 value; -}; - -namespace TFE_Profiler -{ - // The main profiling API is used through Macros which can be disabled based on build flags. - u32 beginZone(const char* name, const char* func, u32 lineNumber); - void endZone(u32 id, u64 dt); - - void frameBegin(); - void frameEnd(); - - void addCounter(const char* name, s32* counter); - - // Profile data API, this is used directly. - f64 getTimeInFrame(); - - u32 getZoneCount(); - void getZoneInfo(u32 index, TFE_ZoneInfo* info); - - u32 getCounterCount(); - void getCounterInfo(u32 index, TFE_CounterInfo* info); -} - -class TFE_Profiler_Zone -{ -public: - TFE_Profiler_Zone(const char* name, const char* func, u32 lineNumber) - { - m_time = TFE_System::getCurrentTimeInTicks(); - m_id = TFE_Profiler::beginZone(name, func, lineNumber); - } - - ~TFE_Profiler_Zone() - { - const u64 deltaTime = TFE_System::getCurrentTimeInTicks() - m_time; - TFE_Profiler::endZone(m_id, deltaTime); - } -private: - u64 m_time; - s32 m_id; -}; - -class TFE_Profiler_ZoneManual -{ -public: - TFE_Profiler_ZoneManual(const char* name, const char* func, u32 lineNumber) - { - m_time = TFE_System::getCurrentTimeInTicks(); - m_id = TFE_Profiler::beginZone(name, func, lineNumber); - } - - void end() - { - const u64 deltaTime = TFE_System::getCurrentTimeInTicks() - m_time; - TFE_Profiler::endZone(m_id, deltaTime); - } -private: - u64 m_time; - s32 m_id; -}; -#endif diff --git a/components/darkforces/tfe/TFE_System/system.cpp b/components/darkforces/tfe/TFE_System/system.cpp deleted file mode 100644 index c8d9923c..00000000 --- a/components/darkforces/tfe/TFE_System/system.cpp +++ /dev/null @@ -1,204 +0,0 @@ -// ESP32 (esp-box-emu) version of the TFE system layer. -// Timing is based on esp_timer (microsecond resolution); everything else that -// the desktop version does (SDL, shell execution, vsync tracking) is stubbed. -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace TFE_System -{ - f64 c_gameTimeScale = 1.02; // Adjust game time to match DosBox. - - static u64 s_time; - static u64 s_startTime; - static f64 s_freq; - static f64 s_refreshRate; - - static f64 s_dt = 1.0 / 60.0; // This is just to handle the first frame, so any reasonable value will work. - static f64 s_dtRaw = 1.0 / 60.0; - static const f64 c_maxDt = 0.05; // 20 fps - - static bool s_synced = false; - static bool s_resetStartTime = false; - static bool s_quitMessagePosted = false; - static bool s_systemUiRequestPosted = false; - - static char s_versionString[64]; - - static inline u64 perfCounter() - { - return (u64)esp_timer_get_time(); - } - - void init(f32 refreshRate, bool synced, const char* versionString) - { - TFE_System::logWrite(LOG_MSG, "Startup", "TFE_System::init"); - s_time = perfCounter(); - s_startTime = s_time; - s_freq = 1.0 / 1000000.0; // esp_timer runs in microseconds. - - s_refreshRate = f64(refreshRate); - s_synced = synced; - s_resetStartTime = false; - s_quitMessagePosted = false; - s_systemUiRequestPosted = false; - - strncpy(s_versionString, versionString ? versionString : "", sizeof(s_versionString) - 1); - s_versionString[sizeof(s_versionString) - 1] = 0; - } - - void shutdown() - { - } - - void setVsync(bool sync) - { - s_synced = sync; - } - - bool getVSync() - { - return s_synced; - } - - const char* getVersionString() - { - return s_versionString; - } - - void resetStartTime() - { - s_resetStartTime = true; - } - - f64 updateThreadLocal(u64* localTime) - { - const u64 curTime = perfCounter(); - const u64 uDt = (*localTime) > 0u ? curTime - (*localTime) : 0u; - - const f64 dt = f64(uDt) * s_freq; - *localTime = curTime; - - return dt; - } - - void update() - { - const u64 curTime = perfCounter(); - const u64 uDt = (curTime > s_time) ? (curTime - s_time) : 1; // Make sure time is monotonic. - s_time = curTime; - if (s_resetStartTime) - { - s_startTime = s_time; - s_resetStartTime = false; - } - - // Delta time since the previous frame. - f64 dt = f64(uDt) * s_freq; - s_dtRaw = dt; - // Make sure that if the current fps is too low, the game just slows down. - // This avoids the "spiral of death" when using fixed time steps and avoids issues - // during loading spikes. - s_dt = std::min(dt, c_maxDt); - } - - // Timing - // Return the delta time. - f64 getDeltaTime() - { - return s_dt; - } - - f64 getDeltaTimeRaw() - { - return s_dtRaw; - } - - // Get time since "start time" - f64 getTime() - { - const u64 uDt = s_time - s_startTime; - return f64(uDt) * s_freq; - } - - u64 getCurrentTimeInTicks() - { - return perfCounter() - s_startTime; - } - - f64 convertFromTicksToSeconds(u64 ticks) - { - return f64(ticks) * s_freq; - } - - f64 microsecondsToSeconds(f64 mu) - { - return mu / 1000000.0; - } - - void getDateTimeString(char* output) - { - time_t _tm = time(NULL); - struct tm* curtime = localtime(&_tm); - const char* str = curtime ? asctime(curtime) : nullptr; - if (str) - { - strcpy(output, str); - // asctime() appends a newline, remove it. - size_t len = strlen(output); - if (len && output[len - 1] == '\n') { output[len - 1] = 0; } - } - else - { - strcpy(output, "unknown"); - } - } - - bool osShellExecute(const char* pathToExe, const char* exeDir, const char* param, bool waitForCompletion) - { - return false; - } - - void sleep(u32 sleepDeltaMS) - { - if (sleepDeltaMS == 0) - { - taskYIELD(); - return; - } - vTaskDelay(pdMS_TO_TICKS(sleepDeltaMS) ? pdMS_TO_TICKS(sleepDeltaMS) : 1); - } - - void postQuitMessage() - { - s_quitMessagePosted = true; - } - - void postSystemUiRequest() - { - s_systemUiRequestPosted = true; - } - - bool quitMessagePosted() - { - return s_quitMessagePosted; - } - - bool systemUiRequestPosted() - { - bool systemUiPostReq = s_systemUiRequestPosted; - s_systemUiRequestPosted = false; - return systemUiPostReq; - } -} diff --git a/components/darkforces/tfe/TFE_System/system.h b/components/darkforces/tfe/TFE_System/system.h deleted file mode 100644 index 6a3da442..00000000 --- a/components/darkforces/tfe/TFE_System/system.h +++ /dev/null @@ -1,89 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine System Library -// System functionality, such as timers and logging. -////////////////////////////////////////////////////////////////////// - -#include -#include "types.h" - -#define TFE_MAJOR_VERSION 0 -#define TFE_MINOR_VERSION 2 -#define TFE_BUILD_VERSION 1 - -enum LogWriteType -{ - LOG_MSG = 0, - LOG_WARNING, - LOG_ERROR, - LOG_CRITICAL, //Critical log messages are CRITICAL errors that also act as asserts when attached to a debugger. - LOG_COUNT -}; - -namespace TFE_System -{ - void init(f32 refreshRate, bool synced, const char* versionString); - void shutdown(); - void resetStartTime(); - void setVsync(bool sync); - bool getVSync(); - - void update(); - f64 updateThreadLocal(u64* localTime); - - // Timing - // --- The current time and delta time are determined once per frame, during the update() function. - // In other words an entire frame operates on a single instance of time. - // Return the delta time. - f64 getDeltaTime(); - f64 getDeltaTimeRaw(); - // Get the absolute time since the last start time. - f64 getTime(); - - u64 getCurrentTimeInTicks(); - f64 convertFromTicksToSeconds(u64 ticks); - f64 microsecondsToSeconds(f64 mu); - - void getDateTimeString(char* output); - - // Log - bool logOpen(const char* filename); - void logClose(); - void logWrite(LogWriteType type, const char* tag, const char* str, ...); - - // Lighter weight debug output (only useful when running in a terminal or debugger). - void debugWrite(const char* tag, const char* str, ...); - - // System - bool osShellExecute(const char* pathToExe, const char* exeDir, const char* param, bool waitForCompletion); - void sleep(u32 sleepDeltaMS); - - void postQuitMessage(); - bool quitMessagePosted(); - - void postSystemUiRequest(); - bool systemUiRequestPosted(); - - const char* getVersionString(); - - extern f64 c_gameTimeScale; -} - -// _strlwr/_strupr exist on Windows; roll our own -// and use them throghout. This works on Windows -// and Linux/unix-like. -static inline void __strlwr(char *c) -{ - while (*c) { - *c = tolower(*c); - c++; - } -} - -static inline void __strupr(char *c) -{ - while (*c) { - *c = toupper(*c); - c++; - } -} diff --git a/components/darkforces/tfe/TFE_System/tfeMessage.h b/components/darkforces/tfe/TFE_System/tfeMessage.h deleted file mode 100644 index 5cccc0c0..00000000 --- a/components/darkforces/tfe/TFE_System/tfeMessage.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once -////////////////////////////////////////////////////////////////////// -// The Force Engine Profiler -// Simple "zone" based profiler. -// Add TFE_PROFILE_ENABLED to preprocessor defines in the build to enable. -// Currently does not respect the call path, that is TODO. -////////////////////////////////////////////////////////////////////// - -#include "types.h" -#include "system.h" - -enum TFE_Message -{ - TFE_MSG_SAVE = 0, - TFE_MSG_SECRET, - TFE_MSG_FLYMODE, - TFE_MSG_NOCLIP, - TFE_MSG_TESTER, - TFE_MSG_COUNT -}; - -namespace TFE_System -{ - const char* getMessage(TFE_Message msg); - bool loadMessages(const char* path); - void freeMessages(); -} \ No newline at end of file diff --git a/components/darkforces/tfe/TFE_System/types.h b/components/darkforces/tfe/TFE_System/types.h deleted file mode 100644 index 7584881e..00000000 --- a/components/darkforces/tfe/TFE_System/types.h +++ /dev/null @@ -1,154 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -typedef uint64_t u64; -typedef int64_t s64; -#ifdef TFE_ESPBOX -// On the ESP32 toolchain int32_t is 'long'; use plain int so that integer -// literals resolve to the s32/u32 overloads (min/max/clamp) as on the desktop. -typedef unsigned int u32; -typedef int s32; -#else -typedef uint32_t u32; -typedef int32_t s32; -#endif -typedef uint16_t u16; -typedef int16_t s16; -typedef uint8_t u8; -typedef int8_t s8; -typedef intptr_t iptr; -typedef float f32; -typedef double f64; - -#ifdef TFE_ESPBOX -typedef uint32_t atomic_u32; -typedef int32_t atomic_s32; -typedef float atomic_f32; -typedef bool atomic_bool; -#else -typedef std::atomic atomic_u32; -typedef std::atomic atomic_s32; -typedef std::atomic atomic_f32; -typedef std::atomic atomic_bool; -#endif - -struct Vec2f -{ - union - { - struct { f32 x, z; }; - f32 m[2]; - }; -}; - -struct Vec3f -{ - union - { - struct { f32 x, y, z; }; - f32 m[3]; - }; -}; - -struct Vec4f -{ - union - { - struct { f32 x, y, z, w; }; - f32 m[4]; - }; -}; - -struct Vec2i -{ - union - { - struct { s32 x, z; }; - s32 m[2]; - }; -}; - -struct Vec3i -{ - union - { - struct { s32 x, y, z; }; - s32 m[3]; - }; -}; - -struct Vec4i -{ - union - { - struct { s32 x, y, z, w; }; - s32 m[4]; - }; -}; - -struct Vec4ui -{ - union - { - struct { u32 x, y, z, w; }; - u32 m[4]; - }; -}; - -struct Mat3 -{ - union - { - struct { Vec3f m0, m1, m2; }; - struct { Vec3f m[3]; }; - f32 data[9]; - }; -}; - -struct Mat4 -{ - union - { - struct { Vec4f m0, m1, m2, m3; }; - struct { Vec4f m[4]; }; - f32 data[16]; - }; -}; - -// Jedi "Bool" type. -typedef u32 JBool; -enum JediBool : u32 -{ - JTRUE = 0xffffffffu, - JFALSE = 0u, -}; - -#ifdef _WIN32 -#define strcasecmp _stricmp -#define strncasecmp _strnicmp -#endif - -#ifdef _WIN32 -#define TFE_STDCALL __stdcall -#else -#define TFE_STDCALL -#endif - -#define TFE_ARRAYSIZE(arr) (sizeof(arr)/sizeof(*arr)) // Size of a static C-style array. Don't use on pointers! - -#define FLAG_BIT(bit) (1u << u32(bit)) -#define SIGN_BIT(x) ((x)<0?1:0) - -// Move to math -#define PI 3.14159265358979323846f - -enum AssetPool -{ - POOL_GAME = 0, - POOL_LEVEL, - POOL_COUNT -}; \ No newline at end of file diff --git a/components/doom/CMakeLists.txt b/components/doom/CMakeLists.txt index dbe63476..f83725f6 100644 --- a/components/doom/CMakeLists.txt +++ b/components/doom/CMakeLists.txt @@ -1,7 +1,9 @@ +# Doom: PrBoom, from the esp-cpp/prboom submodule (the engine in +# prboom/prboom, its glue in prboom/port) idf_component_register( - INCLUDE_DIRS "include" - SRC_DIRS "src" "prboom" - PRIV_INCLUDE_DIRS "." "prboom" + INCLUDE_DIRS "prboom/port/include" + SRC_DIRS "prboom/port" "prboom/prboom" + PRIV_INCLUDE_DIRS "prboom" "prboom/prboom" LDFRAGMENTS "linker.lf" REQUIRES box-emu shared_memory ) diff --git a/components/doom/data/doom1.wad b/components/doom/data/doom1.wad deleted file mode 100644 index 1a58f662..00000000 Binary files a/components/doom/data/doom1.wad and /dev/null differ diff --git a/components/doom/data/prboom.wad b/components/doom/data/prboom.wad deleted file mode 100644 index be73e432..00000000 Binary files a/components/doom/data/prboom.wad and /dev/null differ diff --git a/components/doom/include/doom.hpp b/components/doom/include/doom.hpp deleted file mode 100644 index f5c835d2..00000000 --- a/components/doom/include/doom.hpp +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -void reset_doom(); -void init_doom(const std::string& rom_filename, uint8_t *romdata, size_t rom_data_size); -void doom_init_shared_memory(); -void pause_doom_tasks(); -void resume_doom_tasks(); -void load_doom(std::string_view save_path, int save_slot); -void save_doom(std::string_view save_path, int save_slot); -void run_doom_rom(); -void deinit_doom(); -std::span get_doom_video_buffer(); diff --git a/components/doom/prboom b/components/doom/prboom new file mode 160000 index 00000000..b18131f6 --- /dev/null +++ b/components/doom/prboom @@ -0,0 +1 @@ +Subproject commit b18131f69c42c55164c2cec1073157629a1a3a79 diff --git a/components/doom/prboom/AUTHORS b/components/doom/prboom/AUTHORS deleted file mode 100644 index 7839f8ed..00000000 --- a/components/doom/prboom/AUTHORS +++ /dev/null @@ -1,163 +0,0 @@ -This file is now the amalgamated list of authors, contributors and credits -for PrBoom. Hopefully by keeping these all in one place, they will remain -more accurate. - -Doom was originally written by id software; when playing with any id main -wad file, you can see their list of credits, which includes the list of -programmers. After some years, they released the source code, to allow -others to work on improving the game. - -One of the first projects was DosDoom, by Chi Hoang. This was a quick port -of the released source code, which was for Linux, to DOS. This was then -picked up by TeamTNT (http://www.teamtnt.com/), who produced Boom, a greatly -debugged and extended version of Doom. The Boom programmers were Lee -Killough, Jim Flynn, Rand Phares, Ty Halderman. - -Several projects started working from the Boom source code. One was PrBoom, -made by Florian Schulze, that ported the code to Windows, added suport for -higher resolutions and later OpenGL. Another was Marine's Best Friend -(known as MBF) by Lee Killough, which fixed a lot of Boom bugs and added -many new game features. Finally, there was LxDoom, a port of Boom to Linux -by Colin Phipps. - -In October 1999, id Software re-released the Doom source code under the -GNU General Public License. TeamTNT have also changed to the new license, -and the other sources mentioned above have all allowed their code to be -GPLed. So PrBoom is covered by the GPL. - -In May 2000, LxDoom, PrBoom, and a derived port called LSDLDoom, merged into -one. The current authors of PrBoom are: - -Florian Schulze -Colin Phipps -Neil Stevens - Mac OS X porting -Andrey Budko -Rob Young (RjY) - -Our thanks go to all the authors of the ports mentioned above, and also the -following people who contributed code to LxDoom or PrBoom: - -Jess Haas -Of LSDLdoom, who merged his project into PrBoom, contributing his SDL code. - -Nicolas Kalkhof -Much work on the OpenGL renderer. - -James "Quasar" Haley -Ever willing to talk about source ideas, and has pointed me in the direction of -a lot of Boom and MBF bugs; also various bits code from his port Eternity have -been used, such as the BEX enhancements. - -Bob Aman (sporkmonger.com) -Created the RMUDAnsiTextView class used in the Mac launcher. - -Gady Kozma gady@math.tau.ac.il -Added hires to the SVGALib version of LxDoom, and other useful patches. - -Dick Leban -Lots of feedback about portability issues and helping get the network code -working properly back at v1.3.6. - -Eduardo Casino Almao -Lots of helpful feedback and suggestions, but more importantly actually getting -to grips with the code and giving very precise bug reports and patches. - -Joey Hess -For numerous patches, like the glibc fixes and window manager updates, and -help with the music. - -Ben Winslow -Various useful patches, like the colour ENDOOM code. - -Josh Parsons josh@schlick.anu.edu.au -Sent me the patches to use autoconf for configuring LxDoom. - -Steve Van Devender -Found the bug causing slight noise at the start of sounds playing, and other -patches. - -Barry Mead -Improvements to the mouse code and other odd patches. - -Mattias Kunkel -Made the lxdoom.spec file for creating LxDoom RPMs. - -Vicente Aguilar vicente@hal.dhis.org -Handy patch for the file handling - -Benjamin L McGee -Patch fixing the joystick code. - -Chris Young -Patch improving the ENDOOM printing - -Peter Jay Salzman -Cleanup patches - -Oliver Kraus -Send bug reports and patches for Solaris/Sparc. - -Paul S Jenner -Nice patch to make RPM building easier - -Julian -Fixed inline asm for gcc-2.95 (from Eternity) - -Lionel Ulmer -Patch to fix alignment problems on ARM processors. - -Ville Vuorinen -Spotted and helped patch the player spawn bug, as well as helping with some -Win32 issues. - -Steven Elliot -Misc patches. - -Andreas Dehmel -Spotted & patched a savegame bug. - -Jon Dowland -Bug reports & fixes, documentation improvements. - -If you have sent in patches and I forgot to list you, I apologise. Please email -me and I will add you. - -Also, thanks to the following people who have helped in various ways: - -Simon "fraggle" Howard -More MBF bugs. - -Robert Phipps -Network game testing, feature suggestions etc. - -Udo Monk -His port xdoom is very portable, and I referred to his code sometimes for help -with the X stuff; also his collection of Doom tools (XWadTools) is the -definitive tools collection for Linux. - -Andre Majorel -For Yadex, so I can debug those problematic levels more easily. - -Michael Heasley -Author of musserver, which helped me first add music support. - -Rafael Reilova -Helped with the music server program for LxDoom - -Frederic Oghdayan -For useful feedback on LxDoom v1.0.1, and repeating his bug reports until I -believed them :-). - -Adam Hegyi -Prompted me to hunt down those last few demo sync bugs, and provided some useful -insights and example demos to help. - -Adam Williamson -Pointing me toward yet another compatibility bug. - -Ingo van Lil -Another bug spotter. - -Everyone who contributed indirectly to MBF and Boom and Doom; see the -respective documentation files. - diff --git a/components/doom/prboom/CMakeLists.txt b/components/doom/prboom/CMakeLists.txt deleted file mode 100644 index 3f4b6f83..00000000 --- a/components/doom/prboom/CMakeLists.txt +++ /dev/null @@ -1,19 +0,0 @@ -set(COMPONENT_SRCDIRS ".") -set(COMPONENT_ADD_INCLUDEDIRS ".") -set(COMPONENT_REQUIRES "retro-go") -register_component() - -# The PSRAM cache bug seems responsible for very odd bugs that I spent way too much time -# trying to debug... In retro-go the fix is disabled because of the huge performance overhead -# but I guess we'll have to live with it in at least the prboom-go module... - -rg_setup_compile_options( - -Wno-error=address - -Wno-misleading-indentation - -Wno-format-overflow - -Wno-char-subscripts - -Wno-missing-field-initializers - -mfix-esp32-psram-cache-issue - -DHAVE_CONFIG_H - -O2 -) diff --git a/components/doom/prboom/COPYING b/components/doom/prboom/COPYING deleted file mode 100644 index f698bce6..00000000 --- a/components/doom/prboom/COPYING +++ /dev/null @@ -1,367 +0,0 @@ -GNU GENERAL PUBLIC LICENSE -Version 2, June 1991 - -Copyright (C) 1989, 1991 Free Software Foundation, Inc. -59 Temple Place - Suite 330, Boston, MA 02111-1307, USA - -Everyone is permitted to copy and distribute verbatim copies -of this license document, but changing it is not allowed. - -Preamble -The licenses for most software are designed to take away your freedom -to share and change it. By contrast, the GNU General Public License -is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit -to using it. (Some other Free Software Foundation software is covered -by the GNU Library General Public License instead.) You can apply it -to your programs, too. - -When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge -for this service if you wish), that you receive source code or can -get it if you want it, that you can change the software or use pieces -of it in new free programs; and that you know you can do these -things. - -To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the software, or if you modify it. - -For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - -We protect your rights with two steps: (1) copyright the software, -and (2) offer you this license which gives you legal permission to -copy, distribute and/or modify the software. - -Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, -we want its recipients to know that what they have is not the -original, so that any problems introduced by others will not reflect -on the original authors' reputations. - -Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making -the program proprietary. To prevent this, we have made it clear that -any patent must be licensed for everyone's free use or not licensed -at all. - -The precise terms and conditions for copying, distribution and -modification follow. - -TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION -0. This License applies to any program or other work which contains a -notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the -Program is covered only if its contents constitute a work based on -the Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - -1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any -warranty; and give any other recipients of the Program a copy of this -License along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a -fee. - -2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - -a) You must cause the modified files to carry prominent notices -stating that you changed the files and the date of any change. - -b) You must cause any work that you distribute or publish, that in -whole or in part contains or is derived from the Program or any part -thereof, to be licensed as a whole at no charge to all third parties -under the terms of this License. - -c) If the modified program normally reads commands interactively when -run, you must cause it, when started running for such interactive use -in the most ordinary way, to print or display an announcement -including an appropriate copyright notice and a notice that there is -no warranty (or else, saying that you provide a warranty) and that -users may redistribute the program under these conditions, and -telling the user how to view a copy of this License. (Exception: if -the Program itself is interactive but does not normally print such an -announcement, your work based on the Program is not required to print -an announcement.) -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the -Program with the Program (or with a work based on the Program) on a -volume of a storage or distribution medium does not bring the other -work under the scope of this License. - -3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the -following: - -a) Accompany it with the complete corresponding machine-readable -source code, which must be distributed under the terms of Sections 1 -and 2 above on a medium customarily used for software interchange; -or, - -b) Accompany it with a written offer, valid for at least three years, -to give any third party, for a charge no more than your cost of -physically performing source distribution, a complete -machine-readable copy of the corresponding source code, to be -distributed under the terms of Sections 1 and 2 above on a medium -customarily used for software interchange; or, - -c) Accompany it with the information you received as to the offer to -distribute corresponding source code. (This alternative is allowed -only for noncommercial distribution and only if you received the -program in object code or executable form with such an offer, in -accord with Subsection b above.) -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - -4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this -License. However, parties who have received copies, or rights, from -you under this License will not have their licenses terminated so -long as such parties remain in full compliance. - -5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - -6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject -to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted -herein. You are not responsible for enforcing compliance by third -parties to this License. - -7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do -not excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under -this License and any other pertinent obligations, then as a -consequence you may not distribute the Program at all. For example, -if a patent license would not permit royalty-free redistribution of -the Program by all those who receive copies directly or indirectly -through you, then the only way you could satisfy both it and this -License would be to refrain entirely from distribution of the -Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended -to apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is -willing to distribute software through any other system and a -licensee cannot impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - -8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - -9. The Free Software Foundation may publish revised and/or new -versions of the General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published -by the Free Software Foundation. If the Program does not specify a -version number of this License, you may choose any version ever -published by the Free Software Foundation. - -10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the -author to ask for permission. For software which is copyrighted by -the Free Software Foundation, write to the Free Software Foundation; -we sometimes make exceptions for this. Our decision will be guided by -the two goals of preserving the free status of all derivatives of our -free software and of promoting the sharing and reuse of software -generally. - -NO WARRANTY - -11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - -END OF TERMS AND CONDITIONS -How to Apply These Terms to Your New Programs -If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make -it free software which everyone can redistribute and change under -these terms. - -To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - -one line to give the program's name and an idea of what it does. -Copyright (C) yyyy name of author - -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. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA -02111-1307, USA. - -Also add information on how to contact you by electronic and paper -mail. - -If the program is interactive, make it output a short notice like -this when it starts in an interactive mode: - -Gnomovision version 69, Copyright (C) yyyy name of author -Gnomovision comes with ABSOLUTELY NO WARRANTY; for details -type `show w'. This is free software, and you are welcome -to redistribute it under certain conditions; type `show c' -for details. - -The hypothetical commands `show w' and `show c' should show the -appropriate parts of the General Public License. Of course, the -commands you use may be called something other than `show w' and -`show c'; they could even be mouse-clicks or menu items--whatever -suits your program. - -You should also get your employer (if you work as a programmer) or -your school, if any, to sign a "copyright disclaimer" for the -program, if necessary. Here is a sample; alter the names: - -Yoyodyne, Inc., hereby disclaims all copyright -interest in the program `Gnomovision' -(which makes passes at compilers) written -by James Hacker. - -signature of Ty Coon, 1 April 1989 -Ty Coon, President of Vice - -This General Public License does not permit incorporating your -program into proprietary programs. If your program is a subroutine -library, you may consider it more useful to permit linking -proprietary applications with the library. If this is what you want -to do, use the GNU Library General Public License instead of this -License. - - ----------------------------------------------------------------------- ----------- -Return to GNU's home page. -FSF & GNU inquiries & questions to gnu@gnu.org. Other ways to contact -the FSF. - -Comments on these web pages to webmasters@www.gnu.org, send other -questions to gnu@gnu.org. - -Copyright notice above. -Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, -MA 02111, USA - -Updated: 16 Feb 1998 tower - diff --git a/components/doom/prboom/am_map.c b/components/doom/prboom/am_map.c deleted file mode 100644 index fb89558f..00000000 --- a/components/doom/prboom/am_map.c +++ /dev/null @@ -1,1593 +0,0 @@ -/* Emacs style mode select -*- C++ -*- - *----------------------------------------------------------------------------- - * - * - * PrBoom: a Doom port merged with LxDoom and LSDLDoom - * based on BOOM, a modified and improved DOOM engine - * Copyright (C) 1999 by - * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman - * Copyright (C) 1999-2000 by - * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze - * Copyright 2005, 2006 by - * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko - * - * 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. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA. - * - * DESCRIPTION: - * the automap code - * - *----------------------------------------------------------------------------- - */ - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include "doomstat.h" -#include "st_stuff.h" -#include "r_main.h" -#include "p_setup.h" -#include "p_maputl.h" -#include "w_wad.h" -#include "v_video.h" -#include "p_spec.h" -#include "am_map.h" -#include "dstrings.h" -#include "d_deh.h" // Ty 03/27/98 - externalizations -#include "lprintf.h" // jff 08/03/98 - declaration of lprintf -#include "g_game.h" - -//jff 1/7/98 default automap colors added -int mapcolor_back; // map background -int mapcolor_grid; // grid lines color -int mapcolor_wall; // normal 1s wall color -int mapcolor_fchg; // line at floor height change color -int mapcolor_cchg; // line at ceiling height change color -int mapcolor_clsd; // line at sector with floor=ceiling color -int mapcolor_rkey; // red key color -int mapcolor_bkey; // blue key color -int mapcolor_ykey; // yellow key color -int mapcolor_rdor; // red door color (diff from keys to allow option) -int mapcolor_bdor; // blue door color (of enabling one but not other ) -int mapcolor_ydor; // yellow door color -int mapcolor_tele; // teleporter line color -int mapcolor_secr; // secret sector boundary color -int mapcolor_exit; // jff 4/23/98 add exit line color -int mapcolor_unsn; // computer map unseen line color -int mapcolor_flat; // line with no floor/ceiling changes -int mapcolor_sprt; // general sprite color -int mapcolor_item; // item sprite color -int mapcolor_frnd; // friendly sprite color -int mapcolor_enemy; // enemy sprite color -int mapcolor_hair; // crosshair color -int mapcolor_sngl; // single player arrow color -int mapcolor_me; // consoleplayer's chosen colour -int mapcolor_plyr[4] = { 112, 88, 64, 32 }; // colors for player arrows in multiplayer - -//jff 3/9/98 add option to not show secret sectors until entered -int map_secret_after; -//jff 4/3/98 add symbols for "no-color" for disable and "black color" for black -#define NC 0 -#define BC 247 - -// drawing stuff -#define FB 0 - -// scale on entry -#define INITSCALEMTOF (.2*FRACUNIT) -// how much the automap moves window per tic in frame-buffer coordinates -// moves 140 pixels in 1 second -#define F_PANINC 4 -// how much zoom-in per tic -// goes to 2x in 1 second -#define M_ZOOMIN ((int) (1.02*FRACUNIT)) -// how much zoom-out per tic -// pulls out to 0.5x in 1 second -#define M_ZOOMOUT ((int) (FRACUNIT/1.02)) - -#define PLAYERRADIUS (16*(1<>16) -// translates between frame-buffer and map coordinates -#define CXMTOF(x) (f_x + MTOF((x)-m_x)) -#define CYMTOF(y) (f_y + (f_h - MTOF((y)-m_y))) - -typedef struct -{ - mpoint_t a, b; -} mline_t; - -// -// The vector graphics for the automap. -// A line drawing of the player pointing right, -// starting from the middle. -// -#define R ((8*PLAYERRADIUS)/7) -mline_t player_arrow[] = -{ - { { -R+R/8, 0 }, { R, 0 } }, // ----- - { { R, 0 }, { R-R/2, R/4 } }, // -----> - { { R, 0 }, { R-R/2, -R/4 } }, - { { -R+R/8, 0 }, { -R-R/8, R/4 } }, // >----> - { { -R+R/8, 0 }, { -R-R/8, -R/4 } }, - { { -R+3*R/8, 0 }, { -R+R/8, R/4 } }, // >>---> - { { -R+3*R/8, 0 }, { -R+R/8, -R/4 } } -}; -#undef R -#define NUMPLYRLINES (sizeof(player_arrow)/sizeof(mline_t)) - -#define R ((8*PLAYERRADIUS)/7) -mline_t cheat_player_arrow[] = -{ // killough 3/22/98: He's alive, Jim :) - { { -R+R/8, 0 }, { R, 0 } }, // ----- - { { R, 0 }, { R-R/2, R/4 } }, // -----> - { { R, 0 }, { R-R/2, -R/4 } }, - { { -R+R/8, 0 }, { -R-R/8, R/4 } }, // >----> - { { -R+R/8, 0 }, { -R-R/8, -R/4 } }, - { { -R+3*R/8, 0 }, { -R+R/8, R/4 } }, // >>---> - { { -R+3*R/8, 0 }, { -R+R/8, -R/4 } }, - { { -R/10-R/6, R/4}, {-R/10-R/6, -R/4} }, // J - { { -R/10-R/6, -R/4}, {-R/10-R/6-R/8, -R/4} }, - { { -R/10-R/6-R/8, -R/4}, {-R/10-R/6-R/8, -R/8} }, - { { -R/10, R/4}, {-R/10, -R/4}}, // F - { { -R/10, R/4}, {-R/10+R/8, R/4}}, - { { -R/10+R/4, R/4}, {-R/10+R/4, -R/4}}, // F - { { -R/10+R/4, R/4}, {-R/10+R/4+R/8, R/4}}, -}; -#undef R -#define NUMCHEATPLYRLINES (sizeof(cheat_player_arrow)/sizeof(mline_t)) - -#define R (FRACUNIT) -mline_t triangle_guy[] = -{ -{ { (fixed_t)(-.867*R), (fixed_t)(-.5*R) }, { (fixed_t)( .867*R), (fixed_t)(-.5*R) } }, -{ { (fixed_t)( .867*R), (fixed_t)(-.5*R) }, { (fixed_t)(0 ), (fixed_t)( R) } }, -{ { (fixed_t)(0 ), (fixed_t)( R) }, { (fixed_t)(-.867*R), (fixed_t)(-.5*R) } } -}; -#undef R -#define NUMTRIANGLEGUYLINES (sizeof(triangle_guy)/sizeof(mline_t)) - -//jff 1/5/98 new symbol for keys on automap -#define R (FRACUNIT) -mline_t cross_mark[] = -{ - { { -R, 0 }, { R, 0} }, - { { 0, -R }, { 0, R } }, -}; -#undef R -#define NUMCROSSMARKLINES (sizeof(cross_mark)/sizeof(mline_t)) -//jff 1/5/98 end of new symbol - -#define R (FRACUNIT) -mline_t thintriangle_guy[] = -{ -{ { (fixed_t)(-.5*R), (fixed_t)(-.7*R) }, { (fixed_t)( R), (fixed_t)( 0) } }, -{ { (fixed_t)( R), (fixed_t)( 0) }, { (fixed_t)(-.5*R), (fixed_t)( .7*R) } }, -{ { (fixed_t)(-.5*R), (fixed_t)( .7*R) }, { (fixed_t)(-.5*R), (fixed_t)(-.7*R) } } -}; -#undef R -#define NUMTHINTRIANGLEGUYLINES (sizeof(thintriangle_guy)/sizeof(mline_t)) - -int ddt_cheating = 0; // killough 2/7/98: make global, rename to ddt_* - -static int leveljuststarted = 1; // kluge until AM_LevelInit() is called - -enum automapmode_e automapmode; // Mode that the automap is in - -// location of window on screen -static int f_x; -static int f_y; - -// size of window on screen -static int f_w; -static int f_h; - -static mpoint_t m_paninc; // how far the window pans each tic (map coords) -static fixed_t mtof_zoommul; // how far the window zooms each tic (map coords) -static fixed_t ftom_zoommul; // how far the window zooms each tic (fb coords) - -static fixed_t m_x, m_y; // LL x,y window location on the map (map coords) -static fixed_t m_x2, m_y2; // UR x,y window location on the map (map coords) - -// -// width/height of window on map (map coords) -// -static fixed_t m_w; -static fixed_t m_h; - -// based on level size -static fixed_t min_x; -static fixed_t min_y; -static fixed_t max_x; -static fixed_t max_y; - -static fixed_t max_w; // max_x-min_x, -static fixed_t max_h; // max_y-min_y - -// based on player size -static fixed_t min_w; -static fixed_t min_h; - - -static fixed_t min_scale_mtof; // used to tell when to stop zooming out -static fixed_t max_scale_mtof; // used to tell when to stop zooming in - -// old stuff for recovery later -static fixed_t old_m_w, old_m_h; -static fixed_t old_m_x, old_m_y; - -// old location used by the Follower routine -static mpoint_t f_oldloc; - -// used by MTOF to scale from map-to-frame-buffer coords -static fixed_t scale_mtof = (fixed_t)INITSCALEMTOF; -// used by FTOM to scale from frame-buffer-to-map coords (=1/scale_mtof) -static fixed_t scale_ftom; - -static player_t *plr; // the player represented by an arrow - -// killough 2/22/98: Remove limit on automap marks, -// and make variables external for use in savegames. - -mpoint_t *markpoints = NULL; // where the points are -int markpointnum = 0; // next point to be assigned (also number of points now) -int markpointnum_max = 0; // killough 2/22/98 - -// Reset the growable automap-marks array on emulator teardown (see -// R_ResetDrawSegs). The array and its count/capacity counters survive across -// launches; dropping them forces reallocation instead of reusing freed memory. -void AM_ResetMarks(void) { - markpoints = NULL; - markpointnum = 0; - markpointnum_max = 0; -} - -static boolean stopped = true; - -// -// AM_activateNewScale() -// -// Changes the map scale after zooming or translating -// -// Passed nothing, returns nothing -// -static void AM_activateNewScale(void) -{ - m_x += m_w/2; - m_y += m_h/2; - m_w = FTOM(f_w); - m_h = FTOM(f_h); - m_x -= m_w/2; - m_y -= m_h/2; - m_x2 = m_x + m_w; - m_y2 = m_y + m_h; -} - -// -// AM_saveScaleAndLoc() -// -// Saves the current center and zoom -// Affects the variables that remember old scale and loc -// -// Passed nothing, returns nothing -// -static void AM_saveScaleAndLoc(void) -{ - old_m_x = m_x; - old_m_y = m_y; - old_m_w = m_w; - old_m_h = m_h; -} - -// -// AM_restoreScaleAndLoc() -// -// restores the center and zoom from locally saved values -// Affects global variables for location and scale -// -// Passed nothing, returns nothing -// -static void AM_restoreScaleAndLoc(void) -{ - m_w = old_m_w; - m_h = old_m_h; - if (!(automapmode & am_follow)) - { - m_x = old_m_x; - m_y = old_m_y; - } - else - { - m_x = (plr->mo->x >> FRACTOMAPBITS) - m_w/2;//e6y - m_y = (plr->mo->y >> FRACTOMAPBITS) - m_h/2;//e6y - } - m_x2 = m_x + m_w; - m_y2 = m_y + m_h; - - // Change the scaling multipliers - scale_mtof = FixedDiv(f_w<= markpointnum_max) - markpoints = realloc(markpoints, - (markpointnum_max = markpointnum_max ? - markpointnum_max*2 : 16) * sizeof(*markpoints)); - - markpoints[markpointnum].x = m_x + m_w/2; - markpoints[markpointnum].y = m_y + m_h/2; - markpointnum++; -} - -// -// AM_findMinMaxBoundaries() -// -// Determines bounding box of all vertices, -// sets global variables controlling zoom range. -// -// Passed nothing, returns nothing -// -static void AM_findMinMaxBoundaries(void) -{ - int i; - fixed_t a; - fixed_t b; - - min_x = min_y = INT_MAX; - max_x = max_y = -INT_MAX; - - for (i=0;i max_x) - max_x = vertexes[i].x; - - if (vertexes[i].y < min_y) - min_y = vertexes[i].y; - else if (vertexes[i].y > max_y) - max_y = vertexes[i].y; - } - - max_w = (max_x >>= FRACTOMAPBITS) - (min_x >>= FRACTOMAPBITS);//e6y - max_h = (max_y >>= FRACTOMAPBITS) - (min_y >>= FRACTOMAPBITS);//e6y - - min_w = 2*PLAYERRADIUS; // const? never changed? - min_h = 2*PLAYERRADIUS; - - a = FixedDiv(f_w< max_x) - m_x = max_x - m_w/2; - else if (m_x + m_w/2 < min_x) - m_x = min_x - m_w/2; - - if (m_y + m_h/2 > max_y) - m_y = max_y - m_h/2; - else if (m_y + m_h/2 < min_y) - m_y = min_y - m_h/2; - - m_x2 = m_x + m_w; - m_y2 = m_y + m_h; -} - - -// -// AM_initVariables() -// -// Initialize the variables for the automap -// -// Affects the automap global variables -// Status bar is notified that the automap has been entered -// Passed nothing, returns nothing -// -static void AM_initVariables(void) -{ - int pnum; - static event_t st_notify = { ev_keyup, AM_MSGENTERED, 0, 0 }; - - automapmode |= am_active; - - f_oldloc.x = INT_MAX; - - m_paninc.x = m_paninc.y = 0; - ftom_zoommul = FRACUNIT; - mtof_zoommul = FRACUNIT; - - m_w = FTOM(f_w); - m_h = FTOM(f_h); - - // find player to center on initially - if (!playeringame[pnum = consoleplayer]) - for (pnum=0;pnummo->x >> FRACTOMAPBITS) - m_w/2;//e6y - m_y = (plr->mo->y >> FRACTOMAPBITS) - m_h/2;//e6y - AM_changeWindowLoc(); - - // for saving & restoring - old_m_x = m_x; - old_m_y = m_y; - old_m_w = m_w; - old_m_h = m_h; - - // inform the status bar of the change - ST_Responder(&st_notify); -} - -// -// AM_loadPics() -// -static void AM_loadPics(void) -{ - // cph - mark numbers no longer needed cached -} - -// -// AM_unloadPics() -// -static void AM_unloadPics(void) -{ - // cph - mark numbers no longer needed cached -} - -// -// AM_clearMarks() -// -// Sets the number of marks to 0, thereby clearing them from the display -// -// Affects the global variable markpointnum -// Passed nothing, returns nothing -// -void AM_clearMarks(void) -{ - markpointnum = 0; -} - -// -// AM_LevelInit() -// -// Initialize the automap at the start of a new level -// should be called at the start of every level -// -// Passed nothing, returns nothing -// Affects automap's global variables -// -// CPhipps - get status bar height from status bar code -static void AM_LevelInit(void) -{ - leveljuststarted = 0; - - f_x = f_y = 0; - f_w = SCREENWIDTH; // killough 2/7/98: get rid of finit_ vars - f_h = SCREENHEIGHT-ST_SCALED_HEIGHT;// to allow runtime setting of width/height - - AM_findMinMaxBoundaries(); - scale_mtof = FixedDiv(min_scale_mtof, (int) (0.7*FRACUNIT)); - if (scale_mtof > max_scale_mtof) - scale_mtof = min_scale_mtof; - scale_ftom = FixedDiv(FRACUNIT, scale_mtof); -} - -// -// AM_Stop() -// -// Cease automap operations, unload patches, notify status bar -// -// Passed nothing, returns nothing -// -void AM_Stop (void) -{ - static event_t st_notify = { 0, ev_keyup, AM_MSGEXITED, 0 }; - - AM_unloadPics(); - automapmode &= ~am_active; - ST_Responder(&st_notify); - stopped = true; -} - -// -// AM_Start() -// -// Start up automap operations, -// if a new level, or game start, (re)initialize level variables -// init map variables -// load mark patches -// -// Passed nothing, returns nothing -// -void AM_Start(void) -{ - static int lastlevel = -1, lastepisode = -1; - - if (!stopped) - AM_Stop(); - stopped = false; - if (lastlevel != gamemap || lastepisode != gameepisode) - { - AM_LevelInit(); - lastlevel = gamemap; - lastepisode = gameepisode; - } - AM_initVariables(); - AM_loadPics(); -} - -// -// AM_minOutWindowScale() -// -// Set the window scale to the maximum size -// -// Passed nothing, returns nothing -// -static void AM_minOutWindowScale(void) -{ - scale_mtof = min_scale_mtof; - scale_ftom = FixedDiv(FRACUNIT, scale_mtof); - AM_activateNewScale(); -} - -// -// AM_maxOutWindowScale(void) -// -// Set the window scale to the minimum size -// -// Passed nothing, returns nothing -// -static void AM_maxOutWindowScale(void) -{ - scale_mtof = max_scale_mtof; - scale_ftom = FixedDiv(FRACUNIT, scale_mtof); - AM_activateNewScale(); -} - -// -// AM_Responder() -// -// Handle events (user inputs) in automap mode -// -// Passed an input event, returns true if its handled -// -boolean AM_Responder -( event_t* ev ) -{ - int rc; - static int bigstate=0; - int ch; // phares - - rc = false; - - if (!(automapmode & am_active)) - { - if (ev->type == ev_keydown && ev->data1 == key_map) // phares - { - AM_Start (); - rc = true; - } - } - else if (ev->type == ev_keydown) - { - rc = true; - ch = ev->data1; // phares - if (ch == key_map_right) // | - if (!(automapmode & am_follow)) // V - m_paninc.x = FTOM(F_PANINC); - else - rc = false; - else if (ch == key_map_left) - if (!(automapmode & am_follow)) - m_paninc.x = -FTOM(F_PANINC); - else - rc = false; - else if (ch == key_map_up) - if (!(automapmode & am_follow)) - m_paninc.y = FTOM(F_PANINC); - else - rc = false; - else if (ch == key_map_down) - if (!(automapmode & am_follow)) - m_paninc.y = -FTOM(F_PANINC); - else - rc = false; - else if (ch == key_map_zoomout) - { - mtof_zoommul = M_ZOOMOUT; - ftom_zoommul = M_ZOOMIN; - } - else if (ch == key_map_zoomin) - { - mtof_zoommul = M_ZOOMIN; - ftom_zoommul = M_ZOOMOUT; - } - else if (ch == key_map) - { - bigstate = 0; - AM_Stop (); - } - else if (ch == key_map_gobig) - { - bigstate = !bigstate; - if (bigstate) - { - AM_saveScaleAndLoc(); - AM_minOutWindowScale(); - } - else - AM_restoreScaleAndLoc(); - } - else if (ch == key_map_follow) - { - automapmode ^= am_follow; // CPhipps - put all automap mode stuff into one enum - f_oldloc.x = INT_MAX; - // Ty 03/27/98 - externalized - plr->message = (automapmode & am_follow) ? s_AMSTR_FOLLOWON : s_AMSTR_FOLLOWOFF; - } - else if (ch == key_map_grid) - { - automapmode ^= am_grid; // CPhipps - // Ty 03/27/98 - *not* externalized - plr->message = (automapmode & am_grid) ? s_AMSTR_GRIDON : s_AMSTR_GRIDOFF; - } - else if (ch == key_map_mark) - { - /* Ty 03/27/98 - *not* externalized - * cph 2001/11/20 - use doom_printf so we don't have our own buffer */ - doom_printf("%s %d", s_AMSTR_MARKEDSPOT, markpointnum); - AM_addMark(); - } - else if (ch == key_map_clear) - { - AM_clearMarks(); // Ty 03/27/98 - *not* externalized - plr->message = s_AMSTR_MARKSCLEARED; // ^ - } // | - else if (ch == key_map_rotate) { - automapmode ^= am_rotate; - plr->message = (automapmode & am_rotate) ? s_AMSTR_ROTATEON : s_AMSTR_ROTATEOFF; - } - else if (ch == key_map_overlay) { - automapmode ^= am_overlay; - plr->message = (automapmode & am_overlay) ? s_AMSTR_OVERLAYON : s_AMSTR_OVERLAYOFF; - } - else // phares - { - rc = false; - } - } - else if (ev->type == ev_keyup) - { - rc = false; - ch = ev->data1; - if (ch == key_map_right) - { - if (!(automapmode & am_follow)) - m_paninc.x = 0; - } - else if (ch == key_map_left) - { - if (!(automapmode & am_follow)) - m_paninc.x = 0; - } - else if (ch == key_map_up) - { - if (!(automapmode & am_follow)) - m_paninc.y = 0; - } - else if (ch == key_map_down) - { - if (!(automapmode & am_follow)) - m_paninc.y = 0; - } - else if ((ch == key_map_zoomout) || (ch == key_map_zoomin)) - { - mtof_zoommul = FRACUNIT; - ftom_zoommul = FRACUNIT; - } - } - return rc; -} - -// -// AM_rotate() -// -// Rotation in 2D. -// Used to rotate player arrow line character. -// -// Passed the coordinates of a point, and an angle -// Returns the coordinates rotated by the angle -// -// CPhipps - made static & enhanced for automap rotation - -static void AM_rotate(fixed_t* x, fixed_t* y, angle_t a, fixed_t xorig, fixed_t yorig) -{ - fixed_t tmpx; - - //e6y - xorig>>=FRACTOMAPBITS; - yorig>>=FRACTOMAPBITS; - - tmpx = - FixedMul(*x - xorig,finecosine[a>>ANGLETOFINESHIFT]) - - FixedMul(*y - yorig,finesine[a>>ANGLETOFINESHIFT]); - - *y = yorig + - FixedMul(*x - xorig,finesine[a>>ANGLETOFINESHIFT]) - + FixedMul(*y - yorig,finecosine[a>>ANGLETOFINESHIFT]); - - *x = tmpx + xorig; -} - -// -// AM_changeWindowScale() -// -// Automap zooming -// -// Passed nothing, returns nothing -// -static void AM_changeWindowScale(void) -{ - // Change the scaling multipliers - scale_mtof = FixedMul(scale_mtof, mtof_zoommul); - scale_ftom = FixedDiv(FRACUNIT, scale_mtof); - - if (scale_mtof < min_scale_mtof) - AM_minOutWindowScale(); - else if (scale_mtof > max_scale_mtof) - AM_maxOutWindowScale(); - else - AM_activateNewScale(); -} - -// -// AM_doFollowPlayer() -// -// Turn on follow mode - the map scrolls opposite to player motion -// -// Passed nothing, returns nothing -// -static void AM_doFollowPlayer(void) -{ - if (f_oldloc.x != plr->mo->x || f_oldloc.y != plr->mo->y) - { - m_x = FTOM(MTOF(plr->mo->x >> FRACTOMAPBITS)) - m_w/2;//e6y - m_y = FTOM(MTOF(plr->mo->y >> FRACTOMAPBITS)) - m_h/2;//e6y - m_x2 = m_x + m_w; - m_y2 = m_y + m_h; - f_oldloc.x = plr->mo->x; - f_oldloc.y = plr->mo->y; - } -} - -// -// AM_Ticker() -// -// Updates on gametic - enter follow mode, zoom, or change map location -// -// Passed nothing, returns nothing -// -void AM_Ticker (void) -{ - if (!(automapmode & am_active)) - return; - - if (automapmode & am_follow) - AM_doFollowPlayer(); - - // Change the zoom if necessary - if (ftom_zoommul != FRACUNIT) - AM_changeWindowScale(); - - // Change x,y location - if (m_paninc.x || m_paninc.y) - AM_changeWindowLoc(); -} - -// -// AM_clipMline() -// -// Automap clipping of lines. -// -// Based on Cohen-Sutherland clipping algorithm but with a slightly -// faster reject and precalculated slopes. If the speed is needed, -// use a hash algorithm to handle the common cases. -// -// Passed the line's coordinates on map and in the frame buffer performs -// clipping on them in the lines frame coordinates. -// Returns true if any part of line was not clipped -// -static boolean AM_clipMline -( mline_t* ml, - fline_t* fl ) -{ - enum - { - LEFT =1, - RIGHT =2, - BOTTOM =4, - TOP =8 - }; - - register int outcode1 = 0; - register int outcode2 = 0; - register int outside; - - fpoint_t tmp; - int dx; - int dy; - - -#define DOOUTCODE(oc, mx, my) \ - (oc) = 0; \ - if ((my) < 0) (oc) |= TOP; \ - else if ((my) >= f_h) (oc) |= BOTTOM; \ - if ((mx) < 0) (oc) |= LEFT; \ - else if ((mx) >= f_w) (oc) |= RIGHT; - - - // do trivial rejects and outcodes - if (ml->a.y > m_y2) - outcode1 = TOP; - else if (ml->a.y < m_y) - outcode1 = BOTTOM; - - if (ml->b.y > m_y2) - outcode2 = TOP; - else if (ml->b.y < m_y) - outcode2 = BOTTOM; - - if (outcode1 & outcode2) - return false; // trivially outside - - if (ml->a.x < m_x) - outcode1 |= LEFT; - else if (ml->a.x > m_x2) - outcode1 |= RIGHT; - - if (ml->b.x < m_x) - outcode2 |= LEFT; - else if (ml->b.x > m_x2) - outcode2 |= RIGHT; - - if (outcode1 & outcode2) - return false; // trivially outside - - // transform to frame-buffer coordinates. - fl->a.x = CXMTOF(ml->a.x); - fl->a.y = CYMTOF(ml->a.y); - fl->b.x = CXMTOF(ml->b.x); - fl->b.y = CYMTOF(ml->b.y); - - DOOUTCODE(outcode1, fl->a.x, fl->a.y); - DOOUTCODE(outcode2, fl->b.x, fl->b.y); - - if (outcode1 & outcode2) - return false; - - while (outcode1 | outcode2) - { - // may be partially inside box - // find an outside point - if (outcode1) - outside = outcode1; - else - outside = outcode2; - - // clip to each side - if (outside & TOP) - { - dy = fl->a.y - fl->b.y; - dx = fl->b.x - fl->a.x; - tmp.x = fl->a.x + (dx*(fl->a.y))/dy; - tmp.y = 0; - } - else if (outside & BOTTOM) - { - dy = fl->a.y - fl->b.y; - dx = fl->b.x - fl->a.x; - tmp.x = fl->a.x + (dx*(fl->a.y-f_h))/dy; - tmp.y = f_h-1; - } - else if (outside & RIGHT) - { - dy = fl->b.y - fl->a.y; - dx = fl->b.x - fl->a.x; - tmp.y = fl->a.y + (dy*(f_w-1 - fl->a.x))/dx; - tmp.x = f_w-1; - } - else if (outside & LEFT) - { - dy = fl->b.y - fl->a.y; - dx = fl->b.x - fl->a.x; - tmp.y = fl->a.y + (dy*(-fl->a.x))/dx; - tmp.x = 0; - } - - if (outside == outcode1) - { - fl->a = tmp; - DOOUTCODE(outcode1, fl->a.x, fl->a.y); - } - else - { - fl->b = tmp; - DOOUTCODE(outcode2, fl->b.x, fl->b.y); - } - - if (outcode1 & outcode2) - return false; // trivially outside - } - - return true; -} -#undef DOOUTCODE - -// -// AM_drawMline() -// -// Clip lines, draw visible parts of lines. -// -// Passed the map coordinates of the line, and the color to draw it -// Color -1 is special and prevents drawing. Color 247 is special and -// is translated to black, allowing Color 0 to represent feature disable -// in the defaults file. -// Returns nothing. -// -static void AM_drawMline -( mline_t* ml, - int color ) -{ - static fline_t fl; - - if (color==-1) // jff 4/3/98 allow not drawing any sort of line - return; // by setting its color to -1 - if (color==247) // jff 4/3/98 if color is 247 (xparent), use black - color=0; - - if (AM_clipMline(ml, &fl)) - V_DrawLine(&fl, color); // draws it on frame buffer using fb coords -} - -// -// AM_drawGrid() -// -// Draws blockmap aligned grid lines. -// -// Passed the color to draw the grid lines -// Returns nothing -// -static void AM_drawGrid(int color) -{ - fixed_t x, y; - fixed_t start, end; - mline_t ml; - - // Figure out start of vertical gridlines - start = m_x; - if ((start-bmaporgx)%(MAPBLOCKUNITS<> LockedKeyShift; - if (!type || type==7) - return 3; //any or all keys - else return (type-1)%3; - } - switch (type) // closed keyed door - { - case 26: case 32: case 99: case 133: - /*bluekey*/ - return 1; - case 27: case 34: case 136: case 137: - /*yellowkey*/ - return 2; - case 28: case 33: case 134: case 135: - /*redkey*/ - return 0; - default: - return -1; //not a keyed door - } -} - -// -// Determines visible lines, draws them. -// This is LineDef based, not LineSeg based. -// -// jff 1/5/98 many changes in this routine -// backward compatibility not needed, so just changes, no ifs -// addition of clauses for: -// doors opening, keyed door id, secret sectors, -// teleports, exit lines, key things -// ability to suppress any of added features or lines with no height changes -// -// support for gamma correction in automap abandoned -// -// jff 4/3/98 changed mapcolor_xxxx=0 as control to disable feature -// jff 4/3/98 changed mapcolor_xxxx=-1 to disable drawing line completely -// -static void AM_drawWalls(void) -{ - int i; - static mline_t l; - - // draw the unclipped visible portions of all lines - for (i=0;ix >> FRACTOMAPBITS;//e6y - l.a.y = lines[i].v1->y >> FRACTOMAPBITS;//e6y - l.b.x = lines[i].v2->x >> FRACTOMAPBITS;//e6y - l.b.y = lines[i].v2->y >> FRACTOMAPBITS;//e6y - - if (automapmode & am_rotate) { - AM_rotate(&l.a.x, &l.a.y, ANG90-plr->mo->angle, plr->mo->x, plr->mo->y); - AM_rotate(&l.b.x, &l.b.y, ANG90-plr->mo->angle, plr->mo->x, plr->mo->y); - } - - // if line has been seen or IDDT has been used - if (ddt_cheating || (lines[i].flags & ML_MAPPED)) - { - if ((lines[i].flags & ML_DONTDRAW) && !ddt_cheating) - continue; - { - /* cph - show keyed doors and lines */ - int amd; - if ((mapcolor_bdor || mapcolor_ydor || mapcolor_rdor) && - !(lines[i].flags & ML_SECRET) && /* non-secret */ - (amd = AM_DoorColor(lines[i].special)) != -1 - ) - { - { - switch (amd) /* closed keyed door */ - { - case 1: - /*bluekey*/ - AM_drawMline(&l, - mapcolor_bdor? mapcolor_bdor : mapcolor_cchg); - continue; - case 2: - /*yellowkey*/ - AM_drawMline(&l, - mapcolor_ydor? mapcolor_ydor : mapcolor_cchg); - continue; - case 0: - /*redkey*/ - AM_drawMline(&l, - mapcolor_rdor? mapcolor_rdor : mapcolor_cchg); - continue; - case 3: - /*any or all*/ - AM_drawMline(&l, - mapcolor_clsd? mapcolor_clsd : mapcolor_cchg); - continue; - } - } - } - } - if /* jff 4/23/98 add exit lines to automap */ - ( - mapcolor_exit && - ( - lines[i].special==11 || - lines[i].special==52 || - lines[i].special==197 || - lines[i].special==51 || - lines[i].special==124 || - lines[i].special==198 - ) - ) { - AM_drawMline(&l, mapcolor_exit); /* exit line */ - continue; - } - - if (!lines[i].backsector) - { - // jff 1/10/98 add new color for 1S secret sector boundary - if (mapcolor_secr && //jff 4/3/98 0 is disable - ( - ( - map_secret_after && - P_WasSecret(lines[i].frontsector) && - !P_IsSecret(lines[i].frontsector) - ) - || - ( - !map_secret_after && - P_WasSecret(lines[i].frontsector) - ) - ) - ) - AM_drawMline(&l, mapcolor_secr); // line bounding secret sector - else //jff 2/16/98 fixed bug - AM_drawMline(&l, mapcolor_wall); // special was cleared - } - else /* now for 2S lines */ - { - // jff 1/10/98 add color change for all teleporter types - if - ( - mapcolor_tele && !(lines[i].flags & ML_SECRET) && - (lines[i].special == 39 || lines[i].special == 97 || - lines[i].special == 125 || lines[i].special == 126) - ) - { // teleporters - AM_drawMline(&l, mapcolor_tele); - } - else if (lines[i].flags & ML_SECRET) // secret door - { - AM_drawMline(&l, mapcolor_wall); // wall color - } - else if - ( - mapcolor_clsd && - !(lines[i].flags & ML_SECRET) && // non-secret closed door - ((lines[i].backsector->floorheight==lines[i].backsector->ceilingheight) || - (lines[i].frontsector->floorheight==lines[i].frontsector->ceilingheight)) - ) - { - AM_drawMline(&l, mapcolor_clsd); // non-secret closed door - } //jff 1/6/98 show secret sector 2S lines - else if - ( - mapcolor_secr && //jff 2/16/98 fixed bug - ( // special was cleared after getting it - (map_secret_after && - ( - (P_WasSecret(lines[i].frontsector) - && !P_IsSecret(lines[i].frontsector)) || - (P_WasSecret(lines[i].backsector) - && !P_IsSecret(lines[i].backsector)) - ) - ) - || //jff 3/9/98 add logic to not show secret til after entered - ( // if map_secret_after is true - !map_secret_after && - (P_WasSecret(lines[i].frontsector) || - P_WasSecret(lines[i].backsector)) - ) - ) - ) - { - AM_drawMline(&l, mapcolor_secr); // line bounding secret sector - } //jff 1/6/98 end secret sector line change - else if (lines[i].backsector->floorheight != - lines[i].frontsector->floorheight) - { - AM_drawMline(&l, mapcolor_fchg); // floor level change - } - else if (lines[i].backsector->ceilingheight != - lines[i].frontsector->ceilingheight) - { - AM_drawMline(&l, mapcolor_cchg); // ceiling level change - } - else if (mapcolor_flat && ddt_cheating) - { - AM_drawMline(&l, mapcolor_flat); //2S lines that appear only in IDDT - } - } - } // now draw the lines only visible because the player has computermap - else if (plr->powers[pw_allmap]) // computermap visible lines - { - if (!(lines[i].flags & ML_DONTDRAW)) // invisible flag lines do not show - { - if - ( - mapcolor_flat - || - !lines[i].backsector - || - lines[i].backsector->floorheight - != lines[i].frontsector->floorheight - || - lines[i].backsector->ceilingheight - != lines[i].frontsector->ceilingheight - ) - AM_drawMline(&l, mapcolor_unsn); - } - } - } -} - -// -// AM_drawLineCharacter() -// -// Draws a vector graphic according to numerous parameters -// -// Passed the structure defining the vector graphic shape, the number -// of vectors in it, the scale to draw it at, the angle to draw it at, -// the color to draw it with, and the map coordinates to draw it at. -// Returns nothing -// -static void AM_drawLineCharacter -( mline_t* lineguy, - int lineguylines, - fixed_t scale, - angle_t angle, - int color, - fixed_t x, - fixed_t y ) -{ - int i; - mline_t l; - - if (automapmode & am_rotate) angle -= plr->mo->angle - ANG90; // cph - - for (i=0;imo->angle, - mapcolor_sngl, //jff color - plr->mo->x >> FRACTOMAPBITS,//e6y - plr->mo->y >> FRACTOMAPBITS//e6y - ); - else - AM_drawLineCharacter - ( - player_arrow, - NUMPLYRLINES, - 0, - plr->mo->angle, - mapcolor_sngl, //jff color - plr->mo->x >> FRACTOMAPBITS,//e6y - plr->mo->y >> FRACTOMAPBITS);//e6y - return; - } - - for (i=0;imo->x >> FRACTOMAPBITS, y = p->mo->y >> FRACTOMAPBITS;//e6y - if (automapmode & am_rotate) - AM_rotate(&x, &y, ANG90-plr->mo->angle, plr->mo->x, plr->mo->y); - - AM_drawLineCharacter (player_arrow, NUMPLYRLINES, 0, p->mo->angle, - p->powers[pw_invisibility] ? 246 /* *close* to black */ - : mapcolor_plyr[i], //jff 1/6/98 use default color - x, y); - } - } -} - -// -// AM_drawThings() -// -// Draws the things on the automap in double IDDT cheat mode -// -// Passed colors and colorrange, no longer used -// Returns nothing -// -static void AM_drawThings(void) -{ - int i; - mobj_t* t; - - // for all sectors - for (i=0;ix >> FRACTOMAPBITS, y = t->y >> FRACTOMAPBITS;//e6y - - if (automapmode & am_rotate) - AM_rotate(&x, &y, ANG90-plr->mo->angle, plr->mo->x, plr->mo->y); - - //jff 1/5/98 case over doomednum of thing being drawn - if (mapcolor_rkey || mapcolor_ykey || mapcolor_bkey) - { - switch(t->info->doomednum) - { - //jff 1/5/98 treat keys special - case 38: case 13: //jff red key - AM_drawLineCharacter - ( - cross_mark, - NUMCROSSMARKLINES, - 16<angle, - mapcolor_rkey!=-1? mapcolor_rkey : mapcolor_sprt, - x, y - ); - t = t->snext; - continue; - case 39: case 6: //jff yellow key - AM_drawLineCharacter - ( - cross_mark, - NUMCROSSMARKLINES, - 16<angle, - mapcolor_ykey!=-1? mapcolor_ykey : mapcolor_sprt, - x, y - ); - t = t->snext; - continue; - case 40: case 5: //jff blue key - AM_drawLineCharacter - ( - cross_mark, - NUMCROSSMARKLINES, - 16<angle, - mapcolor_bkey!=-1? mapcolor_bkey : mapcolor_sprt, - x, y - ); - t = t->snext; - continue; - default: - break; - } - } - //jff 1/5/98 end added code for keys - //jff previously entire code - AM_drawLineCharacter - ( - thintriangle_guy, - NUMTHINTRIANGLEGUYLINES, - 16<angle, - t->flags & MF_FRIEND && !t->player ? mapcolor_frnd : - /* cph 2006/07/30 - Show count-as-kills in red. */ - ((t->flags & (MF_COUNTKILL | MF_CORPSE)) == MF_COUNTKILL) ? mapcolor_enemy : - /* bbm 2/28/03 Show countable items in yellow. */ - t->flags & MF_COUNTITEM ? mapcolor_item : mapcolor_sprt, - x, y - ); - t = t->snext; - } - } -} - -// -// AM_drawMarks() -// -// Draw the marked locations on the automap -// -// Passed nothing, returns nothing -// -// killough 2/22/98: -// Rewrote AM_drawMarks(). Removed limit on marks. -// -static void AM_drawMarks(void) -{ - int i; - for (i=0;imo->angle, plr->mo->x, plr->mo->y); - - fx = CXMTOF(fx); fy = CYMTOF(fy); - - do - { - int d = j % 10; - if (d==1) // killough 2/22/98: less spacing for '1' - fx++; - - if (fx >= f_x && fx < f_w - w && fy >= f_y && fy < f_h - h) { - // cph - construct patch name and draw marker - char namebuf[] = { 'A', 'M', 'M', 'N', 'U', 'M', '0'+d, 0 }; - - V_DrawNamePatch(fx, fy, FB, namebuf, CR_DEFAULT, VPT_NONE); - } - fx -= w-1; // killough 2/22/98: 1 space backwards - j /= 10; - } - while (j>0); - } -} - -// -// AM_drawCrosshair() -// -// Draw the single point crosshair representing map center -// -// Passed the color to draw the pixel with -// Returns nothing -// -// CPhipps - made static inline, and use the general pixel plotter function - -inline static void AM_drawCrosshair(int color) -{ - fline_t line; - - line.a.x = (f_w/2)-1; - line.a.y = (f_h/2); - line.b.x = (f_w/2)+1; - line.b.y = (f_h/2); - V_DrawLine(&line, color); - - line.a.x = (f_w/2); - line.a.y = (f_h/2)-1; - line.b.x = (f_w/2); - line.b.y = (f_h/2)+1; - V_DrawLine(&line, color); -} - -// -// AM_Drawer() -// -// Draws the entire automap -// -// Passed nothing, returns nothing -// -void AM_Drawer (void) -{ - // CPhipps - all automap modes put into one enum - if (!(automapmode & am_active)) return; - - if (!(automapmode & am_overlay)) // cph - If not overlay mode, clear background for the automap - V_FillRect(FB, f_x, f_y, f_w, f_h, (byte)mapcolor_back); //jff 1/5/98 background default color - if (automapmode & am_grid) - AM_drawGrid(mapcolor_grid); //jff 1/7/98 grid default color - AM_drawWalls(); - AM_drawPlayers(); - if (ddt_cheating==2) - AM_drawThings(); //jff 1/5/98 default double IDDT sprite - AM_drawCrosshair(mapcolor_hair); //jff 1/7/98 default crosshair color - - AM_drawMarks(); -} diff --git a/components/doom/prboom/am_map.h b/components/doom/prboom/am_map.h deleted file mode 100644 index 850c9ce5..00000000 --- a/components/doom/prboom/am_map.h +++ /dev/null @@ -1,111 +0,0 @@ -/* Emacs style mode select -*- C++ -*- - *----------------------------------------------------------------------------- - * - * - * PrBoom: a Doom port merged with LxDoom and LSDLDoom - * based on BOOM, a modified and improved DOOM engine - * Copyright (C) 1999 by - * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman - * Copyright (C) 1999-2000 by - * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze - * Copyright 2005, 2006 by - * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko - * - * 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. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA. - * - * DESCRIPTION: - * AutoMap module. - * - *-----------------------------------------------------------------------------*/ - -#ifndef __AMMAP_H__ -#define __AMMAP_H__ - -#include "d_event.h" - -#define MAPBITS 12 -#define FRACTOMAPBITS (FRACBITS-MAPBITS) - -// Used by ST StatusBar stuff. -#define AM_MSGHEADER (('a'<<24)+('m'<<16)) -#define AM_MSGENTERED (AM_MSGHEADER | ('e'<<8)) -#define AM_MSGEXITED (AM_MSGHEADER | ('x'<<8)) - -// Called by main loop. -boolean AM_Responder (event_t* ev); - -// Called by main loop. -void AM_Ticker (void); - -// Called by main loop, -// called instead of view drawer if automap active. -void AM_Drawer (void); - -// Called to force the automap to quit -// if the level is completed while it is up. -void AM_Stop (void); - -// killough 2/22/98: for saving automap information in savegame: - -extern void AM_Start(void); - -//jff 4/16/98 make externally available - -extern void AM_clearMarks(void); - -typedef struct -{ - fixed_t x,y; -} mpoint_t; - -extern mpoint_t *markpoints; -extern int markpointnum, markpointnum_max; - -// end changes -- killough 2/22/98 - -// killough 5/2/98: moved from m_misc.c - -//jff 1/7/98 automap colors added -extern int mapcolor_back; // map background -extern int mapcolor_grid; // grid lines color -extern int mapcolor_wall; // normal 1s wall color -extern int mapcolor_fchg; // line at floor height change color -extern int mapcolor_cchg; // line at ceiling height change color -extern int mapcolor_clsd; // line at sector with floor=ceiling color -extern int mapcolor_rkey; // red key color -extern int mapcolor_bkey; // blue key color -extern int mapcolor_ykey; // yellow key color -extern int mapcolor_rdor; // red door color (diff from keys to allow option) -extern int mapcolor_bdor; // blue door color (of enabling one not other) -extern int mapcolor_ydor; // yellow door color -extern int mapcolor_tele; // teleporter line color -extern int mapcolor_secr; // secret sector boundary color -//jff 4/23/98 -extern int mapcolor_exit; // exit line -extern int mapcolor_unsn; // computer map unseen line color -extern int mapcolor_flat; // line with no floor/ceiling changes -extern int mapcolor_sprt; // general sprite color -extern int mapcolor_item; // item sprite color -extern int mapcolor_enemy; // enemy sprite color -extern int mapcolor_frnd; // friendly sprite color -extern int mapcolor_hair; // crosshair color -extern int mapcolor_sngl; // single player arrow color -extern int mapcolor_plyr[4]; // colors for players in multiplayer -extern int mapcolor_me; // consoleplayer's chosen colour -//jff 3/9/98 -extern int map_secret_after; // secrets do not appear til after bagged - -#endif diff --git a/components/doom/prboom/config.h b/components/doom/prboom/config.h deleted file mode 100644 index 5b039afd..00000000 --- a/components/doom/prboom/config.h +++ /dev/null @@ -1,52 +0,0 @@ -/* Uncomment this to exhaustively run memory checks while the game is running - (this is EXTREMELY slow). */ -/* #undef CHECKHEAP */ - -/* Define for support for MBF helper dogs */ -//#define DOGS 0 - -/* Uncomment this to cause heap dumps to be generated. Only useful if - INSTRUMENTED is also defined. */ -/* #undef HEAPDUMP */ - -/* Define on targets supporting 386 assembly */ -/* #undef I386_ASM */ - -/* Define this to see real-time memory allocation statistics, and enable extra - debugging features */ -/* #undef INSTRUMENTED */ - -/* If your platform has a fast version of max, define MAX to it */ -/* #undef MAX */ - -/* If your platform has a fast version of min, define MIN to it */ -/* #undef MIN */ - -/* Name of package */ -#define PACKAGE "prboom-go" - -/* Set to the attribute to apply to struct definitions to make them packed */ -#define PACKEDATTR __attribute__((packed)) - -/* Define to enable internal range checking */ -/* #undef RANGECHECK */ - -/* When defined this causes quick checks which only impose significant - overhead if a posible error is detected. */ -#define SIMPLECHECKS - -/* Defining this causes time stamps to be created each time a lump is locked, - and lumps locked for long periods of time are reported */ -/* #undef TIMEDIAG */ - -/* Version number of package */ -#define VERSION "2.5.0" - -/* Define to remove DEH support */ -#define NODEHSUPPORT - -/* Define to remove true color support (keep 8bit palette only) */ -#define NOTRUECOLOR - -/* Define to bundle prboom.wad (minus the trig tables, which we always include) */ -#define PRBOOMWAD diff --git a/components/doom/prboom/d_client.c b/components/doom/prboom/d_client.c deleted file mode 100644 index 98877556..00000000 --- a/components/doom/prboom/d_client.c +++ /dev/null @@ -1,529 +0,0 @@ -/* Emacs style mode select -*- C++ -*- - *----------------------------------------------------------------------------- - * - * - * PrBoom: a Doom port merged with LxDoom and LSDLDoom - * based on BOOM, a modified and improved DOOM engine - * Copyright (C) 1999 by - * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman - * Copyright (C) 1999-2000 by - * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze - * Copyright 2005, 2006 by - * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko - * - * 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. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA. - * - * DESCRIPTION: - * Network client. Passes information to/from server, staying - * synchronised. - * Contains the main wait loop, waiting for network input or - * time before doing the next tic. - * Rewritten for LxDoom, but based around bits of the old code. - * - *----------------------------------------------------------------------------- - */ - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif -#include -#ifdef HAVE_UNISTD_H -#include -#endif -#ifdef HAVE_SYS_WAIT_H -#include -#endif - -#ifdef USE_SDL_NET - #include "SDL.h" -#endif - -#include "doomtype.h" -#include "doomstat.h" -#include "d_net.h" -#include "z_zone.h" - -#include "d_main.h" -#include "g_game.h" -#include "m_menu.h" - -#include "protocol.h" -#include "i_network.h" -#include "i_system.h" -#include "i_main.h" -#include "i_video.h" -#include "m_argv.h" -#include "r_fps.h" -#include "lprintf.h" - -ticcmd_t netcmds[MAXPLAYERS][BACKUPTICS]; -static ticcmd_t* localcmds; -int maketic; -int ticdup = 1; - -static boolean isExtraDDisplay = false; - -#ifdef HAVE_NET -static boolean server; -static int remotetic; // Tic expected from the remote -static int remotesend; // Tic expected by the remote -static unsigned numqueuedpackets; -static packet_header_t** queuedpacket; -static int xtratics = 0; -static int wanted_player_number; - -static void D_QuitNetGame (void); - -void D_InitNetGame (void) -{ - int i; - int numplayers = 1; - - i = M_CheckParm("-net"); - if (i && i < myargc-1) i++; - - if (!(netgame = server = !!i)) { - playeringame[consoleplayer = 0] = true; - // e6y - // for play, recording or playback using "single-player coop" mode. - // Equivalent to using prboom_server with -N 1 - netgame = M_CheckParm("-solo-net"); - } else { - // Get game info from server - packet_header_t *packet = Z_Malloc(1000, PU_STATIC, NULL); - struct setup_packet_s *sinfo = (void*)(packet+1); - struct { packet_header_t head; short pn; } PACKEDATTR initpacket; - - I_InitNetwork(); - udp_socket = I_Socket(0); - I_ConnectToServer(myargv[i]); - - do - { - do { - // Send init packet - initpacket.pn = doom_htons(wanted_player_number); - packet_set(&initpacket.head, PKT_INIT, 0); - I_SendPacket(&initpacket.head, sizeof(initpacket)); - I_WaitForPacket(5000); - } while (!I_GetPacket(packet, 1000)); - if (packet->type == PKT_DOWN) I_Error("Server aborted the game"); - } while (packet->type != PKT_SETUP); - - // Once we have been accepted by the server, we should tell it when we leave - atexit(D_QuitNetGame); - - // Get info from the setup packet - consoleplayer = sinfo->yourplayer; - compatibility_level = sinfo->complevel; - G_Compatibility(); - startskill = sinfo->skill; - deathmatch = sinfo->deathmatch; - startmap = sinfo->level; - startepisode = sinfo->episode; - ticdup = sinfo->ticdup; - xtratics = sinfo->extratic; - G_ReadOptions(sinfo->game_options); - - lprintf(LO_INFO, "\tjoined game as player %d/%d; %d WADs specified\n", - consoleplayer+1, numplayers = sinfo->players, sinfo->numwads); - { - char *p = sinfo->wadnames; - int i = sinfo->numwads; - - while (i--) { - D_AddFile(p, source_net); - p += strlen(p) + 1; - } - } - Z_Free(packet); - } - localcmds = netcmds[displayplayer = consoleplayer]; - for (i=0; itype != PKT_GO); - } - Z_Free(packet); -} - -boolean D_NetGetWad(const char* name) -{ -#if defined(HAVE_WAIT_H) - size_t psize = sizeof(packet_header_t) + strlen(name) + 500; - packet_header_t *packet; - boolean done = false; - - if (!server || strchr(name, '/')) return false; // If it contains path info, reject - - do { - // Send WAD request to remote - packet = Z_Malloc(psize, PU_STATIC, NULL); - packet_set(packet, PKT_WAD, 0); - *(byte*)(packet+1) = consoleplayer; - strcpy(1+(byte*)(packet+1), name); - I_SendPacket(packet, sizeof(packet_header_t) + strlen(name) + 2); - - I_uSleep(10000); - } while (!I_GetPacket(packet, psize) || (packet->type != PKT_WAD)); - Z_Free(packet); - - if (!strcasecmp((void*)(packet+1), name)) { - pid_t pid; - int rv; - byte *p = (byte*)(packet+1) + strlen(name) + 1; - - /* Automatic wad file retrieval using wget (supports http and ftp, using URLs) - * Unix systems have all these commands handy, this kind of thing is easy - * Any windo$e port will have some awkward work replacing these. - */ - /* cph - caution here. This is data from an untrusted source. - * Don't pass it via a shell. */ - if ((pid = fork()) == -1) - perror("fork"); - else if (!pid) { - /* Child chains to wget, does the download */ - execlp("wget", "wget", p, NULL); - } - /* This is the parent, i.e. main LxDoom process */ - wait(&rv); - if (!(done = !access(name, R_OK))) { - if (!strcmp(p+strlen(p)-4, ".zip")) { - p = strrchr(p, '/')+1; - if ((pid = fork()) == -1) - perror("fork"); - else if (!pid) { - /* Child executes decompressor */ - execlp("unzip", "unzip", p, name, NULL); - } - /* Parent waits for the file */ - wait(&rv); - done = !!access(name, R_OK); - } - /* Add more decompression protocols here as desired */ - } - Z_Free(buffer); - } - return done; -#else /* HAVE_WAIT_H */ - return false; -#endif -} - -void NetUpdate(void) -{ - static int lastmadetic; - if (isExtraDDisplay) - return; - if (server) { // Receive network packets - size_t recvlen; - packet_header_t *packet = Z_Malloc(10000, PU_STATIC, NULL); - while ((recvlen = I_GetPacket(packet, 10000))) { - switch(packet->type) { - case PKT_TICS: - { - byte *p = (void*)(packet+1); - int tics = *p++; - unsigned long ptic = doom_ntohl(packet->tic); - if (ptic > (unsigned)remotetic) { // Missed some - packet_set(packet, PKT_RETRANS, remotetic); - *(byte*)(packet+1) = consoleplayer; - I_SendPacket(packet, sizeof(*packet)+1); - } else { - if (ptic + tics <= (unsigned)remotetic) break; // Will not improve things - remotetic = ptic; - while (tics--) { - int players = *p++; - while (players--) { - int n = *p++; - RawToTic(&netcmds[n][remotetic%BACKUPTICS], p); - p += sizeof(ticcmd_t); - } - remotetic++; - } - } - } - break; - case PKT_RETRANS: // Resend request - remotesend = doom_ntohl(packet->tic); - break; - case PKT_DOWN: // Server downed - { - int j; - for (j=0; j 0 ? newtics : 0); - lastmadetic += newtics; - if (ffmap) newtics++; - while (newtics--) { - I_StartTic(); - if (maketic - gametic > BACKUPTICS/2) break; - G_BuildTiccmd(&localcmds[maketic%BACKUPTICS]); - maketic++; - } - if (server && maketic > remotesend) { // Send the tics to the server - int sendtics; - remotesend -= xtratics; - if (remotesend < 0) remotesend = 0; - sendtics = maketic - remotesend; - { - size_t pkt_size = sizeof(packet_header_t) + 2 + sendtics * sizeof(ticcmd_t); - packet_header_t *packet = Z_Malloc(pkt_size, PU_STATIC, NULL); - - packet_set(packet, PKT_TICC, maketic - sendtics); - *(byte*)(packet+1) = sendtics; - *(((byte*)(packet+1))+1) = consoleplayer; - { - void *tic = ((byte*)(packet+1)) +2; - while (sendtics--) { - TicToRaw(tic, &localcmds[remotesend++%BACKUPTICS]); - tic = (byte *)tic + sizeof(ticcmd_t); - } - } - I_SendPacket(packet, pkt_size); - Z_Free(packet); - } - } - } -} -#else - -void D_BuildNewTiccmds(void) -{ - static int lastmadetic; - int newtics = I_GetTime() - lastmadetic; - lastmadetic += newtics; - while (newtics--) - { - I_StartTic(); - if (maketic - gametic > BACKUPTICS/2) break; - G_BuildTiccmd(&localcmds[maketic%BACKUPTICS]); - maketic++; - } -} -#endif - -#ifdef HAVE_NET -/* cph - data passed to this must be in the Doom (little-) endian */ -void D_NetSendMisc(netmisctype_t type, size_t len, void* data) -{ - if (server) { - size_t size = sizeof(packet_header_t) + 3*sizeof(int) + len; - packet_header_t *packet = Z_Malloc(size, PU_STATIC, NULL); - int *p = (void*)(packet+1); - - packet_set(packet, PKT_EXTRA, gametic); - *p++ = LONG(type); *p++ = LONG(consoleplayer); *p++ = LONG(len); - memcpy(p, data, len); - I_SendPacket(packet, size); - - Z_Free(packet); - } -} - -static void CheckQueuedPackets(void) -{ - int i; - for (i=0; (unsigned)itic) <= gametic) - switch (queuedpacket[i]->type) { - case PKT_QUIT: // Player quit the game - { - int pn = *(byte*)(queuedpacket[i]+1); - playeringame[pn] = false; - doom_printf("Player %d left the game\n", pn); - } - break; - case PKT_EXTRA: - { - int *p = (int*)(queuedpacket[i]+1); - size_t len = LONG(*(p+2)); - switch (LONG(*p)) { - case nm_plcolour: - G_ChangedPlayerColour(LONG(*(p+1)), LONG(*(p+3))); - break; - case nm_savegamename: - if (len < SAVEDESCLEN) { - memcpy(savedescription, p+3, len); - // Force terminating 0 in case - savedescription[len] = 0; - } - break; - } - } - break; - default: // Should not be queued - break; - } - - { // Requeue remaining packets - int newnum = 0; - packet_header_t **newqueue = NULL; - - for (i=0; (unsigned)itic) > gametic) { - newqueue = Z_Realloc(newqueue, ++newnum * sizeof *newqueue, - PU_STATIC, NULL); - newqueue[newnum-1] = queuedpacket[i]; - } else Z_Free(queuedpacket[i]); - - Z_Free(queuedpacket); - numqueuedpackets = newnum; queuedpacket = newqueue; - } -} -#endif // HAVE_NET - -void TryRunTics (void) -{ - int runtics; - int entertime = I_GetTime(); - - // Wait for tics to run - while (1) { -#ifdef HAVE_NET - NetUpdate(); - runtics = (server ? remotetic : maketic) - gametic; -#else - D_BuildNewTiccmds(); - runtics = maketic - gametic; -#endif - if (!runtics) { - if (!movement_smooth) { -#ifdef HAVE_NET - if (server) - I_WaitForPacket(ms_to_next_tick); - else -#endif - // I_uSleep(ms_to_next_tick*1000); - } - if (I_GetTime() - entertime > 10) { -#ifdef HAVE_NET - if (server) { - char buf[sizeof(packet_header_t)+1]; - remotesend--; - packet_set((packet_header_t *)buf, PKT_RETRANS, remotetic); - buf[sizeof(buf)-1] = consoleplayer; - I_SendPacket((packet_header_t *)buf, sizeof buf); - } -#endif - M_Ticker(); return; - } - //if ((displaytime) < (tic_vars.next-SDL_GetTicks())) - { - WasRenderedInTryRunTics = true; - if (movement_smooth && gamestate==wipegamestate) - { - isExtraDDisplay = true; - D_Display(); - isExtraDDisplay = false; - } - } - } else break; - } - - while (runtics--) { -#ifdef HAVE_NET - if (server) CheckQueuedPackets(); -#endif - if (advancedemo) - D_DoAdvanceDemo (); - M_Ticker (); - if (movement_smooth) { - tic_vars.start = I_GetTimeMS(); - tic_vars.next = (unsigned int)((tic_vars.start * tic_vars.msec + 1.0f) / tic_vars.msec); - tic_vars.step = tic_vars.next - tic_vars.start; - } - G_Ticker (); - gametic++; -#ifdef HAVE_NET - NetUpdate(); // Keep sending our tics to avoid stalling remote nodes -#endif - } -} - -#ifdef HAVE_NET -static void D_QuitNetGame (void) -{ - byte buf[1 + sizeof(packet_header_t)]; - packet_header_t *packet = (void*)buf; - int i; - - if (!server) return; - buf[sizeof(packet_header_t)] = consoleplayer; - packet_set(packet, PKT_QUIT, gametic); - - for (i=0; i<4; i++) { - I_SendPacket(packet, 1 + sizeof(packet_header_t)); - I_uSleep(10000); - } -} -#endif diff --git a/components/doom/prboom/d_deh.c b/components/doom/prboom/d_deh.c deleted file mode 100644 index 3653541c..00000000 --- a/components/doom/prboom/d_deh.c +++ /dev/null @@ -1,3083 +0,0 @@ -/* Emacs style mode select -*- C++ -*- - *----------------------------------------------------------------------------- - * - * - * PrBoom: a Doom port merged with LxDoom and LSDLDoom - * based on BOOM, a modified and improved DOOM engine - * Copyright (C) 1999 by - * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman - * Copyright (C) 1999-2004 by - * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze - * Copyright 2005, 2006 by - * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko - * - * 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. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA. - * - * DESCRIPTION: - * Dehacked file support - * New for the TeamTNT "Boom" engine - * - * Author: Ty Halderman, TeamTNT - * - *--------------------------------------------------------------------*/ - -// killough 5/2/98: fixed headers, removed rendunant external declarations: -#include "doomdef.h" -#include "doomtype.h" -#include "doomstat.h" -#include "d_deh.h" -#include "sounds.h" -#include "info.h" -#include "m_cheat.h" -#include "p_inter.h" -#include "p_enemy.h" -#include "g_game.h" -#include "d_think.h" -#include "w_wad.h" - -// CPhipps - modify to use logical output routine -#include "lprintf.h" - -// haleyjd 9/22/99 -int HelperThing = -1; // in P_SpawnMapThing to substitute helper thing - -// variables used in other routines -boolean deh_pars = false; // in wi_stuff to allow pars in modified games - -// #include "d_deh.h" -- we don't do that here but we declare the -// variables. This externalizes everything that there is a string -// set for in the language files. See d_deh.h for detailed comments, -// original English values etc. These are set to the macro values, -// which are set by D_ENGLSH.H or D_FRENCH.H(etc). BEX files are a -// better way of changing these strings globally by language. - -// ==================================================================== -// Any of these can be changed using the bex extensions -#include "dstrings.h" // to get the initial values -/* cph - const's - * - removed redundant "can't XXX in a netgame" strings. - */ -const char* const s_D_DEVSTR = D_DEVSTR; -const char* const s_D_CDROM = D_CDROM; -const char* const s_PRESSKEY = PRESSKEY; -const char* const s_PRESSYN = PRESSYN; -const char* const s_QUITMSG = QUITMSG; -const char* const s_QSAVESPOT = QSAVESPOT; // PRESSKEY; -const char* const s_SAVEDEAD = SAVEDEAD; // PRESSKEY; // remove duplicate y/n -const char* const s_QSPROMPT = QSPROMPT; // PRESSYN; -const char* const s_QLPROMPT = QLPROMPT; // PRESSYN; -const char* const s_NEWGAME = NEWGAME; // PRESSKEY; -const char* const s_RESTARTLEVEL= RESTARTLEVEL; // PRESSYN; -const char* const s_NIGHTMARE = NIGHTMARE; // PRESSYN; -const char* const s_SWSTRING = SWSTRING; // PRESSKEY; -const char* const s_MSGOFF = MSGOFF; -const char* const s_MSGON = MSGON; -const char* const s_NETEND = NETEND; // PRESSKEY; -const char* const s_ENDGAME = ENDGAME; // PRESSYN; // killough 4/4/98: end -const char* const s_DOSY = DOSY; -const char* const s_DETAILHI = DETAILHI; -const char* const s_DETAILLO = DETAILLO; -const char* const s_GAMMALVL0 = GAMMALVL0; -const char* const s_GAMMALVL1 = GAMMALVL1; -const char* const s_GAMMALVL2 = GAMMALVL2; -const char* const s_GAMMALVL3 = GAMMALVL3; -const char* const s_GAMMALVL4 = GAMMALVL4; -const char* const s_EMPTYSTRING = EMPTYSTRING; -const char* const s_GOTARMOR = GOTARMOR; -const char* const s_GOTMEGA = GOTMEGA; -const char* const s_GOTHTHBONUS = GOTHTHBONUS; -const char* const s_GOTARMBONUS = GOTARMBONUS; -const char* const s_GOTSTIM = GOTSTIM; -const char* const s_GOTMEDINEED = GOTMEDINEED; -const char* const s_GOTMEDIKIT = GOTMEDIKIT; -const char* const s_GOTSUPER = GOTSUPER; -const char* const s_GOTBLUECARD = GOTBLUECARD; -const char* const s_GOTYELWCARD = GOTYELWCARD; -const char* const s_GOTREDCARD = GOTREDCARD; -const char* const s_GOTBLUESKUL = GOTBLUESKUL; -const char* const s_GOTYELWSKUL = GOTYELWSKUL; -const char* const s_GOTREDSKULL = GOTREDSKULL; -const char* const s_GOTINVUL = GOTINVUL; -const char* const s_GOTBERSERK = GOTBERSERK; -const char* const s_GOTINVIS = GOTINVIS; -const char* const s_GOTSUIT = GOTSUIT; -const char* const s_GOTMAP = GOTMAP; -const char* const s_GOTVISOR = GOTVISOR; -const char* const s_GOTMSPHERE = GOTMSPHERE; -const char* const s_GOTCLIP = GOTCLIP; -const char* const s_GOTCLIPBOX = GOTCLIPBOX; -const char* const s_GOTROCKET = GOTROCKET; -const char* const s_GOTROCKBOX = GOTROCKBOX; -const char* const s_GOTCELL = GOTCELL; -const char* const s_GOTCELLBOX = GOTCELLBOX; -const char* const s_GOTSHELLS = GOTSHELLS; -const char* const s_GOTSHELLBOX = GOTSHELLBOX; -const char* const s_GOTBACKPACK = GOTBACKPACK; -const char* const s_GOTBFG9000 = GOTBFG9000; -const char* const s_GOTCHAINGUN = GOTCHAINGUN; -const char* const s_GOTCHAINSAW = GOTCHAINSAW; -const char* const s_GOTLAUNCHER = GOTLAUNCHER; -const char* const s_GOTPLASMA = GOTPLASMA; -const char* const s_GOTSHOTGUN = GOTSHOTGUN; -const char* const s_GOTSHOTGUN2 = GOTSHOTGUN2; -const char* const s_PD_BLUEO = PD_BLUEO; -const char* const s_PD_REDO = PD_REDO; -const char* const s_PD_YELLOWO = PD_YELLOWO; -const char* const s_PD_BLUEK = PD_BLUEK; -const char* const s_PD_REDK = PD_REDK; -const char* const s_PD_YELLOWK = PD_YELLOWK; -const char* const s_PD_BLUEC = PD_BLUEC; -const char* const s_PD_REDC = PD_REDC; -const char* const s_PD_YELLOWC = PD_YELLOWC; -const char* const s_PD_BLUES = PD_BLUES; -const char* const s_PD_REDS = PD_REDS; -const char* const s_PD_YELLOWS = PD_YELLOWS; -const char* const s_PD_ANY = PD_ANY; -const char* const s_PD_ALL3 = PD_ALL3; -const char* const s_PD_ALL6 = PD_ALL6; -const char* const s_GGSAVED = GGSAVED; -const char* const s_HUSTR_MSGU = HUSTR_MSGU; -const char* const s_HUSTR_E1M1 = HUSTR_E1M1; -const char* const s_HUSTR_E1M2 = HUSTR_E1M2; -const char* const s_HUSTR_E1M3 = HUSTR_E1M3; -const char* const s_HUSTR_E1M4 = HUSTR_E1M4; -const char* const s_HUSTR_E1M5 = HUSTR_E1M5; -const char* const s_HUSTR_E1M6 = HUSTR_E1M6; -const char* const s_HUSTR_E1M7 = HUSTR_E1M7; -const char* const s_HUSTR_E1M8 = HUSTR_E1M8; -const char* const s_HUSTR_E1M9 = HUSTR_E1M9; -const char* const s_HUSTR_E2M1 = HUSTR_E2M1; -const char* const s_HUSTR_E2M2 = HUSTR_E2M2; -const char* const s_HUSTR_E2M3 = HUSTR_E2M3; -const char* const s_HUSTR_E2M4 = HUSTR_E2M4; -const char* const s_HUSTR_E2M5 = HUSTR_E2M5; -const char* const s_HUSTR_E2M6 = HUSTR_E2M6; -const char* const s_HUSTR_E2M7 = HUSTR_E2M7; -const char* const s_HUSTR_E2M8 = HUSTR_E2M8; -const char* const s_HUSTR_E2M9 = HUSTR_E2M9; -const char* const s_HUSTR_E3M1 = HUSTR_E3M1; -const char* const s_HUSTR_E3M2 = HUSTR_E3M2; -const char* const s_HUSTR_E3M3 = HUSTR_E3M3; -const char* const s_HUSTR_E3M4 = HUSTR_E3M4; -const char* const s_HUSTR_E3M5 = HUSTR_E3M5; -const char* const s_HUSTR_E3M6 = HUSTR_E3M6; -const char* const s_HUSTR_E3M7 = HUSTR_E3M7; -const char* const s_HUSTR_E3M8 = HUSTR_E3M8; -const char* const s_HUSTR_E3M9 = HUSTR_E3M9; -const char* const s_HUSTR_E4M1 = HUSTR_E4M1; -const char* const s_HUSTR_E4M2 = HUSTR_E4M2; -const char* const s_HUSTR_E4M3 = HUSTR_E4M3; -const char* const s_HUSTR_E4M4 = HUSTR_E4M4; -const char* const s_HUSTR_E4M5 = HUSTR_E4M5; -const char* const s_HUSTR_E4M6 = HUSTR_E4M6; -const char* const s_HUSTR_E4M7 = HUSTR_E4M7; -const char* const s_HUSTR_E4M8 = HUSTR_E4M8; -const char* const s_HUSTR_E4M9 = HUSTR_E4M9; -const char* const s_HUSTR_1 = HUSTR_1; -const char* const s_HUSTR_2 = HUSTR_2; -const char* const s_HUSTR_3 = HUSTR_3; -const char* const s_HUSTR_4 = HUSTR_4; -const char* const s_HUSTR_5 = HUSTR_5; -const char* const s_HUSTR_6 = HUSTR_6; -const char* const s_HUSTR_7 = HUSTR_7; -const char* const s_HUSTR_8 = HUSTR_8; -const char* const s_HUSTR_9 = HUSTR_9; -const char* const s_HUSTR_10 = HUSTR_10; -const char* const s_HUSTR_11 = HUSTR_11; -const char* const s_HUSTR_12 = HUSTR_12; -const char* const s_HUSTR_13 = HUSTR_13; -const char* const s_HUSTR_14 = HUSTR_14; -const char* const s_HUSTR_15 = HUSTR_15; -const char* const s_HUSTR_16 = HUSTR_16; -const char* const s_HUSTR_17 = HUSTR_17; -const char* const s_HUSTR_18 = HUSTR_18; -const char* const s_HUSTR_19 = HUSTR_19; -const char* const s_HUSTR_20 = HUSTR_20; -const char* const s_HUSTR_21 = HUSTR_21; -const char* const s_HUSTR_22 = HUSTR_22; -const char* const s_HUSTR_23 = HUSTR_23; -const char* const s_HUSTR_24 = HUSTR_24; -const char* const s_HUSTR_25 = HUSTR_25; -const char* const s_HUSTR_26 = HUSTR_26; -const char* const s_HUSTR_27 = HUSTR_27; -const char* const s_HUSTR_28 = HUSTR_28; -const char* const s_HUSTR_29 = HUSTR_29; -const char* const s_HUSTR_30 = HUSTR_30; -const char* const s_HUSTR_31 = HUSTR_31; -const char* const s_HUSTR_32 = HUSTR_32; -const char* const s_PHUSTR_1 = PHUSTR_1; -const char* const s_PHUSTR_2 = PHUSTR_2; -const char* const s_PHUSTR_3 = PHUSTR_3; -const char* const s_PHUSTR_4 = PHUSTR_4; -const char* const s_PHUSTR_5 = PHUSTR_5; -const char* const s_PHUSTR_6 = PHUSTR_6; -const char* const s_PHUSTR_7 = PHUSTR_7; -const char* const s_PHUSTR_8 = PHUSTR_8; -const char* const s_PHUSTR_9 = PHUSTR_9; -const char* const s_PHUSTR_10 = PHUSTR_10; -const char* const s_PHUSTR_11 = PHUSTR_11; -const char* const s_PHUSTR_12 = PHUSTR_12; -const char* const s_PHUSTR_13 = PHUSTR_13; -const char* const s_PHUSTR_14 = PHUSTR_14; -const char* const s_PHUSTR_15 = PHUSTR_15; -const char* const s_PHUSTR_16 = PHUSTR_16; -const char* const s_PHUSTR_17 = PHUSTR_17; -const char* const s_PHUSTR_18 = PHUSTR_18; -const char* const s_PHUSTR_19 = PHUSTR_19; -const char* const s_PHUSTR_20 = PHUSTR_20; -const char* const s_PHUSTR_21 = PHUSTR_21; -const char* const s_PHUSTR_22 = PHUSTR_22; -const char* const s_PHUSTR_23 = PHUSTR_23; -const char* const s_PHUSTR_24 = PHUSTR_24; -const char* const s_PHUSTR_25 = PHUSTR_25; -const char* const s_PHUSTR_26 = PHUSTR_26; -const char* const s_PHUSTR_27 = PHUSTR_27; -const char* const s_PHUSTR_28 = PHUSTR_28; -const char* const s_PHUSTR_29 = PHUSTR_29; -const char* const s_PHUSTR_30 = PHUSTR_30; -const char* const s_PHUSTR_31 = PHUSTR_31; -const char* const s_PHUSTR_32 = PHUSTR_32; -const char* const s_THUSTR_1 = THUSTR_1; -const char* const s_THUSTR_2 = THUSTR_2; -const char* const s_THUSTR_3 = THUSTR_3; -const char* const s_THUSTR_4 = THUSTR_4; -const char* const s_THUSTR_5 = THUSTR_5; -const char* const s_THUSTR_6 = THUSTR_6; -const char* const s_THUSTR_7 = THUSTR_7; -const char* const s_THUSTR_8 = THUSTR_8; -const char* const s_THUSTR_9 = THUSTR_9; -const char* const s_THUSTR_10 = THUSTR_10; -const char* const s_THUSTR_11 = THUSTR_11; -const char* const s_THUSTR_12 = THUSTR_12; -const char* const s_THUSTR_13 = THUSTR_13; -const char* const s_THUSTR_14 = THUSTR_14; -const char* const s_THUSTR_15 = THUSTR_15; -const char* const s_THUSTR_16 = THUSTR_16; -const char* const s_THUSTR_17 = THUSTR_17; -const char* const s_THUSTR_18 = THUSTR_18; -const char* const s_THUSTR_19 = THUSTR_19; -const char* const s_THUSTR_20 = THUSTR_20; -const char* const s_THUSTR_21 = THUSTR_21; -const char* const s_THUSTR_22 = THUSTR_22; -const char* const s_THUSTR_23 = THUSTR_23; -const char* const s_THUSTR_24 = THUSTR_24; -const char* const s_THUSTR_25 = THUSTR_25; -const char* const s_THUSTR_26 = THUSTR_26; -const char* const s_THUSTR_27 = THUSTR_27; -const char* const s_THUSTR_28 = THUSTR_28; -const char* const s_THUSTR_29 = THUSTR_29; -const char* const s_THUSTR_30 = THUSTR_30; -const char* const s_THUSTR_31 = THUSTR_31; -const char* const s_THUSTR_32 = THUSTR_32; -const char* const s_HUSTR_CHATMACRO1 = HUSTR_CHATMACRO1; -const char* const s_HUSTR_CHATMACRO2 = HUSTR_CHATMACRO2; -const char* const s_HUSTR_CHATMACRO3 = HUSTR_CHATMACRO3; -const char* const s_HUSTR_CHATMACRO4 = HUSTR_CHATMACRO4; -const char* const s_HUSTR_CHATMACRO5 = HUSTR_CHATMACRO5; -const char* const s_HUSTR_CHATMACRO6 = HUSTR_CHATMACRO6; -const char* const s_HUSTR_CHATMACRO7 = HUSTR_CHATMACRO7; -const char* const s_HUSTR_CHATMACRO8 = HUSTR_CHATMACRO8; -const char* const s_HUSTR_CHATMACRO9 = HUSTR_CHATMACRO9; -const char* const s_HUSTR_CHATMACRO0 = HUSTR_CHATMACRO0; -const char* const s_HUSTR_TALKTOSELF1 = HUSTR_TALKTOSELF1; -const char* const s_HUSTR_TALKTOSELF2 = HUSTR_TALKTOSELF2; -const char* const s_HUSTR_TALKTOSELF3 = HUSTR_TALKTOSELF3; -const char* const s_HUSTR_TALKTOSELF4 = HUSTR_TALKTOSELF4; -const char* const s_HUSTR_TALKTOSELF5 = HUSTR_TALKTOSELF5; -const char* const s_HUSTR_MESSAGESENT = HUSTR_MESSAGESENT; -const char* const s_HUSTR_PLRGREEN = HUSTR_PLRGREEN; -const char* const s_HUSTR_PLRINDIGO = HUSTR_PLRINDIGO; -const char* const s_HUSTR_PLRBROWN = HUSTR_PLRBROWN; -const char* const s_HUSTR_PLRRED = HUSTR_PLRRED; -const char* const s_AMSTR_FOLLOWON = AMSTR_FOLLOWON; -const char* const s_AMSTR_FOLLOWOFF = AMSTR_FOLLOWOFF; -const char* const s_AMSTR_GRIDON = AMSTR_GRIDON; -const char* const s_AMSTR_GRIDOFF = AMSTR_GRIDOFF; -const char* const s_AMSTR_MARKEDSPOT = AMSTR_MARKEDSPOT; -const char* const s_AMSTR_MARKSCLEARED = AMSTR_MARKSCLEARED; -// CPhipps - automap rotate & overlay -const char* const s_AMSTR_ROTATEON = AMSTR_ROTATEON; -const char* const s_AMSTR_ROTATEOFF = AMSTR_ROTATEOFF; -const char* const s_AMSTR_OVERLAYON = AMSTR_OVERLAYON; -const char* const s_AMSTR_OVERLAYOFF = AMSTR_OVERLAYOFF; -const char* const s_STSTR_MUS = STSTR_MUS; -const char* const s_STSTR_NOMUS = STSTR_NOMUS; -const char* const s_STSTR_DQDON = STSTR_DQDON; -const char* const s_STSTR_DQDOFF = STSTR_DQDOFF; -const char* const s_STSTR_KFAADDED = STSTR_KFAADDED; -const char* const s_STSTR_FAADDED = STSTR_FAADDED; -const char* const s_STSTR_NCON = STSTR_NCON; -const char* const s_STSTR_NCOFF = STSTR_NCOFF; -const char* const s_STSTR_BEHOLD = STSTR_BEHOLD; -const char* const s_STSTR_BEHOLDX = STSTR_BEHOLDX; -const char* const s_STSTR_CHOPPERS = STSTR_CHOPPERS; -const char* const s_STSTR_CLEV = STSTR_CLEV; -const char* const s_STSTR_COMPON = STSTR_COMPON; -const char* const s_STSTR_COMPOFF = STSTR_COMPOFF; -const char* const s_E1TEXT = E1TEXT; -const char* const s_E2TEXT = E2TEXT; -const char* const s_E3TEXT = E3TEXT; -const char* const s_E4TEXT = E4TEXT; -const char* const s_C1TEXT = C1TEXT; -const char* const s_C2TEXT = C2TEXT; -const char* const s_C3TEXT = C3TEXT; -const char* const s_C4TEXT = C4TEXT; -const char* const s_C5TEXT = C5TEXT; -const char* const s_C6TEXT = C6TEXT; -const char* const s_P1TEXT = P1TEXT; -const char* const s_P2TEXT = P2TEXT; -const char* const s_P3TEXT = P3TEXT; -const char* const s_P4TEXT = P4TEXT; -const char* const s_P5TEXT = P5TEXT; -const char* const s_P6TEXT = P6TEXT; -const char* const s_T1TEXT = T1TEXT; -const char* const s_T2TEXT = T2TEXT; -const char* const s_T3TEXT = T3TEXT; -const char* const s_T4TEXT = T4TEXT; -const char* const s_T5TEXT = T5TEXT; -const char* const s_T6TEXT = T6TEXT; -const char* const s_CC_ZOMBIE = CC_ZOMBIE; -const char* const s_CC_SHOTGUN = CC_SHOTGUN; -const char* const s_CC_HEAVY = CC_HEAVY; -const char* const s_CC_IMP = CC_IMP; -const char* const s_CC_DEMON = CC_DEMON; -const char* const s_CC_LOST = CC_LOST; -const char* const s_CC_CACO = CC_CACO; -const char* const s_CC_HELL = CC_HELL; -const char* const s_CC_BARON = CC_BARON; -const char* const s_CC_ARACH = CC_ARACH; -const char* const s_CC_PAIN = CC_PAIN; -const char* const s_CC_REVEN = CC_REVEN; -const char* const s_CC_MANCU = CC_MANCU; -const char* const s_CC_ARCH = CC_ARCH; -const char* const s_CC_SPIDER = CC_SPIDER; -const char* const s_CC_CYBER = CC_CYBER; -const char* const s_CC_HERO = CC_HERO; -// Ty 03/30/98 - new substitutions for background textures -// during int screens -const char* const bgflatE1 = "FLOOR4_8"; // end of DOOM Episode 1 -const char* const bgflatE2 = "SFLR6_1"; // end of DOOM Episode 2 -const char* const bgflatE3 = "MFLR8_4"; // end of DOOM Episode 3 -const char* const bgflatE4 = "MFLR8_3"; // end of DOOM Episode 4 -const char* const bgflat06 = "SLIME16"; // DOOM2 after MAP06 -const char* const bgflat11 = "RROCK14"; // DOOM2 after MAP11 -const char* const bgflat20 = "RROCK07"; // DOOM2 after MAP20 -const char* const bgflat30 = "RROCK17"; // DOOM2 after MAP30 -const char* const bgflat15 = "RROCK13"; // DOOM2 going MAP15 to MAP31 -const char* const bgflat31 = "RROCK19"; // DOOM2 going MAP31 to MAP32 -const char* const bgcastcall = "BOSSBACK"; // Panel behind cast call - -const char* const startup1 = ""; // blank lines are default and are not printed -const char* const startup2 = ""; -const char* const startup3 = ""; -const char* const startup4 = ""; -const char* const startup5 = ""; - -// end d_deh.h variable declarations -// ==================================================================== - -const char* const deh_newlevel = "NEWLEVEL"; // CPhipps - const - -// DOOM shareware/registered/retail (Ultimate) names. -// CPhipps - const**const -const char * const *const mapnames[] = -{ - &s_HUSTR_E1M1, - &s_HUSTR_E1M2, - &s_HUSTR_E1M3, - &s_HUSTR_E1M4, - &s_HUSTR_E1M5, - &s_HUSTR_E1M6, - &s_HUSTR_E1M7, - &s_HUSTR_E1M8, - &s_HUSTR_E1M9, - - &s_HUSTR_E2M1, - &s_HUSTR_E2M2, - &s_HUSTR_E2M3, - &s_HUSTR_E2M4, - &s_HUSTR_E2M5, - &s_HUSTR_E2M6, - &s_HUSTR_E2M7, - &s_HUSTR_E2M8, - &s_HUSTR_E2M9, - - &s_HUSTR_E3M1, - &s_HUSTR_E3M2, - &s_HUSTR_E3M3, - &s_HUSTR_E3M4, - &s_HUSTR_E3M5, - &s_HUSTR_E3M6, - &s_HUSTR_E3M7, - &s_HUSTR_E3M8, - &s_HUSTR_E3M9, - - &s_HUSTR_E4M1, - &s_HUSTR_E4M2, - &s_HUSTR_E4M3, - &s_HUSTR_E4M4, - &s_HUSTR_E4M5, - &s_HUSTR_E4M6, - &s_HUSTR_E4M7, - &s_HUSTR_E4M8, - &s_HUSTR_E4M9, - - &deh_newlevel, // spares? Unused. - &deh_newlevel, - &deh_newlevel, - &deh_newlevel, - &deh_newlevel, - &deh_newlevel, - &deh_newlevel, - &deh_newlevel, - &deh_newlevel -}; - -// CPhipps - const**const -const char * const*const mapnames2[] = // DOOM 2 map names. -{ - &s_HUSTR_1, - &s_HUSTR_2, - &s_HUSTR_3, - &s_HUSTR_4, - &s_HUSTR_5, - &s_HUSTR_6, - &s_HUSTR_7, - &s_HUSTR_8, - &s_HUSTR_9, - &s_HUSTR_10, - &s_HUSTR_11, - - &s_HUSTR_12, - &s_HUSTR_13, - &s_HUSTR_14, - &s_HUSTR_15, - &s_HUSTR_16, - &s_HUSTR_17, - &s_HUSTR_18, - &s_HUSTR_19, - &s_HUSTR_20, - - &s_HUSTR_21, - &s_HUSTR_22, - &s_HUSTR_23, - &s_HUSTR_24, - &s_HUSTR_25, - &s_HUSTR_26, - &s_HUSTR_27, - &s_HUSTR_28, - &s_HUSTR_29, - &s_HUSTR_30, - &s_HUSTR_31, - &s_HUSTR_32, -}; - -// CPhipps - const**const -const char * const*const mapnamesp[] = // Plutonia WAD map names. -{ - &s_PHUSTR_1, - &s_PHUSTR_2, - &s_PHUSTR_3, - &s_PHUSTR_4, - &s_PHUSTR_5, - &s_PHUSTR_6, - &s_PHUSTR_7, - &s_PHUSTR_8, - &s_PHUSTR_9, - &s_PHUSTR_10, - &s_PHUSTR_11, - - &s_PHUSTR_12, - &s_PHUSTR_13, - &s_PHUSTR_14, - &s_PHUSTR_15, - &s_PHUSTR_16, - &s_PHUSTR_17, - &s_PHUSTR_18, - &s_PHUSTR_19, - &s_PHUSTR_20, - - &s_PHUSTR_21, - &s_PHUSTR_22, - &s_PHUSTR_23, - &s_PHUSTR_24, - &s_PHUSTR_25, - &s_PHUSTR_26, - &s_PHUSTR_27, - &s_PHUSTR_28, - &s_PHUSTR_29, - &s_PHUSTR_30, - &s_PHUSTR_31, - &s_PHUSTR_32, -}; - -// CPhipps - const**const -const char * const*const mapnamest[] = // TNT WAD map names. -{ - &s_THUSTR_1, - &s_THUSTR_2, - &s_THUSTR_3, - &s_THUSTR_4, - &s_THUSTR_5, - &s_THUSTR_6, - &s_THUSTR_7, - &s_THUSTR_8, - &s_THUSTR_9, - &s_THUSTR_10, - &s_THUSTR_11, - - &s_THUSTR_12, - &s_THUSTR_13, - &s_THUSTR_14, - &s_THUSTR_15, - &s_THUSTR_16, - &s_THUSTR_17, - &s_THUSTR_18, - &s_THUSTR_19, - &s_THUSTR_20, - - &s_THUSTR_21, - &s_THUSTR_22, - &s_THUSTR_23, - &s_THUSTR_24, - &s_THUSTR_25, - &s_THUSTR_26, - &s_THUSTR_27, - &s_THUSTR_28, - &s_THUSTR_29, - &s_THUSTR_30, - &s_THUSTR_31, - &s_THUSTR_32, -}; - - -#ifndef NODEHSUPPORT - -#define TRUE 1 -#define FALSE 0 - -// killough 10/98: new functions, to allow processing DEH files in-memory -// (e.g. from wads) - -typedef struct { - /* cph 2006/08/06 - - * if lump != NULL, lump is the start of the lump, - * inp is the current read pos. */ - const byte *inp, *lump; - long size; - /* else, !lump, and f is the file being read */ - FILE* f; -} DEHFILE; - -// killough 10/98: emulate IO whether input really comes from a file or not - -static char *dehfgets(char *buf, size_t n, DEHFILE *fp) -{ - if (!fp->lump) // If this is a real file, - return (fgets)(buf, n, fp->f); // return regular fgets - if (!n || !*fp->inp || fp->size<=0) // If no more characters - return NULL; - if (n==1) - fp->size--, *buf = *fp->inp++; - else - { // copy buffer - char *p = buf; - while (n>1 && *fp->inp && fp->size && - (n--, fp->size--, *p++ = *fp->inp++) != '\n') - ; - *p = 0; - } - return buf; // Return buffer pointer -} - -static int dehfeof(DEHFILE *fp) -{ - return !fp->lump ? feof(fp->f) : !*fp->inp || fp->size<=0; -} - -static int dehfgetc(DEHFILE *fp) -{ - return !fp->lump ? fgetc(fp->f) : fp->size > 0 ? - fp->size--, *fp->inp++ : EOF; -} - -// Do this for a lookup--the pointer (loaded above) is cross-referenced -// to a string key that is the same as the define above. We will use -// strdups to set these new values that we read from the file, orphaning -// the original value set above. - -// CPhipps - make strings pointed to const -typedef struct { - const char *const * ppstr; // doubly indirect pointer to string - const char * const lookup; // pointer to lookup string name -} deh_strs; - -/* CPhipps - const, static - * - removed redundant "Can't XXX in a netgame" strings - */ -static const deh_strs deh_strlookup[] = { - {&s_D_DEVSTR,"D_DEVSTR"}, - {&s_D_CDROM,"D_CDROM"}, - {&s_PRESSKEY,"PRESSKEY"}, - {&s_PRESSYN,"PRESSYN"}, - {&s_QUITMSG,"QUITMSG"}, - {&s_QSAVESPOT,"QSAVESPOT"}, - {&s_SAVEDEAD,"SAVEDEAD"}, - /* cph - disabled to prevent format string attacks in WAD files - {&s_QSPROMPT,"QSPROMPT"}, - {&s_QLPROMPT,"QLPROMPT"},*/ - {&s_NEWGAME,"NEWGAME"}, - {&s_RESTARTLEVEL,"RESTARTLEVEL"}, - {&s_NIGHTMARE,"NIGHTMARE"}, - {&s_SWSTRING,"SWSTRING"}, - {&s_MSGOFF,"MSGOFF"}, - {&s_MSGON,"MSGON"}, - {&s_NETEND,"NETEND"}, - {&s_ENDGAME,"ENDGAME"}, - {&s_DOSY,"DOSY"}, - {&s_DETAILHI,"DETAILHI"}, - {&s_DETAILLO,"DETAILLO"}, - {&s_GAMMALVL0,"GAMMALVL0"}, - {&s_GAMMALVL1,"GAMMALVL1"}, - {&s_GAMMALVL2,"GAMMALVL2"}, - {&s_GAMMALVL3,"GAMMALVL3"}, - {&s_GAMMALVL4,"GAMMALVL4"}, - {&s_EMPTYSTRING,"EMPTYSTRING"}, - {&s_GOTARMOR,"GOTARMOR"}, - {&s_GOTMEGA,"GOTMEGA"}, - {&s_GOTHTHBONUS,"GOTHTHBONUS"}, - {&s_GOTARMBONUS,"GOTARMBONUS"}, - {&s_GOTSTIM,"GOTSTIM"}, - {&s_GOTMEDINEED,"GOTMEDINEED"}, - {&s_GOTMEDIKIT,"GOTMEDIKIT"}, - {&s_GOTSUPER,"GOTSUPER"}, - {&s_GOTBLUECARD,"GOTBLUECARD"}, - {&s_GOTYELWCARD,"GOTYELWCARD"}, - {&s_GOTREDCARD,"GOTREDCARD"}, - {&s_GOTBLUESKUL,"GOTBLUESKUL"}, - {&s_GOTYELWSKUL,"GOTYELWSKUL"}, - {&s_GOTREDSKULL,"GOTREDSKULL"}, - {&s_GOTINVUL,"GOTINVUL"}, - {&s_GOTBERSERK,"GOTBERSERK"}, - {&s_GOTINVIS,"GOTINVIS"}, - {&s_GOTSUIT,"GOTSUIT"}, - {&s_GOTMAP,"GOTMAP"}, - {&s_GOTVISOR,"GOTVISOR"}, - {&s_GOTMSPHERE,"GOTMSPHERE"}, - {&s_GOTCLIP,"GOTCLIP"}, - {&s_GOTCLIPBOX,"GOTCLIPBOX"}, - {&s_GOTROCKET,"GOTROCKET"}, - {&s_GOTROCKBOX,"GOTROCKBOX"}, - {&s_GOTCELL,"GOTCELL"}, - {&s_GOTCELLBOX,"GOTCELLBOX"}, - {&s_GOTSHELLS,"GOTSHELLS"}, - {&s_GOTSHELLBOX,"GOTSHELLBOX"}, - {&s_GOTBACKPACK,"GOTBACKPACK"}, - {&s_GOTBFG9000,"GOTBFG9000"}, - {&s_GOTCHAINGUN,"GOTCHAINGUN"}, - {&s_GOTCHAINSAW,"GOTCHAINSAW"}, - {&s_GOTLAUNCHER,"GOTLAUNCHER"}, - {&s_GOTPLASMA,"GOTPLASMA"}, - {&s_GOTSHOTGUN,"GOTSHOTGUN"}, - {&s_GOTSHOTGUN2,"GOTSHOTGUN2"}, - {&s_PD_BLUEO,"PD_BLUEO"}, - {&s_PD_REDO,"PD_REDO"}, - {&s_PD_YELLOWO,"PD_YELLOWO"}, - {&s_PD_BLUEK,"PD_BLUEK"}, - {&s_PD_REDK,"PD_REDK"}, - {&s_PD_YELLOWK,"PD_YELLOWK"}, - {&s_PD_BLUEC,"PD_BLUEC"}, - {&s_PD_REDC,"PD_REDC"}, - {&s_PD_YELLOWC,"PD_YELLOWC"}, - {&s_PD_BLUES,"PD_BLUES"}, - {&s_PD_REDS,"PD_REDS"}, - {&s_PD_YELLOWS,"PD_YELLOWS"}, - {&s_PD_ANY,"PD_ANY"}, - {&s_PD_ALL3,"PD_ALL3"}, - {&s_PD_ALL6,"PD_ALL6"}, - {&s_GGSAVED,"GGSAVED"}, - {&s_HUSTR_MSGU,"HUSTR_MSGU"}, - {&s_HUSTR_E1M1,"HUSTR_E1M1"}, - {&s_HUSTR_E1M2,"HUSTR_E1M2"}, - {&s_HUSTR_E1M3,"HUSTR_E1M3"}, - {&s_HUSTR_E1M4,"HUSTR_E1M4"}, - {&s_HUSTR_E1M5,"HUSTR_E1M5"}, - {&s_HUSTR_E1M6,"HUSTR_E1M6"}, - {&s_HUSTR_E1M7,"HUSTR_E1M7"}, - {&s_HUSTR_E1M8,"HUSTR_E1M8"}, - {&s_HUSTR_E1M9,"HUSTR_E1M9"}, - {&s_HUSTR_E2M1,"HUSTR_E2M1"}, - {&s_HUSTR_E2M2,"HUSTR_E2M2"}, - {&s_HUSTR_E2M3,"HUSTR_E2M3"}, - {&s_HUSTR_E2M4,"HUSTR_E2M4"}, - {&s_HUSTR_E2M5,"HUSTR_E2M5"}, - {&s_HUSTR_E2M6,"HUSTR_E2M6"}, - {&s_HUSTR_E2M7,"HUSTR_E2M7"}, - {&s_HUSTR_E2M8,"HUSTR_E2M8"}, - {&s_HUSTR_E2M9,"HUSTR_E2M9"}, - {&s_HUSTR_E3M1,"HUSTR_E3M1"}, - {&s_HUSTR_E3M2,"HUSTR_E3M2"}, - {&s_HUSTR_E3M3,"HUSTR_E3M3"}, - {&s_HUSTR_E3M4,"HUSTR_E3M4"}, - {&s_HUSTR_E3M5,"HUSTR_E3M5"}, - {&s_HUSTR_E3M6,"HUSTR_E3M6"}, - {&s_HUSTR_E3M7,"HUSTR_E3M7"}, - {&s_HUSTR_E3M8,"HUSTR_E3M8"}, - {&s_HUSTR_E3M9,"HUSTR_E3M9"}, - {&s_HUSTR_E4M1,"HUSTR_E4M1"}, - {&s_HUSTR_E4M2,"HUSTR_E4M2"}, - {&s_HUSTR_E4M3,"HUSTR_E4M3"}, - {&s_HUSTR_E4M4,"HUSTR_E4M4"}, - {&s_HUSTR_E4M5,"HUSTR_E4M5"}, - {&s_HUSTR_E4M6,"HUSTR_E4M6"}, - {&s_HUSTR_E4M7,"HUSTR_E4M7"}, - {&s_HUSTR_E4M8,"HUSTR_E4M8"}, - {&s_HUSTR_E4M9,"HUSTR_E4M9"}, - {&s_HUSTR_1,"HUSTR_1"}, - {&s_HUSTR_2,"HUSTR_2"}, - {&s_HUSTR_3,"HUSTR_3"}, - {&s_HUSTR_4,"HUSTR_4"}, - {&s_HUSTR_5,"HUSTR_5"}, - {&s_HUSTR_6,"HUSTR_6"}, - {&s_HUSTR_7,"HUSTR_7"}, - {&s_HUSTR_8,"HUSTR_8"}, - {&s_HUSTR_9,"HUSTR_9"}, - {&s_HUSTR_10,"HUSTR_10"}, - {&s_HUSTR_11,"HUSTR_11"}, - {&s_HUSTR_12,"HUSTR_12"}, - {&s_HUSTR_13,"HUSTR_13"}, - {&s_HUSTR_14,"HUSTR_14"}, - {&s_HUSTR_15,"HUSTR_15"}, - {&s_HUSTR_16,"HUSTR_16"}, - {&s_HUSTR_17,"HUSTR_17"}, - {&s_HUSTR_18,"HUSTR_18"}, - {&s_HUSTR_19,"HUSTR_19"}, - {&s_HUSTR_20,"HUSTR_20"}, - {&s_HUSTR_21,"HUSTR_21"}, - {&s_HUSTR_22,"HUSTR_22"}, - {&s_HUSTR_23,"HUSTR_23"}, - {&s_HUSTR_24,"HUSTR_24"}, - {&s_HUSTR_25,"HUSTR_25"}, - {&s_HUSTR_26,"HUSTR_26"}, - {&s_HUSTR_27,"HUSTR_27"}, - {&s_HUSTR_28,"HUSTR_28"}, - {&s_HUSTR_29,"HUSTR_29"}, - {&s_HUSTR_30,"HUSTR_30"}, - {&s_HUSTR_31,"HUSTR_31"}, - {&s_HUSTR_32,"HUSTR_32"}, - {&s_PHUSTR_1,"PHUSTR_1"}, - {&s_PHUSTR_2,"PHUSTR_2"}, - {&s_PHUSTR_3,"PHUSTR_3"}, - {&s_PHUSTR_4,"PHUSTR_4"}, - {&s_PHUSTR_5,"PHUSTR_5"}, - {&s_PHUSTR_6,"PHUSTR_6"}, - {&s_PHUSTR_7,"PHUSTR_7"}, - {&s_PHUSTR_8,"PHUSTR_8"}, - {&s_PHUSTR_9,"PHUSTR_9"}, - {&s_PHUSTR_10,"PHUSTR_10"}, - {&s_PHUSTR_11,"PHUSTR_11"}, - {&s_PHUSTR_12,"PHUSTR_12"}, - {&s_PHUSTR_13,"PHUSTR_13"}, - {&s_PHUSTR_14,"PHUSTR_14"}, - {&s_PHUSTR_15,"PHUSTR_15"}, - {&s_PHUSTR_16,"PHUSTR_16"}, - {&s_PHUSTR_17,"PHUSTR_17"}, - {&s_PHUSTR_18,"PHUSTR_18"}, - {&s_PHUSTR_19,"PHUSTR_19"}, - {&s_PHUSTR_20,"PHUSTR_20"}, - {&s_PHUSTR_21,"PHUSTR_21"}, - {&s_PHUSTR_22,"PHUSTR_22"}, - {&s_PHUSTR_23,"PHUSTR_23"}, - {&s_PHUSTR_24,"PHUSTR_24"}, - {&s_PHUSTR_25,"PHUSTR_25"}, - {&s_PHUSTR_26,"PHUSTR_26"}, - {&s_PHUSTR_27,"PHUSTR_27"}, - {&s_PHUSTR_28,"PHUSTR_28"}, - {&s_PHUSTR_29,"PHUSTR_29"}, - {&s_PHUSTR_30,"PHUSTR_30"}, - {&s_PHUSTR_31,"PHUSTR_31"}, - {&s_PHUSTR_32,"PHUSTR_32"}, - {&s_THUSTR_1,"THUSTR_1"}, - {&s_THUSTR_2,"THUSTR_2"}, - {&s_THUSTR_3,"THUSTR_3"}, - {&s_THUSTR_4,"THUSTR_4"}, - {&s_THUSTR_5,"THUSTR_5"}, - {&s_THUSTR_6,"THUSTR_6"}, - {&s_THUSTR_7,"THUSTR_7"}, - {&s_THUSTR_8,"THUSTR_8"}, - {&s_THUSTR_9,"THUSTR_9"}, - {&s_THUSTR_10,"THUSTR_10"}, - {&s_THUSTR_11,"THUSTR_11"}, - {&s_THUSTR_12,"THUSTR_12"}, - {&s_THUSTR_13,"THUSTR_13"}, - {&s_THUSTR_14,"THUSTR_14"}, - {&s_THUSTR_15,"THUSTR_15"}, - {&s_THUSTR_16,"THUSTR_16"}, - {&s_THUSTR_17,"THUSTR_17"}, - {&s_THUSTR_18,"THUSTR_18"}, - {&s_THUSTR_19,"THUSTR_19"}, - {&s_THUSTR_20,"THUSTR_20"}, - {&s_THUSTR_21,"THUSTR_21"}, - {&s_THUSTR_22,"THUSTR_22"}, - {&s_THUSTR_23,"THUSTR_23"}, - {&s_THUSTR_24,"THUSTR_24"}, - {&s_THUSTR_25,"THUSTR_25"}, - {&s_THUSTR_26,"THUSTR_26"}, - {&s_THUSTR_27,"THUSTR_27"}, - {&s_THUSTR_28,"THUSTR_28"}, - {&s_THUSTR_29,"THUSTR_29"}, - {&s_THUSTR_30,"THUSTR_30"}, - {&s_THUSTR_31,"THUSTR_31"}, - {&s_THUSTR_32,"THUSTR_32"}, - {&s_HUSTR_CHATMACRO1,"HUSTR_CHATMACRO1"}, - {&s_HUSTR_CHATMACRO2,"HUSTR_CHATMACRO2"}, - {&s_HUSTR_CHATMACRO3,"HUSTR_CHATMACRO3"}, - {&s_HUSTR_CHATMACRO4,"HUSTR_CHATMACRO4"}, - {&s_HUSTR_CHATMACRO5,"HUSTR_CHATMACRO5"}, - {&s_HUSTR_CHATMACRO6,"HUSTR_CHATMACRO6"}, - {&s_HUSTR_CHATMACRO7,"HUSTR_CHATMACRO7"}, - {&s_HUSTR_CHATMACRO8,"HUSTR_CHATMACRO8"}, - {&s_HUSTR_CHATMACRO9,"HUSTR_CHATMACRO9"}, - {&s_HUSTR_CHATMACRO0,"HUSTR_CHATMACRO0"}, - {&s_HUSTR_TALKTOSELF1,"HUSTR_TALKTOSELF1"}, - {&s_HUSTR_TALKTOSELF2,"HUSTR_TALKTOSELF2"}, - {&s_HUSTR_TALKTOSELF3,"HUSTR_TALKTOSELF3"}, - {&s_HUSTR_TALKTOSELF4,"HUSTR_TALKTOSELF4"}, - {&s_HUSTR_TALKTOSELF5,"HUSTR_TALKTOSELF5"}, - {&s_HUSTR_MESSAGESENT,"HUSTR_MESSAGESENT"}, - {&s_HUSTR_PLRGREEN,"HUSTR_PLRGREEN"}, - {&s_HUSTR_PLRINDIGO,"HUSTR_PLRINDIGO"}, - {&s_HUSTR_PLRBROWN,"HUSTR_PLRBROWN"}, - {&s_HUSTR_PLRRED,"HUSTR_PLRRED"}, - //{c_HUSTR_KEYGREEN,"HUSTR_KEYGREEN"}, - //{c_HUSTR_KEYINDIGO,"HUSTR_KEYINDIGO"}, - //{c_HUSTR_KEYBROWN,"HUSTR_KEYBROWN"}, - //{c_HUSTR_KEYRED,"HUSTR_KEYRED"}, - {&s_AMSTR_FOLLOWON,"AMSTR_FOLLOWON"}, - {&s_AMSTR_FOLLOWOFF,"AMSTR_FOLLOWOFF"}, - {&s_AMSTR_GRIDON,"AMSTR_GRIDON"}, - {&s_AMSTR_GRIDOFF,"AMSTR_GRIDOFF"}, - {&s_AMSTR_MARKEDSPOT,"AMSTR_MARKEDSPOT"}, - {&s_AMSTR_MARKSCLEARED,"AMSTR_MARKSCLEARED"}, - {&s_STSTR_MUS,"STSTR_MUS"}, - {&s_STSTR_NOMUS,"STSTR_NOMUS"}, - {&s_STSTR_DQDON,"STSTR_DQDON"}, - {&s_STSTR_DQDOFF,"STSTR_DQDOFF"}, - {&s_STSTR_KFAADDED,"STSTR_KFAADDED"}, - {&s_STSTR_FAADDED,"STSTR_FAADDED"}, - {&s_STSTR_NCON,"STSTR_NCON"}, - {&s_STSTR_NCOFF,"STSTR_NCOFF"}, - {&s_STSTR_BEHOLD,"STSTR_BEHOLD"}, - {&s_STSTR_BEHOLDX,"STSTR_BEHOLDX"}, - {&s_STSTR_CHOPPERS,"STSTR_CHOPPERS"}, - {&s_STSTR_CLEV,"STSTR_CLEV"}, - {&s_STSTR_COMPON,"STSTR_COMPON"}, - {&s_STSTR_COMPOFF,"STSTR_COMPOFF"}, - {&s_E1TEXT,"E1TEXT"}, - {&s_E2TEXT,"E2TEXT"}, - {&s_E3TEXT,"E3TEXT"}, - {&s_E4TEXT,"E4TEXT"}, - {&s_C1TEXT,"C1TEXT"}, - {&s_C2TEXT,"C2TEXT"}, - {&s_C3TEXT,"C3TEXT"}, - {&s_C4TEXT,"C4TEXT"}, - {&s_C5TEXT,"C5TEXT"}, - {&s_C6TEXT,"C6TEXT"}, - {&s_P1TEXT,"P1TEXT"}, - {&s_P2TEXT,"P2TEXT"}, - {&s_P3TEXT,"P3TEXT"}, - {&s_P4TEXT,"P4TEXT"}, - {&s_P5TEXT,"P5TEXT"}, - {&s_P6TEXT,"P6TEXT"}, - {&s_T1TEXT,"T1TEXT"}, - {&s_T2TEXT,"T2TEXT"}, - {&s_T3TEXT,"T3TEXT"}, - {&s_T4TEXT,"T4TEXT"}, - {&s_T5TEXT,"T5TEXT"}, - {&s_T6TEXT,"T6TEXT"}, - {&s_CC_ZOMBIE,"CC_ZOMBIE"}, - {&s_CC_SHOTGUN,"CC_SHOTGUN"}, - {&s_CC_HEAVY,"CC_HEAVY"}, - {&s_CC_IMP,"CC_IMP"}, - {&s_CC_DEMON,"CC_DEMON"}, - {&s_CC_LOST,"CC_LOST"}, - {&s_CC_CACO,"CC_CACO"}, - {&s_CC_HELL,"CC_HELL"}, - {&s_CC_BARON,"CC_BARON"}, - {&s_CC_ARACH,"CC_ARACH"}, - {&s_CC_PAIN,"CC_PAIN"}, - {&s_CC_REVEN,"CC_REVEN"}, - {&s_CC_MANCU,"CC_MANCU"}, - {&s_CC_ARCH,"CC_ARCH"}, - {&s_CC_SPIDER,"CC_SPIDER"}, - {&s_CC_CYBER,"CC_CYBER"}, - {&s_CC_HERO,"CC_HERO"}, - {&bgflatE1,"BGFLATE1"}, - {&bgflatE2,"BGFLATE2"}, - {&bgflatE3,"BGFLATE3"}, - {&bgflatE4,"BGFLATE4"}, - {&bgflat06,"BGFLAT06"}, - {&bgflat11,"BGFLAT11"}, - {&bgflat20,"BGFLAT20"}, - {&bgflat30,"BGFLAT30"}, - {&bgflat15,"BGFLAT15"}, - {&bgflat31,"BGFLAT31"}, - {&bgcastcall,"BGCASTCALL"}, - // Ty 04/08/98 - added 5 general purpose startup announcement - // strings for hacker use. See m_menu.c - {&startup1,"STARTUP1"}, - {&startup2,"STARTUP2"}, - {&startup3,"STARTUP3"}, - {&startup4,"STARTUP4"}, - {&startup5,"STARTUP5"}, -}; - -static int deh_numstrlookup = sizeof(deh_strlookup)/sizeof(deh_strlookup[0]); - -// Function prototypes -static void lfstrip(char *); // strip the \r and/or \n off of a line -static void rstrip(char *); // strip trailing whitespace -static char * ptr_lstrip(char *); // point past leading whitespace -static boolean deh_GetData(char *, char *, uint_64_t *, char **, FILE *); -static boolean deh_procStringSub(char *, char *, char *, FILE *); -static char * dehReformatStr(char *); - -// Prototypes for block processing functions -// Pointers to these functions are used as the blocks are encountered. - -static void deh_procThing(DEHFILE *fpin, FILE* fpout, char *line); -static void deh_procFrame(DEHFILE *, FILE*, char *); -static void deh_procPointer(DEHFILE *, FILE*, char *); -static void deh_procSounds(DEHFILE *, FILE*, char *); -static void deh_procAmmo(DEHFILE *, FILE*, char *); -static void deh_procWeapon(DEHFILE *, FILE*, char *); -static void deh_procSprite(DEHFILE *, FILE*, char *); -static void deh_procCheat(DEHFILE *, FILE*, char *); -static void deh_procMisc(DEHFILE *, FILE*, char *); -static void deh_procText(DEHFILE *, FILE*, char *); -static void deh_procPars(DEHFILE *, FILE*, char *); -static void deh_procStrings(DEHFILE *, FILE*, char *); -static void deh_procError(DEHFILE *, FILE*, char *); -static void deh_procBexCodePointers(DEHFILE *, FILE*, char *); -static void deh_procHelperThing(DEHFILE *, FILE *, char *); // haleyjd 9/22/99 -// haleyjd: handlers to fully deprecate the DeHackEd text section -static void deh_procBexSounds(DEHFILE *, FILE *, char *); -static void deh_procBexMusic(DEHFILE *, FILE *, char *); -static void deh_procBexSprites(DEHFILE *, FILE *, char *); - -// Structure deh_block is used to hold the block names that can -// be encountered, and the routines to use to decipher them - -typedef struct -{ - const char *key; // a mnemonic block code name // CPhipps - const* - void (*const fptr)(DEHFILE *, FILE*, char *); // handler -} deh_block; - -#define DEH_BUFFERMAX 1024 // input buffer area size, hardcodedfor now -// killough 8/9/98: make DEH_BLOCKMAX self-adjusting -#define DEH_BLOCKMAX (sizeof deh_blocks/sizeof*deh_blocks) // size of array -#define DEH_MAXKEYLEN 32 // as much of any key as we'll look at -#define DEH_MOBJINFOMAX 24 // number of ints in the mobjinfo_t structure (!) - -// Put all the block header values, and the function to be called when that -// one is encountered, in this array: -static const deh_block deh_blocks[] = { // CPhipps - static const - /* 0 */ {"Thing",deh_procThing}, - /* 1 */ {"Frame",deh_procFrame}, - /* 2 */ {"Pointer",deh_procPointer}, - /* 3 */ {"Sound",deh_procSounds}, // Ty 03/16/98 corrected from "Sounds" - /* 4 */ {"Ammo",deh_procAmmo}, - /* 5 */ {"Weapon",deh_procWeapon}, - /* 6 */ {"Sprite",deh_procSprite}, - /* 7 */ {"Cheat",deh_procCheat}, - /* 8 */ {"Misc",deh_procMisc}, - /* 9 */ {"Text",deh_procText}, // -- end of standard "deh" entries, - - // begin BOOM Extensions (BEX) - - /* 10 */ {"[STRINGS]",deh_procStrings}, // new string changes - /* 11 */ {"[PARS]",deh_procPars}, // alternative block marker - /* 12 */ {"[CODEPTR]",deh_procBexCodePointers}, // bex codepointers by mnemonic - /* 13 */ {"[HELPER]", deh_procHelperThing}, // helper thing substitution haleyjd 9/22/99 - /* 14 */ {"[SPRITES]", deh_procBexSprites}, // bex style sprites - /* 15 */ {"[SOUNDS]", deh_procBexSounds}, // bex style sounds - /* 16 */ {"[MUSIC]", deh_procBexMusic}, // bex style music - /* 17 */ {"", deh_procError} // dummy to handle anything else -}; - -// flag to skip included deh-style text, used with INCLUDE NOTEXT directive -static boolean includenotext = false; - -static boolean deh_initialized = false; - -// MOBJINFO - Dehacked block name = "Thing" -// Usage: Thing nn (name) -// These are for mobjinfo_t types. Each is an integer -// within the structure, so we can use index of the string in this -// array to offset by sizeof(int) into the mobjinfo_t array at [nn] -// * things are base zero but dehacked considers them to start at #1. *** -// CPhipps - static const - -static const char *deh_mobjinfo[DEH_MOBJINFOMAX] = -{ - "ID #", // .doomednum - "Initial frame", // .spawnstate - "Hit points", // .spawnhealth - "First moving frame", // .seestate - "Alert sound", // .seesound - "Reaction time", // .reactiontime - "Attack sound", // .attacksound - "Injury frame", // .painstate - "Pain chance", // .painchance - "Pain sound", // .painsound - "Close attack frame", // .meleestate - "Far attack frame", // .missilestate - "Death frame", // .deathstate - "Exploding frame", // .xdeathstate - "Death sound", // .deathsound - "Speed", // .speed - "Width", // .radius - "Height", // .height - "Mass", // .mass - "Missile damage", // .damage - "Action sound", // .activesound - "Bits", // .flags - "Bits2", // .flags - "Respawn frame" // .raisestate -}; - -// Strings that are used to indicate flags ("Bits" in mobjinfo) -// This is an array of bit masks that are related to p_mobj.h -// values, using the smae names without the MF_ in front. -// Ty 08/27/98 new code -// -// killough 10/98: -// -// Convert array to struct to allow multiple values, make array size variable - -#define DEH_MOBJFLAGMAX (sizeof deh_mobjflags/sizeof*deh_mobjflags) - -struct deh_mobjflags_s { - const char *name; // CPhipps - const* - uint_64_t value; -}; - -// CPhipps - static const -static const struct deh_mobjflags_s deh_mobjflags[] = { - {"SPECIAL", MF_SPECIAL}, // call P_Specialthing when touched - {"SOLID", MF_SOLID}, // block movement - {"SHOOTABLE", MF_SHOOTABLE}, // can be hit - {"NOSECTOR", MF_NOSECTOR}, // invisible but touchable - {"NOBLOCKMAP", MF_NOBLOCKMAP}, // inert but displayable - {"AMBUSH", MF_AMBUSH}, // deaf monster - {"JUSTHIT", MF_JUSTHIT}, // will try to attack right back - {"JUSTATTACKED", MF_JUSTATTACKED}, // take at least 1 step before attacking - {"SPAWNCEILING", MF_SPAWNCEILING}, // initially hang from ceiling - {"NOGRAVITY", MF_NOGRAVITY}, // don't apply gravity during play - {"DROPOFF", MF_DROPOFF}, // can jump from high places - {"PICKUP", MF_PICKUP}, // will pick up items - {"NOCLIP", MF_NOCLIP}, // goes through walls - {"SLIDE", MF_SLIDE}, // keep info about sliding along walls - {"FLOAT", MF_FLOAT}, // allow movement to any height - {"TELEPORT", MF_TELEPORT}, // don't cross lines or look at heights - {"MISSILE", MF_MISSILE}, // don't hit same species, explode on block - {"DROPPED", MF_DROPPED}, // dropped, not spawned (like ammo clip) - {"SHADOW", MF_SHADOW}, // use fuzzy draw like spectres - {"NOBLOOD", MF_NOBLOOD}, // puffs instead of blood when shot - {"CORPSE", MF_CORPSE}, // so it will slide down steps when dead - {"INFLOAT", MF_INFLOAT}, // float but not to target height - {"COUNTKILL", MF_COUNTKILL}, // count toward the kills total - {"COUNTITEM", MF_COUNTITEM}, // count toward the items total - {"SKULLFLY", MF_SKULLFLY}, // special handling for flying skulls - {"NOTDMATCH", MF_NOTDMATCH}, // do not spawn in deathmatch - - // killough 10/98: TRANSLATION consists of 2 bits, not 1: - - {"TRANSLATION", MF_TRANSLATION1}, // for Boom bug-compatibility - {"TRANSLATION1", MF_TRANSLATION1}, // use translation table for color (players) - {"TRANSLATION2", MF_TRANSLATION2}, // use translation table for color (players) - {"UNUSED1", MF_TRANSLATION2}, // unused bit # 1 -- For Boom bug-compatibility - {"UNUSED2", MF_UNUSED2}, // unused bit # 2 -- For Boom compatibility - {"UNUSED3", MF_UNUSED3}, // unused bit # 3 -- For Boom compatibility - {"UNUSED4", MF_TRANSLUCENT}, // unused bit # 4 -- For Boom compatibility - {"TRANSLUCENT", MF_TRANSLUCENT}, // apply translucency to sprite (BOOM) - {"TOUCHY", MF_TOUCHY}, // dies on contact with solid objects (MBF) - {"BOUNCES", MF_BOUNCES}, // bounces off floors, ceilings and maybe walls (MBF) - {"FRIEND", MF_FRIEND}, // a friend of the player(s) (MBF) -}; - -// STATE - Dehacked block name = "Frame" and "Pointer" -// Usage: Frame nn -// Usage: Pointer nn (Frame nn) -// These are indexed separately, for lookup to the actual -// function pointers. Here we'll take whatever Dehacked gives -// us and go from there. The (Frame nn) after the pointer is the -// real place to put this value. The "Pointer" value is an xref -// that Dehacked uses and is useless to us. -// * states are base zero and have a dummy #0 (TROO) - -static const char *deh_state[] = // CPhipps - static const* -{ - "Sprite number", // .sprite (spritenum_t) // an enum - "Sprite subnumber", // .frame (long) - "Duration", // .tics (long) - "Next frame", // .nextstate (statenum_t) - // This is set in a separate "Pointer" block from Dehacked - "Codep Frame", // pointer to first use of action (actionf_t) - "Unknown 1", // .misc1 (long) - "Unknown 2" // .misc2 (long) -}; - -// SFXINFO_STRUCT - Dehacked block name = "Sounds" -// Sound effects, typically not changed (redirected, and new sfx put -// into the pwad, but not changed here. Can you tell that Gregdidn't -// know what they were for, mostly? Can you tell that I don't either? -// Mostly I just put these into the same slots as they are in the struct. -// This may not be supported in our -deh option if it doesn't make sense by then. - -// * sounds are base zero but have a dummy #0 - -static const char *deh_sfxinfo[] = // CPhipps - static const* -{ - "Offset", // pointer to a name string, changed in text - "Zero/One", // .singularity (int, one at a time flag) - "Value", // .priority - "Zero 1", // .link (sfxinfo_t*) referenced sound if linked - "Zero 2", // .pitch - "Zero 3", // .volume - "Zero 4", // .data (SAMPLE*) sound data - "Neg. One 1", // .usefulness - "Neg. One 2" // .lumpnum -}; - -// MUSICINFO is not supported in Dehacked. Ignored here. -// * music entries are base zero but have a dummy #0 - -// SPRITE - Dehacked block name = "Sprite" -// Usage = Sprite nn -// Sprite redirection by offset into the text area - unsupported by BOOM -// * sprites are base zero and dehacked uses it that way. - -// static const char *deh_sprite[] = // CPhipps - static const* -// { -// "Offset" // supposed to be the offset into the text section -// }; - -// AMMO - Dehacked block name = "Ammo" -// usage = Ammo n (name) -// Ammo information for the few types of ammo - -static const char *deh_ammo[] = // CPhipps - static const* -{ - "Max ammo", // maxammo[] - "Per ammo" // clipammo[] -}; - -// WEAPONS - Dehacked block name = "Weapon" -// Usage: Weapon nn (name) -// Basically a list of frames and what kind of ammo (see above)it uses. - -static const char *deh_weapon[] = // CPhipps - static const* -{ - "Ammo type", // .ammo - "Deselect frame", // .upstate - "Select frame", // .downstate - "Bobbing frame", // .readystate - "Shooting frame", // .atkstate - "Firing frame" // .flashstate -}; - -// CHEATS - Dehacked block name = "Cheat" -// Usage: Cheat 0 -// Always uses a zero in the dehacked file, for consistency. No meaning. -// These are just plain funky terms compared with id's -// -// killough 4/18/98: integrated into main cheat table now (see st_stuff.c) - -// MISC - Dehacked block name = "Misc" -// Usage: Misc 0 -// Always uses a zero in the dehacked file, for consistency. No meaning. - -static const char *deh_misc[] = // CPhipps - static const* -{ - "Initial Health", // initial_health - "Initial Bullets", // initial_bullets - "Max Health", // maxhealth - "Max Armor", // max_armor - "Green Armor Class", // green_armor_class - "Blue Armor Class", // blue_armor_class - "Max Soulsphere", // max_soul - "Soulsphere Health", // soul_health - "Megasphere Health", // mega_health - "God Mode Health", // god_health - "IDFA Armor", // idfa_armor - "IDFA Armor Class", // idfa_armor_class - "IDKFA Armor", // idkfa_armor - "IDKFA Armor Class", // idkfa_armor_class - "BFG Cells/Shot", // BFGCELLS - "Monsters Infight" // Unknown--not a specific number it seems, but - // the logic has to be here somewhere or - // it'd happen always -}; - -// TEXT - Dehacked block name = "Text" -// Usage: Text fromlen tolen -// Dehacked allows a bit of adjustment to the length (why?) - -// BEX extension [CODEPTR] -// Usage: Start block, then each line is: -// FRAME nnn = PointerMnemonic - -typedef struct { - actionf_t cptr; // actual pointer to the subroutine - const char *lookup; // mnemonic lookup string to be specified in BEX - // CPhipps - const* -} deh_bexptr; - -static const deh_bexptr deh_bexptrs[] = // CPhipps - static const -{ - {A_Light0, "A_Light0"}, - {A_WeaponReady, "A_WeaponReady"}, - {A_Lower, "A_Lower"}, - {A_Raise, "A_Raise"}, - {A_Punch, "A_Punch"}, - {A_ReFire, "A_ReFire"}, - {A_FirePistol, "A_FirePistol"}, - {A_Light1, "A_Light1"}, - {A_FireShotgun, "A_FireShotgun"}, - {A_Light2, "A_Light2"}, - {A_FireShotgun2, "A_FireShotgun2"}, - {A_CheckReload, "A_CheckReload"}, - {A_OpenShotgun2, "A_OpenShotgun2"}, - {A_LoadShotgun2, "A_LoadShotgun2"}, - {A_CloseShotgun2, "A_CloseShotgun2"}, - {A_FireCGun, "A_FireCGun"}, - {A_GunFlash, "A_GunFlash"}, - {A_FireMissile, "A_FireMissile"}, - {A_Saw, "A_Saw"}, - {A_FirePlasma, "A_FirePlasma"}, - {A_BFGsound, "A_BFGsound"}, - {A_FireBFG, "A_FireBFG"}, - {A_BFGSpray, "A_BFGSpray"}, - {A_Explode, "A_Explode"}, - {A_Pain, "A_Pain"}, - {A_PlayerScream, "A_PlayerScream"}, - {A_Fall, "A_Fall"}, - {A_XScream, "A_XScream"}, - {A_Look, "A_Look"}, - {A_Chase, "A_Chase"}, - {A_FaceTarget, "A_FaceTarget"}, - {A_PosAttack, "A_PosAttack"}, - {A_Scream, "A_Scream"}, - {A_SPosAttack, "A_SPosAttack"}, - {A_VileChase, "A_VileChase"}, - {A_VileStart, "A_VileStart"}, - {A_VileTarget, "A_VileTarget"}, - {A_VileAttack, "A_VileAttack"}, - {A_StartFire, "A_StartFire"}, - {A_Fire, "A_Fire"}, - {A_FireCrackle, "A_FireCrackle"}, - {A_Tracer, "A_Tracer"}, - {A_SkelWhoosh, "A_SkelWhoosh"}, - {A_SkelFist, "A_SkelFist"}, - {A_SkelMissile, "A_SkelMissile"}, - {A_FatRaise, "A_FatRaise"}, - {A_FatAttack1, "A_FatAttack1"}, - {A_FatAttack2, "A_FatAttack2"}, - {A_FatAttack3, "A_FatAttack3"}, - {A_BossDeath, "A_BossDeath"}, - {A_CPosAttack, "A_CPosAttack"}, - {A_CPosRefire, "A_CPosRefire"}, - {A_TroopAttack, "A_TroopAttack"}, - {A_SargAttack, "A_SargAttack"}, - {A_HeadAttack, "A_HeadAttack"}, - {A_BruisAttack, "A_BruisAttack"}, - {A_SkullAttack, "A_SkullAttack"}, - {A_Metal, "A_Metal"}, - {A_SpidRefire, "A_SpidRefire"}, - {A_BabyMetal, "A_BabyMetal"}, - {A_BspiAttack, "A_BspiAttack"}, - {A_Hoof, "A_Hoof"}, - {A_CyberAttack, "A_CyberAttack"}, - {A_PainAttack, "A_PainAttack"}, - {A_PainDie, "A_PainDie"}, - {A_KeenDie, "A_KeenDie"}, - {A_BrainPain, "A_BrainPain"}, - {A_BrainScream, "A_BrainScream"}, - {A_BrainDie, "A_BrainDie"}, - {A_BrainAwake, "A_BrainAwake"}, - {A_BrainSpit, "A_BrainSpit"}, - {A_SpawnSound, "A_SpawnSound"}, - {A_SpawnFly, "A_SpawnFly"}, - {A_BrainExplode, "A_BrainExplode"}, - {A_Detonate, "A_Detonate"}, // killough 8/9/98 - {A_Mushroom, "A_Mushroom"}, // killough 10/98 - {A_Die, "A_Die"}, // killough 11/98 - {A_Spawn, "A_Spawn"}, // killough 11/98 - {A_Turn, "A_Turn"}, // killough 11/98 - {A_Face, "A_Face"}, // killough 11/98 - {A_Scratch, "A_Scratch"}, // killough 11/98 - {A_PlaySound, "A_PlaySound"}, // killough 11/98 - {A_RandomJump, "A_RandomJump"}, // killough 11/98 - {A_LineEffect, "A_LineEffect"}, // killough 11/98 - - // This NULL entry must be the last in the list - {NULL, "A_NULL"}, // Ty 05/16/98 -}; - -// to hold startup code pointers from INFO.C -// CPhipps - static -static actionf_t *deh_codeptr; -static char **deh_spritenames; -static char **deh_musicnames; -static char **deh_soundnames; - -// ==================================================================== -// ProcessDehFile -// Purpose: Read and process a DEH or BEX file -// Args: filename -- name of the DEH/BEX file -// outfilename -- output file (DEHOUT.TXT), appended to here -// Returns: void -// -// killough 10/98: -// substantially modified to allow input from wad lumps instead of .deh files. - -void D_ProcessDehFile(const char *filename, const char *outfilename, int lumpnum) -{ - static FILE *fileout; // In case -dehout was used - DEHFILE infile, *filein = &infile; // killough 10/98 - char inbuffer[DEH_BUFFERMAX]; // Place to put the primary infostring - - // Initialize structures only if needed - if (!deh_initialized) - { - lprintf(LO_WARN, "D_ProcessDehFile: Initializing DEH engine...\n"); - - deh_codeptr = calloc(NUMSTATES + 1, sizeof(actionf_t)); - deh_spritenames = calloc(NUMSPRITES + 1, sizeof(char *)); - deh_musicnames = calloc(NUMMUSIC + 1, sizeof(char *)); - deh_soundnames = calloc(NUMSFX + 1, sizeof(char *)); - - // Keep a copy of the original values - for (int i = 0; i < NUMSTATES; i++) - deh_codeptr[i] = states[i].action; - for (int i = 0; i < NUMSPRITES; i++) - deh_spritenames[i] = sprnames[i]; - for(int i = 1; i < NUMMUSIC; i++) - deh_musicnames[i] = S_music[i].name; - for(int i = 1; i < NUMSFX; i++) - deh_soundnames[i] = S_sfx[i].name; - } - - // Open output file if we're writing output - if (outfilename && *outfilename && !fileout) - { - static boolean firstfile = true; // to allow append to output log - if (!strcmp(outfilename, "-")) - fileout = stdout; - else - if (!(fileout=fopen(outfilename, firstfile ? "wt" : "at"))) - { - lprintf(LO_WARN, "Could not open -dehout file %s\n... using stdout.\n", - outfilename); - fileout = stdout; - } - firstfile = false; - } - - // killough 10/98: allow DEH files to come from wad lumps - - if (filename) - { - if (!(infile.f = fopen(filename,"rt"))) - { - lprintf(LO_WARN, "-deh file %s not found\n",filename); - return; // should be checked up front anyway - } - infile.lump = NULL; - } - else // DEH file comes from lump indicated by third argument - { - infile.size = W_LumpLength(lumpnum); - infile.inp = infile.lump = W_CacheLumpNum(lumpnum); - filename = "(WAD)"; - } - - lprintf(LO_INFO, "Loading DEH file %s\n",filename); - lprintf(LO_INFO, "Lump number %d, address: %p\n",lumpnum, infile.lump); - if (fileout) fprintf(fileout,"\nLoading DEH file %s\n\n",filename); - - // loop until end of file - - while (dehfgets(inbuffer,sizeof(inbuffer),filein)) - { - unsigned i; - - lfstrip(inbuffer); - if (fileout) fprintf(fileout,"Line='%s'\n",inbuffer); - if (!*inbuffer || *inbuffer == '#' || *inbuffer == ' ') - continue; /* Blank line or comment line */ - - // -- If DEH_BLOCKMAX is set right, the processing is independently - // -- handled based on data in the deh_blocks[] structure array - - // killough 10/98: INCLUDE code rewritten to allow arbitrary nesting, - // and to greatly simplify code, fix memory leaks, other bugs - - if (!strncasecmp(inbuffer,"INCLUDE",7)) // include a file - { - // preserve state while including a file - // killough 10/98: moved to here - - char *nextfile; - boolean oldnotext = includenotext; // killough 10/98 - - // killough 10/98: exclude if inside wads (only to discourage - // the practice, since the code could otherwise handle it) - - if (infile.lump) - { - if (fileout) - fprintf(fileout, - "No files may be included from wads: %s\n",inbuffer); - continue; - } - - // check for no-text directive, used when including a DEH - // file but using the BEX format to handle strings - - if (!strncasecmp(nextfile = ptr_lstrip(inbuffer+7),"NOTEXT",6)) - includenotext = true, nextfile = ptr_lstrip(nextfile+6); - - if (fileout) - fprintf(fileout,"Branching to include file %s...\n", nextfile); - - // killough 10/98: - // Second argument must be NULL to prevent closing fileout too soon - - D_ProcessDehFile(nextfile,NULL,0); // do the included file - - includenotext = oldnotext; - if (fileout) fprintf(fileout,"...continuing with %s\n",filename); - continue; - } - - for (i=0; i= NUMSTATES) - { - if (fpout) fprintf(fpout,"Bad pointer number %d of %d\n", - indexnum, NUMSTATES); - return; // killough 10/98: fix SegViol - } - strcpy(key,"A_"); // reusing the key area to prefix the mnemonic - strcat(key,ptr_lstrip(mnemonic)); - - found = FALSE; - i= -1; // incremented to start at zero at the top of the loop - do // Ty 05/16/98 - fix loop logic to look for null ending entry - { - ++i; - if (!strcasecmp(key,deh_bexptrs[i].lookup)) - { // Ty 06/01/98 - add to states[].action for new djgcc version - states[indexnum].action = deh_bexptrs[i].cptr; // assign - if (fpout) fprintf(fpout, - " - applied %s from codeptr[%d] to states[%d]\n", - deh_bexptrs[i].lookup,i,indexnum); - found = TRUE; - } - } while (!found && (deh_bexptrs[i].cptr != NULL)); - - if (!found) - if (fpout) fprintf(fpout, - "Invalid frame pointer mnemonic '%s' at %d\n", - mnemonic, indexnum); - } - return; -} - -//--------------------------------------------------------------------------- -// To be on the safe, compatible side, we manually convert DEH bitflags -// to prboom types - POPE -//--------------------------------------------------------------------------- -static uint_64_t getConvertedDEHBits(uint_64_t bits) { - const uint_64_t bitMap[32] = { - /* cf linuxdoom-1.10 p_mobj.h */ - MF_SPECIAL, // 0 Can be picked up - When touched the thing can be picked up. - MF_SOLID, // 1 Obstacle - The thing is solid and will not let you (or others) pass through it - MF_SHOOTABLE, // 2 Shootable - Can be shot. - MF_NOSECTOR, // 3 Total Invisibility - Invisible, but can be touched - MF_NOBLOCKMAP, // 4 Don't use the blocklinks (inert but displayable) - MF_AMBUSH, // 5 Semi deaf - The thing is a deaf monster - MF_JUSTHIT, // 6 In pain - Will try to attack right back after being hit - MF_JUSTATTACKED, // 7 Steps before attack - Will take at least one step before attacking - MF_SPAWNCEILING, // 8 Hangs from ceiling - When the level starts, this thing will be at ceiling height. - MF_NOGRAVITY, // 9 No gravity - Gravity does not affect this thing - MF_DROPOFF, // 10 Travels over cliffs - Monsters normally do not walk off ledges/steps they could not walk up. With this set they can walk off any height of cliff. Usually only used for flying monsters. - MF_PICKUP, // 11 Pick up items - The thing can pick up gettable items. - MF_NOCLIP, // 12 No clipping - Thing can walk through walls. - MF_SLIDE, // 13 Slides along walls - Keep info about sliding along walls (don't really know much about this one). - MF_FLOAT, // 14 Floating - Thing can move to any height - MF_TELEPORT, // 15 Semi no clipping - Don't cross lines or look at teleport heights. (don't really know much about this one either). - MF_MISSILE, // 16 Projectiles - Behaves like a projectile, explodes when hitting something that blocks movement - MF_DROPPED, // 17 Disappearing weapon - Dropped, not spawned (like an ammo clip) I have not had much success in using this one. - MF_SHADOW, // 18 Partial invisibility - Drawn like a spectre. - MF_NOBLOOD, // 19 Puffs (vs. bleeds) - If hit will spawn bullet puffs instead of blood splats. - MF_CORPSE, // 20 Sliding helpless - Will slide down steps when dead. - MF_INFLOAT, // 21 No auto levelling - float but not to target height (?) - MF_COUNTKILL, // 22 Affects kill % - counted as a killable enemy and affects percentage kills on level summary. - MF_COUNTITEM, // 23 Affects item % - affects percentage items gathered on level summary. - MF_SKULLFLY, // 24 Running - special handling for flying skulls. - MF_NOTDMATCH, // 25 Not in deathmatch - do not spawn in deathmatch (like keys) - MF_TRANSLATION1, // 26 Color 1 (grey / red) - MF_TRANSLATION2, // 27 Color 2 (brown / red) - // Convert bit 28 to MF_TOUCHY, not (MF_TRANSLATION1|MF_TRANSLATION2) - // fixes bug #1576151 (part 1) - MF_TOUCHY, // 28 - explodes on contact (MBF) - MF_BOUNCES, // 29 - bounces off walls and floors (MBF) - MF_FRIEND, // 30 - friendly monster helps players (MBF) - MF_TRANSLUCENT // e6y: Translucency via dehacked/bex doesn't work without it - }; - int i; - uint_64_t shiftBits = bits; - uint_64_t convertedBits = 0; - for (i=0; i<32; i++) { - if (shiftBits & 0x1) convertedBits |= bitMap[i]; - shiftBits >>= 1; - } - return convertedBits; -} - -//--------------------------------------------------------------------------- -// See usage below for an explanation of this function's existence - POPE -//--------------------------------------------------------------------------- -static void setMobjInfoValue(int mobjInfoIndex, int keyIndex, uint_64_t value) { - mobjinfo_t *mi; - if (mobjInfoIndex >= NUMMOBJTYPES || mobjInfoIndex < 0) return; - mi = &mobjinfo[mobjInfoIndex]; - switch (keyIndex) { - case 0: mi->doomednum = (int)value; return; - case 1: mi->spawnstate = (int)value; return; - case 2: mi->spawnhealth = (int)value; return; - case 3: mi->seestate = (int)value; return; - case 4: mi->seesound = (int)value; return; - case 5: mi->reactiontime = (int)value; return; - case 6: mi->attacksound = (int)value; return; - case 7: mi->painstate = (int)value; return; - case 8: mi->painchance = (int)value; return; - case 9: mi->painsound = (int)value; return; - case 10: mi->meleestate = (int)value; return; - case 11: mi->missilestate = (int)value; return; - case 12: mi->deathstate = (int)value; return; - case 13: mi->xdeathstate = (int)value; return; - case 14: mi->deathsound = (int)value; return; - case 15: mi->speed = (int)value; return; - case 16: mi->radius = (int)value; return; - case 17: mi->height = (int)value; return; - case 18: mi->mass = (int)value; return; - case 19: mi->damage = (int)value; return; - case 20: mi->activesound = (int)value; return; - case 21: mi->flags = value; return; - case 22: return; // "Bits2", unused - case 23: mi->raisestate = (int)value; return; - default: return; - } -} - -// ==================================================================== -// deh_procThing -// Purpose: Handle DEH Thing block -// Args: fpin -- input file stream -// fpout -- output file stream (DEHOUT.TXT) -// line -- current line in file to process -// Returns: void -// -// Ty 8/27/98 - revised to also allow mnemonics for -// bit masks for monster attributes -// - -static void deh_procThing(DEHFILE *fpin, FILE* fpout, char *line) -{ - char key[DEH_MAXKEYLEN]; - char inbuffer[DEH_BUFFERMAX]; - uint_64_t value; // All deh values are ints or longs - int indexnum; - int ix; - char *strval; - - strncpy(inbuffer,line,DEH_BUFFERMAX - 1); - if (fpout) fprintf(fpout,"Thing line: '%s'\n",inbuffer); - - // killough 8/98: allow hex numbers in input: - ix = sscanf(inbuffer,"%s %i",key, &indexnum); - if (fpout) fprintf(fpout,"count=%d, Thing %d\n",ix, indexnum); - - // Note that the mobjinfo[] array is base zero, but object numbers - // in the dehacked file start with one. Grumble. - --indexnum; - - // now process the stuff - // Note that for Things we can look up the key and use its offset - // in the array of key strings as an int offset in the structure - - // get a line until a blank or end of file--it's not - // blank now because it has our incoming key in it - while (!dehfeof(fpin) && *inbuffer && (*inbuffer != ' ')) - { - // e6y: Correction of wrong processing of Bits parameter if its value is equal to zero - // No more desync on HACX demos. - int bGetData; - - if (!dehfgets(inbuffer, sizeof(inbuffer), fpin)) break; - lfstrip(inbuffer); // toss the end of line - - // killough 11/98: really bail out on blank lines (break != continue) - if (!*inbuffer) break; // bail out with blank line between sections - - // e6y: Correction of wrong processing of Bits parameter if its value is equal to zero - // No more desync on HACX demos. - bGetData = deh_GetData(inbuffer,key,&value,&strval,fpout); - if (!bGetData) - // Old code: if (!deh_GetData(inbuffer,key,&value,&strval,fpout)) // returns TRUE if ok - { - if (fpout) fprintf(fpout,"Bad data pair in '%s'\n",inbuffer); - continue; - } - for (ix=0; ix>32) & 0xffffffff, - (unsigned long)deh_mobjflags[iy].value & 0xffffffff, strval - ); - } - value |= deh_mobjflags[iy].value; - break; - } - if (iy >= DEH_MOBJFLAGMAX && fpout) { - fprintf(fpout, "Could not find bit mnemonic %s\n", strval); - } - } - - // Don't worry about conversion -- simply print values - if (fpout) { - fprintf(fpout, - "Bits = 0x%08lX%08lX\n", - (unsigned long)(value>>32) & 0xffffffff, - (unsigned long)value & 0xffffffff - ); - } - mobjinfo[indexnum].flags = value; // e6y - } - } - if (fpout) { - fprintf(fpout, - "Assigned 0x%08lx%08lx to %s(%d) at index %d\n", - (unsigned long)(value>>32) & 0xffffffff, - (unsigned long)value & 0xffffffff, key, indexnum, ix - ); - } - } - } - return; -} - -// ==================================================================== -// deh_procFrame -// Purpose: Handle DEH Frame block -// Args: fpin -- input file stream -// fpout -- output file stream (DEHOUT.TXT) -// line -- current line in file to process -// Returns: void -// -static void deh_procFrame(DEHFILE *fpin, FILE* fpout, char *line) -{ - char key[DEH_MAXKEYLEN]; - char inbuffer[DEH_BUFFERMAX]; - uint_64_t value; // All deh values are ints or longs - int indexnum; - - strncpy(inbuffer,line,DEH_BUFFERMAX - 1); - - // killough 8/98: allow hex numbers in input: - sscanf(inbuffer,"%s %i",key, &indexnum); - if (fpout) fprintf(fpout,"Processing Frame at index %d: %s\n",indexnum,key); - if (indexnum < 0 || indexnum >= NUMSTATES) - if (fpout) fprintf(fpout,"Bad frame number %d of %d\n",indexnum, NUMSTATES); - - while (!dehfeof(fpin) && *inbuffer && (*inbuffer != ' ')) - { - if (!dehfgets(inbuffer, sizeof(inbuffer), fpin)) break; - lfstrip(inbuffer); - if (!*inbuffer) break; // killough 11/98 - if (!deh_GetData(inbuffer,key,&value,NULL,fpout)) // returns TRUE if ok - { - if (fpout) fprintf(fpout,"Bad data pair in '%s'\n",inbuffer); - continue; - } - if (!strcasecmp(key,deh_state[0])) // Sprite number - { - if (fpout) fprintf(fpout," - sprite = %lld\n",value); - states[indexnum].sprite = (spritenum_t)value; - } - else - if (!strcasecmp(key,deh_state[1])) // Sprite subnumber - { - if (fpout) fprintf(fpout," - frame = %lld\n",value); - states[indexnum].frame = (long)value; // long - } - else - if (!strcasecmp(key,deh_state[2])) // Duration - { - if (fpout) fprintf(fpout," - tics = %lld\n",value); - states[indexnum].tics = (long)value; // long - } - else - if (!strcasecmp(key,deh_state[3])) // Next frame - { - if (fpout) fprintf(fpout," - nextstate = %lld\n",value); - states[indexnum].nextstate = (statenum_t)value; - } - else - if (!strcasecmp(key,deh_state[4])) // Codep frame (not set in Frame deh block) - { - if (fpout) fprintf(fpout," - codep, should not be set in Frame section!\n"); - /* nop */ ; - } - else - if (!strcasecmp(key,deh_state[5])) // Unknown 1 - { - if (fpout) fprintf(fpout," - misc1 = %lld\n",value); - states[indexnum].misc1 = (long)value; // long - } - else - if (!strcasecmp(key,deh_state[6])) // Unknown 2 - { - if (fpout) fprintf(fpout," - misc2 = %lld\n",value); - states[indexnum].misc2 = (long)value; // long - } - else - if (fpout) fprintf(fpout,"Invalid frame string index for '%s'\n",key); - } - return; -} - -// ==================================================================== -// deh_procPointer -// Purpose: Handle DEH Code pointer block, can use BEX [CODEPTR] instead -// Args: fpin -- input file stream -// fpout -- output file stream (DEHOUT.TXT) -// line -- current line in file to process -// Returns: void -// -static void deh_procPointer(DEHFILE *fpin, FILE* fpout, char *line) // done -{ - char key[DEH_MAXKEYLEN]; - char inbuffer[DEH_BUFFERMAX]; - uint_64_t value; // All deh values are ints or longs - int indexnum; - int i; // looper - - strncpy(inbuffer,line,DEH_BUFFERMAX - 1); - // NOTE: different format from normal - - // killough 8/98: allow hex numbers in input, fix error case: - if (sscanf(inbuffer,"%*s %*i (%s %i)",key, &indexnum) != 2) - { - if (fpout) fprintf(fpout,"Bad data pair in '%s'\n",inbuffer); - return; - } - - if (fpout) fprintf(fpout,"Processing Pointer at index %d: %s\n",indexnum, key); - if (indexnum < 0 || indexnum >= NUMSTATES) - { - if (fpout) - fprintf(fpout,"Bad pointer number %d of %d\n",indexnum, NUMSTATES); - return; - } - - while (!dehfeof(fpin) && *inbuffer && (*inbuffer != ' ')) - { - if (!dehfgets(inbuffer, sizeof(inbuffer), fpin)) break; - lfstrip(inbuffer); - if (!*inbuffer) break; // killough 11/98 - if (!deh_GetData(inbuffer,key,&value,NULL,fpout)) // returns TRUE if ok - { - if (fpout) fprintf(fpout,"Bad data pair in '%s'\n",inbuffer); - continue; - } - - if (value < 0 || value >= NUMSTATES) - { - if (fpout) - fprintf(fpout,"Bad pointer number %lld of %d\n",value, NUMSTATES); - return; - } - - if (!strcasecmp(key,deh_state[4])) // Codep frame (not set in Frame deh block) - { - states[indexnum].action = deh_codeptr[value]; - if (fpout) fprintf(fpout," - applied from codeptr[%lld] to states[%d]\n", - value,indexnum); - // Write BEX-oriented line to match: - // for (i=0;i FRAME %d = %s\n", - indexnum, &deh_bexptrs[i].lookup[2]); - break; - } - if (deh_bexptrs[i].cptr == NULL) // stop at null entry - break; - } - } - else - if (fpout) fprintf(fpout,"Invalid frame pointer index for '%s' at %lld\n", - key, value); - } - return; -} - -// ==================================================================== -// deh_procSounds -// Purpose: Handle DEH Sounds block -// Args: fpin -- input file stream -// fpout -- output file stream (DEHOUT.TXT) -// line -- current line in file to process -// Returns: void -// -static void deh_procSounds(DEHFILE *fpin, FILE* fpout, char *line) -{ - char key[DEH_MAXKEYLEN]; - char inbuffer[DEH_BUFFERMAX]; - uint_64_t value; // All deh values are ints or longs - int indexnum; - - strncpy(inbuffer,line,DEH_BUFFERMAX - 1); - - // killough 8/98: allow hex numbers in input: - sscanf(inbuffer,"%s %i",key, &indexnum); - if (fpout) fprintf(fpout,"Processing Sounds at index %d: %s\n", - indexnum, key); - if (indexnum < 0 || indexnum >= NUMSFX) - if (fpout) fprintf(fpout,"Bad sound number %d of %d\n", - indexnum, NUMSFX); - - while (!dehfeof(fpin) && *inbuffer && (*inbuffer != ' ')) - { - if (!dehfgets(inbuffer, sizeof(inbuffer), fpin)) break; - lfstrip(inbuffer); - if (!*inbuffer) break; // killough 11/98 - if (!deh_GetData(inbuffer,key,&value,NULL,fpout)) // returns TRUE if ok - { - if (fpout) fprintf(fpout,"Bad data pair in '%s'\n",inbuffer); - continue; - } - if (!strcasecmp(key,deh_sfxinfo[0])) // Offset - /* nop */ ; // we don't know what this is, I don't think - else - if (!strcasecmp(key,deh_sfxinfo[1])) // Zero/One - S_sfx[indexnum].singularity = (int)value; - else - if (!strcasecmp(key,deh_sfxinfo[2])) // Value - S_sfx[indexnum].priority = (int)value; - else - if (!strcasecmp(key,deh_sfxinfo[3])) // Zero 1 - S_sfx[indexnum].link = (sfxinfo_t *)value; - else - if (!strcasecmp(key,deh_sfxinfo[4])) // Zero 2 - S_sfx[indexnum].pitch = (int)value; - else - if (!strcasecmp(key,deh_sfxinfo[5])) // Zero 3 - S_sfx[indexnum].volume = (int)value; - else - if (!strcasecmp(key,deh_sfxinfo[6])) // Zero 4 - (void *) value;// S_sfx[indexnum].data = (void *) value; // killough 5/3/98: changed cast - else - if (!strcasecmp(key,deh_sfxinfo[7])) // Neg. One 1 - S_sfx[indexnum].usefulness = (int)value; - else - if (!strcasecmp(key,deh_sfxinfo[8])) // Neg. One 2 - S_sfx[indexnum].lumpnum = (int)value; - else - if (fpout) fprintf(fpout, - "Invalid sound string index for '%s'\n",key); - } - return; -} - -// ==================================================================== -// deh_procAmmo -// Purpose: Handle DEH Ammo block -// Args: fpin -- input file stream -// fpout -- output file stream (DEHOUT.TXT) -// line -- current line in file to process -// Returns: void -// -static void deh_procAmmo(DEHFILE *fpin, FILE* fpout, char *line) -{ - char key[DEH_MAXKEYLEN]; - char inbuffer[DEH_BUFFERMAX]; - uint_64_t value; // All deh values are ints or longs - int indexnum; - - strncpy(inbuffer,line,DEH_BUFFERMAX - 1); - - // killough 8/98: allow hex numbers in input: - sscanf(inbuffer,"%s %i",key, &indexnum); - if (fpout) fprintf(fpout,"Processing Ammo at index %d: %s\n", - indexnum, key); - if (indexnum < 0 || indexnum >= NUMAMMO) - if (fpout) fprintf(fpout,"Bad ammo number %d of %d\n", - indexnum,NUMAMMO); - - while (!dehfeof(fpin) && *inbuffer && (*inbuffer != ' ')) - { - if (!dehfgets(inbuffer, sizeof(inbuffer), fpin)) break; - lfstrip(inbuffer); - if (!*inbuffer) break; // killough 11/98 - if (!deh_GetData(inbuffer,key,&value,NULL,fpout)) // returns TRUE if ok - { - if (fpout) fprintf(fpout,"Bad data pair in '%s'\n",inbuffer); - continue; - } - if (!strcasecmp(key,deh_ammo[0])) // Max ammo - maxammo[indexnum] = (int)value; - else - if (!strcasecmp(key,deh_ammo[1])) // Per ammo - clipammo[indexnum] = (int)value; - else - if (fpout) fprintf(fpout,"Invalid ammo string index for '%s'\n",key); - } - return; -} - -// ==================================================================== -// deh_procWeapon -// Purpose: Handle DEH Weapon block -// Args: fpin -- input file stream -// fpout -- output file stream (DEHOUT.TXT) -// line -- current line in file to process -// Returns: void -// -static void deh_procWeapon(DEHFILE *fpin, FILE* fpout, char *line) -{ - char key[DEH_MAXKEYLEN]; - char inbuffer[DEH_BUFFERMAX]; - uint_64_t value; // All deh values are ints or longs - int indexnum; - - strncpy(inbuffer,line,DEH_BUFFERMAX - 1); - - // killough 8/98: allow hex numbers in input: - sscanf(inbuffer,"%s %i",key, &indexnum); - if (fpout) fprintf(fpout,"Processing Weapon at index %d: %s\n", - indexnum, key); - if (indexnum < 0 || indexnum >= NUMWEAPONS) - if (fpout) fprintf(fpout,"Bad weapon number %d of %d\n", - indexnum, NUMAMMO); - - while (!dehfeof(fpin) && *inbuffer && (*inbuffer != ' ')) - { - if (!dehfgets(inbuffer, sizeof(inbuffer), fpin)) break; - lfstrip(inbuffer); - if (!*inbuffer) break; // killough 11/98 - if (!deh_GetData(inbuffer,key,&value,NULL,fpout)) // returns TRUE if ok - { - if (fpout) fprintf(fpout,"Bad data pair in '%s'\n",inbuffer); - continue; - } - if (!strcasecmp(key,deh_weapon[0])) // Ammo type - weaponinfo[indexnum].ammo = (ammotype_t)value; - else - if (!strcasecmp(key,deh_weapon[1])) // Deselect frame - weaponinfo[indexnum].upstate = (int)value; - else - if (!strcasecmp(key,deh_weapon[2])) // Select frame - weaponinfo[indexnum].downstate = (int)value; - else - if (!strcasecmp(key,deh_weapon[3])) // Bobbing frame - weaponinfo[indexnum].readystate = (int)value; - else - if (!strcasecmp(key,deh_weapon[4])) // Shooting frame - weaponinfo[indexnum].atkstate = (int)value; - else - if (!strcasecmp(key,deh_weapon[5])) // Firing frame - weaponinfo[indexnum].flashstate = (int)value; - else - if (fpout) fprintf(fpout,"Invalid weapon string index for '%s'\n",key); - } - return; -} - -// ==================================================================== -// deh_procSprite -// Purpose: Dummy - we do not support the DEH Sprite block -// Args: fpin -- input file stream -// fpout -- output file stream (DEHOUT.TXT) -// line -- current line in file to process -// Returns: void -// -static void deh_procSprite(DEHFILE *fpin, FILE* fpout, char *line) // Not supported -{ - char key[DEH_MAXKEYLEN]; - char inbuffer[DEH_BUFFERMAX]; - int indexnum; - - // Too little is known about what this is supposed to do, and - // there are better ways of handling sprite renaming. Not supported. - - strncpy(inbuffer,line,DEH_BUFFERMAX - 1); - - // killough 8/98: allow hex numbers in input: - sscanf(inbuffer,"%s %i",key, &indexnum); - if (fpout) fprintf(fpout, - "Ignoring Sprite offset change at index %d: %s\n",indexnum, key); - while (!dehfeof(fpin) && *inbuffer && (*inbuffer != ' ')) - { - if (!dehfgets(inbuffer, sizeof(inbuffer), fpin)) break; - lfstrip(inbuffer); - if (!*inbuffer) break; // killough 11/98 - // ignore line - if (fpout) fprintf(fpout,"- %s\n",inbuffer); - } - return; -} - -// ==================================================================== -// deh_procPars -// Purpose: Handle BEX extension for PAR times -// Args: fpin -- input file stream -// fpout -- output file stream (DEHOUT.TXT) -// line -- current line in file to process -// Returns: void -// -static void deh_procPars(DEHFILE *fpin, FILE* fpout, char *line) // extension -{ - char key[DEH_MAXKEYLEN]; - char inbuffer[DEH_BUFFERMAX]; - int indexnum; - int episode, level, partime, oldpar; - - // new item, par times - // usage: After [PARS] Par 0 section identifier, use one or more of these - // lines: - // par 3 5 120 - // par 14 230 - // The first would make the par for E3M5 be 120 seconds, and the - // second one makes the par for MAP14 be 230 seconds. The number - // of parameters on the line determines which group of par values - // is being changed. Error checking is done based on current fixed - // array sizes of[4][10] and [32] - - strncpy(inbuffer,line,DEH_BUFFERMAX - 1); - - // killough 8/98: allow hex numbers in input: - sscanf(inbuffer,"%s %i",key, &indexnum); - if (fpout) fprintf(fpout, - "Processing Par value at index %d: %s\n",indexnum, key); - // indexnum is a dummy entry - while (!dehfeof(fpin) && *inbuffer && (*inbuffer != ' ')) - { - if (!dehfgets(inbuffer, sizeof(inbuffer), fpin)) break; - lfstrip(strlwr(inbuffer)); // lowercase it - if (!*inbuffer) break; // killough 11/98 - if (3 != sscanf(inbuffer,"par %i %i %i",&episode, &level, &partime)) - { // not 3 - if (2 != sscanf(inbuffer,"par %i %i",&level, &partime)) - { // not 2 - if (fpout) fprintf(fpout,"Invalid par time setting string: %s\n",inbuffer); - } - else - { // is 2 - // Ty 07/11/98 - wrong range check, not zero-based - if (level < 1 || level > 32) // base 0 array (but 1-based parm) - { - if (fpout) fprintf(fpout,"Invalid MAPnn value MAP%d\n",level); - } - else - { - oldpar = cpars[level-1]; - if (fpout) fprintf(fpout,"Changed par time for MAP%02d from %d to %d\n",level,oldpar,partime); - cpars[level-1] = partime; - deh_pars = TRUE; - } - } - } - else - { // is 3 - // note that though it's a [4][10] array, the "left" and "top" aren't used, - // effectively making it a base 1 array. - // Ty 07/11/98 - level was being checked against max 3 - dumb error - // Note that episode 4 does not have par times per original design - // in Ultimate DOOM so that is not supported here. - if (episode < 1 || episode > 3 || level < 1 || level > 9) - { - if (fpout) fprintf(fpout, - "Invalid ExMx values E%dM%d\n",episode, level); - } - else - { - oldpar = pars[episode][level]; - pars[episode][level] = partime; - if (fpout) fprintf(fpout, - "Changed par time for E%dM%d from %d to %d\n", - episode,level,oldpar,partime); - deh_pars = TRUE; - } - } - } - return; -} - -// ==================================================================== -// deh_procCheat -// Purpose: Handle DEH Cheat block -// Args: fpin -- input file stream -// fpout -- output file stream (DEHOUT.TXT) -// line -- current line in file to process -// Returns: void -// -static void deh_procCheat(DEHFILE *fpin, FILE* fpout, char *line) // done -{ - char key[DEH_MAXKEYLEN]; - char inbuffer[DEH_BUFFERMAX]; - uint_64_t value; // All deh values are ints or longs - char ch = 0; // CPhipps - `writable' null string to initialise... - char *strval = &ch; // pointer to the value area - int ix, iy; // array indices - char *p; // utility pointer - - if (fpout) fprintf(fpout,"Processing Cheat: %s\n",line); - - strncpy(inbuffer,line,DEH_BUFFERMAX - 1); - while (!dehfeof(fpin) && *inbuffer && (*inbuffer != ' ')) - { - if (!dehfgets(inbuffer, sizeof(inbuffer), fpin)) break; - lfstrip(inbuffer); - if (!*inbuffer) break; // killough 11/98 - if (!deh_GetData(inbuffer,key,&value,&strval,fpout)) // returns TRUE if ok - { - if (fpout) fprintf(fpout,"Bad data pair in '%s'\n",inbuffer); - continue; - } - // Otherwise we got a (perhaps valid) cheat name, - // so look up the key in the array - - // killough 4/18/98: use main cheat code table in st_stuff.c now - for (ix=0; cheat[ix].cheat; ix++) - if (cheat[ix].deh_cheat) // killough 4/18/98: skip non-deh - { - if (!strcasecmp(key,cheat[ix].deh_cheat)) // found the cheat, ignored case - { - // replace it but don't overflow it. Use current length as limit. - // Ty 03/13/98 - add 0xff code - // Deal with the fact that the cheats in deh files are extended - // with character 0xFF to the original cheat length, which we don't do. - for (iy=0; strval[iy]; iy++) - strval[iy] = (strval[iy]==(char)0xff) ? '\0' : strval[iy]; - - iy = ix; // killough 4/18/98 - - // Ty 03/14/98 - skip leading spaces - p = strval; - while (*p == ' ') ++p; - // Ty 03/16/98 - change to use a strdup and orphan the original - // Also has the advantage of allowing length changes. - // strncpy(cheat[iy].cheat,p,strlen(cheat[iy].cheat)); -#if 0 - { // killough 9/12/98: disable cheats which are prefixes of this one - int i; - for (i=0; cheat[i].cheat; i++) - if (cheat[i].when & not_deh && - !strncasecmp(cheat[i].cheat, - cheat[iy].cheat, - strlen(cheat[i].cheat)) && i != iy) - cheat[i].deh_modified = true; - } -#endif - cheat[iy].cheat = strdup(p); - if (fpout) fprintf(fpout, - "Assigned new cheat '%s' to cheat '%s'at index %d\n", - p, cheat[ix].deh_cheat, iy); // killough 4/18/98 - } - } - if (fpout) fprintf(fpout,"- %s\n",inbuffer); - } - return; -} - -// ==================================================================== -// deh_procMisc -// Purpose: Handle DEH Misc block -// Args: fpin -- input file stream -// fpout -- output file stream (DEHOUT.TXT) -// line -- current line in file to process -// Returns: void -// -static void deh_procMisc(DEHFILE *fpin, FILE* fpout, char *line) // done -{ - char key[DEH_MAXKEYLEN]; - char inbuffer[DEH_BUFFERMAX]; - uint_64_t value; // All deh values are ints or longs - - strncpy(inbuffer,line,DEH_BUFFERMAX - 1); - while (!dehfeof(fpin) && *inbuffer && (*inbuffer != ' ')) - { - if (!dehfgets(inbuffer, sizeof(inbuffer), fpin)) break; - lfstrip(inbuffer); - if (!*inbuffer) break; // killough 11/98 - if (!deh_GetData(inbuffer,key,&value,NULL,fpout)) // returns TRUE if ok - { - if (fpout) fprintf(fpout,"Bad data pair in '%s'\n",inbuffer); - continue; - } - // Otherwise it's ok - if (fpout) fprintf(fpout,"Processing Misc item '%s'\n", key); - - if (!strcasecmp(key,deh_misc[0])) // Initial Health - initial_health = (int)value; - else - if (!strcasecmp(key,deh_misc[1])) // Initial Bullets - initial_bullets = (int)value; - else - if (!strcasecmp(key,deh_misc[2])) // Max Health - maxhealth = (int)value; - else - if (!strcasecmp(key,deh_misc[3])) // Max Armor - max_armor = (int)value; - else - if (!strcasecmp(key,deh_misc[4])) // Green Armor Class - green_armor_class = (int)value; - else - if (!strcasecmp(key,deh_misc[5])) // Blue Armor Class - blue_armor_class = (int)value; - else - if (!strcasecmp(key,deh_misc[6])) // Max Soulsphere - max_soul = (int)value; - else - if (!strcasecmp(key,deh_misc[7])) // Soulsphere Health - soul_health = (int)value; - else - if (!strcasecmp(key,deh_misc[8])) // Megasphere Health - mega_health = (int)value; - else - if (!strcasecmp(key,deh_misc[9])) // God Mode Health - god_health = (int)value; - else - if (!strcasecmp(key,deh_misc[10])) // IDFA Armor - idfa_armor = (int)value; - else - if (!strcasecmp(key,deh_misc[11])) // IDFA Armor Class - idfa_armor_class = (int)value; - else - if (!strcasecmp(key,deh_misc[12])) // IDKFA Armor - idkfa_armor = (int)value; - else - if (!strcasecmp(key,deh_misc[13])) // IDKFA Armor Class - idkfa_armor_class = (int)value; - else - if (!strcasecmp(key,deh_misc[14])) // BFG Cells/Shot - bfgcells = (int)value; - else - if (!strcasecmp(key,deh_misc[15])) { // Monsters Infight - // e6y: Dehacked support - monsters infight - if (value == 202) monsters_infight = 0; - else if (value == 221) monsters_infight = 1; - else if (fpout) fprintf(fpout, - "Invalid value for 'Monsters Infight': %i", (int)value); - - /* No such switch in DOOM - nop */ //e6y ; - } else - if (fpout) fprintf(fpout, - "Invalid misc item string index for '%s'\n",key); - } - return; -} - -// ==================================================================== -// deh_procText -// Purpose: Handle DEH Text block -// Notes: We look things up in the current information and if found -// we replace it. At the same time we write the new and -// improved BEX syntax to the log file for future use. -// Args: fpin -- input file stream -// fpout -- output file stream (DEHOUT.TXT) -// line -- current line in file to process -// Returns: void -// -static void deh_procText(DEHFILE *fpin, FILE* fpout, char *line) -{ - char key[DEH_MAXKEYLEN]; - char inbuffer[DEH_BUFFERMAX*2]; // can't use line -- double size buffer too. - int i; // loop variable - int fromlen, tolen; // as specified on the text block line - int usedlen; // shorter of fromlen and tolen if not matched - boolean found = FALSE; // to allow early exit once found - char* line2 = NULL; // duplicate line for rerouting - - // Ty 04/11/98 - Included file may have NOTEXT skip flag set - if (includenotext) // flag to skip included deh-style text - { - if (fpout) fprintf(fpout, - "Skipped text block because of notext directive\n"); - strcpy(inbuffer,line); - while (!dehfeof(fpin) && *inbuffer && (*inbuffer != ' ')) - dehfgets(inbuffer, sizeof(inbuffer), fpin); // skip block - // Ty 05/17/98 - don't care if this fails - return; // ************** Early return - } - - // killough 8/98: allow hex numbers in input: - sscanf(line,"%s %i %i",key,&fromlen,&tolen); - if (fpout) fprintf(fpout, - "Processing Text (key=%s, from=%d, to=%d)\n", - key, fromlen, tolen); - - // killough 10/98: fix incorrect usage of feof - { - int c, totlen = 0; - while (totlen < fromlen + tolen && (c = dehfgetc(fpin)) != EOF) - if (c != '\r') - inbuffer[totlen++] = c; - inbuffer[totlen]='\0'; - } - - // if the from and to are 4, this may be a sprite rename. Check it - // against the array and process it as such if it matches. Remember - // that the original names are (and should remain) uppercase. - // Future: this will be from a separate [SPRITES] block. - if (fromlen==4 && tolen==4) - { - i=0; - while (sprnames[i]) // null terminated list in info.c //jff 3/19/98 - { //check pointer - if (!strncasecmp(sprnames[i],inbuffer,fromlen)) //not first char - { - if (fpout) fprintf(fpout, - "Changing name of sprite at index %d from %s to %*s\n", - i,sprnames[i],tolen,&inbuffer[fromlen]); - // Ty 03/18/98 - not using strdup because length is fixed - - // killough 10/98: but it's an array of pointers, so we must - // use strdup unless we redeclare sprnames and change all else - { - // CPhipps - fix constness problem - char *s; - sprnames[i] = s = strdup(sprnames[i]); - - strncpy(s,&inbuffer[fromlen],tolen); - } - found = TRUE; - break; // only one will match--quit early - } - ++i; // next array element - } - } - else - if (fromlen < 7 && tolen < 7) // lengths of music and sfx are 6 or shorter - { - usedlen = (fromlen < tolen) ? fromlen : tolen; - if (fromlen != tolen) - if (fpout) fprintf(fpout, - "Warning: Mismatched lengths from=%d, to=%d, used %d\n", - fromlen, tolen, usedlen); - // Try sound effects entries - see sounds.c - for (i=1; i 12) ? "..." : "",fromlen,tolen); - if ((size_t)fromlen <= strlen(inbuffer)) - { - line2 = strdup(&inbuffer[fromlen]); - inbuffer[fromlen] = '\0'; - } - - deh_procStringSub(NULL, inbuffer, line2, fpout); - } - free(line2); // may be NULL, ignored by free() - return; -} - -static void deh_procError(DEHFILE *fpin, FILE* fpout, char *line) -{ - char inbuffer[DEH_BUFFERMAX]; - - strncpy(inbuffer,line,DEH_BUFFERMAX - 1); - if (fpout) fprintf(fpout,"Unmatched Block: '%s'\n",inbuffer); - return; -} - -// ==================================================================== -// deh_procStrings -// Purpose: Handle BEX [STRINGS] extension -// Args: fpin -- input file stream -// fpout -- output file stream (DEHOUT.TXT) -// line -- current line in file to process -// Returns: void -// -static void deh_procStrings(DEHFILE *fpin, FILE* fpout, char *line) -{ - char key[DEH_MAXKEYLEN]; - char inbuffer[DEH_BUFFERMAX]; - uint_64_t value; // All deh values are ints or longs - char *strval; // holds the string value of the line - static int maxstrlen = 128; // maximum string length, bumped 128 at - // a time as needed - // holds the final result of the string after concatenation - static char *holdstring = NULL; - boolean found = false; // looking for string continuation - - if (fpout) fprintf(fpout,"Processing extended string substitution\n"); - - if (!holdstring) holdstring = malloc(maxstrlen*sizeof(*holdstring)); - - *holdstring = '\0'; // empty string to start with - strncpy(inbuffer,line,DEH_BUFFERMAX - 1); - // Ty 04/24/98 - have to allow inbuffer to start with a blank for - // the continuations of C1TEXT etc. - while (!dehfeof(fpin) && *inbuffer) /* && (*inbuffer != ' ') */ - { - if (!dehfgets(inbuffer, sizeof(inbuffer), fpin)) break; - if (*inbuffer == '#') continue; // skip comment lines - lfstrip(inbuffer); - if (!*inbuffer) break; // killough 11/98 - if (!*holdstring) // first one--get the key - { - if (!deh_GetData(inbuffer,key,&value,&strval,fpout)) // returns TRUE if ok - { - if (fpout) fprintf(fpout,"Bad data pair in '%s'\n",inbuffer); - continue; - } - } - while (strlen(holdstring) + strlen(inbuffer) > (size_t)maxstrlen) // Ty03/29/98 - fix stupid error - { - // killough 11/98: allocate enough the first time - maxstrlen += strlen(holdstring) + strlen(inbuffer) - maxstrlen; - if (fpout) fprintf(fpout, - "* increased buffer from to %d for buffer size %d\n", - maxstrlen,(int)strlen(inbuffer)); - holdstring = realloc(holdstring,maxstrlen*sizeof(*holdstring)); - } - // concatenate the whole buffer if continuation or the value iffirst - strcat(holdstring,ptr_lstrip(((*holdstring) ? inbuffer : strval))); - rstrip(holdstring); - // delete any trailing blanks past the backslash - // note that blanks before the backslash will be concatenated - // but ones at the beginning of the next line will not, allowing - // indentation in the file to read well without affecting the - // string itself. - if (holdstring[strlen(holdstring)-1] == '\\') - { - holdstring[strlen(holdstring)-1] = '\0'; - continue; // ready to concatenate - } - if (*holdstring) // didn't have a backslash, trap above would catch that - { - // go process the current string - found = deh_procStringSub(key, NULL, holdstring, fpout); // supply keyand not search string - - if (!found) - if (fpout) fprintf(fpout, - "Invalid string key '%s', substitution skipped.\n",key); - - *holdstring = '\0'; // empty string for the next one - } - } - return; -} - -// ==================================================================== -// deh_procStringSub -// Purpose: Common string parsing and handling routine for DEH and BEX -// Args: key -- place to put the mnemonic for the string if found -// lookfor -- original value string to look for -// newstring -- string to put in its place if found -// fpout -- file stream pointer for log file (DEHOUT.TXT) -// Returns: boolean: True if string found, false if not -// -boolean deh_procStringSub(char *key, char *lookfor, char *newstring, FILE *fpout) -{ - boolean found; // loop exit flag - int i; // looper - - found = false; - for (i=0;i '%s'\n",key,newstring); - - if (!key) - if (fpout) fprintf(fpout, - "Assigned '%.12s%s' to'%.12s%s' at key %s\n", - lookfor, (strlen(lookfor) > 12) ? "..." : "", - newstring, (strlen(newstring) > 12) ? "..." :"", - deh_strlookup[i].lookup); - - if (!key) // must have passed an old style string so showBEX - if (fpout) fprintf(fpout, - "*BEX FORMAT:\n%s = %s\n*END BEX\n", - deh_strlookup[i].lookup, - dehReformatStr(newstring)); - - break; - } - } - if (!found) - if (fpout) fprintf(fpout, - "Could not find '%.12s'\n",key ? key: lookfor); - - return found; -} - -//======================================================================== -// haleyjd 9/22/99 -// -// deh_procHelperThing -// -// Allows handy substitution of any thing for helper dogs. DEH patches -// are being made frequently for this purpose and it requires a complete -// rewiring of the DOG thing. I feel this is a waste of effort, and so -// have added this new [HELPER] BEX block - -static void deh_procHelperThing(DEHFILE *fpin, FILE *fpout, char *line) -{ - char key[DEH_MAXKEYLEN]; - char inbuffer[DEH_BUFFERMAX]; - uint_64_t value; // All deh values are ints or longs - - strncpy(inbuffer,line,DEH_BUFFERMAX - 1); - while (!dehfeof(fpin) && *inbuffer && (*inbuffer != ' ')) - { - if (!dehfgets(inbuffer, sizeof(inbuffer), fpin)) break; - lfstrip(inbuffer); - if (!*inbuffer) break; - if (!deh_GetData(inbuffer,key,&value,NULL,fpout)) // returns TRUE if ok - { - if (fpout) fprintf(fpout,"Bad data pair in '%s'\n",inbuffer); - continue; - } - // Otherwise it's ok - if (fpout) - { - fprintf(fpout,"Processing Helper Thing item '%s'\n", key); - fprintf(fpout,"value is %i", (int)value); - } - if (!strncasecmp(key, "type", 4)) - HelperThing = (int)value; - } - return; -} - -// -// deh_procBexSprites -// -// Supports sprite name substitutions without requiring use -// of the DeHackEd Text block -// -static void deh_procBexSprites(DEHFILE *fpin, FILE *fpout, char *line) -{ - char key[DEH_MAXKEYLEN]; - char inbuffer[DEH_BUFFERMAX]; - uint_64_t value; // All deh values are ints or longs - char *strval; // holds the string value of the line - char candidate[5]; - int rover; - - if(fpout) - fprintf(fpout,"Processing sprite name substitution\n"); - - strncpy(inbuffer,line,DEH_BUFFERMAX - 1); - - while(!dehfeof(fpin) && *inbuffer && (*inbuffer != ' ')) - { - if(!dehfgets(inbuffer, sizeof(inbuffer), fpin)) - break; - if(*inbuffer == '#') - continue; // skip comment lines - lfstrip(inbuffer); - if(!*inbuffer) - break; // killough 11/98 - if(!deh_GetData(inbuffer,key,&value,&strval,fpout)) // returns TRUE if ok - { - if(fpout) - fprintf(fpout,"Bad data pair in '%s'\n",inbuffer); - continue; - } - // do it - memset(candidate, 0, sizeof(candidate)); - strncpy(candidate, ptr_lstrip(strval), 4); - if(strlen(candidate) != 4) - { - if(fpout) - fprintf(fpout, "Bad length for sprite name '%s'\n", - candidate); - continue; - } - - rover = 0; - while(deh_spritenames[rover]) - { - if(!strncasecmp(deh_spritenames[rover], key, 4)) - { - if(fpout) - fprintf(fpout, "Substituting '%s' for sprite '%s'\n", - candidate, deh_spritenames[rover]); - - sprnames[rover] = strdup(candidate); - break; - } - rover++; - } - } -} - -// ditto for sound names -static void deh_procBexSounds(DEHFILE *fpin, FILE *fpout, char *line) -{ - char key[DEH_MAXKEYLEN]; - char inbuffer[DEH_BUFFERMAX]; - uint_64_t value; // All deh values are ints or longs - char *strval; // holds the string value of the line - char candidate[7]; - int rover, len; - - if(fpout) - fprintf(fpout,"Processing sound name substitution\n"); - - strncpy(inbuffer,line,DEH_BUFFERMAX - 1); - - while(!dehfeof(fpin) && *inbuffer && (*inbuffer != ' ')) - { - if(!dehfgets(inbuffer, sizeof(inbuffer), fpin)) - break; - if(*inbuffer == '#') - continue; // skip comment lines - lfstrip(inbuffer); - if(!*inbuffer) - break; // killough 11/98 - if(!deh_GetData(inbuffer,key,&value,&strval,fpout)) // returns TRUE if ok - { - if(fpout) - fprintf(fpout,"Bad data pair in '%s'\n",inbuffer); - continue; - } - // do it - memset(candidate, 0, 7); - strncpy(candidate, ptr_lstrip(strval), 6); - len = strlen(candidate); - if(len < 1 || len > 6) - { - if(fpout) - fprintf(fpout, "Bad length for sound name '%s'\n", - candidate); - continue; - } - - rover = 1; - while(deh_soundnames[rover]) - { - if(!strncasecmp(deh_soundnames[rover], key, 6)) - { - if(fpout) - fprintf(fpout, "Substituting '%s' for sound '%s'\n", - candidate, deh_soundnames[rover]); - - S_sfx[rover].name = strdup(candidate); - break; - } - rover++; - } - } -} - -// ditto for music names -static void deh_procBexMusic(DEHFILE *fpin, FILE *fpout, char *line) -{ - char key[DEH_MAXKEYLEN]; - char inbuffer[DEH_BUFFERMAX]; - uint_64_t value; // All deh values are ints or longs - char *strval; // holds the string value of the line - char candidate[7]; - int rover, len; - - if(fpout) - fprintf(fpout,"Processing music name substitution\n"); - - strncpy(inbuffer,line,DEH_BUFFERMAX - 1); - - while(!dehfeof(fpin) && *inbuffer && (*inbuffer != ' ')) - { - if(!dehfgets(inbuffer, sizeof(inbuffer), fpin)) - break; - if(*inbuffer == '#') - continue; // skip comment lines - lfstrip(inbuffer); - if(!*inbuffer) - break; // killough 11/98 - if(!deh_GetData(inbuffer,key,&value,&strval,fpout)) // returns TRUE if ok - { - if(fpout) - fprintf(fpout,"Bad data pair in '%s'\n",inbuffer); - continue; - } - // do it - memset(candidate, 0, 7); - strncpy(candidate, ptr_lstrip(strval), 6); - len = strlen(candidate); - if(len < 1 || len > 6) - { - if(fpout) - fprintf(fpout, "Bad length for music name '%s'\n", - candidate); - continue; - } - - rover = 1; - while(deh_musicnames[rover]) - { - if(!strncasecmp(deh_musicnames[rover], key, 6)) - { - if(fpout) - fprintf(fpout, "Substituting '%s' for music '%s'\n", - candidate, deh_musicnames[rover]); - - S_music[rover].name = strdup(candidate); - break; - } - rover++; - } - } -} - -// ==================================================================== -// General utility function(s) -// ==================================================================== - -// ==================================================================== -// dehReformatStr -// Purpose: Convert a string into a continuous string with embedded -// linefeeds for "\n" sequences in the source string -// Args: string -- the string to convert -// Returns: the converted string (converted in a static buffer) -// -static char *dehReformatStr(char *string) -{ - static char *buff = NULL; // only processing the changed string, - char *s, *t; - - if (!buff) - buff = malloc(DEH_BUFFERMAX); - - s = string; // source - t = buff; // target - // let's play... - - while (*s) - { - if (*s == '\n') - ++s, *t++ = '\\', *t++ = 'n', *t++ = '\\', *t++='\n'; - else - *t++ = *s++; - } - *t = '\0'; - return buff; -} - -// ==================================================================== -// lfstrip -// Purpose: Strips CR/LF off the end of a string -// Args: s -- the string to work on -// Returns: void -- the string is modified in place -// -// killough 10/98: only strip at end of line, not entire string - -static void lfstrip(char *s) // strip the \r and/or \n off of a line -{ - char *p = s+strlen(s); - while (p > s && (*--p=='\r' || *p=='\n')) - *p = 0; -} - -// ==================================================================== -// rstrip -// Purpose: Strips trailing blanks off a string -// Args: s -- the string to work on -// Returns: void -- the string is modified in place -// -static void rstrip(char *s) // strip trailing whitespace -{ - char *p = s+strlen(s); // killough 4/4/98: same here - while (p > s && isspace(*--p)) // break on first non-whitespace - *p='\0'; -} - -// ==================================================================== -// ptr_lstrip -// Purpose: Points past leading whitespace in a string -// Args: s -- the string to work on -// Returns: char * pointing to the first nonblank character in the -// string. The original string is not changed. -// -static char *ptr_lstrip(char *p) // point past leading whitespace -{ - while (isspace(*p)) - p++; - return p; -} - -// e6y: Correction of wrong processing of Bits parameter if its value is equal to zero -// No more desync on HACX demos. -// FIXME!!! (lame) -static boolean StrToInt(char *s, long *l) -{ - return ( - (sscanf(s, " 0x%lx", l) == 1) || - (sscanf(s, " 0X%lx", l) == 1) || - (sscanf(s, " 0%lo", l) == 1) || - (sscanf(s, " %ld", l) == 1) - ); -} - -// ==================================================================== -// deh_GetData -// Purpose: Get a key and data pair from a passed string -// Args: s -- the string to be examined -// k -- a place to put the key -// l -- pointer to a long integer to store the number -// strval -- a pointer to the place in s where the number -// value comes from. Pass NULL to not use this. -// fpout -- stream pointer to output log (DEHOUT.TXT) -// Notes: Expects a key phrase, optional space, equal sign, -// optional space and a value, mostly an int but treated -// as a long just in case. The passed pointer to hold -// the key must be DEH_MAXKEYLEN in size. - -static boolean deh_GetData(char *s, char *k, uint_64_t *l, char **strval, FILE *fpout) -{ - char *t; // current char - long val; // to hold value of pair - char buffer[DEH_MAXKEYLEN]; // to hold key in progress - // e6y: Correction of wrong processing of Bits parameter if its value is equal to zero - // No more desync on HACX demos. - boolean okrc = 1; // assume good unless we have problems - int i; // iterator - - *buffer = '\0'; - val = 0; // defaults in case not otherwise set - for (i=0, t=s; *t && i < DEH_MAXKEYLEN; t++, i++) - { - if (*t == '=') break; - buffer[i] = *t; // copy it - } - buffer[--i] = '\0'; // terminate the key before the '=' - if (!*t) // end of string with no equal sign - { - okrc = FALSE; - } - else - { - if (!*++t) - { - val = 0; // in case "thiskey =" with no value - okrc = FALSE; - } - // we've incremented t - // e6y: Correction of wrong processing of Bits parameter if its value is equal to zero - // No more desync on HACX demos. - // Old code: e6y val = strtol(t,NULL,0); // killough 8/9/98: allow hex or octal input - if (!StrToInt(t,&val)) - { - val = 0; - okrc = 2; - } - } - - // go put the results in the passed pointers - *l = val; // may be a faked zero - - // if spaces between key and equal sign, strip them - strcpy(k,ptr_lstrip(buffer)); // could be a zero-length string - - if (strval != NULL) // pass NULL if you don't want this back - *strval = t; // pointer, has to be somewhere in s, - // even if pointing at the zero byte. - - return(okrc); -} -#else -void D_ProcessDehFile(const char *filename, const char *outfilename, int lumpnum) -{ - lprintf(LO_WARN, "D_ProcessDehFile: deh support has been disabled at build time!\n"); -} -#endif diff --git a/components/doom/prboom/d_deh.h b/components/doom/prboom/d_deh.h deleted file mode 100644 index 513e0b05..00000000 --- a/components/doom/prboom/d_deh.h +++ /dev/null @@ -1,1113 +0,0 @@ -/* Emacs style mode select -*- C++ -*- - *----------------------------------------------------------------------------- - * - * - * PrBoom: a Doom port merged with LxDoom and LSDLDoom - * based on BOOM, a modified and improved DOOM engine - * Copyright (C) 1999 by - * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman - * Copyright (C) 1999-2006 by - * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze - * Copyright 2005, 2006 by - * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko - * - * 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. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA. - * - * DESCRIPTION: - * Dehacked file support - * New for the TeamTNT "Boom" engine - * - * Author: Ty Halderman, TeamTNT - * - * Description: This file translates the #defined string constants - * to named variables to externalize them for deh/bex changes. - * Should be able to compile with D_FRENCH (for example) and still - * work (untested). - * - */ - -#ifndef __D_DEH__ -#define __D_DEH__ - -void D_ProcessDehFile(const char *filename, const char *outfilename, int lumpnum); - -// -// Ty 03/22/98 - note that we are keeping the english versions and -// comments in this file -// New string names all start with an extra s_ to avoid conflicts, -// but are otherwise identical to the original including uppercase. -// This is partly to keep the changes simple and partly for easier -// identification of the locations in which they're used. -// -// Printed strings for translation -// - -// -// D_Main.C -// -//#define D_DEVSTR "Development mode ON.\n" -extern const char* const s_D_DEVSTR; // = D_DEVSTR; -//#define D_CDROM "CD-ROM Version: default.cfg from c:\\doomdata\n" -extern const char* const s_D_CDROM; // = D_CDROM; - -// -// M_Menu.C -// -//#define PRESSKEY "press a key." -extern const char* const s_PRESSKEY; // = PRESSKEY; -//#define PRESSYN "press y or n." -extern const char* const s_PRESSYN; // = PRESSYN; -//#define QUITMSG "are you sure you want to\nquit this great game?" -extern const char* const s_QUITMSG; // = QUITMSG; -//#define LOADNET "you can't do load while in a net game!\n\n"PRESSKEY -extern const char* const s_LOADNET; // = LOADNET; -//#define QLOADNET "you can't quickload during a netgame!\n\n"PRESSKEY -extern const char* const s_QLOADNET; // = QLOADNET; -//#define QSAVESPOT "you haven't picked a quicksave slot yet!\n\n"PRESSKEY -extern const char* const s_QSAVESPOT; // = QSAVESPOT; -//#define SAVEDEAD "you can't save if you aren't playing!\n\n"PRESSKEY -extern const char* const s_SAVEDEAD; // = SAVEDEAD; -//#define QSPROMPT "quicksave over your game named\n\n'%s'?\n\n"PRESSYN -extern const char* const s_QSPROMPT; // = QSPROMPT; -//#define QLPROMPT "do you want to quickload the game named\n\n'%s'?\n\n"PRESSYN -extern const char* const s_QLPROMPT; // = QLPROMPT; - -/* -#define NEWGAME \ -"you can't start a new game\n"\ -"while in a network game.\n\n"PRESSKEY -*/ -extern const char* const s_NEWGAME; // = NEWGAME; - -// CPhipps - message given when asked if to restart the level -extern const char* const s_RESTARTLEVEL; - -/* -#define NIGHTMARE \ -"are you sure? this skill level\n"\ -"isn't even remotely fair.\n\n"PRESSYN -*/ -extern const char* const s_NIGHTMARE; // = NIGHTMARE; - -/* -#define SWSTRING \ -"this is the shareware version of doom.\n\n"\ -"you need to order the entire trilogy.\n\n"PRESSKEY -*/ -extern const char* const s_SWSTRING; // = SWSTRING; - -//#define MSGOFF "Messages OFF" -extern const char* const s_MSGOFF; // = MSGOFF; -//#define MSGON "Messages ON" -extern const char* const s_MSGON; // = MSGON; -//#define NETEND "you can't end a netgame!\n\n"PRESSKEY -extern const char* const s_NETEND; // = NETEND; -//#define ENDGAME "are you sure you want to end the game?\n\n"PRESSYN -extern const char* const s_ENDGAME; // = ENDGAME; - -//#define DOSY "(press y to quit)" -extern const char* const s_DOSY; // = DOSY; - -//#define DETAILHI "High detail" -extern const char* const s_DETAILHI; // = DETAILHI; -//#define DETAILLO "Low detail" -extern const char* const s_DETAILLO; // = DETAILLO; -//#define GAMMALVL0 "Gamma correction OFF" -extern const char* const s_GAMMALVL0; // = GAMMALVL0; -//#define GAMMALVL1 "Gamma correction level 1" -extern const char* const s_GAMMALVL1; // = GAMMALVL1; -//#define GAMMALVL2 "Gamma correction level 2" -extern const char* const s_GAMMALVL2; // = GAMMALVL2; -//#define GAMMALVL3 "Gamma correction level 3" -extern const char* const s_GAMMALVL3; // = GAMMALVL3; -//#define GAMMALVL4 "Gamma correction level 4" -extern const char* const s_GAMMALVL4; // = GAMMALVL4; -//#define EMPTYSTRING "empty slot" -extern const char* const s_EMPTYSTRING; // = EMPTYSTRING; - -// -// P_inter.C -// -//#define GOTARMOR "Picked up the armor." -extern const char* const s_GOTARMOR; // = GOTARMOR; -//#define GOTMEGA "Picked up the MegaArmor!" -extern const char* const s_GOTMEGA; // = GOTMEGA; -//#define GOTHTHBONUS "Picked up a health bonus." -extern const char* const s_GOTHTHBONUS; // = GOTHTHBONUS; -//#define GOTARMBONUS "Picked up an armor bonus." -extern const char* const s_GOTARMBONUS; // = GOTARMBONUS; -//#define GOTSTIM "Picked up a stimpack." -extern const char* const s_GOTSTIM; // = GOTSTIM; -//#define GOTMEDINEED "Picked up a medikit that you REALLY need!" -extern const char* const s_GOTMEDINEED; // = GOTMEDINEED; -//#define GOTMEDIKIT "Picked up a medikit." -extern const char* const s_GOTMEDIKIT; // = GOTMEDIKIT; -//#define GOTSUPER "Supercharge!" -extern const char* const s_GOTSUPER; // = GOTSUPER; - -//#define GOTBLUECARD "Picked up a blue keycard." -extern const char* const s_GOTBLUECARD; // = GOTBLUECARD; -//#define GOTYELWCARD "Picked up a yellow keycard." -extern const char* const s_GOTYELWCARD; // = GOTYELWCARD; -//#define GOTREDCARD "Picked up a red keycard." -extern const char* const s_GOTREDCARD; // = GOTREDCARD; -//#define GOTBLUESKUL "Picked up a blue skull key." -extern const char* const s_GOTBLUESKUL; // = GOTBLUESKUL; -//#define GOTYELWSKUL "Picked up a yellow skull key." -extern const char* const s_GOTYELWSKUL; // = GOTYELWSKUL; -//#define GOTREDSKULL "Picked up a red skull key." -extern const char* const s_GOTREDSKULL; // = GOTREDSKULL; - -//#define GOTINVUL "Invulnerability!" -extern const char* const s_GOTINVUL; // = GOTINVUL; -//#define GOTBERSERK "Berserk!" -extern const char* const s_GOTBERSERK; // = GOTBERSERK; -//#define GOTINVIS "Partial Invisibility" -extern const char* const s_GOTINVIS; // = GOTINVIS; -//#define GOTSUIT "Radiation Shielding Suit" -extern const char* const s_GOTSUIT; // = GOTSUIT; -//#define GOTMAP "Computer Area Map" -extern const char* const s_GOTMAP; // = GOTMAP; -//#define GOTVISOR "Light Amplification Visor" -extern const char* const s_GOTVISOR; // = GOTVISOR; -//#define GOTMSPHERE "MegaSphere!" -extern const char* const s_GOTMSPHERE; // = GOTMSPHERE; - -//#define GOTCLIP "Picked up a clip." -extern const char* const s_GOTCLIP; // = GOTCLIP; -//#define GOTCLIPBOX "Picked up a box of bullets." -extern const char* const s_GOTCLIPBOX; // = GOTCLIPBOX; -//#define GOTROCKET "Picked up a rocket." -extern const char* const s_GOTROCKET; // = GOTROCKET; -//#define GOTROCKBOX "Picked up a box of rockets." -extern const char* const s_GOTROCKBOX; // = GOTROCKBOX; -//#define GOTCELL "Picked up an energy cell." -extern const char* const s_GOTCELL; // = GOTCELL; -//#define GOTCELLBOX "Picked up an energy cell pack." -extern const char* const s_GOTCELLBOX; // = GOTCELLBOX; -//#define GOTSHELLS "Picked up 4 shotgun shells." -extern const char* const s_GOTSHELLS; // = GOTSHELLS; -//#define GOTSHELLBOX "Picked up a box of shotgun shells." -extern const char* const s_GOTSHELLBOX; // = GOTSHELLBOX; -//#define GOTBACKPACK "Picked up a backpack full of ammo!" -extern const char* const s_GOTBACKPACK; // = GOTBACKPACK; - -//#define GOTBFG9000 "You got the BFG9000! Oh, yes." -extern const char* const s_GOTBFG9000; // = GOTBFG9000; -//#define GOTCHAINGUN "You got the chaingun!" -extern const char* const s_GOTCHAINGUN; // = GOTCHAINGUN; -//#define GOTCHAINSAW "A chainsaw! Find some meat!" -extern const char* const s_GOTCHAINSAW; // = GOTCHAINSAW; -//#define GOTLAUNCHER "You got the rocket launcher!" -extern const char* const s_GOTLAUNCHER; // = GOTLAUNCHER; -//#define GOTPLASMA "You got the plasma gun!" -extern const char* const s_GOTPLASMA; // = GOTPLASMA; -//#define GOTSHOTGUN "You got the shotgun!" -extern const char* const s_GOTSHOTGUN; // = GOTSHOTGUN; -//#define GOTSHOTGUN2 "You got the super shotgun!" -extern const char* const s_GOTSHOTGUN2; // = GOTSHOTGUN2; - -// -// P_Doors.C -// -//#define PD_BLUEO "You need a blue key to activate this object" -extern const char* const s_PD_BLUEO; // = PD_BLUEO; -//#define PD_REDO "You need a red key to activate this object" -extern const char* const s_PD_REDO; // = PD_REDO; -//#define PD_YELLOWO "You need a yellow key to activate this object" -extern const char* const s_PD_YELLOWO; // = PD_YELLOWO; -//#define PD_BLUEK "You need a blue key to open this door" -extern const char* const s_PD_BLUEK; // = PD_BLUEK; -//#define PD_REDK "You need a red key to open this door" -extern const char* const s_PD_REDK; // = PD_REDK; -//#define PD_YELLOWK "You need a yellow key to open this door" -extern const char* const s_PD_YELLOWK; // = PD_YELLOWK; -//jff 02/05/98 Create messages specific to card and skull keys -//#define PD_BLUEC "You need a blue card to open this door" -extern const char* const s_PD_BLUEC; // = PD_BLUEC; -//#define PD_REDC "You need a red card to open this door" -extern const char* const s_PD_REDC; // = PD_REDC; -//#define PD_YELLOWC "You need a yellow card to open this door" -extern const char* const s_PD_YELLOWC; // = PD_YELLOWC; -//#define PD_BLUES "You need a blue skull to open this door" -extern const char* const s_PD_BLUES; // = PD_BLUES; -//#define PD_REDS "You need a red skull to open this door" -extern const char* const s_PD_REDS; // = PD_REDS; -//#define PD_YELLOWS "You need a yellow skull to open this door" -extern const char* const s_PD_YELLOWS; // = PD_YELLOWS; -//#define PD_ANY "Any key will open this door" -extern const char* const s_PD_ANY; // = PD_ANY; -//#define PD_ALL3 "You need all three keys to open this door" -extern const char* const s_PD_ALL3; // = PD_ALL3; -//#define PD_ALL6 "You need all six keys to open this door" -extern const char* const s_PD_ALL6; // = PD_ALL6; - -// -// G_game.C -// -//#define GGSAVED "game saved." -extern const char* const s_GGSAVED; // = GGSAVED; - -// -// HU_stuff.C -// -//#define HUSTR_MSGU "[Message unsent]" -extern const char* const s_HUSTR_MSGU; // = HUSTR_MSGU; - -//#define HUSTR_E1M1 "E1M1: Hangar" -extern const char* const s_HUSTR_E1M1; // = HUSTR_E1M1; -//#define HUSTR_E1M2 "E1M2: Nuclear Plant" -extern const char* const s_HUSTR_E1M2; // = HUSTR_E1M2; -//#define HUSTR_E1M3 "E1M3: Toxin Refinery" -extern const char* const s_HUSTR_E1M3; // = HUSTR_E1M3; -//#define HUSTR_E1M4 "E1M4: Command Control" -extern const char* const s_HUSTR_E1M4; // = HUSTR_E1M4; -//#define HUSTR_E1M5 "E1M5: Phobos Lab" -extern const char* const s_HUSTR_E1M5; // = HUSTR_E1M5; -//#define HUSTR_E1M6 "E1M6: Central Processing" -extern const char* const s_HUSTR_E1M6; // = HUSTR_E1M6; -//#define HUSTR_E1M7 "E1M7: Computer Station" -extern const char* const s_HUSTR_E1M7; // = HUSTR_E1M7; -//#define HUSTR_E1M8 "E1M8: Phobos Anomaly" -extern const char* const s_HUSTR_E1M8; // = HUSTR_E1M8; -//#define HUSTR_E1M9 "E1M9: Military Base" -extern const char* const s_HUSTR_E1M9; // = HUSTR_E1M9; - -//#define HUSTR_E2M1 "E2M1: Deimos Anomaly" -extern const char* const s_HUSTR_E2M1; // = HUSTR_E2M1; -//#define HUSTR_E2M2 "E2M2: Containment Area" -extern const char* const s_HUSTR_E2M2; // = HUSTR_E2M2; -//#define HUSTR_E2M3 "E2M3: Refinery" -extern const char* const s_HUSTR_E2M3; // = HUSTR_E2M3; -//#define HUSTR_E2M4 "E2M4: Deimos Lab" -extern const char* const s_HUSTR_E2M4; // = HUSTR_E2M4; -//#define HUSTR_E2M5 "E2M5: Command Center" -extern const char* const s_HUSTR_E2M5; // = HUSTR_E2M5; -//#define HUSTR_E2M6 "E2M6: Halls of the Damned" -extern const char* const s_HUSTR_E2M6; // = HUSTR_E2M6; -//#define HUSTR_E2M7 "E2M7: Spawning Vats" -extern const char* const s_HUSTR_E2M7; // = HUSTR_E2M7; -//#define HUSTR_E2M8 "E2M8: Tower of Babel" -extern const char* const s_HUSTR_E2M8; // = HUSTR_E2M8; -//#define HUSTR_E2M9 "E2M9: Fortress of Mystery" -extern const char* const s_HUSTR_E2M9; // = HUSTR_E2M9; - -//#define HUSTR_E3M1 "E3M1: Hell Keep" -extern const char* const s_HUSTR_E3M1; // = HUSTR_E3M1; -//#define HUSTR_E3M2 "E3M2: Slough of Despair" -extern const char* const s_HUSTR_E3M2; // = HUSTR_E3M2; -//#define HUSTR_E3M3 "E3M3: Pandemonium" -extern const char* const s_HUSTR_E3M3; // = HUSTR_E3M3; -//#define HUSTR_E3M4 "E3M4: House of Pain" -extern const char* const s_HUSTR_E3M4; // = HUSTR_E3M4; -//#define HUSTR_E3M5 "E3M5: Unholy Cathedral" -extern const char* const s_HUSTR_E3M5; // = HUSTR_E3M5; -//#define HUSTR_E3M6 "E3M6: Mt. Erebus" -extern const char* const s_HUSTR_E3M6; // = HUSTR_E3M6; -//#define HUSTR_E3M7 "E3M7: Limbo" -extern const char* const s_HUSTR_E3M7; // = HUSTR_E3M7; -//#define HUSTR_E3M8 "E3M8: Dis" -extern const char* const s_HUSTR_E3M8; // = HUSTR_E3M8; -//#define HUSTR_E3M9 "E3M9: Warrens" -extern const char* const s_HUSTR_E3M9; // = HUSTR_E3M9; - -//#define HUSTR_E4M1 "E4M1: Hell Beneath" -extern const char* const s_HUSTR_E4M1; // = HUSTR_E4M1; -//#define HUSTR_E4M2 "E4M2: Perfect Hatred" -extern const char* const s_HUSTR_E4M2; // = HUSTR_E4M2; -//#define HUSTR_E4M3 "E4M3: Sever The Wicked" -extern const char* const s_HUSTR_E4M3; // = HUSTR_E4M3; -//#define HUSTR_E4M4 "E4M4: Unruly Evil" -extern const char* const s_HUSTR_E4M4; // = HUSTR_E4M4; -//#define HUSTR_E4M5 "E4M5: They Will Repent" -extern const char* const s_HUSTR_E4M5; // = HUSTR_E4M5; -//#define HUSTR_E4M6 "E4M6: Against Thee Wickedly" -extern const char* const s_HUSTR_E4M6; // = HUSTR_E4M6; -//#define HUSTR_E4M7 "E4M7: And Hell Followed" -extern const char* const s_HUSTR_E4M7; // = HUSTR_E4M7; -//#define HUSTR_E4M8 "E4M8: Unto The Cruel" -extern const char* const s_HUSTR_E4M8; // = HUSTR_E4M8; -//#define HUSTR_E4M9 "E4M9: Fear" -extern const char* const s_HUSTR_E4M9; // = HUSTR_E4M9; - -//#define HUSTR_1 "level 1: entryway" -extern const char* const s_HUSTR_1; // = HUSTR_1; -//#define HUSTR_2 "level 2: underhalls" -extern const char* const s_HUSTR_2; // = HUSTR_2; -//#define HUSTR_3 "level 3: the gantlet" -extern const char* const s_HUSTR_3; // = HUSTR_3; -//#define HUSTR_4 "level 4: the focus" -extern const char* const s_HUSTR_4; // = HUSTR_4; -//#define HUSTR_5 "level 5: the waste tunnels" -extern const char* const s_HUSTR_5; // = HUSTR_5; -//#define HUSTR_6 "level 6: the crusher" -extern const char* const s_HUSTR_6; // = HUSTR_6; -//#define HUSTR_7 "level 7: dead simple" -extern const char* const s_HUSTR_7; // = HUSTR_7; -//#define HUSTR_8 "level 8: tricks and traps" -extern const char* const s_HUSTR_8; // = HUSTR_8; -//#define HUSTR_9 "level 9: the pit" -extern const char* const s_HUSTR_9; // = HUSTR_9; -//#define HUSTR_10 "level 10: refueling base" -extern const char* const s_HUSTR_10; // = HUSTR_10; -//#define HUSTR_11 "level 11: 'o' of destruction!" -extern const char* const s_HUSTR_11; // = HUSTR_11; - -//#define HUSTR_12 "level 12: the factory" -extern const char* const s_HUSTR_12; // = HUSTR_12; -//#define HUSTR_13 "level 13: downtown" -extern const char* const s_HUSTR_13; // = HUSTR_13; -//#define HUSTR_14 "level 14: the inmost dens" -extern const char* const s_HUSTR_14; // = HUSTR_14; -//#define HUSTR_15 "level 15: industrial zone" -extern const char* const s_HUSTR_15; // = HUSTR_15; -//#define HUSTR_16 "level 16: suburbs" -extern const char* const s_HUSTR_16; // = HUSTR_16; -//#define HUSTR_17 "level 17: tenements" -extern const char* const s_HUSTR_17; // = HUSTR_17; -//#define HUSTR_18 "level 18: the courtyard" -extern const char* const s_HUSTR_18; // = HUSTR_18; -//#define HUSTR_19 "level 19: the citadel" -extern const char* const s_HUSTR_19; // = HUSTR_19; -//#define HUSTR_20 "level 20: gotcha!" -extern const char* const s_HUSTR_20; // = HUSTR_20; - -//#define HUSTR_21 "level 21: nirvana" -extern const char* const s_HUSTR_21; // = HUSTR_21; -//#define HUSTR_22 "level 22: the catacombs" -extern const char* const s_HUSTR_22; // = HUSTR_22; -//#define HUSTR_23 "level 23: barrels o' fun" -extern const char* const s_HUSTR_23; // = HUSTR_23; -//#define HUSTR_24 "level 24: the chasm" -extern const char* const s_HUSTR_24; // = HUSTR_24; -//#define HUSTR_25 "level 25: bloodfalls" -extern const char* const s_HUSTR_25; // = HUSTR_25; -//#define HUSTR_26 "level 26: the abandoned mines" -extern const char* const s_HUSTR_26; // = HUSTR_26; -//#define HUSTR_27 "level 27: monster condo" -extern const char* const s_HUSTR_27; // = HUSTR_27; -//#define HUSTR_28 "level 28: the spirit world" -extern const char* const s_HUSTR_28; // = HUSTR_28; -//#define HUSTR_29 "level 29: the living end" -extern const char* const s_HUSTR_29; // = HUSTR_29; -//#define HUSTR_30 "level 30: icon of sin" -extern const char* const s_HUSTR_30; // = HUSTR_30; - -//#define HUSTR_31 "level 31: wolfenstein" -extern const char* const s_HUSTR_31; // = HUSTR_31; -//#define HUSTR_32 "level 32: grosse" -extern const char* const s_HUSTR_32; // = HUSTR_32; - -//#define PHUSTR_1 "level 1: congo" -extern const char* const s_PHUSTR_1; // = PHUSTR_1; -//#define PHUSTR_2 "level 2: well of souls" -extern const char* const s_PHUSTR_2; // = PHUSTR_2; -//#define PHUSTR_3 "level 3: aztec" -extern const char* const s_PHUSTR_3; // = PHUSTR_3; -//#define PHUSTR_4 "level 4: caged" -extern const char* const s_PHUSTR_4; // = PHUSTR_4; -//#define PHUSTR_5 "level 5: ghost town" -extern const char* const s_PHUSTR_5; // = PHUSTR_5; -//#define PHUSTR_6 "level 6: baron's lair" -extern const char* const s_PHUSTR_6; // = PHUSTR_6; -//#define PHUSTR_7 "level 7: caughtyard" -extern const char* const s_PHUSTR_7; // = PHUSTR_7; -//#define PHUSTR_8 "level 8: realm" -extern const char* const s_PHUSTR_8; // = PHUSTR_8; -//#define PHUSTR_9 "level 9: abattoire" -extern const char* const s_PHUSTR_9; // = PHUSTR_9; -//#define PHUSTR_10 "level 10: onslaught" -extern const char* const s_PHUSTR_10; // = PHUSTR_10; -//#define PHUSTR_11 "level 11: hunted" -extern const char* const s_PHUSTR_11; // = PHUSTR_11; - -//#define PHUSTR_12 "level 12: speed" -extern const char* const s_PHUSTR_12; // = PHUSTR_12; -//#define PHUSTR_13 "level 13: the crypt" -extern const char* const s_PHUSTR_13; // = PHUSTR_13; -//#define PHUSTR_14 "level 14: genesis" -extern const char* const s_PHUSTR_14; // = PHUSTR_14; -//#define PHUSTR_15 "level 15: the twilight" -extern const char* const s_PHUSTR_15; // = PHUSTR_15; -//#define PHUSTR_16 "level 16: the omen" -extern const char* const s_PHUSTR_16; // = PHUSTR_16; -//#define PHUSTR_17 "level 17: compound" -extern const char* const s_PHUSTR_17; // = PHUSTR_17; -//#define PHUSTR_18 "level 18: neurosphere" -extern const char* const s_PHUSTR_18; // = PHUSTR_18; -//#define PHUSTR_19 "level 19: nme" -extern const char* const s_PHUSTR_19; // = PHUSTR_19; -//#define PHUSTR_20 "level 20: the death domain" -extern const char* const s_PHUSTR_20; // = PHUSTR_20; - -//#define PHUSTR_21 "level 21: slayer" -extern const char* const s_PHUSTR_21; // = PHUSTR_21; -//#define PHUSTR_22 "level 22: impossible mission" -extern const char* const s_PHUSTR_22; // = PHUSTR_22; -//#define PHUSTR_23 "level 23: tombstone" -extern const char* const s_PHUSTR_23; // = PHUSTR_23; -//#define PHUSTR_24 "level 24: the final frontier" -extern const char* const s_PHUSTR_24; // = PHUSTR_24; -//#define PHUSTR_25 "level 25: the temple of darkness" -extern const char* const s_PHUSTR_25; // = PHUSTR_25; -//#define PHUSTR_26 "level 26: bunker" -extern const char* const s_PHUSTR_26; // = PHUSTR_26; -//#define PHUSTR_27 "level 27: anti-christ" -extern const char* const s_PHUSTR_27; // = PHUSTR_27; -//#define PHUSTR_28 "level 28: the sewers" -extern const char* const s_PHUSTR_28; // = PHUSTR_28; -//#define PHUSTR_29 "level 29: odyssey of noises" -extern const char* const s_PHUSTR_29; // = PHUSTR_29; -//#define PHUSTR_30 "level 30: the gateway of hell" -extern const char* const s_PHUSTR_30; // = PHUSTR_30; - -//#define PHUSTR_31 "level 31: cyberden" -extern const char* const s_PHUSTR_31; // = PHUSTR_31; -//#define PHUSTR_32 "level 32: go 2 it" -extern const char* const s_PHUSTR_32; // = PHUSTR_32; - -//#define THUSTR_1 "level 1: system control" -extern const char* const s_THUSTR_1; // = THUSTR_1; -//#define THUSTR_2 "level 2: human bbq" -extern const char* const s_THUSTR_2; // = THUSTR_2; -//#define THUSTR_3 "level 3: power control" -extern const char* const s_THUSTR_3; // = THUSTR_3; -//#define THUSTR_4 "level 4: wormhole" -extern const char* const s_THUSTR_4; // = THUSTR_4; -//#define THUSTR_5 "level 5: hanger" -extern const char* const s_THUSTR_5; // = THUSTR_5; -//#define THUSTR_6 "level 6: open season" -extern const char* const s_THUSTR_6; // = THUSTR_6; -//#define THUSTR_7 "level 7: prison" -extern const char* const s_THUSTR_7; // = THUSTR_7; -//#define THUSTR_8 "level 8: metal" -extern const char* const s_THUSTR_8; // = THUSTR_8; -//#define THUSTR_9 "level 9: stronghold" -extern const char* const s_THUSTR_9; // = THUSTR_9; -//#define THUSTR_10 "level 10: redemption" -extern const char* const s_THUSTR_10; // = THUSTR_10; -//#define THUSTR_11 "level 11: storage facility" -extern const char* const s_THUSTR_11; // = THUSTR_11; - -//#define THUSTR_12 "level 12: crater" -extern const char* const s_THUSTR_12; // = THUSTR_12; -//#define THUSTR_13 "level 13: nukage processing" -extern const char* const s_THUSTR_13; // = THUSTR_13; -//#define THUSTR_14 "level 14: steel works" -extern const char* const s_THUSTR_14; // = THUSTR_14; -//#define THUSTR_15 "level 15: dead zone" -extern const char* const s_THUSTR_15; // = THUSTR_15; -//#define THUSTR_16 "level 16: deepest reaches" -extern const char* const s_THUSTR_16; // = THUSTR_16; -//#define THUSTR_17 "level 17: processing area" -extern const char* const s_THUSTR_17; // = THUSTR_17; -//#define THUSTR_18 "level 18: mill" -extern const char* const s_THUSTR_18; // = THUSTR_18; -//#define THUSTR_19 "level 19: shipping/respawning" -extern const char* const s_THUSTR_19; // = THUSTR_19; -//#define THUSTR_20 "level 20: central processing" -extern const char* const s_THUSTR_20; // = THUSTR_20; - -//#define THUSTR_21 "level 21: administration center" -extern const char* const s_THUSTR_21; // = THUSTR_21; -//#define THUSTR_22 "level 22: habitat" -extern const char* const s_THUSTR_22; // = THUSTR_22; -//#define THUSTR_23 "level 23: lunar mining project" -extern const char* const s_THUSTR_23; // = THUSTR_23; -//#define THUSTR_24 "level 24: quarry" -extern const char* const s_THUSTR_24; // = THUSTR_24; -//#define THUSTR_25 "level 25: baron's den" -extern const char* const s_THUSTR_25; // = THUSTR_25; -//#define THUSTR_26 "level 26: ballistyx" -extern const char* const s_THUSTR_26; // = THUSTR_26; -//#define THUSTR_27 "level 27: mount pain" -extern const char* const s_THUSTR_27; // = THUSTR_27; -//#define THUSTR_28 "level 28: heck" -extern const char* const s_THUSTR_28; // = THUSTR_28; -//#define THUSTR_29 "level 29: river styx" -extern const char* const s_THUSTR_29; // = THUSTR_29; -//#define THUSTR_30 "level 30: last call" -extern const char* const s_THUSTR_30; // = THUSTR_30; - -//#define THUSTR_31 "level 31: pharaoh" -extern const char* const s_THUSTR_31; // = THUSTR_31; -//#define THUSTR_32 "level 32: caribbean" -extern const char* const s_THUSTR_32; // = THUSTR_32; - -//#define HUSTR_CHATMACRO1 "I'm ready to kick butt!" -extern const char* const s_HUSTR_CHATMACRO1; // = HUSTR_CHATMACRO1; -//#define HUSTR_CHATMACRO2 "I'm OK." -extern const char* const s_HUSTR_CHATMACRO2; // = HUSTR_CHATMACRO2; -//#define HUSTR_CHATMACRO3 "I'm not looking too good!" -extern const char* const s_HUSTR_CHATMACRO3; // = HUSTR_CHATMACRO3; -//#define HUSTR_CHATMACRO4 "Help!" -extern const char* const s_HUSTR_CHATMACRO4; // = HUSTR_CHATMACRO4; -//#define HUSTR_CHATMACRO5 "You suck!" -extern const char* const s_HUSTR_CHATMACRO5; // = HUSTR_CHATMACRO5; -//#define HUSTR_CHATMACRO6 "Next time, scumbag..." -extern const char* const s_HUSTR_CHATMACRO6; // = HUSTR_CHATMACRO6; -//#define HUSTR_CHATMACRO7 "Come here!" -extern const char* const s_HUSTR_CHATMACRO7; // = HUSTR_CHATMACRO7; -//#define HUSTR_CHATMACRO8 "I'll take care of it." -extern const char* const s_HUSTR_CHATMACRO8; // = HUSTR_CHATMACRO8; -//#define HUSTR_CHATMACRO9 "Yes" -extern const char* const s_HUSTR_CHATMACRO9; // = HUSTR_CHATMACRO9; -//#define HUSTR_CHATMACRO0 "No" -extern const char* const s_HUSTR_CHATMACRO0; // = HUSTR_CHATMACRO0; - -//#define HUSTR_TALKTOSELF1 "You mumble to yourself" -extern const char* const s_HUSTR_TALKTOSELF1; // = HUSTR_TALKTOSELF1; -//#define HUSTR_TALKTOSELF2 "Who's there?" -extern const char* const s_HUSTR_TALKTOSELF2; // = HUSTR_TALKTOSELF2; -//#define HUSTR_TALKTOSELF3 "You scare yourself" -extern const char* const s_HUSTR_TALKTOSELF3; // = HUSTR_TALKTOSELF3; -//#define HUSTR_TALKTOSELF4 "You start to rave" -extern const char* const s_HUSTR_TALKTOSELF4; // = HUSTR_TALKTOSELF4; -//#define HUSTR_TALKTOSELF5 "You've lost it..." -extern const char* const s_HUSTR_TALKTOSELF5; // = HUSTR_TALKTOSELF5; - -//#define HUSTR_MESSAGESENT "[Message Sent]" -extern const char* const s_HUSTR_MESSAGESENT; // = HUSTR_MESSAGESENT; - -// The following should NOT be changed unless it seems -// just AWFULLY necessary - -//#define HUSTR_PLRGREEN "Green: " -extern const char* const s_HUSTR_PLRGREEN; // = HUSTR_PLRGREEN; -//#define HUSTR_PLRINDIGO "Indigo: " -extern const char* const s_HUSTR_PLRINDIGO; // = HUSTR_PLRINDIGO; -//#define HUSTR_PLRBROWN "Brown: " -extern const char* const s_HUSTR_PLRBROWN; // = HUSTR_PLRBROWN; -//#define HUSTR_PLRRED "Red: " -extern const char* const s_HUSTR_PLRRED; // = HUSTR_PLRRED; - -// -// AM_map.C -// - -//#define AMSTR_FOLLOWON "Follow Mode ON" -extern const char* const s_AMSTR_FOLLOWON; // = AMSTR_FOLLOWON; -//#define AMSTR_FOLLOWOFF "Follow Mode OFF" -extern const char* const s_AMSTR_FOLLOWOFF; // = AMSTR_FOLLOWOFF; - -//#define AMSTR_GRIDON "Grid ON" -extern const char* const s_AMSTR_GRIDON; // = AMSTR_GRIDON; -//#define AMSTR_GRIDOFF "Grid OFF" -extern const char* const s_AMSTR_GRIDOFF; // = AMSTR_GRIDOFF; - -//#define AMSTR_MARKEDSPOT "Marked Spot" -extern const char* const s_AMSTR_MARKEDSPOT; // = AMSTR_MARKEDSPOT; -//#define AMSTR_MARKSCLEARED "All Marks Cleared" -extern const char* const s_AMSTR_MARKSCLEARED; // = AMSTR_MARKSCLEARED; - -// CPhipps - automap rotate & overlay -extern const char* const s_AMSTR_ROTATEON; -extern const char* const s_AMSTR_ROTATEOFF; -extern const char* const s_AMSTR_OVERLAYON; -extern const char* const s_AMSTR_OVERLAYOFF; - -// -// ST_stuff.C -// - -//#define STSTR_MUS "Music Change" -extern const char* const s_STSTR_MUS; // = STSTR_MUS; -//#define STSTR_NOMUS "IMPOSSIBLE SELECTION" -extern const char* const s_STSTR_NOMUS; // = STSTR_NOMUS; -//#define STSTR_DQDON "Degreelessness Mode On" -extern const char* const s_STSTR_DQDON; // = STSTR_DQDON; -//#define STSTR_DQDOFF "Degreelessness Mode Off" -extern const char* const s_STSTR_DQDOFF; // = STSTR_DQDOFF; - -//#define STSTR_KFAADDED "Very Happy Ammo Added" -extern const char* const s_STSTR_KFAADDED; // = STSTR_KFAADDED; -//#define STSTR_FAADDED "Ammo (no keys) Added" -extern const char* const s_STSTR_FAADDED; // = STSTR_FAADDED; - -//#define STSTR_NCON "No Clipping Mode ON" -extern const char* const s_STSTR_NCON; // = STSTR_NCON; -//#define STSTR_NCOFF "No Clipping Mode OFF" -extern const char* const s_STSTR_NCOFF; // = STSTR_NCOFF; - -//#define STSTR_BEHOLD "inVuln, Str, Inviso, Rad, Allmap, or Lite-amp" -extern const char* const s_STSTR_BEHOLD; // = STSTR_BEHOLD; -//#define STSTR_BEHOLDX "Power-up Toggled" -extern const char* const s_STSTR_BEHOLDX; // = STSTR_BEHOLDX; - -//#define STSTR_CHOPPERS "... doesn't suck - GM" -extern const char* const s_STSTR_CHOPPERS; // = STSTR_CHOPPERS; -//#define STSTR_CLEV "Changing Level..." -extern const char* const s_STSTR_CLEV; // = STSTR_CLEV; - -// -// F_Finale.C -// -/* -#define E1TEXT \ -"Once you beat the big badasses and\n"\ -"clean out the moon base you're supposed\n"\ -"to win, aren't you? Aren't you? Where's\n"\ -"your fat reward and ticket home? What\n"\ -"the hell is this? It's not supposed to\n"\ -"end this way!\n"\ -"\n" \ -"It stinks like rotten meat, but looks\n"\ -"like the lost Deimos base. Looks like\n"\ -"you're stuck on The Shores of Hell.\n"\ -"The only way out is through.\n"\ -"\n"\ -"To continue the DOOM experience, play\n"\ -"The Shores of Hell and its amazing\n"\ -"sequel, Inferno!\n" -*/ -extern const char* const s_E1TEXT; // = E1TEXT; - - -/* -#define E2TEXT \ -"You've done it! The hideous cyber-\n"\ -"demon lord that ruled the lost Deimos\n"\ -"moon base has been slain and you\n"\ -"are triumphant! But ... where are\n"\ -"you? You clamber to the edge of the\n"\ -"moon and look down to see the awful\n"\ -"truth.\n" \ -"\n"\ -"Deimos floats above Hell itself!\n"\ -"You've never heard of anyone escaping\n"\ -"from Hell, but you'll make the bastards\n"\ -"sorry they ever heard of you! Quickly,\n"\ -"you rappel down to the surface of\n"\ -"Hell.\n"\ -"\n" \ -"Now, it's on to the final chapter of\n"\ -"DOOM! -- Inferno." -*/ -extern const char* const s_E2TEXT; // = E2TEXT; - - -/* -#define E3TEXT \ -"The loathsome spiderdemon that\n"\ -"masterminded the invasion of the moon\n"\ -"bases and caused so much death has had\n"\ -"its ass kicked for all time.\n"\ -"\n"\ -"A hidden doorway opens and you enter.\n"\ -"You've proven too tough for Hell to\n"\ -"contain, and now Hell at last plays\n"\ -"fair -- for you emerge from the door\n"\ -"to see the green fields of Earth!\n"\ -"Home at last.\n" \ -"\n"\ -"You wonder what's been happening on\n"\ -"Earth while you were battling evil\n"\ -"unleashed. It's good that no Hell-\n"\ -"spawn could have come through that\n"\ -"door with you ..." -*/ -extern const char* const s_E3TEXT; // = E3TEXT; - - -/* -#define E4TEXT \ -"the spider mastermind must have sent forth\n"\ -"its legions of hellspawn before your\n"\ -"final confrontation with that terrible\n"\ -"beast from hell. but you stepped forward\n"\ -"and brought forth eternal damnation and\n"\ -"suffering upon the horde as a true hero\n"\ -"would in the face of something so evil.\n"\ -"\n"\ -"besides, someone was gonna pay for what\n"\ -"happened to daisy, your pet rabbit.\n"\ -"\n"\ -"but now, you see spread before you more\n"\ -"potential pain and gibbitude as a nation\n"\ -"of demons run amok among our cities.\n"\ -"\n"\ -"next stop, hell on earth!" -*/ -extern const char* const s_E4TEXT; // = E4TEXT; - - -// after level 6, put this: - -/* -#define C1TEXT \ -"YOU HAVE ENTERED DEEPLY INTO THE INFESTED\n" \ -"STARPORT. BUT SOMETHING IS WRONG. THE\n" \ -"MONSTERS HAVE BROUGHT THEIR OWN REALITY\n" \ -"WITH THEM, AND THE STARPORT'S TECHNOLOGY\n" \ -"IS BEING SUBVERTED BY THEIR PRESENCE.\n" \ -"\n"\ -"AHEAD, YOU SEE AN OUTPOST OF HELL, A\n" \ -"FORTIFIED ZONE. IF YOU CAN GET PAST IT,\n" \ -"YOU CAN PENETRATE INTO THE HAUNTED HEART\n" \ -"OF THE STARBASE AND FIND THE CONTROLLING\n" \ -"SWITCH WHICH HOLDS EARTH'S POPULATION\n" \ -"HOSTAGE." -*/ -extern const char* const s_C1TEXT; // = C1TEXT; - -// After level 11, put this: - -/* -#define C2TEXT \ -"YOU HAVE WON! YOUR VICTORY HAS ENABLED\n" \ -"HUMANKIND TO EVACUATE EARTH AND ESCAPE\n"\ -"THE NIGHTMARE. NOW YOU ARE THE ONLY\n"\ -"HUMAN LEFT ON THE FACE OF THE PLANET.\n"\ -"CANNIBAL MUTATIONS, CARNIVOROUS ALIENS,\n"\ -"AND EVIL SPIRITS ARE YOUR ONLY NEIGHBORS.\n"\ -"YOU SIT BACK AND WAIT FOR DEATH, CONTENT\n"\ -"THAT YOU HAVE SAVED YOUR SPECIES.\n"\ -"\n"\ -"BUT THEN, EARTH CONTROL BEAMS DOWN A\n"\ -"MESSAGE FROM SPACE: \"SENSORS HAVE LOCATED\n"\ -"THE SOURCE OF THE ALIEN INVASION. IF YOU\n"\ -"GO THERE, YOU MAY BE ABLE TO BLOCK THEIR\n"\ -"ENTRY. THE ALIEN BASE IS IN THE HEART OF\n"\ -"YOUR OWN HOME CITY, NOT FAR FROM THE\n"\ -"STARPORT.\" SLOWLY AND PAINFULLY YOU GET\n"\ -"UP AND RETURN TO THE FRAY." -*/ -extern const char* const s_C2TEXT; // = C2TEXT; - - -// After level 20, put this: - -/* -#define C3TEXT \ -"YOU ARE AT THE CORRUPT HEART OF THE CITY,\n"\ -"SURROUNDED BY THE CORPSES OF YOUR ENEMIES.\n"\ -"YOU SEE NO WAY TO DESTROY THE CREATURES'\n"\ -"ENTRYWAY ON THIS SIDE, SO YOU CLENCH YOUR\n"\ -"TEETH AND PLUNGE THROUGH IT.\n"\ -"\n"\ -"THERE MUST BE A WAY TO CLOSE IT ON THE\n"\ -"OTHER SIDE. WHAT DO YOU CARE IF YOU'VE\n"\ -"GOT TO GO THROUGH HELL TO GET TO IT?" -*/ -extern const char* const s_C3TEXT; // = C3TEXT; - - -// After level 29, put this: - -/* -#define C4TEXT \ -"THE HORRENDOUS VISAGE OF THE BIGGEST\n"\ -"DEMON YOU'VE EVER SEEN CRUMBLES BEFORE\n"\ -"YOU, AFTER YOU PUMP YOUR ROCKETS INTO\n"\ -"HIS EXPOSED BRAIN. THE MONSTER SHRIVELS\n"\ -"UP AND DIES, ITS THRASHING LIMBS\n"\ -"DEVASTATING UNTOLD MILES OF HELL'S\n"\ -"SURFACE.\n"\ -"\n"\ -"YOU'VE DONE IT. THE INVASION IS OVER.\n"\ -"EARTH IS SAVED. HELL IS A WRECK. YOU\n"\ -"WONDER WHERE BAD FOLKS WILL GO WHEN THEY\n"\ -"DIE, NOW. WIPING THE SWEAT FROM YOUR\n"\ -"FOREHEAD YOU BEGIN THE LONG TREK BACK\n"\ -"HOME. REBUILDING EARTH OUGHT TO BE A\n"\ -"LOT MORE FUN THAN RUINING IT WAS.\n" -*/ -extern const char* const s_C4TEXT; // = C4TEXT; - - - -// Before level 31, put this: - -/* -#define C5TEXT \ -"CONGRATULATIONS, YOU'VE FOUND THE SECRET\n"\ -"LEVEL! LOOKS LIKE IT'S BEEN BUILT BY\n"\ -"HUMANS, RATHER THAN DEMONS. YOU WONDER\n"\ -"WHO THE INMATES OF THIS CORNER OF HELL\n"\ -"WILL BE." -*/ -extern const char* const s_C5TEXT; // = C5TEXT; - - -// Before level 32, put this: - -/* -#define C6TEXT \ -"CONGRATULATIONS, YOU'VE FOUND THE\n"\ -"SUPER SECRET LEVEL! YOU'D BETTER\n"\ -"BLAZE THROUGH THIS ONE!\n" -*/ -extern const char* const s_C6TEXT; // = C6TEXT; - - -// after map 06 - -/* -#define P1TEXT \ -"You gloat over the steaming carcass of the\n"\ -"Guardian. With its death, you've wrested\n"\ -"the Accelerator from the stinking claws\n"\ -"of Hell. You relax and glance around the\n"\ -"room. Damn! There was supposed to be at\n"\ -"least one working prototype, but you can't\n"\ -"see it. The demons must have taken it.\n"\ -"\n"\ -"You must find the prototype, or all your\n"\ -"struggles will have been wasted. Keep\n"\ -"moving, keep fighting, keep killing.\n"\ -"Oh yes, keep living, too." -*/ -extern const char* const s_P1TEXT; // = P1TEXT; - - -// after map 11 - -/* -#define P2TEXT \ -"Even the deadly Arch-Vile labyrinth could\n"\ -"not stop you, and you've gotten to the\n"\ -"prototype Accelerator which is soon\n"\ -"efficiently and permanently deactivated.\n"\ -"\n"\ -"You're good at that kind of thing." -*/ -extern const char* const s_P2TEXT; // = P2TEXT; - - -// after map 20 - -/* -#define P3TEXT \ -"You've bashed and battered your way into\n"\ -"the heart of the devil-hive. Time for a\n"\ -"Search-and-Destroy mission, aimed at the\n"\ -"Gatekeeper, whose foul offspring is\n"\ -"cascading to Earth. Yeah, he's bad. But\n"\ -"you know who's worse!\n"\ -"\n"\ -"Grinning evilly, you check your gear, and\n"\ -"get ready to give the bastard a little Hell\n"\ -"of your own making!" -*/ -extern const char* const s_P3TEXT; // = P3TEXT; - -// after map 30 - -/* -#define P4TEXT \ -"The Gatekeeper's evil face is splattered\n"\ -"all over the place. As its tattered corpse\n"\ -"collapses, an inverted Gate forms and\n"\ -"sucks down the shards of the last\n"\ -"prototype Accelerator, not to mention the\n"\ -"few remaining demons. You're done. Hell\n"\ -"has gone back to pounding bad dead folks \n"\ -"instead of good live ones. Remember to\n"\ -"tell your grandkids to put a rocket\n"\ -"launcher in your coffin. If you go to Hell\n"\ -"when you die, you'll need it for some\n"\ -"final cleaning-up ..." -*/ -extern const char* const s_P4TEXT; // = P4TEXT; - -// before map 31 - -/* -#define P5TEXT \ -"You've found the second-hardest level we\n"\ -"got. Hope you have a saved game a level or\n"\ -"two previous. If not, be prepared to die\n"\ -"aplenty. For master marines only." -*/ -extern const char* const s_P5TEXT; // = P5TEXT; - -// before map 32 - -/* -#define P6TEXT \ -"Betcha wondered just what WAS the hardest\n"\ -"level we had ready for ya? Now you know.\n"\ -"No one gets out alive." -*/ -extern const char* const s_P6TEXT; // = P6TEXT; - - -/* -#define T1TEXT \ -"You've fought your way out of the infested\n"\ -"experimental labs. It seems that UAC has\n"\ -"once again gulped it down. With their\n"\ -"high turnover, it must be hard for poor\n"\ -"old UAC to buy corporate health insurance\n"\ -"nowadays..\n"\ -"\n"\ -"Ahead lies the military complex, now\n"\ -"swarming with diseased horrors hot to get\n"\ -"their teeth into you. With luck, the\n"\ -"complex still has some warlike ordnance\n"\ -"laying around." -*/ -extern const char* const s_T1TEXT; // = T1TEXT; - - -/* -#define T2TEXT \ -"You hear the grinding of heavy machinery\n"\ -"ahead. You sure hope they're not stamping\n"\ -"out new hellspawn, but you're ready to\n"\ -"ream out a whole herd if you have to.\n"\ -"They might be planning a blood feast, but\n"\ -"you feel about as mean as two thousand\n"\ -"maniacs packed into one mad killer.\n"\ -"\n"\ -"You don't plan to go down easy." -*/ -extern const char* const s_T2TEXT; // = T2TEXT; - - -/* -#define T3TEXT \ -"The vista opening ahead looks real damn\n"\ -"familiar. Smells familiar, too -- like\n"\ -"fried excrement. You didn't like this\n"\ -"place before, and you sure as hell ain't\n"\ -"planning to like it now. The more you\n"\ -"brood on it, the madder you get.\n"\ -"Hefting your gun, an evil grin trickles\n"\ -"onto your face. Time to take some names." -*/ -extern const char* const s_T3TEXT; // = T3TEXT; - -/* -#define T4TEXT \ -"Suddenly, all is silent, from one horizon\n"\ -"to the other. The agonizing echo of Hell\n"\ -"fades away, the nightmare sky turns to\n"\ -"blue, the heaps of monster corpses start \n"\ -"to evaporate along with the evil stench \n"\ -"that filled the air. Jeeze, maybe you've\n"\ -"done it. Have you really won?\n"\ -"\n"\ -"Something rumbles in the distance.\n"\ -"A blue light begins to glow inside the\n"\ -"ruined skull of the demon-spitter." -*/ -extern const char* const s_T4TEXT; // = T4TEXT; - - -/* -#define T5TEXT \ -"What now? Looks totally different. Kind\n"\ -"of like King Tut's condo. Well,\n"\ -"whatever's here can't be any worse\n"\ -"than usual. Can it? Or maybe it's best\n"\ -"to let sleeping gods lie.." -*/ -extern const char* const s_T5TEXT; // = T5TEXT; - - -/* -#define T6TEXT \ -"Time for a vacation. You've burst the\n"\ -"bowels of hell and by golly you're ready\n"\ -"for a break. You mutter to yourself,\n"\ -"Maybe someone else can kick Hell's ass\n"\ -"next time around. Ahead lies a quiet town,\n"\ -"with peaceful flowing water, quaint\n"\ -"buildings, and presumably no Hellspawn.\n"\ -"\n"\ -"As you step off the transport, you hear\n"\ -"the stomp of a cyberdemon's iron shoe." -*/ -extern const char* const s_T6TEXT; // = T6TEXT; - -// -// Character cast strings F_FINALE.C -// -//#define CC_ZOMBIE "ZOMBIEMAN" -extern const char* const s_CC_ZOMBIE; // = CC_ZOMBIE; -//#define CC_SHOTGUN "SHOTGUN GUY" -extern const char* const s_CC_SHOTGUN; // = CC_SHOTGUN; -//#define CC_HEAVY "HEAVY WEAPON DUDE" -extern const char* const s_CC_HEAVY; // = CC_HEAVY; -//#define CC_IMP "IMP" -extern const char* const s_CC_IMP; // = CC_IMP; -//#define CC_DEMON "DEMON" -extern const char* const s_CC_DEMON; // = CC_DEMON; -//#define CC_LOST "LOST SOUL" -extern const char* const s_CC_LOST; // = CC_LOST; -//#define CC_CACO "CACODEMON" -extern const char* const s_CC_CACO; // = CC_CACO; -//#define CC_HELL "HELL KNIGHT" -extern const char* const s_CC_HELL; // = CC_HELL; -//#define CC_BARON "BARON OF HELL" -extern const char* const s_CC_BARON; // = CC_BARON; -//#define CC_ARACH "ARACHNOTRON" -extern const char* const s_CC_ARACH; // = CC_ARACH; -//#define CC_PAIN "PAIN ELEMENTAL" -extern const char* const s_CC_PAIN; // = CC_PAIN; -//#define CC_REVEN "REVENANT" -extern const char* const s_CC_REVEN; // = CC_REVEN; -//#define CC_MANCU "MANCUBUS" -extern const char* const s_CC_MANCU; // = CC_MANCU; -//#define CC_ARCH "ARCH-VILE" -extern const char* const s_CC_ARCH; // = CC_ARCH; -//#define CC_SPIDER "THE SPIDER MASTERMIND" -extern const char* const s_CC_SPIDER; // = CC_SPIDER; -//#define CC_CYBER "THE CYBERDEMON" -extern const char* const s_CC_CYBER; // = CC_CYBER; -//#define CC_HERO "OUR HERO" -extern const char* const s_CC_HERO; // = CC_HERO; - -// Ty 03/30/98 - new substitutions for background textures during int screens -// char* bgflatE1 = "FLOOR4_8"; -extern const char* const bgflatE1; -// char* bgflatE2 = "SFLR6_1"; -extern const char* const bgflatE2; -// char* bgflatE3 = "MFLR8_4"; -extern const char* const bgflatE3; -// char* bgflatE4 = "MFLR8_3"; -extern const char* const bgflatE4; - -// char* bgflat06 = "SLIME16"; -extern const char* const bgflat06; -// char* bgflat11 = "RROCK14"; -extern const char* const bgflat11; -// char* bgflat20 = "RROCK07"; -extern const char* const bgflat20; -// char* bgflat30 = "RROCK17"; -extern const char* const bgflat30; -// char* bgflat15 = "RROCK13"; -extern const char* const bgflat15; -// char* bgflat31 = "RROCK19"; -extern const char* const bgflat31; - -// char* bgcastcall = "BOSSBACK"; // panel behind cast call -extern const char* const bgcastcall; - -// ignored if blank, general purpose startup announcements -// char* startup1 = ""; -extern const char* const startup1; -// char* startup2 = ""; -extern const char* const startup2; -// char* startup3 = ""; -extern const char* const startup3; -// char* startup4 = ""; -extern const char* const startup4; -// char* startup5 = ""; -extern const char* const startup5; - -#endif diff --git a/components/doom/prboom/d_englsh.h b/components/doom/prboom/d_englsh.h deleted file mode 100644 index 86e74164..00000000 --- a/components/doom/prboom/d_englsh.h +++ /dev/null @@ -1,707 +0,0 @@ -/* Emacs style mode select -*- C++ -*- - *----------------------------------------------------------------------------- - * - * - * PrBoom: a Doom port merged with LxDoom and LSDLDoom - * based on BOOM, a modified and improved DOOM engine - * Copyright (C) 1999 by - * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman - * Copyright (C) 1999-2000 by - * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze - * Copyright 2005, 2006 by - * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko - * - * 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. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA. - * - * DESCRIPTION: - * Printed strings for translation. - * English language support (default). - * See dstrings.h for suggestions about foreign language BEX support - * - *-----------------------------------------------------------------------------*/ - -#ifndef __D_ENGLSH__ -#define __D_ENGLSH__ - -/* d_main.c */ -#define D_DEVSTR "Development mode ON.\n" -#define D_CDROM "CD-ROM Version: default.cfg from c:\\doomdata\n" - -/* m_menu.c */ -#define PRESSKEY "press a key." -#define PRESSYN "press y or n." -#define QUITMSG "are you sure you want to\nquit this great game?" -#define LOADNET "you can't do load while in a net game!\n\n"PRESSKEY -#define QLOADNET "you can't quickload during a netgame!\n\n"PRESSKEY -#define QSAVESPOT "you haven't picked a quicksave slot yet!\n\n"PRESSKEY -#define SAVEDEAD "you can't save if you aren't playing!\n\n"PRESSKEY -#define QSPROMPT "quicksave over your game named\n\n'%s'?\n\n"PRESSYN -#define QLPROMPT "do you want to quickload the game named\n\n'%s'?\n\n"PRESSYN - -#define NEWGAME \ - "you can't start a new game\n"\ - "while in a network game.\n\n"PRESSKEY - -#define NIGHTMARE \ - "are you sure? this skill level\n"\ - "isn't even remotely fair.\n\n"PRESSYN - -#define SWSTRING \ - "this is the shareware version of doom.\n\n"\ - "you need to order the entire trilogy.\n\n"PRESSKEY - -#define MSGOFF "Messages OFF" -#define MSGON "Messages ON" -#define NETEND "you can't end a netgame!\n\n"PRESSKEY -#define ENDGAME "are you sure you want to end the game?\n\n"PRESSYN -#define RESTARTLEVEL "restart the level?\n\n"PRESSYN - -#define DOSY "(press y to quit)" - -#define DETAILHI "High detail" -#define DETAILLO "Low detail" -#define GAMMALVL0 "Gamma correction OFF" -#define GAMMALVL1 "Gamma correction level 1" -#define GAMMALVL2 "Gamma correction level 2" -#define GAMMALVL3 "Gamma correction level 3" -#define GAMMALVL4 "Gamma correction level 4" -#define EMPTYSTRING "empty slot" - -/* p_inter.c */ -#define GOTARMOR "Picked up the armor." -#define GOTMEGA "Picked up the MegaArmor!" -#define GOTHTHBONUS "Picked up a health bonus." -#define GOTARMBONUS "Picked up an armor bonus." -#define GOTSTIM "Picked up a stimpack." -#define GOTMEDINEED "Picked up a medikit that you REALLY need!" -#define GOTMEDIKIT "Picked up a medikit." -#define GOTSUPER "Supercharge!" - -#define GOTBLUECARD "Picked up a blue keycard." -#define GOTYELWCARD "Picked up a yellow keycard." -#define GOTREDCARD "Picked up a red keycard." -#define GOTBLUESKUL "Picked up a blue skull key." -#define GOTYELWSKUL "Picked up a yellow skull key." -#define GOTREDSKULL "Picked up a red skull key." - -#define GOTINVUL "Invulnerability!" -#define GOTBERSERK "Berserk!" -#define GOTINVIS "Partial Invisibility" -#define GOTSUIT "Radiation Shielding Suit" -#define GOTMAP "Computer Area Map" -#define GOTVISOR "Light Amplification Visor" -#define GOTMSPHERE "MegaSphere!" - -#define GOTCLIP "Picked up a clip." -#define GOTCLIPBOX "Picked up a box of bullets." -#define GOTROCKET "Picked up a rocket." -#define GOTROCKBOX "Picked up a box of rockets." -#define GOTCELL "Picked up an energy cell." -#define GOTCELLBOX "Picked up an energy cell pack." -#define GOTSHELLS "Picked up 4 shotgun shells." -#define GOTSHELLBOX "Picked up a box of shotgun shells." -#define GOTBACKPACK "Picked up a backpack full of ammo!" - -#define GOTBFG9000 "You got the BFG9000! Oh, yes." -#define GOTCHAINGUN "You got the chaingun!" -#define GOTCHAINSAW "A chainsaw! Find some meat!" -#define GOTLAUNCHER "You got the rocket launcher!" -#define GOTPLASMA "You got the plasma gun!" -#define GOTSHOTGUN "You got the shotgun!" -#define GOTSHOTGUN2 "You got the super shotgun!" - -/* p_doors.c */ -#define PD_BLUEO "You need a blue key to activate this object" -#define PD_REDO "You need a red key to activate this object" -#define PD_YELLOWO "You need a yellow key to activate this object" -#define PD_BLUEK "You need a blue key to open this door" -#define PD_REDK "You need a red key to open this door" -#define PD_YELLOWK "You need a yellow key to open this door" -/* jff 02/05/98 Create messages specific to card and skull keys */ -#define PD_BLUEC "You need a blue card to open this door" -#define PD_REDC "You need a red card to open this door" -#define PD_YELLOWC "You need a yellow card to open this door" -#define PD_BLUES "You need a blue skull to open this door" -#define PD_REDS "You need a red skull to open this door" -#define PD_YELLOWS "You need a yellow skull to open this door" -#define PD_ANY "Any key will open this door" -#define PD_ALL3 "You need all three keys to open this door" -#define PD_ALL6 "You need all six keys to open this door" - -/* g_game.c */ -#define GGSAVED "game saved." - -/* hu_stuff.c */ -#define HUSTR_MSGU "[Message unsent]" - -#define HUSTR_E1M1 "E1M1: Hangar" -#define HUSTR_E1M2 "E1M2: Nuclear Plant" -#define HUSTR_E1M3 "E1M3: Toxin Refinery" -#define HUSTR_E1M4 "E1M4: Command Control" -#define HUSTR_E1M5 "E1M5: Phobos Lab" -#define HUSTR_E1M6 "E1M6: Central Processing" -#define HUSTR_E1M7 "E1M7: Computer Station" -#define HUSTR_E1M8 "E1M8: Phobos Anomaly" -#define HUSTR_E1M9 "E1M9: Military Base" - -#define HUSTR_E2M1 "E2M1: Deimos Anomaly" -#define HUSTR_E2M2 "E2M2: Containment Area" -#define HUSTR_E2M3 "E2M3: Refinery" -#define HUSTR_E2M4 "E2M4: Deimos Lab" -#define HUSTR_E2M5 "E2M5: Command Center" -#define HUSTR_E2M6 "E2M6: Halls of the Damned" -#define HUSTR_E2M7 "E2M7: Spawning Vats" -#define HUSTR_E2M8 "E2M8: Tower of Babel" -#define HUSTR_E2M9 "E2M9: Fortress of Mystery" - -#define HUSTR_E3M1 "E3M1: Hell Keep" -#define HUSTR_E3M2 "E3M2: Slough of Despair" -#define HUSTR_E3M3 "E3M3: Pandemonium" -#define HUSTR_E3M4 "E3M4: House of Pain" -#define HUSTR_E3M5 "E3M5: Unholy Cathedral" -#define HUSTR_E3M6 "E3M6: Mt. Erebus" -#define HUSTR_E3M7 "E3M7: Limbo" -#define HUSTR_E3M8 "E3M8: Dis" -#define HUSTR_E3M9 "E3M9: Warrens" - -#define HUSTR_E4M1 "E4M1: Hell Beneath" -#define HUSTR_E4M2 "E4M2: Perfect Hatred" -#define HUSTR_E4M3 "E4M3: Sever The Wicked" -#define HUSTR_E4M4 "E4M4: Unruly Evil" -#define HUSTR_E4M5 "E4M5: They Will Repent" -#define HUSTR_E4M6 "E4M6: Against Thee Wickedly" -#define HUSTR_E4M7 "E4M7: And Hell Followed" -#define HUSTR_E4M8 "E4M8: Unto The Cruel" -#define HUSTR_E4M9 "E4M9: Fear" - -#define HUSTR_1 "level 1: entryway" -#define HUSTR_2 "level 2: underhalls" -#define HUSTR_3 "level 3: the gantlet" -#define HUSTR_4 "level 4: the focus" -#define HUSTR_5 "level 5: the waste tunnels" -#define HUSTR_6 "level 6: the crusher" -#define HUSTR_7 "level 7: dead simple" -#define HUSTR_8 "level 8: tricks and traps" -#define HUSTR_9 "level 9: the pit" -#define HUSTR_10 "level 10: refueling base" -#define HUSTR_11 "level 11: 'o' of destruction!" - -#define HUSTR_12 "level 12: the factory" -#define HUSTR_13 "level 13: downtown" -#define HUSTR_14 "level 14: the inmost dens" -#define HUSTR_15 "level 15: industrial zone" -#define HUSTR_16 "level 16: suburbs" -#define HUSTR_17 "level 17: tenements" -#define HUSTR_18 "level 18: the courtyard" -#define HUSTR_19 "level 19: the citadel" -#define HUSTR_20 "level 20: gotcha!" - -#define HUSTR_21 "level 21: nirvana" -#define HUSTR_22 "level 22: the catacombs" -#define HUSTR_23 "level 23: barrels o' fun" -#define HUSTR_24 "level 24: the chasm" -#define HUSTR_25 "level 25: bloodfalls" -#define HUSTR_26 "level 26: the abandoned mines" -#define HUSTR_27 "level 27: monster condo" -#define HUSTR_28 "level 28: the spirit world" -#define HUSTR_29 "level 29: the living end" -#define HUSTR_30 "level 30: icon of sin" - -#define HUSTR_31 "level 31: wolfenstein" -#define HUSTR_32 "level 32: grosse" - -#define PHUSTR_1 "level 1: congo" -#define PHUSTR_2 "level 2: well of souls" -#define PHUSTR_3 "level 3: aztec" -#define PHUSTR_4 "level 4: caged" -#define PHUSTR_5 "level 5: ghost town" -#define PHUSTR_6 "level 6: baron's lair" -#define PHUSTR_7 "level 7: caughtyard" -#define PHUSTR_8 "level 8: realm" -#define PHUSTR_9 "level 9: abattoire" -#define PHUSTR_10 "level 10: onslaught" -#define PHUSTR_11 "level 11: hunted" - -#define PHUSTR_12 "level 12: speed" -#define PHUSTR_13 "level 13: the crypt" -#define PHUSTR_14 "level 14: genesis" -#define PHUSTR_15 "level 15: the twilight" -#define PHUSTR_16 "level 16: the omen" -#define PHUSTR_17 "level 17: compound" -#define PHUSTR_18 "level 18: neurosphere" -#define PHUSTR_19 "level 19: nme" -#define PHUSTR_20 "level 20: the death domain" - -#define PHUSTR_21 "level 21: slayer" -#define PHUSTR_22 "level 22: impossible mission" -#define PHUSTR_23 "level 23: tombstone" -#define PHUSTR_24 "level 24: the final frontier" -#define PHUSTR_25 "level 25: the temple of darkness" -#define PHUSTR_26 "level 26: bunker" -#define PHUSTR_27 "level 27: anti-christ" -#define PHUSTR_28 "level 28: the sewers" -#define PHUSTR_29 "level 29: odyssey of noises" -#define PHUSTR_30 "level 30: the gateway of hell" - -#define PHUSTR_31 "level 31: cyberden" -#define PHUSTR_32 "level 32: go 2 it" - -#define THUSTR_1 "level 1: system control" -#define THUSTR_2 "level 2: human bbq" -#define THUSTR_3 "level 3: power control" -#define THUSTR_4 "level 4: wormhole" -#define THUSTR_5 "level 5: hanger" -#define THUSTR_6 "level 6: open season" -#define THUSTR_7 "level 7: prison" -#define THUSTR_8 "level 8: metal" -#define THUSTR_9 "level 9: stronghold" -#define THUSTR_10 "level 10: redemption" -#define THUSTR_11 "level 11: storage facility" - -#define THUSTR_12 "level 12: crater" -#define THUSTR_13 "level 13: nukage processing" -#define THUSTR_14 "level 14: steel works" -#define THUSTR_15 "level 15: dead zone" -#define THUSTR_16 "level 16: deepest reaches" -#define THUSTR_17 "level 17: processing area" -#define THUSTR_18 "level 18: mill" -#define THUSTR_19 "level 19: shipping/respawning" -#define THUSTR_20 "level 20: central processing" - -#define THUSTR_21 "level 21: administration center" -#define THUSTR_22 "level 22: habitat" -#define THUSTR_23 "level 23: lunar mining project" -#define THUSTR_24 "level 24: quarry" -#define THUSTR_25 "level 25: baron's den" -#define THUSTR_26 "level 26: ballistyx" -#define THUSTR_27 "level 27: mount pain" -#define THUSTR_28 "level 28: heck" -#define THUSTR_29 "level 29: river styx" -#define THUSTR_30 "level 30: last call" - -#define THUSTR_31 "level 31: pharaoh" -#define THUSTR_32 "level 32: caribbean" - -#define HUSTR_CHATMACRO1 "I'm ready to kick butt!" -#define HUSTR_CHATMACRO2 "I'm OK." -#define HUSTR_CHATMACRO3 "I'm not looking too good!" -#define HUSTR_CHATMACRO4 "Help!" -#define HUSTR_CHATMACRO5 "You suck!" -#define HUSTR_CHATMACRO6 "Next time, scumbag..." -#define HUSTR_CHATMACRO7 "Come here!" -#define HUSTR_CHATMACRO8 "I'll take care of it." -#define HUSTR_CHATMACRO9 "Yes" -#define HUSTR_CHATMACRO0 "No" - -#define HUSTR_TALKTOSELF1 "You mumble to yourself" -#define HUSTR_TALKTOSELF2 "Who's there?" -#define HUSTR_TALKTOSELF3 "You scare yourself" -#define HUSTR_TALKTOSELF4 "You start to rave" -#define HUSTR_TALKTOSELF5 "You've lost it..." - -#define HUSTR_MESSAGESENT "[Message Sent]" - -/* The following should NOT be changed unless it seems - * just AWFULLY necessary */ - -#define HUSTR_PLRGREEN "Player 1: " -#define HUSTR_PLRINDIGO "Player 2: " -#define HUSTR_PLRBROWN "Player 3: " -#define HUSTR_PLRRED "Player 4: " - -#define HUSTR_KEYGREEN 'g' -#define HUSTR_KEYINDIGO 'i' -#define HUSTR_KEYBROWN 'b' -#define HUSTR_KEYRED 'r' - -/* am_map.c */ - -#define AMSTR_FOLLOWON "Follow Mode ON" -#define AMSTR_FOLLOWOFF "Follow Mode OFF" - -#define AMSTR_GRIDON "Grid ON" -#define AMSTR_GRIDOFF "Grid OFF" - -#define AMSTR_MARKEDSPOT "Marked Spot" -#define AMSTR_MARKSCLEARED "All Marks Cleared" - -#define AMSTR_ROTATEON "Rotate Mode ON" -#define AMSTR_ROTATEOFF "Rotate Mode OFF" - -#define AMSTR_OVERLAYON "Overlay Mode ON" -#define AMSTR_OVERLAYOFF "Overlay Mode OFF" - -/* st_stuff.c */ - -#define STSTR_MUS "Music Change" -#define STSTR_NOMUS "IMPOSSIBLE SELECTION" -#define STSTR_DQDON "Degreelessness Mode On" -#define STSTR_DQDOFF "Degreelessness Mode Off" - -#define STSTR_KFAADDED "Very Happy Ammo Added" -#define STSTR_FAADDED "Ammo (no keys) Added" - -#define STSTR_NCON "No Clipping Mode ON" -#define STSTR_NCOFF "No Clipping Mode OFF" - -#define STSTR_BEHOLD "inVuln, Str, Inviso, Rad, Allmap, or Lite-amp" -#define STSTR_BEHOLDX "Power-up Toggled" - -#define STSTR_CHOPPERS "... doesn't suck - GM" -#define STSTR_CLEV "Changing Level..." - -#define STSTR_COMPON "Compatibility Mode On" /* phares */ -#define STSTR_COMPOFF "Compatibility Mode Off" /* phares */ - -/* f_finale.c */ - -#define E1TEXT \ - "Once you beat the big badasses and\n"\ - "clean out the moon base you're supposed\n"\ - "to win, aren't you? Aren't you? Where's\n"\ - "your fat reward and ticket home? What\n"\ - "the hell is this? It's not supposed to\n"\ - "end this way!\n"\ - "\n" \ - "It stinks like rotten meat, but looks\n"\ - "like the lost Deimos base. Looks like\n"\ - "you're stuck on The Shores of Hell.\n"\ - "The only way out is through.\n"\ - "\n"\ - "To continue the DOOM experience, play\n"\ - "The Shores of Hell and its amazing\n"\ - "sequel, Inferno!\n" - - -#define E2TEXT \ - "You've done it! The hideous cyber-\n"\ - "demon lord that ruled the lost Deimos\n"\ - "moon base has been slain and you\n"\ - "are triumphant! But ... where are\n"\ - "you? You clamber to the edge of the\n"\ - "moon and look down to see the awful\n"\ - "truth.\n" \ - "\n"\ - "Deimos floats above Hell itself!\n"\ - "You've never heard of anyone escaping\n"\ - "from Hell, but you'll make the bastards\n"\ - "sorry they ever heard of you! Quickly,\n"\ - "you rappel down to the surface of\n"\ - "Hell.\n"\ - "\n" \ - "Now, it's on to the final chapter of\n"\ - "DOOM! -- Inferno." - - -#define E3TEXT \ - "The loathsome spiderdemon that\n"\ - "masterminded the invasion of the moon\n"\ - "bases and caused so much death has had\n"\ - "its ass kicked for all time.\n"\ - "\n"\ - "A hidden doorway opens and you enter.\n"\ - "You've proven too tough for Hell to\n"\ - "contain, and now Hell at last plays\n"\ - "fair -- for you emerge from the door\n"\ - "to see the green fields of Earth!\n"\ - "Home at last.\n" \ - "\n"\ - "You wonder what's been happening on\n"\ - "Earth while you were battling evil\n"\ - "unleashed. It's good that no Hell-\n"\ - "spawn could have come through that\n"\ - "door with you ..." - - -#define E4TEXT \ - "the spider mastermind must have sent forth\n"\ - "its legions of hellspawn before your\n"\ - "final confrontation with that terrible\n"\ - "beast from hell. but you stepped forward\n"\ - "and brought forth eternal damnation and\n"\ - "suffering upon the horde as a true hero\n"\ - "would in the face of something so evil.\n"\ - "\n"\ - "besides, someone was gonna pay for what\n"\ - "happened to daisy, your pet rabbit.\n"\ - "\n"\ - "but now, you see spread before you more\n"\ - "potential pain and gibbitude as a nation\n"\ - "of demons run amok among our cities.\n"\ - "\n"\ - "next stop, hell on earth!" - - -/* after level 6, put this: */ - -#define C1TEXT \ - "YOU HAVE ENTERED DEEPLY INTO THE INFESTED\n" \ - "STARPORT. BUT SOMETHING IS WRONG. THE\n" \ - "MONSTERS HAVE BROUGHT THEIR OWN REALITY\n" \ - "WITH THEM, AND THE STARPORT'S TECHNOLOGY\n" \ - "IS BEING SUBVERTED BY THEIR PRESENCE.\n" \ - "\n"\ - "AHEAD, YOU SEE AN OUTPOST OF HELL, A\n" \ - "FORTIFIED ZONE. IF YOU CAN GET PAST IT,\n" \ - "YOU CAN PENETRATE INTO THE HAUNTED HEART\n" \ - "OF THE STARBASE AND FIND THE CONTROLLING\n" \ - "SWITCH WHICH HOLDS EARTH'S POPULATION\n" \ - "HOSTAGE." - -/* After level 11, put this: */ - -#define C2TEXT \ - "YOU HAVE WON! YOUR VICTORY HAS ENABLED\n" \ - "HUMANKIND TO EVACUATE EARTH AND ESCAPE\n"\ - "THE NIGHTMARE. NOW YOU ARE THE ONLY\n"\ - "HUMAN LEFT ON THE FACE OF THE PLANET.\n"\ - "CANNIBAL MUTATIONS, CARNIVOROUS ALIENS,\n"\ - "AND EVIL SPIRITS ARE YOUR ONLY NEIGHBORS.\n"\ - "YOU SIT BACK AND WAIT FOR DEATH, CONTENT\n"\ - "THAT YOU HAVE SAVED YOUR SPECIES.\n"\ - "\n"\ - "BUT THEN, EARTH CONTROL BEAMS DOWN A\n"\ - "MESSAGE FROM SPACE: \"SENSORS HAVE LOCATED\n"\ - "THE SOURCE OF THE ALIEN INVASION. IF YOU\n"\ - "GO THERE, YOU MAY BE ABLE TO BLOCK THEIR\n"\ - "ENTRY. THE ALIEN BASE IS IN THE HEART OF\n"\ - "YOUR OWN HOME CITY, NOT FAR FROM THE\n"\ - "STARPORT.\" SLOWLY AND PAINFULLY YOU GET\n"\ - "UP AND RETURN TO THE FRAY." - - -/* After level 20, put this: */ - -#define C3TEXT \ - "YOU ARE AT THE CORRUPT HEART OF THE CITY,\n"\ - "SURROUNDED BY THE CORPSES OF YOUR ENEMIES.\n"\ - "YOU SEE NO WAY TO DESTROY THE CREATURES'\n"\ - "ENTRYWAY ON THIS SIDE, SO YOU CLENCH YOUR\n"\ - "TEETH AND PLUNGE THROUGH IT.\n"\ - "\n"\ - "THERE MUST BE A WAY TO CLOSE IT ON THE\n"\ - "OTHER SIDE. WHAT DO YOU CARE IF YOU'VE\n"\ - "GOT TO GO THROUGH HELL TO GET TO IT?" - - -/* After level 29, put this: */ - -#define C4TEXT \ - "THE HORRENDOUS VISAGE OF THE BIGGEST\n"\ - "DEMON YOU'VE EVER SEEN CRUMBLES BEFORE\n"\ - "YOU, AFTER YOU PUMP YOUR ROCKETS INTO\n"\ - "HIS EXPOSED BRAIN. THE MONSTER SHRIVELS\n"\ - "UP AND DIES, ITS THRASHING LIMBS\n"\ - "DEVASTATING UNTOLD MILES OF HELL'S\n"\ - "SURFACE.\n"\ - "\n"\ - "YOU'VE DONE IT. THE INVASION IS OVER.\n"\ - "EARTH IS SAVED. HELL IS A WRECK. YOU\n"\ - "WONDER WHERE BAD FOLKS WILL GO WHEN THEY\n"\ - "DIE, NOW. WIPING THE SWEAT FROM YOUR\n"\ - "FOREHEAD YOU BEGIN THE LONG TREK BACK\n"\ - "HOME. REBUILDING EARTH OUGHT TO BE A\n"\ - "LOT MORE FUN THAN RUINING IT WAS.\n" - -/* Before level 31, put this: */ - -#define C5TEXT \ - "CONGRATULATIONS, YOU'VE FOUND THE SECRET\n"\ - "LEVEL! LOOKS LIKE IT'S BEEN BUILT BY\n"\ - "HUMANS, RATHER THAN DEMONS. YOU WONDER\n"\ - "WHO THE INMATES OF THIS CORNER OF HELL\n"\ - "WILL BE." - - -/* Before level 32, put this: */ - -#define C6TEXT \ - "CONGRATULATIONS, YOU'VE FOUND THE\n"\ - "SUPER SECRET LEVEL! YOU'D BETTER\n"\ - "BLAZE THROUGH THIS ONE!\n" - -/*** Plutonia ***/ -/* after map 06 */ - -#define P1TEXT \ - "You gloat over the steaming carcass of the\n"\ - "Guardian. With its death, you've wrested\n"\ - "the Accelerator from the stinking claws\n"\ - "of Hell. You relax and glance around the\n"\ - "room. Damn! There was supposed to be at\n"\ - "least one working prototype, but you can't\n"\ - "see it. The demons must have taken it.\n"\ - "\n"\ - "You must find the prototype, or all your\n"\ - "struggles will have been wasted. Keep\n"\ - "moving, keep fighting, keep killing.\n"\ - "Oh yes, keep living, too." - - -/* after map 11 */ - -#define P2TEXT \ - "Even the deadly Arch-Vile labyrinth could\n"\ - "not stop you, and you've gotten to the\n"\ - "prototype Accelerator which is soon\n"\ - "efficiently and permanently deactivated.\n"\ - "\n"\ - "You're good at that kind of thing." - - -/* after map 20 */ - -#define P3TEXT \ - "You've bashed and battered your way into\n"\ - "the heart of the devil-hive. Time for a\n"\ - "Search-and-Destroy mission, aimed at the\n"\ - "Gatekeeper, whose foul offspring is\n"\ - "cascading to Earth. Yeah, he's bad. But\n"\ - "you know who's worse!\n"\ - "\n"\ - "Grinning evilly, you check your gear, and\n"\ - "get ready to give the bastard a little Hell\n"\ - "of your own making!" - -/* after map 30 */ - -#define P4TEXT \ - "The Gatekeeper's evil face is splattered\n"\ - "all over the place. As its tattered corpse\n"\ - "collapses, an inverted Gate forms and\n"\ - "sucks down the shards of the last\n"\ - "prototype Accelerator, not to mention the\n"\ - "few remaining demons. You're done. Hell\n"\ - "has gone back to pounding bad dead folks \n"\ - "instead of good live ones. Remember to\n"\ - "tell your grandkids to put a rocket\n"\ - "launcher in your coffin. If you go to Hell\n"\ - "when you die, you'll need it for some\n"\ - "final cleaning-up ..." - -/* before map 31 */ - -#define P5TEXT \ - "You've found the second-hardest level we\n"\ - "got. Hope you have a saved game a level or\n"\ - "two previous. If not, be prepared to die\n"\ - "aplenty. For master marines only." - -/* before map 32 */ - -#define P6TEXT \ - "Betcha wondered just what WAS the hardest\n"\ - "level we had ready for ya? Now you know.\n"\ - "No one gets out alive." - -/*** TNT: Evilution ***/ - -#define T1TEXT \ - "You've fought your way out of the infested\n"\ - "experimental labs. It seems that UAC has\n"\ - "once again gulped it down. With their\n"\ - "high turnover, it must be hard for poor\n"\ - "old UAC to buy corporate health insurance\n"\ - "nowadays..\n"\ - "\n"\ - "Ahead lies the military complex, now\n"\ - "swarming with diseased horrors hot to get\n"\ - "their teeth into you. With luck, the\n"\ - "complex still has some warlike ordnance\n"\ - "laying around." - - -#define T2TEXT \ - "You hear the grinding of heavy machinery\n"\ - "ahead. You sure hope they're not stamping\n"\ - "out new hellspawn, but you're ready to\n"\ - "ream out a whole herd if you have to.\n"\ - "They might be planning a blood feast, but\n"\ - "you feel about as mean as two thousand\n"\ - "maniacs packed into one mad killer.\n"\ - "\n"\ - "You don't plan to go down easy." - - -#define T3TEXT \ - "The vista opening ahead looks real damn\n"\ - "familiar. Smells familiar, too -- like\n"\ - "fried excrement. You didn't like this\n"\ - "place before, and you sure as hell ain't\n"\ - "planning to like it now. The more you\n"\ - "brood on it, the madder you get.\n"\ - "Hefting your gun, an evil grin trickles\n"\ - "onto your face. Time to take some names." - -#define T4TEXT \ - "Suddenly, all is silent, from one horizon\n"\ - "to the other. The agonizing echo of Hell\n"\ - "fades away, the nightmare sky turns to\n"\ - "blue, the heaps of monster corpses start \n"\ - "to evaporate along with the evil stench \n"\ - "that filled the air. Jeeze, maybe you've\n"\ - "done it. Have you really won?\n"\ - "\n"\ - "Something rumbles in the distance.\n"\ - "A blue light begins to glow inside the\n"\ - "ruined skull of the demon-spitter." - - -#define T5TEXT \ - "What now? Looks totally different. Kind\n"\ - "of like King Tut's condo. Well,\n"\ - "whatever's here can't be any worse\n"\ - "than usual. Can it? Or maybe it's best\n"\ - "to let sleeping gods lie.." - - -#define T6TEXT \ - "Time for a vacation. You've burst the\n"\ - "bowels of hell and by golly you're ready\n"\ - "for a break. You mutter to yourself,\n"\ - "Maybe someone else can kick Hell's ass\n"\ - "next time around. Ahead lies a quiet town,\n"\ - "with peaceful flowing water, quaint\n"\ - "buildings, and presumably no Hellspawn.\n"\ - "\n"\ - "As you step off the transport, you hear\n"\ - "the stomp of a cyberdemon's iron shoe." - - - -/* - * Character cast strings F_FINALE.C - */ -#define CC_ZOMBIE "ZOMBIEMAN" -#define CC_SHOTGUN "SHOTGUN GUY" -#define CC_HEAVY "HEAVY WEAPON DUDE" -#define CC_IMP "IMP" -#define CC_DEMON "DEMON" -#define CC_LOST "LOST SOUL" -#define CC_CACO "CACODEMON" -#define CC_HELL "HELL KNIGHT" -#define CC_BARON "BARON OF HELL" -#define CC_ARACH "ARACHNOTRON" -#define CC_PAIN "PAIN ELEMENTAL" -#define CC_REVEN "REVENANT" -#define CC_MANCU "MANCUBUS" -#define CC_ARCH "ARCH-VILE" -#define CC_SPIDER "THE SPIDER MASTERMIND" -#define CC_CYBER "THE CYBERDEMON" -#define CC_HERO "OUR HERO" - - -#endif diff --git a/components/doom/prboom/d_event.h b/components/doom/prboom/d_event.h deleted file mode 100644 index da5e702b..00000000 --- a/components/doom/prboom/d_event.h +++ /dev/null @@ -1,125 +0,0 @@ -/* Emacs style mode select -*- C++ -*- - *----------------------------------------------------------------------------- - * - * - * PrBoom: a Doom port merged with LxDoom and LSDLDoom - * based on BOOM, a modified and improved DOOM engine - * Copyright (C) 1999 by - * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman - * Copyright (C) 1999-2000 by - * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze - * Copyright 2005, 2006 by - * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko - * - * 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. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA. - * - * DESCRIPTION: - * Event information structures. - * - *-----------------------------------------------------------------------------*/ - - -#ifndef __D_EVENT__ -#define __D_EVENT__ - - -#include "doomtype.h" - - -// -// Event handling. -// - -// Input event types. -typedef enum -{ - ev_keydown, - ev_keyup, - ev_mouse, - ev_joystick -} evtype_t; - -// Event structure. -typedef struct -{ - evtype_t type; - int data1; // keys / mouse/joystick buttons - int data2; // mouse/joystick x move - int data3; // mouse/joystick y move -} event_t; - - -typedef enum -{ - ga_nothing, - ga_loadlevel, - ga_newgame, - ga_loadgame, - ga_savegame, - ga_playdemo, - ga_completed, - ga_victory, - ga_worlddone, -} gameaction_t; - - - -// -// Button/action code definitions. -// -typedef enum -{ - // Press "Fire". - BT_ATTACK = 1, - - // Use button, to open doors, activate switches. - BT_USE = 2, - - // Flag: game events, not really buttons. - BT_SPECIAL = 128, - BT_SPECIALMASK = 3, - - // Flag, weapon change pending. - // If true, the next 4 bits hold weapon num. - BT_CHANGE = 4, - - // The 4bit weapon mask and shift, convenience. -//BT_WEAPONMASK = (8+16+32), - BT_WEAPONMASK = (8+16+32+64), // extended to pick up SSG // phares - BT_WEAPONSHIFT = 3, - - // Special events - BTS_LOADGAME = 0, // Loads a game - // Pause the game. - BTS_PAUSE = 1, - // Save the game at each console. - BTS_SAVEGAME = 2, - BTS_RESTARTLEVEL= 3, // Restarts the current level - - // Savegame slot numbers occupy the second byte of buttons. - BTS_SAVEMASK = (4+8+16), - BTS_SAVESHIFT = 2, - -} buttoncode_t; - - -// -// GLOBAL VARIABLES -// - -extern gameaction_t gameaction; - -#endif diff --git a/components/doom/prboom/d_items.c b/components/doom/prboom/d_items.c deleted file mode 100644 index 5adc28df..00000000 --- a/components/doom/prboom/d_items.c +++ /dev/null @@ -1,140 +0,0 @@ -/* Emacs style mode select -*- C++ -*- - *----------------------------------------------------------------------------- - * - * - * PrBoom: a Doom port merged with LxDoom and LSDLDoom - * based on BOOM, a modified and improved DOOM engine - * Copyright (C) 1999 by - * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman - * Copyright (C) 1999-2000 by - * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze - * Copyright 2005, 2006 by - * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko - * - * 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. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA. - * - * DESCRIPTION: - * Something to do with weapon sprite frames. Don't ask me. - * - *----------------------------------------------------------------------------- - */ - -// We are referring to sprite numbers. -#include "doomtype.h" -#include "info.h" - -#ifdef __GNUG__ -#pragma implementation "d_items.h" -#endif -#include "d_items.h" - - -// -// PSPRITE ACTIONS for waepons. -// This struct controls the weapon animations. -// -// Each entry is: -// ammo/amunition type -// upstate -// downstate -// readystate -// atkstate, i.e. attack/fire/hit frame -// flashstate, muzzle flash -// -weaponinfo_t weaponinfo[NUMWEAPONS] = -{ - { - // fist - am_noammo, - S_PUNCHUP, - S_PUNCHDOWN, - S_PUNCH, - S_PUNCH1, - S_NULL - }, - { - // pistol - am_clip, - S_PISTOLUP, - S_PISTOLDOWN, - S_PISTOL, - S_PISTOL1, - S_PISTOLFLASH - }, - { - // shotgun - am_shell, - S_SGUNUP, - S_SGUNDOWN, - S_SGUN, - S_SGUN1, - S_SGUNFLASH1 - }, - { - // chaingun - am_clip, - S_CHAINUP, - S_CHAINDOWN, - S_CHAIN, - S_CHAIN1, - S_CHAINFLASH1 - }, - { - // missile launcher - am_misl, - S_MISSILEUP, - S_MISSILEDOWN, - S_MISSILE, - S_MISSILE1, - S_MISSILEFLASH1 - }, - { - // plasma rifle - am_cell, - S_PLASMAUP, - S_PLASMADOWN, - S_PLASMA, - S_PLASMA1, - S_PLASMAFLASH1 - }, - { - // bfg 9000 - am_cell, - S_BFGUP, - S_BFGDOWN, - S_BFG, - S_BFG1, - S_BFGFLASH1 - }, - { - // chainsaw - am_noammo, - S_SAWUP, - S_SAWDOWN, - S_SAW, - S_SAW1, - S_NULL - }, - { - // super shotgun - am_shell, - S_DSGUNUP, - S_DSGUNDOWN, - S_DSGUN, - S_DSGUN1, - S_DSGUNFLASH1 - }, -}; diff --git a/components/doom/prboom/d_items.h b/components/doom/prboom/d_items.h deleted file mode 100644 index 8da4df29..00000000 --- a/components/doom/prboom/d_items.h +++ /dev/null @@ -1,59 +0,0 @@ -/* Emacs style mode select -*- C++ -*- - *----------------------------------------------------------------------------- - * - * - * PrBoom: a Doom port merged with LxDoom and LSDLDoom - * based on BOOM, a modified and improved DOOM engine - * Copyright (C) 1999 by - * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman - * Copyright (C) 1999-2000 by - * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze - * Copyright 2005, 2006 by - * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko - * - * 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. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA. - * - * DESCRIPTION: - * Items: key cards, artifacts, weapon, ammunition. - * - *-----------------------------------------------------------------------------*/ - - -#ifndef __D_ITEMS__ -#define __D_ITEMS__ - -#include "doomdef.h" - -#ifdef __GNUG__ -#pragma interface -#endif - - -/* Weapon info: sprite frames, ammunition use. */ -typedef struct -{ - ammotype_t ammo; - int upstate; - int downstate; - int readystate; - int atkstate; - int flashstate; - -} weaponinfo_t; - -extern weaponinfo_t weaponinfo[NUMWEAPONS]; - -#endif diff --git a/components/doom/prboom/d_main.c b/components/doom/prboom/d_main.c deleted file mode 100644 index d147cc62..00000000 --- a/components/doom/prboom/d_main.c +++ /dev/null @@ -1,1070 +0,0 @@ -/* Emacs style mode select -*- C++ -*- - *----------------------------------------------------------------------------- - * - * - * PrBoom: a Doom port merged with LxDoom and LSDLDoom - * based on BOOM, a modified and improved DOOM engine - * Copyright (C) 1999 by - * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman - * Copyright (C) 1999-2004 by - * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze - * Copyright 2005, 2006 by - * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko - * - * 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. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA. - * - * DESCRIPTION: - * DOOM main program (D_DoomMain) and game loop (D_DoomLoop), - * plus functions to determine game mode (shareware, registered), - * parse command line parameters, configure game parameters (turbo), - * and call the startup functions. - * - *----------------------------------------------------------------------------- - */ - - -#include -#include -#include -#include - -#include "doomdef.h" -#include "doomtype.h" -#include "doomstat.h" -#include "d_net.h" -#include "dstrings.h" -#include "sounds.h" -#include "z_zone.h" -#include "w_wad.h" -#include "s_sound.h" -#include "v_video.h" -#include "f_finale.h" -#include "f_wipe.h" -#include "m_argv.h" -#include "m_misc.h" -#include "m_menu.h" -#include "i_main.h" -#include "i_system.h" -#include "i_sound.h" -#include "i_video.h" -#include "g_game.h" -#include "hu_stuff.h" -#include "wi_stuff.h" -#include "st_stuff.h" -#include "am_map.h" -#include "p_setup.h" -#include "r_draw.h" -#include "r_main.h" -#include "r_fps.h" -#include "d_main.h" -#include "d_deh.h" // Ty 04/08/98 - Externalizations -#include "lprintf.h" // jff 08/03/98 - declaration of lprintf -#include "am_map.h" - -boolean devparm; // started game with -devparm - -// jff 1/24/98 add new versions of these variables to remember command line -boolean clnomonsters; // checkparm of -nomonsters -boolean clrespawnparm; // checkparm of -respawn -boolean clfastparm; // checkparm of -fast -// jff 1/24/98 end definition of command line version of play mode switches - -boolean nomonsters; // working -nomonsters -boolean respawnparm; // working -respawn -boolean fastparm; // working -fast - -boolean singletics = false; // debug flag to cancel adaptiveness - -//jff 1/22/98 parms for disabling music and sound -boolean nosfxparm; -boolean nomusicparm; - -//jff 4/18/98 -extern boolean inhelpscreens; - -skill_t startskill; -int startepisode; -int startmap; -boolean autostart; -int ffmap; - -boolean advancedemo; - -const char *basesavegame; - -static int demosequence; // killough 5/2/98: made static -static int pagetic; -static const char *pagename; // CPhipps - const - -// wipegamestate can be set to -1 to force a wipe on the next draw -gamestate_t wipegamestate = GS_DEMOSCREEN; -extern boolean setsizeneeded; -extern int showMessages; - -//jff 4/19/98 list of standard IWAD names -const char *standard_iwads[]= -{ - "doom.wad", // Ultimate DOOM - "plutonia.wad", // Final DOOM - The Plutonia Experiment - "tnt.wad", // Final Doom - TNT: Evilution - "doom2.wad", // DOOM2 - "doom2f.wad", // DOOM2 French - "doom1.wad", // DOOM Shareware - "freedoom.wad", /* wart@kobold.org: added freedoom for Fedora Extras */ - NULL, -}; - -/* - * D_PostEvent - Event handling - * - * Called by I/O functions when an event is received. - * Try event handlers for each code area in turn. - * cph - in the true spirit of the Boom source, let the - * short ciruit operator madness begin! - */ - -void D_PostEvent(event_t *ev) -{ - /* cph - suppress all input events at game start - * FIXME: This is a lousy kludge */ - if (gametic < 3) return; - - if (M_Responder(ev)) - return; - - if (gamestate == GS_LEVEL) { - if (HU_Responder(ev)) - return; - if (ST_Responder(ev)) - return; - if (AM_Responder(ev)) - return; - } - - G_Responder(ev); -} - -// -// D_Wipe -// -// CPhipps - moved the screen wipe code from D_Display to here -// The screens to wipe between are already stored, this just does the timing -// and screen updating - -static void D_Wipe(void) -{ - boolean done; - int wipestart = I_GetTime () - 1; - - do - { - int nowtime, tics; - do - { - I_uSleep(5000); // CPhipps - don't thrash cpu in this loop - nowtime = I_GetTime(); - tics = nowtime - wipestart; - } - while (!tics); - wipestart = nowtime; - done = wipe_ScreenWipe(tics); - I_UpdateNoBlit(); - M_Drawer(); // menu is drawn even on top of wipes - I_FinishUpdate(); // page flip or blit buffer - } - while (!done); -} - -// -// D_PageDrawer -// -static void D_PageDrawer(void) -{ - // proff/nicolas 09/14/98 -- now stretchs bitmaps to fullscreen! - // CPhipps - updated for new patch drawing - // proff - added M_DrawCredits - if (pagename) - V_DrawNamePatch(0, 0, 0, pagename, CR_DEFAULT, VPT_STRETCH); - else - M_DrawCredits(); -} - -// -// D_Display -// draw current display, possibly wiping it from the previous -// - -void D_Display (void) -{ - static boolean isborderstate = false; - static boolean borderwillneedredraw = false; - static gamestate_t oldgamestate = -1; - boolean wipe = gamestate != wipegamestate; - boolean viewactive = false, isborder = false; - - if (nodrawers) // for comparative timing / profiling - return; - - if (!I_StartDisplay()) - return; - - // save the current screen if about to wipe - if (wipe) - wipe_StartScreen(); - - if (gamestate != GS_LEVEL) { // Not a level - switch (oldgamestate) { - case -1: - case GS_LEVEL: - V_SetPalette(0); // cph - use default (basic) palette - default: - break; - } - - switch (gamestate) { - case GS_INTERMISSION: - WI_Drawer(); - break; - case GS_FINALE: - F_Drawer(); - break; - case GS_DEMOSCREEN: - D_PageDrawer(); - break; - default: - break; - } - } else if (gametic != basetic) { // In a level - boolean redrawborderstuff; - - HU_Erase(); - - if (setsizeneeded) { // change the view size if needed - R_ExecuteSetViewSize(); - oldgamestate = -1; // force background redraw - } - - // Work out if the player view is visible, and if there is a border - viewactive = (!(automapmode & am_active) || (automapmode & am_overlay)) && !inhelpscreens; - isborder = viewactive ? (viewheight != SCREENHEIGHT) : (!inhelpscreens && (automapmode & am_active)); - - if (oldgamestate != GS_LEVEL) { - R_FillBackScreen (); // draw the pattern into the back screen - redrawborderstuff = isborder; - } else { - // CPhipps - - // If there is a border, and either there was no border last time, - // or the border might need refreshing, then redraw it. - redrawborderstuff = isborder && (!isborderstate || borderwillneedredraw); - // The border may need redrawing next time if the border surrounds the screen, - // and there is a menu being displayed - borderwillneedredraw = menuactive && isborder && viewactive && (viewwidth != SCREENWIDTH); - } - if (redrawborderstuff) - R_DrawViewBorder(); - - // Now do the drawing - if (viewactive) - R_RenderPlayerView (&players[displayplayer]); - if (automapmode & am_active) - AM_Drawer(); - ST_Drawer((viewheight != SCREENHEIGHT) || ((automapmode & am_active) && !(automapmode & am_overlay)), redrawborderstuff); - R_DrawViewBorder(); - HU_Drawer(); - } - - isborderstate = isborder; - oldgamestate = wipegamestate = gamestate; - - // draw pause pic - if (paused) { - // Simplified the "logic" here and no need for x-coord caching - POPE - V_DrawNamePatch((320 - V_NamePatchWidth("M_PAUSE"))/2, 4, - 0, "M_PAUSE", CR_DEFAULT, VPT_STRETCH); - } - - // menus go directly to the screen - M_Drawer(); // menu is drawn even on top of everything -#ifdef HAVE_NET - NetUpdate(); // send out any new accumulation -#else - D_BuildNewTiccmds(); -#endif - - // normal update - if (!wipe) - I_FinishUpdate (); // page flip or blit buffer - else { - // wipe update - wipe_EndScreen(); - D_Wipe(); - } - - I_EndDisplay(); - - //e6y: don't thrash cpu during pausing - if (paused) { - I_uSleep(1000); - } -} - -// -// D_DoomLoop() -// -// Not a globally visible function, -// just included for source reference, -// called by D_DoomMain, never exits. -// Manages timing and IO, -// calls all ?_Responder, ?_Ticker, and ?_Drawer, -// calls I_GetTime, I_StartFrame, and I_StartTic -// - -static void D_DoomLoop(void) -{ - for (;;) - { - WasRenderedInTryRunTics = false; - // frame syncronous IO operations - I_StartFrame (); - - if (ffmap == gamemap) ffmap = 0; - - // process one or more tics - if (singletics) - { - I_StartTic (); - G_BuildTiccmd (&netcmds[consoleplayer][maketic%BACKUPTICS]); - if (advancedemo) - D_DoAdvanceDemo (); - M_Ticker (); - G_Ticker (); - gametic++; - maketic++; - } - else - TryRunTics (); // will run at least one tic - - // killough 3/16/98: change consoleplayer to displayplayer - if (players[displayplayer].mo) // cph 2002/08/10 - S_UpdateSounds(players[displayplayer].mo);// move positional sounds - - // Update display, next frame, with current state. - if (!movement_smooth || !WasRenderedInTryRunTics || gamestate != wipegamestate) - D_Display(); - } -} - -// -// DEMO LOOP -// - -// -// D_PageTicker -// Handles timing for warped projection -// -void D_PageTicker(void) -{ - if (--pagetic < 0) - D_AdvanceDemo(); -} - -// -// D_AdvanceDemo -// Called after each demo or intro demosequence finishes -// -void D_AdvanceDemo (void) -{ - advancedemo = true; -} - -/* killough 11/98: functions to perform demo sequences - * cphipps 10/99: constness fixes - */ - -static void D_SetPageName(const char *name) -{ - pagename = name; -} - -static void D_DrawTitle1(const char *name) -{ - S_StartMusic(mus_intro); - pagetic = (TICRATE*170)/35; - D_SetPageName(name); -} - -static void D_DrawTitle2(const char *name) -{ - S_StartMusic(mus_dm2ttl); - D_SetPageName(name); -} - -/* killough 11/98: tabulate demo sequences - */ - -static struct -{ - void (*func)(const char *); - const char *name; -} const demostates[][4] = - { - { - {D_DrawTitle1, "TITLEPIC"}, - {D_DrawTitle1, "TITLEPIC"}, - {D_DrawTitle2, "TITLEPIC"}, - {D_DrawTitle1, "TITLEPIC"}, - }, - - { - {G_DeferedPlayDemo, "demo1"}, - {G_DeferedPlayDemo, "demo1"}, - {G_DeferedPlayDemo, "demo1"}, - {G_DeferedPlayDemo, "demo1"}, - }, - { - {D_SetPageName, NULL}, - {D_SetPageName, NULL}, - {D_SetPageName, NULL}, - {D_SetPageName, NULL}, - }, - - { - {G_DeferedPlayDemo, "demo2"}, - {G_DeferedPlayDemo, "demo2"}, - {G_DeferedPlayDemo, "demo2"}, - {G_DeferedPlayDemo, "demo2"}, - }, - - { -/* - {D_SetPageName, "HELP2"}, - {D_SetPageName, "HELP2"}, -*/ - {D_SetPageName, NULL}, - {D_SetPageName, NULL}, - {D_SetPageName, "CREDIT"}, - {D_DrawTitle1, "TITLEPIC"}, - }, - - { - {G_DeferedPlayDemo, "demo3"}, - {G_DeferedPlayDemo, "demo3"}, - {G_DeferedPlayDemo, "demo3"}, - {G_DeferedPlayDemo, "demo3"}, - }, - - { - {NULL}, - {NULL}, - {NULL}, - {D_SetPageName, "CREDIT"}, - }, - - { - {NULL}, - {NULL}, - {NULL}, - {G_DeferedPlayDemo, "demo4"}, - }, - - { - {NULL}, - {NULL}, - {NULL}, - {NULL}, - } - }; - -/* - * This cycles through the demo sequences. - * killough 11/98: made table-driven - */ - -void D_DoAdvanceDemo(void) -{ - players[consoleplayer].playerstate = PST_LIVE; /* not reborn */ - advancedemo = usergame = paused = false; - gameaction = ga_nothing; - - pagetic = TICRATE * 11; /* killough 11/98: default behavior */ - gamestate = GS_DEMOSCREEN; - - if (netgame && !demoplayback) - demosequence = 0; - else if (!demostates[++demosequence][gamemode].func) - demosequence = 0; - demostates[demosequence][gamemode].func - (demostates[demosequence][gamemode].name); -} - -// -// D_StartTitle -// -void D_StartTitle (void) -{ - gameaction = ga_nothing; - demosequence = -1; - D_AdvanceDemo(); -} - -// -// D_AddFile -// -// Add files to be loaded later by W_Init() -// -bool D_AddFile(const char *file) -{ - char relpath[PATH_MAX + 1]; - - if (numwadfiles == MAX_WAD_FILES) - I_Error("D_AddFile: Can't load more than %d WADs\n", MAX_WAD_FILES); - - snprintf(relpath, PATH_MAX, "%s/%s", I_DoomExeDir(), file); - - if (access(relpath, R_OK) == 0) - file = relpath; - else if (access(file, R_OK) != 0) { - lprintf(LO_WARN, "D_AddFile: %s not found\n", file); - return false; - } - - wadfiles[numwadfiles++] = (wadfile_info_t){ - .name = strdup(file), - .handle = NULL, - .data = NULL, - .size = 0, - }; - - return true; -} - -// -// CheckIWAD -// -// Verify a file is indeed tagged as an IWAD -// Scan its lumps for levelnames and return gamemode as indicated -// Detect missing wolf levels in DOOM II -// -// The filename to check is passed in iwadname, the gamemode detected is -// returned in gmode, hassec returns the presence of secret levels -// -// jff 4/19/98 Add routine to test IWAD for validity and determine -// the gamemode from it. Also note if DOOM II, whether secret levels exist -// CPhipps - const char* for iwadname, made static -static void CheckIWAD(wadfile_info_t *iwad,GameMode_t *gmode,boolean *hassec) -{ - int ud=0,rg=0,sw=0,cm=0,sc=0; - wadinfo_t header = {0}; - FILE *fp = NULL; - - if (!iwad) - I_Error("CheckIWAD: Can't open NULL IWAD"); - - if (iwad->data) - memcpy(&header, iwad->data, sizeof(header)); - else if ((fp = fopen(iwad->name, "rb"))) - fread(&header, sizeof(header), 1, fp); - else - I_Error("CheckIWAD: Can't open IWAD: %s", iwad->name); - - // read IWAD header - if (!strncmp(header.identification, "IWAD", 4)) - { - size_t length; - filelump_t *fileinfo; - - // read IWAD directory - header.numlumps = LONG(header.numlumps); - header.infotableofs = LONG(header.infotableofs); - length = header.numlumps; - fileinfo = calloc(sizeof(filelump_t), length); - - if (iwad->data) - memcpy(fileinfo, iwad->data + header.infotableofs, sizeof(filelump_t) * length); - else if (fseek(fp, header.infotableofs, SEEK_SET) == 0) - fread(fileinfo, sizeof(filelump_t), length, fp); - else - I_Error("CheckIWAD: Can't read IWAD: %s", iwad->name); - - // scan directory for levelname lumps - while (length--) - if (fileinfo[length].name[0] == 'E' && - fileinfo[length].name[2] == 'M' && - fileinfo[length].name[4] == 0) - { - if (fileinfo[length].name[1] == '4') - ++ud; - else if (fileinfo[length].name[1] == '3') - ++rg; - else if (fileinfo[length].name[1] == '2') - ++rg; - else if (fileinfo[length].name[1] == '1') - ++sw; - } - else if (fileinfo[length].name[0] == 'M' && - fileinfo[length].name[1] == 'A' && - fileinfo[length].name[2] == 'P' && - fileinfo[length].name[5] == 0) - { - ++cm; - if (fileinfo[length].name[3] == '3') - if (fileinfo[length].name[4] == '1' || - fileinfo[length].name[4] == '2') - ++sc; - } - - free(fileinfo); - } - else // missing IWAD tag in header - I_Error("CheckIWAD: IWAD tag %s not present", iwad->name); - - if (fp) - fclose(fp); - - // Determine game mode from levels present - // Must be a full set for whichever mode is present - // Lack of wolf-3d levels also detected here - - *gmode = indetermined; - *hassec = false; - if (cm>=30) - { - *gmode = commercial; - *hassec = sc>=2; - } - else if (ud>=9) - *gmode = retail; - else if (rg>=18) - *gmode = registered; - else if (sw>=9) - *gmode = shareware; -} - - -static void L_SetupConsoleMasks(void) { - int p; - int i; - const char *cena="ICWEFDA",*pos; //jff 9/3/98 use this for parsing console masks // CPhipps - const char*'s - - //jff 9/3/98 get mask for console output filter - if ((p = M_CheckParm ("-cout"))) { - lprintf(LO_DEBUG, "mask for console output: "); - if (++p != myargc && *myargv[p] != '-') - for (i=0,cons_output_mask=0;(size_t)iname); - - switch (gamemode) - { - case retail: - doomverstr = "The Ultimate DOOM"; - gamemission = doom; - break; - case shareware: - doomverstr = "DOOM Shareware"; - gamemission = doom; - break; - case registered: - doomverstr = "DOOM Registered"; - gamemission = doom; - break; - case commercial: // Ty 08/27/98 - fixed gamemode vs gamemission - p = strlen(iwad->name); - if (p>=7 && !strncasecmp(iwad->name+p-7,"tnt.wad",7)) { - doomverstr = "DOOM 2: TNT - Evilution"; - gamemission = pack_tnt; - } else if (p>=12 && !strncasecmp(iwad->name+p-12,"plutonia.wad",12)) { - doomverstr = "DOOM 2: Plutonia Experiment"; - gamemission = pack_plut; - } else { - doomverstr = "DOOM 2: Hell on Earth"; - gamemission = doom2; - } - break; - default: - doomverstr = "Public DOOM"; - gamemission = none; - break; - } - - /* cphipps - the main display. This shows the build date, copyright, and game type */ - lprintf(LO_ALWAYS, "%s %s (built %s), playing: %s\n" - "PrBoom is released under the GNU General Public license v2.0.\n" - "You are welcome to redistribute it under certain conditions.\n" - "It comes with ABSOLUTELY NO WARRANTY. See the file COPYING for details.\n", - PACKAGE, VERSION, version_date, doomverstr); - - // Add prboom.wad at the very beginning so it can be overriden by mods -#ifdef PRBOOMWAD - #include "prboom_wad.h" - wadfiles[numwadfiles++] = (wadfile_info_t){ - .name = "prboom.wad", - .data = prboom_wad, - .size = prboom_wad_size, - .handle = NULL, - }; -#else - if (!D_AddFile("prboom.wad")) - I_Error("PRBOOM.WAD not found\n"); -#endif - - if ((devparm = M_CheckParm("-devparm"))) - lprintf(LO_CONFIRM, "%s", s_D_DEVSTR); - - // set save path to -save parm or current dir - basesavegame = I_DoomExeDir(); - if ((p=M_CheckParm("-save")) && p 400) - scale = 400; - //jff 9/3/98 use logical output routine - lprintf (LO_CONFIRM,"turbo scale: %i%%\n",scale); - forwardmove[0] = forwardmove[0]*scale/100; - forwardmove[1] = forwardmove[1]*scale/100; - sidemove[0] = sidemove[0]*scale/100; - sidemove[1] = sidemove[1]*scale/100; - } - - // get skill / episode / map from parms - - startskill = sk_none; // jff 3/24/98 was sk_medium, just note not picked - startepisode = 1; - startmap = 1; - autostart = false; - - if ((p = M_CheckParm ("-skill")) && p < myargc-1) - { - startskill = myargv[p+1][0]-'1'; - autostart = true; - } - - if ((p = M_CheckParm ("-episode")) && p < myargc-1) - { - startepisode = myargv[p+1][0]-'0'; - startmap = 1; - autostart = true; - } - - if ((p = M_CheckParm ("-timer")) && p < myargc-1 && deathmatch) - { - int time = atoi(myargv[p+1]); - //jff 9/3/98 use logical output routine - lprintf(LO_CONFIRM,"Levels will end after %d minute%s.\n", time, time>1 ? "s" : ""); - } - - if ((p = M_CheckParm ("-warp")) || // killough 5/2/98 - (p = M_CheckParm ("-wart"))) - // Ty 08/29/98 - moved this check later so we can have -warp alone: && p < myargc-1) - { - startmap = 0; // Ty 08/29/98 - allow "-warp x" to go to first map in wad(s) - autostart = true; // Ty 08/29/98 - move outside the decision tree - if (gamemode == commercial) - { - if (p < myargc-1) - startmap = atoi(myargv[p+1]); // Ty 08/29/98 - add test if last parm - } - else // 1/25/98 killough: fix -warp xxx from crashing Doom 1 / UD - { - if (p < myargc-2) - { - startepisode = atoi(myargv[++p]); - startmap = atoi(myargv[p+1]); - } - } - } - // Ty 08/29/98 - later we'll check for startmap=0 and autostart=true - // as a special case that -warp * was used. Actually -warp with any - // non-numeric will do that but we'll only document "*" - - nomusicparm = M_CheckParm("-nosound") || M_CheckParm("-nomusic"); - nosfxparm = M_CheckParm("-nosound") || M_CheckParm("-nosfx"); - nodrawers = M_CheckParm ("-nodraw"); - noblit = M_CheckParm ("-noblit"); - - //proff 11/22/98: Added setting of viewangleoffset - if ((p = M_CheckParm("-viewangle"))) - { - viewangleoffset = atoi(myargv[p+1]); - viewangleoffset = viewangleoffset<0 ? 0 : (viewangleoffset>7 ? 7 : viewangleoffset); - viewangleoffset = (8-viewangleoffset) * ANG45; - } - - // init subsystems - - G_ReloadDefaults(); // killough 3/4/98: set defaults just loaded. - // jff 3/24/98 this sets startskill if it was -1 - -#ifndef NODEHSUPPORT - // ty 03/09/98 do dehacked stuff - // Note: do this before any other since it is expected by - // the deh patch author that this is actually part of the EXE itself - // Using -deh in BOOM, others use -dehacked. - // Ty 03/18/98 also allow .bex extension. .bex overrides if both exist. - - if ((p = M_CheckParm ("-deh"))) - { - char file[PATH_MAX+1]; // cph - localised - // the parms after p are deh/bex file names, - // until end of parms or another - preceded parm - // Ty 04/11/98 - Allow multiple -deh files in a row - - while (++p != myargc && *myargv[p] != '-') - { - AddDefaultExtension(strcpy(file, myargv[p]), ".bex"); - if (access(file, F_OK)) // nope - { - AddDefaultExtension(strcpy(file, myargv[p]), ".deh"); - if (access(file, F_OK)) // still nope - I_Error("D_DoomMainSetup: Cannot find .deh or .bex file named %s",myargv[p]); - } - // during the beta we have debug output to dehout.txt - D_ProcessDehFile(file,D_dehout(),0); - } - } - // ty 03/09/98 end of do dehacked stuff -#endif - - // add any files specified on the command line with -file wadfile - // to the wad list - if ((p = M_CheckParm ("-file"))) - { - // the parms after p are wadfile/lump names, - // until end of parms or another - preceded parm - while (++p != myargc && *myargv[p] != '-') - if (D_AddFile(myargv[p])) - modifiedgame = true; - } - - if (!(p = M_CheckParm("-playdemo")) || p >= myargc-1) { /* killough */ - if ((p = M_CheckParm ("-fastdemo")) && p < myargc-1) /* killough */ - fastdemo = true; // run at fastest speed possible - else - p = M_CheckParm ("-timedemo"); - } - - if (p && p < myargc-1) - { - char file[PATH_MAX+1]; // cph - localised - strcpy(file,myargv[p+1]); - AddDefaultExtension(file,".lmp"); // killough - D_AddFile (file); - //jff 9/3/98 use logical output routine - lprintf(LO_CONFIRM,"Playing demo %s\n",file); - if ((p = M_CheckParm ("-ffmap")) && p < myargc-1) { - ffmap = atoi(myargv[p+1]); - } - } - - // internal translucency set to config file value // phares - general_translucency = default_translucency; // phares - - lprintf(LO_INFO, "I_Init: Setting up machine state.\n"); - I_Init(); - - // CPhipps - move up netgame init - lprintf(LO_INFO, "D_InitNetGame: Checking for network game.\n"); - D_InitNetGame(); - - lprintf(LO_INFO, "W_Init: Init WADfiles.\n"); - W_Init(); // CPhipps - handling of wadfiles init changed - - lprintf(LO_INFO, "V_Init: Setting up video.\n"); - V_Init(SCREENWIDTH, SCREENHEIGHT, default_videomode); - -#ifndef NODEHSUPPORT - // e6y: option to disable automatic loading of dehacked-in-wad lump - if (!M_CheckParm ("-nodeh")) - if ((p = W_CheckNumForName("DEHACKED")) != -1) // cph - add dehacked-in-a-wad support - D_ProcessDehFile(NULL, D_dehout(), p); -#endif - - lprintf(LO_INFO, "M_Init: Init miscellaneous info.\n"); - M_Init(); - -#ifdef HAVE_NET - // CPhipps - now wait for netgame start - D_CheckNetGame(); -#endif - - lprintf(LO_INFO, "R_Init: Init DOOM refresh daemon:\n"); - R_Init(); - - lprintf(LO_INFO, "P_Init: Init Playloop state.\n"); - P_Init(); - - lprintf(LO_INFO, "S_Init: Setting up sound.\n"); - S_Init(snd_SfxVolume, snd_MusicVolume); - - lprintf(LO_INFO, "HU_Init: Setting up heads up display.\n"); - HU_Init(); - - lprintf(LO_INFO, "ST_Init: Init status bar.\n"); - ST_Init(); - - // Show hacked startup messages, if any - if (*startup1 || *startup2 || *startup3 || *startup4 || *startup5) - { - if (*startup1) lprintf(LO_INFO, "%s", startup1); - if (*startup2) lprintf(LO_INFO, "%s", startup2); - if (*startup3) lprintf(LO_INFO, "%s", startup3); - if (*startup4) lprintf(LO_INFO, "%s", startup4); - if (*startup5) lprintf(LO_INFO, "%s", startup5); - } - - lprintf(LO_INFO, "\n"); - - idmusnum = -1; //jff 3/17/98 insure idmus number is blank - - // start the apropriate game based on parms - - // killough 12/98: - // Support -loadgame with -record and reimplement -recordfrom. - - if ((slot = M_CheckParm("-recordfrom")) && (p = slot+2) < myargc) - G_RecordDemo(myargv[p]); - else - { - slot = M_CheckParm("-loadgame"); - if ((p = M_CheckParm("-record")) && ++p < myargc) - { - autostart = true; - G_RecordDemo(myargv[p]); - } - } - - if ((p = M_CheckParm ("-fastdemo")) && ++p < myargc) - { // killough - fastdemo = true; // run at fastest speed possible - timingdemo = true; // show stats after quit - G_DeferedPlayDemo(myargv[p]); - singledemo = true; // quit after one demo - } - else if ((p = M_CheckParm("-timedemo")) && ++p < myargc) - { - singletics = true; - timingdemo = true; // show stats after quit - G_DeferedPlayDemo(myargv[p]); - singledemo = true; // quit after one demo - } - else if ((p = M_CheckParm("-playdemo")) && ++p < myargc) - { - G_DeferedPlayDemo(myargv[p]); - singledemo = true; // quit after one demo - } - - if (slot && ++slot < myargc) - { - slot = atoi(myargv[slot]); // killough 3/16/98: add slot info - G_LoadGame(slot, true); // killough 5/15/98: add command flag // cph - no filename - } - else if (!singledemo) - { - if (autostart || netgame) - { - G_InitNew(startskill, startepisode, startmap); - if (demorecording) - G_BeginRecording(); - } - else - D_StartTitle(); // start up intro loop - } -} - -// -// D_DoomMain -// - -void D_DoomMain(void) -{ - D_DoomMainSetup(); // CPhipps - setup out of main execution stack - D_DoomLoop(); // never returns -} diff --git a/components/doom/prboom/d_main.h b/components/doom/prboom/d_main.h deleted file mode 100644 index 43d8c863..00000000 --- a/components/doom/prboom/d_main.h +++ /dev/null @@ -1,75 +0,0 @@ -/* Emacs style mode select -*- C++ -*- - *----------------------------------------------------------------------------- - * - * - * PrBoom: a Doom port merged with LxDoom and LSDLDoom - * based on BOOM, a modified and improved DOOM engine - * Copyright (C) 1999 by - * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman - * Copyright (C) 1999-2000 by - * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze - * Copyright 2005, 2006 by - * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko - * - * 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. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA. - * - * DESCRIPTION: - * Main startup and splash screenstuff. - * - *-----------------------------------------------------------------------------*/ - -#ifndef __D_MAIN__ -#define __D_MAIN__ - -#include "d_event.h" -#include "w_wad.h" - -#ifdef __GNUG__ -#pragma interface -#endif - -extern const char *basesavegame; // killough 2/16/98: savegame path - -//jff 1/24/98 make command line copies of play modes available -extern boolean clnomonsters; // checkparm of -nomonsters -extern boolean clrespawnparm; // checkparm of -respawn -extern boolean clfastparm; // checkparm of -fast -//jff end of external declaration of command line playmode - -extern boolean nosfxparm; -extern boolean nomusicparm; -extern int ffmap; - -// Called by IO functions when input is detected. -void D_PostEvent(event_t* ev); - -// Demo stuff -extern boolean advancedemo; -void D_AdvanceDemo(void); -void D_DoAdvanceDemo (void); - -// -// BASE LEVEL -// - -void D_Display(void); -void D_PageTicker(void); -void D_StartTitle(void); -void D_DoomMain(void); -void D_DoomMainSetup(void); -bool D_AddFile(const char *file); - -#endif diff --git a/components/doom/prboom/d_net.h b/components/doom/prboom/d_net.h deleted file mode 100644 index fcdeb6c4..00000000 --- a/components/doom/prboom/d_net.h +++ /dev/null @@ -1,214 +0,0 @@ -/* Emacs style mode select -*- C++ -*- - *----------------------------------------------------------------------------- - * - * - * PrBoom: a Doom port merged with LxDoom and LSDLDoom - * based on BOOM, a modified and improved DOOM engine - * Copyright (C) 1999 by - * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman - * Copyright (C) 1999-2000 by - * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze - * Copyright 2005, 2006 by - * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko - * - * 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. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA. - * - * DESCRIPTION: - * Networking stuff. - * - *-----------------------------------------------------------------------------*/ - - -#ifndef __D_NET__ -#define __D_NET__ - -#include "d_player.h" - - -#ifdef __GNUG__ -#pragma interface -#endif - - -// -// Network play related stuff. -// There is a data struct that stores network -// communication related stuff, and another -// one that defines the actual packets to -// be transmitted. -// - -#define DOOMCOM_ID 0x12345678l - -// Max computers/players in a game. -#define MAXNETNODES 8 - - -typedef enum -{ - CMD_SEND = 1, - CMD_GET = 2 - -} command_t; - - -// -// Network packet data. -// -typedef struct -{ - // High bit is retransmit request. - unsigned checksum; - // Only valid if NCMD_RETRANSMIT. - byte retransmitfrom; - - byte starttic; - byte player; - byte numtics; - ticcmd_t cmds[BACKUPTICS]; - -} doomdata_t; - -// -// Startup packet difference -// SG: 4/12/98 -// Added so we can send more startup data to synch things like -// bobbing, recoil, etc. -// this is just mapped over the ticcmd_t array when setup packet is sent -// -// Note: the original code takes care of startskill, deathmatch, nomonsters -// respawn, startepisode, startmap -// Note: for phase 1 we need to add monsters_remember, variable_friction, -// weapon_recoil, allow_pushers, over_under, player_bobbing, -// fastparm, demo_insurance, and the rngseed -//Stick all options into bytes so we don't need to mess with bitfields -//WARNING: make sure this doesn't exceed the size of the ticcmds area! -//sizeof(ticcmd_t)*BACKUPTICS -//This is the current length of our extra stuff -// -//killough 5/2/98: this should all be replaced by calls to G_WriteOptions() -//and G_ReadOptions(), which were specifically designed to set up packets. -//By creating a separate struct and functions to read/write the options, -//you now have two functions and data to maintain instead of just one. -//If the array in g_game.c which G_WriteOptions()/G_ReadOptions() operates -//on, is too large (more than sizeof(ticcmd_t)*BACKUPTICS), it can -//either be shortened, or the net code needs to divide it up -//automatically into packets. The STARTUPLEN below is non-portable. -//There's a portable way to do it without having to know the sizes. - -#define STARTUPLEN 12 -typedef struct -{ - byte monsters_remember; - byte variable_friction; - byte weapon_recoil; - byte allow_pushers; - byte over_under; - byte player_bobbing; - byte fastparm; - byte demo_insurance; - unsigned long rngseed; - char filler[sizeof(ticcmd_t)*BACKUPTICS-STARTUPLEN]; -} startup_t; - -typedef enum { - // Leave space, so low values corresponding to normal netgame setup packets can be ignored - nm_plcolour = 3, - nm_savegamename = 4, -} netmisctype_t; - -typedef struct -{ - netmisctype_t type; - size_t len; - byte value[sizeof(ticcmd_t)*BACKUPTICS - sizeof(netmisctype_t) - sizeof(size_t)]; -} netmisc_t; - -typedef struct -{ - // Supposed to be DOOMCOM_ID? - long id; - - // DOOM executes an int to execute commands. - short intnum; - // Communication between DOOM and the driver. - // Is CMD_SEND or CMD_GET. - short command; - // Is dest for send, set by get (-1 = no packet). - short remotenode; - - // Number of bytes in doomdata to be sent - short datalength; - - // Info common to all nodes. - // Console is allways node 0. - short numnodes; - // Flag: 1 = no duplication, 2-5 = dup for slow nets. - short ticdup; - // Flag: 1 = send a backup tic in every packet. - short extratics; - // Flag: 1 = deathmatch. - short deathmatch; - // Flag: -1 = new game, 0-5 = load savegame - short savegame; - short episode; // 1-3 - short map; // 1-9 - short skill; // 1-5 - - // Info specific to this node. - short consoleplayer; - short numplayers; - - // These are related to the 3-display mode, - // in which two drones looking left and right - // were used to render two additional views - // on two additional computers. - // Probably not operational anymore. - // 1 = left, 0 = center, -1 = right - short angleoffset; - // 1 = drone - short drone; - - // The packet data to be sent. - doomdata_t data; - -} doomcom_t; - -// Create any new ticcmds and broadcast to other players. -#ifdef HAVE_NET -void NetUpdate (void); -#else -void D_BuildNewTiccmds(void); -#endif - -//? how many ticks to run? -void TryRunTics (void); - -// CPhipps - move to header file -void D_InitNetGame (void); // This does the setup -void D_CheckNetGame(void); // This waits for game start - -// CPhipps - misc info broadcast -void D_NetSendMisc(netmisctype_t type, size_t len, void* data); - -// CPhipps - ask server for a wad file we need -boolean D_NetGetWad(const char* name); - -// Netgame stuff (buffers and pointers, i.e. indices). -extern doomcom_t *doomcom; -extern doomdata_t *netbuffer; // This points inside doomcom. - -#endif diff --git a/components/doom/prboom/d_player.h b/components/doom/prboom/d_player.h deleted file mode 100644 index a45abe8c..00000000 --- a/components/doom/prboom/d_player.h +++ /dev/null @@ -1,234 +0,0 @@ -/* Emacs style mode select -*- C++ -*- - *----------------------------------------------------------------------------- - * - * - * PrBoom: a Doom port merged with LxDoom and LSDLDoom - * based on BOOM, a modified and improved DOOM engine - * Copyright (C) 1999 by - * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman - * Copyright (C) 1999-2000 by - * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze - * Copyright 2005, 2006 by - * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko - * - * 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. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA. - * - * DESCRIPTION: - * Player state structure. - * - *-----------------------------------------------------------------------------*/ - - -#ifndef __D_PLAYER__ -#define __D_PLAYER__ - - -// The player data structure depends on a number -// of other structs: items (internal inventory), -// animation states (closely tied to the sprites -// used to represent them, unfortunately). -#include "d_items.h" -#include "p_pspr.h" - -// In addition, the player is just a special -// case of the generic moving object/actor. -#include "p_mobj.h" - -// Finally, for odd reasons, the player input -// is buffered within the player data struct, -// as commands per game tick. -#include "d_ticcmd.h" - -#ifdef __GNUG__ -#pragma interface -#endif - - -// -// Player states. -// -typedef enum -{ - // Playing or camping. - PST_LIVE, - // Dead on the ground, view follows killer. - PST_DEAD, - // Ready to restart/respawn??? - PST_REBORN - -} playerstate_t; - - -// -// Player internal flags, for cheats and debug. -// -typedef enum -{ - // No clipping, walk through barriers. - CF_NOCLIP = 1, - // No damage, no health loss. - CF_GODMODE = 2, - // Not really a cheat, just a debug aid. - CF_NOMOMENTUM = 4 - -} cheat_t; - - -// -// Extended player object info: player_t -// -typedef struct player_s -{ - mobj_t* mo; - playerstate_t playerstate; - ticcmd_t cmd; - - // Determine POV, - // including viewpoint bobbing during movement. - // Focal origin above r.z - fixed_t viewz; - // Base height above floor for viewz. - fixed_t viewheight; - // Bob/squat speed. - fixed_t deltaviewheight; - // bounded/scaled total momentum. - fixed_t bob; - - /* killough 10/98: used for realistic bobbing (i.e. not simply overall speed) - * mo->momx and mo->momy represent true momenta experienced by player. - * This only represents the thrust that the player applies himself. - * This avoids anomolies with such things as Boom ice and conveyors. - */ - fixed_t momx, momy; // killough 10/98 - - // This is only used between levels, - // mo->health is used during levels. - int health; - int armorpoints; - // Armor type is 0-2. - int armortype; - - // Power ups. invinc and invis are tic counters. - int powers[NUMPOWERS]; - boolean cards[NUMCARDS]; - boolean backpack; - - // Frags, kills of other players. - int frags[MAXPLAYERS]; - weapontype_t readyweapon; - - // Is wp_nochange if not changing. - weapontype_t pendingweapon; - - boolean weaponowned[NUMWEAPONS]; - int ammo[NUMAMMO]; - int maxammo[NUMAMMO]; - - // True if button down last tic. - int attackdown; - int usedown; - - // Bit flags, for cheats and debug. - // See cheat_t, above. - int cheats; - - // Refired shots are less accurate. - int refire; - - // For intermission stats. - int killcount; - int itemcount; - int secretcount; - - // Hint messages. // CPhipps - const - const char* message; - - // For screen flashing (red or bright). - int damagecount; - int bonuscount; - - // Who did damage (NULL for floors/ceilings). - mobj_t* attacker; - - // So gun flashes light up areas. - int extralight; - - // Current PLAYPAL, ??? - // can be set to REDCOLORMAP for pain, etc. - int fixedcolormap; - - // Player skin colorshift, - // 0-3 for which color to draw player. - int colormap; - - // Overlay view sprites (gun, etc). - pspdef_t psprites[NUMPSPRITES]; - - // True if secret level has been done. - boolean didsecret; - -} player_t; - - -// -// INTERMISSION -// Structure passed e.g. to WI_Start(wb) -// -typedef struct -{ - boolean in; // whether the player is in game - - // Player stats, kills, collected items etc. - int skills; - int sitems; - int ssecret; - int stime; - int frags[4]; - int score; // current score on entry, modified on return - -} wbplayerstruct_t; - -typedef struct -{ - int epsd; // episode # (0-2) - - // if true, splash the secret level - boolean didsecret; - - // previous and next levels, origin 0 - int last; - int next; - - int maxkills; - int maxitems; - int maxsecret; - int maxfrags; - - // the par time - int partime; - - // index of this player in game - int pnum; - - wbplayerstruct_t plyr[MAXPLAYERS]; - - // CPhipps - total game time for completed levels so far - int totaltimes; - -} wbstartstruct_t; - - -#endif diff --git a/components/doom/prboom/d_server.c b/components/doom/prboom/d_server.c deleted file mode 100644 index dd16483a..00000000 --- a/components/doom/prboom/d_server.c +++ /dev/null @@ -1,754 +0,0 @@ -/* Emacs style mode select -*- C++ -*- - *----------------------------------------------------------------------------- - * - * - * PrBoom: a Doom port merged with LxDoom and LSDLDoom - * based on BOOM, a modified and improved DOOM engine - * Copyright (C) 1999 by - * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman - * Copyright (C) 1999-2004 by - * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze - * Copyright 2005, 2006 by - * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko - * - * 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. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA. - * - * DESCRIPTION: - * Network game server code - * New for LxDoom, but drawing ideas and code fragments from the - * earlier net code - *----------------------------------------------------------------------------- - */ - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include -#include -#include -#include -#include -#ifdef HAVE_UNISTD_H -#include -#endif -#include -#include -#include -#include - -#ifdef USE_SDL_NET - #include "SDL.h" -#endif - -#include "doomtype.h" -#include "protocol.h" -#include "i_network.h" -#ifndef PRBOOM_SERVER -#include "m_fixed.h" -#endif -#include "i_system.h" -#include "m_swap.h" - -#ifndef HAVE_NET - -int main(void) -{ - fprintf(stderr, - PACKAGE "-server: You must compile with networking enabled!\n"); - exit(1); - return 1; -} - -#else - -#ifndef HAVE_GETOPT -/* The following code for getopt is from the libc-source of FreeBSD, - * it might be changed a little bit. - * Florian Schulze (florian.schulze@gmx.net) - */ - -/* - * Copyright (c) 1987, 1993, 1994 - * The Regents of the University of California. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -#if defined(LIBC_SCCS) && !defined(lint) -#if 0 -static char sccsid[] = "@(#)getopt.c 8.3 (Berkeley) 4/27/95"; -#endif -static const char rcsid[] = "$FreeBSD$"; -#endif /* LIBC_SCCS and not lint */ - -int opterr = 1, /* if error message should be printed */ - optind = 1, /* index into parent argv vector */ - optopt, /* character checked for validity */ - optreset; /* reset getopt */ -char *optarg; /* argument associated with option */ - -#define BADCH (int)'?' -#define BADARG (int)':' -#define EMSG "" - -char *__progname="prboom_server"; - -/* - * getopt -- - * Parse argc/argv argument vector. - */ -int -getopt(nargc, nargv, ostr) - int nargc; - char * const *nargv; - const char *ostr; -{ - extern char *__progname; - static char *place = EMSG; /* option letter processing */ - char *oli; /* option letter list index */ - int ret; - - if (optreset || !*place) { /* update scanning pointer */ - optreset = 0; - if (optind >= nargc || *(place = nargv[optind]) != '-') { - place = EMSG; - return (-1); - } - if (place[1] && *++place == '-') { /* found "--" */ - ++optind; - place = EMSG; - return (-1); - } - } /* option letter okay? */ - if ((optopt = (int)*place++) == (int)':' || - !(oli = strchr(ostr, optopt))) { - /* - * if the user didn't specify '-' as an option, - * assume it means -1. - */ - if (optopt == (int)'-') - return (-1); - if (!*place) - ++optind; - if (opterr && *ostr != ':') - (void)fprintf(stderr, - "%s: illegal option -- %c\n", __progname, optopt); - return (BADCH); - } - if (*++oli != ':') { /* don't need argument */ - optarg = NULL; - if (!*place) - ++optind; - } - else { /* need an argument */ - if (*place) /* no white space */ - optarg = place; - else if (nargc <= ++optind) { /* no arg */ - place = EMSG; - if (*ostr == ':') - ret = BADARG; - else - ret = BADCH; - if (opterr) - (void)fprintf(stderr, - "%s: option requires an argument -- %c\n", - __progname, optopt); - return (ret); - } - else /* white space */ - optarg = nargv[optind]; - place = EMSG; - ++optind; - } - return (optopt); /* dump back option letter */ -} -#else -#include -#endif - -#define MAXPLAYERS 4 -#define BACKUPTICS 12 - -// Dummies to forfill l_udp.c unused client stuff -int M_CheckParm(const char* p) { p = NULL; return 1; } -int myargc; -char** myargv; - -void NORETURN I_Error(const char *error, ...) // killough 3/20/98: add const -{ - va_list argptr; - va_start(argptr,error); - vfprintf(stderr,error,argptr); - va_end(argptr); - exit(-1); -} - -int playerjoingame[MAXPLAYERS], playerleftgame[MAXPLAYERS]; -UDP_CHANNEL remoteaddr[MAXPLAYERS]; -enum { pc_unused, pc_connected, pc_ready, pc_confirmedready, pc_playing, pc_quit } playerstate[MAXPLAYERS]; -int displaycounter; - -boolean n_players_in_state(int n, int ps) { - int i,j; - for (i=j=0;itic); -} - - - -void read_config_file(FILE* fp, struct setup_packet_s* sp) -{ - byte* gameopt = sp->game_options; - - while (!feof(fp)) { - char def[80]; - char strparm[100]; - if (fscanf (fp, "%79s %99[^\n]\n", def, strparm) == 2) { - int v = atoi(strparm); - if (!strcmp(def,"default_skill")) { - if (verbose) printf("config file sets default_skill to %d\n",v); - sp->skill = v-1; - } else if (!strcmp(def,"default_compatibility_level")) { - if (verbose) printf("config file sets compatibility_level to %d\n",v); - if (v == -1) v = MAX_COMPATIBILITY_LEVEL-1; //e6y: -1 => maxcompat - sp->complevel = v; - } else { - int i; - for (i=0; i= MAXPLAYERS); } - -int main(int argc, char** argv) -{ -#ifndef USE_SDL_NET - int localport = 5030; -#else - Uint16 localport = 5030; -#endif - int numplayers = 2, xtratics = 0, ticdup = 1; - int exectics = 0; // gametics completed - struct setup_packet_s setupinfo = { 2, 0, 1, 1, 1, 0, best_compatibility, 0, 0}; - char**wadname = NULL; - char**wadget = NULL; - int numwads = 0; - { - int opt; - byte *gameopt = setupinfo.game_options; - - memcpy(gameopt, &def_game_options, sizeof (setupinfo.game_options)); - while ((opt = getopt(argc, argv, "c:t:x:p:e:l:adrfns:N:vw:")) != EOF) - switch (opt) { - case 'c': - { - FILE *cf = fopen(optarg,"r"); - if (!cf) { perror("fopen"); return -1; } - read_config_file(cf,&setupinfo); - fclose(cf); - } - break; - case 't': - if (optarg) ticdup = atoi(optarg); - break; - case 'x': - if (optarg) xtratics = atoi(optarg); - break; - case 'p': - if (optarg) localport = atoi(optarg); - break; - case 'e': - if (optarg) setupinfo.episode = atoi(optarg); - break; - case 'l': - if (optarg) setupinfo.level = atoi(optarg); - break; - case 'a': - setupinfo.deathmatch = 2; - break; - case 'd': - setupinfo.deathmatch = 1; - break; - case 'r': - setupinfo.game_options[6] = 1; - break; - case 'f': - setupinfo.game_options[7] = 1; - break; - case 'n': - setupinfo.game_options[8] = 1; - break; - case 's': - if (optarg) setupinfo.skill = atoi(optarg)-1; - break; - case 'N': - if (optarg) setupinfo.players = numplayers = atoi(optarg); - break; - case 'v': - verbose++; - break; - case 'w': - if (optarg) { - char *p; - wadname = realloc(wadname, ++numwads * sizeof *wadname); - wadget = realloc(wadget , numwads * sizeof *wadget ); - wadname[numwads-1] = strdup(optarg); - if ((p = strchr(wadname[numwads-1], ','))) { - *p++ = 0; wadget[numwads-1] = p; - } else wadget[numwads-1] = NULL; - } - break; - } - } - - setupinfo.ticdup = ticdup; setupinfo.extratic = xtratics; - { /* Random number seed - * Mirrors the corresponding code in G_ReadOptions */ - int rngseed = (int)time(NULL); - setupinfo.game_options[13] = rngseed & 0xff; - rngseed >>= 8; - setupinfo.game_options[12] = rngseed & 0xff; - rngseed >>= 8; - setupinfo.game_options[11] = rngseed & 0xff; - rngseed >>= 8; - setupinfo.game_options[10] = rngseed & 0xff; - } - I_InitSockets(localport); - - printf("Listening on port %d, waiting for %d players\n", localport, numplayers); - - { // no players initially - int i; - for (i=0; i2) printf("Received packet:"); - switch (packet->type) { - case PKT_INIT: - if (!ingame) { - { - int n; - struct setup_packet_s *sinfo = (void*)(packet+1); - - /* Find player number and add to the game */ - n = *(short*)(packet+1); - - if (badplayer(n) || playerstate[n] != pc_unused) - for (n=0; nyourplayer = n; - sinfo->numwads = numwads; - for (i=0; iwadnames + extrabytes, wadname[i]); - extrabytes += strlen(wadname[i]) + 1; - } - I_SendPacketTo(packet, sizeof *packet + sizeof setupinfo + extrabytes, - remoteaddr+n); - I_uSleep(10000); - I_SendPacketTo(packet, sizeof *packet + sizeof setupinfo + extrabytes, - remoteaddr+n); - } - } - } - break; - case PKT_GO: - if (!ingame) { - int from = *(byte*)(packet+1); - - if (badplayer(from) || playerstate[from] == pc_unused) break; - if (confirming) { - if (playerstate[from] != pc_confirmedready) curplayers++; - playerstate[from] = pc_confirmedready; - } else - playerstate[from] = pc_ready; - } - break; - case PKT_TICC: - { - byte tics = *(byte*)(packet+1); - int from = *(((byte*)(packet+1))+1); - - if (badplayer(from)) break; - - if (verbose>2) - printf("tics %ld - %ld from %d\n", ptic(packet), ptic(packet) + tics - 1, from); - if (ptic(packet) > remoteticfrom[from]) { - // Missed tics, so request a resend - packet_set(packet, PKT_RETRANS, remoteticfrom[from]); - I_SendPacketTo(packet, sizeof *packet, remoteaddr+from); - } else { - ticcmd_t *newtic = (void*)(((byte*)(packet+1))+2); - if (ptic(packet) + tics < remoteticfrom[from]) break; // Won't help - remoteticfrom[from] = ptic(packet); - while (tics--) - netcmds[from][remoteticfrom[from]++%BACKUPTICS] = *newtic++; - } - } - break; - case PKT_RETRANS: - { - int from = *(byte*)(packet+1); - if (badplayer(from)) break; - - if (verbose>2) printf("%d requests resend from %d\n", from, ptic(packet)); - remoteticto[from] = ptic(packet); - } - break; - case PKT_QUIT: - { - int from = *(byte*)(packet+1); - if (badplayer(from)) break; - - if (!ingame && playerstate[from] != pc_unused) { - // If we already got a PKT_GO, we have to remove this player frmo the count of ready players. And we then flag this player slot as vacant. - printf("player %d pulls out\n", from); - if (playerstate[from] == pc_confirmedready) curplayers--; - playerstate[from] = pc_unused; - } else - if (playerleftgame[from] == INT_MAX) { // In the game - playerleftgame[from] = ptic(packet); - --curplayers; - if (verbose) printf("%d quits at %d (%d left)\n", from, ptic(packet),curplayers); - if (ingame && !curplayers) exit(0); // All players have exited - } - } - // Fall through and broadcast it - case PKT_EXTRA: - BroadcastPacket(packet, len); - if (packet->type == PKT_EXTRA) { - if (verbose>2) printf("misc from %d\n", *(((byte*)(packet+1))+1)); - } - break; - case PKT_WAD: - { - int i; - int from = *(byte*)(packet+1); - char *name = 1 + (char*)(packet+1); - size_t size = sizeof(packet_header_t); - packet_header_t *reply; - - if (badplayer(from) || playerstate[from] != pc_unused) break; - - if (verbose) printf("Request for %s ", name); - for (i=0; itype); - break; - } - } - free(packet); - if (!ingame && n_players_in_state(numplayers,pc_confirmedready)) { - int i; - packet_header_t gopacket; - packet = &gopacket; - ingame=true; - printf("All players joined, beginning game.\n"); - for (i=0; i1) printf("%d new tics can be run\n", lowtic - exectics); - - if (lowtic > exectics) - exectics = lowtic; // count exec'ed tics - // Now send all tics up to lowtic - for (i=0; i1) printf("sending %d tics to %d\n", tics, i); - while (tics--) { - int j, playersthistic = 0; - byte *q = p++; - for (j=0; j remoteticto[i])) { - *p++ = j; - memcpy(p, &netcmds[j][remoteticto[i]%BACKUPTICS], sizeof(ticcmd_t)); - p += sizeof(ticcmd_t); - playersthistic++; - } - *q = playersthistic; - remoteticto[i]++; - } - I_SendPacketTo(packet, p - ((byte*)packet), remoteaddr+i); - free(packet); - } - { - if (remoteticfrom[i] == remoteticto[i]) { - backoffcounter[i] = 0; - } else if (remoteticfrom[i] > remoteticto[i]+1) { - if ((backoffcounter[i] += remoteticfrom[i] - remoteticto[i] - 1) > 35) { - packet_header_t *packet = malloc(sizeof(packet_header_t)); - packet_set(packet, PKT_BACKOFF, remoteticto[i]); - I_SendPacketTo(packet,sizeof *packet,remoteaddr+i); - backoffcounter[i] = 0; - if (verbose) printf("telling client %d to back off\n",i); - free(packet); - } - } - } - } - } - if (!((ingame ? 0xff : 0xf) & displaycounter++)) { - int i; - fprintf(stderr,"Player states: ["); - for (i=0;i -#include -#include -//#include "dosbox.h" -#include "dbopl.h" - -#ifdef _MSC_VER -#define inline __inline -#endif - -#define GCC_UNLIKELY(x) x - -#define TRUE 1 -#define FALSE 0 - -#ifndef PI -#define PI 3.14159265358979323846 -#endif - -#define OPLRATE ((double)(14318180.0 / 288.0)) - -//Try to use most precision for frequencies -//Else try to keep different waves in synch -//#define WAVE_PRECISION 1 -#ifndef WAVE_PRECISION -//Wave bits available in the top of the 32bit range -//Original adlib uses 10.10, we use 10.22 -#define WAVE_BITS 10 -#else -//Need some extra bits at the top to have room for octaves and frequency multiplier -//We support to 8 times lower rate -//128 * 15 * 8 = 15350, 2^13.9, so need 14 bits -#define WAVE_BITS 14 -#endif -#define WAVE_SH ( 32 - WAVE_BITS ) -#define WAVE_MASK ( ( 1 << WAVE_SH ) - 1 ) - -//Use the same accuracy as the waves -#define LFO_SH ( WAVE_SH - 10 ) -//LFO is controlled by our tremolo 256 sample limit -#define LFO_MAX ( 256 << ( LFO_SH ) ) - - -//Maximum amount of attenuation bits -//Envelope goes to 511, 9 bits -#if (DBOPL_WAVE == WAVE_TABLEMUL ) -//Uses the value directly -#define ENV_BITS ( 9 ) -#else -//Add 3 bits here for more accuracy and would have to be shifted up either way -#define ENV_BITS ( 9 ) -#endif -//Limits of the envelope with those bits and when the envelope goes silent -#define ENV_MIN 0 -#define ENV_EXTRA ( ENV_BITS - 9 ) -#define ENV_MAX ( 511 << ENV_EXTRA ) -#define ENV_LIMIT ( ( 12 * 256) >> ( 3 - ENV_EXTRA ) ) -#define ENV_SILENT( _X_ ) ( (_X_) >= ENV_LIMIT ) - -//Attack/decay/release rate counter shift -#define RATE_SH 24 -#define RATE_MASK ( ( 1 << RATE_SH ) - 1 ) -//Has to fit within 16bit lookuptable -#define MUL_SH 16 - -//Check some ranges -#if ENV_EXTRA > 3 -#error Too many envelope bits -#endif - -static inline void Operator__SetState(Operator *self, Bit8u s ); -static inline Bit32u Chip__ForwardNoise(Chip *self); - -// C++'s template<> sure is useful sometimes. - -static Channel* Channel__BlockTemplate(Channel *self, Chip* chip, - Bit32u samples, Bit32s* output, - SynthMode mode ); -#define BLOCK_TEMPLATE(mode) \ - static Channel* Channel__BlockTemplate_ ## mode(Channel *self, Chip* chip, \ - Bit32u samples, Bit32s* output) \ - { \ - return Channel__BlockTemplate(self, chip, samples, output, mode); \ - } - -BLOCK_TEMPLATE(sm2AM) -BLOCK_TEMPLATE(sm2FM) -BLOCK_TEMPLATE(sm3AM) -BLOCK_TEMPLATE(sm3FM) -BLOCK_TEMPLATE(sm3FMFM) -BLOCK_TEMPLATE(sm3AMFM) -BLOCK_TEMPLATE(sm3FMAM) -BLOCK_TEMPLATE(sm3AMAM) -BLOCK_TEMPLATE(sm2Percussion) -BLOCK_TEMPLATE(sm3Percussion) - -//How much to substract from the base value for the final attenuation -static const Bit8u KslCreateTable[16] = { - //0 will always be be lower than 7 * 8 - 64, 32, 24, 19, - 16, 12, 11, 10, - 8, 6, 5, 4, - 3, 2, 1, 0, -}; - -#define M(_X_) ((Bit8u)( (_X_) * 2)) -static const Bit8u FreqCreateTable[16] = { - M(0.5), M(1 ), M(2 ), M(3 ), M(4 ), M(5 ), M(6 ), M(7 ), - M(8 ), M(9 ), M(10), M(10), M(12), M(12), M(15), M(15) -}; -#undef M - -//We're not including the highest attack rate, that gets a special value -static const Bit8u AttackSamplesTable[13] = { - 69, 55, 46, 40, - 35, 29, 23, 20, - 19, 15, 11, 10, - 9 -}; -//On a real opl these values take 8 samples to reach and are based upon larger tables -static const Bit8u EnvelopeIncreaseTable[13] = { - 4, 5, 6, 7, - 8, 10, 12, 14, - 16, 20, 24, 28, - 32, -}; - -#if ( DBOPL_WAVE == WAVE_HANDLER ) || ( DBOPL_WAVE == WAVE_TABLELOG ) -Bit16u *ExpTable=NULL; // [ 256 ]; -#endif - -#if ( DBOPL_WAVE == WAVE_HANDLER ) -//PI table used by WAVEHANDLER -Bit16u *SinTable = NULL; // [ 512 ]; -#endif - -#if ( DBOPL_WAVE > WAVE_HANDLER ) -//Layout of the waveform table in 512 entry intervals -//With overlapping waves we reduce the table to half it's size - -// | |//\\|____|WAV7|//__|/\ |____|/\/\| -// |\\//| | |WAV7| | \/| | | -// |06 |0126|17 |7 |3 |4 |4 5 |5 | - -//6 is just 0 shifted and masked - -Bit16s *WaveTable = NULL; // [ 8 * 512 ]; -//Distance into WaveTable the wave starts -static const Bit16u WaveBaseTable[8] = { - 0x000, 0x200, 0x200, 0x800, - 0xa00, 0xc00, 0x100, 0x400, - -}; -//Mask the counter with this -static const Bit16u WaveMaskTable[8] = { - 1023, 1023, 511, 511, - 1023, 1023, 512, 1023, -}; - -//Where to start the counter on at keyon -static const Bit16u WaveStartTable[8] = { - 512, 0, 0, 0, - 0, 512, 512, 256, -}; -#endif - -#if ( DBOPL_WAVE == WAVE_TABLEMUL ) -Bit16u *MulTable = NULL; // [ 384 ]; -#endif - -Bit8u *KslTable = NULL; // [ 8 * 16 ]; -Bit8u *TremoloTable = NULL; // [ TREMOLO_TABLE ]; -//Start of a channel behind the chip struct start -Bit16u *ChanOffsetTable = NULL; // [32]; -//Start of an operator behind the chip struct start -Bit16u *OpOffsetTable = NULL; // [64]; - -//The lower bits are the shift of the operator vibrato value -//The highest bit is right shifted to generate -1 or 0 for negation -//So taking the highest input value of 7 this gives 3, 7, 3, 0, -3, -7, -3, 0 -static const Bit8s VibratoTable[ 8 ] = { - 1 - 0x00, 0 - 0x00, 1 - 0x00, 30 - 0x00, - 1 - 0x80, 0 - 0x80, 1 - 0x80, 30 - 0x80 -}; - -//Shift strength for the ksl value determined by ksl strength -static const Bit8u KslShiftTable[4] = { - 31,1,2,0 -}; - -//Generate a table index and table shift value using input value from a selected rate -static void EnvelopeSelect( Bit8u val, Bit8u *index, Bit8u *shift ) { - if ( val < 13 * 4 ) { //Rate 0 - 12 - *shift = 12 - ( val >> 2 ); - *index = val & 3; - } else if ( val < 15 * 4 ) { //rate 13 - 14 - *shift = 0; - *index = val - 12 * 4; - } else { //rate 15 and up - *shift = 0; - *index = 12; - } -} - -#if ( DBOPL_WAVE == WAVE_HANDLER ) -/* - Generate the different waveforms out of the sine/exponetial table using handlers -*/ -static inline Bits MakeVolume( Bitu wave, Bitu volume ) { - Bitu total = wave + volume; - Bitu index = total & 0xff; - Bitu sig = ExpTable[ index ]; - Bitu exp = total >> 8; -#if 0 - //Check if we overflow the 31 shift limit - if ( exp >= 32 ) { - LOG_MSG( "WTF %d %d", total, exp ); - } -#endif - return (sig >> exp); -}; - -static Bits DB_FASTCALL WaveForm0( Bitu i, Bitu volume ) { - Bits neg = 0 - (( i >> 9) & 1);//Create ~0 or 0 - Bitu wave = SinTable[i & 511]; - return (MakeVolume( wave, volume ) ^ neg) - neg; -} -static Bits DB_FASTCALL WaveForm1( Bitu i, Bitu volume ) { - Bit32u wave = SinTable[i & 511]; - wave |= ( ( (i ^ 512 ) & 512) - 1) >> ( 32 - 12 ); - return MakeVolume( wave, volume ); -} -static Bits DB_FASTCALL WaveForm2( Bitu i, Bitu volume ) { - Bitu wave = SinTable[i & 511]; - return MakeVolume( wave, volume ); -} -static Bits DB_FASTCALL WaveForm3( Bitu i, Bitu volume ) { - Bitu wave = SinTable[i & 255]; - wave |= ( ( (i ^ 256 ) & 256) - 1) >> ( 32 - 12 ); - return MakeVolume( wave, volume ); -} -static Bits DB_FASTCALL WaveForm4( Bitu i, Bitu volume ) { - //Twice as fast - i <<= 1; - Bits neg = 0 - (( i >> 9) & 1);//Create ~0 or 0 - Bitu wave = SinTable[i & 511]; - wave |= ( ( (i ^ 512 ) & 512) - 1) >> ( 32 - 12 ); - return (MakeVolume( wave, volume ) ^ neg) - neg; -} -static Bits DB_FASTCALL WaveForm5( Bitu i, Bitu volume ) { - //Twice as fast - i <<= 1; - Bitu wave = SinTable[i & 511]; - wave |= ( ( (i ^ 512 ) & 512) - 1) >> ( 32 - 12 ); - return MakeVolume( wave, volume ); -} -static Bits DB_FASTCALL WaveForm6( Bitu i, Bitu volume ) { - Bits neg = 0 - (( i >> 9) & 1);//Create ~0 or 0 - return (MakeVolume( 0, volume ) ^ neg) - neg; -} -static Bits DB_FASTCALL WaveForm7( Bitu i, Bitu volume ) { - //Negative is reversed here - Bits neg = (( i >> 9) & 1) - 1; - Bitu wave = (i << 3); - //When negative the volume also runs backwards - wave = ((wave ^ neg) - neg) & 4095; - return (MakeVolume( wave, volume ) ^ neg) - neg; -} - -static const WaveHandler WaveHandlerTable[8] = { - WaveForm0, WaveForm1, WaveForm2, WaveForm3, - WaveForm4, WaveForm5, WaveForm6, WaveForm7 -}; - -#endif - -/* - Operator -*/ - -//We zero out when rate == 0 -static inline void Operator__UpdateAttack(Operator *self, const Chip* chip ) { - Bit8u rate = self->reg60 >> 4; - if ( rate ) { - Bit8u val = (rate << 2) + self->ksr; - self->attackAdd = chip->attackRates[ val ]; - self->rateZero &= ~(1 << ATTACK); - } else { - self->attackAdd = 0; - self->rateZero |= (1 << ATTACK); - } -} -static inline void Operator__UpdateDecay(Operator *self, const Chip* chip ) { - Bit8u rate = self->reg60 & 0xf; - if ( rate ) { - Bit8u val = (rate << 2) + self->ksr; - self->decayAdd = chip->linearRates[ val ]; - self->rateZero &= ~(1 << DECAY); - } else { - self->decayAdd = 0; - self->rateZero |= (1 << DECAY); - } -} -static inline void Operator__UpdateRelease(Operator *self, const Chip* chip ) { - Bit8u rate = self->reg80 & 0xf; - if ( rate ) { - Bit8u val = (rate << 2) + self->ksr; - self->releaseAdd = chip->linearRates[ val ]; - self->rateZero &= ~(1 << RELEASE); - if ( !(self->reg20 & MASK_SUSTAIN ) ) { - self->rateZero &= ~( 1 << SUSTAIN ); - } - } else { - self->rateZero |= (1 << RELEASE); - self->releaseAdd = 0; - if ( !(self->reg20 & MASK_SUSTAIN ) ) { - self->rateZero |= ( 1 << SUSTAIN ); - } - } -} - -static inline void Operator__UpdateAttenuation(Operator *self) { - Bit8u kslBase = (Bit8u)((self->chanData >> SHIFT_KSLBASE) & 0xff); - Bit32u tl = self->reg40 & 0x3f; - Bit8u kslShift = KslShiftTable[ self->reg40 >> 6 ]; - //Make sure the attenuation goes to the right bits - self->totalLevel = tl << ( ENV_BITS - 7 ); //Total level goes 2 bits below max - self->totalLevel += ( kslBase << ENV_EXTRA ) >> kslShift; -} - -static void Operator__UpdateFrequency(Operator *self) { - Bit32u freq = self->chanData & (( 1 << 10 ) - 1); - Bit32u block = (self->chanData >> 10) & 0xff; -#ifdef WAVE_PRECISION - block = 7 - block; - self->waveAdd = ( freq * self->freqMul ) >> block; -#else - self->waveAdd = ( freq << block ) * self->freqMul; -#endif - if ( self->reg20 & MASK_VIBRATO ) { - self->vibStrength = (Bit8u)(freq >> 7); - -#ifdef WAVE_PRECISION - self->vibrato = ( self->vibStrength * self->freqMul ) >> block; -#else - self->vibrato = ( self->vibStrength << block ) * self->freqMul; -#endif - } else { - self->vibStrength = 0; - self->vibrato = 0; - } -} - -static void Operator__UpdateRates(Operator *self, const Chip* chip ) { - //Mame seems to reverse this where enabling ksr actually lowers - //the rate, but pdf manuals says otherwise? - Bit8u newKsr = (Bit8u)((self->chanData >> SHIFT_KEYCODE) & 0xff); - if ( !( self->reg20 & MASK_KSR ) ) { - newKsr >>= 2; - } - if ( self->ksr == newKsr ) - return; - self->ksr = newKsr; - Operator__UpdateAttack( self, chip ); - Operator__UpdateDecay( self, chip ); - Operator__UpdateRelease( self, chip ); -} - -static inline Bit32s Operator__RateForward(Operator *self, Bit32u add ) { - Bit32s ret; - self->rateIndex += add; - /*Bit32s*/ ret = self->rateIndex >> RATE_SH; - self->rateIndex = self->rateIndex & RATE_MASK; - return ret; -} - -static Bits Operator__TemplateVolume(Operator *self, OperatorState yes) { - Bit32s vol = self->volume; - Bit32s change; - switch ( yes ) { - case OFF: - return ENV_MAX; - case ATTACK: - change = Operator__RateForward( self, self->attackAdd ); - if ( !change ) - return vol; - vol += ( (~vol) * change ) >> 3; - if ( vol < ENV_MIN ) { - self->volume = ENV_MIN; - self->rateIndex = 0; - Operator__SetState( self, DECAY ); - return ENV_MIN; - } - break; - case DECAY: - vol += Operator__RateForward( self, self->decayAdd ); - if ( GCC_UNLIKELY(vol >= self->sustainLevel) ) { - //Check if we didn't overshoot max attenuation, then just go off - if ( GCC_UNLIKELY(vol >= ENV_MAX) ) { - self->volume = ENV_MAX; - Operator__SetState( self, OFF ); - return ENV_MAX; - } - //Continue as sustain - self->rateIndex = 0; - Operator__SetState( self, SUSTAIN ); - } - break; - case SUSTAIN: - if ( self->reg20 & MASK_SUSTAIN ) { - return vol; - } - /* fallthrough */ - //In sustain phase, but not sustaining, do regular release - case RELEASE: - vol += Operator__RateForward( self, self->releaseAdd );; - if ( GCC_UNLIKELY(vol >= ENV_MAX) ) { - self->volume = ENV_MAX; - Operator__SetState( self, OFF ); - return ENV_MAX; - } - break; - } - self->volume = vol; - return vol; -} - -#define TEMPLATE_VOLUME(mode) \ - static Bits Operator__TemplateVolume ## mode(Operator *self) \ - { \ - return Operator__TemplateVolume(self, mode); \ - } - -TEMPLATE_VOLUME(OFF) -TEMPLATE_VOLUME(RELEASE) -TEMPLATE_VOLUME(SUSTAIN) -TEMPLATE_VOLUME(ATTACK) -TEMPLATE_VOLUME(DECAY) - -static const VolumeHandler VolumeHandlerTable[5] = { - &Operator__TemplateVolumeOFF, - &Operator__TemplateVolumeRELEASE, - &Operator__TemplateVolumeSUSTAIN, - &Operator__TemplateVolumeDECAY, - &Operator__TemplateVolumeATTACK, -}; - -static inline Bitu Operator__ForwardVolume(Operator *self) { - return self->currentLevel + (self->volHandler)(self); -} - - -static inline Bitu Operator__ForwardWave(Operator *self) { - self->waveIndex += self->waveCurrent; - return self->waveIndex >> WAVE_SH; -} - -static void Operator__Write20(Operator *self, const Chip* chip, Bit8u val ) { - Bit8u change = (self->reg20 ^ val ); - if ( !change ) - return; - self->reg20 = val; - //Shift the tremolo bit over the entire register, saved a branch, YES! - self->tremoloMask = (Bit8s)(val) >> 7; - self->tremoloMask &= ~(( 1 << ENV_EXTRA ) -1); - //Update specific features based on changes - if ( change & MASK_KSR ) { - Operator__UpdateRates( self, chip ); - } - //With sustain enable the volume doesn't change - if ( self->reg20 & MASK_SUSTAIN || ( !self->releaseAdd ) ) { - self->rateZero |= ( 1 << SUSTAIN ); - } else { - self->rateZero &= ~( 1 << SUSTAIN ); - } - //Frequency multiplier or vibrato changed - if ( change & (0xf | MASK_VIBRATO) ) { - self->freqMul = chip->freqMul[ val & 0xf ]; - Operator__UpdateFrequency(self); - } -} - -static void Operator__Write40(Operator *self, const Chip *chip, Bit8u val ) { - if (!(self->reg40 ^ val )) - return; - self->reg40 = val; - Operator__UpdateAttenuation( self ); -} - -static void Operator__Write60(Operator *self, const Chip* chip, Bit8u val ) { - Bit8u change = self->reg60 ^ val; - self->reg60 = val; - if ( change & 0x0f ) { - Operator__UpdateDecay( self, chip ); - } - if ( change & 0xf0 ) { - Operator__UpdateAttack( self, chip ); - } -} - -static void Operator__Write80(Operator *self, const Chip* chip, Bit8u val ) { - Bit8u change = (self->reg80 ^ val ); - Bit8u sustain; - if ( !change ) - return; - self->reg80 = val; - sustain = val >> 4; - //Turn 0xf into 0x1f - sustain |= ( sustain + 1) & 0x10; - self->sustainLevel = sustain << ( ENV_BITS - 5 ); - if ( change & 0x0f ) { - Operator__UpdateRelease( self, chip ); - } -} - -static void Operator__WriteE0(Operator *self, const Chip* chip, Bit8u val ) { - Bit8u waveForm; - if ( !(self->regE0 ^ val) ) - return; - //in opl3 mode you can always selet 7 waveforms regardless of waveformselect - waveForm = val & ( ( 0x3 & chip->waveFormMask ) | (0x7 & chip->opl3Active ) ); - self->regE0 = val; -#if( DBOPL_WAVE == WAVE_HANDLER ) - self->waveHandler = WaveHandlerTable[ waveForm ]; -#else - self->waveBase = WaveTable + WaveBaseTable[ waveForm ]; - self->waveStart = WaveStartTable[ waveForm ] << WAVE_SH; - self->waveMask = WaveMaskTable[ waveForm ]; -#endif -} - -static inline void Operator__SetState(Operator *self, Bit8u s ) { - self->state = s; - self->volHandler = VolumeHandlerTable[ s ]; -} - -static inline int Operator__Silent(Operator *self) { - if ( !ENV_SILENT( self->totalLevel + self->volume ) ) - return FALSE; - if ( !(self->rateZero & ( 1 << self->state ) ) ) - return FALSE; - return TRUE; -} - -static inline void Operator__Prepare(Operator *self, const Chip* chip ) { - self->currentLevel = self->totalLevel + (chip->tremoloValue & self->tremoloMask); - self->waveCurrent = self->waveAdd; - if ( self->vibStrength >> chip->vibratoShift ) { - Bit32s add = self->vibrato >> chip->vibratoShift; - //Sign extend over the shift value - Bit32s neg = chip->vibratoSign; - //Negate the add with -1 or 0 - add = ( add ^ neg ) - neg; - self->waveCurrent += add; - } -} - -static void Operator__KeyOn(Operator *self, Bit8u mask ) { - if ( !self->keyOn ) { - //Restart the frequency generator -#if( DBOPL_WAVE > WAVE_HANDLER ) - self->waveIndex = self->waveStart; -#else - self->waveIndex = 0; -#endif - self->rateIndex = 0; - Operator__SetState( self, ATTACK ); - } - self->keyOn |= mask; -} - -static void Operator__KeyOff(Operator *self, Bit8u mask ) { - self->keyOn &= ~mask; - if ( !self->keyOn ) { - if ( self->state != OFF ) { - Operator__SetState( self, RELEASE ); - } - } -} - -static inline Bits Operator__GetWave(Operator *self, Bitu index, Bitu vol ) { -#if( DBOPL_WAVE == WAVE_HANDLER ) - return self->waveHandler( index, vol << ( 3 - ENV_EXTRA ) ); -#elif( DBOPL_WAVE == WAVE_TABLEMUL ) - return(self->waveBase[ index & self->waveMask ] * MulTable[ vol >> ENV_EXTRA ]) >> MUL_SH; -#elif( DBOPL_WAVE == WAVE_TABLELOG ) - Bit32s wave = self->waveBase[ index & self->waveMask ]; - Bit32u total = ( wave & 0x7fff ) + vol << ( 3 - ENV_EXTRA ); - Bit32s sig = ExpTable[ total & 0xff ]; - Bit32u exp = total >> 8; - Bit32s neg = wave >> 16; - return((sig ^ neg) - neg) >> exp; -#else -#error "No valid wave routine" -#endif -} - -static inline Bits Operator__GetSample(Operator *self, Bits modulation ) { - Bitu vol = Operator__ForwardVolume(self); - if ( ENV_SILENT( vol ) ) { - //Simply forward the wave - self->waveIndex += self->waveCurrent; - return 0; - } else { - Bitu index = Operator__ForwardWave(self); - index += modulation; - return Operator__GetWave( self, index, vol ); - } -} - -static void Operator__Operator(Operator *self) { - self->chanData = 0; - self->freqMul = 0; - self->waveIndex = 0; - self->waveAdd = 0; - self->waveCurrent = 0; - self->keyOn = 0; - self->ksr = 0; - self->reg20 = 0; - self->reg40 = 0; - self->reg60 = 0; - self->reg80 = 0; - self->regE0 = 0; - Operator__SetState( self, OFF ); - self->rateZero = (1 << OFF); - self->sustainLevel = ENV_MAX; - self->currentLevel = ENV_MAX; - self->totalLevel = ENV_MAX; - self->volume = ENV_MAX; - self->releaseAdd = 0; -} - -/* - Channel -*/ - -static void Channel__Channel(Channel *self) { - Operator__Operator(&self->op[0]); - Operator__Operator(&self->op[1]); - self->old[0] = self->old[1] = 0; - self->chanData = 0; - self->regB0 = 0; - self->regC0 = 0; - self->maskLeft = -1; - self->maskRight = -1; - self->feedback = 31; - self->fourMask = 0; - self->synthHandler = Channel__BlockTemplate_sm2FM; -}; - -static inline Operator* Channel__Op( Channel *self, Bitu index ) { - return &( ( self + (index >> 1) )->op[ index & 1 ]); -} - -static void Channel__SetChanData(Channel *self, const Chip* chip, Bit32u data ) { - Bit32u change = self->chanData ^ data; - self->chanData = data; - Channel__Op( self, 0 )->chanData = data; - Channel__Op( self, 1 )->chanData = data; - //Since a frequency update triggered this, always update frequency - Operator__UpdateFrequency(Channel__Op( self, 0 )); - Operator__UpdateFrequency(Channel__Op( self, 1 )); - if ( change & ( 0xff << SHIFT_KSLBASE ) ) { - Operator__UpdateAttenuation(Channel__Op( self, 0 )); - Operator__UpdateAttenuation(Channel__Op( self, 1 )); - } - if ( change & ( 0xff << SHIFT_KEYCODE ) ) { - Operator__UpdateRates(Channel__Op( self, 0 ), chip); - Operator__UpdateRates(Channel__Op( self, 1 ), chip); - } -} - -static void Channel__UpdateFrequency(Channel *self, const Chip* chip, Bit8u fourOp ) { - //Extrace the frequency bits - Bit32u data = self->chanData & 0xffff; - Bit32u kslBase = KslTable[ data >> 6 ]; - Bit32u keyCode = ( data & 0x1c00) >> 9; - if ( chip->reg08 & 0x40 ) { - keyCode |= ( data & 0x100)>>8; /* notesel == 1 */ - } else { - keyCode |= ( data & 0x200)>>9; /* notesel == 0 */ - } - //Add the keycode and ksl into the highest bits of chanData - data |= (keyCode << SHIFT_KEYCODE) | ( kslBase << SHIFT_KSLBASE ); - Channel__SetChanData( self + 0, chip, data ); - if ( fourOp & 0x3f ) { - Channel__SetChanData( self + 1, chip, data ); - } -} - -static void Channel__WriteA0(Channel *self, const Chip* chip, Bit8u val ) { - Bit32u change; - Bit8u fourOp = chip->reg104 & chip->opl3Active & self->fourMask; - //Don't handle writes to silent fourop channels - if ( fourOp > 0x80 ) - return; - change = (self->chanData ^ val ) & 0xff; - if ( change ) { - self->chanData ^= change; - Channel__UpdateFrequency( self, chip, fourOp ); - } -} - -static void Channel__WriteB0(Channel *self, const Chip* chip, Bit8u val ) { - Bitu change; - Bit8u fourOp = chip->reg104 & chip->opl3Active & self->fourMask; - //Don't handle writes to silent fourop channels - if ( fourOp > 0x80 ) - return; - change = (self->chanData ^ ( val << 8 ) ) & 0x1f00; - if ( change ) { - self->chanData ^= change; - Channel__UpdateFrequency( self, chip, fourOp ); - } - //Check for a change in the keyon/off state - if ( !(( val ^ self->regB0) & 0x20)) - return; - self->regB0 = val; - if ( val & 0x20 ) { - Operator__KeyOn( Channel__Op(self, 0), 0x1 ); - Operator__KeyOn( Channel__Op(self, 1), 0x1 ); - if ( fourOp & 0x3f ) { - Operator__KeyOn( Channel__Op(self + 1, 0), 1 ); - Operator__KeyOn( Channel__Op(self + 1, 1), 1 ); - } - } else { - Operator__KeyOff( Channel__Op(self, 0), 0x1 ); - Operator__KeyOff( Channel__Op(self, 1), 0x1 ); - if ( fourOp & 0x3f ) { - Operator__KeyOff( Channel__Op(self + 1, 0), 1 ); - Operator__KeyOff( Channel__Op(self + 1, 1), 1 ); - } - } -} - -static void Channel__WriteC0(Channel *self, const Chip* chip, Bit8u val ) { - Bit8u synth; - Bit8u change = val ^ self->regC0; - if ( !change ) - return; - self->regC0 = val; - self->feedback = ( val >> 1 ) & 7; - if ( self->feedback ) { - //We shift the input to the right 10 bit wave index value - self->feedback = 9 - self->feedback; - } else { - self->feedback = 31; - } - //Select the new synth mode - if ( chip->opl3Active ) { - //4-op mode enabled for this channel - if ( (chip->reg104 & self->fourMask) & 0x3f ) { - Channel* chan0, *chan1; - //Check if it's the 2nd channel in a 4-op - if ( !(self->fourMask & 0x80 ) ) { - chan0 = self; - chan1 = self + 1; - } else { - chan0 = self - 1; - chan1 = self; - } - - synth = ( (chan0->regC0 & 1) << 0 )| (( chan1->regC0 & 1) << 1 ); - switch ( synth ) { - case 0: - chan0->synthHandler = Channel__BlockTemplate_sm3FMFM; - break; - case 1: - chan0->synthHandler = Channel__BlockTemplate_sm3AMFM; - break; - case 2: - chan0->synthHandler = Channel__BlockTemplate_sm3FMAM ; - break; - case 3: - chan0->synthHandler = Channel__BlockTemplate_sm3AMAM ; - break; - } - //Disable updating percussion channels - } else if ((self->fourMask & 0x40) && ( chip->regBD & 0x20) ) { - - //Regular dual op, am or fm - } else if ( val & 1 ) { - self->synthHandler = Channel__BlockTemplate_sm3AM; - } else { - self->synthHandler = Channel__BlockTemplate_sm3FM; - } - self->maskLeft = ( val & 0x10 ) ? -1 : 0; - self->maskRight = ( val & 0x20 ) ? -1 : 0; - //opl2 active - } else { - //Disable updating percussion channels - if ( (self->fourMask & 0x40) && ( chip->regBD & 0x20 ) ) { - - //Regular dual op, am or fm - } else if ( val & 1 ) { - self->synthHandler = Channel__BlockTemplate_sm2AM; - } else { - self->synthHandler = Channel__BlockTemplate_sm2FM; - } - } -} - -static void Channel__ResetC0(Channel *self, const Chip* chip ) { - Bit8u val = self->regC0; - self->regC0 ^= 0xff; - Channel__WriteC0( self, chip, val ); -}; - -static inline void Channel__GeneratePercussion(Channel *self, Chip* chip, - Bit32s* output, int opl3Mode ) { - Bit32u noiseBit, c2, c5, phaseBit, hhVol, sdVol, tcVol; - Bit32s sample; - Channel* chan = self; - - //BassDrum - Bit32s mod = (Bit32u)((self->old[0] + self->old[1])) >> self->feedback; - self->old[0] = self->old[1]; - self->old[1] = Operator__GetSample( Channel__Op(self, 0), mod ); - - //When bassdrum is in AM mode first operator is ignoed - if ( chan->regC0 & 1 ) { - mod = 0; - } else { - mod = self->old[0]; - } - sample = Operator__GetSample( Channel__Op(self, 1), mod ); - - //Precalculate stuff used by other outputs - noiseBit = Chip__ForwardNoise(chip) & 0x1; - c2 = Operator__ForwardWave(Channel__Op(self, 2)); - c5 = Operator__ForwardWave(Channel__Op(self, 5)); - phaseBit = (((c2 & 0x88) ^ ((c2<<5) & 0x80)) | ((c5 ^ (c5<<2)) & 0x20)) ? 0x02 : 0x00; - - //Hi-Hat - hhVol = Operator__ForwardVolume(Channel__Op(self, 2)); - if ( !ENV_SILENT( hhVol ) ) { - Bit32u hhIndex = (phaseBit<<8) | (0x34 << ( phaseBit ^ (noiseBit << 1 ))); - sample += Operator__GetWave( Channel__Op(self, 2), hhIndex, hhVol ); - } - //Snare Drum - sdVol = Operator__ForwardVolume( Channel__Op(self, 3) ); - if ( !ENV_SILENT( sdVol ) ) { - Bit32u sdIndex = ( 0x100 + (c2 & 0x100) ) ^ ( noiseBit << 8 ); - sample += Operator__GetWave( Channel__Op(self, 3), sdIndex, sdVol ); - } - //Tom-tom - sample += Operator__GetSample( Channel__Op(self, 4), 0 ); - - //Top-Cymbal - tcVol = Operator__ForwardVolume(Channel__Op(self, 5)); - if ( !ENV_SILENT( tcVol ) ) { - Bit32u tcIndex = (1 + phaseBit) << 8; - sample += Operator__GetWave( Channel__Op(self, 5), tcIndex, tcVol ); - } - sample <<= 1; - if ( opl3Mode ) { - output[0] += sample; - output[1] += sample; - } else { - output[0] += sample; - } -} - -Channel* Channel__BlockTemplate(Channel *self, Chip* chip, - Bit32u samples, Bit32s* output, - SynthMode mode ) { - Bitu i; - - switch( mode ) { - case sm2AM: - case sm3AM: - if ( Operator__Silent(Channel__Op(self, 0)) - && Operator__Silent(Channel__Op(self, 1))) { - self->old[0] = self->old[1] = 0; - return(self + 1); - } - break; - case sm2FM: - case sm3FM: - if ( Operator__Silent(Channel__Op(self, 1))) { - self->old[0] = self->old[1] = 0; - return (self + 1); - } - break; - case sm3FMFM: - if ( Operator__Silent(Channel__Op(self, 3))) { - self->old[0] = self->old[1] = 0; - return (self + 2); - } - break; - case sm3AMFM: - if ( Operator__Silent( Channel__Op(self, 0) ) - && Operator__Silent( Channel__Op(self, 3) )) { - self->old[0] = self->old[1] = 0; - return (self + 2); - } - break; - case sm3FMAM: - if ( Operator__Silent( Channel__Op(self, 1)) - && Operator__Silent( Channel__Op(self, 3))) { - self->old[0] = self->old[1] = 0; - return (self + 2); - } - break; - case sm3AMAM: - if ( Operator__Silent( Channel__Op(self, 0) ) - && Operator__Silent( Channel__Op(self, 2) ) - && Operator__Silent( Channel__Op(self, 3) )) { - self->old[0] = self->old[1] = 0; - return (self + 2); - } - break; - - default: - abort(); - } - //Init the operators with the the current vibrato and tremolo values - Operator__Prepare( Channel__Op( self, 0 ), chip ); - Operator__Prepare( Channel__Op( self, 1 ), chip ); - if ( mode > sm4Start ) { - Operator__Prepare( Channel__Op( self, 2 ), chip ); - Operator__Prepare( Channel__Op( self, 3 ), chip ); - } - if ( mode > sm6Start ) { - Operator__Prepare( Channel__Op( self, 4 ), chip ); - Operator__Prepare( Channel__Op( self, 5 ), chip ); - } - for ( i = 0; i < samples; i++ ) { - Bit32s mod, sample, out0; - Bits next; - //Early out for percussion handlers - if ( mode == sm2Percussion ) { - Channel__GeneratePercussion( self, chip, output + i, FALSE ); - continue; //Prevent some unitialized value bitching - } else if ( mode == sm3Percussion ) { - Channel__GeneratePercussion( self, chip, output + i * 2, TRUE ); - continue; //Prevent some unitialized value bitching - } - - //Do unsigned shift so we can shift out all bits but still stay in 10 bit range otherwise - mod = (Bit32u)((self->old[0] + self->old[1])) >> self->feedback; - self->old[0] = self->old[1]; - self->old[1] = Operator__GetSample( Channel__Op(self, 0), mod ); - sample = 0; - out0 = self->old[0]; - if ( mode == sm2AM || mode == sm3AM ) { - sample = out0 + Operator__GetSample( Channel__Op(self, 1), 0 ); - } else if ( mode == sm2FM || mode == sm3FM ) { - sample = Operator__GetSample( Channel__Op(self, 1), out0 ); - } else if ( mode == sm3FMFM ) { - next = Operator__GetSample( Channel__Op(self, 1), out0 ); - next = Operator__GetSample( Channel__Op(self, 2), next ); - sample = Operator__GetSample( Channel__Op(self, 3), next ); - } else if ( mode == sm3AMFM ) { - sample = out0; - next = Operator__GetSample( Channel__Op(self, 1), 0 ); - next = Operator__GetSample( Channel__Op(self, 2), next ); - sample += Operator__GetSample( Channel__Op(self, 3), next ); - } else if ( mode == sm3FMAM ) { - sample = Operator__GetSample( Channel__Op(self, 1), out0 ); - next = Operator__GetSample( Channel__Op(self, 2), 0 ); - sample += Operator__GetSample( Channel__Op(self, 3), next ); - } else if ( mode == sm3AMAM ) { - sample = out0; - next = Operator__GetSample( Channel__Op(self, 1), 0 ); - sample += Operator__GetSample( Channel__Op(self, 2), next ); - sample += Operator__GetSample( Channel__Op(self, 3), 0 ); - } - switch( mode ) { - case sm2AM: - case sm2FM: - output[ i ] += sample; - break; - case sm3AM: - case sm3FM: - case sm3FMFM: - case sm3AMFM: - case sm3FMAM: - case sm3AMAM: - output[ i * 2 + 0 ] += sample & self->maskLeft; - output[ i * 2 + 1 ] += sample & self->maskRight; - break; - default: - abort(); - } - } - switch( mode ) { - case sm2AM: - case sm2FM: - case sm3AM: - case sm3FM: - return ( self + 1 ); - case sm3FMFM: - case sm3AMFM: - case sm3FMAM: - case sm3AMAM: - return ( self + 2 ); - case sm2Percussion: - case sm3Percussion: - return( self + 3 ); - default: - abort(); - } - return 0; -} - -/* - Chip -*/ - -void Chip__Chip(Chip *self) { - int i; - - for (i=0; i<18; ++i) { - Channel__Channel(&self->chan[i]); - } - - self->reg08 = 0; - self->reg04 = 0; - self->regBD = 0; - self->reg104 = 0; - self->opl3Active = 0; -} - -static inline Bit32u Chip__ForwardNoise(Chip *self) { - Bitu count; - self->noiseCounter += self->noiseAdd; - count = self->noiseCounter >> LFO_SH; - self->noiseCounter &= WAVE_MASK; - for ( ; count > 0; --count ) { - //Noise calculation from mame - self->noiseValue ^= ( 0x800302 ) & ( 0 - (self->noiseValue & 1 ) ); - self->noiseValue >>= 1; - } - return self->noiseValue; -} - -static inline Bit32u Chip__ForwardLFO(Chip *self, Bit32u samples ) { - Bit32u todo, count; - //Current vibrato value, runs 4x slower than tremolo - self->vibratoSign = ( VibratoTable[ self->vibratoIndex >> 2] ) >> 7; - self->vibratoShift = ( VibratoTable[ self->vibratoIndex >> 2] & 7) + self->vibratoStrength; - self->tremoloValue = TremoloTable[ self->tremoloIndex ] >> self->tremoloStrength; - - //Check hom many samples there can be done before the value changes - todo = LFO_MAX - self->lfoCounter; - count = (todo + self->lfoAdd - 1) / self->lfoAdd; - if ( count > samples ) { - count = samples; - self->lfoCounter += count * self->lfoAdd; - } else { - self->lfoCounter += count * self->lfoAdd; - self->lfoCounter &= (LFO_MAX - 1); - //Maximum of 7 vibrato value * 4 - self->vibratoIndex = ( self->vibratoIndex + 1 ) & 31; - //Clip tremolo to the the table size - if ( self->tremoloIndex + 1 < TREMOLO_TABLE ) - ++self->tremoloIndex; - else - self->tremoloIndex = 0; - } - return count; -} - - -static void Chip__WriteBD(Chip *self, Bit8u val ) { - Bit8u change = self->regBD ^ val; - if ( !change ) - return; - self->regBD = val; - //TODO could do this with shift and xor? - self->vibratoStrength = (val & 0x40) ? 0x00 : 0x01; - self->tremoloStrength = (val & 0x80) ? 0x00 : 0x02; - if ( val & 0x20 ) { - //Drum was just enabled, make sure channel 6 has the right synth - if ( change & 0x20 ) { - if ( self->opl3Active ) { - self->chan[6].synthHandler - = Channel__BlockTemplate_sm3Percussion; - } else { - self->chan[6].synthHandler - = Channel__BlockTemplate_sm2Percussion; - } - } - //Bass Drum - if ( val & 0x10 ) { - Operator__KeyOn( &self->chan[6].op[0], 0x2 ); - Operator__KeyOn( &self->chan[6].op[1], 0x2 ); - } else { - Operator__KeyOff( &self->chan[6].op[0], 0x2 ); - Operator__KeyOff( &self->chan[6].op[1], 0x2 ); - } - //Hi-Hat - if ( val & 0x1 ) { - Operator__KeyOn( &self->chan[7].op[0], 0x2 ); - } else { - Operator__KeyOff( &self->chan[7].op[0], 0x2 ); - } - //Snare - if ( val & 0x8 ) { - Operator__KeyOn( &self->chan[7].op[1], 0x2 ); - } else { - Operator__KeyOff( &self->chan[7].op[1], 0x2 ); - } - //Tom-Tom - if ( val & 0x4 ) { - Operator__KeyOn( &self->chan[8].op[0], 0x2 ); - } else { - Operator__KeyOff( &self->chan[8].op[0], 0x2 ); - } - //Top Cymbal - if ( val & 0x2 ) { - Operator__KeyOn( &self->chan[8].op[1], 0x2 ); - } else { - Operator__KeyOff( &self->chan[8].op[1], 0x2 ); - } - //Toggle keyoffs when we turn off the percussion - } else if ( change & 0x20 ) { - //Trigger a reset to setup the original synth handler - Channel__ResetC0( &self->chan[6], self ); - Operator__KeyOff( &self->chan[6].op[0], 0x2 ); - Operator__KeyOff( &self->chan[6].op[1], 0x2 ); - Operator__KeyOff( &self->chan[7].op[0], 0x2 ); - Operator__KeyOff( &self->chan[7].op[1], 0x2 ); - Operator__KeyOff( &self->chan[8].op[0], 0x2 ); - Operator__KeyOff( &self->chan[8].op[1], 0x2 ); - } -} - - -#define REGOP( _FUNC_ ) \ - index = ( ( reg >> 3) & 0x20 ) | ( reg & 0x1f ); \ - if ( OpOffsetTable[ index ] ) { \ - Operator* regOp = (Operator*)( ((char *)self ) + OpOffsetTable[ index ] ); \ - Operator__ ## _FUNC_ (regOp, self, val); \ - } - -#define REGCHAN( _FUNC_ ) \ - index = ( ( reg >> 4) & 0x10 ) | ( reg & 0xf ); \ - if ( ChanOffsetTable[ index ] ) { \ - Channel* regChan = (Channel*)( ((char *)self ) + ChanOffsetTable[ index ] ); \ - Channel__ ## _FUNC_ (regChan, self, val); \ - } - -void Chip__WriteReg(Chip *self, Bit32u reg, Bit8u val ) { - Bitu index; - switch ( (reg & 0xf0) >> 4 ) { - case 0x00 >> 4: - if ( reg == 0x01 ) { - self->waveFormMask = ( val & 0x20 ) ? 0x7 : 0x0; - } else if ( reg == 0x104 ) { - //Only detect changes in lowest 6 bits - if ( !((self->reg104 ^ val) & 0x3f) ) - return; - //Always keep the highest bit enabled, for checking > 0x80 - self->reg104 = 0x80 | ( val & 0x3f ); - } else if ( reg == 0x105 ) { - int i; - - //MAME says the real opl3 doesn't reset anything on opl3 disable/enable till the next write in another register - if ( !((self->opl3Active ^ val) & 1 ) ) - return; - self->opl3Active = ( val & 1 ) ? 0xff : 0; - //Update the 0xc0 register for all channels to signal the switch to mono/stereo handlers - for ( i = 0; i < 18;i++ ) { - Channel__ResetC0( &self->chan[i], self ); - } - } else if ( reg == 0x08 ) { - self->reg08 = val; - } - case 0x10 >> 4: - break; - case 0x20 >> 4: - case 0x30 >> 4: - REGOP( Write20 ); - break; - case 0x40 >> 4: - case 0x50 >> 4: - REGOP( Write40 ); - break; - case 0x60 >> 4: - case 0x70 >> 4: - REGOP( Write60 ); - break; - case 0x80 >> 4: - case 0x90 >> 4: - REGOP( Write80 ); - break; - case 0xa0 >> 4: - REGCHAN( WriteA0 ); - break; - case 0xb0 >> 4: - if ( reg == 0xbd ) { - Chip__WriteBD( self, val ); - } else { - REGCHAN( WriteB0 ); - } - break; - case 0xc0 >> 4: - REGCHAN( WriteC0 ); - case 0xd0 >> 4: - break; - case 0xe0 >> 4: - case 0xf0 >> 4: - REGOP( WriteE0 ); - break; - } -} - -Bit32u Chip__WriteAddr(Chip *self, Bit32u port, Bit8u val ) { - switch ( port & 3 ) { - case 0: - return val; - case 2: - if ( self->opl3Active || (val == 0x05) ) - return 0x100 | val; - else - return val; - } - return 0; -} - -void Chip__GenerateBlock2(Chip *self, Bitu total, Bit32s* output ) { - while ( total > 0 ) { - Channel *ch; - int count; - - Bit32u samples = Chip__ForwardLFO( self, total ); - memset(output, 0, sizeof(Bit32s) * samples); - count = 0; - for ( ch = self->chan; ch < self->chan + 9; ) { - count++; - ch = (ch->synthHandler)( ch, self, samples, output ); - } - total -= samples; - output += samples; - } -} - -void Chip__GenerateBlock3(Chip *self, Bitu total, Bit32s* output ) { - while ( total > 0 ) { - int count; - Channel *ch; - - Bit32u samples = Chip__ForwardLFO( self, total ); - memset(output, 0, sizeof(Bit32s) * samples *2); - count = 0; - for ( ch = self->chan; ch < self->chan + 18; ) { - count++; - ch = (ch->synthHandler)( ch, self, samples, output ); - } - total -= samples; - output += samples * 2; - } -} - -void Chip__Setup(Chip *self, Bit32u rate ) { - double original = OPLRATE; - Bit32u i; -// double original = rate; - double scale = original / (double)rate; - - //Noise counter is run at the same precision as general waves - self->noiseAdd = (Bit32u)( 0.5 + scale * ( 1 << LFO_SH ) ); - self->noiseCounter = 0; - self->noiseValue = 1; //Make sure it triggers the noise xor the first time - //The low frequency oscillation counter - //Every time his overflows vibrato and tremoloindex are increased - self->lfoAdd = (Bit32u)( 0.5 + scale * ( 1 << LFO_SH ) ); - self->lfoCounter = 0; - self->vibratoIndex = 0; - self->tremoloIndex = 0; - - //With higher octave this gets shifted up - //-1 since the freqCreateTable = *2 - { -#ifdef WAVE_PRECISION - double freqScale = ( 1 << 7 ) * scale * ( 1 << ( WAVE_SH - 1 - 10)); - for ( i = 0; i < 16; i++ ) { - self->freqMul[i] = (Bit32u)( 0.5 + freqScale * FreqCreateTable[ i ] ); - } -#else - Bit32u freqScale = (Bit32u)( 0.5 + scale * ( 1 << ( WAVE_SH - 1 - 10))); - for ( i = 0; i < 16; i++ ) { - self->freqMul[i] = freqScale * FreqCreateTable[ i ]; - } -#endif - } - - //-3 since the real envelope takes 8 steps to reach the single value we supply - for ( i = 0; i < 76; i++ ) { - Bit8u index, shift; - EnvelopeSelect( (Bit8u) i, &index, &shift ); - self->linearRates[i] = (Bit32u)( scale * (EnvelopeIncreaseTable[ index ] << ( RATE_SH + ENV_EXTRA - shift - 3 ))); - } - //Generate the best matching attack rate - for ( i = 0; i < 62; i++ ) { - Bit8u index, shift; - Bit32s original, guessAdd, bestAdd, bestDiff; - Bit32u passes; - EnvelopeSelect( (Bit8u) i, &index, &shift ); - //Original amount of samples the attack would take - original = (Bit32u)( (AttackSamplesTable[ index ] << shift) / scale); - - guessAdd = (Bit32u)( scale * (EnvelopeIncreaseTable[ index ] << ( RATE_SH - shift - 3 ))); - bestAdd = guessAdd; - bestDiff = 1 << 30; - - for ( passes = 0; passes < 16; passes ++ ) { - Bit32s diff, lDiff; - Bit32s volume = ENV_MAX; - Bit32s samples = 0; - Bit32u count = 0; - while ( volume > 0 && samples < original * 2 ) { - Bit32s change; - count += guessAdd; - change = count >> RATE_SH; - count &= RATE_MASK; - if ( GCC_UNLIKELY(change) ) { // less than 1 % - volume += ( ~volume * change ) >> 3; - } - samples++; - - } - diff = original - samples; - lDiff = labs( diff ); - //Init last on first pass - if ( lDiff < bestDiff ) { - bestDiff = lDiff; - bestAdd = guessAdd; - if ( !bestDiff ) - break; - } - //Below our target - if ( diff < 0 ) { - //Better than the last time - Bit32s mul = ((original - diff) << 12) / original; - guessAdd = ((guessAdd * mul) >> 12); - guessAdd++; - } else if ( diff > 0 ) { - Bit32s mul = ((original - diff) << 12) / original; - guessAdd = (guessAdd * mul) >> 12; - guessAdd--; - } - } - self->attackRates[i] = bestAdd; - } - for ( i = 62; i < 76; i++ ) { - //This should provide instant volume maximizing - self->attackRates[i] = 8 << RATE_SH; - } - //Setup the channels with the correct four op flags - //Channels are accessed through a table so they appear linear here - self->chan[ 0].fourMask = 0x00 | ( 1 << 0 ); - self->chan[ 1].fourMask = 0x80 | ( 1 << 0 ); - self->chan[ 2].fourMask = 0x00 | ( 1 << 1 ); - self->chan[ 3].fourMask = 0x80 | ( 1 << 1 ); - self->chan[ 4].fourMask = 0x00 | ( 1 << 2 ); - self->chan[ 5].fourMask = 0x80 | ( 1 << 2 ); - - self->chan[ 9].fourMask = 0x00 | ( 1 << 3 ); - self->chan[10].fourMask = 0x80 | ( 1 << 3 ); - self->chan[11].fourMask = 0x00 | ( 1 << 4 ); - self->chan[12].fourMask = 0x80 | ( 1 << 4 ); - self->chan[13].fourMask = 0x00 | ( 1 << 5 ); - self->chan[14].fourMask = 0x80 | ( 1 << 5 ); - - //mark the percussion channels - self->chan[ 6].fourMask = 0x40; - self->chan[ 7].fourMask = 0x40; - self->chan[ 8].fourMask = 0x40; - - //Clear Everything in opl3 mode - Chip__WriteReg( self, 0x105, 0x1 ); - for ( i = 0; i < 512; i++ ) { - if ( i == 0x105 ) - continue; - Chip__WriteReg( self, i, 0xff ); - Chip__WriteReg( self, i, 0x0 ); - } - Chip__WriteReg( self, 0x105, 0x0 ); - //Clear everything in opl2 mode - for ( i = 0; i < 255; i++ ) { - Chip__WriteReg( self, i, 0xff ); - Chip__WriteReg( self, i, 0x0 ); - } -} - -void DBOPL_InitTables( void ) { - int i, oct; - Chip *chip = NULL; - - // NOTE: no "already done" guard here. The wave/volume tables below live in - // buffers that are shared_malloc'd fresh (and zeroed) on every emulator - // launch, so they MUST be repopulated each launch. A static doneTables guard - // used to skip this on relaunch, leaving the tables all-zero -> the OPL synth - // produced pure silence (music dead on the 2nd+ launch; SFX are PCM and - // unaffected). DBOPL_InitTables is only called once per launch (from - // OPL_Init), so unconditional init is correct and cheap. -#if ( DBOPL_WAVE == WAVE_HANDLER ) || ( DBOPL_WAVE == WAVE_TABLELOG ) - //Exponential volume table, same as the real adlib - for ( i = 0; i < 256; i++ ) { - //Save them in reverse - ExpTable[i] = (int)( 0.5 + ( pow(2.0, ( 255 - i) * ( 1.0 /256 ) )-1) * 1024 ); - ExpTable[i] += 1024; //or remove the -1 oh well :) - //Preshift to the left once so the final volume can shift to the right - ExpTable[i] *= 2; - } -#endif -#if ( DBOPL_WAVE == WAVE_HANDLER ) - //Add 0.5 for the trunc rounding of the integer cast - //Do a PI sinetable instead of the original 0.5 PI - for ( i = 0; i < 512; i++ ) { - SinTable[i] = (Bit16s)( 0.5 - log10( sin( (i + 0.5) * (PI / 512.0) ) ) / log10(2.0)*256 ); - } -#endif -#if ( DBOPL_WAVE == WAVE_TABLEMUL ) - //Multiplication based tables - for ( i = 0; i < 384; i++ ) { - int s = i * 8; - //TODO maybe keep some of the precision errors of the original table? - double val = ( 0.5 + ( pow(2.0, -1.0 + ( 255 - s) * ( 1.0 /256 ) )) * ( 1 << MUL_SH )); - MulTable[i] = (Bit16u)(val); - } - - //Sine Wave Base - for ( i = 0; i < 512; i++ ) { - WaveTable[ 0x0200 + i ] = (Bit16s)(sin( (i + 0.5) * (PI / 512.0) ) * 4084); - WaveTable[ 0x0000 + i ] = -WaveTable[ 0x200 + i ]; - } - //Exponential wave - for ( i = 0; i < 256; i++ ) { - WaveTable[ 0x700 + i ] = (Bit16s)( 0.5 + ( pow(2.0, -1.0 + ( 255 - i * 8) * ( 1.0 /256 ) ) ) * 4085 ); - WaveTable[ 0x6ff - i ] = -WaveTable[ 0x700 + i ]; - } -#endif -#if ( DBOPL_WAVE == WAVE_TABLELOG ) - //Sine Wave Base - for ( i = 0; i < 512; i++ ) { - WaveTable[ 0x0200 + i ] = (Bit16s)( 0.5 - log10( sin( (i + 0.5) * (PI / 512.0) ) ) / log10(2.0)*256 ); - WaveTable[ 0x0000 + i ] = ((Bit16s)0x8000) | WaveTable[ 0x200 + i]; - } - //Exponential wave - for ( i = 0; i < 256; i++ ) { - WaveTable[ 0x700 + i ] = i * 8; - WaveTable[ 0x6ff - i ] = ((Bit16s)0x8000) | i * 8; - } -#endif - - // | |//\\|____|WAV7|//__|/\ |____|/\/\| - // |\\//| | |WAV7| | \/| | | - // |06 |0126|27 |7 |3 |4 |4 5 |5 | - -#if (( DBOPL_WAVE == WAVE_TABLELOG ) || ( DBOPL_WAVE == WAVE_TABLEMUL )) - for ( i = 0; i < 256; i++ ) { - //Fill silence gaps - WaveTable[ 0x400 + i ] = WaveTable[0]; - WaveTable[ 0x500 + i ] = WaveTable[0]; - WaveTable[ 0x900 + i ] = WaveTable[0]; - WaveTable[ 0xc00 + i ] = WaveTable[0]; - WaveTable[ 0xd00 + i ] = WaveTable[0]; - //Replicate sines in other pieces - WaveTable[ 0x800 + i ] = WaveTable[ 0x200 + i ]; - //double speed sines - WaveTable[ 0xa00 + i ] = WaveTable[ 0x200 + i * 2 ]; - WaveTable[ 0xb00 + i ] = WaveTable[ 0x000 + i * 2 ]; - WaveTable[ 0xe00 + i ] = WaveTable[ 0x200 + i * 2 ]; - WaveTable[ 0xf00 + i ] = WaveTable[ 0x200 + i * 2 ]; - } -#endif - - //Create the ksl table - for ( oct = 0; oct < 8; oct++ ) { - int base = oct * 8; - for ( i = 0; i < 16; i++ ) { - int val = base - KslCreateTable[i]; - if ( val < 0 ) - val = 0; - //*4 for the final range to match attenuation range - KslTable[ oct * 16 + i ] = val * 4; - } - } - //Create the Tremolo table, just increase and decrease a triangle wave - for ( i = 0; i < TREMOLO_TABLE / 2; i++ ) { - Bit8u val = i << ENV_EXTRA; - TremoloTable[i] = val; - TremoloTable[TREMOLO_TABLE - 1 - i] = val; - } - //Create a table with offsets of the channels from the start of the chip - for ( i = 0; i < 32; i++ ) { - Bitu blah; - Bitu index = i & 0xf; - if ( index >= 9 ) { - ChanOffsetTable[i] = 0; - continue; - } - //Make sure the four op channels follow eachother - if ( index < 6 ) { - index = (index % 3) * 2 + ( index / 3 ); - } - //Add back the bits for highest ones - if ( i >= 16 ) - index += 9; - blah = (Bitu) ( &(chip->chan[ index ]) ); - ChanOffsetTable[i] = (Bit16u) blah; - } - //Same for operators - for ( i = 0; i < 64; i++ ) { - Bitu chNum, opNum, blah; - Channel* chan = NULL; - if ( i % 8 >= 6 || ( (i / 8) % 4 == 3 ) ) { - OpOffsetTable[i] = 0; - continue; - } - chNum = (i / 8) * 3 + (i % 8) % 3; - //Make sure we use 16 and up for the 2nd range to match the chanoffset gap - if ( chNum >= 12 ) - chNum += 16 - 12; - opNum = ( i % 8 ) / 3; - blah = (Bitu) ( &(chan->op[opNum]) ); - OpOffsetTable[i] = (Bit16u) (ChanOffsetTable[ chNum ] + blah); - } -#if 0 - //Stupid checks if table's are correct - for ( Bitu i = 0; i < 18; i++ ) { - Bit32u find = (Bit16u)( &(chip->chan[ i ]) ); - for ( Bitu c = 0; c < 32; c++ ) { - if ( ChanOffsetTable[c] == find ) { - find = 0; - break; - } - } - if ( find ) { - find = find; - } - } - for ( Bitu i = 0; i < 36; i++ ) { - Bit32u find = (Bit16u)( &(chip->chan[ i / 2 ].op[i % 2]) ); - for ( Bitu c = 0; c < 64; c++ ) { - if ( OpOffsetTable[c] == find ) { - find = 0; - break; - } - } - if ( find ) { - find = find; - } - } -#endif -} - - diff --git a/components/doom/prboom/dbopl.h b/components/doom/prboom/dbopl.h deleted file mode 100644 index cc31850a..00000000 --- a/components/doom/prboom/dbopl.h +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright (C) 2002-2010 The DOSBox 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. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ - -//#include "inttypes.h" //NSM -#include -#include - -#ifdef _MSC_VER - #if _MSC_VER < 1300 - #include - typedef INT_PTR intptr_t; - #endif -#endif - -//Use 8 handlers based on a small logatirmic wavetabe and an exponential table for volume -#define WAVE_HANDLER 10 -//Use a logarithmic wavetable with an exponential table for volume -#define WAVE_TABLELOG 11 -//Use a linear wavetable with a multiply table for volume -#define WAVE_TABLEMUL 12 - -//Select the type of wave generator routine -#define DBOPL_WAVE WAVE_TABLEMUL - -#define TREMOLO_TABLE 52 - -typedef struct _Chip Chip; -typedef struct _Operator Operator; -typedef struct _Channel Channel; - -typedef uintptr_t Bitu; -typedef intptr_t Bits; -typedef uint32_t Bit32u; -typedef int32_t Bit32s; -typedef uint16_t Bit16u; -typedef int16_t Bit16s; -typedef uint8_t Bit8u; -typedef int8_t Bit8s; - -#if (DBOPL_WAVE == WAVE_HANDLER) -typedef Bits ( DB_FASTCALL *WaveHandler) ( Bitu i, Bitu volume ); -#endif - -#define DB_FASTCALL - -typedef Bits (*VolumeHandler)(Operator *self); -typedef Channel* (*SynthHandler)(Channel *self, Chip* chip, Bit32u samples, Bit32s* output ); - -//Different synth modes that can generate blocks of data -typedef enum { - sm2AM, - sm2FM, - sm3AM, - sm3FM, - sm4Start, - sm3FMFM, - sm3AMFM, - sm3FMAM, - sm3AMAM, - sm6Start, - sm2Percussion, - sm3Percussion, -} SynthMode; - -//Shifts for the values contained in chandata variable -enum { - SHIFT_KSLBASE = 16, - SHIFT_KEYCODE = 24, -}; - -//Masks for operator 20 values -enum { - MASK_KSR = 0x10, - MASK_SUSTAIN = 0x20, - MASK_VIBRATO = 0x40, - MASK_TREMOLO = 0x80, -}; - -typedef enum { - OFF, - RELEASE, - SUSTAIN, - DECAY, - ATTACK, -} OperatorState; - -struct _Operator { - VolumeHandler volHandler; - -#if (DBOPL_WAVE == WAVE_HANDLER) - WaveHandler waveHandler; //Routine that generate a wave -#else - Bit16s* waveBase; - Bit32u waveMask; - Bit32u waveStart; -#endif - Bit32u waveIndex; //WAVE_BITS shifted counter of the frequency index - Bit32u waveAdd; //The base frequency without vibrato - Bit32u waveCurrent; //waveAdd + vibratao - - Bit32u chanData; //Frequency/octave and derived data coming from whatever channel controls this - Bit32u freqMul; //Scale channel frequency with this, TODO maybe remove? - Bit32u vibrato; //Scaled up vibrato strength - Bit32s sustainLevel; //When stopping at sustain level stop here - Bit32s totalLevel; //totalLevel is added to every generated volume - Bit32u currentLevel; //totalLevel + tremolo - Bit32s volume; //The currently active volume - - Bit32u attackAdd; //Timers for the different states of the envelope - Bit32u decayAdd; - Bit32u releaseAdd; - Bit32u rateIndex; //Current position of the evenlope - - Bit8u rateZero; //Bits for the different states of the envelope having no changes - Bit8u keyOn; //Bitmask of different values that can generate keyon - //Registers, also used to check for changes - Bit8u reg20, reg40, reg60, reg80, regE0; - //Active part of the envelope we're in - Bit8u state; - //0xff when tremolo is enabled - Bit8u tremoloMask; - //Strength of the vibrato - Bit8u vibStrength; - //Keep track of the calculated KSR so we can check for changes - Bit8u ksr; -}; - -struct _Channel { - Operator op[2]; - SynthHandler synthHandler; - Bit32u chanData; //Frequency/octave and derived values - Bit32s old[2]; //Old data for feedback - - Bit8u feedback; //Feedback shift - Bit8u regB0; //Register values to check for changes - Bit8u regC0; - //This should correspond with reg104, bit 6 indicates a Percussion channel, bit 7 indicates a silent channel - Bit8u fourMask; - Bit8s maskLeft; //Sign extended values for both channel's panning - Bit8s maskRight; - -}; - -struct _Chip { - //This is used as the base counter for vibrato and tremolo - Bit32u lfoCounter; - Bit32u lfoAdd; - - - Bit32u noiseCounter; - Bit32u noiseAdd; - Bit32u noiseValue; - - //Frequency scales for the different multiplications - Bit32u freqMul[16]; - //Rates for decay and release for rate of this chip - Bit32u linearRates[76]; - //Best match attack rates for the rate of this chip - Bit32u attackRates[76]; - - //18 channels with 2 operators each - Channel chan[18]; - - Bit8u reg104; - Bit8u reg08; - Bit8u reg04; - Bit8u regBD; - Bit8u vibratoIndex; - Bit8u tremoloIndex; - Bit8s vibratoSign; - Bit8u vibratoShift; - Bit8u tremoloValue; - Bit8u vibratoStrength; - Bit8u tremoloStrength; - //Mask for allowed wave forms - Bit8u waveFormMask; - //0 or -1 when enabled - Bit8s opl3Active; - -}; - -/* -struct Handler : public Adlib::Handler { - DBOPL::Chip chip; - virtual Bit32u WriteAddr( Bit32u port, Bit8u val ); - virtual void WriteReg( Bit32u addr, Bit8u val ); - virtual void Generate( MixerChannel* chan, Bitu samples ); - virtual void Init( Bitu rate ); -}; -*/ - -#ifdef __cplusplus -extern "C" void Chip__Setup(Chip *self, Bit32u rate ); -extern "C" void DBOPL_InitTables( void ); -extern "C" void Chip__Chip(Chip *self); -extern "C" void Chip__WriteReg(Chip *self, Bit32u reg, Bit8u val ); -extern "C" void Chip__GenerateBlock2(Chip *self, Bitu total, Bit32s* output ); -#else -void Chip__Setup(Chip *self, Bit32u rate ); -void DBOPL_InitTables( void ); -void Chip__Chip(Chip *self); -void Chip__WriteReg(Chip *self, Bit32u reg, Bit8u val ); -void Chip__GenerateBlock2(Chip *self, Bitu total, Bit32s* output ); - -#endif - diff --git a/components/doom/prboom/docs/DMSPEC16.txt b/components/doom/prboom/docs/DMSPEC16.txt deleted file mode 100644 index e5094fa9..00000000 --- a/components/doom/prboom/docs/DMSPEC16.txt +++ /dev/null @@ -1,3810 +0,0 @@ -From MSFell@aol.com Thu Dec 15 1994, upload as DMSPEC16.ZIP - - ------------------------------------------------------------------------------- - - T H E U N O F F I C I A L -================= =============== =============== ================ -\\ . . . . . . .\\ //. . . . . . .\\ //. . . . . . .\\ \\. . .\\// . .// -||. . ._____. . .|| ||. . ._____. . .|| ||. . ._____. . .|| || . . .\/ . ..|| -|| . .|| ||. . || || . .|| ||. . || || . .|| ||. . || ||. . . . . . .|| -||. . || || . .|| ||. . || || . .|| ||. . || || . .|| || . | . . . ..|| -|| . .|| ||. _-|| ||-_ .|| ||. . || || . .|| ||. _-|| ||-_.|\ . . . .|| -||. . || ||-' || || `-|| || . .|| ||. . || ||-' || || `|\_ . .|..|| -|| . _|| || || || || ||_ . || || . _|| || || || |\ `-_/| .|| -||_-' || .|/ || || \|. || `-_|| ||_-' || .|/ || || | \ / -_.|| -|| ||_-' || || `-_|| || || ||_-' || || | \ / | '|| -|| `' || || `' || || `' || || | \ / | || -|| .===' `===. .==='.`===. .===' /==. | \/ | || -|| .==' \_|-_ `===. .===' _|_ `===. .===' _-|/ `== \/ | || -|| .==' _-' `-_ `=' _-' `-_ `=' _-' `-_ /| \/ | || -|| .==' _-' `-__\._-' `-_./__-' `' |. /| | || -||.==' _-' `' | /==.|| -==' _-' S P E C S \/ `== -\ _-' `-_ / - `'' ``' - Release v1.666 - December 15th, 1994 - Written by: Matthew S Fell (msfell@aol.com) - - "The poets talk about love, ...but what I talk about is DOOM, - because in the end, DOOM is all that counts." - - Alex Machine/George Stark/Stephen King, _The Dark Half_ ------------------------------------------------------------------------------- - - - - - - - - ----------- -DISCLAIMER ----------- - - These specs are to aid in informing the public about the games -DOOM and DOOM 2, by id Software. In no way should this promote your -killing yourself, killing others, or killing in any other fashion. -Additionally, the author does not claim ANY responsibility -regarding ANY illegal activity concerning this file, or indirectly related -to this file. The information contained in this file only reflects -id Software indirectly, and questioning id Software regarding any -information in this file is not recommended. - ----------------- -COPYRIGHT NOTICE ----------------- - -This article is Copyright 1994 by Matt Fell. All rights reserved. -You are granted the following rights: - -I. To make copies of this work in original form, so long as - (a) the copies are exact and complete; - (b) the copies include the copyright notice and these paragraphs - in their entirety; - (c) the copies give obvious credit to the author, Matt Fell; - (d) the copies are in electronic form. -II. To distribute this work, or copies made under the provisions - above, so long as - (a) this is the original work and not a derivative form; - (b) you do not charge a fee for copying or for distribution; - (c) you ensure that the distributed form includes the copyright - notice, this paragraph, the disclaimer of warranty in - their entirety and credit to the author; - (d) the distributed form is not in an electronic magazine or - within computer software (prior explicit permission may be - obtained from the author); - (e) the distributed form is the NEWEST version of the article to - the best of the knowledge of the distributor; - (f) the distributed form is electronic. - - You may not distribute this work by any non-electronic media, -including but not limited to books, newsletters, magazines, manuals, -catalogs, and speech. You may not distribute this work in electronic -magazines or within computer software without prior written explicit -permission. These rights are temporary and revocable upon written, oral, -or other notice by the author. This copyright notice shall be governed -by the laws of the state of Ohio. - If you would like additional rights beyond those granted above, -write to the author at "msfell@aol.com" on the Internet. - - --------- -CONTENTS --------- - -[1] Introduction - [1-1] id Software's Copyright - [1-2] What's New -[2] The Basics - [2-1] Pwads - [2-2] DOOM version information - [2-3] Terminology conventions -[3] List of DOOM.WAD Directory Entries -[4] The Levels - [4-1] ExMy or MAPxy - [4-2] THINGS - [4-2-1] Thing Types - [4-2-2] Thing Sizes - [4-2-3] Thing Options - [4-3] LINEDEFS - [4-3-1] Linedef Flags - [4-3-2] Linedef Types - [4-4] SIDEDEFS - [4-5] VERTEXES - [4-6] SEGS - [4-7] SSECTORS - [4-8] NODES - [4-9] SECTORS - [4-9-1] Special Sector Types - [4-10] REJECT - [4-11] BLOCKMAP -[5] Graphics - [5-1] Picture Format -[6] Flats (Floor and Ceiling Textures) - [6-1] Animated Floors, see [8-4-1] -[7] Sounds and Music - [7-1] PC Speaker Sound Effects - [7-2] Soundcard Sound Effects - [7-3] Music - [7-4] GENMIDI - [7-5] DMXGUS -[8] Miscellaneous Lumps - [8-1] PLAYPAL - [8-2] COLORMAP - [8-3] ENDOOM - [8-4] TEXTURE1 and TEXTURE2 - [8-4-1] Animated Walls - [8-4-2] The SKY Textures - [8-5] PNAMES - [8-6] DEMOs - [8-6-1] Level changes from 1.2 to 1.666 DOOM.WAD -[9] Savegame Files - -[10] The DOOM.EXE File - [10-1] Version 1.2 DOOM.EXE Data Segment Overview - [10-1] Version 1.666 DOOM.EXE Data Segment Overview - [10-3] Detail on some EXE Data Structures - -APPENDICES - -[A-1] Backus-Naur Form definitions of wad elements -[A-2] Engine limits -[A-3] DOOM.WAD changes and errors -[A-3] A BLOCKMAP algorithm -[A-4] Other helpful documents -[A-5] Acknowledgments - - -------------------------- -CHAPTER [1]: Introduction -------------------------- - - DOOM is simply an all-time great game. A big factor in its success -and durability is the plethora of user-created add-ons. id Software -tacitly encouraged them by including the -FILE parameter, and by having -a data format that is both straightforward and easy to understand. -DOOM is basically two files, DOOM.EXE and DOOM.WAD. DOOM.EXE is the -"engine" which does the display and controls the game, and DOOM.WAD has -ALL of the graphics, sound, and map/level data that the engine uses. -The -FILE parameter allows small or large external "WAD" files to be -incorporated, changing any number of those graphics, sounds, and maps. - DOOM 2 has many things in common with DOOM. It uses the same EXE file -as version 1.666 of DOOM, and the WAD file format is the same. It's just -the contents of the WAD file that are different; there are more enemies! -more pictures! more weapons! more stuff!! - - This document explains in great detail nearly all aspects of the doom -WAD file format. And a new chapter (10) documents the location of data -within DOOM.EXE itself, so that various unusual game-play changes can -be made. This information has been updated to apply to DOOM 2 as well -as DOOM 1. - The specs were originally conceived as an aid to programmers making -DOOM utilities, especially map-editors. Coincidentally, there might also -be information useful to advanced level designers and players. - The material herein is somewhat technical and it is not recommended for -beginners, unless they are determined. There are some other very useful -documents in existence; I list the ones I know of in Appendix [A-3]. - - -[1-1]: id Software's Copyright and the Shareware Version -======================================================== - - My comments and statements are by no means official, and the excerpts -below are just the parts that I think are relevant to these specs. Please -read the LICENSE.DOC and README.EXE that came with DOOM. - - The LICENSE.DOC says: - - "You shall not: rent, lease, sell, distribute for money or other - consideration, modify, translate, disassemble, decompile, reverse - engineer, or create derivative works based upon the Software. - Notwithstanding the foregoing, you may create a map editor, modify - maps and make your own maps (collectively referenced as the - "Permitted Derivative Works") for the Software. You may not sell - or distribute any Permitted Derivative Works but you may exchange - the Permitted Derivative Works at no charge amongst other end-users. - In order to commercially distribute any such map editor or data - utility you must first sign ID's Data Utility License and ID - reserves the right to deny authorization to commercial distribute - the any such map editor or data utility. You may request a copy of - the Data Editor License from ID" - - "(except for backup purposes) You may not otherwise reproduce, copy - or disclose to others, in whole or in any part, the Software." - - The README says: - - "id Software respectfully requests that you do not modify the levels - for the shareware version of DOOM. We feel that the distribution of - new levels that work with the shareware version of DOOM will lessen a - potential user's incentive to purchase the registered version. - - "If you would like to work with modified levels of DOOM, we encourage - you to purchase the registered version of the game." - - If you are making add-ons, plan on them not working on the shareware -game, and plan on including statements about the trademarks and copyrights -that id Software owns, as well as disclaimers that they won't support your -add-on product, nor will they support DOOM after it has been modified. - - -[1-2]: What's New -================= - - Each new version of these specs renders the previous version obsolete. - This document has grown considerably in size, and to fight that trend, -I'll not discuss it any more. - It has now been five months since the specs were updated. I won't talk -about that either. I'll just apologize for not releasing updates in late -May and July like I should have. Those updates would have been numbered -1.4 and 1.5, so perhaps that's why this is version 1.666. - Here's some of the new or revised sections since the 1.3 specs: - - - DOOM 2 info, especially in [4-2-1] and [4-3-2] - - lots of info on the DOOM.EXE file in [10] - - BNF style definitions in [A-1] - - DOOM engine limits in [A-2] - - the DEMO format [8-6] - - the ENDOOM lump [8-3] - - comprehensive list of WAD lumps in [3] - - - many parts rewritten for clarity - - changes in terminology to reflect id's where possible, and to be - more consistent throughout - - reformatted again, errors and typos corrected - - -------------------- -CHAPTER [2]: Basics -------------------- - - The starting point is the concept of "WAD". It is not an acronym, it -just means a collection of data. Throughout this document, "WAD" or "wad" -will mean a file with a .WAD extension that contains data for the doom -engine to use. - A WAD file has three parts: - - (1) a twelve-byte header - (2) one or more "lumps" - (3) a directory or "info table" that contains the names, offsets, and - sizes of all the lumps in the WAD - - The header consists of three four-byte parts: - - (a) an ASCII string which must be either "IWAD" or "PWAD" - (b) a 4-byte (long) integer which is the number of lumps in the wad - (c) a long integer which is the file offset to the start of - the directory - - The directory has one 16-byte entry for every lump. Each entry consists -of three parts: - - (a) a long integer, the file offset to the start of the lump - (b) a long integer, the size of the lump in bytes - (c) an 8-byte ASCII string, the name of the lump, padded with zeros. - For example, the "DEMO1" entry in hexadecimal would be - (44 45 4D 4F 31 00 00 00) - - A "lump" is just data, in one of several different formats. Some -contain sound data, some contain graphics data, some contain level -structure data, etc. These specs are mostly concerned with delineating -the formats of the various lump types. There are 10 different types of -map/level lump formats, each has a section in chapter [4] (sections 2-11). -There are 13 other types of lump formats, listed below with the section -where the format is explained, and the actual lump names in parentheses. -Also, Appendix [A-1] has definitions of the structures of all these -WAD elements. - - [8-1] palettes (PLAYPAL) - [8-2] colormaps (COLORMAP) - [8-3] dos exit text (ENDOOM) - [8-6] demos (DEMO1, DEMO2, and DEMO3) - [8-4] texture composition list (TEXTURE1 and TEXTURE2) - [8-5] wall patch "number for name" indexing list (PNAMES) - [7-4] midi mapping (GENMIDI) - [7-5] Gravis UltraSound patch mappings (DMXGUS) - [7-1] PC speaker sound effects (DP*) - [7-2] Soundcard sound effects (DS*) - [7-3] songs (D_*) - [6] flats (lumpnames between F_START and F_END) - [5] all other graphics (all other lumps) - - The "marker" and "label" lump names like "S_START" and "E1M1" (or -"MAP01") do not actually refer to lumps - they have zero length. They -merely serve to mark the beginning or end of a set of related lumps. - - It is possible to include other directory entries and lumps in a wad -file, e.g. an entry called CLOWNS could point to a lump that includes the -level creator's name, date of completion, and the latitude and longitude -of the Holy Grail. None of these non-standard entries will be used by -DOOM, nor will they cause it problems. - - -[2-1]: Pwads -============ - - There are two types of wad files. The original DOOM.WAD and DOOM2.WAD -files are "IWAD"s, or "Internal wads", meaning they contain all of the -data necessary to play. The other type is the "PWAD" file, "Patch wad", -an external file which has the same structure, but with far fewer entries -in the directory. The data in a pwad is substituted for the original data -in the DOOM.WAD, thus allowing for much easier distribution of new levels. -Only those resources listed in the pwad's directory are changed, -everything else is loaded from the IWAD. All external wads should have -the "PWAD" indicator, as id has requested. - A typical pwad might contain new data for a single level, in which -case it would contain the 10 lumps and 11 directory entries necessary -to define the level (as described in chapter [4]). - A pwad file may contain more than one level or parts of levels, in -addition to replacement graphics, sounds, etc. (as of version 1.666, -sprites and flats do NOT work from pwads - see chapter [5] for more). -In fact, there is apparently no limit to how many entries may be in a -pwad. The original doom levels are pretty complicated, and they are -from 50-200 kilobytes each in size, uncompressed. - Pwad files need to have the extension .WAD to work. Many of them have -descriptive names, e.g. if J.R.R. Tolkien made a new level, he might call -it GONDOLIN.WAD - to use this level, a player would type - - DOOM -FILE GONDOLIN.WAD - -at the command line, along with any other parameters. More than one -external file can be added, thus in general: - - DOOM -FILE [pwad_filename] [pwad_filename] [pwad_filename] ... - - If there are duplicate entries amongst the directories of all the -wads being "added", the pwads listed LAST take precedence. - When the game loads, a "modified game" message will appear if there -are any pwads involved, reminding the player that id Software will not -give technical support or answer questions regarding modified levels. - With DOOM version 1.666, there is also the @responsefile option for -listing command line parameters and -file specifications. See the DOOM -README or the latest FAQ for more information. Also, there are numerous -"front-end" utilities that make it easier to play pwads, e.g. load several -external files at once, warp to certain levels, specify options, etc. - - -[2-2]: DOOM versions -==================== - -Version Date Time Is - -1.0 10dec93 01:00 first release (aka DOOM Operating System 0.99) -1.1 16dec93 01:10 slightly different from 1.0, newer dos extender -1.2 17feb94 01:20 modem play added! -1.3 - - unauthorized beta release -1.4 28jun94 01:04 shareware beta -1.5 ??jul94 ? shareware beta -1.6 03aug94 01:06 shareware beta -1.666 01sep94 16:42 registered full upgrade! -1.666 ? ? DOOM 2! - - The important releases as of this writing are 1.2 and 1.666. Hopefully, -everyone will move up to 1.666 soon; it has many important improvements -over 1.2. The 1.4, 1.5, and 1.6 shareware betas contained increasing -amounts of the stuff that's now in 1.666, but there's no information -here about what exactly those changes were. One, I didn't keep track, -and two, they're not really important. - See appendix [A-3] for some miscellany about what has changed from -version to version. - - -[2-3]: Terminology conventions -============================== - - Throughout this document, I will use the following conventions for -numbers and variable types: - -(1) Most numbers will be decimal. Hexadecimal numbers will usually be - labeled thus: 0xffff or $ffff. But sometimes I'll say "hex ...". - And in tablature form, a column heading "HEX" indicates all the - numbers in that column are hexadecimal. -(2) "byte" is of course the generic, 8 bits. It will usually mean one - 8-bit component of a larger data type, or an 8-bit ASCII - character, or some such. As a number, it is an unsigned 8-bit - integer (0..255). -(3) "short" is a signed 16-bit integer (-32768..32767), stored in - lo-hi format. -(4) "ushort" or "unsigned short" is an unsigned 16-bit integer (0..65535). -(5) "integer" or "long" is a signed 32-bit integer. If you don't read - this first, my use of the word "integer" might not be immediately - apparent. -(6) "string8" or "8-byte string" is an ASCII string with length between - 1 and 8 characters inclusive. If its length is less than 8, the - remaining bytes are zeros. -(7) The first byte of a file or any data structure, for addressing and - offset purposes, is byte #0, not byte #1. -(8) Some abbreviations I use: E1, E2, and E3 refer to episodes 1, 2, and - 3 respectively. "The EXE" means the file DOOM.EXE. -(666) Any reference to this number is purely intentional. - - ------------------------------------------------ -CHAPTER [3]: List of DOOM.WAD Directory Entries ------------------------------------------------ - - There are over 2000 entries in the DOOM.WAD directory. Most of them -can be easily described in groups, and so are not explicitly mentioned -in this list. This includes the sprites (see [4-2-1] for sprite names -and [5] for the sprite lump naming system), the wall patches ([8-4] and -[8-5] have more info), the flats (chapter [6]), the sounds and songs -(chapter [7]), and the map data lumps (chapter [4]). All the others -are listed here. - There have been several changes from version to version. The "Ver" -column indicates in which doom versions the lump exists: - -___ no indication means it is in every version. Most are like this. -1.1 it was in 1.0 and 1.1, but not in 1.2 and later. It is obsolete. -1.2 it is not in 1.1 and earlier, only in 1.2 and up. -1.6 it is not in 1.2 and earlier, only in 1.666 and up. -r it is only in the registered version, not the shareware. -1 it is only in DOOM 1, it is not in DOOM 2. -2 it is only in DOOM 2, it is not in DOOM 1. - - In the lump names, x (and y and e) indicates variable ASCII -characters, and * can be replaced by an ASCII string (up to the -8-byte lumpname limit). - -LumpName Ver Description --------- --- ----------- -PLAYPAL fourteen 256 color palettes. See [8-1]. -COLORMAP maps colors in the palette down to darker ones. [8-2]. -ENDOOM text message displayed when you exit to DOS. [8-3]. -DEMOx x=1-3, are the demos. [8-6]. -ExMy subsequent entries define a single level's data. [4]. -MAPxy 2 like ExMy, but for DOOM 2. -TEXTURE1 list of wall texture names and their composition data, - used in the SIDEDEF portion of each level. [8-4]. -TEXTURE2 r more wall texture compositions. -PNAMES lists all lump names used as wall patches. [8-5]. -GENMIDI General Midi standard instrument data. [7-3]. -DMXGUS Gravis Ultra Sound instrument patches. [7-4]. - -D_ExMy music for a doom 1 level. [7-2]. -D_INTER music played on the summary screen between levels. -D_INTRO music played when the game starts. -D_INTROA 1.2 more introductory music. -D_VICTOR music played on the victory text-screen after an episode. -D_BUNNY r music for while a certain rabbit has his story told... -D_* 2 music for a doom 2 level. - -DP_* vary PC speaker sound effects. [7-1]. -DS_* vary Soundcard sound effects. [7-1]. - - All the remaining entries in the directory, except the flats between -F_START and F_END, and the "markers" like S_START, refer to lumps which -are pictures, in the doom/wad graphic format described in chapter [5]. -The flats are also pictures, but in a format described in chapter [6]. - The next seven are full screen (320 by 200 pixel) pictures. After -that, ST* are status-bar pictures, WI* are for the screens between -levels, and M_* are for menus. - -HELP1 Ad-screen says Register!, with some screen shots. -HELP2 Actual help, all the controls explained. -TITLEPIC Maybe this is the title screen? Gee, I dunno... -CREDIT People at id Software who created this great game. -VICTORY2 r Screen shown after a victorious end to episode 2. -PFUB1 r A nice little rabbit minding his own peas and queues... -PFUB2 r ...a hint of what's waiting in Doom 2. - -ENDx r x=0-6, big red "THE END" gets shot up. -AMMNUMx x=0-9. Small grey digits for ammo count (15/200 etc). -STxBARy 1.1 x=M or A, y= L or R. Status bar used to be in pieces. -STCHAT 1.1 Status bar used to have a "chat" box. -STRSNUMx 1.1 x=0-9. Small red digits. -STWEAPx 1.1 x=0-5. COOL little weapon icons. Why'd they drop them? -STFRAGS 1.1 Tiny "FRAG" to be placed on top of part of status bar. -STBAR 1.2 Status Bar as used in deathmatches. -STGNUMx x=0-9. Small grey digits used on the "Arms" panel. -STTNUMx x=0-9. Big red digits used for Armor, Health, etc. -STTMINUS 1.6 Big red "-" used for negative frags. -STYSNUMx x=0-9. Small yellow digits used on the "Arms" panel. -STTPRCNT Big red % used in Armor and Health. -STKEYSx x=0-5. Blue/Yellow/Red Keycards and Skullkeys. -STDISK Disk, used at bottom right corner during disk accesses. -STCDROM 1.6 CD, used during CD-ROM accesses. -STARMS "Arms" panel which replaces "Frags" in non-deathmatch. -STCFNxxx xxx=033-095, also 121. Small red ASCII characters. -STFBx x=0-3. Green/black/brown/red squares, for ST player faces. -STPBx x=0-3. Squares with bottoms, for inter-level screens. -STFSTxy x=0-4, y=0-2. Player face. x=0 is 100% health...x=4 is - very low health. y=0 is glancing right, y=2 left. -STFTLx0 x=0-4. Face looking left, player hurt from that direction. -STFTRx0 x=0-4. Face looking right. -STFOUCHx x=0-4. Face looking surprised (hurt bad). -STFEVLx x=0-4. Face with a grin (when pick up new weapons). -STFKILLx x=0-4. Face with a grimace (when killing foes). -STFGOD0 Face with yellow eyes (invulnerable). -STFDEAD0 Dead face. -BRDR_* Tiny pictures used as a border between a less-than-full - screen view and the "outside" marbleized zone. TL is - top left, BR bottom right, you can guess the rest. -WIBONUS 1.1 Medium sized red text "BONUS" -WISCORE 1.1 "SCORE" -WIMSTPx 1.1 x=0-3. Red text "ONE" to "FOUR". -WIMSTBx 1.1 x=0-3. Grey text "ONE" to "FOUR". -WIMINUS 1.6 Small red "-" used for negative frags. -WIMAPx x=0-2. 320x200 maps used on inter-level screens for e1,2,3. -WIAe0x0y patches used to animate inter-level maps. -WIURH0 "YOU ARE HERE" with an arrow pointing left. -WIURH1 "YOU ARE HERE" with an arrow pointing right. -WISPLAT Splat mark that indicates a completed level. -WIOSTK "KILLS" -WIOSTI "ITEMS" -WIF "FINISHED" -WIMSTT "TOTAL" -WIOSTS "SCRT" -WIOSTF "F." -WITIME "TIME" -WIPAR "PAR" -WIMSTAR "YOU" -WIPCNT "%" -WINUMx x=0-9. Medium sized red digits. -WICOLON ":" -WISUCKS "SUCKS" -WIFRGS "FRAGS" -WILVxy x=0-2, y=0-8. E(x+1)M(y+1) level names in grey/white letters. -WIPx x=1-4. Red "P1" - "P4", for multiplayer summaries. -WIBPx x=1-4. Grey "P1" - "P4" -WIKILRS Small red "KILLERS" going sideways up, for deathmatches. -WIVCTMS Small red "VICTIMS" for the top of the deathmatch chart. -WISCRT2 "SECRET" -WIENTER "ENTERING" -M_DOOM The DOOM logo -M_RDTHIS Big red "Read This!" -M_OPTION "Options" -M_QUITG "Quit Game" -M_NGAME "New Game" -M_SKULL1 The skull indicator with eyes lit. -M_SKULL2 The skull indicator with eyes unlit. -M_THERMO The marker on e.g. the Sfx volume "thermometer". -M_THERMR The right end of the thermometer. -M_THERML The left end. -M_THERMM The middle, repeated over and over. -M_ENDGAM "End Game" -M_PAUSE "Pause" -M_MESSG "Messages:" -M_MSGON "on" -M_MSGOFF "off" -M_EPISOD "Which Epsiode?" -M_EPI1 "Knee-Deep In The Dead" -M_EPI2 "The Shores Of Hell" -M_EPI3 "Inferno" -M_HURT "Hurt me plenty." -M_JKILL "I'm too young to die." -M_ROUGH "Hey, not too rough." -M_SKILL "Choose Skill Level:" -M_NEWG "NEW GAME" (title of New Game menu) -M_ULTRA "Ultra-Violence." -M_NMARE 1.2 "Nightmare!" -M_SVOL "Sound Volume" -M_OPTTTL "OPTIONS" (title of Options menu) -M_SAVEG "Save Game" -M_LOADG "Load Game" -M_DISP "Display" -M_MSENS "Mouse sensitivity" -M_GDHIGH "high" -M_GDLOW "low" -M_DETAIL "Graphic Detail:" -M_DISOPT "DISPLAY OPTIONS" -M_SCRNSZ "Screen Size" -M_SGTTL "SAVE GAME" -M_LGTTL "LOAD GAME" -M_SFXVOL "Sfx Volume" -M_MUSVOL "Music Volume" -M_LSLEFT Load/save box, left part -M_LSCNTR Load/save box, center part (repeated) -M_LSRGHT Load/save box, right part - - The following entries are markers that do not point to a lump; they -have zero size: - -S_START marks the start of the item/monster "sprite" section. - See chapter [5] for the naming convention used here. -S_END is immediately after the last sprite. -P_START marks the beginning of the wall patches. -P1_START before the first of the shareware wall patches. -P1_END after the last of the shareware wall patches. -P2_START r registered wall patches. -P2_END r registered wall patches. -P_END marks the end of the wall patches. -F_START marks the beginning of the flats (floor textures). -F1_START shareware flats. -F1_END shareware flats. -F2_START r registered flats. -F2_END r registered flats. -F_END marks the end of the flats. - - ------------------------ -CHAPTER [4]: The Levels ------------------------ - - Each level has eleven directory entries and ten lumps: E[x]M[y] (or -MAPxy in a DOOM 2 wad), THINGS, LINEDEFS, SIDEDEFS, VERTEXES, SEGS, -SSECTORS, NODES, SECTORS, REJECT, and BLOCKMAP. - In the DOOM.WAD file, all of these entries are present for every level. -In a pwad external file, they don't all need to be present. Whichever -entries are in a pwad will be substituted for the originals. For example, -a pwad with just two entries, E3M6 and THINGS, would use all the walls -and such from the original E3M6, but could have a completely different -set of THINGS. - - -[4-1]: ExMy or MAPxy -==================== - - DOOM 1 levels have an ExMy label in a wad's directory. x is a single -(ASCII) digit 1-3 for the episode number and y is 1-9 for the mission -number. - DOOM 2 levels have a MAPxy label in a wad's directory. xy can range -from (ASCII) 01 to 32, for the level number. - This label just indicates that the lump names following it are part -of the designated level. The label does not actually point to a lump, -and the size field in the directory is 0. The assignment of lumps to -this level stops with either the next ExMy or MAPxy entry, or with a -non-map entry like TEXTURE1. - Without these labels, there would be no way to differentiate amongst -the many lumps named "THINGS", "LINEDEFS", etc. - - -[4-2]: THINGS -============= - - "Things" in DOOM are player start positions, monsters, weapons, keys, -barrels, etc. The size of each THINGS lump will be a multiple of ten, -since each thing requires ten bytes to describe it, in five -fields: - -(1) X position of thing (at level's inception) -(2) Y position of thing -(3) Angle the thing faces. On the automap, 0 is east, 90 is north, 180 - is west, 270 is south. This value is only used for monsters, player - starts, deathmatch starts, and teleporter landing spots. Other - things look the same from all directions. Values are rounded to - the nearest 45 degree angle, so if the value is 80, it will - actually face 90 - north. -(4) Type of thing, see next subsection, [4-2-1] -(5) Thing options, see [4-2-3] - - -[4-2-1]: Thing Types --------------------- - - Short 4 of 5, occupying bytes 6-7 of each thing record, specifies its -kind. The table below summarizes the different types. They are listed -in functional groups. You can easily get a numerical-order list by -extracting this table and SORTing it. - -Dec/Hex The thing's number in decimal and hexadecimal. This is the - number used in the THINGS lump on a level (ExMy or MAPxx). -V Version of DOOM needed to use this object: - no mark indicates all versions have this object -r requires registered DOOM or DOOM 2 -2 requires DOOM 2 -Spr The sprite name associated with this thing. This is the first - four letters of the lumps that are pictures of this thing. -seq. The sequence of frames displayed. "-" means it displays nothing. - Unanimated things will have just an "a" here, e.g. a backpack's - only picture can be found in the wad under BPAKA0. Animated - things will show the order that their frames are displayed - (they cycle back after the last one). So the blue key - alternates between BKEYA0 and BKEYB0. The soulsphere uses - SOULA0-SOULB0-C0-D0-C0-B0 then repeats. Thing 15, a dead - player, is PLAYN0. -+ Monsters and players and barrels. They can be hurt, and they - have a more complicated sprite arrangement. See chapter [5]. -CAPITAL Monsters, counts toward the KILL ratio at the end of a level. -# An obstacle, players and monsters can't move through it. -^ Hangs from the ceiling, or floats (if a monster). -$ A regular item that players may get. -! An artifact item; counts toward the ITEM ratio at level's end. - Note that 2025, the radiation suit, was an ITEM in version - 1.2, but it is not an ITEM in version 1.666 on. Also note - that 2022 and 2024, invulnerability and invisibility, do not - respawn in -altdeath games. - -Dec. Hex V Spr seq. Thing is: - - -1 ffff ---- - (nothing) - 0 0000 ---- - (nothing) - 1 0001 PLAY + Player 1 start (Player 1 start needed on ALL -levels) - 2 0002 PLAY + Player 2 start (Player starts 2-4 are needed in) - 3 0003 PLAY + Player 3 start (cooperative mode multiplayer games) - 4 0004 PLAY + Player 4 start - 11 000b ---- - Deathmatch start positions. Should have >= 4/level - 14 000e ---- - Teleport landing. Where players/monsters land when - 14 they teleport to the SECTOR containing this thing - -3004 0bbc POSS + # FORMER HUMAN: regular pistol-shooting zombieman - 84 0054 2 SSWV + # WOLFENSTEIN SS: guest appearance by Wolf3D blue guy - 9 0009 SPOS + # FORMER HUMAN SERGEANT: black armor, shotgunners - 65 0041 2 CPOS + # HEAVY WEAPON DUDE: red armor, chaingunners -3001 0bb9 TROO + # IMP: brown, hurl fireballs -3002 0bba SARG + # DEMON: pink, muscular bull-like chewers - 58 003a SARG + # SPECTRE: invisible version of the DEMON -3006 0bbe r SKUL + ^# LOST SOUL: flying flaming skulls, they really bite -3005 0bbd r HEAD + ^# CACODEMON: red one-eyed floating heads. Behold... - 69 0045 2 BOS2 + # HELL KNIGHT: grey-not-pink BARON, weaker -3003 0bbb BOSS + # BARON OF HELL: cloven hooved minotaur boss - 68 0044 2 BSPI + # ARACHNOTRON: baby SPIDER, shoots green plasma - 71 0047 2 PAIN + ^# PAIN ELEMENTAL: shoots LOST SOULS, deserves its -name - 66 0042 2 SKEL + # REVENANT: Fast skeletal dude shoots homing missles - 67 0043 2 FATT + # MANCUBUS: Big, slow brown guy shoots barrage of -fire - 64 0040 2 VILE + # ARCH-VILE: Super-fire attack, ressurects the dead! - 7 0007 r SPID + # SPIDER MASTERMIND: giant walking brain boss - 16 0010 r CYBR + # CYBER-DEMON: robo-boss, rocket launcher - - 88 0058 2 BBRN + # BOSS BRAIN: Horrifying visage of the ultimate demon - 89 0059 2 - - Boss Shooter: Shoots spinning skull-blocks - 87 0057 2 - - Spawn Spot: Where Todd McFarlane's guys appear - -2005 07d5 CSAW a $ Chainsaw -2001 07d1 SHOT a $ Shotgun - 82 0052 2 SGN2 a $ Double-barreled shotgun -2002 07d2 MGUN a $ Chaingun, gatling gun, mini-gun, whatever -2003 07d3 LAUN a $ Rocket launcher -2004 07d4 r PLAS a $ Plasma gun -2006 07d6 r BFUG a $ Bfg9000 -2007 07d7 CLIP a $ Ammo clip -2008 07d8 SHEL a $ Shotgun shells -2010 07da ROCK a $ A rocket -2047 07ff r CELL a $ Cell charge -2048 0800 AMMO a $ Box of Ammo -2049 0801 SBOX a $ Box of Shells -2046 07fe BROK a $ Box of Rockets - 17 0011 r CELP a $ Cell charge pack - 8 0008 BPAK a $ Backpack: doubles maximum ammo capacities - -2011 07db STIM a $ Stimpak -2012 07dc MEDI a $ Medikit -2014 07de BON1 abcdcb ! Health Potion +1% health -2015 07df BON2 abcdcb ! Spirit Armor +1% armor -2018 07e2 ARM1 ab $ Green armor 100% -2019 07e3 ARM2 ab $ Blue armor 200% - 83 0053 2 MEGA abcd ! Megasphere: 200% health, 200% armor -2013 07dd SOUL abcdcb ! Soulsphere, Supercharge, +100% health -2022 07e6 r PINV abcd ! Invulnerability -2023 07e7 r PSTR a ! Berserk Strength and 100% health -2024 07e8 PINS abcd ! Invisibility -2025 07e9 SUIT a (!)Radiation suit - see notes on ! above -2026 07ea PMAP abcdcb ! Computer map -2045 07fd PVIS ab ! Lite Amplification goggles - - 5 0005 BKEY ab $ Blue keycard - 40 0028 r BSKU ab $ Blue skullkey - 13 000d RKEY ab $ Red keycard - 38 0026 r RSKU ab $ Red skullkey - 6 0006 YKEY ab $ Yellow keycard - 39 0027 r YSKU ab $ Yellow skullkey - -2035 07f3 BAR1 ab+ # Barrel; not an obstacle after blown up - (BEXP sprite) - 72 0048 2 KEEN a+ # A guest appearance by Billy - - 48 0030 ELEC a # Tall, techno pillar - 30 001e r COL1 a # Tall green pillar - 32 0020 r COL3 a # Tall red pillar - 31 001f r COL2 a # Short green pillar - 36 0024 r COL5 ab # Short green pillar with beating heart - 33 0021 r COL4 a # Short red pillar - 37 0025 r COL6 a # Short red pillar with skull - 47 002f r SMIT a # Stalagmite: small brown pointy stump - 43 002b r TRE1 a # Burnt tree: gray tree - 54 0036 r TRE2 a # Large brown tree - -2028 07ec COLU a # Floor lamp - 85 0055 2 TLMP abcd # Tall techno floor lamp - 86 0056 2 TLP2 abcd # Short techno floor lamp - 34 0022 CAND a Candle - 35 0023 CBRA a # Candelabra - 44 002c r TBLU abcd # Tall blue firestick - 45 002d r TGRE abcd # Tall green firestick - 46 002e TRED abcd # Tall red firestick - 55 0037 r SMBT abcd # Short blue firestick - 56 0038 r SMGT abcd # Short green firestick - 57 0039 r SMRT abcd # Short red firestick - 70 0046 2 FCAN abc # Burning barrel - - 41 0029 r CEYE abcb # Evil Eye: floating eye in symbol, over candle - 42 002a r FSKU abc # Floating Skull: flaming skull-rock - - 49 0031 r GOR1 abcb ^# Hanging victim, twitching - 63 003f r GOR1 abcb ^ Hanging victim, twitching - 50 0032 r GOR2 a ^# Hanging victim, arms out - 59 003b r GOR2 a ^ Hanging victim, arms out - 52 0034 r GOR4 a ^# Hanging pair of legs - 60 003c r GOR4 a ^ Hanging pair of legs - 51 0033 r GOR3 a ^# Hanging victim, 1-legged - 61 003d r GOR3 a ^ Hanging victim, 1-legged - 53 0035 r GOR5 a ^# Hanging leg - 62 003e r GOR5 a ^ Hanging leg - 73 0049 2 HDB1 a ^# Hanging victim, guts removed - 74 004a 2 HDB2 a ^# Hanging victim, guts and brain removed - 75 004b 2 HDB3 a ^# Hanging torso, looking down - 76 004c 2 HDB4 a ^# Hanging torso, open skull - 77 004d 2 HDB5 a ^# Hanging torso, looking up - 78 004e 2 HDB6 a ^# Hanging torso, brain removed - - 25 0019 r POL1 a # Impaled human - 26 001a r POL6 ab # Twitching impaled human - 27 001b r POL4 a # Skull on a pole - 28 001c r POL2 a # 5 skulls shish kebob - 29 001d r POL3 ab # Pile of skulls and candles - 10 000a PLAY w Bloody mess (an exploded player) - 12 000c PLAY w Bloody mess, this thing is exactly the same as 10 - 24 0018 POL5 a Pool of blood and flesh - 79 004f 2 POB1 a Pool of blood - 80 0050 2 POB2 a Pool of blood - 81 0051 2 BRS1 a Pool of brains - 15 000f PLAY n Dead player - 18 0012 POSS l Dead former human - 19 0013 SPOS l Dead former sergeant - 20 0014 TROO m Dead imp - 21 0015 SARG n Dead demon - 22 0016 r HEAD l Dead cacodemon - 23 0017 r SKUL k Dead lost soul, invisible - (they blow up when killed) - - -[4-2-2]: Thing Sizes --------------------- - - The list below gives the radius, height, mass, speed, and toughness -of all the monsters in DOOM 1 and 2. Almost all non-monster things only -differ in their "radius", dependent on whether they are obstacles or not. -For collision purposes, things are NOT circular. They occupy a square -whose side equals slightly more than 2 times the radius. This square -does not turn, it is always aligned with the x and y axes of a level. -Consider a simple collision detection in a coordinate plane: - - IF (ABS(x1-x2) =< (r1+r2)) AND (ABS(y1-y2) =< (r1+r2)) THEN *collision* - - This will result in square objects centered on their (x,y) positions, -and that is the behavior that DOOM objects exhibit. - I don't know why the horizontal size is "slightly more" than 2 times -the radius, but it is. A player cannot enter a corridor of width 32, but -can enter a corridor of width 33. Experiments have shown that no monster -can enter a corridor that is exactly (2*radius) wide. It must be bigger. -Moving up to the next multiple of 8 is a good idea, if not 16 or 32. - Monsters CAN enter sectors that are exactly "Height" high. But obstacles -are infinitely high for collision purposes. A player on a very high ledge -might not be able to jump off, because of an obstacle right next to him, -even though it is far below him. - Height is also used when under a crushing ceiling, and to determine -if an object can move from one sector to another. The space between the -highest floor and the lowest ceiling must be "Height" or greater for the -object to fit. - Toughness indicates how much punishment a monster can take until it -dies. Bullets do 10 damage, Shotgun shells 70 (7 pellets, each is 10), -Plasma 20, Rockets 100, and the BFG does 1000 for a direct hit. There's -more info on this stuff in the DOOM FAQ. - -Dec. Hex Radius Height Mass Tough Speed Sprite name or class of things: - -- - 16 56 100 (100) - PLAY -3004 0bbc 20 56 100 20 8 POSS - 84 0054 20 56 100 50 8 SSWV - 9 0009 20 56 100 30 8 SPOS - 65 0041 20 56 100 70 8 CPOS -3001 0bb9 20 56 100 60 8 TROO -3002 0bba 30 56 400 150 10 SARG - 58 003a 30 56 400 150 10 SARG (Inviso model) -3006 0bbe 16 56 50 100 8 SKUL -3005 0bbd 31 56 400 400 8 HEAD - 69 0045 24 64 1000 500 8 BOS2 -3003 0bbb 24 64 1000 1000 8 BOSS - 68 0044 64 64 600 500 12 BSPI - 71 0047 31 56 400 400 8 PAIN - 66 0042 20 56 500 300 10 SKEL - 67 0043 48 64 1000 600 8 FATT - 64 0040 20 56 500 700 15 VILE - 7 0007 128 100 1000 3000 12 SPID - 16 0010 40 110 1000 4000 16 CYBR - 88 0058 16 16 6666 250 0 BBRN - 72 0048 16 72 6666 100 0 KEEN -2035 07f3 10 42 100 20 0 BAR1 - - - 20 16 - - - most non-obstacles (e.g. gettables) - - - 16 16 - - - most obstacles - 54 0036 32 16 - - - large brown tree - - -[4-2-3]: Thing Options ----------------------- - - Short 5 of 5, occupying bytes 8-9 of each thing record, control a -few options, according to which bits are set: - -bit 0 the THING is present at skill 1 and 2 -bit 1 the THING is present at skill 3 (hurt me plenty) -bit 2 the THING is present at skill 4 and 5 (ultra-violence, nightmare) -bit 3 indicates a deaf guard. -bit 4 means the THING only appears in multiplayer mode. - -bits 5-15 have no effect. - - The skill settings are most used with the monsters, of course...the -most common skill level settings are hex 07/0f (on all skills), 06/0e -(on skill 3-4-5), and 04/0c (only on skill 4-5). Unusual skill settings -are perfectly allowable, e.g. hex 05 for a thing which is present on -skill 1, 2, 4, and 5, but not skill 3. - "deaf guard" only has meaning for monsters, who will not attack until -they see a player if they are deaf. Otherwise, they will activate when -they hear gunshots, etc. (including the punch!). Sound does not travel -through solid walls (walls that are solid at the time of the noise). -Also, lines can be set so that sound does not pass through them (see -[4-3-1] bit 6). This option is also known as the "ambush" option (or -flag, or attribute). - - -[4-3]: LINEDEFS -=============== - - Each linedef represents a line from one of the VERTEXES to another, -and each linedef's record is 14 bytes, containing 7 fields: - -(1) from the VERTEX with this number (the first vertex is 0). -(2) to the VERTEX with this number (31 is the 32nd vertex). -(3) flags, see [4-3-1] below. -(4) types, see [4-3-2] below. -(5) is a "tag" or "trigger" number which ties this line's effect type - to all SECTORS that have the same tag number (in their last - field). -(6) number of the "right" SIDEDEF for this linedef. -(7) "left" SIDEDEF, if this line adjoins 2 SECTORS. Otherwise, it is - equal to -1 (FFFF hex). - - "right" and "left" are based on the direction of the linedef as -indicated by the "from" and "to", or "start" and "end", VERTEXES. -This sketch should make it clear: - - left side right side - start -----------------> end <----------------- start - right side left side - - IMPORTANT: All lines must have a right side. If it is a one-sided -line, then it must go the proper direction, so its single side is -facing the sector it is part of. DOOM will crash on a level that has -a line with no right side. - - -[4-3-1]: Linedef Flags ----------------------- - - The third field of each linedef controls some attributes of -that line. These attributes (aka flags) are indicated by bits. If the -bit is set (equal to 1), the condition is true for that line. If the -bit is not set (equal to 0), the condition is not true. Note that the -"unpegged" flags cannot be independently set for the two SIDEDEFs of -a line. Here's a list of the flags, followed by a discussion of each: - -bit Condition - -0 Impassible -1 Block Monsters -2 Two-sided -3 Upper Unpegged -4 Lower Unpegged -5 Secret -6 Block Sound -7 Not on Map -8 Already on Map -9-15 unused - - 0 (Impassible) - Players and monsters cannot cross this line. Note that -if there is no sector on the other side, they can't go through the line -anyway, regardless of the flags. - - 1 (Block Monsters) - Monsters cannot cross this line. - - 2 (Two-sided) - The linedef's two sidedefs can have "-" as a texture, -which in this case means "transparent". If this flag is not set, the -sidedefs can't be transparent: if "-" is viewed, it will result in the -"hall of mirrors" effect. However, a linedef CAN have two non-transparent -sidedefs, even if this flag is not set, as long as it is between two -sectors. - Another side effect of this flag is that if it is set, then gunfire -(pistol, shotgun, chaingun) can go through it. If this flag is not set, -gunfire cannot go through the line. Projectiles (rockets, plasma etc.) -are not restricted this way. They can go through as long as there's a -sector on the other side (and the sector heights allow it). - Finally, monsters can see through and attack through two-sided lines, -despite any of the line's other flag settings and textures (once again, -provided sector heights and the REJECT [4-10] allow it). - - 3 (Upper unpegged) - The upper texture is pasted onto the wall from -the top down instead of from the bottom up like usual. - Upper textures normally have the bottom of the wall texture to be -drawn lined up with the bottom of the "upper" space in which it is -to be drawn (sidedef Y offsets then apply [4-4]). This can result -in the upper texture being misaligned with a neighboring "middle" -texture. To help solve this problem, common at "windows", this flag -can be set. - If the upper texture is unpegged, it is drawn with the wall texture's -top row at the ceiling, just like middle and lower textures are usually -drawn. This can help realign the upper texture with a neighbor. - - The article TEXTURES, cited in appendix [A-4] gives a great deal -more explanation on the "unpegged" flags and how to use them. - - 4 (Lower unpegged) - Lower and middle textures are drawn from the -bottom up, instead of from the top down like usual. - This is also commonly used on lower textures under "windows". It is -also used on doorjambs, because when the door opens, the sector ceiling -is rising, so the "sides" (the doorjambs), which are middle textures, -will be drawn from the ever-changing ceiling height down, and thus will -appear to be "moving". Unpegging them will make them be drawn from the -floor up, and since the floor height doesn't change when a door opens, -then will not move. - There's one slight difference with lower textures being unpegged - -they are not necessarily drawn with the bottom of the wall texture placed -at the bottom of the wall. The height of the facing sector and the height -of the wall texture are taken into account. So if the sector is 160 high, -and the wall texture is 128 high, then lower unpegged will cause the 32nd -row of the wall texture to be at the floor, NOT the 128th row. This of -course excludes sidedef Y offsets, which are applied AFTER unpegged -flags do their stuff. - - 5 (Secret) - On the automap, this line appears in red like a normal -solid wall that has nothing on the other side. This is useful in -protecting secret doors and such. Note that if the sector on the other -side of this "secret" line has its floor height HIGHER than the sector -on the facing side of the secret line, then the map will show the lines -beyond and thus give up the secret. - Also note that this flag has NOTHING to do with the SECRETS ratio on -inter-level screens. That's done with special sector 9 (see [4-9-1]). - - 6 (Block Sound) - For purposes of monsters hearing sounds and thus -becoming alerted. Every time a player fires a weapon, the "sound" of -it travels from sector to sector, alerting all non-deaf monsters in -each new sector. But the sound will die when it hits a second line -with this flag. The sound can cross one such line, but not two. All -possible routes for the sound to take are taken, so it can get to -some out-of-the-way places. Another thing that blocks sound, instantly, -is incompatible sector heights. Sound can go from a sector with 0/72 -floor/ceiling heights to one with 64/192, but the sound CANNOT go -from a 0/128 sector to an adjacent 128/256 sector. - - 7 (Not on Map) - The line is not shown on the automap, even if the -computer all-map power up is acquired. - - 8 (Already on Map) - When the level is begun, this line is already -on the automap, even though it hasn't been seen (in the display) yet. -Normally lines only get mapped once part of the line has been seen in -the display window. - - Automap line colors: Red lines indicate the line is one-sided, that -there is a sector on only one side (or the line is marked secret). -Brown lines are between two sectors with different floor heights but -the same ceiling height. Yellow lines are between two sectors with -different ceiling heights and the same or different floor heights. -Gray lines are as-yet-unseen lines revealed by the computer all-map. -Without the all-map, lines between sectors with identical floor and -ceiling heights don't show up. With it, they are gray. - - -[4-3-2]: Linedef Types ----------------------- - - The in field 4 of 7 of a linedef can control various special -effects like doors opening, floors moving, etc. Some of them must be -activated by "using" them, like switches, and some of them are activated -when they are walked over. There are a huge number of ways to use these -effects, but it's all done by using one of a hundred or so line function -types. - The most common way they work is this: a player walks across a line -or activates (presses the spacebar or the use key) right in front of -a line. That line has a function type that is non-zero. It also has -a tag number. Then ALL sectors on the level with the same tag number, -that are not already engaged in some action, undergo the effects that -the linedef type number dictates. Note that the tag numbers are NOT the -sector numbers, nor the linedef numbers. A tag number is in a lindef's -5th field, and a sector's last field. - -Explanations of all the abbreviations in the table: - -Val The value of the linedef "type" field (#4). If you want them - in numerical order, use SORT or something. -* This line function only works in 1.666 and up -Class The category of the effect -Act Activation. How the linedef's effect is activated. -n does NOT require a tag number (see note 5 below) -W walk-over activation -S switch ("use" - default config is spacebar) -G gunfire (pistol, shotgun, chaingun) cross or hit line -1 the line may be activated once only -R potentially repeatable activation -& affected sectors "locked out" from further changes. See notes 9/10. -m Monster actions can activate the line's effect -Sound The type of noise made by moving sectors -Speed How quickly a floor moves up/down etc. -Tm Time - how long it "rests"; doors "rest" when they've gone as - high as they're going to go, lifts "rest" at the bottom, etc. -Chg Change - some of them cause a floor texture change and/or special - sector change. See note 11 below. -T Trigger model, see note 11 below. -N Numeric model, see note 11 below. -X Floor texture is transferred, and Sector type 0. -P Special Sector types 4, 5, 7, 9, 11, 16 transfer. -Effect What happens to the affected sector(s). -open The ceiling goes (up) to LEC-4. -close The ceiling goes (down) to the floor level. -up Will move up at specified speed if the destination is above. - If the destination is below, it arrives there instantly. -down Will move down at specified speed if the destination is below. - If the destination is above, it arrives there instantly. -open/ The door can be activated while moving. If it's open or opening, - close it closes. If it's closed or closing, it opens, then pauses, - then closes. -open, The door can only be activated if it is in the closed state. - close It opens, pauses, then closes. -lift The floor goes down to LIF, rests, then back up to original height. -L lowest -H highest -C ceiling -F floor -E adjacent sectors, excluding the affected sector -I adjacent sectors, including the affected sector -nh next-higher, i.e. LEF that is higher than source. - - More notes and longer discussions related to these terms: - -1. "Adjacent" is any sector that shares a LINEDEF with the tagged sector -(sectors are adjacent to themselves). -2. All S activations and the teleporters only work from the RIGHT side -of the linedef. -3. For teleporters, if more than 1 sector is tagged the same and each -has a teleport landing THING, then the lowest numbered sector is the -destination. -4. Floors that raise up an absolute height (up 24, 32) will go up INTO -ceilings, so using the WR and SR types of these in levels is unwise. -5. A few of the linedef types don't require tag numbers: the end-level -switches, the scrolling wall type 48 (0x30), and the "manual" doors which -operate on the sector facing the left side of the linedef with the manual -door line type. -666. Here's the terms id uses for different types of activations: - Manual: nSR and nS1 doors - Trigger: W1 - Retrigger: WR - Switch: S1 - Button: SR - Impact: G - Effect: line 48 is the only one -7. The "moving floors" go up to a maximum of HIF and go down to a minimum -of LIF. Why they sometimes go up first and sometimes down is still a -mystery to me. -8. The "crushing ceilings" go from their original ceiling height down -to (floor + 8), then back up. While crushing a creature, their downward -speed slows considerably. "Fast hurt" does about 120% total damage per -crush, and "slow hurt" grabs you and does somewhere around 1000-2000% -total damage per crush. -9. The & symbol indicates that a sector cannot be affected any more by -other line types after it has performed this effect, even if it has -finished. These are the floor-texture-changers and... (keep reading) -10. Moving floors and crushing ceilings also "lock out" further changes -to the sectors affected, EXCEPT for restarting the moving floor or -crushing ceiling. If a line triggers a type 6 crushing ceiling in a -sector, then it is stopped, then ANY other line with a "crush" type that -is tagged to the same sector will cause the type 6 crusher to start -again, with its original maximum and minimum ceiling heights. -11. Some line types cause floor textures and/or some special sector types -(see [4-9-1]) to transfer to the tagged sector. The tagged sectors' floor -and/or special sector (SS) type will change to match that of the "model" -sector. The TRIGGER model gets the info from the sector that the -activating line's right side faces. The NUMERIC model gets the info -from the sector on the other side of the lowest numbered two-sided -linedef that has one side in the tagged sector. - All of these "change" line types transfer the floor texture. Also, -they all can pass a special sector trait of "0" or "nothing", i.e. if -the destination is an acid-floor or "damaging" sector, then any of these -lines can erase the damaging effect. Lines 59, 93, 37, 84, and 9 (see -note 12 for more specifics on line type 9) also have the ability to -transfer the "secret" trait of SS 9, and the damaging traits of SS -4, 5, 7, 11, and 16. None of the "blinking light" effects of SSs can be -transferred. SS 4 "blinks" and causes damage, but only the damaging part -can be transferred. SS 11 also turns off god-mode and causes a level END -when health <11%, this characteristic is part of SS 11, and cannot be -isolated via fancy transfers. -12. Line type 9 is a special one. The definitive example is the chainsaw -pillar on E1M2. Take the lowest-numbered linedef that has a sidedef in -the tagged sector. If that linedef is one-sided, nothing happens. If it -is 2-sided, then the tagged sector's floor will move down to match the -2nd sector's floor height (or it will jump instantly up if it was below, -like other floors that are supposed to move "down"). - If this 2nd sector CONTAINS the tagged sector, i.e. all the linedefs -with a sidedef in the tagged sector have their other sidedef in the 2nd -sector, then this 2nd sector is the "donut". This donut's floor will -move "up" to match the floor height of the sector on the other side of -the DONUT's lowest-numbered linedef, excluding those linedefs that are -shared with the "donut hole" central sector. Also, the donut will undergo -a floor texture change and special sector type change to match the -"outside". The donut sector does not have to be completely surrounded -by another sector (i.e. it can have 1-sided linedefs), but if its -lowest-numbered linedef is not 2-sided, a minor glitch results: the donut -and the donut-hole both move to a strange height, and the donut changes -floor texture to TLITE6_6 - the last flat in the directory. - Note that if the donut hole and the donut are both going to move, the -donut hole is going to move to match the height that the donut is "going -to". In other words, the whole thing will be at a single height when -they're done, and this is the height of the "outside" sector that borders -the donut. - Whew! -13. Line types 30 and 96, "up ShortestLowerTexture" means that affected -sector(s) floors go up a number of units equal to the height of the -shortest "lower" texture facing out from the sector(s). -14. STAIRS. Any sector tagged to a stair-raiser line will go up 8. Now -find the lowest-numbered 2-sided linedef whose RIGHT side faces this -sector (the first step). The sector on the other side of the lindedef -becomes the next step, and its floor height changes to be 8 above the -previous step (it raises up if it was lower, or it changes instantly if -it was higher). This process continues as long as there are 2-sided -lines with right sides facing each successive step. A couple things -will stop the stairway: - (a) no 2-sided linedef whose right side faces the current step - (b) a sector with a different floor texture - (c) a sector that has already been moved by this stairway (this stops - ouroboros stairways that circle around to repeat themselves) - (d) "locked-out" sectors that can't change their floor height anymore - The component steps of a stairway can have any shape or size. - The turbo stairs (100, 127) work just like regular stairs except that -each step goes up 16 not 8, and rising steps can crush things between -themselves and the ceiling. -15. Line types 78 and 85 do NOTHING as of version 1.666. - - - -Val Class Act Sound Speed Tm Chg Effect - -SPECIAL (Continuous effect, doesn't need triggereing) - - 48 Spec n-- - - - - Scrolling wall - -LOCAL DOORS ("MANUAL" DOORS) - - 1 mDoor nSRm door med 4 - open/close - 26 mDoor nSR door med 4 - open/close BLUE KEY - 28 mDoor nSR door med 4 - open/close RED KEY - 27 mDoor nSR door med 4 - open/close YELLOW KEY - 31 mDoor nS1 door med - - open - 32 mDoor nS1 door med - - open BLUE KEY - 33 mDoor nS1 door med - - open RED KEY - 34 mDoor nS1 door med - - open YELLOW KEY - 46 mDoor nGR door med - - open -117 * mDoor nSR blaze turbo 4 - open/close -118 * mDoor nS1 blaze turbo - - open - -REMOTE DOORS - - 4 rDoor W1 door med 4 - open,close - 29 rDoor S1 door med 4 - open,close - 90 rDoor WR door med 4 - open,close - 63 rDoor SR door med 4 - open,close - 2 rDoor W1 door med - - open -103 rDoor S1 door med - - open - 86 rDoor WR door med - - open - 61 rDoor SR door med - - open - 3 rDoor W1 door med - - close - 50 rDoor S1 door med - - close - 75 rDoor WR door med - - close - 42 rDoor SR door med - - close - 16 rDoor W1 door med 30 - close, then opens - 76 rDoor WR door med 30 - close, then opens -108 * rDoor W1 blaze turbo 4 - open,close -111 * rDoor WR blaze turbo 4 - open,close -105 * rDoor S1 blaze turbo 4 - open,close -114 * rDoor SR blaze turbo 4 - open,close -109 * rDoor W1 blaze turbo - - open -112 * rDoor S1 blaze turbo - - open -106 * rDoor WR blaze turbo - - open -115 * rDoor SR blaze turbo - - open -110 * rDoor W1 blaze turbo - - close -113 * rDoor S1 blaze turbo - - close -107 * rDoor WR blaze turbo - - close -116 * rDoor SR blaze turbo - - close -133 * rDoor S1 blaze turbo - - open BLUE KEY - 99 * rDoor SR blaze turbo - - open BLUE KEY -135 * rDoor S1 blaze turbo - - open RED KEY -134 * rDoor SR blaze turbo - - open RED KEY -137 * rDoor S1 blaze turbo - - open YELLOW KEY -136 * rDoor SR blaze turbo - - open YELLOW KEY - -CEILINGS - - 40 Ceil W1 mover slow - - up to HEC - 41 Ceil S1 mover slow - - down to floor - 43 Ceil SR mover slow - - down to floor - 44 Ceil W1 mover slow - - down to floor + 8 - 49 Ceil S1 mover slow - - down to floor + 8 - 72 Ceil WR mover slow - - down to floor + 8 - -LIFTS - - 10 Lift W1 lift fast 3 - lift - 21 Lift S1 lift fast 3 - lift - 88 Lift WRm lift fast 3 - lift - 62 Lift SR lift fast 3 - lift -121 * Lift W1 lift turbo 3 - lift -122 * Lift S1 lift turbo 3 - lift -120 * Lift WR lift turbo 3 - lift -123 * Lift SR lift turbo 3 - lift - -FLOORS - -119 * Floor W1 mover slow - - up to nhEF -128 * Floor WR mover slow - - up to nhEF - 18 Floor S1 mover slow - - up to nhEF - 69 Floor SR mover slow - - up to nhEF - 22 Floor W1& mover slow - TX up to nhEF - 95 Floor WR& mover slow - TX up to nhEF - 20 Floor S1& mover slow - TX up to nhEF - 68 Floor SR& mover slow - TX up to nhEF - 47 Floor G1& mover slow - TX up to nhEF - 5 Floor W1 mover slow - - up to LIC - 91 Floor WR mover slow - - up to LIC -101 Floor S1 mover slow - - up to LIC - 64 Floor SR mover slow - - up to LIC - 24 Floor G1 mover slow - - up to LIC -130 * Floor W1 mover turbo - - up to nhEF -131 * Floor S1 mover turbo - - up to nhEF -129 * Floor WR mover turbo - - up to nhEF -132 * Floor SR mover turbo - - up to nhEF - 56 Floor W1& mover slow - - up to LIC - 8, CRUSH - 94 Floor WR& mover slow - - up to LIC - 8, CRUSH - 55 Floor S1 mover slow - - up to LIC - 8, CRUSH - 65 Floor SR mover slow - - up to LIC - 8, CRUSH - 58 Floor W1 mover slow - - up 24 - 92 Floor WR mover slow - - up 24 - 15 Floor S1& mover slow - TX up 24 - 66 Floor SR& mover slow - TX up 24 - 59 Floor W1& mover slow - TXP up 24 - 93 Floor WR& mover slow - TXP up 24 - 14 Floor S1& mover slow - TX up 32 - 67 Floor SR& mover slow - TX up 32 -140 * Floor S1 mover med - - up 512 - 30 Floor W1 mover slow - - up ShortestLowerTexture - 96 Floor WR mover slow - - up ShortestLowerTexture - 38 Floor W1 mover slow - - down to LEF - 23 Floor S1 mover slow - - down to LEF - 82 Floor WR mover slow - - down to LEF - 60 Floor SR mover slow - - down to LEF - 37 Floor W1 mover slow - NXP down to LEF - 84 Floor WR mover slow - NXP down to LEF - 19 Floor W1 mover slow - - down to HEF -102 Floor S1 mover slow - - down to HEF - 83 Floor WR mover slow - - down to HEF - 45 Floor SR mover slow - - down to HEF - 36 Floor W1 mover fast - - down to HEF + 8 - 71 Floor S1 mover fast - - down to HEF + 8 - 98 Floor WR mover fast - - down to HEF + 8 - 70 Floor SR mover fast - - down to HEF + 8 - 9 Floor S1 mover slow - NXP donut (see note 12 above) - -STAIRS - - 8 Stair W1 mover slow - - stairs - 7 Stair S1 mover slow - - stairs -100 * Stair W1 mover turbo - - stairs (each up 16 not 8) + crush -127 * Stair S1 mover turbo - - stairs (each up 16 not 8) + crush - -MOVING FLOORS - - 53 MvFlr W1& lift slow 3 - start moving floor - 54 MvFlr W1& - - - - stop moving floor - 87 MvFlr WR& lift slow 3 - start moving floor - 89 MvFlr WR& - - - - stop moving floor - -CRUSHING CEILINGS - - 6 Crush W1& crush med 0 - start crushing, fast hurt - 25 Crush W1& crush med 0 - start crushing, slow hurt - 73 Crush WR& crush slow 0 - start crushing, slow hurt - 77 Crush WR& crush med 0 - start crushing, fast hurt - 57 Crush W1& - - - - stop crush - 74 Crush WR& - - - - stop crush -141 * Crush W1& none? slow 0 - start crushing, slow hurt "Silent" - -EXIT LEVEL - - 11 Exit nS- clunk - - - End level, go to next level - 51 Exit nS- clunk - - - End level, go to secret level - 52 Exit nW- clunk - - - End level, go to next level -124 * Exit nW- clunk - - - End level, go to secret level - -TELEPORT - - 39 Telpt W1m tport - - - Teleport - 97 Telpt WRm tport - - - Teleport -125 * Telpt W1m tport - - - Teleport monsters only -126 * Telpt WRm tport - - - Teleport monsters only - -LIGHT - - 35 Light W1 - - - - 0 -104 Light W1 - - - - LE (light level) - 12 Light W1 - - - - HE (light level) - 13 Light W1 - - - - 255 - 79 Light WR - - - - 0 - 80 Light WR - - - - HE (light level) - 81 Light WR - - - - 255 - 17 Light W1 - - - - Light blinks (see [4-9-1] type 3) -138 * Light SR clunk - - - 255 -139 * Light SR clunk - - - 0 - - -[4-4]: SIDEDEFS -=============== - - A sidedef is a definition of what wall texture(s) to draw along a -LINEDEF, and a group of sidedefs outline the space of a SECTOR. - There will be one sidedef for a line that borders only one sector -(and it must be the RIGHT side, as noted in [4-3]). It is not -necessary to define what the doom player would see from the other -side of that line because the doom player can't go there. The doom -player can only go where there is a sector. - Each sidedef's record is 30 bytes, comprising 2 fields, then -3 <8-byte string> fields, then a final field: - -(1) X offset for pasting the appropriate wall texture onto the wall's - "space": positive offset moves into the texture, so the left - portion gets cut off (# of columns off left side = offset). - Negative offset moves texture farther right, in the wall's space. -(2) Y offset: analogous to the X, for vertical. -(3) "upper" texture name: the part above the juncture with a lower - ceiling of an adjacent sector. -(4) "lower" texture name: the part below a juncture with a higher - floored adjacent sector. -(5) "middle" texture name: the regular part of the wall. Also known as - "normal" or "full" texture. -(6) SECTOR that this sidedef faces or helps to surround. - - The texture names are from the TEXTURE1/2 resources. The names of -wall patches in the directory (between P_START and P_END) are not -directly used, they are referenced through the PNAMES lump. - Simple sidedefs have no upper or lower texture, and so they will have -"-" instead of a texture name. Also, two-sided lines can be transparent, -in which case "-" means transparent (no texture). - If the wall is wider than the texture to be pasted onto it, then the -texture is tiled horizontally. A 64-wide texture will be pasted at 0, -64, 128, etc., unless an X-offset changes this. - If the wall is taller than the texture, than the texture is tiled -vertically, with one very important difference: it starts new tiles -ONLY at 128, 256, 384, etc. So if the texture is less than 128 high, -there will be junk filling the undefined areas, and it looks ugly. -This is sometimes called the "Tutti Frutti" effect. - - There are some transparent textures which can be used as middle textures -on 2-sided sidedefs (between sectors). These textures need to be composed -of a single patch (see [8-4]), and note that on a very tall wall, they -will NOT be tiled. Only one will be placed, at the spot determined by -the "lower unpegged" flag being on/off and the sidedef's y offset. And -if a transparent texture is used as an upper or lower texture, then -the good old "Tutti Frutti" effect will have its way. - Also note that animated wall textures (see [8-4-1]) do NOT animate -if they are the "middle" texture on a 2-sided line. So much for the -lava waterfall with the hidden room at its base...hmm, maybe not... - - -[4-5]: VERTEXES -=============== - - These are the beginning and end points for LINEDEFS and SEGS. Each -vertice's record is 4 bytes in 2 fields: - -(1) X coordinate -(2) Y coordinate - - On the automap within the game, with the grid on (press 'G'), the -lines are 128 apart (0x80), two lines = 256 (0x100). - A note on the coordinates: the coordinate system used for the vertices -and the heights of the sectors corresponds to pixels, for purposes of -texture-mapping. So a sector that's 128 high, or a multiple of 128, is -pretty typical, since many wall textures are 128 pixels high. - And yes, the correct spelling of the plural of "vertex" is "vertices". - - -[4-6]: SEGS -=========== - - The SEGS are stored in a sequential order determined by the SSECTORS, -which are part of the NODES recursive tree. - Each seg is 12 bytes in 6 fields: - -(1) start of seg is VERTEX with this number -(2) end VERTEX -(3) angle: 0= east, 16384=north, -16384=south, -32768=west. - In hex, it's 0000=east, 4000=north, 8000=west, c000=south. - This is also know as BAMS for Binary Angle Measurement. -(4) LINEDEF that this seg goes along -(5) direction: 0 if the seg goes the same direction as the linedef it - is on, 1 if the seg goes the opposite direction. This is the - same as (0 if the seg is on the RIGHT side of the linedef) or - (1 if the seg is on the LEFT side of the linedef). -(6) offset: distance along the linedef to the start of this seg (the - vertex in field 1). The offset is in the same direction as the - seg. If field 5 is 0, then the distance is from the "start" - vertex of the linedef to the "start" vertex of the seg. If field - 5 is 1, then the offset is from the "end" vertex of the linedef - to the "start" vertex of the seg. So if the seg begins at one of - the two endpoints of the linedef, this offset will be 0. - - For diagonal segs, the offset distance can be obtained from the -formula DISTANCE = SQR((x2 - x1)^2 + (y2 - y1)^2). The angle can be -calculated from the inverse tangent of the dx and dy in the vertices, -multiplied to convert PI/2 radians (90 degrees) to 16384. And since -most arctan functions return a value between -(pi/2) and (pi/2), -you'll have to do some tweaking based on the sign of (x2-x1), to -account for segs that go "west". - - -[4-7]: SSECTORS -=============== - - SSECTOR stands for sub-sector. These divide up all the SECTORS into -convex polygons. They are then referenced through the NODES resources. -There will be (number of nodes + 1) ssectors. - Each ssector is 4 bytes in 2 fields: - -(1) This many SEGS are in this SSECTOR... -(2) ...starting with this SEG number - - The segs in ssector 0 should be segs 0 through x, then ssector 1 -contains segs x+1 through y, ssector 2 containg segs y+1 to z, etc. - - -[4-8]: NODES -============ - - A detailed explanation of the nodes follows this list of a node's -structure in the wad file. - Each node is 28 bytes in 14 fields: - -(1) X coordinate of partition line's start -(2) Y coordinate of partition line's start -(3) DX, change in X to end of partition line -(4) DY, change in Y to end of partition line - - If (1) to (4) equaled 64, 128, -64, -64, the partition line would -go from (64,128) to (0,64). - -(5) Y upper bound for right bounding-box.\ -(6) Y lower bound All SEGS in right child of node -(7) X lower bound must be within this box. -(8) X upper bound / -(9) Y upper bound for left bounding box. \ -(10) Y lower bound All SEGS in left child of node -(11) X lower bound must be within this box. -(12) X upper bound / -(13) a NODE or SSECTOR number for the right child. If bit 15 of this - is set, then the rest of the number represents the - child SSECTOR. If not, the child is a recursed node. -(14) a NODE or SSECTOR number for the left child. - - The NODES lump is by far the most difficult to understand of all the -data structures in DOOM. A new level won't display right without a valid -set of precalculated nodes, ssectors, and segs. - Here I will explain what the nodes are for, and how they can be -generated automatically from the set of linedefs, sidedefs, and -vertices. I am NOT including any code or a pseudo-code algorithm, like -I do for the BLOCKMAP (appendix [A-3]). This is for reasons of space, -and more importantly, the fact that I haven't written any such -algorithm myself. If there's to be some "node code" published here, it -will have to be donated by someone, well-commented, well-organized, in -pseudo-code, and 100% effective! So the odds are long against it. - - The NODES are branches in a binary space partition (BSP) that divides -up the level and is used to determine which walls are in front of others, -a process know as hidden-surface removal. The SSECTORS (sub-sectors) and -SEGS (segments) lumps are necessary parts of the structure. - A BSP tree is normally used in 3d space, but DOOM uses a simplified -2d version of the scheme. Basically, the idea is to keep dividing the -map into smaller spaces until each of the smallest spaces contains only -wall segments which cannot possibly occlude (block from view) other -walls in its own space. The smallest, undivided spaces will become -SSECTORS. Each wall segment is part or all of a linedef (and thus a -straight line), and becomes a SEG. All of the divisions are kept track -of in a binary tree structure, which is used to greatly speed the -rendering process (drawing what is seen). How does this binary tree -lead to faster rendering? I have no idea. - Only the SECTORS need to be divided. The parts of the levels that are -"outside" sectors are ignored. Also, only the walls need to be kept -track of. The sides of any created ssectors which are not parts of -linedefs do not become segs. - Some sectors do not require any dividing. Consider a square sector. -All the walls are orthogonal to the floor (the walls are all straight -up and down), so from any viewpoint inside the square, none of its -four walls can possibly block the view of any of the others. Now -imagine a sector shaped like this drawing: - -+--------------.------+ The * is the viewpoint, looking ->, east. The -| . | diagonal wall marked @ @ can't be seen at all, -| /\ |@ and the vertical wall marked @@@ is partially -| *-> / @\ |@ occluded by the other diagonal wall. This sector -| / @\|@ needs to be divided. Suppose the diagonal wall -+---------/ is extended, as shown by the two dots (..): - -now each of the two resulting sub-sectors are sufficient, because while -in either one, no wall that is part of that sub-sector blocks any other. - In general, being a convex polygon is the goal of a ssector. Convex -means a line connecting any two points that are inside the polygon will -be completely contained in the polygon. All triangles and rectangles are -convex, but not all quadrilaterals. In doom's simple Euclidean space, -convex also means that all the interior angles of the polygon are less -than or equal to 180 degrees. - Now, an additional complication arises because of the two-sided -linedef. Its two sides are in different sectors, so they will end up -in different ssectors too. Thus every two-sided linedef becomes two segs -(or more), or you could say that every sidedef becomes a seg. Creating -segs from sidedefs is a good idea, because the seg can then be associated -with a sector. Two segs that aren't part of the same sector cannot -possibly be in the same ssector, so further division is required of any -set of segs that aren't all from the same sector. - Whenever a division needs to be made, a SEG is picked, somewhat -arbitrarily, which along with its imaginary extensions, forms a "knife" -that divides the remaining space in two (thus binary). This seg is the -partition line of a node, and the remaining spaces on either side of -the partition line become the right and left CHILDREN of the node. All -partition lines have a direction, and the space on the "right" side of -the partition is the right child of the node; the space on the "left" -is the left child (there's a cute sketch in [4-3]: LINEDEFS that shows -how right and left relate to the start and end of a line). Note that if -there does not exist a seg in the remaining space which can serve as a -partition line, then there is no need for a further partition, i.e. -it's a ssector and a "leaf" on the node tree. - If the "knife" passes through any lines/segs (but not at vertices), -they are split at the intersection, with one part going to each child. -A two-sided linedef, which is two segs, when split results in four segs. -A two sider that lies along an extension of the partition line has each -of its two segs go to opposite sides of the partition line. This is the -eventual fate of ALL segs on two-sided linedefs. - As the partition lines are picked and the nodes created, a strict -ordering must be maintained. The node tree is created from the "top" -down. After the first division is made, then the left child is divided, -then its left child, and so on, until a node's child is a ssector. The -n you move back up the tree one branch, and divide the right child, then -its left, etc. ALWAYS left first, on the way down. - Since there will be splits along the way, there is no way to know -ahead of time how many nodes and ssectors there will be at the end. -And the top of the tree, the node that is created first, is given the -highest number. So as nodes and ssectors are created, they are simply -numbered in order from 0 on up, and when it's all done (nothing's left -but ssectors), then ALL the numbers, for nodes and ssectors, are -reversed. If there's 485 nodes, then 485 becomes 0 and 0 becomes 485. - Here is another fabulous drawing which will explain everything. -+ is a vertex, - and | indicate linedefs, the . . indicates an -extension of a partition line. The <, >, and ^ symbols indicate the -directions of partition lines. All the space within the drawing is -actual level space, i.e. sectors. - - +-----+-------+-------+ 0 (5) - | | | | / \ ==> / \ - | e |^ f |^ g | 1 4 (4) (1) - | |4 |5 | / \ / \ / \ / \ -+---- + . . +-------+-------+ 2 3 e 5 (3) (2) 2 (0) -| | < 0 | / \ / \ / \ / \ / \ / \ -| a | b | a b c d f g 6 5 4 3 1 0 -| |^ | -| . . |2. . . . . +---------+ The order in which How the elements are -| | |1 > the node tree's numbered when it's -| c |^ d | elements get made. finished. -| |3 | 0 = node (5) = node -+-----+-----------+ a = ssector 6 = ssector - - 1. Make segs from all the linedefs. There are 5 two-sided lines here. - 2. Pick the vertex at 0 and go west (left). This is the first - partition line. Note the . . extension line. - 3. Pick the vertex at 1, going east. The backwards extension . . cuts - the line 3>2>, and the unlabeled left edge line. The left edge - was one seg, it becomes two. The 3>2> line was two segs, it - becomes four. New vertices are created at the intersection - points to do this. - 4. Pick the (newly created) vertex at 2. Now the REMAINING spaces on - both sides of the partition line are suitable for ssectors. The - left one is first, it becomes a, the right b. Note that ssector - a has 3 segs, and ssector b has 5 segs. The . . imaginary lines - are NOT segs. - 5. Back up the tree, and take 1's right branch. Pick 3. Once again, we - can make 2 ssectors, c and d, 3 segs each. Back up the tree to 0. - 6. Pick 4. Now the left side is a ssector, it becomes e. But the right - side is not, it needs one more node. Pick 5, make f and g. - 7. All done, so reverse all the ordination of the nodes and the - ssectors. Ssector 0's segs become segs 0-2, ssector 1's segs - become segs 3-7, etc. The segs are written sequentially according - to the ssector numbering. - - If we want to create an algorithm to do the nodes automatically, it -needs to be able to pick partition lines automatically. From studying -the original maps, it appears that they usually chose a linedef which -divides the child's space roughly in "half". This is restricted by the -availability of a seg in a good location, with a good angle. Also, the -"half" refers to the total number of ssectors in any particular child, -which we have no way of knowing when we start! Optimization methods are -probably used, or maybe brute force, trying every candidate seg until -the "best" one is found. - What is the best possible choice for a partition line? Well, there -are apparently two goals when creating a BSP tree, which are partially -exclusive. One is to have a balanced tree, i.e. for any node, there are -about the same total number of sub-nodes on either side of it. The other -goal is to minimize the number of "splits" necessary, in this case, the -number of seg splits needed, along with the accompanying new vertices -and extra segs. Only a very primitive and specially constructed set of -linedefs could avoid having any splits, so they are inevitable. It's -just that with some choices of partition lines, there end up being -fewer splits. For example, - -+--------------+ If a and b are chosen as partition lines, -| | there will be four extra vertices needed, -+---+ +---+ < A and this shape becomes five ssectors and - |^ ^| 16 segs. If A and B are chosen, however, -+---+a b+---+ < B there are no extra vertices, and only three -| | ssectors and 12 segs. -+--------------+ - - I've read that for a "small" number of polygons (less than 1000?), -which is what we're dealing with in a doom level, one should definitely -try to minimize splits, and not worry about balancing the tree. I can't -say for sure, but it does appear that the original levels strive for -this. Their trees are not totally unbalanced, but there are some parts -where many successive nodes each have a node and a ssector as children -(this is unbalanced). And there are a lot of examples to prove that the -number of extra segs and vertices they create is very low compared to -what it could be. I think the algorithm that id Software used tried to -optimize both, but with fewer splits being more important. - - -[4-9]: SECTORS -============== - - A SECTOR is a horizontal (east-west and north-south) area of the map -where a floor height and ceiling height is defined. It can have any -shape. Any change in floor or ceiling height or texture requires a -new sector (and therefore separating linedefs and sidedefs). If you -didn't already know, this is where you find out that DOOM is in many -respects still a two-dimensional world, because there can only be ONE -floor height in each sector. No buildings with two floors, one above -the other, although fairly convincing illusions are possible. - Each sector's record is 26 bytes, comprising 2 fields, then -2 <8-byte string> fields, then 3 fields: - -(1) Floor is at this height for this sector -(2) Ceiling height -(3) name of the flat used for the floor texture, from the directory. -(4) name of the flat used for the ceiling texture. - All the flats in the directory between F_START and F_END work - as either floors or ceilings. -(5) lightlevel of this sector: 0 = total dark, 255 (0xff) = maximum - light. There are actually only 32 brightnesses possible (see - COLORMAP [8-2]), so 0-7 are the same, ..., 248-255 are the same. -(6) special sector: see [4-9-1] immediately below. -(7) a "tag" number corresponding to LINEDEF(s) with the same tag - number. When that linedef is activated, something will usually - happen to this sector - its floor will rise, the lights will - go out, etc. See [4-3-2] for the list of linedef effects. - - -[4-9-1]: Special Sector Types ------------------------------ - - Bytes 22-23 of each Sector record are a which determines -some area-effects called special sectors. - Light changes are automatic. The brightness level will alternate -between the light value specified for the special sector, and the lowest -value amongst adjacent sectors (two sectors are adjacent if a linedef -has a sidedef facing each sector). If there is no lower light value, -or no adjacent sectors, then the "blink" sectors will instead alternate -between 0 light and their own specified light level. The "oscillate" -special (8) does nothing if there is no lower light level. - "blink off" means the light is at the specified level most of the time, -and changes to the lower value for just a moment. "blink on" means the -light is usually at the lower value, and changes to the sector's value -for just a moment. Every "synchronized" blinking sector on the level -will change at the same time, whereas the unsynchonized blinking sectors -change independently. "oscillate" means the light level goes smoothly -from the lower to the higher and back; it takes about 2 seconds to go -from maximum to minimum and back (255 down to 0 back up to 255). - The damaging sector types only affect players, monsters suffer no ill -effects from them whatsoever. Players will only take damage when they -are standing on the floor of the damaging sector. "-10/20%" means that -the player takes 20% damage at the end of every second that they are in -the sector, except at skill 1, they will take 10% damage. If the player -has armor, then the damage is split between health and armor. - -Dec Hex Class Condition or effect - - 0 00 - Normal, no special characteristic. - 1 01 Light random off - 2 02 Light blink 0.5 second - 3 03 Light blink 1.0 second - 4 04 Both -10/20% health AND light blink 0.5 second - 5 05 Damage -5/10% health - 7 07 Damage -2/5% health - 8 08 Light oscillates - 9 09 Secret a player must stand in this sector to get credit for - finding this secret. This is for the SECRETS ratio - on inter-level screens. -10 0a Door 30 seconds after level start, ceiling closes like a door. -11 0b End -10/20% health. If a player's health is lowered to less - than 11% while standing here, then the level ends! Play - proceeds to the next level. If it is a final level - (levels 8 in DOOM 1, level 30 in DOOM 2), the game ends! -12 0c Light blink 0.5 second, synchronized -13 0d Light blink 1.0 second, synchronized -14 0e Door 300 seconds after level start, ceiling opens like a door. -16 10 Damage -10/20% health - - The following value can only be used in versions 1.666 and up, it will -cause an error and exit to DOS in version 1.2 and earlier: - -17 11 Light flickers on and off randomly - - All other values cause an error and exit to DOS. This includes these -two values which were developed and are quoted by id as being available, -but are not actually implemented in DOOM.EXE (as of version 1.666): - - 6 06 - crushing ceiling -15 0f - ammo creator - - What a shame! The "ammo creator" sounds especially interesting! - - -[4-10]: REJECT -============== - - The REJECT lump is used to help speed play on large levels. It can -also be used for some special effects like monsters in plain sight who -CANNOT attack or see players. - The size of a REJECT in bytes is (number of SECTORS ^ 2) / 8, rounded -up. It is an array of bits, with each bit controlling whether monsters -in a given sector can detect and/or attack players in another sector. - Make a table of sectors vs. sectors, like this: - - sector that the player is in - 0 1 2 3 4 - +--------------- -sector 0 | 0 1 0 0 0 -that 1 | 1 0 1 1 0 -the 2 | 0 1 0 1 0 -monster 3 | 0 1 1 1 0 -is in 4 | 0 0 1 0 0 - - A 1 means the monster cannot become activated by seeing a player, nor -can it attack the player. A 0 means there is no restriction. All non- -deaf monsters still become activated by weapon sounds that they hear -(including the bare fist!). And activated monsters will still pursue -the player, but they will not attack if their current sector vs. sector -bit is "1". So a REJECT that's set to all 1s gives a bunch of pacifist -monsters who will follow the player around and look menacing, but never -actually attack. - How the table turns into the REJECT resource: - Reading left-to-right, then top-to-bottom, like a page, the first bit -in the table becomes bit 0 of byte 0, the 2nd bit is bit 1 of byte 0, -the 9th bit is bit 0 of byte 1, etc. So if the above table represented -a level with only 5 sectors, its REJECT would be 4 bytes: - -10100010 00101001 01000111 xxxxxxx0 (hex A2 29 47 00, decimal 162 41 71 0) - - In other words, the REJECT is a long string of bits which are read -from least significant bit to most significant bit, according to the -lo-hi storage scheme used in a certain "x86" family of CPUs. - Usually, if a monster in sector A can't detect a player in sector B, -then the reverse is true too, thus if sector8/sector5 is set, then -sector5/sector8 will be set also. Same sector prohibitions, e.g. 0/0, -3/3, etc. are only useful for special effects (pacifist monsters), or -for tiny sectors that monsters can't get to anyway. - - The REJECT array was designed to speed the monster-detection process. -If a sector pair is prohibited, the game engine doesn't even bother -checking line-of-sight feasibility for the monster to "see" the player -and consider attacking. When a level has hundreds of monsters and -hundreds of sectors, a good REJECT can prevent the drastic slowdowns -that might otherwise occur (even fast CPUs can fall victim to this -phenomenon). - - -[4-11]: BLOCKMAP -================ - - The BLOCKMAP is a pre-calculated structure that the game engine uses -to simplify collision-detection between moving things and walls. If a -level doesn't have a blockmap, it will display fine, but everybody walks -through walls, and no one can hurt anyone else. - A concise definition of the BLOCKMAP is in appendix [A-1]. This is -the full explanation of it. - The whole level is cut into "blocks", each is a 128 (hex 80) wide -square (the grid lines in the automap correspond to these blocks). The -BLOCKMAP is a collection of lists, one list for each block, which say -what LINEDEFS are wholly or partially in that block (i.e. part of the -line passes through the block). When the game engine needs to check -for an object/wall collision (to prevent a player from walking through -a wall or to explode a rocket when it hits a wall, etc.), it just looks -up the blocklist for the block that the object is in. This tells it -which linedefs it needs to check for collisions. Most blocks will have -few if any lines in them, so there will be a substantial savings in -processor time if it only checks a couple linedefs per object instead -of a thousand or so linedefs per object - it would have to check every -single linedef on the level if not for these blocklists. - The blocks are also used for object/object collisions, but that is -not visible in the WAD format. During play, each block is also given a -dynamic "thing list", which tells what THINGS are currently in that -block. Again, this negates the need to check every moving object vs. -every other object for collisions - only a few need be tested. - The BLOCKMAP is composed of three parts: the header, the offsets, and -the blocklists. - The 8-byte header contains 4 short integers: - -(1) X coordinate of block-grid origin -(2) Y coordinate of block-grid origin -(3) # of columns (blocks in X direction) -(4) # of rows (blocks in Y direction) - - The block-grid origin is the bottom-left corner of the bottom-left -(southwest) block. id's blockmap builder this origin point at 8 less -than the minimum values of x and y achieved in any vertex on the level. - The number of columns and rows needs to be sufficient to contain -every linedef in the level. If there are linedefs outside the blockmap, -it will not be able to prevent monsters or players from crossing those -linedefs, which can cause problems, including the hall of mirrors effect. - - There are N blocks, N = (number of columns * number of rows). Each -block has a blocklist and an offset to that blocklist. Immediately -following the 8-byte header are N unsigned short integers. The first -is the offset in short-ints NOT bytes, from the start of the BLOCKMAP -lump to the start of the first blocklist. The last offset points to -blocklist (N-1), the last blocklist. Note that all these offsets are -UNSIGNED, so they can point to a location 65535 shorts (131070 bytes) -into the BLOCKMAP. If they were signed, they could only go up to 32767. - The blocks are numbered going east (right) first, then north (up). -Block 0 is at the southwest corner (row 0, column 0). Block 1 is at -row 0, column 1. If there are 37 columns, then block 38 is at row 1, -column 0, etc. - - After the offsets come the blocklists. Each blocklist starts with -a short-int 0 (0x0000) and ends with a short-int -1 (0xffff). In between -are the numbers of every linedef which has any portion whatsoever in the -128 x 128 coordinate area of that block. If the block-grid origin is at -(0,0), then the first column is X = 0 to 127 inclusive, the second column -is X = 128 to 255 inclusive, etc. So a vertical line with X = 128 which -might seem to be on the border of two columns of blocks is actually only -in the easternmost/rightmost column. Likewise for the rows. - The first linedef in the LINEDEFS lump is linedef number 0, and so on. -An "empty" block's blocklist only has the two shorts 0 and -1. A non- -empty block might have this as its blocklist: 0 330 331 333 -1. This -means that linedefs 330, 331, and 333 have some part of them pass through -this block. A block that has linedef 0 in it will go: 0 0 .. etc .. -1. - - There is an upper limit to how big a BLOCKMAP can be. Even empty -blocklists require at least 3 shorts - the 0, the -1, and the offset to -the blocklist. The offsets are unsigned shorts, which would imply a -maximum value of short #65535 ( = byte 131070) for the start of the last -blocklist. At a little over 6 bytes per blocklist, that would be a maximum -of around 21000 blocks (145 by 145 blocks, 18560 in coordinates). But the -actual limit is less. Experiments suggest that the maximum total size of -all the blocklists, not counting the offsets, is 65535 bytes. This limits -a minimalist level to around 120 blocks square (15360 in coordinates), -or a realistically complex level to around 100 blocks square (12800 in -coordinates). - - ---------------------- -CHAPTER [5]: Graphics ---------------------- - - The great majority of the entries in the directory reference lumps -that are in a special picture format. The same format is used for the -sprites (monsters, items), the wall patches, and various miscellaneous -pictures for the status bar, menu text, inter-level map, etc. Every -one of these picture lumps contains exactly one picture. The flats -(floor and ceiling pictures) are NOT in this format, they are raw data; -see chapter [6]. - A great many of these lumps are used in sprites. A "sprite" is the -picture or pictures necessary to display any of the THINGS. Some of -them are simple, a single lump like SUITA0. Most of the monsters have -50 or more lumps. - The first four letters of these lumps are the sprite's "name". TROO -is for imps, BKEY is for the blue key, and so on. See [4-2-1] for a list -of them all. The fifth letter in the lump is an indication of what "frame" -it is, for animation sequences. The letters correspond to numbers, ASCII -"A" equalling 0, "B" is 1, ... "Z" is 25, etc. The highest needed by a -DOOM 1 sprite is W=22, but some of the DOOM 2 monsters need a few more -frames. - The "0" in the lump name is for "rotations" or "rot"s. All the -static objects like torches and barrels and dead bodies look the same -from any angle. This is because they have a "rot=0 lump" as DOOM itself -might say. Monsters and projectiles look different from different -angles. This is done with rots 1-8. This diagram shows how rot 1 is for -the front and they go counter-clockwise (looking from above) to 8: - - 3 - 4 | 2 - \|/ - 5--*----> 1 Thing is facing this direction - /|\ - 6 | 8 - 7 - - Many things have sets of lumps like this: TROOA1, TROOA2A8, TROOA3A7, -TROOA4A6, TROOA5, TROOB1, etc. This means that for frame 0 (A), the -pairs of rots/angles (2 and 8), (3 and 7), and (4 and 6) are mirror- -images. In the long run, this saves space in the wad file, and from the -designer's point of view, it's 37% fewer pictures to have to draw. - If a sprite's frame has a non-zero rot, it needs to have ALL 8 of -them. Also note that no more than two rots can be squeezed into one -lump's name. Some other two-rot lumps with a different format are -shown in the SPIDA1D1, SPIDA2D2, etc. lumps. - - IMPORTANT: Sprite lumps and flats cannot be added or replaced via pwads -unless they ALL are. That is, ALL sprites' lumps must be located in a -single wad file, and ALL flats' lumps must be in a single wad file. Wall -patches CAN be used in external wads, because the PNAMES lump gives a -number to every pname, and is used as a quick-index list to load in -wall patches. - Version 1.666 was rumored to be able to include sprites in pwads (in -fact the README says it can), but it can't. - - -[5-1]: Picture Format -===================== - - Each picture has three sections. First, an 8-byte header composed of -four short-integers. Then a number of long-integer pointers. Then the -picture's pixel/color data. See [A-1] for concise BNF style definitions, -here is a meatier explanation of the format: - -(A) The header's four fields are: - - (1) Width. The number of columns of picture data. - (2) Height. The number of rows. - (3) Left offset. The number of pixels to the left of the center; - where the first column gets drawn. - (4) Top offset. The number of pixels above the origin; - where the top row is. - - The width and height define a rectangular space or limits for drawing -a picture within. To be "centered", (3) is usually about half of the -total width. If the picture had 30 columns, and (3) was 10, then it -would be off-center to the right, especially when the player is standing -right in front of it, looking at it. If a picture has 30 rows, and (4) -is 60, it will appear to "float" like a blue soul-sphere. If (4) equals -the number of rows, it will appear to rest on the ground. If (4) is less -than that for an object, the bottom part of the picture looks awkward. - With walls patches, (3) is always (columns/2)-1, and (4) is always -(rows)-5. This is because the walls are drawn consistently within their -own space (There are two integers in each SIDEDEF which can offset the -starting position for drawing a wall's texture within the wall space). - - Finally, if (3) and (4) are NEGATIVE integers, then they are the -absolute coordinates from the top-left corner of the screen, to begin -drawing the picture, assuming the VIEW is full-screen (i.e., the full -320x200). This is only done with the picture of the player's current -weapon - fist, chainsaw, bfg9000, etc. The game engine scales the -picture down appropriatelyif the view is less than full-screen. - -(B) After the header, there are N = field (1) = = (# of columns) -4-byte integers. These are pointers to the data for each COLUMN. -The value of the pointer represents the offset in bytes from the first -byte of the picture lump. - -(C) Each column is composed of some number of BYTES (NOT integers), -arranged in "posts": - - The first byte is the row to begin drawing this post at. 0 means -whatever height the header (4) upwards-offset describes, larger numbers -move correspondingly down. - The second byte is how many colored pixels (non-transparent) to draw, -going downwards. - Then follow (# of pixels) + 2 bytes, which define what color each -pixel is, using the game palette. The first and last bytes AREN'T drawn, -and I don't know why they are there. Probably just leftovers from the -creation process on the NeXT machines. Only the middle (# of pixels in -this post) are drawn, starting at the row specified in the first byte -of the post. - After the last byte of a post, either the column ends, or there is -another post, which will start as stated above. - 255 (0xFF) ends the column, so a column that starts this way is a null -column, all "transparent". Draw the next column. - - ------------------------------------------------ -CHAPTER [6]: Flats (Floor and Ceiling Textures) ------------------------------------------------ - - All the lumpnames for flats are in the directory between the F_START -and F_END entries. Calling them flats is a good way to avoid confusion -with wall textures. There is no look-up or meta-structure in flats as -there is in walls textures. Each flat is 4096 raw bytes, making a square -64 by 64 pixels. This is pasted onto a floor or ceiling with the same -orientation as the automap would imply, i.e. the first byte is the color -at the NW corner, the 64th byte (byte 63, 0x3f) is the NE corner, etc. - The blocks in the automap grid are 128 by 128, so four flats will fit -in each block. Note that there is no way to offset the placement of flats, -as can be done with wall textures. They are pasted according to grid lines -64 apart, reckoned from the coordinate (0,0). This allows flats to flow -smoothly even across jagged boundaries between sectors with the same -floor or ceiling height. - - As discussed in chapter [5], replacement and/or new-name flats don't -work right from pwad files unless they are all in the same wad. - Theoretically, you can change all the flats want by constructing a -new DOOM.WAD or ALLFLATS.WAD pwad, but you have to make sure no floor -or ceiling uses an entry name which isn't in your F_ section. And you -have to include these four entries for DOOM 1 use, although you can -change their actual contents (pictures): FLOOR4_8, SFLR6_1, MFLR8_4, -and FLOOR7_2. The first three are needed as backgrounds for the episode -end texts. The last is what is shown "outside" the border of the display -window if the display is not full-screen. - - -[6-1]: Animated Flats ---------------------- - - See Chapter [8-4-1] for a discussion of how the animated walls and -flats work. Unfortunately, the fact that the flats all need to be -lumped together in one wad file means that its not possible to change -the animations via a pwad file, unless it contains ALL the flats, which -amounts to several hundred k. Plus it is illegal to distribute the -original data, so to pass around modifications, either all the flats -must be all-new, or a utility must be used to construct a FLATS.WAD -on an end-user's hard drive, using the original DOOM.WAD plus the -additions. (Note: Bernd Kreimeier, listed in [A-5], has written a -utility that does just this. It is called DMADDS11). - - ------------------------------ -CHAPTER [7]: Sounds and Music ------------------------------ - - -[7-1]: PC Speaker Sound Effects -=============================== - - DP* entries in the directory refer to lumps that are sound data for -systems using the PC speaker. - It's a quick and simple format. First is a that's always 0, -then a that's the number of bytes of sound data, then follow -that many bytes worth of sound data. That is, the lump's bytes will be -0, 0, N, 0, then N bytes of data. The DP* lumps range in size from around -10 bytes to around 150 bytes, and the data seem to range from 0 to 96 -(0x00 to 0x60). The numbers obviously indicate frequency, but beyond -that I don't know the exact correlation in Hz, nor the time duration -of each byte worth of data. Feel free to figure this out and tell me. - - -[7-2]: Soundcard Sound Effects -============================== - - DS* entries in the directory refer to lumps that are sound data for -systems using soundcards. - This data is in a RAW format for 8-bit 11 KHz mono sound - first is -an 8-byte header composed of 4 unsigned short integers: - -(1) 3 (means what?) -(2) 11025 (the sample rate, samples per second) -(3) N (the number of samples) -(4) 0 - - Each sample is a single byte, since they are 8-bit samples. The -maximum number of samples is 65535, so at 11 KHz, a little less than -6 seconds is the longest possible sound effect. - - -[7-3]: Music -============ - - D_* entries is the directory refer to lumps that are music. This -music is in the MUS file format, which goes like this: - -offset type contents - -0 ASCII "MUS" and CTRL-Z (hex 4d 55 53 1a) -4 # of bytes of music data -6 # of bytes of header data (offset to start of music) -8 number of primary channels -10 number of secondary channels -12 number of instrument patches -14 0 -16 s instrument patch numbers -X to end ? Music data - - X is the header size (the second short). Drum patch numbers (greater -than 128) are 28 less than the numbers listed in the DMXGUS lump. - What the exact format of the music data is, I don't know. - - -[7-4]: GENMIDI -============== - - This has something to do with General MIDI, obviously. This lump -has 3 sections: an 8-byte header (the ASCII text "#OPL_II#"), then -150 36-byte records (1 for each instrument), then 150 32-byte strings -(names of instruments, padded with zeros). Perhaps the 36 bytes contain -waveform information for the General MIDI standard instruments (this -guess is based on exactly one glance at a dump of the byte values, -so don't put too much faith in it). - - -[7-5]: DMXGUS -============= - - This lump is used to do instrument patch mappings on the Gravis -Ultra-Sound soundcard. It's in a very simple format - ASCII text! -Here's the start and end of the DMXGUS lump from DOOM 1 version 1.2, -which is 200 lines, of which the first 10 are comments: - -#Purpose: Different size patch libraries for different memory sizes. -# The libraries are built in such a way as to leave 8K+32bytes -# after the patches are loaded for digital audio. -# -#Revision History: 06/22/93 - Fixed problem with 512K patch library -# 07/26/93 - patch names changed in various releases -# -# -#Explanation of Columns: Patch # 256K 512K 768K 1024K Patch Name -# -0, 2, 1, 1, 1, acpiano -1, 2, 1, 1, 1, britepno -2, 2, 1, 1, 1, synpiano -. -. -. -213, 128, 128, 128, 128, castinet -214, 128, 128, 128, 128, surdo1 -215, 128, 128, 128, 128, surdo2 - - --------------------------------- -CHAPTER [8]: Miscellaneous Lumps --------------------------------- - - -[8-1]: PLAYPAL -============== - - There are 14 palettes here, each is 768 bytes = 256 rgb triples. -That is, the first three bytes of a palette are the red, green, and -blue portions of color 0. And so on. Note that the values use the -full range (0..255), while standard VGA digital-analog converters -use values 0-63. - The first palette, palette 0, is used for most situations. - Palettes 10-12 are used (briefly) when an item is picked up, the -more items that are picked up in quick succession, the brighter it -gets, palette 12 being the brightest. - Palette 13 is used while wearing a radiation suit. - Palettes 3, 2, then 0 again are used after getting berserk strength. - If the player is hurt, then the palette shifts up to number X, then -comes "down" one every second or so, to palette 2, then palette 0 -(normal) again. What X is depends on how badly the player got hurt: -Over 100% damage (add health loss and armor loss), X=8. 93%, X=7. 81%, -X=6. 55%, X=5. 35%, X=4. 16%, X=2. These are just rough estimates -based on a single test session long ago. Why bother tracking down -the exact division points? - - Unknown: what palettes 1 and 9 are for. - - -[8-2]: COLORMAP -=============== - - This contains 34 sets of 256 bytes, which "map" the colors "down" in -brightness. Brightness varies from sector to sector. At very low -brightness, almost all the colors are mapped to black, the darkest gray, -etc. At the highest brightness levels, most colors are mapped to their -own values, i.e. they don't change. - In each set of 256 bytes, byte 0 will have the number of the palette -color to which original color 0 gets mapped. - The colormaps are numbered 0-33. Colormaps 0-31 are for the different -brightness levels, 0 being the brightest (light level 248-255), 31 being -the darkest (light level 0-7). Light level is the fifth field of each -SECTOR record, see [4-9]. - Colormap 32 is used for every pixel in the display window (but not -the status bar), regardless of sector brightness, when the player is -under the effect of the "Invulnerability" power-up. This colormap is -all whites and greys. - Colormap 33 is all black for some reason. - While the light-amplification goggles power-up is in effect, everything -in the display uses colormap 0, regardless of sector brightness. - - -[8-3]: ENDOOM -============= - - When you finally have to leave DOOM, you exit to dos, and a colorful -box of text appears. This is it. It is 4000 bytes, which are simply -stored in the screen memory area for 80x25 16-color text mode. Thus -it follows the same format as screen memory does: each character on -the screen takes up two bytes. The second byte of each pair is from -the (extended) ASCII character set, while the first byte of each pair -is the color attribute for that character. The color attribute can -be explained thus: - - bit 7 6 5 4 3 2 1 0 - +-----+---+---+---+---+---+---+---+ - | | . . | . . . | - |Blink| Background| Foreground | - | | . . | . . . | - +-----+---+---+---+---+---+---+---+ - - So the foreground color can be from 0-15, the background color can -be from 0-7, and the "blink" attribute is either on or off. All this -very low-level info can be found in many ancient PC programming books, -but otherwise it might be hard to locate... - - -[8-4]: TEXTURE1 and TEXTURE2 -============================ - - These are lists of wall texture names used in SIDEDEFS lumps. Each -wall texture is composed of one or more wall patches, whose names are -listed in the PNAMES lump. But in a texture, the wall patches are not -referred to by name, rather by the index number indicating what position -they occupy in the PNAMES lump. - The TEXTURE2 lump is only present in the registered DOOM.WAD. The -TEXTURE1 lump is identical in DOOM.WAD and the shareware DOOM1.WAD, and -it only refers to pname numbers up to 163, because the shareware wad -only has the first 163 wall patches, not all 350. - - A TEXTURE lump starts with a 4-byte long integer N which is the number -of textures defined in it. Following it are N long integers which are the -offsets in bytes from the beginning of the TEXTURE lump to the start of -each texture's definition. - Then there are N texture definitions, which have the following format. -The first (texture name) field is an 8-byte string (less than 8 byte -names are padded with zeros), the rest of the fields are 2-byte short -integers: - -(1) The name of the texture, used in SIDEDEFS, e.g. "FIREWALL". -(2) always 0. -(3) always 0. -(4) total width of texture -(5) total height of texture - - The fourth and fifth fields define a "space" (usually 128 by 128 - or 64 by 72 or etc...) in which individual wall patches are placed - to form the overall picture. To tile vertically on a very tall wall - without exhibiting the "Tutti Frutti" effect, a texture must have - height 128, the maximum. There is no maximum width. - -(6) always 0. -(7) always 0. -(8) Number of 5-field (5 ) patch descriptors that follow. This -means that each texture entry has variable length. Many entries have just -1 patch, the most used in DOOM in a single texture is 64. - - Patch descriptor: - - (a) x offset from top-left corner of texture space defined in fields - 4 and 5 to start placement of this patch - (b) y offset - (c) number (0...) of the entry in the PNAMES lump that contains the - lump name from the directory, of the wall patch to use... - (d) always 1, is for something called "stepdir"... - (e) always 0, is for "colormap"... - - Each texture's entry ends after the last of its patch descriptors. - Note that patches can have transparent parts, since they are in the -same picture format as everything else. Thus there can be (and are) -transparent wall textures. These should only be used on a border between -two sectors, to avoid "hall of mirrors" problems. - Also, textures intended for use as the "middle" texture of a 2-sided -SIDEDEF (e.g. transparent textures) should only be composed of a single -patch. A limitation in the game engine will cause the "medusa" effect -if there is more than 1 patch in any middle texture that is visible in -the display window. This effect causes the computer to slow to a crawl -and make play impossible until the offending wall is out of view. - - -[8-4-1]: Animated Walls ------------------------ - - Some of the walls and floors are animated. In the case of wall -textures, it is possible to substantially customize these animations. -Flats' animations can theoretically also be modified, but since flats -don't work from pwads, that can make the effort very difficult. - The game engine sets up a number of wall animation cycles based on -what entries it finds in the TEXTURE lumps. It also sets up flat -animations based on what lumps exist between F_START and F_END. -Versions before 1.666 can have up to 9 animated walls and 5 animated -flats. Version 1.666 (DOOM 1 or 2) can have 13 walls and 9 floors -animate. - For wall animations, the entries in the columns "First" and "Last" -below, and all the entries between them (in the order that they occur -in the TEXTURE lump) are linked. If one of them is listed as a texture -on a sidedef, that sidedef will change texture to the next in the cycle -about 3 times a second, going back to after . Flats work -similarly, except the order is dictated by the wad directory. If both -of the and texture/flat names are not present, no problem. -Then that potential cycle is unused. But if is present, and - either is not present or is listed BEFORE , then an -error occurs while the DOOM operating system sets up, and it aborts. - Note that much longer sequences are possible! The entries between - and can be almost anything; they need not be the same -in number as in the original, nor do they have to follow the same -naming pattern. Thus one could set up SLADRIP1, TRON2, TRON3, TRON4, -..., TRON67, SLADRIP3 for a 69-frame animated wall! - The "Ver" column indicates what version of DOOM is required. "All" -indicates all versions have it. The "r" signifies that the shareware -DOOM1.WAD does not contain the necessary picture lumps. The "2" means -that only DOOM 2 has the necessary picture lumps, but version 1.666 of -DOOM.EXE for DOOM 1 also has the capability to use these animation-cycle -names (for pwad designers). - -First Last Ver Normal # of frames - -BLODGR1 BLODGR4 r 4 -BLODRIP1 BLODRIP4 r 4 -FIREBLU1 FIREBLU2 r 2 -FIRELAV3 FIRELAVA r 2 (3 patches are in DOOM.WAD, 1 is unused) -FIREMAG1 FIREMAG3 r 3 -FIREWALA FIREWALL r 3 -GSTFONT1 GSTFONT3 r 3 -ROCKRED1 ROCKRED3 r 3 -SLADRIP1 SLADRIP3 All 3 - -BFALL1 BFALL4 2 4 -SFALL1 SFALL4 2 4 -WFALL1 WFALL4 2 4 -DBRAIN1 DBRAIN4 2 4 - -(floor/ceiling animations): - -NUKAGE1 NUKAGE3 All 3 -FWATER1 FWATER4 r 4 -SWATER1 SWATER4 - 4 (SWATER lumps aren't in any DOOM.WAD) -LAVA1 LAVA4 r 4 -BLOOD1 BLOOD3 r 3 - -RROCK05 RROCK08 2 4 -SLIME01 SLIME04 2 4 -SLIME05 SLIME08 2 4 -SLIME09 SLIME12 2 4 - - -[8-4-2]: The SKY Textures -------------------------- - - The SKY1, SKY2, and SKY3 textures are rather special in that they are -used as sky backgrounds when the player is out in the open. They can -also be used on regular walls, but they usually aren't, because then -they just look like a painting. The "background" effect is done by -the game engine. There is a special flat, F_SKY1, which is used to -indicate that a floor or ceiling is "transparent" to the SKY beyond. -The picture data in the F_SKY1 flat is not even used. - Upper textures between F_SKY1 ceilinged sectors do not have the -specified texture (if any) drawn. Instead, they are "sky". Likewise -with lower textures between F_SKY1 floored sectors, but it doesn't -work as well, because if the player's viewpoint is below the top of -a lower-texture-sky (i.e. if any part of it is in the upper half of -the display), it causes a hall-of-mirrors effect. - SKY textures as sky backgrounds are mirror-images of what they look -like on walls. - The SKY textures are always placed with their tops at the top of the -view window. Since they cannot be more than 128 high, just like any -other texture, a rather ugly "seam" in the sky is sometimes visible -if the player can see too far "down". - SKY textures do move horizontally, though, to give a realistic -effect. Doing a complete 360 degree turn will scroll by a 256-wide -SKY four times. A 1024-wide SKY will exactly circumscribe the horizon. -The 0 column of the SKY texture will be at due north (as on the automap), -the 256 column is at west, 512 is south, and 768 is east. So the middle -part of a 256-wide SKY is visible at NW, SW, SE, and NE. - - SKY textures can be composed of several patches, just like regular -textures, but trying to animate the sky doesn't work. DOOM.EXE can be -changed so that SKY2 is the start of an animation cycle, and indeed -on a wall it will animate, but the sky background does not. This is -perhaps related to the way that "middle" textures of sidedefs do not -animate. - - -[8-5]: PNAMES -============= - - This is a list of all the names of lumps that are going to be used -as wall patches. DOOM assigns numbers to these names, in the order -that they are listed. The numbers are then used in TEXTURE1 and TEXTURE2 -entries to refer to wall patch lumps. In a texture composition entry, -0 means the first pname, 1 is the second, ... - - The first four bytes of the PNAMES lump is a long integer N. - Then follow N pnames, each of which occupies 8 bytes. Pnames less than -8 bytes long are padded with zeros. These names duplicate an entry in -the directory (but are not case sensitive - lowercase letters will match -uppercase letters and vice versa). Unlike sprites and floors, wall -patches can be loaded from external pwads. Whichever pwad was listed -last on the command line and contains a lump with the same name as the -one in the PNAMES lump (which itself could be from a pwad) is the pwad -that is used to get the picture data for that wall patch. - - -[8-6]: DEMOs -============ - - If you start DOOM and do nothing, after a few seconds, it automatically -shows a demo of play on some level. Also, external demos can be recorded -and played back by using the command line parameters explained in the -README and/or the DOOM FAQ. All external demos have a .LMP extension -which the DOOM OS attaches; you only type the [demoname] without the -.LMP extension. - The DOOM.WAD lumps DEMO1, DEMO2, and DEMO3 are in exactly the same -format as these external .LMP files. Strictly speaking, the "demo" -format should not be called the "LMP" format, because any external -file without a wadfile header, i.e. it is just raw data, is a "lump" -and deserves the .LMP extension. - - A DOOM demo has three parts: - - (1) header - 7 or 13 bytes - (2) data recording player moves - 4 bytes per player per gametic - (3) quit byte - equals 128 (0x80) - -(1) There are two different kinds of header depending on the version of -DOOM used to record the demo. Versions up to 1.2 use a 7-byte header: - - byte range purpose - -0 0-4 skill level. 0="I'm too young to die", 4="Nightmare!" -1 1-3 episode. -2 1-9 mission/map. -3 0-1 player 1 is present if this is 1. -4 0-1 player 2. -5 0-1 player 3. -6 0-1 player 4. - - Versions after 1.2 use a 13-byte header: - -byte range purpose - -0 104-106 version. 104=1.4 beta, 105=1.5 beta, 106=1.6 beta or 1.666 -1 0-4 skill level. 0="I'm too young to die", 4="Nightmare!" -2 1-3 episode. In DOOM 2 this is always 1. -3 1-32 mission/map/level. In DOOM 1, it's 1-9. In DOOM 2, it's 1-32. -4 0-2 mode. 0=single or cooperative, 1=deathmatch, 2=altdeath -5 0- respawn. 0=no respawn parameter, (any other value)=respawn. -6 0- fast. 0=no fast parameter, (any other value)=fast. -7 0- nomonsters. 0=monsters exist, (any other value)=nomonsters. -8 0-3 viewpoint. 0=player 1's status bar, ..., 3=player 4. -9 0-1 player 1 is present if this is 1. -10 0x0a 0-1 player 2. -11 0x0b 0-1 player 3. -12 0x0c 0-1 player 4. - -(2) The player-move data is recorded in 4-byte chunks. Every 1/35 of a -second is a gametic, and for every gametic, there is one 4-byte chunk -per player. So the time duration of a demo (in seconds) is approximately -equal to its length in bytes divided by (140 * number_of_players). - - The four bytes recording each player's actions are: - - (a) Forward/Backward Movement. - (b) Strafe Right/Left Movement. - (c) Turn Left/Right. - (d) other actions - use/activate, fire, change weapons. - - The first three are signed bytes (i.e. of type ). - - (a) Ranges from -127 to 127, negative numbers are backward movement, - positive numbers are forward movement. Without the -turbo option - above 100, values outside -50..50 cannot be achieved. With a - keyboard or joystick, these are the regular values: - - Move forward: 25 (0x19) with Speed on: 50 (0x32) - Move backward: -25 (0xE7) with Speed on: -50 (0xCE) - - Fancy mouse use can achieve any number in the range. - - (b) Ranges from -127 to 127, negative numbers are left-strafe movement, - positive numbers are right-strafe movement. The keyboard values are: - - Strafe right: 24 (0x18) with Speed on: 50 (0x32) - Strafe left: -24 (0xE8) with Speed on: -50 (0xCE) - - (c) Ranges from -127 to 127, negative numbers are right turns, positive - numbers are left turns. The keyboard values vary from version to - version, but are all in the range -5..5, and that's with Speed on. - - Using the mouse can achieve much higher numbers here. I doubt if - the maximums of 127 and -127 can actually be achieved in play, - though. - - (d) the bits of this byte indicate what actions the player is engaged in: - - bit 0 Fire current weapon - bit 1 Use (a switch, open a door, etc.) - bit 2 Change weapon to the one indicated in bits 3-5: - - bits 5-3 = 000 Fist or Chainsaw - 001 Pistol - 010 Shotgun - 011 Chaingun - 100 Rocket Launcher - 101 Plasma Rifle - 110 BFG 9000 - 111 Super Shotgun (DOOM 2 only) - - bit 6 unused - bit 7 indicates a special action which alters the meanings - of the other bits: - - bits 1-0 = 01 pause or unpause - = 10 save game in slot # recorded in bits 4 to 2 - (slot number can thus be 0 to 7 but - should NOT be 6 or 7 or else!) - - There might be other special actions. The save game action happens -during replay of the demo, so be careful when playing demos if you -have important savegames! One or more of them could conceivably get -overwritten. - -(3) The last byte of a demo has the value 128 (0x80) - - -[8-6-1]: Level changes from 1.2 to 1.666 DOOM.WAD -================================================= - - Many people have experienced the error "Demo from a different game -version", because DOOM versions will only play back demos that were -recorded with the same version number. Theoretically, though, ANY -version can be converted to ANY other version. Versions up to 1.2 -don't even require any modification, and versions 1.4 and up just -require that their first byte be changed. To change between the two -families (pre-1.4 and post-1.2) would just require extra header bytes -be added/shaved. - But there are serious complications to converting demos. There have -been some minor changes and bug-fixes to the levels from version to -version. Since the demos only record player actions, they have NOTHING -about the level in them, so they depend on the level used for playback -to be the same as the level used for recording. Some kinds of differences -in the playback level can cause the demo to become "unsynchronized" -with the level, and players will seem to have gone crazy. For example, -if a deathmatch start-position is at a different location, when a -demo-player is spawned there, they will try to open doors that don't -exist at the new location, shoot at people who aren't there, etc. -The entire playback is ruined from that point on. Some examples of -changes that don't matter are different floor and wall textures, light -levels, and linedef "unpegged" flags. But most changes DO matter. - Note that changes like (nomonsters) vs. (monsters), (respawn) vs. -(regular), (altdeath) vs. (regular deathmatch) will very quickly lead -to unsynchronized goofball players. - - - ---------------------------- -CHAPTER [9]: Savegame Files ---------------------------- - - -------------------------------- -CHAPTER [10]: The DOOM.EXE File -------------------------------- - - Via pwads, a great many characteristics of the DOOM environment can -be changed: maps, pictures, sounds, etc. But there are also a lot of -neat things that can be done by patching the DOOM.EXE file itself. -There is a large collection of data at the end of the EXE file, and by -patching some bytes, we can turn literal values into variables. For -example, the player has a 16-unit "radius" which prevents him from -entering very small passageways. The player's radius can be made 1 and -his "height" 1, so he can enter mouse-sized crawlspaces. There are a -lot more exciting examples, such as invisible monsters, cyber-demons -that look like players, super-fast shotguns, and a hundred others, but -I won't describe all of that here. See appendix [A-4] for some EXE -utilities and documents. Here I will simply give the data that has -been figured out to date. - I freely mix hex and decimal numbers below. Hopefully you can tell from -the context. All of the stuff below applies to registered version 1.2, -and some of it applies to version 1.666 also. This chapter has not yet -been completely updated for 1.666, but it soon will be. - -[10-1]: Version 1.2 DOOM.EXE Data Segment Overview -================================================== - - The data begins at 0x6f414 (455700) and continues to the end of the -file, 0x8db27 (580391). Here's an overview of the sections: - -start length what - -6f414 3d30 TEXT STRINGS -73412 1a34 various unknowns, probably to do with I/O, sound, mouse, etc. -74bf8 10000 looks like hard-coded math tables, for speed? -84bf8 148 misc. -84d40 82 gamma correction messages -84dc2 280 "are you sure you want to quit" messages -85042 3a2 MENUS (new game, load game, etc.) -853e4 140 ? -85524 36c configuration options and defaults, like in DEFAULT.CFG -85890 174 ? -85a04 60 ? -85a64 54 ? -85ab8 c4 ? -85b7c 20 max ammo at start, and ammo per thing -85b9c c0 ammo type and frame #s for the weapons -85c5c 188 ANIMATED WALLS and FLOORS -85de4 258 SWITCH-WALLS -8603c c0 ? -860fc d4 ? -861d0 500 5 colormaps for use with the gamma correction setting 0-4 -866e4 fc ? -867e0 40 pointers to chatmacros, "Green:", etc. -86820 88 pointers to level names, used on Automap -868a8 d8 splat mark coordinates for end-level screen -86980 5a8 wimap patch animations for end-level screen -86f28 224 SONG NAMES list of pointers -8714c 8b8 SOUND TABLE -87a04 1a4 SPRITE NAMES list of pointers -87ba8 3800 STATE TABLE -8b3a8 20 ? -8b3c8 2368 THING TABLE -8d730 3fd ? - -[10-2]: Version 1.666 DOOM.EXE Data Segment Overview -==================================================== - - -[10-3]: Detail on some EXE Data Structures -========================================== - - More detail on some of the data follows. The "names" of each section -are the hexadecimal offsets to the start of that data, in the registered -versions 1.2 and 1.666 of DOOM.EXE. 1.2 offsets are to the left of the -asterisk, 1.666 to the right. "Integer" means a 4-byte integer -in hi-lo format, unless otherwise noted (e.g. "2-byte short integer"). - -6f414 *** 82a14 - - START OF DATA. Several times I'll refer to "pointers". All of these -pointers are integers. Add the values of these pointers to $6f414 or -$82a14 depending on the version, and you'll get the location of what's -being pointed to. - Note: there's also at least one other kind of pointer in here, with -larger values, that point to a location in the code, NOT the data. I call -these "code-pointers" for now. I know it's a lame term. - -6f414 *** a2228 - - TEXT STRINGS. They all start on 4-byte boundaries, i.e. at xxxx0/4/8/c. -$00 ends the string. Then the next one starts at the next boundary, so a 4 -byte string is followed by $00, then 3 bytes of random junk, then the next -string. - -73140 - - I think this is the last string, "TZ" - -73144 - - Misc. stuff I haven't investigated. Some of it has to do with sound card -stuff and mice and joysticks, because at 7384c is "DMXGUS.INI" and at 74ba8 -are pointers which point to the strings "None", "PC_Speaker", "Adlib", etc. - -74bf8 - - 64k of precisely ordered numbers, which leads me to believe they are -pre-calculated math tables, to speed up some floating point operations -used in the screen draw routine. Any other guesses? - -84bfc - - 3 pointers to the episode 1/2/3 end texts, "Once you beat...", "You've -done it...", and "The loathsome Spiderdemon is dead..." - -84c24 - - pointer to the string "doom.wad" - -84c74 - - pointer to the string "default.cfg" - -84c78 - - 8 integers: 1, 25, 50, 24, 40, 640, 1280, 320 - -84c98 - - 2 code-pointers - -84ccc - - 29 integers, with values like 90 and 135 and 180. Angles? - -84d40 - - "Gamma correction OFF", 00s, "Gamma correction level 1", ... 4. Each -occupies $1a bytes. - -84dc2 - - 8 text messages used to confirm quitting, each uses $50 bytes - -85042 - - MENUS. I know this controls to some extent which menu pictures are used -for which menu, but I haven't figured it all out yet. - -853e4 - - 14 ints: 42, 22, 23, 24, 28, 29, 31, 40, zeros - -8541c - - 256 bytes, values from 00-ff, no two the same, "random" order. - -85524 - - The configuration options. Each is 5 integers: a pointer to a string, -like "mouse_sensitivity", a code-pointer, the default value for that -option, a 0 or 1 (1 for all the "key_" options), and a 0. It would be -pretty dense to do anything with this, I think. - -85890 - - About 117 integers, with a definite structure, but I can't figure it -out, and changing/experimenting seems to do nothing. - -85a64 - - 21 sets of 4 bytes: 0, 0, 1, 0, 320, 168, "33", 0, 1, $(b2 26 26 2e), -$(ff 63 fd ff), a pointer that points to the $(b2...), 0, 1, "ema", 0, 0, -1, 0, 1, "xma". All these are unchanged from version 0.99 through 1.2, -except the pointer obviously. - -85ab8 - - Ints: 0, -1, -1, 0, 0, 0, 0, 4, 7, 10, 12, 14, 15, 15, 0, 0, 112, 96, 64, -176, then 16 that are members of this set {-65536, -47000, 0, 47000, 65536}, -then 4, 5, 6, 7, 0, 1, 2, 3, 8, 3, 1, 5, 7 - -85b7c *** 95714 - - AMMO AMOUNTS. 8 integers: 200, 50, 300, 50, 10, 4, 20, 1. The first four -are the maximum initial capacity for ammo, shells, cells, and rockets. The -backpack doubles these amounts. The second four are how many ammo in a -clip, shells, rockets/rocket, and cells/cell item. Boxes have 5x as much. - -859bc *** 95734 - - AMMO TABLE. 8 sets of 6 integers (9 sets in 1.666): - - version 1.2 version 1.666 - -Punch 5 4 3 2 5 0 Punch 5 4 3 2 5 0 -Pistol 0 12 11 10 13 17 Pistol 0 12 11 10 13 17 -Shotgun 1 20 19 18 21 30 Shotgun 1 20 19 18 21 30 -Chaingun 0 34 33 32 35 38 Chaingun 0 51 50 49 52 55 -Laucher 3 42 41 40 43 46 Laucher 3 59 58 57 60 63 -Plasma 2 59 58 57 60 62 Plasma 2 76 75 74 77 79 -BFG 2 66 65 64 67 71 BFG 2 83 82 81 84 88 -Chainsaw 5 53 52 50 54 0 Chainsaw 5 70 69 67 71 0 - Super-Shotgun 1 34 33 32 35 47 - - The first number of each set is the ammo type. Type 5 never runs out. -The next three numbers are 3 state #s (see the STATE TABLE below) for the -pictures displayed when moving while holding that weapon. You know, the -"bobbing weapon" effect? Fifth is the first state of the "shoot" sequence -for that weapon, and last is the first state of the "firing" sequence. The -"firing" pictures are the ones that are lit up, fire coming out, etc. - -85c5c *** 9580c - - ANIMATED WALLS and FLOORS. Each is 26 bytes: an integer, a 8-byte string, -$00, a 8-byte string, $00, and a final integer. - -0 NUKAGE3 NUKAGE1 8 -0 FWATER4 FWATER1 8 -0 SWATER4 SWATER1 8 -0 LAVA4 LAVA1 8 -0 BLOOD4 BLOOD1 8 - <---- v1.666 has four more: 0 RROCK08 RROCK05 8 -1 BLODGR4 BLODGR1 8 0 SLIME04 SLIME01 8 -1 SLADRIP4 SLADRIP1 8 0 SLIME08 SLIME05 8 -1 BLODRIP4 BLODRIP1 8 0 SLIME12 SLIME09 8 -1 FIREWALL FIREWALA 8 -1 GSTFONT3 GSTFONT1 8 -1 FIRELAVA FIRELAV3 8 -1 FIREBLU2 FIREBLU1 8 -1 ROCKRED3 ROCKRED1 8 - <---- V1.666 has four more: 1 BFALL4 BFALL1 8 - 1 SFALL4 SFALL1 8 - 1 WFALL4 WFALL1 8 - 1 DBRAIN4 DBRAIN1 8 - - Obviously the 0/1 means floor or wall. The first string is the name of -the animation cycle's LAST listed texture, the second string is the FIRST -listed texture. The cycle includes them and all entries between them in -whichever wad file is in effect (It doesn't have to be DOOM.WAD, a pwad -with new TEXTURE1 and 2 resources works quite nicely). The final 8 -doesn't seem to mean much. - -85dc8 - - A -1 then a bunch of zeros, maybe space for another animation cycle? - -85de4 *** 95a64 - - SWITCH WALL NAMES. Each is 20 bytes: an 8-byte string, 00, another -string, 00, and a 2-byte short integer. There are 28 switch names here -in v1.2 and 39 switch names in v1.666. When a switch is pulled, the game -checks to see if the wall texture is on this list. If it is, it changes -the wall texture to the corresponding alternate texture. The -is 1, 2, or 3. 1 means it's in all versions, 2 means only registered -DOOM 1 and DOOM 2, 3 means DOOM 2 only. - -86028 - - 20 zeros, again, room for one more? - -8603c *** - - 48 integers: 3 0 2 1 3 0 2 0 3 1 2 0 0 0 0 0 - 2 0 2 1 0 0 0 0 3 1 3 0 0 0 0 0 - 2 0 3 1 2 1 3 1 2 1 3 0 0 0 0 0 - -860fc *** - - 50 integers, all are either 50 or -50. - -861d0 *** - - 5 sets of 256 bytes, each is a COLORMAP, for the gamma correction -settings OFF, 1, 2, 3, 4. - -866d0 *** - - 5 integers: 1, 0, -1, 0, 0 - -866e4 *** - - 13 sets of 5 - 10 bytes, each set terminated by a $FF - -8675e *** - - $74 $20 - -86760 *** - - 13 pointers to the stuff at 866e4. An integer '0' between each pointer. - -867c8 *** - - 6 integers: -1, -1, 0, -1, 0, 1 - -867e0 *** - - 10 pointers to the 10 default chatmacros, then 4 pointers, to "Green:", -"Indigo:", "Brown:", "Red:" - -86820 *** - - AUTOMAP LEVEL NAMES. 27 pointers to the level names used on the automap. - -8689c *** - - The ascii letters "gibr" - the keys for sending messages in multiplayer. - -868a8 *** - - SPLAT MARK COORDINATES. At what screen coordinates to place the WISPLAT -picture on the end-level screen, for th 27 levels. 54 integers, 27 pairs. -e1m1 x, e1m1 y, ..., e3m9 y. - -86980, 86bb0, 86da8 *** - - END-LEVEL MAP ANIMATIONS. Each is 14 integers. The first one is (0, 11, -3, 224, 104, 0, 0, 0, 0, 0, 0, 0, 0, 0). The first number is 0 for all the -ones on maps 0 and 2 (episodes 1 and 3), and it's 2 for map 1. The 11 is -always 11 except the last one of map 2 is 8. The 3 means 3 pictures are -involved in the animation, e.g WIA00100, WIA00101, and WIA00102. 224 and 104 -are the x and y coordinates. The sixth number is not 0 for map 1 - it's -from 1 to 8. This controls the way the Tower of Mystery "appears". All the -other numbers are always 0. - -86ef8 *** - - Three integers, how many animations for WIMAP0, 1, 2 respectively. - -86f04 *** - - Three pointers, to the starts of the animations for WIMAP0, 1, 2 -respectively. - -8714c *** - - SOUND TABLE. 61 and 1/2 sounds are listed here. Each is 9 integers: a -pointer to the string which is the sound's "name", then a 0 or 1, then -a value ranging from 32 to 128, then 0, -1, -1, 0, 0, 0. The names are -"pistol", "shotgn", ... "hoof", "metal", "chgun". Prefix DS or DP and you -get the entries in DOOM.WAD for the sound data. The "chgun" is the 1/2 - -there's no "DSCHGUN" in doom.wad, and the entry in this table is incomplete -anyway, lacking the all-important 0, -1, -1, 0, 0, 0 ending :-). There seem -to be a few glitches in the way the sounds were fit into the whole scheme, -this is just one of them. - -879ec *** - - pointer to start of SOUND TABLE. - -879f0 *** - - Integer = 150. 150 whats? - -87a04 *** - - SPRITE NAME POINTERS. 105 pointers to the strings "TROO", "SHTG", ..., -"SMRT". - -87ba8 *** 9834c - - STATE TABLE. 512 entries in v1.2, 967 entries in v1.666. Each entry -is 28 bytes in 7 integers: - -(1) sprite number 0-..., lookup in sprite name pointers list. -(2) sprite frame, 0="A" in a sprite lump, 1="B", etc. -(3) duration, how many gametics this state is displayed until - it looks for the next. -1 (0xffffffff) is forever. -(4) a "code pointer" which indicates what action(s) accompany - the displaying of this state. -(5) next state in sequence. 0 means no next state, sequence is done. -(6) always 0, has no effect. -(7) always 0, has no effect. - - -8b3a8 *** - - Two integers: 1, 0, then 6 code-pointers. - -8b3c8 *** 9ed10 - - THING TABLE. 103 entries in v1.2 which are each 88 bytes = 22 integers. -136 entries in v1.666, which are each 92 bytes = 23 integers. - -(1) Thing number, as used in maps. See [4-2-1]. Some of them are - equal to -1, e.g. the players' entry, and all projectiles. -(2) "Spawn" state. State number (from STATE TABLE) for when this - thing first appears. -(3) Health. Inanimates can't be killed, so it doesn't apply to them. -(4) "Moving" state. First state # of monsters pursuing, etc. -(5) "See player" sound. For monsters who become activated. Also for - projectiles' first sound. Note that sounds are 1-..., not 0-... - 0 indicates no sound. -(6) Reaction Time. Lower is faster. -(7) "Attack" sound. -(8) "Pain" state. -(9) Painchance. The chance out of 256 that a monster will be disrupted - when it gets hurt. Otherwise, they keep attacking. -(10) "Pain" sound. -(11) "Close attack" state. -(12) "Distance attack" state. -(13) "Death" state, or "explode" for projectiles. -(14) "Explosive death" state, only some monsters can be "mushed". -(15) "Death" sound, or "explode" for projectiles. -(16) Speed of movement. Projectiles' speed are * 65536. -(17) Horizontal size (radius) * 65536 -(18) Height * 65536 -(19) Mass -(20) Missile damage. Also, the Lost Soul has a 3 here, for it's attack. -(21) "Act" sound, for wandering monsters. -(22) Flags, see below -(23) "Respawn" state, for monsters being ressurected. VERSION 1.666 ONLY - - Flags. 0 = condition is false. 1 = condition is true. - - bit flagname effect on thing - - 0 Special it is a gettable thing (ammo, health, etc.) - 1 Solid creatures can't pass through (but projectiles can) - 2 Shootable can be hurt (note barrels have this set) - 3 NoSector totally invisible - 4 NoBlockmap - 5 - 6 (InPain) ? - 7 - 8 SpawnCeiling hung from ceiling - 9 NoGravity floating monsters and not-on-ground things - 10 Dropoff doesn't automatically hug floor if "jump" off ledge - 11 Pickup can pick up gettable items - 12 (NoClip) walks through walls - 13 - 14 Float floating monsters - 15 (Semi-NoClip) climb tall steps - 16 Missile projectiles - 17 (Disappearing ? - Weapon) - 18 Shadow semi-invisible like Spectres - 19 NoBlood uses PUFF instead of BLUD when hurt (e.g. barrels) - 20 (SlideHelpless) ? - 21 - 22 CountKill Monster: counts toward KILLS ratio on inter-level - 23 CountItem Artifact: counts toward ITEMS on inter-level screen - 24 (Running) ? - 25 NotDMatch this thing doesn't get spawned in deathmatch modes - 26 Color0 \ 00 = green stays green 01 = change to dark greys - 27 Color1 / 10 = change to browns 11 = change to dark reds - 28- unused - -8d730 *** n/a - - Misc junk I can't figure out. - -8db27 *** a7b99 - - End of DOOM.EXE - - ------------------------------------------------------------- -APPENDIX [A-1]: Backus-Naur Form definitions of WAD elements ------------------------------------------------------------- - - The descriptions below use a modified Backus-Naur Form (BNF) notation. -Each entry looks like - - := description ;type or comment (optional) - description cont'd. ;type or comment (optional) - - Descriptions composed of more than one sequential keyword or element -are usually listed with one element per line. This is for clarity and also -allows each succesive element to be assigned different types without extra -lines. - - := ; - - is a shorthand for - - := - := - - The description is one or more of the following predefined types, -and/or previously or subsequently defined keywords. - - is an unsigned 8-bit integer (0 to 255). - is a signed 8-bit integer (-128 to 127). - is an unsigned 16-bit integer in lo-hi format (0 to 65535) - is a signed 16-bit integer (-32768 to 32767). - is a signed 32-bit integer (-2147483648 to 2147483647). - is an ASCII string of from 1 to 8 bytes. If its length is - less than 8 bytes, the remainder are zeros (hex 00). - - Any of these may be followed by a range: means a byte -restricted to the range 1 to 99 inclusive. A single number means that -value is literally included: inserts that 8-bit value. - - { } are used to enclose a group of elements. - - | is used to separate choices - exactly one of the choices applies. - - [ ] are used following an element or group of elements to indicate -an array. Usually a literal value or a keyword will be used to denote -how many members the array has. [666] means that the element - is repeated 666 times in sequence. { } [zeus] -means that whatever the value of is, there are that many pairs -of and . [1..16] indicates the value may be from -1 to 16 inclusive, and [...] indicates an indefinite number. - - A literal string "ABCD" may appear, in which case those ASCII characters -are directly inserted. - ------- - - := "PWAD"|"IWAD" - - - - - - := ;number of lumps in WAD file - := ;file offset to directory start - - := [numlumps] - := ;see different kinds below - - := { | } [numlumps] - := ; - ; - ; - - := |